Compare commits
6 Commits
main
...
frontend-i
| Author | SHA1 | Date | |
|---|---|---|---|
| 431f2bf82f | |||
| 69542f08cd | |||
| e79f28f52b | |||
| b3f607b0fc | |||
| a137946a92 | |||
| 462dccffba |
245
.github/workflows/deploy.yml
vendored
245
.github/workflows/deploy.yml
vendored
@ -1,22 +1,12 @@
|
||||
name: CI/CD Pipeline - Apartment Dashboard
|
||||
name: Deploy Apartment Dashboard
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
NODE_VERSION: '20'
|
||||
IMAGE_NAME: apartment-dashboard
|
||||
|
||||
jobs:
|
||||
# ============================================================
|
||||
# Lint Job - Runs first, blocks everything if linting fails
|
||||
# ============================================================
|
||||
lint:
|
||||
name: Run Linter
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
@ -26,227 +16,46 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
node-version: '18'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run linter
|
||||
run: npm run lint
|
||||
- name: Build application
|
||||
run: npm run build
|
||||
|
||||
# ============================================================
|
||||
# Dependency Scan Job - Runs in parallel with lint
|
||||
# ============================================================
|
||||
scan-deps:
|
||||
name: Scan Dependencies
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Trivy
|
||||
- name: Build Docker image
|
||||
run: |
|
||||
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin v0.58.0
|
||||
docker build -t apartment-dashboard:${{ github.sha }} .
|
||||
docker tag apartment-dashboard:${{ github.sha }} apartment-dashboard:latest
|
||||
|
||||
- name: Scan dependencies for vulnerabilities
|
||||
- name: Deploy to server
|
||||
run: |
|
||||
trivy fs \
|
||||
--exit-code 1 \
|
||||
--ignore-unfixed \
|
||||
--severity CRITICAL,HIGH \
|
||||
--scanners vuln \
|
||||
.
|
||||
|
||||
# ============================================================
|
||||
# Build & Push Job - Build image and push to Harbor
|
||||
# ============================================================
|
||||
build:
|
||||
name: Build & Push Image
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint, scan-deps]
|
||||
if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
|
||||
|
||||
outputs:
|
||||
image_tag: ${{ steps.set-tag.outputs.tag }}
|
||||
full_image: ${{ steps.set-tag.outputs.full_image }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set image tag
|
||||
id: set-tag
|
||||
run: |
|
||||
SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||
echo "tag=${SHORT_SHA}" >> $GITHUB_OUTPUT
|
||||
echo "full_image=${{ secrets.HARBOR_REGISTRY }}/${{ secrets.HARBOR_PROJECT }}/${{ env.IMAGE_NAME }}:${SHORT_SHA}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Harbor
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ secrets.HARBOR_REGISTRY }}
|
||||
username: ${{ secrets.HARBOR_USERNAME }}
|
||||
password: ${{ secrets.HARBOR_PASSWORD }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: build-push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
${{ secrets.HARBOR_REGISTRY }}/${{ secrets.HARBOR_PROJECT }}/${{ env.IMAGE_NAME }}:${{ steps.set-tag.outputs.tag }}
|
||||
${{ secrets.HARBOR_REGISTRY }}/${{ secrets.HARBOR_PROJECT }}/${{ env.IMAGE_NAME }}:latest
|
||||
|
||||
# ============================================================
|
||||
# Vulnerability Scanning with Trivy
|
||||
# ============================================================
|
||||
- name: Install Trivy
|
||||
run: |
|
||||
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin v0.58.0
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
run: |
|
||||
trivy image \
|
||||
--exit-code 1 \
|
||||
--ignore-unfixed \
|
||||
--vuln-type os,library \
|
||||
--severity CRITICAL,HIGH \
|
||||
--format table \
|
||||
${{ steps.set-tag.outputs.full_image }}
|
||||
|
||||
- name: Run Trivy and output SARIF
|
||||
if: always()
|
||||
run: |
|
||||
trivy image \
|
||||
--format sarif \
|
||||
--output trivy-results.sarif \
|
||||
${{ steps.set-tag.outputs.full_image }} || true
|
||||
|
||||
# ============================================================
|
||||
# SBOM Generation with Syft
|
||||
# ============================================================
|
||||
- name: Install Syft
|
||||
run: |
|
||||
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin
|
||||
|
||||
- name: Generate SBOM with Syft
|
||||
run: |
|
||||
syft ${{ steps.set-tag.outputs.full_image }} -o spdx-json=sbom.spdx.json
|
||||
|
||||
# ============================================================
|
||||
# Image Signing with Cosign
|
||||
# ============================================================
|
||||
- name: Install Cosign
|
||||
uses: sigstore/cosign-installer@v3
|
||||
|
||||
- name: Sign image with Cosign
|
||||
env:
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
run: |
|
||||
cosign sign --key env://COSIGN_PRIVATE_KEY \
|
||||
--yes \
|
||||
${{ secrets.HARBOR_REGISTRY }}/${{ secrets.HARBOR_PROJECT }}/${{ env.IMAGE_NAME }}@${{ steps.build-push.outputs.digest }}
|
||||
|
||||
# ============================================================
|
||||
# Attach SBOM to image in Harbor
|
||||
# ============================================================
|
||||
- name: Attach SBOM to image
|
||||
env:
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
run: |
|
||||
cosign attest --key env://COSIGN_PRIVATE_KEY \
|
||||
--type spdxjson \
|
||||
--predicate sbom.spdx.json \
|
||||
--yes \
|
||||
${{ secrets.HARBOR_REGISTRY }}/${{ secrets.HARBOR_PROJECT }}/${{ env.IMAGE_NAME }}@${{ steps.build-push.outputs.digest }}
|
||||
|
||||
# ============================================================
|
||||
# Deploy Job - Pull image and restart on production server
|
||||
# ============================================================
|
||||
deploy:
|
||||
name: Deploy to Production
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Sync docker-compose.yml to server
|
||||
uses: appleboy/scp-action@v0.1.7
|
||||
with:
|
||||
host: ${{ secrets.SSH_HOST }}
|
||||
username: ${{ secrets.SSH_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
port: ${{ secrets.SSH_PORT || 22 }}
|
||||
source: "docker-compose.yml"
|
||||
target: ${{ secrets.DEPLOY_PATH }}
|
||||
|
||||
- name: Deploy via SSH
|
||||
uses: appleboy/ssh-action@v1.2.4
|
||||
with:
|
||||
host: ${{ secrets.SSH_HOST }}
|
||||
username: ${{ secrets.SSH_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
port: ${{ secrets.SSH_PORT || 22 }}
|
||||
script_stop: true
|
||||
script: |
|
||||
set -e
|
||||
|
||||
# Image to deploy (using specific SHA tag, not latest)
|
||||
IMAGE="${{ needs.build.outputs.full_image }}"
|
||||
echo "Deploying image: $IMAGE"
|
||||
# Copy files to deployment directory
|
||||
sudo mkdir -p /media/stephen/Storage_Linux/infrastructure/services/apartments
|
||||
sudo cp -r . /media/stephen/Storage_Linux/infrastructure/services/apartments/
|
||||
|
||||
# Navigate to deployment directory
|
||||
cd ${{ secrets.DEPLOY_PATH }}
|
||||
cd /media/stephen/Storage_Linux/infrastructure/services/apartments
|
||||
|
||||
# Pull the specific image (using pre-configured Docker credentials)
|
||||
docker pull "$IMAGE"
|
||||
# Stop existing container if running
|
||||
sudo docker compose down || true
|
||||
|
||||
# Update and restart with new image
|
||||
export IMAGE
|
||||
docker compose up -d
|
||||
# Start new container
|
||||
sudo docker compose up -d
|
||||
|
||||
# Clean up old images
|
||||
docker image prune -f
|
||||
|
||||
# Wait for container to start
|
||||
echo "Waiting for container to start..."
|
||||
sleep 10
|
||||
|
||||
# Verify container is running
|
||||
if docker compose ps | grep -q "Up"; then
|
||||
echo "Container is running successfully"
|
||||
else
|
||||
echo "ERROR: Container failed to start"
|
||||
docker compose logs --tail=50
|
||||
exit 1
|
||||
fi
|
||||
sudo docker image prune -f
|
||||
|
||||
- name: Verify deployment
|
||||
uses: appleboy/ssh-action@v1.2.4
|
||||
with:
|
||||
host: ${{ secrets.SSH_HOST }}
|
||||
username: ${{ secrets.SSH_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
port: ${{ secrets.SSH_PORT || 22 }}
|
||||
script: |
|
||||
# Test health endpoint (frontend serves index.html)
|
||||
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://apartments.maverickapplications.com/ || echo "000")
|
||||
run: |
|
||||
# Wait a moment for container to start
|
||||
sleep 10
|
||||
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
echo "Health check passed (HTTP $HTTP_CODE)"
|
||||
else
|
||||
echo "WARNING: Health check returned HTTP $HTTP_CODE"
|
||||
echo "Container may still be initializing..."
|
||||
exit 1
|
||||
fi
|
||||
# Check if container is running
|
||||
cd /media/stephen/Storage_Linux/infrastructure/services/apartments
|
||||
sudo docker compose ps
|
||||
|
||||
# Test endpoint (optional)
|
||||
curl -f http://localhost:80 || echo "Container may still be starting..."
|
||||
@ -1,13 +1,13 @@
|
||||
# Build stage
|
||||
FROM node:20-alpine as build
|
||||
FROM node:18-alpine as build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
|
||||
# Install dependencies (including devDependencies needed for build)
|
||||
RUN npm ci
|
||||
# Install dependencies
|
||||
RUN npm ci --only=production
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
@ -18,9 +18,6 @@ RUN npm run build
|
||||
# Production stage
|
||||
FROM nginx:alpine
|
||||
|
||||
# Update Alpine packages to fix security vulnerabilities
|
||||
RUN apk upgrade --no-cache
|
||||
|
||||
# Copy built app to nginx
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
|
||||
|
||||
@ -1,4 +0,0 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEBOFl4SHzoZVM59+668t2tecTyKM+
|
||||
cE4zaOkbFO30u7d2+bjpwPnbYrTutKmAeehYzCAVW/OYea7ML0cW2YCSCQ==
|
||||
-----END PUBLIC KEY-----
|
||||
@ -1,16 +1,15 @@
|
||||
name: apartment-dashboard
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
apartment-dashboard:
|
||||
image: ${IMAGE:-apartment-dashboard:latest}
|
||||
build: .
|
||||
container_name: apartment-dashboard
|
||||
restart: unless-stopped
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.docker.network=traefik"
|
||||
- "traefik.http.routers.apartments.rule=Host(`apartments.maverickapplications.com`)"
|
||||
- "traefik.http.routers.apartments.entrypoints=web"
|
||||
- "traefik.http.routers.apartments.entrypoints=websecure"
|
||||
- "traefik.http.routers.apartments.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.apartments.loadbalancer.server.port=80"
|
||||
networks:
|
||||
- traefik
|
||||
|
||||
@ -15,7 +15,7 @@ export default defineConfig([
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: { ...globals.browser, __APP_VERSION__: 'readonly' },
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
ecmaFeatures: { jsx: true },
|
||||
|
||||
275
package-lock.json
generated
275
package-lock.json
generated
@ -339,9 +339,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
|
||||
"integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.6.tgz",
|
||||
"integrity": "sha512-ShbM/3XxwuxjFiuVBHA+d3j5dyac0aEVVq1oluIDf71hUw0aRF59dV/efUsIwFnR6m8JNM2FjZOzmaZ8yG61kw==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@ -356,9 +356,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",
|
||||
"integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.6.tgz",
|
||||
"integrity": "sha512-S8ToEOVfg++AU/bHwdksHNnyLyVM+eMVAOf6yRKFitnwnbwwPNqKr3srzFRe7nzV69RQKb5DgchIX5pt3L53xg==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@ -373,9 +373,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-hd5zdUarsK6strW+3Wxi5qWws+rJhCCbMiC9QZyzoxfk5uHRIE8T287giQxzVpEvCwuJ9Qjg6bEjcRJcgfLqoA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -390,9 +390,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-0Z7KpHSr3VBIO9A/1wcT3NTy7EB4oNC4upJ5ye3R7taCc2GUdeynSLArnon5G8scPwaU866d3H4BCrE5xLW25A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -407,9 +407,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-FFCssz3XBavjxcFxKsGy2DYK5VSvJqa6y5HXljKzhRZ87LvEi13brPrf/wdyl/BbpbMKJNOr1Sd0jtW4Ge1pAA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -424,9 +424,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-GfXs5kry/TkGM2vKqK2oyiLFygJRqKVhawu3+DOCk7OxLy/6jYkWXhlHwOoTb0WqGnWGAS7sooxbZowy+pK9Yg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -441,9 +441,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-aoLF2c3OvDn2XDTRvn8hN6DRzVVpDlj2B/F66clWd/FHLiHaG3aVZjxQX2DYphA5y/evbdGvC6Us13tvyt4pWg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -458,9 +458,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-2SkqTjTSo2dYi/jzFbU9Plt1vk0+nNg8YC8rOXXea+iA3hfNJWebKYPs3xnOUf9+ZWhKAaxnQNUf2X9LOpeiMQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -475,9 +475,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",
|
||||
"integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.6.tgz",
|
||||
"integrity": "sha512-SZHQlzvqv4Du5PrKE2faN0qlbsaW/3QQfUUc6yO2EjFcA83xnwm91UbEEVx4ApZ9Z5oG8Bxz4qPE+HFwtVcfyw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@ -492,9 +492,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-b967hU0gqKd9Drsh/UuAm21Khpoh6mPBSgz8mKRq4P5mVK8bpA+hQzmm/ZwGVULSNBzKdZPQBRT3+WuVavcWsQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -509,9 +509,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",
|
||||
"integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.6.tgz",
|
||||
"integrity": "sha512-aHWdQ2AAltRkLPOsKdi3xv0mZ8fUGPdlKEjIEhxCPm5yKEThcUjHpWB1idN74lfXGnZ5SULQSgtr5Qos5B0bPw==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@ -526,9 +526,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",
|
||||
"integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.6.tgz",
|
||||
"integrity": "sha512-VgKCsHdXRSQ7E1+QXGdRPlQ/e08bN6WMQb27/TMfV+vPjjTImuT9PmLXupRlC90S1JeNNW5lzkAEO/McKeJ2yg==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
@ -543,9 +543,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",
|
||||
"integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.6.tgz",
|
||||
"integrity": "sha512-WViNlpivRKT9/py3kCmkHnn44GkGXVdXfdc4drNmRl15zVQ2+D2uFwdlGh6IuK5AAnGTo2qPB1Djppj+t78rzw==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
@ -560,9 +560,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",
|
||||
"integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.6.tgz",
|
||||
"integrity": "sha512-wyYKZ9NTdmAMb5730I38lBqVu6cKl4ZfYXIs31Baf8aoOtB4xSGi3THmDYt4BTFHk7/EcVixkOV2uZfwU3Q2Jw==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@ -577,9 +577,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",
|
||||
"integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.6.tgz",
|
||||
"integrity": "sha512-KZh7bAGGcrinEj4qzilJ4hqTY3Dg2U82c8bv+e1xqNqZCrCyc+TL9AUEn5WGKDzm3CfC5RODE/qc96OcbIe33w==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
@ -594,9 +594,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",
|
||||
"integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.6.tgz",
|
||||
"integrity": "sha512-9N1LsTwAuE9oj6lHMyyAM+ucxGiVnEqUdp4v7IaMmrwb06ZTEVCIs3oPPplVsnjPfyjmxwHxHMF8b6vzUVAUGw==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
@ -611,9 +611,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-A6bJB41b4lKFWRKNrWoP2LHsjVzNiaurf7wyj/XtFNTsnPuxwEBWHLty+ZE0dWBKuSK1fvKgrKaNjBS7qbFKig==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -628,9 +628,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-IjA+DcwoVpjEvyxZddDqBY+uJ2Snc6duLpjmkXm/v4xuS3H+3FkLZlDm9ZsAbF9rsfP3zeA0/ArNDORZgrxR/Q==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -645,9 +645,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-dUXuZr5WenIDlMHdMkvDc1FAu4xdWixTCRgP7RQLBOkkGgwuuzaGSYcOpW4jFxzpzL1ejb8yF620UxAqnBrR9g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -662,9 +662,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-l8ZCvXP0tbTJ3iaqdNf3pjaOSd5ex/e6/omLIQCVBLmHTlfXW3zAxQ4fnDmPLOB1x9xrcSi/xtCWFwCZRIaEwg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -679,9 +679,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-hKrmDa0aOFOr71KQ/19JC7az1P0GWtCN1t2ahYAf4O007DHZt/dW8ym5+CUdJhQ/qkZmI1HAF8KkJbEFtCL7gw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -696,9 +696,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-+SqBcAWoB1fYKmpWoQP4pGtx+pUUC//RNYhFdbcSA16617cchuryuhOCRpPsjCblKukAckWsV+aQ3UKT/RMPcA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -713,9 +713,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-dyCGxv1/Br7MiSC42qinGL8KkG4kX0pEsdb0+TKhmJZgCUDBGmyo1/ArCjNGiOLiIAgdbWgmWgib4HoCi5t7kA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -730,9 +730,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.6.tgz",
|
||||
"integrity": "sha512-42QOgcZeZOvXfsCBJF5Afw73t4veOId//XD3i+/9gSkhSV6Gk3VPlWncctI+JcOyERv85FUo7RxuxGy+z8A43Q==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@ -747,9 +747,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",
|
||||
"integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.6.tgz",
|
||||
"integrity": "sha512-4AWhgXmDuYN7rJI6ORB+uU9DHLq/erBbuMoAuB4VWJTu5KtCgcKYPynF0YI1VkBNuEfjNlLrFr9KZPJzrtLkrQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@ -764,9 +764,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.6.tgz",
|
||||
"integrity": "sha512-NgJPHHbEpLQgDH2MjQu90pzW/5vvXIZ7KOnPyNBm92A6WgZ/7b6fJyUBjoumLqeOQQGqY2QjQxRo97ah4Sj0cA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@ -848,9 +848,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/core": {
|
||||
"version": "0.15.2",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.2.tgz",
|
||||
"integrity": "sha512-78Md3/Rrxh83gCxoUc0EiciuOHsIITzLy53m3d9UyiW8y9Dj2D29FeETqyKA+BRK76tnTp6RXWb3pCay8Oyomg==",
|
||||
"version": "0.15.1",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.1.tgz",
|
||||
"integrity": "sha512-bkOp+iumZCCbt1K1CmWf0R9pM5yKpDv+ZXtvSyQpudrI9kuFLp+bM2WOPXImuD/ceQuaa8f5pj93Y7zyECIGNA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
@ -921,13 +921,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/plugin-kit": {
|
||||
"version": "0.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.5.tgz",
|
||||
"integrity": "sha512-Z5kJ+wU3oA7MMIqVR9tyZRtjYPr4OC004Q4Rw7pgOKUOKkJfZ3O24nz3WYfGRpMDNmcOi3TwQOmgm7B7Tpii0w==",
|
||||
"version": "0.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.3.tgz",
|
||||
"integrity": "sha512-1+WqvgNMhmlAambTvT3KPtCl/Ibr68VldY2XY40SL1CE0ZXiakFR/cbTspaF5HsnpDMvcYYoJHfl4980NBjGag==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@eslint/core": "^0.15.2",
|
||||
"@eslint/core": "^0.15.1",
|
||||
"levn": "^0.4.1"
|
||||
},
|
||||
"engines": {
|
||||
@ -2227,9 +2227,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",
|
||||
"integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",
|
||||
"version": "0.25.6",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.6.tgz",
|
||||
"integrity": "sha512-GVuzuUwtdsghE3ocJ9Bs8PNoF13HNQ5TXbEi2AhvVb8xU1Iwt9Fos9FEamfoee+u/TOsn7GUWc04lz46n2bbTg==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
@ -2240,32 +2240,32 @@
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.27.2",
|
||||
"@esbuild/android-arm": "0.27.2",
|
||||
"@esbuild/android-arm64": "0.27.2",
|
||||
"@esbuild/android-x64": "0.27.2",
|
||||
"@esbuild/darwin-arm64": "0.27.2",
|
||||
"@esbuild/darwin-x64": "0.27.2",
|
||||
"@esbuild/freebsd-arm64": "0.27.2",
|
||||
"@esbuild/freebsd-x64": "0.27.2",
|
||||
"@esbuild/linux-arm": "0.27.2",
|
||||
"@esbuild/linux-arm64": "0.27.2",
|
||||
"@esbuild/linux-ia32": "0.27.2",
|
||||
"@esbuild/linux-loong64": "0.27.2",
|
||||
"@esbuild/linux-mips64el": "0.27.2",
|
||||
"@esbuild/linux-ppc64": "0.27.2",
|
||||
"@esbuild/linux-riscv64": "0.27.2",
|
||||
"@esbuild/linux-s390x": "0.27.2",
|
||||
"@esbuild/linux-x64": "0.27.2",
|
||||
"@esbuild/netbsd-arm64": "0.27.2",
|
||||
"@esbuild/netbsd-x64": "0.27.2",
|
||||
"@esbuild/openbsd-arm64": "0.27.2",
|
||||
"@esbuild/openbsd-x64": "0.27.2",
|
||||
"@esbuild/openharmony-arm64": "0.27.2",
|
||||
"@esbuild/sunos-x64": "0.27.2",
|
||||
"@esbuild/win32-arm64": "0.27.2",
|
||||
"@esbuild/win32-ia32": "0.27.2",
|
||||
"@esbuild/win32-x64": "0.27.2"
|
||||
"@esbuild/aix-ppc64": "0.25.6",
|
||||
"@esbuild/android-arm": "0.25.6",
|
||||
"@esbuild/android-arm64": "0.25.6",
|
||||
"@esbuild/android-x64": "0.25.6",
|
||||
"@esbuild/darwin-arm64": "0.25.6",
|
||||
"@esbuild/darwin-x64": "0.25.6",
|
||||
"@esbuild/freebsd-arm64": "0.25.6",
|
||||
"@esbuild/freebsd-x64": "0.25.6",
|
||||
"@esbuild/linux-arm": "0.25.6",
|
||||
"@esbuild/linux-arm64": "0.25.6",
|
||||
"@esbuild/linux-ia32": "0.25.6",
|
||||
"@esbuild/linux-loong64": "0.25.6",
|
||||
"@esbuild/linux-mips64el": "0.25.6",
|
||||
"@esbuild/linux-ppc64": "0.25.6",
|
||||
"@esbuild/linux-riscv64": "0.25.6",
|
||||
"@esbuild/linux-s390x": "0.25.6",
|
||||
"@esbuild/linux-x64": "0.25.6",
|
||||
"@esbuild/netbsd-arm64": "0.25.6",
|
||||
"@esbuild/netbsd-x64": "0.25.6",
|
||||
"@esbuild/openbsd-arm64": "0.25.6",
|
||||
"@esbuild/openbsd-x64": "0.25.6",
|
||||
"@esbuild/openharmony-arm64": "0.25.6",
|
||||
"@esbuild/sunos-x64": "0.25.6",
|
||||
"@esbuild/win32-arm64": "0.25.6",
|
||||
"@esbuild/win32-ia32": "0.25.6",
|
||||
"@esbuild/win32-x64": "0.25.6"
|
||||
}
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
@ -2537,14 +2537,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
@ -2685,9 +2682,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
|
||||
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
|
||||
"version": "10.4.5",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
|
||||
"integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
@ -2949,9 +2946,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
|
||||
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@ -4189,14 +4186,14 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
@ -4318,18 +4315,18 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.3.1",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz",
|
||||
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
|
||||
"version": "7.0.4",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.0.4.tgz",
|
||||
"integrity": "sha512-SkaSguuS7nnmV7mfJ8l81JGBFV7Gvzp8IzgE8A8t23+AxuNX61Q5H1Tpz5efduSN7NHC8nQXD3sKQKZAu5mNEA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.27.0",
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3",
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.6",
|
||||
"picomatch": "^4.0.2",
|
||||
"postcss": "^8.5.6",
|
||||
"rollup": "^4.43.0",
|
||||
"tinyglobby": "^0.2.15"
|
||||
"rollup": "^4.40.0",
|
||||
"tinyglobby": "^0.2.14"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "apartment-dashboard",
|
||||
"private": true,
|
||||
"version": "1.1.0",
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
397
src/App.jsx
397
src/App.jsx
@ -1,29 +1,17 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Routes, Route, Link, useLocation, Navigate } from 'react-router-dom';
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Area, AreaChart, ScatterChart, Scatter, ComposedChart, ReferenceLine } from 'recharts';
|
||||
import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List, LogOut, User, ChevronDown, ChevronUp, Settings, Shield } from 'lucide-react';
|
||||
import useAuth from './hooks/useAuth';
|
||||
import ProtectedRoute from './components/ProtectedRoute';
|
||||
import AdminRoute from './components/AdminRoute';
|
||||
import Login from './pages/Login';
|
||||
import UserList from './pages/admin/UserList';
|
||||
import UserDetail from './pages/admin/UserDetail';
|
||||
import ActivityStream from './pages/admin/ActivityStream';
|
||||
import AdminOverview from './pages/admin/AdminOverview';
|
||||
import UsageStats from './pages/admin/UsageStats';
|
||||
import AdminSettings from './pages/admin/AdminSettings';
|
||||
import ScraperManagement from './pages/admin/ScraperManagement';
|
||||
import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List } from 'lucide-react';
|
||||
|
||||
const ApartmentDashboard = () => {
|
||||
// Router
|
||||
const location = useLocation();
|
||||
const { user, loading: authLoading, logout } = useAuth();
|
||||
|
||||
// Basic state
|
||||
const [selectedUnit, setSelectedUnit] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [_lastUpdated, setLastUpdated] = useState(new Date());
|
||||
const [lastUpdated, setLastUpdated] = useState(new Date());
|
||||
const [modalTimeRange, setModalTimeRange] = useState('month');
|
||||
const [unitPriceHistory, setUnitPriceHistory] = useState([]);
|
||||
const [loadingPriceHistory, setLoadingPriceHistory] = useState(false);
|
||||
@ -31,27 +19,10 @@ const ApartmentDashboard = () => {
|
||||
// Filters
|
||||
const [priceFilter, setPriceFilter] = useState({ min: 0, max: 10000 });
|
||||
const [bedroomFilter, setBedroomFilter] = useState('all');
|
||||
const [towerFilter, setTowerFilter] = useState('all');
|
||||
const [facingFilter, setFacingFilter] = useState('all');
|
||||
const [sortBy, setSortBy] = useState('unitCode');
|
||||
const [sortDirection, setSortDirection] = useState('asc');
|
||||
const [watchedUnits, setWatchedUnits] = useState(new Set());
|
||||
const [unitsViewMode, setUnitsViewMode] = useState('list');
|
||||
const [columnSettingsOpen, setColumnSettingsOpen] = useState(false);
|
||||
const [visibleColumns, setVisibleColumns] = useState({
|
||||
unit: true,
|
||||
plan: true,
|
||||
bedBath: true,
|
||||
area: true,
|
||||
price: true,
|
||||
pricePerSqft: true,
|
||||
days: true,
|
||||
high: true,
|
||||
low: true,
|
||||
delta: true,
|
||||
soonest: true,
|
||||
actions: true
|
||||
});
|
||||
|
||||
// API Data state - using your working endpoints
|
||||
const [dailySummary, setDailySummary] = useState(null);
|
||||
@ -61,10 +32,10 @@ const ApartmentDashboard = () => {
|
||||
const [planStats, setPlanStats] = useState([]);
|
||||
|
||||
// Enhanced data state (optional endpoints)
|
||||
const [_bestDeals, setBestDeals] = useState([]);
|
||||
const [bestDeals, setBestDeals] = useState([]);
|
||||
const [priceDrops, setPriceDrops] = useState([]);
|
||||
const [_staleInventory, setStaleInventory] = useState([]);
|
||||
const [_marketInsights, setMarketInsights] = useState(null);
|
||||
const [staleInventory, setStaleInventory] = useState([]);
|
||||
const [marketInsights, setMarketInsights] = useState(null);
|
||||
|
||||
// Analytics data state
|
||||
const [analyticsData, setAnalyticsData] = useState(null);
|
||||
@ -83,11 +54,11 @@ const ApartmentDashboard = () => {
|
||||
|
||||
// Fetch core endpoints that we know work
|
||||
const coreRequests = [
|
||||
fetch(`${API_BASE}/daily-summary`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/price-history`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/available-units`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/recent-activity`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/plan-stats`, { credentials: 'include' })
|
||||
fetch(`${API_BASE}/daily-summary`),
|
||||
fetch(`${API_BASE}/price-history`),
|
||||
fetch(`${API_BASE}/available-units`),
|
||||
fetch(`${API_BASE}/recent-activity`),
|
||||
fetch(`${API_BASE}/plan-stats`)
|
||||
];
|
||||
|
||||
const [
|
||||
@ -125,11 +96,11 @@ const ApartmentDashboard = () => {
|
||||
// Try to fetch enhanced endpoints (won't break if they don't exist)
|
||||
try {
|
||||
const enhancedRequests = [
|
||||
fetch(`${API_BASE}/best-deals?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/price-drops?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/stale-inventory?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/market-insights`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/last-scrape`, { credentials: 'include' })
|
||||
fetch(`${API_BASE}/best-deals?limit=5`),
|
||||
fetch(`${API_BASE}/price-drops?limit=5`),
|
||||
fetch(`${API_BASE}/stale-inventory?limit=5`),
|
||||
fetch(`${API_BASE}/market-insights`),
|
||||
fetch(`${API_BASE}/last-scrape`)
|
||||
];
|
||||
|
||||
const enhancedResponses = await Promise.all(enhancedRequests);
|
||||
@ -167,19 +138,16 @@ const ApartmentDashboard = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// Initial data fetch - only when authenticated
|
||||
// Initial data fetch
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
fetchData();
|
||||
}
|
||||
}, [user]);
|
||||
}, []);
|
||||
|
||||
// Auto-refresh every 5 minutes - only when authenticated
|
||||
// Auto-refresh every 5 minutes
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
const interval = setInterval(fetchData, 5 * 60 * 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [user]);
|
||||
}, []);
|
||||
|
||||
// Helper functions
|
||||
const formatPrice = (price) => `$${(price || 0).toLocaleString()}`;
|
||||
@ -308,7 +276,7 @@ const ApartmentDashboard = () => {
|
||||
return filtered;
|
||||
};
|
||||
|
||||
const _toggleWatchUnit = (unitCode) => {
|
||||
const toggleWatchUnit = (unitCode) => {
|
||||
const newWatched = new Set(watchedUnits);
|
||||
if (newWatched.has(unitCode)) {
|
||||
newWatched.delete(unitCode);
|
||||
@ -322,7 +290,7 @@ const ApartmentDashboard = () => {
|
||||
const fetchUnitPriceHistory = async (unitCode) => {
|
||||
setLoadingPriceHistory(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/unit/${unitCode}/price-history`, { credentials: 'include' });
|
||||
const response = await fetch(`${API_BASE}/unit/${unitCode}/price-history`);
|
||||
if (response.ok) {
|
||||
const history = await response.json();
|
||||
setUnitPriceHistory(history);
|
||||
@ -351,7 +319,7 @@ const ApartmentDashboard = () => {
|
||||
if (analyticsData) return; // Already fetched
|
||||
setLoadingAnalytics(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/analytics`, { credentials: 'include' });
|
||||
const response = await fetch(`${API_BASE}/analytics`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setAnalyticsData(data);
|
||||
@ -370,7 +338,6 @@ const ApartmentDashboard = () => {
|
||||
if (location.pathname === '/analytics' && !analyticsData) {
|
||||
fetchAnalytics();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [location.pathname]);
|
||||
|
||||
// Calculate insights from available data
|
||||
@ -417,22 +384,9 @@ const ApartmentDashboard = () => {
|
||||
|
||||
// Filter function for units
|
||||
const filteredUnits = availableUnits.filter(unit => {
|
||||
const price = unit.currentPrice || 0;
|
||||
const matchesPrice = price >= priceFilter.min && (priceFilter.max === 10000 || price <= priceFilter.max);
|
||||
const matchesPrice = (unit.currentPrice || 0) >= priceFilter.min && (unit.currentPrice || 0) <= priceFilter.max;
|
||||
const matchesBedroom = bedroomFilter === 'all' || (unit.bedCount != null && unit.bedCount.toString() === bedroomFilter);
|
||||
const matchesTower = towerFilter === 'all'
|
||||
|| (towerFilter === 'east' && unit.unitCode?.startsWith('E'))
|
||||
|| (towerFilter === 'west' && unit.unitCode?.startsWith('W'))
|
||||
|| (towerFilter === 'downing' && /^\d/.test(unit.unitCode));
|
||||
const matchesFacing = facingFilter === 'all'
|
||||
|| (() => {
|
||||
if (/^\d/.test(unit.unitCode)) return true;
|
||||
const lastDigit = parseInt(unit.unitCode?.slice(-1));
|
||||
if (facingFilter === 'north') return lastDigit % 2 === 0;
|
||||
if (facingFilter === 'south') return lastDigit % 2 !== 0;
|
||||
return true;
|
||||
})();
|
||||
return matchesPrice && matchesBedroom && matchesTower && matchesFacing;
|
||||
return matchesPrice && matchesBedroom;
|
||||
}).sort((a, b) => {
|
||||
const dir = sortDirection === 'asc' ? 1 : -1;
|
||||
switch (sortBy) {
|
||||
@ -443,16 +397,12 @@ const ApartmentDashboard = () => {
|
||||
case 'price': return dir * ((a.currentPrice || 0) - (b.currentPrice || 0));
|
||||
case 'pricePerSqft': return dir * (((a.currentPrice || 0) / (a.area || 1)) - ((b.currentPrice || 0) / (b.area || 1)));
|
||||
case 'daysAvailable': return dir * ((a.daysAvailable || 0) - (b.daysAvailable || 0));
|
||||
case 'maxPrice': return dir * ((a.maxPrice || 0) - (b.maxPrice || 0));
|
||||
case 'minPrice': return dir * ((a.minPrice || 0) - (b.minPrice || 0));
|
||||
case 'delta': return dir * ((a.priceChangeToday || 0) - (b.priceChangeToday || 0));
|
||||
case 'soonest': return dir * (a.soonest || '').localeCompare(b.soonest || '');
|
||||
default: return 0;
|
||||
}
|
||||
});
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const MetricCard = ({ title, value, subtitle, icon: IconProp, trend, color = "blue", highlight = false }) => (
|
||||
const MetricCard = ({ title, value, subtitle, icon: Icon, trend, color = "blue", highlight = false }) => (
|
||||
<div className={`bg-white rounded-lg shadow-md p-6 border-l-4 ${highlight ? 'ring-2 ring-yellow-400' : ''}`}
|
||||
style={{borderLeftColor: color === 'blue' ? '#3B82F6' : color === 'green' ? '#10B981' : color === 'red' ? '#EF4444' : '#F59E0B'}}>
|
||||
<div className="flex items-center justify-between">
|
||||
@ -468,7 +418,7 @@ const ApartmentDashboard = () => {
|
||||
{Math.abs(trend)}%
|
||||
</span>
|
||||
)}
|
||||
<IconProp className="w-8 h-8 text-gray-400" />
|
||||
<Icon className="w-8 h-8 text-gray-400" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -489,15 +439,6 @@ const ApartmentDashboard = () => {
|
||||
);
|
||||
}
|
||||
|
||||
// Auth loading state
|
||||
if (authLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (error && !dailySummary) {
|
||||
return (
|
||||
@ -533,34 +474,12 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
{priceDrops.length > 0 && (
|
||||
<div className="flex items-center space-x-2 bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-sm">
|
||||
<Bell className="w-4 h-4" />
|
||||
<span>{priceDrops.length} price drops</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{user && (
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
{user.picture ? (
|
||||
<img src={user.picture} alt={user.name} className="w-8 h-8 rounded-full" />
|
||||
) : (
|
||||
<User className="w-8 h-8 text-gray-400" />
|
||||
)}
|
||||
<span className="text-sm text-gray-700">{user.name}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={logout}
|
||||
className="flex items-center space-x-1 px-3 py-1 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
<span>Logout</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-4 mt-4">
|
||||
@ -582,64 +501,12 @@ const ApartmentDashboard = () => {
|
||||
>
|
||||
Analytics
|
||||
</Link>
|
||||
{user && user.role === 'admin' && (
|
||||
<div className="relative group">
|
||||
<button
|
||||
className={`flex items-center space-x-2 px-4 py-2 rounded-md ${location.pathname.startsWith('/admin') ? 'bg-violet-600 text-white' : 'bg-violet-100 text-violet-700 border border-violet-300 hover:bg-violet-200'}`}
|
||||
>
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Admin</span>
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
</button>
|
||||
<div className="absolute left-0 mt-1 w-48 bg-white rounded-md shadow-lg border border-gray-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-150 z-50">
|
||||
<Link
|
||||
to="/admin"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Overview
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/users"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/users' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Users
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/activity"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/activity' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Activity
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/stats"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/stats' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Statistics
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/settings"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/settings' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Settings
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/scraper"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/scraper' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Scraper
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
{/* Overview Page */}
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<>
|
||||
{/* Key Metrics */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
@ -721,7 +588,7 @@ const ApartmentDashboard = () => {
|
||||
/>
|
||||
<YAxis tickFormatter={(value) => formatPrice(value)} domain={getAxisDomain(priceHistory.filter(d => d.avgPrice !== null), 'avgPrice')} />
|
||||
<Tooltip
|
||||
formatter={(value) => [formatPrice(value), 'Avg Price']}
|
||||
formatter={(value, name) => [formatPrice(value), 'Avg Price']}
|
||||
labelFormatter={(date) => formatDate(date)}
|
||||
/>
|
||||
<Area type="monotone" dataKey="avgPrice" stroke="#8B0000" fill="#8B0000" fillOpacity={0.1} />
|
||||
@ -741,7 +608,7 @@ const ApartmentDashboard = () => {
|
||||
/>
|
||||
<YAxis domain={getAxisDomain(priceHistory, 'unitCount')} />
|
||||
<Tooltip
|
||||
formatter={(value) => [value, 'Available Units']}
|
||||
formatter={(value, name) => [value, 'Available Units']}
|
||||
labelFormatter={(date) => formatDate(date)}
|
||||
/>
|
||||
<Area type="monotone" dataKey="unitCount" stroke="#3B82F6" fill="#3B82F6" fillOpacity={0.2} />
|
||||
@ -783,7 +650,7 @@ const ApartmentDashboard = () => {
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="name" angle={-45} textAnchor="end" height={80} />
|
||||
<YAxis tickFormatter={(value) => formatPrice(value)} domain={getAxisDomain(planStats, 'avgPrice')} />
|
||||
<Tooltip formatter={(value) => [formatPrice(value), 'Avg Price']} />
|
||||
<Tooltip formatter={(value, name) => [formatPrice(value), 'Avg Price']} />
|
||||
<Bar dataKey="avgPrice" fill="#8B0000" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
@ -791,12 +658,10 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Units Page */}
|
||||
<Route path="/units" element={
|
||||
<ProtectedRoute>
|
||||
<div className="space-y-6">
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
@ -816,7 +681,7 @@ const ApartmentDashboard = () => {
|
||||
onChange={(e) => setPriceFilter({...priceFilter, max: parseInt(e.target.value)})}
|
||||
className="w-32"
|
||||
/>
|
||||
<span className="text-sm">{priceFilter.max === 10000 ? 'No limit' : formatPrice(priceFilter.max)}</span>
|
||||
<span className="text-sm">{formatPrice(priceFilter.max)}</span>
|
||||
</div>
|
||||
<select
|
||||
value={bedroomFilter}
|
||||
@ -828,25 +693,6 @@ const ApartmentDashboard = () => {
|
||||
<option value="1">1 BR</option>
|
||||
<option value="2">2 BR</option>
|
||||
</select>
|
||||
<select
|
||||
value={towerFilter}
|
||||
onChange={(e) => setTowerFilter(e.target.value)}
|
||||
className="border rounded-md px-3 py-2"
|
||||
>
|
||||
<option value="all">All Buildings</option>
|
||||
<option value="east">East Tower</option>
|
||||
<option value="west">West Tower</option>
|
||||
<option value="downing">23 S Downing</option>
|
||||
</select>
|
||||
<select
|
||||
value={facingFilter}
|
||||
onChange={(e) => setFacingFilter(e.target.value)}
|
||||
className="border rounded-md px-3 py-2"
|
||||
>
|
||||
<option value="all">All Facing</option>
|
||||
<option value="north">North Facing</option>
|
||||
<option value="south">South Facing</option>
|
||||
</select>
|
||||
<select
|
||||
value={`${sortBy}-${sortDirection}`}
|
||||
onChange={(e) => {
|
||||
@ -884,51 +730,6 @@ const ApartmentDashboard = () => {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Column Settings Toggle */}
|
||||
<div className="mt-4 border-t pt-4">
|
||||
<button
|
||||
onClick={() => setColumnSettingsOpen(!columnSettingsOpen)}
|
||||
className="flex items-center text-sm text-gray-600 hover:text-gray-900"
|
||||
>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
<span>Column Settings</span>
|
||||
{columnSettingsOpen ? (
|
||||
<ChevronUp className="w-4 h-4 ml-1" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 ml-1" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{columnSettingsOpen && (
|
||||
<div className="mt-3 flex flex-wrap gap-4">
|
||||
{[
|
||||
{ key: 'unit', label: 'Unit' },
|
||||
{ key: 'plan', label: 'Plan' },
|
||||
{ key: 'bedBath', label: 'Bed/Bath' },
|
||||
{ key: 'area', label: 'Area' },
|
||||
{ key: 'price', label: 'Price' },
|
||||
{ key: 'pricePerSqft', label: '$/sqft' },
|
||||
{ key: 'days', label: 'Days' },
|
||||
{ key: 'high', label: 'High' },
|
||||
{ key: 'low', label: 'Low' },
|
||||
{ key: 'delta', label: 'Delta' },
|
||||
{ key: 'soonest', label: 'Soonest' },
|
||||
{ key: 'actions', label: 'Actions' }
|
||||
].map(({ key, label }) => (
|
||||
<label key={key} className="flex items-center space-x-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={visibleColumns[key]}
|
||||
onChange={(e) => setVisibleColumns({...visibleColumns, [key]: e.target.checked})}
|
||||
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm">{label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Unit Cards - Grid View */}
|
||||
@ -979,13 +780,12 @@ const ApartmentDashboard = () => {
|
||||
|
||||
{/* Unit Cards - List View */}
|
||||
{unitsViewMode === 'list' && (
|
||||
<div className="bg-white rounded-lg shadow-md overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
{visibleColumns.unit && (
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none sticky left-0 z-10 bg-gray-50 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('unitCode')}
|
||||
>
|
||||
<span className="flex items-center">
|
||||
@ -993,8 +793,6 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'unitCode' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.plan && (
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('planName')}
|
||||
@ -1004,8 +802,6 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'planName' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.bedBath && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('bedCount')}
|
||||
@ -1015,8 +811,6 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'bedCount' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.area && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('area')}
|
||||
@ -1026,8 +820,6 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'area' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.price && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('price')}
|
||||
@ -1037,8 +829,6 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'price' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.pricePerSqft && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('pricePerSqft')}
|
||||
@ -1048,8 +838,6 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'pricePerSqft' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.days && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('daysAvailable')}
|
||||
@ -1059,41 +847,6 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'daysAvailable' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.high && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('maxPrice')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
High
|
||||
{sortBy === 'maxPrice' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.low && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('minPrice')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
Low
|
||||
{sortBy === 'minPrice' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.delta && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('delta')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
Delta
|
||||
{sortBy === 'delta' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.soonest && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('soonest')}
|
||||
@ -1103,10 +856,7 @@ const ApartmentDashboard = () => {
|
||||
{sortBy === 'soonest' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.actions && (
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Actions</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@ -1115,36 +865,14 @@ const ApartmentDashboard = () => {
|
||||
key={unit.unitCode}
|
||||
className={`border-b ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'} ${watchedUnits.has(unit.unitCode) ? 'ring-2 ring-inset ring-blue-400' : ''} hover:bg-blue-50`}
|
||||
>
|
||||
{visibleColumns.unit && <td className={`py-3 px-4 font-bold sticky left-0 z-10 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)] ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}`}>{unit.unitCode}</td>}
|
||||
{visibleColumns.plan && <td className="py-3 px-4 text-gray-600">{unit.planName}</td>}
|
||||
{visibleColumns.bedBath && <td className="py-3 px-4 text-center">{unit.bedCount}/{unit.bathCount}</td>}
|
||||
{visibleColumns.area && <td className="py-3 px-4 text-center">{unit.area} sqft</td>}
|
||||
{visibleColumns.price && <td className="py-3 px-4 text-right font-bold text-green-600">{formatPrice(unit.currentPrice)}</td>}
|
||||
{visibleColumns.pricePerSqft && <td className="py-3 px-4 text-right text-gray-500">${((unit.currentPrice || 0) / (unit.area || 1)).toFixed(2)}</td>}
|
||||
{visibleColumns.days && <td className="py-3 px-4 text-center">{unit.daysAvailable || 0}</td>}
|
||||
{visibleColumns.high && <td className="py-3 px-4 text-right text-gray-600">{formatPrice(unit.maxPrice)}</td>}
|
||||
{visibleColumns.low && <td className="py-3 px-4 text-right text-gray-600">{formatPrice(unit.minPrice)}</td>}
|
||||
{visibleColumns.delta && (
|
||||
<td className={`py-3 px-4 text-right ${
|
||||
unit.priceChangeToday > 0 ? 'text-red-600' :
|
||||
unit.priceChangeToday < 0 ? 'text-green-600' :
|
||||
'text-gray-500'
|
||||
}`}>
|
||||
<span className="flex items-center justify-end">
|
||||
{unit.priceChangeToday !== null && unit.priceChangeToday !== 0 && (
|
||||
unit.priceChangeToday > 0
|
||||
? <ArrowUp className="w-4 h-4 mr-1" />
|
||||
: <ArrowDown className="w-4 h-4 mr-1" />
|
||||
)}
|
||||
{unit.priceChangeToday !== null
|
||||
? `${unit.priceChangeToday > 0 ? '+' : ''}${formatPrice(unit.priceChangeToday)}`
|
||||
: '--'
|
||||
}
|
||||
</span>
|
||||
</td>
|
||||
)}
|
||||
{visibleColumns.soonest && <td className="py-3 px-4 text-center">{unit.soonest ? (new Date(unit.soonest) <= new Date() ? 'Now' : formatDate(unit.soonest)) : '-'}</td>}
|
||||
{visibleColumns.actions && (
|
||||
<td className="py-3 px-4 font-bold">{unit.unitCode}</td>
|
||||
<td className="py-3 px-4 text-gray-600">{unit.planName}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.bedCount}/{unit.bathCount}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.area} sqft</td>
|
||||
<td className="py-3 px-4 text-right font-bold text-green-600">{formatPrice(unit.currentPrice)}</td>
|
||||
<td className="py-3 px-4 text-right text-gray-500">${((unit.currentPrice || 0) / (unit.area || 1)).toFixed(2)}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.daysAvailable || 0}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.soonest ? (new Date(unit.soonest) <= new Date() ? 'Now' : formatDate(unit.soonest)) : '-'}</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<button
|
||||
onClick={() => openUnitDetail(unit)}
|
||||
@ -1153,7 +881,6 @@ const ApartmentDashboard = () => {
|
||||
Details
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@ -1169,12 +896,10 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Analytics Page */}
|
||||
<Route path="/analytics" element={
|
||||
<ProtectedRoute>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-xl font-semibold">Market Analytics</h2>
|
||||
@ -1378,44 +1103,6 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Admin Routes */}
|
||||
<Route path="/admin" element={
|
||||
<AdminRoute>
|
||||
<AdminOverview />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/users" element={
|
||||
<AdminRoute>
|
||||
<UserList />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/users/:id" element={
|
||||
<AdminRoute>
|
||||
<UserDetail />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/activity" element={
|
||||
<AdminRoute>
|
||||
<ActivityStream />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/stats" element={
|
||||
<AdminRoute>
|
||||
<UsageStats />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/settings" element={
|
||||
<AdminRoute>
|
||||
<AdminSettings />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/scraper" element={
|
||||
<AdminRoute>
|
||||
<ScraperManagement />
|
||||
</AdminRoute>
|
||||
} />
|
||||
|
||||
{/* Catch-all redirect to overview */}
|
||||
@ -1540,7 +1227,7 @@ const ApartmentDashboard = () => {
|
||||
/>
|
||||
<YAxis tickFormatter={(value) => formatPrice(value)} domain={['dataMin - 50', 'dataMax + 50']} />
|
||||
<Tooltip
|
||||
formatter={(value) => [formatPrice(value), modalTimeRange === 'year' ? 'Weekly Avg' : 'Price']}
|
||||
formatter={(value, name) => [formatPrice(value), modalTimeRange === 'year' ? 'Weekly Avg' : 'Price']}
|
||||
labelFormatter={(date) => formatDate(date)}
|
||||
/>
|
||||
<Line type="monotone" dataKey="price" stroke="#8B0000" strokeWidth={2} dot={modalTimeRange === 'month'} />
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const AdminRoute = ({ children }) => {
|
||||
const { user, loading } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
// Loading state during auth check
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-violet-600"></div>
|
||||
<p className="mt-4 text-gray-600">Checking permissions...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Not authenticated - redirect to login
|
||||
if (!user) {
|
||||
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
// Not an admin - redirect to home
|
||||
if (user.role !== 'admin') {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export default AdminRoute;
|
||||
@ -1,23 +0,0 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const ProtectedRoute = ({ children }) => {
|
||||
const { user, loading } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export default ProtectedRoute;
|
||||
@ -1,54 +0,0 @@
|
||||
import { createContext, useState, useEffect, useCallback } from 'react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
// eslint-disable-next-line react-refresh/only-export-components
|
||||
export const AuthContext = createContext(null);
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const checkAuth = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/auth/me`, { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setUser(data.user);
|
||||
} else {
|
||||
setUser(null);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Auth check failed:', err);
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, [checkAuth]);
|
||||
|
||||
const login = () => {
|
||||
window.location.href = `${API_BASE}/auth/google`;
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Logout error:', err);
|
||||
}
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, checkAuth }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
@ -1,53 +0,0 @@
|
||||
import { useEffect, useCallback, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import useAuth from './useAuth';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const useActivityTracker = () => {
|
||||
const { user } = useAuth();
|
||||
const location = useLocation();
|
||||
const lastActivity = useRef({ action: null, timestamp: 0 });
|
||||
|
||||
const trackActivity = useCallback(async (action, metadata = {}) => {
|
||||
// Only track if user is authenticated
|
||||
if (!user) return;
|
||||
|
||||
// Debounce: skip if same action within 300ms
|
||||
const now = Date.now();
|
||||
if (lastActivity.current.action === action &&
|
||||
now - lastActivity.current.timestamp < 300) {
|
||||
return;
|
||||
}
|
||||
lastActivity.current = { action, timestamp: now };
|
||||
|
||||
try {
|
||||
await fetch(`${API_BASE}/activity/log`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
action,
|
||||
metadata: {
|
||||
...metadata,
|
||||
page: location.pathname
|
||||
}
|
||||
})
|
||||
});
|
||||
} catch (err) {
|
||||
// Silently fail - activity logging shouldn't break the app
|
||||
console.error('Activity tracking error:', err);
|
||||
}
|
||||
}, [user, location.pathname]);
|
||||
|
||||
// Track page views on route changes
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
trackActivity('page_view', { path: location.pathname });
|
||||
}
|
||||
}, [location.pathname, user, trackActivity]);
|
||||
|
||||
return { trackActivity };
|
||||
};
|
||||
|
||||
export default useActivityTracker;
|
||||
@ -1,14 +0,0 @@
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from '../context/AuthContext';
|
||||
|
||||
const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
|
||||
if (context === null) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export default useAuth;
|
||||
@ -1,16 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { AuthProvider } from './context/AuthContext'
|
||||
import './index.css'
|
||||
import App from './App.jsx'
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
|
||||
@ -1,91 +0,0 @@
|
||||
import { Navigate, useLocation, useSearchParams } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const Login = () => {
|
||||
const { user, loading, login } = useAuth();
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const error = searchParams.get('error');
|
||||
const from = location.state?.from?.pathname || '/';
|
||||
|
||||
// Error messages based on AUTH.md
|
||||
const errorMessages = {
|
||||
cancelled: 'Sign in was cancelled.',
|
||||
unverified: 'Please verify your Google email address first.',
|
||||
invalid_state: 'Session expired. Please try again.',
|
||||
provider_error: 'Google sign in is temporarily unavailable.',
|
||||
auth_failed: 'Authentication failed. Please try again.'
|
||||
};
|
||||
|
||||
// If already authenticated, redirect to intended destination
|
||||
if (!loading && user) {
|
||||
return <Navigate to={from} replace />;
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
<p className="mt-4 text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md max-w-md w-full">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold text-gray-800">Apartment Dashboard</h1>
|
||||
<p className="text-gray-600 mt-2">Sign in to view rental analytics</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-md text-sm">
|
||||
{errorMessages[error] || 'An error occurred. Please try again.'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={login}
|
||||
className="w-full flex items-center justify-center gap-3 px-4 py-3 border border-gray-300 rounded-md shadow-sm bg-white hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 18 18"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<g fill="none" fillRule="evenodd">
|
||||
<path
|
||||
d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 01-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z"
|
||||
fill="#34A853"
|
||||
/>
|
||||
<path
|
||||
d="M3.964 10.71A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"
|
||||
fill="#FBBC05"
|
||||
/>
|
||||
<path
|
||||
d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"
|
||||
fill="#EA4335"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
<span className="text-gray-700 font-medium">Sign in with Google</span>
|
||||
</button>
|
||||
|
||||
<div className="mt-6 text-center text-xs text-gray-500">
|
||||
<p>By signing in, you agree to access apartment rental analytics</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
@ -1,744 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
RefreshCw,
|
||||
Activity,
|
||||
Download,
|
||||
Filter,
|
||||
X,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Bell,
|
||||
Calendar,
|
||||
User,
|
||||
LogIn,
|
||||
LogOut,
|
||||
Eye,
|
||||
Navigation
|
||||
} from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
// Action type icons and labels
|
||||
const ACTION_CONFIG = {
|
||||
LOGIN: { icon: LogIn, label: 'Logged in', color: 'text-green-600' },
|
||||
LOGOUT: { icon: LogOut, label: 'Logged out', color: 'text-gray-600' },
|
||||
PAGE_VIEW: { icon: Eye, label: 'Viewed', color: 'text-blue-600' },
|
||||
NAVIGATION: { icon: Navigation, label: 'Navigated', color: 'text-violet-600' },
|
||||
API_CALL: { icon: Activity, label: 'API call', color: 'text-orange-600' },
|
||||
ADMIN_ENABLE_USER: { icon: User, label: 'Enabled user', color: 'text-green-600' },
|
||||
ADMIN_DISABLE_USER: { icon: User, label: 'Disabled user', color: 'text-red-600' },
|
||||
ADMIN_PROMOTE_USER: { icon: User, label: 'Promoted user', color: 'text-violet-600' },
|
||||
ADMIN_DEMOTE_USER: { icon: User, label: 'Demoted user', color: 'text-orange-600' }
|
||||
};
|
||||
|
||||
// Available action types for filter
|
||||
const ACTION_TYPES = [
|
||||
{ value: '', label: 'All Actions' },
|
||||
{ value: 'LOGIN', label: 'Login' },
|
||||
{ value: 'LOGOUT', label: 'Logout' },
|
||||
{ value: 'PAGE_VIEW', label: 'Page View' },
|
||||
{ value: 'NAVIGATION', label: 'Navigation' }
|
||||
];
|
||||
|
||||
const ActivityStream = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [activities, setActivities] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Pagination
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [totalActivities, setTotalActivities] = useState(0);
|
||||
const limit = 50;
|
||||
|
||||
// Filters
|
||||
const [userFilter, setUserFilter] = useState('');
|
||||
const [actionFilter, setActionFilter] = useState('');
|
||||
const [startDate, setStartDate] = useState('');
|
||||
const [endDate, setEndDate] = useState('');
|
||||
|
||||
// Users for filter dropdown
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loadingUsers, setLoadingUsers] = useState(false);
|
||||
|
||||
// Auto-refresh state
|
||||
const [autoRefresh, setAutoRefresh] = useState(true);
|
||||
const [newActivityCount, setNewActivityCount] = useState(0);
|
||||
const [lastActivityId, setLastActivityId] = useState(null);
|
||||
const autoRefreshInterval = useRef(null);
|
||||
|
||||
// Export modal state
|
||||
const [showExportModal, setShowExportModal] = useState(false);
|
||||
const [exportStartDate, setExportStartDate] = useState('');
|
||||
const [exportEndDate, setExportEndDate] = useState('');
|
||||
const [exporting, setExporting] = useState(false);
|
||||
|
||||
// Check if filters are active
|
||||
const hasActiveFilters = userFilter || actionFilter || startDate || endDate;
|
||||
|
||||
// Fetch users for filter dropdown
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoadingUsers(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/users?limit=100`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setUsers(data.data.users || []);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching users:', err);
|
||||
} finally {
|
||||
setLoadingUsers(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch activities
|
||||
const fetchActivities = useCallback(async (isBackgroundRefresh = false) => {
|
||||
if (!isBackgroundRefresh) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
limit: limit.toString()
|
||||
});
|
||||
|
||||
if (userFilter) {
|
||||
params.append('userId', userFilter);
|
||||
}
|
||||
if (actionFilter) {
|
||||
params.append('action', actionFilter);
|
||||
}
|
||||
if (startDate) {
|
||||
params.append('startDate', new Date(startDate).toISOString());
|
||||
}
|
||||
if (endDate) {
|
||||
// Set end date to end of day
|
||||
const end = new Date(endDate);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
params.append('endDate', end.toISOString());
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/admin/activity?${params}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch activity data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const newActivities = data.data?.activities || [];
|
||||
|
||||
// Check for new activities (for indicator)
|
||||
if (isBackgroundRefresh && newActivities.length > 0 && lastActivityId) {
|
||||
const newCount = newActivities.findIndex(a => a._id === lastActivityId);
|
||||
if (newCount > 0) {
|
||||
setNewActivityCount(newCount);
|
||||
} else if (newCount === -1 && newActivities[0]._id !== lastActivityId) {
|
||||
// All activities are new (or first activity changed)
|
||||
setNewActivityCount(newActivities.length);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isBackgroundRefresh) {
|
||||
setActivities(newActivities);
|
||||
setNewActivityCount(0);
|
||||
if (newActivities.length > 0) {
|
||||
setLastActivityId(newActivities[0]._id);
|
||||
}
|
||||
}
|
||||
|
||||
setTotalPages(data.data?.pagination?.pages || 1);
|
||||
setTotalActivities(data.data?.pagination?.total || 0);
|
||||
} catch (err) {
|
||||
console.error('Error fetching activities:', err);
|
||||
if (!isBackgroundRefresh) {
|
||||
setError(err.message);
|
||||
}
|
||||
} finally {
|
||||
if (!isBackgroundRefresh) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [page, userFilter, actionFilter, startDate, endDate, lastActivityId]);
|
||||
|
||||
// Load new activities when indicator is clicked
|
||||
const loadNewActivities = () => {
|
||||
setNewActivityCount(0);
|
||||
fetchActivities(false);
|
||||
};
|
||||
|
||||
// Fetch on mount and when dependencies change
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, [fetchUsers]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchActivities();
|
||||
}, [fetchActivities]);
|
||||
|
||||
// Auto-refresh every 30 seconds (when tab is active and no filters)
|
||||
useEffect(() => {
|
||||
// Clear existing interval
|
||||
if (autoRefreshInterval.current) {
|
||||
clearInterval(autoRefreshInterval.current);
|
||||
autoRefreshInterval.current = null;
|
||||
}
|
||||
|
||||
// Only auto-refresh if enabled and no filters active
|
||||
if (autoRefresh && !hasActiveFilters) {
|
||||
autoRefreshInterval.current = setInterval(() => {
|
||||
// Only refresh if document is visible
|
||||
if (!document.hidden) {
|
||||
fetchActivities(true);
|
||||
}
|
||||
}, 30000); // 30 seconds
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (autoRefreshInterval.current) {
|
||||
clearInterval(autoRefreshInterval.current);
|
||||
}
|
||||
};
|
||||
}, [autoRefresh, hasActiveFilters, fetchActivities]);
|
||||
|
||||
// Pause auto-refresh when tab is hidden
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.hidden) {
|
||||
// Tab is hidden, pause is handled by the interval check
|
||||
} else {
|
||||
// Tab is visible again, do an immediate check
|
||||
if (autoRefresh && !hasActiveFilters) {
|
||||
fetchActivities(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, [autoRefresh, hasActiveFilters, fetchActivities]);
|
||||
|
||||
// Handle export
|
||||
const handleExport = async () => {
|
||||
if (!exportStartDate || !exportEndDate) {
|
||||
alert('Please select both start and end dates');
|
||||
return;
|
||||
}
|
||||
|
||||
setExporting(true);
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
startDate: new Date(exportStartDate).toISOString(),
|
||||
endDate: new Date(exportEndDate + 'T23:59:59.999').toISOString()
|
||||
});
|
||||
|
||||
if (userFilter) {
|
||||
params.append('userId', userFilter);
|
||||
}
|
||||
if (actionFilter) {
|
||||
params.append('action', actionFilter);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/admin/activity/export?${params}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to export activity data');
|
||||
}
|
||||
|
||||
// Get filename from content-disposition header or generate one
|
||||
const contentDisposition = response.headers.get('content-disposition');
|
||||
let filename = `activity-export-${exportStartDate}-to-${exportEndDate}.csv`;
|
||||
if (contentDisposition) {
|
||||
const match = contentDisposition.match(/filename="?([^"]+)"?/);
|
||||
if (match) {
|
||||
filename = match[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Download the file
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
|
||||
setShowExportModal(false);
|
||||
setExportStartDate('');
|
||||
setExportEndDate('');
|
||||
} catch (err) {
|
||||
console.error('Error exporting activity:', err);
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Clear all filters
|
||||
const clearFilters = () => {
|
||||
setUserFilter('');
|
||||
setActionFilter('');
|
||||
setStartDate('');
|
||||
setEndDate('');
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// Format relative time
|
||||
const formatRelativeTime = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diffMs = now - date;
|
||||
const diffSeconds = Math.floor(diffMs / 1000);
|
||||
const diffMinutes = Math.floor(diffSeconds / 60);
|
||||
const diffHours = Math.floor(diffMinutes / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffSeconds < 60) {
|
||||
return 'Just now';
|
||||
} else if (diffMinutes < 60) {
|
||||
return `${diffMinutes} minute${diffMinutes !== 1 ? 's' : ''} ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays} day${diffDays !== 1 ? 's' : ''} ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Get action description
|
||||
const getActionDescription = (activity) => {
|
||||
const config = ACTION_CONFIG[activity.action] || { label: activity.action };
|
||||
|
||||
switch (activity.action) {
|
||||
case 'PAGE_VIEW':
|
||||
return `viewed ${activity.metadata?.path || 'a page'}`;
|
||||
case 'NAVIGATION':
|
||||
return `navigated from ${activity.metadata?.from || 'unknown'} to ${activity.metadata?.to || 'unknown'}`;
|
||||
case 'LOGIN':
|
||||
return 'logged in';
|
||||
case 'LOGOUT':
|
||||
return 'logged out';
|
||||
case 'ADMIN_ENABLE_USER':
|
||||
return 'enabled a user account';
|
||||
case 'ADMIN_DISABLE_USER':
|
||||
return 'disabled a user account';
|
||||
case 'ADMIN_PROMOTE_USER':
|
||||
return 'promoted a user to admin';
|
||||
case 'ADMIN_DEMOTE_USER':
|
||||
return 'demoted a user from admin';
|
||||
default:
|
||||
return config.label.toLowerCase();
|
||||
}
|
||||
};
|
||||
|
||||
// Get action icon
|
||||
const getActionIcon = (action) => {
|
||||
const config = ACTION_CONFIG[action] || { icon: Activity, color: 'text-gray-600' };
|
||||
const Icon = config.icon;
|
||||
return <Icon className={`w-4 h-4 ${config.color}`} />;
|
||||
};
|
||||
|
||||
// Navigate to user detail
|
||||
const handleUserClick = (userId, e) => {
|
||||
e.stopPropagation();
|
||||
navigate(`/admin/users/${userId}`);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={() => fetchActivities()}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Activity Stream</h1>
|
||||
<p className="text-gray-600">
|
||||
{totalActivities} total activit{totalActivities !== 1 ? 'ies' : 'y'}
|
||||
{hasActiveFilters && ' (filtered)'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center space-x-3">
|
||||
{/* Export Button */}
|
||||
<button
|
||||
onClick={() => setShowExportModal(true)}
|
||||
className="flex items-center space-x-2 px-4 py-2 border border-gray-300 rounded-md bg-white hover:bg-gray-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">Export</span>
|
||||
</button>
|
||||
|
||||
{/* Refresh Button */}
|
||||
<button
|
||||
onClick={() => fetchActivities()}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* New Activity Indicator */}
|
||||
{newActivityCount > 0 && (
|
||||
<button
|
||||
onClick={loadNewActivities}
|
||||
className="w-full flex items-center justify-center space-x-2 py-3 bg-violet-100 text-violet-700 rounded-lg hover:bg-violet-200 transition-colors"
|
||||
>
|
||||
<Bell className="w-4 h-4" />
|
||||
<span>{newActivityCount} new activit{newActivityCount !== 1 ? 'ies' : 'y'} available</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-lg shadow-md p-4">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Filter className="w-5 h-5 text-gray-500" />
|
||||
<span className="font-medium text-gray-700">Filters:</span>
|
||||
</div>
|
||||
|
||||
{/* User Filter */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<label className="text-sm text-gray-600">User:</label>
|
||||
<select
|
||||
value={userFilter}
|
||||
onChange={(e) => { setUserFilter(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
disabled={loadingUsers}
|
||||
>
|
||||
<option value="">All Users</option>
|
||||
{users.map((user) => (
|
||||
<option key={user._id} value={user._id}>
|
||||
{user.name} ({user.email})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Action Filter */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<label className="text-sm text-gray-600">Action:</label>
|
||||
<select
|
||||
value={actionFilter}
|
||||
onChange={(e) => { setActionFilter(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
>
|
||||
{ACTION_TYPES.map((type) => (
|
||||
<option key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Date Range */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Calendar className="w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => { setStartDate(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
placeholder="Start Date"
|
||||
/>
|
||||
<span className="text-gray-500">to</span>
|
||||
<input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => { setEndDate(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
placeholder="End Date"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Clear Filters */}
|
||||
{hasActiveFilters && (
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="flex items-center space-x-1 px-3 py-2 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
<span>Clear</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Auto-refresh toggle */}
|
||||
<div className="ml-auto flex items-center space-x-2">
|
||||
<label className="text-sm text-gray-600">Auto-refresh:</label>
|
||||
<button
|
||||
onClick={() => setAutoRefresh(!autoRefresh)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
autoRefresh && !hasActiveFilters ? 'bg-violet-600' : 'bg-gray-300'
|
||||
}`}
|
||||
disabled={hasActiveFilters}
|
||||
title={hasActiveFilters ? 'Auto-refresh is paused while filters are active' : ''}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
autoRefresh && !hasActiveFilters ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
{hasActiveFilters && (
|
||||
<span className="text-xs text-gray-500">(paused)</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Activity List */}
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{loading && activities.length === 0 ? (
|
||||
/* Skeleton Loader */
|
||||
<div className="divide-y divide-gray-100">
|
||||
{[...Array(8)].map((_, index) => (
|
||||
<div key={index} className="p-4">
|
||||
<div className="flex items-start space-x-4 animate-pulse">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-10 h-10 rounded-full bg-gray-200"></div>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="h-4 bg-gray-200 rounded w-24"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-32"></div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="h-3 bg-gray-200 rounded w-4"></div>
|
||||
<div className="h-3 bg-gray-200 rounded w-40"></div>
|
||||
<div className="h-3 bg-gray-200 rounded w-20"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : activities.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<Activity className="w-16 h-16 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">No Activity Found</h3>
|
||||
<p className="text-gray-600">
|
||||
{hasActiveFilters
|
||||
? 'No activity recorded in this period. Try adjusting your filters.'
|
||||
: 'No activity has been recorded yet. User activity will appear here once users start interacting with the application.'}
|
||||
</p>
|
||||
{hasActiveFilters && (
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="mt-4 px-4 py-2 text-violet-600 hover:text-violet-700 hover:bg-violet-50 rounded-md"
|
||||
>
|
||||
Clear all filters
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{activities.map((activity) => (
|
||||
<div
|
||||
key={activity._id}
|
||||
className="p-4 hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<div className="flex items-start space-x-4">
|
||||
{/* Avatar */}
|
||||
<div
|
||||
className="flex-shrink-0 cursor-pointer"
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
>
|
||||
{activity.userPicture ? (
|
||||
<img
|
||||
src={activity.userPicture}
|
||||
alt={activity.userName}
|
||||
className="w-10 h-10 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-sm font-medium text-gray-600">
|
||||
{activity.userName?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
className="font-medium text-gray-900 hover:text-violet-600 hover:underline"
|
||||
>
|
||||
{activity.userName || 'Unknown User'}
|
||||
</button>
|
||||
<span className="text-gray-600">
|
||||
{getActionDescription(activity)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 mt-1 text-sm text-gray-500">
|
||||
{getActionIcon(activity.action)}
|
||||
<span>{activity.userEmail}</span>
|
||||
<span className="text-gray-300">|</span>
|
||||
<span>{formatRelativeTime(activity.timestamp)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-col sm:flex-row items-center justify-between gap-3 px-4 py-3 bg-gray-50 border-t">
|
||||
<div className="text-sm text-gray-600 text-center sm:text-left">
|
||||
Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, totalActivities)} of {totalActivities} activities
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={() => setPage(Math.max(1, page - 1))}
|
||||
disabled={page === 1 || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<span className="ml-1 hidden sm:inline">Previous</span>
|
||||
</button>
|
||||
<span className="px-3 py-1 text-sm">
|
||||
{page} / {totalPages}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setPage(Math.min(totalPages, page + 1))}
|
||||
disabled={page === totalPages || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<span className="mr-1 hidden sm:inline">Next</span>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Export Modal */}
|
||||
{showExportModal && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-lg font-semibold">Export Activity Data</h3>
|
||||
<button
|
||||
onClick={() => setShowExportModal(false)}
|
||||
className="text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-600 mb-4">
|
||||
Select a date range to export activity data as CSV. Export is limited to 10,000 records.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Start Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={exportStartDate}
|
||||
onChange={(e) => setExportStartDate(e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
End Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={exportEndDate}
|
||||
onChange={(e) => setExportEndDate(e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{userFilter && (
|
||||
<p className="text-sm text-gray-500">
|
||||
Note: Current user filter will be applied to export.
|
||||
</p>
|
||||
)}
|
||||
{actionFilter && (
|
||||
<p className="text-sm text-gray-500">
|
||||
Note: Current action filter will be applied to export.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3 mt-6">
|
||||
<button
|
||||
onClick={() => setShowExportModal(false)}
|
||||
disabled={exporting}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleExport}
|
||||
disabled={exporting || !exportStartDate || !exportEndDate}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
{exporting ? (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span>Exporting...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="w-4 h-4" />
|
||||
<span>Export CSV</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ActivityStream;
|
||||
@ -1,519 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer
|
||||
} from 'recharts';
|
||||
import {
|
||||
Users,
|
||||
UserPlus,
|
||||
Activity,
|
||||
TrendingUp,
|
||||
RefreshCw,
|
||||
Calendar,
|
||||
LogIn,
|
||||
Eye,
|
||||
ChevronRight
|
||||
} from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
// Stats card component
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const StatsCard = ({ title, value, subtitle, icon: IconComponent, color = 'violet', loading = false }) => {
|
||||
const colorClasses = {
|
||||
violet: 'bg-violet-100 text-violet-600',
|
||||
green: 'bg-green-100 text-green-600',
|
||||
blue: 'bg-blue-100 text-blue-600',
|
||||
orange: 'bg-orange-100 text-orange-600',
|
||||
red: 'bg-red-100 text-red-600'
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-600">{title}</p>
|
||||
{loading ? (
|
||||
<div className="h-8 w-16 bg-gray-200 animate-pulse rounded mt-1" />
|
||||
) : (
|
||||
<p className="text-2xl font-bold text-gray-900">{value}</p>
|
||||
)}
|
||||
{subtitle && <p className="text-sm text-gray-500 mt-1">{subtitle}</p>}
|
||||
</div>
|
||||
<div className={`p-3 rounded-full ${colorClasses[color]}`}>
|
||||
<IconComponent className="w-6 h-6" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Action type icons and labels for recent activity
|
||||
const ACTION_CONFIG = {
|
||||
LOGIN: { icon: LogIn, label: 'logged in', color: 'text-green-600' },
|
||||
LOGOUT: { icon: LogIn, label: 'logged out', color: 'text-gray-600' },
|
||||
PAGE_VIEW: { icon: Eye, label: 'viewed', color: 'text-blue-600' },
|
||||
NAVIGATION: { icon: Activity, label: 'navigated', color: 'text-violet-600' }
|
||||
};
|
||||
|
||||
const AdminOverview = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [overview, setOverview] = useState(null);
|
||||
const [activeUsersData, setActiveUsersData] = useState([]);
|
||||
const [recentActivity, setRecentActivity] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Fetch overview stats
|
||||
const fetchOverview = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/stats/overview`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch overview stats');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setOverview(data.data);
|
||||
} catch (err) {
|
||||
console.error('Error fetching overview:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch 7-day active users
|
||||
const fetchActiveUsers = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/stats/active-users?period=daily&days=7`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch active users data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// Sort by date ascending for chart display
|
||||
const sortedData = (data.data || []).sort((a, b) =>
|
||||
new Date(a.date) - new Date(b.date)
|
||||
);
|
||||
setActiveUsersData(sortedData);
|
||||
} catch (err) {
|
||||
console.error('Error fetching active users:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch recent activity (last 10)
|
||||
const fetchRecentActivity = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/activity?limit=10`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch recent activity');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setRecentActivity(data.data?.activities || []);
|
||||
} catch (err) {
|
||||
console.error('Error fetching recent activity:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch all data
|
||||
const fetchAllData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await Promise.all([
|
||||
fetchOverview(),
|
||||
fetchActiveUsers(),
|
||||
fetchRecentActivity()
|
||||
]);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [fetchOverview, fetchActiveUsers, fetchRecentActivity]);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchAllData();
|
||||
}, [fetchAllData]);
|
||||
|
||||
// Format relative time
|
||||
const formatRelativeTime = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diffMs = now - date;
|
||||
const diffSeconds = Math.floor(diffMs / 1000);
|
||||
const diffMinutes = Math.floor(diffSeconds / 60);
|
||||
const diffHours = Math.floor(diffMinutes / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffSeconds < 60) {
|
||||
return 'Just now';
|
||||
} else if (diffMinutes < 60) {
|
||||
return `${diffMinutes}m ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours}h ago`;
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays}d ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Format date for chart
|
||||
const formatChartDate = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
// Get action description
|
||||
const getActionDescription = (activity) => {
|
||||
switch (activity.action) {
|
||||
case 'PAGE_VIEW':
|
||||
return `viewed ${activity.metadata?.path || 'a page'}`;
|
||||
case 'NAVIGATION':
|
||||
return `navigated to ${activity.metadata?.to || 'unknown'}`;
|
||||
case 'LOGIN':
|
||||
return 'logged in';
|
||||
case 'LOGOUT':
|
||||
return 'logged out';
|
||||
default:
|
||||
return activity.action.toLowerCase().replace(/_/g, ' ');
|
||||
}
|
||||
};
|
||||
|
||||
// Navigate to user detail
|
||||
const handleUserClick = (userId, e) => {
|
||||
e.stopPropagation();
|
||||
navigate(`/admin/users/${userId}`);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Admin Dashboard</h1>
|
||||
<p className="text-gray-600">Overview of user activity and statistics</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
<StatsCard
|
||||
title="Total Users"
|
||||
value={overview?.totalUsers || 0}
|
||||
subtitle={`${overview?.activeUsers || 0} active`}
|
||||
icon={Users}
|
||||
color="violet"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Active Today (DAU)"
|
||||
value={overview?.dau || 0}
|
||||
icon={Activity}
|
||||
color="green"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Active This Week (WAU)"
|
||||
value={overview?.wau || 0}
|
||||
icon={TrendingUp}
|
||||
color="blue"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="New This Week"
|
||||
value={overview?.newUsersThisWeek || 0}
|
||||
subtitle={`${overview?.newUsersToday || 0} today`}
|
||||
icon={UserPlus}
|
||||
color="orange"
|
||||
loading={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Second Row Stats */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<StatsCard
|
||||
title="Monthly Active (MAU)"
|
||||
value={overview?.mau || 0}
|
||||
icon={Calendar}
|
||||
color="violet"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Total Logins"
|
||||
value={overview?.totalLogins?.toLocaleString() || 0}
|
||||
subtitle={`Avg ${overview?.avgLoginsPerUser?.toFixed(1) || 0} per user`}
|
||||
icon={LogIn}
|
||||
color="green"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="DAU/MAU Ratio"
|
||||
value={overview?.mau > 0 ? `${((overview?.dau / overview?.mau) * 100).toFixed(1)}%` : '0%'}
|
||||
subtitle="Engagement indicator"
|
||||
icon={TrendingUp}
|
||||
color="blue"
|
||||
loading={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Charts and Activity Row */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* 7-Day Active Users Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Active Users (7 Days)</h2>
|
||||
<button
|
||||
onClick={() => navigate('/admin/stats')}
|
||||
className="text-sm text-violet-600 hover:text-violet-700 flex items-center"
|
||||
>
|
||||
View More
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Chart Skeleton */
|
||||
<div className="h-64 animate-pulse">
|
||||
<div className="flex items-end h-52 space-x-2 px-4">
|
||||
{[...Array(7)].map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-1 bg-gray-200 rounded-t"
|
||||
style={{ height: `${Math.random() * 60 + 20}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex justify-between mt-3 px-4">
|
||||
{[...Array(7)].map((_, i) => (
|
||||
<div key={i} className="h-3 bg-gray-200 rounded w-8" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : activeUsersData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<LineChart data={activeUsersData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={formatChartDate}
|
||||
tick={{ fontSize: 12 }}
|
||||
/>
|
||||
<YAxis
|
||||
allowDecimals={false}
|
||||
tick={{ fontSize: 12 }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => [value, 'Active Users']}
|
||||
labelFormatter={formatChartDate}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="count"
|
||||
stroke="#7c3aed"
|
||||
strokeWidth={2}
|
||||
dot={{ fill: '#7c3aed', strokeWidth: 2 }}
|
||||
activeDot={{ r: 6 }}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
No activity data available
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recent Activity Widget */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Recent Activity</h2>
|
||||
<button
|
||||
onClick={() => navigate('/admin/activity')}
|
||||
className="text-sm text-violet-600 hover:text-violet-700 flex items-center"
|
||||
>
|
||||
View All
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="space-y-3">
|
||||
{[...Array(5)].map((_, i) => (
|
||||
<div key={i} className="flex items-center space-x-3">
|
||||
<div className="w-8 h-8 bg-gray-200 rounded-full animate-pulse" />
|
||||
<div className="flex-1">
|
||||
<div className="h-4 bg-gray-200 rounded animate-pulse w-3/4" />
|
||||
<div className="h-3 bg-gray-200 rounded animate-pulse w-1/2 mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : recentActivity.length > 0 ? (
|
||||
<div className="space-y-3 max-h-[280px] overflow-y-auto">
|
||||
{recentActivity.map((activity) => {
|
||||
const config = ACTION_CONFIG[activity.action] || {
|
||||
icon: Activity,
|
||||
color: 'text-gray-600'
|
||||
};
|
||||
const Icon = config.icon;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={activity._id}
|
||||
className="flex items-start space-x-3 p-2 hover:bg-gray-50 rounded-lg transition-colors"
|
||||
>
|
||||
{/* Avatar */}
|
||||
<button
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
{activity.userPicture ? (
|
||||
<img
|
||||
src={activity.userPicture}
|
||||
alt={activity.userName}
|
||||
className="w-8 h-8 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-xs font-medium text-gray-600">
|
||||
{activity.userName?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm text-gray-900 truncate">
|
||||
<button
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
className="font-medium hover:text-violet-600"
|
||||
>
|
||||
{activity.userName || 'Unknown'}
|
||||
</button>
|
||||
{' '}
|
||||
<span className="text-gray-600">
|
||||
{getActionDescription(activity)}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 flex items-center mt-0.5">
|
||||
<Icon className={`w-3 h-3 mr-1 ${config.color}`} />
|
||||
{formatRelativeTime(activity.timestamp)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Activity className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No recent activity</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Links */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<button
|
||||
onClick={() => navigate('/admin/users')}
|
||||
className="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-shadow flex items-center justify-between"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-violet-100 rounded-lg">
|
||||
<Users className="w-5 h-5 text-violet-600" />
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">Manage Users</span>
|
||||
</div>
|
||||
<ChevronRight className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => navigate('/admin/activity')}
|
||||
className="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-shadow flex items-center justify-between"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-blue-100 rounded-lg">
|
||||
<Activity className="w-5 h-5 text-blue-600" />
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">Activity Stream</span>
|
||||
</div>
|
||||
<ChevronRight className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => navigate('/admin/stats')}
|
||||
className="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-shadow flex items-center justify-between"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-green-100 rounded-lg">
|
||||
<TrendingUp className="w-5 h-5 text-green-600" />
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">Full Statistics</span>
|
||||
</div>
|
||||
<ChevronRight className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminOverview;
|
||||
@ -1,374 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Settings, AlertTriangle, RefreshCw, Save, Clock, Info } from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const AdminSettings = () => {
|
||||
// State
|
||||
const [settings, setSettings] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [saveError, setSaveError] = useState(null);
|
||||
const [saveSuccess, setSaveSuccess] = useState(false);
|
||||
const [apiVersion, setApiVersion] = useState(null);
|
||||
|
||||
// Form state
|
||||
const [retentionDays, setRetentionDays] = useState(90);
|
||||
const [originalRetentionDays, setOriginalRetentionDays] = useState(90);
|
||||
|
||||
// Warning dialog state
|
||||
const [showWarningDialog, setShowWarningDialog] = useState(false);
|
||||
|
||||
// Validation
|
||||
const MIN_RETENTION = 30;
|
||||
const MAX_RETENTION = 365;
|
||||
|
||||
const isValidRetention = retentionDays >= MIN_RETENTION && retentionDays <= MAX_RETENTION;
|
||||
const hasChanges = retentionDays !== originalRetentionDays;
|
||||
const isReducingRetention = retentionDays < originalRetentionDays;
|
||||
|
||||
// Fetch settings
|
||||
const fetchSettings = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/settings`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch settings');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setSettings(data);
|
||||
setRetentionDays(data.activityRetentionDays || 90);
|
||||
setOriginalRetentionDays(data.activityRetentionDays || 90);
|
||||
} catch (err) {
|
||||
console.error('Error fetching settings:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch API version from health endpoint
|
||||
useEffect(() => {
|
||||
fetch(`${API_BASE}/health`)
|
||||
.then(res => res.json())
|
||||
.then(data => setApiVersion(data.version || 'unknown'))
|
||||
.catch(() => setApiVersion('unavailable'));
|
||||
}, []);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
}, [fetchSettings]);
|
||||
|
||||
// Clear success message after 3 seconds
|
||||
useEffect(() => {
|
||||
if (saveSuccess) {
|
||||
const timer = setTimeout(() => setSaveSuccess(false), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [saveSuccess]);
|
||||
|
||||
// Handle save
|
||||
const handleSave = async () => {
|
||||
// If reducing retention, show warning first
|
||||
if (isReducingRetention && !showWarningDialog) {
|
||||
setShowWarningDialog(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/settings`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
activityRetentionDays: retentionDays
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to save settings');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setSettings(data.settings);
|
||||
setOriginalRetentionDays(retentionDays);
|
||||
setSaveSuccess(true);
|
||||
setShowWarningDialog(false);
|
||||
} catch (err) {
|
||||
console.error('Error saving settings:', err);
|
||||
setSaveError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle confirm from warning dialog
|
||||
const handleConfirmChange = () => {
|
||||
handleSave();
|
||||
};
|
||||
|
||||
// Handle cancel from warning dialog
|
||||
const handleCancelChange = () => {
|
||||
setShowWarningDialog(false);
|
||||
};
|
||||
|
||||
// Reset to original value
|
||||
const handleReset = () => {
|
||||
setRetentionDays(originalRetentionDays);
|
||||
setSaveError(null);
|
||||
};
|
||||
|
||||
// Skeleton loader
|
||||
const SettingsSkeleton = () => (
|
||||
<div className="space-y-6 animate-pulse">
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="h-6 bg-gray-200 rounded w-48 mb-4"></div>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="h-4 bg-gray-200 rounded w-32 mb-2"></div>
|
||||
<div className="h-10 bg-gray-200 rounded w-24"></div>
|
||||
</div>
|
||||
<div className="h-4 bg-gray-200 rounded w-full max-w-md"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-3/4 max-w-md"></div>
|
||||
<div className="h-10 bg-gray-200 rounded w-32 mt-4"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchSettings}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Admin Settings</h1>
|
||||
<p className="text-gray-600">
|
||||
Configure application settings and data retention policies
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchSettings}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Settings Content */}
|
||||
{loading ? (
|
||||
<SettingsSkeleton />
|
||||
) : (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center space-x-2 mb-6">
|
||||
<Clock className="w-5 h-5 text-violet-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Activity Log Retention</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 max-w-lg">
|
||||
{/* Retention Period Input */}
|
||||
<div>
|
||||
<label htmlFor="retention-days" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Retention Period (days)
|
||||
</label>
|
||||
<div className="flex items-center space-x-3">
|
||||
<input
|
||||
id="retention-days"
|
||||
type="number"
|
||||
min={MIN_RETENTION}
|
||||
max={MAX_RETENTION}
|
||||
value={retentionDays}
|
||||
onChange={(e) => {
|
||||
const value = parseInt(e.target.value, 10);
|
||||
if (!isNaN(value)) {
|
||||
setRetentionDays(value);
|
||||
}
|
||||
}}
|
||||
className={`w-24 px-3 py-2 border rounded-md focus:ring-2 focus:ring-violet-500 focus:border-violet-500 ${
|
||||
!isValidRetention ? 'border-red-500' : 'border-gray-300'
|
||||
}`}
|
||||
/>
|
||||
<span className="text-sm text-gray-500">
|
||||
({MIN_RETENTION}-{MAX_RETENTION} days)
|
||||
</span>
|
||||
</div>
|
||||
{!isValidRetention && (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
Retention period must be between {MIN_RETENTION} and {MAX_RETENTION} days
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-sm text-gray-600">
|
||||
Activity logs older than this will be automatically deleted. This helps manage database size while maintaining an audit trail for recent activity.
|
||||
</p>
|
||||
|
||||
{/* Current Setting Info */}
|
||||
{settings && (
|
||||
<div className="bg-gray-50 rounded-md p-3">
|
||||
<p className="text-sm text-gray-600">
|
||||
<span className="font-medium">Current setting:</span> {originalRetentionDays} days
|
||||
</p>
|
||||
{settings.activityLogLevel && (
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
<span className="font-medium">Log level:</span> {settings.activityLogLevel}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Save Error */}
|
||||
{saveError && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-md p-3">
|
||||
<p className="text-sm text-red-700">Error: {saveError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success Message */}
|
||||
{saveSuccess && (
|
||||
<div className="bg-green-50 border border-green-200 rounded-md p-3">
|
||||
<p className="text-sm text-green-700">Settings saved successfully</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center space-x-3 pt-2">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || !isValidRetention || saving}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span>Saving...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="w-4 h-4" />
|
||||
<span>Save Changes</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{hasChanges && (
|
||||
<button
|
||||
onClick={handleReset}
|
||||
disabled={saving}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* System Information */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center space-x-2 mb-6">
|
||||
<Info className="w-5 h-5 text-violet-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">System Information</h2>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-lg">
|
||||
<div className="bg-gray-50 rounded-md p-3">
|
||||
<p className="text-sm text-gray-500">Frontend Version</p>
|
||||
<p className="text-lg font-semibold text-gray-900">{__APP_VERSION__}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-md p-3">
|
||||
<p className="text-sm text-gray-500">API Version</p>
|
||||
<p className="text-lg font-semibold text-gray-900">{apiVersion ?? '...'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Warning Dialog */}
|
||||
{showWarningDialog && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<div className="flex items-start space-x-3 mb-4">
|
||||
<div className="flex-shrink-0">
|
||||
<AlertTriangle className="w-6 h-6 text-amber-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-gray-900">
|
||||
Warning: Reducing Retention Period
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 mb-6">
|
||||
<p className="text-gray-600">
|
||||
Reducing the retention period from{' '}
|
||||
<span className="font-semibold">{originalRetentionDays} days</span> to{' '}
|
||||
<span className="font-semibold">{retentionDays} days</span> will permanently delete
|
||||
activity logs older than {retentionDays} days.
|
||||
</p>
|
||||
<p className="text-red-600 font-medium">
|
||||
This action cannot be undone.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={handleCancelChange}
|
||||
disabled={saving}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirmChange}
|
||||
disabled={saving}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-amber-600 text-white rounded-md hover:bg-amber-700 disabled:opacity-50"
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span>Saving...</span>
|
||||
</>
|
||||
) : (
|
||||
<span>Confirm Change</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminSettings;
|
||||
@ -1,416 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Play, RefreshCw, Clock, CheckCircle, XCircle, AlertTriangle } from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const ScraperManagement = () => {
|
||||
const [status, setStatus] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [triggering, setTriggering] = useState(false);
|
||||
const [dryRun, setDryRun] = useState(false);
|
||||
const [triggerResult, setTriggerResult] = useState(null);
|
||||
const [history, setHistory] = useState([]);
|
||||
const [historyLoading, setHistoryLoading] = useState(true);
|
||||
|
||||
const fetchStatus = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/scraper/status`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch scraper status');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setStatus(data);
|
||||
} catch (err) {
|
||||
console.error('Error fetching scraper status:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchHistory = useCallback(async () => {
|
||||
setHistoryLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/scraper/history`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch scraper history');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setHistory(data.data || []);
|
||||
} catch (err) {
|
||||
console.error('Error fetching scraper history:', err);
|
||||
} finally {
|
||||
setHistoryLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
fetchHistory();
|
||||
}, [fetchStatus, fetchHistory]);
|
||||
|
||||
// Auto-clear trigger result after 5 seconds
|
||||
useEffect(() => {
|
||||
if (triggerResult) {
|
||||
const timer = setTimeout(() => setTriggerResult(null), 5000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [triggerResult]);
|
||||
|
||||
const handleRunScraper = async () => {
|
||||
setTriggering(true);
|
||||
setTriggerResult(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/scraper/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ dryRun })
|
||||
});
|
||||
|
||||
if (response.status === 409) {
|
||||
setTriggerResult({ type: 'error', message: 'Scraper is already running' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to trigger scraper');
|
||||
}
|
||||
|
||||
setTriggerResult({ type: 'success', message: `Scraper ${dryRun ? '(dry run) ' : ''}started successfully` });
|
||||
// Re-fetch status and history after triggering
|
||||
await Promise.all([fetchStatus(), fetchHistory()]);
|
||||
} catch (err) {
|
||||
console.error('Error triggering scraper:', err);
|
||||
setTriggerResult({ type: 'error', message: err.message });
|
||||
} finally {
|
||||
setTriggering(false);
|
||||
}
|
||||
};
|
||||
|
||||
const isRunning = status?.currentStatus === 'running';
|
||||
|
||||
const formatDuration = (ms) => {
|
||||
if (!ms) return 'N/A';
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const remainingSeconds = seconds % 60;
|
||||
return `${minutes}m ${remainingSeconds}s`;
|
||||
};
|
||||
|
||||
const formatDate = (dateStr) => {
|
||||
if (!dateStr) return 'N/A';
|
||||
return new Date(dateStr).toLocaleString();
|
||||
};
|
||||
|
||||
// Skeleton loader
|
||||
const StatusSkeleton = () => (
|
||||
<div className="space-y-6 animate-pulse">
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="h-6 bg-gray-200 rounded w-48 mb-4"></div>
|
||||
<div className="space-y-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-32"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-full max-w-md"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-3/4 max-w-md"></div>
|
||||
<div className="h-10 bg-gray-200 rounded w-32 mt-4"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (error && !status) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Scraper Management</h1>
|
||||
<p className="text-gray-600">Trigger and monitor apartment data scrapes</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={() => { fetchStatus(); fetchHistory(); }}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Scraper Management</h1>
|
||||
<p className="text-gray-600">Trigger and monitor apartment data scrapes</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => { fetchStatus(); fetchHistory(); }}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Status Card */}
|
||||
{loading && !status ? (
|
||||
<StatusSkeleton />
|
||||
) : (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
{/* Current Status */}
|
||||
<div className="flex items-center space-x-3 mb-6">
|
||||
<span className="text-lg font-semibold text-gray-900">Status:</span>
|
||||
{isRunning ? (
|
||||
<span className="inline-flex items-center space-x-1.5 px-3 py-1 rounded-full text-sm font-medium bg-amber-100 text-amber-800">
|
||||
<RefreshCw className="w-3.5 h-3.5 animate-spin" />
|
||||
<span>Running</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center space-x-1.5 px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
|
||||
<CheckCircle className="w-3.5 h-3.5" />
|
||||
<span>Idle</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Last Run Summary */}
|
||||
{status?.lastRun && (
|
||||
<div className="mb-6">
|
||||
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-3">Last Run</h3>
|
||||
<div className="bg-gray-50 rounded-md p-4 space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Clock className="w-4 h-4 text-gray-500" />
|
||||
<span className="text-sm text-gray-600">{formatDate(status.lastRun.timestamp)}</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
{status.lastRun.status === 'success' ? (
|
||||
<CheckCircle className="w-4 h-4 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="w-4 h-4 text-red-500" />
|
||||
)}
|
||||
<span className={`text-sm font-medium ${status.lastRun.status === 'success' ? 'text-green-700' : 'text-red-700'}`}>
|
||||
{status.lastRun.status === 'success' ? 'Success' : 'Error'}
|
||||
</span>
|
||||
</div>
|
||||
{status.lastRun.duration != null && (
|
||||
<div className="text-sm text-gray-600">
|
||||
<span className="font-medium">Duration:</span> {formatDuration(status.lastRun.duration)}
|
||||
</div>
|
||||
)}
|
||||
{status.lastRun.unitsProcessed != null && (
|
||||
<div className="text-sm text-gray-600">
|
||||
<span className="font-medium">Units processed:</span> {status.lastRun.unitsProcessed}
|
||||
</div>
|
||||
)}
|
||||
{status.lastRun.pricesInserted != null && (
|
||||
<div className="text-sm text-gray-600">
|
||||
<span className="font-medium">Prices inserted:</span> {status.lastRun.pricesInserted}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Schedule Info */}
|
||||
{(status?.schedule || status?.nextScheduledRun) && (
|
||||
<div className="mb-6">
|
||||
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-3">Schedule</h3>
|
||||
<div className="bg-gray-50 rounded-md p-4 space-y-2">
|
||||
{status.schedule && (
|
||||
<div className="text-sm text-gray-600">
|
||||
<span className="font-medium">Cron:</span>{' '}
|
||||
<code className="bg-gray-200 px-1.5 py-0.5 rounded text-xs">{status.schedule}</code>
|
||||
</div>
|
||||
)}
|
||||
{status.nextScheduledRun && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Clock className="w-4 h-4 text-gray-500" />
|
||||
<span className="text-sm text-gray-600">
|
||||
<span className="font-medium">Next run:</span> {formatDate(status.nextScheduledRun)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Divider */}
|
||||
<hr className="my-6 border-gray-200" />
|
||||
|
||||
{/* Run Controls */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wide">Run Controls</h3>
|
||||
|
||||
<div className="flex items-center space-x-4">
|
||||
<button
|
||||
onClick={handleRunScraper}
|
||||
disabled={triggering || isRunning}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{triggering ? (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span>Starting...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="w-4 h-4" />
|
||||
<span>Run Scraper</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<label className="flex items-center space-x-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={dryRun}
|
||||
onChange={(e) => setDryRun(e.target.checked)}
|
||||
className="w-4 h-4 text-violet-600 border-gray-300 rounded focus:ring-violet-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-700">Dry run</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Trigger Result Message */}
|
||||
{triggerResult && (
|
||||
<div className={`flex items-center space-x-2 p-3 rounded-md border ${
|
||||
triggerResult.type === 'success'
|
||||
? 'bg-green-50 border-green-200'
|
||||
: 'bg-red-50 border-red-200'
|
||||
}`}>
|
||||
{triggerResult.type === 'success' ? (
|
||||
<CheckCircle className="w-4 h-4 text-green-600 flex-shrink-0" />
|
||||
) : (
|
||||
<AlertTriangle className="w-4 h-4 text-red-600 flex-shrink-0" />
|
||||
)}
|
||||
<span className={`text-sm ${
|
||||
triggerResult.type === 'success' ? 'text-green-700' : 'text-red-700'
|
||||
}`}>
|
||||
{triggerResult.message}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Run History */}
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-gray-200">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Run History</h2>
|
||||
</div>
|
||||
|
||||
{historyLoading && history.length === 0 ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Time</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Status</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Trigger</th>
|
||||
<th className="text-right py-3 px-4 font-semibold text-gray-700">Duration</th>
|
||||
<th className="text-right py-3 px-4 font-semibold text-gray-700">Units</th>
|
||||
<th className="text-right py-3 px-4 font-semibold text-gray-700">Prices</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Dry Run</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...Array(5)].map((_, index) => (
|
||||
<tr key={index} className={`border-b ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}`}>
|
||||
<td className="py-3 px-4"><div className="h-4 bg-gray-200 rounded w-36 animate-pulse"></div></td>
|
||||
<td className="py-3 px-4 text-center"><div className="h-5 bg-gray-200 rounded-full w-16 mx-auto animate-pulse"></div></td>
|
||||
<td className="py-3 px-4 text-center"><div className="h-4 bg-gray-200 rounded w-16 mx-auto animate-pulse"></div></td>
|
||||
<td className="py-3 px-4"><div className="h-4 bg-gray-200 rounded w-14 ml-auto animate-pulse"></div></td>
|
||||
<td className="py-3 px-4"><div className="h-4 bg-gray-200 rounded w-10 ml-auto animate-pulse"></div></td>
|
||||
<td className="py-3 px-4"><div className="h-4 bg-gray-200 rounded w-10 ml-auto animate-pulse"></div></td>
|
||||
<td className="py-3 px-4 text-center"><div className="h-4 bg-gray-200 rounded w-8 mx-auto animate-pulse"></div></td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : history.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<Clock className="w-12 h-12 text-gray-400 mx-auto mb-3" />
|
||||
<p className="text-gray-600">No scraper runs recorded yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Time</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Status</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Trigger</th>
|
||||
<th className="text-right py-3 px-4 font-semibold text-gray-700">Duration</th>
|
||||
<th className="text-right py-3 px-4 font-semibold text-gray-700">Units</th>
|
||||
<th className="text-right py-3 px-4 font-semibold text-gray-700">Prices</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Dry Run</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{history.map((run, index) => (
|
||||
<tr key={run._id || index} className={`border-b ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}`}>
|
||||
<td className="py-3 px-4 text-sm text-gray-600">
|
||||
{formatDate(run.startedAt)}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
run.status === 'success'
|
||||
? 'bg-green-100 text-green-800'
|
||||
: run.status === 'running'
|
||||
? 'bg-amber-100 text-amber-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}>
|
||||
{run.status === 'success' ? 'Success' : run.status === 'running' ? 'Running' : 'Failed'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center text-sm text-gray-600 capitalize">
|
||||
{run.trigger || 'N/A'}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-right text-sm text-gray-600">
|
||||
{formatDuration(run.duration)}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-right text-sm text-gray-600">
|
||||
{run.unitsProcessed ?? '-'}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-right text-sm text-gray-600">
|
||||
{run.pricesInserted ?? '-'}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center text-sm text-gray-600">
|
||||
{run.dryRun ? 'Yes' : 'No'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ScraperManagement;
|
||||
@ -1,671 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
BarChart,
|
||||
Bar,
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Legend
|
||||
} from 'recharts';
|
||||
import {
|
||||
TrendingUp,
|
||||
RefreshCw,
|
||||
ArrowLeft,
|
||||
Calendar,
|
||||
Activity,
|
||||
Clock,
|
||||
Users
|
||||
} from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
// Colors for charts
|
||||
const CHART_COLORS = ['#7c3aed', '#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#6366f1', '#ec4899'];
|
||||
|
||||
// Heatmap color scale (light to dark violet)
|
||||
const HEATMAP_COLORS = [
|
||||
'#f5f3ff', // 0 - lightest
|
||||
'#ede9fe', // 1
|
||||
'#ddd6fe', // 2
|
||||
'#c4b5fd', // 3
|
||||
'#a78bfa', // 4
|
||||
'#8b5cf6', // 5
|
||||
'#7c3aed', // 6
|
||||
'#6d28d9', // 7
|
||||
'#5b21b6', // 8
|
||||
'#4c1d95' // 9 - darkest
|
||||
];
|
||||
|
||||
// Day names for heatmap
|
||||
const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
|
||||
const UsageStats = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [activeUsersData, setActiveUsersData] = useState([]);
|
||||
const [actionsData, setActionsData] = useState([]);
|
||||
const [peakTimesData, setPeakTimesData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Period toggle for active users chart
|
||||
const [period, setPeriod] = useState('daily');
|
||||
const [days, setDays] = useState(30);
|
||||
|
||||
// Date range for actions
|
||||
const [actionStartDate, setActionStartDate] = useState(() => {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - 30);
|
||||
return date.toISOString().split('T')[0];
|
||||
});
|
||||
const [actionEndDate, setActionEndDate] = useState(() => {
|
||||
return new Date().toISOString().split('T')[0];
|
||||
});
|
||||
|
||||
// Fetch active users data
|
||||
const fetchActiveUsers = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${API_BASE}/admin/stats/active-users?period=${period}&days=${days}`,
|
||||
{ credentials: 'include' }
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch active users data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// Sort by date ascending for chart display
|
||||
const sortedData = (data.data || []).sort((a, b) =>
|
||||
new Date(a.date) - new Date(b.date)
|
||||
);
|
||||
setActiveUsersData(sortedData);
|
||||
} catch (err) {
|
||||
console.error('Error fetching active users:', err);
|
||||
throw err;
|
||||
}
|
||||
}, [period, days]);
|
||||
|
||||
// Fetch actions breakdown
|
||||
const fetchActions = useCallback(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (actionStartDate) {
|
||||
params.append('startDate', new Date(actionStartDate).toISOString());
|
||||
}
|
||||
if (actionEndDate) {
|
||||
const end = new Date(actionEndDate);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
params.append('endDate', end.toISOString());
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`${API_BASE}/admin/stats/actions?${params}`,
|
||||
{ credentials: 'include' }
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch actions data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setActionsData(data.data?.actions || []);
|
||||
} catch (err) {
|
||||
console.error('Error fetching actions:', err);
|
||||
throw err;
|
||||
}
|
||||
}, [actionStartDate, actionEndDate]);
|
||||
|
||||
// Fetch peak times
|
||||
const fetchPeakTimes = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/stats/peak-times`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch peak times data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setPeakTimesData(data.data);
|
||||
} catch (err) {
|
||||
console.error('Error fetching peak times:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch all data
|
||||
const fetchAllData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await Promise.all([
|
||||
fetchActiveUsers(),
|
||||
fetchActions(),
|
||||
fetchPeakTimes()
|
||||
]);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [fetchActiveUsers, fetchActions, fetchPeakTimes]);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchAllData();
|
||||
}, [fetchAllData]);
|
||||
|
||||
// Re-fetch active users when period changes
|
||||
useEffect(() => {
|
||||
fetchActiveUsers();
|
||||
}, [fetchActiveUsers]);
|
||||
|
||||
// Re-fetch actions when date range changes
|
||||
useEffect(() => {
|
||||
fetchActions();
|
||||
}, [fetchActions]);
|
||||
|
||||
// Format date for chart
|
||||
const formatChartDate = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
const date = new Date(dateStr);
|
||||
|
||||
if (period === 'monthly') {
|
||||
return date.toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
|
||||
} else if (period === 'weekly') {
|
||||
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
}
|
||||
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
};
|
||||
|
||||
// Format hour for display
|
||||
const formatHour = (hour) => {
|
||||
if (hour === 0) return '12am';
|
||||
if (hour === 12) return '12pm';
|
||||
return hour < 12 ? `${hour}am` : `${hour - 12}pm`;
|
||||
};
|
||||
|
||||
// Get color for heatmap cell based on value
|
||||
const getHeatmapColor = (value, maxValue) => {
|
||||
if (!value || maxValue === 0) return HEATMAP_COLORS[0];
|
||||
const intensity = Math.min(Math.floor((value / maxValue) * 10), 9);
|
||||
return HEATMAP_COLORS[intensity];
|
||||
};
|
||||
|
||||
// Build heatmap data (24 hours x 7 days)
|
||||
const buildHeatmapData = () => {
|
||||
if (!peakTimesData?.hourly || !peakTimesData?.daily) return null;
|
||||
|
||||
// Find max value for color scaling
|
||||
const hourlyMax = Math.max(...peakTimesData.hourly.map(h => h.avgActivity || 0));
|
||||
const dailyMax = Math.max(...peakTimesData.daily.map(d => d.avgActivity || 0));
|
||||
const maxValue = Math.max(hourlyMax, dailyMax);
|
||||
|
||||
// Create a simple heatmap structure
|
||||
// For now, we'll show hourly distribution across the week
|
||||
// The backend returns separate hourly and daily averages
|
||||
return {
|
||||
hourly: peakTimesData.hourly,
|
||||
daily: peakTimesData.daily,
|
||||
maxValue
|
||||
};
|
||||
};
|
||||
|
||||
const heatmapData = buildHeatmapData();
|
||||
|
||||
// Custom tooltip for pie chart
|
||||
const CustomPieTooltip = ({ active, payload }) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0];
|
||||
const total = actionsData.reduce((sum, d) => sum + (d.count || 0), 0);
|
||||
const percentage = total > 0 ? ((data.value / total) * 100).toFixed(1) : 0;
|
||||
return (
|
||||
<div className="bg-white p-3 border rounded-lg shadow-lg">
|
||||
<p className="font-medium">{data.payload.action}</p>
|
||||
<p className="text-sm text-gray-600">{data.value.toLocaleString()} ({percentage}%)</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<button
|
||||
onClick={() => navigate('/admin')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Dashboard
|
||||
</button>
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<button
|
||||
onClick={() => navigate('/admin')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700 mb-2"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Dashboard
|
||||
</button>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Usage Statistics</h1>
|
||||
<p className="text-gray-600">Detailed analytics and usage patterns</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Active Users Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 mb-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<TrendingUp className="w-5 h-5 text-violet-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Active Users Over Time</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
{/* Period Toggle */}
|
||||
<div className="flex items-center space-x-1 bg-gray-100 rounded-lg p-1">
|
||||
{['daily', 'weekly', 'monthly'].map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => {
|
||||
setPeriod(p);
|
||||
// Adjust days based on period
|
||||
if (p === 'daily') setDays(30);
|
||||
else if (p === 'weekly') setDays(12);
|
||||
else setDays(12);
|
||||
}}
|
||||
className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
|
||||
period === p
|
||||
? 'bg-white text-violet-600 shadow-sm'
|
||||
: 'text-gray-600 hover:text-gray-900'
|
||||
}`}
|
||||
>
|
||||
{p.charAt(0).toUpperCase() + p.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Days selector */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Calendar className="w-4 h-4 text-gray-500" />
|
||||
<select
|
||||
value={days}
|
||||
onChange={(e) => setDays(parseInt(e.target.value))}
|
||||
className="border border-gray-300 rounded-md px-2 py-1 text-sm focus:ring-2 focus:ring-violet-500"
|
||||
>
|
||||
<option value={7}>Last 7 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
<option value={14}>Last 14 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
<option value={30}>Last 30 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
<option value={90}>Last 90 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Chart Skeleton */
|
||||
<div className="h-80 animate-pulse">
|
||||
<div className="flex items-end h-64 space-x-2 px-8">
|
||||
{[...Array(12)].map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-1 bg-gray-200 rounded-t"
|
||||
style={{ height: `${Math.random() * 60 + 20}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex justify-between mt-4 px-8">
|
||||
{[...Array(6)].map((_, i) => (
|
||||
<div key={i} className="h-3 bg-gray-200 rounded w-12" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : activeUsersData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={320}>
|
||||
<LineChart data={activeUsersData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={formatChartDate}
|
||||
tick={{ fontSize: 12 }}
|
||||
interval="preserveStartEnd"
|
||||
/>
|
||||
<YAxis
|
||||
allowDecimals={false}
|
||||
tick={{ fontSize: 12 }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => [value, 'Active Users']}
|
||||
labelFormatter={formatChartDate}
|
||||
/>
|
||||
<Legend />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="count"
|
||||
name="Active Users"
|
||||
stroke="#7c3aed"
|
||||
strokeWidth={2}
|
||||
dot={{ fill: '#7c3aed', strokeWidth: 2, r: 3 }}
|
||||
activeDot={{ r: 6 }}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-80 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Users className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No active user data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action Breakdown Section */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Pie Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 mb-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Activity className="w-5 h-5 text-blue-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Action Breakdown</h2>
|
||||
</div>
|
||||
|
||||
{/* Date Range */}
|
||||
<div className="flex items-center space-x-2 text-sm">
|
||||
<input
|
||||
type="date"
|
||||
value={actionStartDate}
|
||||
onChange={(e) => setActionStartDate(e.target.value)}
|
||||
className="border border-gray-300 rounded-md px-2 py-1 focus:ring-2 focus:ring-violet-500"
|
||||
/>
|
||||
<span className="text-gray-500">to</span>
|
||||
<input
|
||||
type="date"
|
||||
value={actionEndDate}
|
||||
onChange={(e) => setActionEndDate(e.target.value)}
|
||||
className="border border-gray-300 rounded-md px-2 py-1 focus:ring-2 focus:ring-violet-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Pie Chart Skeleton */
|
||||
<div className="h-64 flex items-center justify-center animate-pulse">
|
||||
<div className="w-48 h-48 rounded-full bg-gray-200 relative">
|
||||
<div className="absolute inset-4 rounded-full bg-white"></div>
|
||||
</div>
|
||||
</div>
|
||||
) : actionsData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={280}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={actionsData}
|
||||
dataKey="count"
|
||||
nameKey="action"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={100}
|
||||
label={({ action, percent }) =>
|
||||
`${action} (${(percent * 100).toFixed(0)}%)`
|
||||
}
|
||||
labelLine={{ stroke: '#64748b', strokeWidth: 1 }}
|
||||
>
|
||||
{actionsData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={CHART_COLORS[index % CHART_COLORS.length]}
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip content={<CustomPieTooltip />} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Activity className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No action data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bar Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center space-x-2 mb-4">
|
||||
<Activity className="w-5 h-5 text-green-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Actions by Type</h2>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Bar Chart Skeleton */
|
||||
<div className="h-64 space-y-3 py-4 animate-pulse">
|
||||
{[...Array(5)].map((_, i) => (
|
||||
<div key={i} className="flex items-center space-x-3">
|
||||
<div className="h-4 bg-gray-200 rounded w-20" />
|
||||
<div
|
||||
className="h-6 bg-gray-200 rounded"
|
||||
style={{ width: `${Math.random() * 50 + 20}%` }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : actionsData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={280}>
|
||||
<BarChart data={actionsData} layout="vertical">
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis type="number" tick={{ fontSize: 12 }} />
|
||||
<YAxis
|
||||
type="category"
|
||||
dataKey="action"
|
||||
tick={{ fontSize: 12 }}
|
||||
width={100}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => [value.toLocaleString(), 'Count']}
|
||||
/>
|
||||
<Bar dataKey="count" radius={[0, 4, 4, 0]}>
|
||||
{actionsData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={CHART_COLORS[index % CHART_COLORS.length]}
|
||||
/>
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Activity className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No action data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Peak Times Heatmap */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center space-x-2 mb-4">
|
||||
<Clock className="w-5 h-5 text-orange-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Peak Usage Times</h2>
|
||||
<span className="text-sm text-gray-500">(Based on last 30 days)</span>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Heatmap Skeleton */
|
||||
<div className="space-y-6 animate-pulse">
|
||||
<div>
|
||||
<div className="h-4 bg-gray-200 rounded w-40 mb-3" />
|
||||
<div className="flex space-x-1">
|
||||
{[...Array(24)].map((_, i) => (
|
||||
<div key={i} className="w-6 h-16 bg-gray-200 rounded" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="h-4 bg-gray-200 rounded w-40 mb-3" />
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{[...Array(7)].map((_, i) => (
|
||||
<div key={i} className="h-16 bg-gray-200 rounded" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : heatmapData ? (
|
||||
<div className="space-y-6">
|
||||
{/* Hourly Distribution */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-700 mb-3">Hourly Activity Distribution</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<div className="inline-flex items-end space-x-1 min-w-full">
|
||||
{heatmapData.hourly.map((hourData, index) => {
|
||||
const height = heatmapData.maxValue > 0
|
||||
? Math.max(20, (hourData.avgActivity / heatmapData.maxValue) * 100)
|
||||
: 20;
|
||||
return (
|
||||
<div key={index} className="flex flex-col items-center">
|
||||
<div
|
||||
className="w-6 rounded-t transition-all duration-200 hover:opacity-80"
|
||||
style={{
|
||||
height: `${height}px`,
|
||||
backgroundColor: getHeatmapColor(hourData.avgActivity, heatmapData.maxValue)
|
||||
}}
|
||||
title={`${formatHour(hourData.hour)}: ${hourData.avgActivity?.toFixed(1) || 0} avg activities`}
|
||||
/>
|
||||
<span className="text-xs text-gray-500 mt-1">
|
||||
{index % 3 === 0 ? formatHour(hourData.hour) : ''}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Daily Distribution */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-700 mb-3">Daily Activity Distribution</h3>
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{heatmapData.daily.map((dayData, index) => {
|
||||
const dayIndex = DAY_NAMES.indexOf(dayData.day);
|
||||
const displayDay = dayIndex !== -1 ? DAY_NAMES[dayIndex] : dayData.day;
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="p-4 rounded-lg text-center transition-all duration-200 hover:opacity-80"
|
||||
style={{
|
||||
backgroundColor: getHeatmapColor(dayData.avgActivity, heatmapData.maxValue)
|
||||
}}
|
||||
title={`${displayDay}: ${dayData.avgActivity?.toFixed(1) || 0} avg activities`}
|
||||
>
|
||||
<p className="text-xs font-medium text-gray-700">{displayDay}</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{dayData.avgActivity?.toFixed(0) || 0}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Color Legend */}
|
||||
<div className="flex items-center justify-end space-x-2">
|
||||
<span className="text-xs text-gray-500">Less</span>
|
||||
<div className="flex space-x-0.5">
|
||||
{HEATMAP_COLORS.map((color, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="w-4 h-4 rounded-sm"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-xs text-gray-500">More</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Clock className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No peak times data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Summary Stats */}
|
||||
{actionsData.length > 0 && (
|
||||
<div className="bg-gray-100 rounded-lg p-4">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Total Actions</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{actionsData.reduce((sum, a) => sum + (a.count || 0), 0).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Most Common</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{actionsData.length > 0
|
||||
? actionsData.reduce((max, a) => a.count > max.count ? a : max, actionsData[0]).action
|
||||
: 'N/A'}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Action Types</p>
|
||||
<p className="text-lg font-bold text-gray-900">{actionsData.length}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Date Range</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{actionStartDate && actionEndDate
|
||||
? `${new Date(actionStartDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} - ${new Date(actionEndDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`
|
||||
: 'All time'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UsageStats;
|
||||
@ -1,480 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { ArrowLeft, Shield, ShieldOff, UserCheck, UserX, RefreshCw, AlertCircle, Clock, Activity } from 'lucide-react';
|
||||
import useAuth from '../../hooks/useAuth';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const UserDetail = () => {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
// State
|
||||
const [user, setUser] = useState(null);
|
||||
const [recentActivity, setRecentActivity] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [actionLoading, setActionLoading] = useState(false);
|
||||
|
||||
// Confirmation dialogs
|
||||
const [showStatusConfirm, setShowStatusConfirm] = useState(false);
|
||||
const [showRoleConfirm, setShowRoleConfirm] = useState(false);
|
||||
|
||||
// Check if viewing own profile
|
||||
const isOwnProfile = currentUser?._id === id;
|
||||
|
||||
// Fetch user details
|
||||
const fetchUser = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
throw new Error('Failed to fetch user details');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUser(data.data.user);
|
||||
setRecentActivity(data.data.recentActivity || []);
|
||||
} catch (err) {
|
||||
console.error('Error fetching user:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchUser();
|
||||
}, [fetchUser]);
|
||||
|
||||
// Toggle user status (enable/disable)
|
||||
const handleToggleStatus = async () => {
|
||||
setActionLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ isActive: !user.isActive })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to update user status');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUser(data.data.user);
|
||||
setShowStatusConfirm(false);
|
||||
} catch (err) {
|
||||
console.error('Error toggling status:', err);
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle user role (promote/demote)
|
||||
const handleToggleRole = async () => {
|
||||
setActionLoading(true);
|
||||
|
||||
try {
|
||||
const newRole = user.role === 'admin' ? 'user' : 'admin';
|
||||
const response = await fetch(`${API_BASE}/admin/users/${id}/role`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ role: newRole })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to update user role');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUser(data.data.user);
|
||||
setShowRoleConfirm(false);
|
||||
} catch (err) {
|
||||
console.error('Error toggling role:', err);
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Format date helper
|
||||
const formatDate = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
// Format datetime helper
|
||||
const formatDateTime = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
// Get activity action description
|
||||
const getActivityDescription = (activity) => {
|
||||
const actions = {
|
||||
'LOGIN': 'Logged in',
|
||||
'LOGOUT': 'Logged out',
|
||||
'PAGE_VIEW': `Viewed ${activity.metadata?.path || 'a page'}`,
|
||||
'API_CALL': `API call to ${activity.metadata?.endpoint || 'unknown'}`,
|
||||
'ADMIN_ENABLE_USER': 'Enabled a user',
|
||||
'ADMIN_DISABLE_USER': 'Disabled a user',
|
||||
'ADMIN_PROMOTE_USER': 'Promoted a user to admin',
|
||||
'ADMIN_DEMOTE_USER': 'Demoted a user from admin'
|
||||
};
|
||||
return actions[activity.action] || activity.action;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-6">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<RefreshCw className="w-8 h-8 animate-spin text-violet-600" />
|
||||
<span className="ml-3 text-gray-600">Loading user details...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<button
|
||||
onClick={() => navigate('/admin/users')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Users
|
||||
</button>
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<p className="text-red-700 mb-4">{error}</p>
|
||||
<button
|
||||
onClick={fetchUser}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Back Button */}
|
||||
<button
|
||||
onClick={() => navigate('/admin/users')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Users
|
||||
</button>
|
||||
|
||||
{/* User Profile Card */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
{user.picture ? (
|
||||
<img
|
||||
src={user.picture}
|
||||
alt={user.name}
|
||||
className="w-20 h-20 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-20 h-20 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-2xl font-medium text-gray-600">
|
||||
{user.name?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{user.name}</h1>
|
||||
<p className="text-gray-600">{user.email}</p>
|
||||
<div className="flex items-center space-x-2 mt-2">
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.role === 'admin'
|
||||
? 'bg-violet-100 text-violet-800'
|
||||
: 'bg-gray-100 text-gray-800'
|
||||
}`}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.isActive
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{user.isActive ? 'Active' : 'Disabled'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={fetchUser}
|
||||
className="p-2 text-gray-400 hover:text-gray-600"
|
||||
title="Refresh"
|
||||
>
|
||||
<RefreshCw className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* User Stats */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6 pt-6 border-t">
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Login Count</p>
|
||||
<p className="text-xl font-semibold">{user.loginCount || 0}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Created</p>
|
||||
<p className="text-lg font-medium">{formatDate(user.createdAt)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Last Login</p>
|
||||
<p className="text-lg font-medium">{formatDateTime(user.lastLoginAt)}</p>
|
||||
</div>
|
||||
{user.disabledAt && (
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Disabled At</p>
|
||||
<p className="text-lg font-medium text-red-600">{formatDateTime(user.disabledAt)}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Google ID (for debugging) */}
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<p className="text-sm text-gray-500">
|
||||
<span className="font-medium">Google ID:</span> {user.googleId}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions Card */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-lg font-semibold mb-4">Actions</h2>
|
||||
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{/* Enable/Disable Button */}
|
||||
<div className="relative group">
|
||||
<button
|
||||
onClick={() => setShowStatusConfirm(true)}
|
||||
disabled={isOwnProfile || actionLoading}
|
||||
className={`flex items-center space-x-2 px-4 py-2 rounded-md transition-colors ${
|
||||
user.isActive
|
||||
? 'bg-red-100 text-red-700 hover:bg-red-200'
|
||||
: 'bg-green-100 text-green-700 hover:bg-green-200'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
>
|
||||
{user.isActive ? (
|
||||
<>
|
||||
<UserX className="w-4 h-4" />
|
||||
<span>Disable User</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UserCheck className="w-4 h-4" />
|
||||
<span>Enable User</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{isOwnProfile && (
|
||||
<div className="absolute bottom-full left-0 mb-2 px-3 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
|
||||
You cannot disable your own account
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Promote/Demote Button */}
|
||||
<div className="relative group">
|
||||
<button
|
||||
onClick={() => setShowRoleConfirm(true)}
|
||||
disabled={isOwnProfile || actionLoading}
|
||||
className={`flex items-center space-x-2 px-4 py-2 rounded-md transition-colors ${
|
||||
user.role === 'admin'
|
||||
? 'bg-orange-100 text-orange-700 hover:bg-orange-200'
|
||||
: 'bg-violet-100 text-violet-700 hover:bg-violet-200'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
>
|
||||
{user.role === 'admin' ? (
|
||||
<>
|
||||
<ShieldOff className="w-4 h-4" />
|
||||
<span>Demote to User</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Promote to Admin</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{isOwnProfile && (
|
||||
<div className="absolute bottom-full left-0 mb-2 px-3 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
|
||||
You cannot demote yourself
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Activity */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-lg font-semibold mb-4 flex items-center">
|
||||
<Activity className="w-5 h-5 mr-2" />
|
||||
Recent Activity
|
||||
</h2>
|
||||
|
||||
{recentActivity.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
<Clock className="w-12 h-12 mx-auto mb-3 text-gray-300" />
|
||||
<p>No recent activity recorded</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{recentActivity.map((activity, index) => (
|
||||
<div
|
||||
key={activity._id || index}
|
||||
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">
|
||||
{getActivityDescription(activity)}
|
||||
</p>
|
||||
{activity.metadata?.ip && (
|
||||
<p className="text-sm text-gray-500">
|
||||
IP: {activity.metadata.ip}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm text-gray-500">
|
||||
{formatDateTime(activity.timestamp)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Confirmation Dialog */}
|
||||
{showStatusConfirm && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">
|
||||
{user.isActive ? 'Disable User' : 'Enable User'}
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-6">
|
||||
{user.isActive
|
||||
? `Are you sure you want to disable ${user.name}? They will no longer be able to access the application.`
|
||||
: `Are you sure you want to enable ${user.name}? They will be able to access the application again.`}
|
||||
</p>
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={() => setShowStatusConfirm(false)}
|
||||
disabled={actionLoading}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleToggleStatus}
|
||||
disabled={actionLoading}
|
||||
className={`px-4 py-2 rounded-md text-white disabled:opacity-50 ${
|
||||
user.isActive
|
||||
? 'bg-red-600 hover:bg-red-700'
|
||||
: 'bg-green-600 hover:bg-green-700'
|
||||
}`}
|
||||
>
|
||||
{actionLoading ? (
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
) : user.isActive ? (
|
||||
'Disable'
|
||||
) : (
|
||||
'Enable'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Role Confirmation Dialog */}
|
||||
{showRoleConfirm && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">
|
||||
{user.role === 'admin' ? 'Demote User' : 'Promote User'}
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-6">
|
||||
{user.role === 'admin'
|
||||
? `Are you sure you want to demote ${user.name} from admin? They will lose access to admin features.`
|
||||
: `Are you sure you want to promote ${user.name} to admin? They will have full administrative access.`}
|
||||
</p>
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={() => setShowRoleConfirm(false)}
|
||||
disabled={actionLoading}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleToggleRole}
|
||||
disabled={actionLoading}
|
||||
className={`px-4 py-2 rounded-md text-white disabled:opacity-50 ${
|
||||
user.role === 'admin'
|
||||
? 'bg-orange-600 hover:bg-orange-700'
|
||||
: 'bg-violet-600 hover:bg-violet-700'
|
||||
}`}
|
||||
>
|
||||
{actionLoading ? (
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
) : user.role === 'admin' ? (
|
||||
'Demote'
|
||||
) : (
|
||||
'Promote'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserDetail;
|
||||
@ -1,436 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Search, ChevronLeft, ChevronRight, Users, RefreshCw } from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const UserList = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Pagination
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [totalUsers, setTotalUsers] = useState(0);
|
||||
const limit = 20;
|
||||
|
||||
// Filters
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('all');
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortOrder, setSortOrder] = useState('desc');
|
||||
|
||||
// Debounce search input (300ms)
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedSearch(searchQuery);
|
||||
setPage(1); // Reset to first page on search
|
||||
}, 300);
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchQuery]);
|
||||
|
||||
// Fetch users
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
limit: limit.toString(),
|
||||
sortBy,
|
||||
sortOrder
|
||||
});
|
||||
|
||||
if (debouncedSearch) {
|
||||
params.append('search', debouncedSearch);
|
||||
}
|
||||
|
||||
if (statusFilter !== 'all') {
|
||||
params.append('status', statusFilter);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/admin/users?${params}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch users');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUsers(data.data.users);
|
||||
setTotalPages(data.data.pagination.totalPages);
|
||||
setTotalUsers(data.data.pagination.total);
|
||||
} catch (err) {
|
||||
console.error('Error fetching users:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, debouncedSearch, statusFilter, sortBy, sortOrder]);
|
||||
|
||||
// Fetch on mount and when dependencies change
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, [fetchUsers]);
|
||||
|
||||
// Handle row click
|
||||
const handleRowClick = (userId) => {
|
||||
navigate(`/admin/users/${userId}`);
|
||||
};
|
||||
|
||||
// Handle status filter change
|
||||
const handleStatusChange = (e) => {
|
||||
setStatusFilter(e.target.value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// Handle sort change
|
||||
const handleSortChange = (field) => {
|
||||
if (sortBy === field) {
|
||||
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
setSortBy(field);
|
||||
setSortOrder('desc');
|
||||
}
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// Format date helper
|
||||
const formatDate = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
// Format datetime helper
|
||||
const formatDateTime = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
// Sort indicator
|
||||
const SortIndicator = ({ field }) => {
|
||||
if (sortBy !== field) return null;
|
||||
return (
|
||||
<span className="ml-1">
|
||||
{sortOrder === 'asc' ? '\u2191' : '\u2193'}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-6">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchUsers}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">User Management</h1>
|
||||
<p className="text-gray-600">
|
||||
{totalUsers} total user{totalUsers !== 1 ? 's' : ''}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchUsers}
|
||||
disabled={loading}
|
||||
className="flex items-center justify-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50 w-full sm:w-auto"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-lg shadow-md p-4">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
{/* Search */}
|
||||
<div className="flex-1 min-w-[250px]">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by name or email..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Filter */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<label className="text-sm font-medium text-gray-700">Status:</label>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={handleStatusChange}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
>
|
||||
<option value="all">All</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="disabled">Disabled</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Users Table */}
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{loading && users.length === 0 ? (
|
||||
/* Skeleton Loader */
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">User</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Email</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Role</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Status</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Logins</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Last Login</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...Array(5)].map((_, index) => (
|
||||
<tr key={index} className={`border-b ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}`}>
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center space-x-3 animate-pulse">
|
||||
<div className="w-8 h-8 rounded-full bg-gray-200"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-24"></div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-40 animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<div className="h-5 bg-gray-200 rounded-full w-12 mx-auto animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<div className="h-5 bg-gray-200 rounded-full w-16 mx-auto animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<div className="h-4 bg-gray-200 rounded w-8 mx-auto animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-32 animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-24 animate-pulse"></div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : users.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<Users className="w-16 h-16 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">No Users Found</h3>
|
||||
<p className="text-gray-600">
|
||||
{debouncedSearch || statusFilter !== 'all'
|
||||
? 'No users found matching your search. Try adjusting your filters.'
|
||||
: 'No users have signed up yet.'}
|
||||
</p>
|
||||
{(debouncedSearch || statusFilter !== 'all') && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setSearchQuery('');
|
||||
setStatusFilter('all');
|
||||
setPage(1);
|
||||
}}
|
||||
className="mt-4 px-4 py-2 text-violet-600 hover:text-violet-700 hover:bg-violet-50 rounded-md"
|
||||
>
|
||||
Clear all filters
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">User</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Email</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('role')}
|
||||
>
|
||||
Role
|
||||
<SortIndicator field="role" />
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('isActive')}
|
||||
>
|
||||
Status
|
||||
<SortIndicator field="isActive" />
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('loginCount')}
|
||||
>
|
||||
Logins
|
||||
<SortIndicator field="loginCount" />
|
||||
</th>
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('lastLoginAt')}
|
||||
>
|
||||
Last Login
|
||||
<SortIndicator field="lastLoginAt" />
|
||||
</th>
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('createdAt')}
|
||||
>
|
||||
Created
|
||||
<SortIndicator field="createdAt" />
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user, index) => (
|
||||
<tr
|
||||
key={user._id}
|
||||
onClick={() => handleRowClick(user._id)}
|
||||
className={`border-b cursor-pointer transition-colors ${
|
||||
index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
|
||||
} hover:bg-violet-50`}
|
||||
>
|
||||
{/* Avatar + Name */}
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
{user.picture ? (
|
||||
<img
|
||||
src={user.picture}
|
||||
alt={user.name}
|
||||
className="w-8 h-8 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-sm font-medium text-gray-600">
|
||||
{user.name?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<span className="font-medium text-gray-900">{user.name}</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Email */}
|
||||
<td className="py-3 px-4 text-gray-600">{user.email}</td>
|
||||
|
||||
{/* Role */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.role === 'admin'
|
||||
? 'bg-violet-100 text-violet-800'
|
||||
: 'bg-gray-100 text-gray-800'
|
||||
}`}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Status */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.isActive
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{user.isActive ? 'Active' : 'Disabled'}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Login Count */}
|
||||
<td className="py-3 px-4 text-center text-gray-600">
|
||||
{user.loginCount || 0}
|
||||
</td>
|
||||
|
||||
{/* Last Login */}
|
||||
<td className="py-3 px-4 text-gray-600">
|
||||
{formatDateTime(user.lastLoginAt)}
|
||||
</td>
|
||||
|
||||
{/* Created */}
|
||||
<td className="py-3 px-4 text-gray-600">
|
||||
{formatDate(user.createdAt)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-col sm:flex-row items-center justify-between gap-3 px-4 py-3 bg-gray-50 border-t">
|
||||
<div className="text-sm text-gray-600 text-center sm:text-left">
|
||||
Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, totalUsers)} of {totalUsers} users
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={() => setPage(Math.max(1, page - 1))}
|
||||
disabled={page === 1 || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<span className="ml-1 hidden sm:inline">Previous</span>
|
||||
</button>
|
||||
<span className="px-3 py-1 text-sm">
|
||||
{page} / {totalPages}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setPage(Math.min(totalPages, page + 1))}
|
||||
disabled={page === totalPages || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<span className="mr-1 hidden sm:inline">Next</span>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserList;
|
||||
@ -1,13 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { readFileSync } from 'fs'
|
||||
|
||||
const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'))
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(pkg.version)
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user