Compare commits

..

5 Commits

Author SHA1 Message Date
9ed775e04a Implement Phase 2 activity monitoring frontend
- Add ActivityStream page with paginated activity list
- Add user, action type, and date range filters
- Implement auto-refresh every 30 seconds (pauses with filters)
- Add "New activity" indicator for real-time updates
- Add export modal with date range picker for CSV download
- Update admin navigation to dropdown with Users and Activity links
2026-01-22 13:01:49 -07:00
a05f99080c Implement Phase 1 admin dashboard frontend
- Add AdminRoute component for admin-only route protection
- Add admin navigation link (visible only to admins)
- Create UserList page with pagination, search, and filters
- Create UserDetail page with enable/disable and promote/demote
- Add confirmation dialogs for destructive actions
- Prevent self-modification (cannot disable/demote yourself)
- All admin routes protected with AdminRoute wrapper
2026-01-22 12:06:33 -07:00
d285429e25 Updates to units page 2026-01-22 11:59:17 -07:00
7b596a9d73 Add frontend authentication with Google OAuth
- Create AuthContext and AuthProvider for auth state management
- Create useAuth hook for easy access to auth state
- Create ProtectedRoute component to guard authenticated routes
- Create Login page with Google sign-in button and error handling
- Create useActivityTracker hook for frontend activity logging
- Update App.jsx to protect all routes and add user display/logout
- Update main.jsx to wrap app with AuthProvider
- Add credentials: 'include' to all API fetch calls
2026-01-21 18:00:22 -07:00
f33ef01a6d Add mobile-friendly sticky column to units list table 2026-01-21 15:08:55 -07:00
16 changed files with 242 additions and 2613 deletions

View File

@ -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..."

View File

@ -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

View File

@ -1,4 +0,0 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEBOFl4SHzoZVM59+668t2tecTyKM+
cE4zaOkbFO30u7d2+bjpwPnbYrTutKmAeehYzCAVW/OYea7ML0cW2YCSCQ==
-----END PUBLIC KEY-----

View File

@ -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

View File

@ -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
View File

@ -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"

View File

@ -1,7 +1,7 @@
{
"name": "apartment-dashboard",
"private": true,
"version": "1.1.0",
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",

View File

@ -9,10 +9,6 @@ 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';
const ApartmentDashboard = () => {
// Router
@ -23,7 +19,7 @@ const ApartmentDashboard = () => {
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,8 +27,6 @@ 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());
@ -61,10 +55,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);
@ -308,7 +302,7 @@ const ApartmentDashboard = () => {
return filtered;
};
const _toggleWatchUnit = (unitCode) => {
const toggleWatchUnit = (unitCode) => {
const newWatched = new Set(watchedUnits);
if (newWatched.has(unitCode)) {
newWatched.delete(unitCode);
@ -370,7 +364,6 @@ const ApartmentDashboard = () => {
if (location.pathname === '/analytics' && !analyticsData) {
fetchAnalytics();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.pathname]);
// Calculate insights from available data
@ -420,19 +413,7 @@ const ApartmentDashboard = () => {
const price = unit.currentPrice || 0;
const matchesPrice = price >= priceFilter.min && (priceFilter.max === 10000 || price <= 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) {
@ -445,14 +426,13 @@ const ApartmentDashboard = () => {
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 'delta': return dir * (((a.maxPrice || 0) - (a.minPrice || 0)) - ((b.maxPrice || 0) - (b.minPrice || 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 +448,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>
@ -592,12 +572,6 @@ const ApartmentDashboard = () => {
<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'}`}
@ -610,24 +584,6 @@ const ApartmentDashboard = () => {
>
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>
)}
@ -721,7 +677,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 +697,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 +739,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>
@ -828,25 +784,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) => {
@ -1124,25 +1061,7 @@ const ApartmentDashboard = () => {
{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.delta && <td className="py-3 px-4 text-right text-gray-600">{formatPrice((unit.maxPrice || 0) - (unit.minPrice || 0))}</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 text-center">
@ -1382,11 +1301,6 @@ const ApartmentDashboard = () => {
} />
{/* Admin Routes */}
<Route path="/admin" element={
<AdminRoute>
<AdminOverview />
</AdminRoute>
} />
<Route path="/admin/users" element={
<AdminRoute>
<UserList />
@ -1402,21 +1316,6 @@ const ApartmentDashboard = () => {
<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 */}
<Route path="*" element={<Navigate to="/" replace />} />
@ -1540,7 +1439,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'} />

View File

@ -1,8 +1,7 @@
import { createContext, useState, useEffect, useCallback } from 'react';
import React, { 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 }) => {

View File

@ -136,7 +136,7 @@ const ActivityStream = () => {
}
const data = await response.json();
const newActivities = data.data?.activities || [];
const newActivities = data.activities || [];
// Check for new activities (for indicator)
if (isBackgroundRefresh && newActivities.length > 0 && lastActivityId) {
@ -157,8 +157,8 @@ const ActivityStream = () => {
}
}
setTotalPages(data.data?.pagination?.pages || 1);
setTotalActivities(data.data?.pagination?.total || 0);
setTotalPages(data.pagination?.pages || 1);
setTotalActivities(data.pagination?.total || 0);
} catch (err) {
console.error('Error fetching activities:', err);
if (!isBackgroundRefresh) {
@ -387,7 +387,7 @@ const ActivityStream = () => {
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Activity Stream</h1>
<p className="text-gray-600">
@ -402,7 +402,7 @@ const ActivityStream = () => {
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>
<span>Export</span>
</button>
{/* Refresh Button */}
@ -412,7 +412,7 @@ const ActivityStream = () => {
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>
<span>Refresh</span>
</button>
</div>
</div>
@ -528,28 +528,9 @@ const ActivityStream = () => {
{/* 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 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 activities...</span>
</div>
) : activities.length === 0 ? (
<div className="text-center py-12">
@ -557,17 +538,9 @@ const ActivityStream = () => {
<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.'}
? 'Try adjusting your filters to see more results.'
: 'No activity has been recorded yet.'}
</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">
@ -625,8 +598,8 @@ const ActivityStream = () => {
{/* 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">
<div className="flex items-center justify-between px-4 py-3 bg-gray-50 border-t">
<div className="text-sm text-gray-600">
Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, totalActivities)} of {totalActivities} activities
</div>
<div className="flex items-center space-x-2">
@ -636,17 +609,17 @@ const ActivityStream = () => {
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>
<span className="ml-1">Previous</span>
</button>
<span className="px-3 py-1 text-sm">
{page} / {totalPages}
Page {page} of {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>
<span className="mr-1">Next</span>
<ChevronRight className="w-4 h-4" />
</button>
</div>

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -155,7 +155,7 @@ const UserList = () => {
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">User Management</h1>
<p className="text-gray-600">
@ -165,7 +165,7 @@ const UserList = () => {
<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"
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>
@ -208,51 +208,9 @@ const UserList = () => {
{/* 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 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 users...</span>
</div>
) : users.length === 0 ? (
<div className="text-center py-12">
@ -260,21 +218,9 @@ const UserList = () => {
<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.'
? 'Try adjusting your filters to see more results.'
: '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">
@ -401,8 +347,8 @@ const UserList = () => {
{/* 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">
<div className="flex items-center justify-between px-4 py-3 bg-gray-50 border-t">
<div className="text-sm text-gray-600">
Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, totalUsers)} of {totalUsers} users
</div>
<div className="flex items-center space-x-2">
@ -412,17 +358,17 @@ const UserList = () => {
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>
<span className="ml-1">Previous</span>
</button>
<span className="px-3 py-1 text-sm">
{page} / {totalPages}
Page {page} of {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>
<span className="mr-1">Next</span>
<ChevronRight className="w-4 h-4" />
</button>
</div>

View File

@ -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)
},
})