Compare commits
53 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1d8be3d840 | |||
| aebb8e66cb | |||
| ed2a278da2 | |||
| db2f5da66a | |||
| 19f8facc49 | |||
| b03760ab01 | |||
| 526dcd8dfc | |||
| 5b2561b6f1 | |||
| 3a6d06192a | |||
| 4b64b80b20 | |||
| ff89f96e31 | |||
| 465f997752 | |||
| 6948aaa92a | |||
| 4c7b49a5f6 | |||
| 6368f1027f | |||
| d64e7d08de | |||
| eb3751cb52 | |||
| 9fda54bd06 | |||
| 0d77a3a0a8 | |||
| 0618b78725 | |||
| 0178e71c67 | |||
| aa9b3a0227 | |||
| 410a33fecf | |||
| 05ebaaeedb | |||
| 84d0f63d36 | |||
| 6a4b549d9f | |||
| f3604b438b | |||
| 531831e84b | |||
| 90bb21e38b | |||
| 2f1a137342 | |||
| adf576fbe1 | |||
| 4264026bbe | |||
| 24b4a314a9 | |||
| ba825823a0 | |||
| fb16b7bbb8 | |||
| 8404125ff0 | |||
| 61ad2d61c1 | |||
| 9fd6b44487 | |||
| 9fe10bcce2 | |||
| f2abb40987 | |||
| 3697344cd0 | |||
| 4aa0ff705f | |||
| dc482e614a | |||
| 448882cfef | |||
| 7f9cb33a40 | |||
| 798f6211e0 | |||
| b992b151d3 | |||
| 87b8414e44 | |||
| ee13556c5c | |||
| afeb35a446 | |||
| ab324f1928 | |||
| 78ab0ad2e9 | |||
| 49c77785e7 |
@@ -53,6 +53,12 @@ VITE_API_URL=/api
|
|||||||
# Timezone
|
# Timezone
|
||||||
TZ=UTC
|
TZ=UTC
|
||||||
|
|
||||||
|
# Runtime user mapping for Docker (optional)
|
||||||
|
# Set these to your host user's UID/GID to avoid permission issues on bind mounts.
|
||||||
|
# Run `id -u` and `id -g` on host to get values. Defaults to 1001.
|
||||||
|
PUID=1001
|
||||||
|
PGID=1001
|
||||||
|
|
||||||
# Analytics (Optional - Umami)
|
# Analytics (Optional - Umami)
|
||||||
VITE_UMAMI_URL=
|
VITE_UMAMI_URL=
|
||||||
VITE_UMAMI_WEBSITE_ID=
|
VITE_UMAMI_WEBSITE_ID=
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Log in to Container Registry
|
- name: Log in to Container Registry
|
||||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||||
|
id: login-ghcr
|
||||||
|
continue-on-error: true
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
@@ -73,7 +75,8 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
context: ./backend
|
context: ./backend
|
||||||
file: ./backend/Dockerfile
|
file: ./backend/Dockerfile
|
||||||
push: ${{ github.event_name != 'pull_request' || github.event.inputs.push == 'true' }}
|
# Always build; only push when registry login succeeded
|
||||||
|
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||||
tags: ${{ steps.meta-backend.outputs.tags }}
|
tags: ${{ steps.meta-backend.outputs.tags }}
|
||||||
labels: ${{ steps.meta-backend.outputs.labels }}
|
labels: ${{ steps.meta-backend.outputs.labels }}
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
@@ -86,7 +89,7 @@ jobs:
|
|||||||
VERSION=${{ steps.meta-backend.outputs.version }}
|
VERSION=${{ steps.meta-backend.outputs.version }}
|
||||||
|
|
||||||
- name: Run Trivy vulnerability scanner
|
- name: Run Trivy vulnerability scanner
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||||
uses: aquasecurity/trivy-action@master
|
uses: aquasecurity/trivy-action@master
|
||||||
with:
|
with:
|
||||||
image-ref: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}:${{ steps.meta-backend.outputs.version }}
|
image-ref: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}:${{ steps.meta-backend.outputs.version }}
|
||||||
@@ -96,7 +99,7 @@ jobs:
|
|||||||
timeout: '10m'
|
timeout: '10m'
|
||||||
|
|
||||||
- name: Upload Trivy scan results to GitHub Security tab
|
- name: Upload Trivy scan results to GitHub Security tab
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||||
uses: github/codeql-action/upload-sarif@v3
|
uses: github/codeql-action/upload-sarif@v3
|
||||||
with:
|
with:
|
||||||
sarif_file: 'trivy-backend.sarif'
|
sarif_file: 'trivy-backend.sarif'
|
||||||
@@ -120,6 +123,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Log in to Container Registry
|
- name: Log in to Container Registry
|
||||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||||
|
id: login-ghcr
|
||||||
|
continue-on-error: true
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
@@ -150,7 +155,8 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
context: ./frontend
|
context: ./frontend
|
||||||
file: ./frontend/Dockerfile
|
file: ./frontend/Dockerfile
|
||||||
push: ${{ github.event_name != 'pull_request' || github.event.inputs.push == 'true' }}
|
# Always build; only push when registry login succeeded
|
||||||
|
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||||
tags: ${{ steps.meta-frontend.outputs.tags }}
|
tags: ${{ steps.meta-frontend.outputs.tags }}
|
||||||
labels: ${{ steps.meta-frontend.outputs.labels }}
|
labels: ${{ steps.meta-frontend.outputs.labels }}
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
@@ -163,7 +169,7 @@ jobs:
|
|||||||
VERSION=${{ steps.meta-frontend.outputs.version }}
|
VERSION=${{ steps.meta-frontend.outputs.version }}
|
||||||
|
|
||||||
- name: Run Trivy vulnerability scanner
|
- name: Run Trivy vulnerability scanner
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||||
uses: aquasecurity/trivy-action@master
|
uses: aquasecurity/trivy-action@master
|
||||||
with:
|
with:
|
||||||
image-ref: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}:${{ steps.meta-frontend.outputs.version }}
|
image-ref: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}:${{ steps.meta-frontend.outputs.version }}
|
||||||
@@ -173,7 +179,7 @@ jobs:
|
|||||||
timeout: '10m'
|
timeout: '10m'
|
||||||
|
|
||||||
- name: Upload Trivy scan results to GitHub Security tab
|
- name: Upload Trivy scan results to GitHub Security tab
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||||
uses: github/codeql-action/upload-sarif@v3
|
uses: github/codeql-action/upload-sarif@v3
|
||||||
with:
|
with:
|
||||||
sarif_file: 'trivy-frontend.sarif'
|
sarif_file: 'trivy-frontend.sarif'
|
||||||
@@ -220,4 +226,4 @@ jobs:
|
|||||||
echo "- PR number (for pull requests)" >> $GITHUB_STEP_SUMMARY
|
echo "- PR number (for pull requests)" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- Version tags (for releases)" >> $GITHUB_STEP_SUMMARY
|
echo "- Version tags (for releases)" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- Short SHA with branch prefix" >> $GITHUB_STEP_SUMMARY
|
echo "- Short SHA with branch prefix" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- \`latest\` (for main branch)" >> $GITHUB_STEP_SUMMARY
|
echo "- \`latest\` (for main branch)" >> $GITHUB_STEP_SUMMARY
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ If you need to customize the application or the pre-built images aren't availabl
|
|||||||
- [Reverse Proxy Setup](#reverse-proxy-setup)
|
- [Reverse Proxy Setup](#reverse-proxy-setup)
|
||||||
- [Maintenance](#maintenance)
|
- [Maintenance](#maintenance)
|
||||||
- [Troubleshooting](#troubleshooting)
|
- [Troubleshooting](#troubleshooting)
|
||||||
|
- [External Media Library](#external-media-library)
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
@@ -111,6 +112,43 @@ If you need to customize the application or the pre-built images aren't availabl
|
|||||||
docker compose -f docker-compose.production.yml logs -f
|
docker compose -f docker-compose.production.yml logs -f
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## External Media Library
|
||||||
|
|
||||||
|
PicPeak can reference an existing, read‑only media library mounted into the backend container. This avoids copying originals into PicPeak storage.
|
||||||
|
|
||||||
|
- Map your host library path to the container as read‑only in `docker-compose.production.yml`:
|
||||||
|
- Add volume under `backend`: `- ${EXTERNAL_MEDIA}:/external-media:ro`
|
||||||
|
- Add backend env: `EXTERNAL_MEDIA_ROOT=/external-media`
|
||||||
|
- In `.env`, set:
|
||||||
|
- `EXTERNAL_MEDIA=/mnt/photos` (example host path)
|
||||||
|
- `EXTERNAL_MEDIA_ROOT=/external-media`
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
- In Admin → Events, set “Source Mode” to “Reference (external folder)”, select a folder under `/external-media`, then import to index and generate thumbnails. Originals stay in your library.
|
||||||
|
|
||||||
|
Backups and Archives:
|
||||||
|
- Backups only include data under `STORAGE_PATH` and exclude external originals. The backup manifest includes `metadata.external_references = { excluded: true, events: N, photos: M }` and the Admin UI surfaces a warning.
|
||||||
|
- Archiving reference events creates a manifest‑only ZIP and deletes thumbnails for that event. External originals are never moved or deleted.
|
||||||
|
|
||||||
|
Local (npm) setup (no Docker):
|
||||||
|
|
||||||
|
1. Create or choose a folder that contains your external originals, e.g. `/Users/you/Pictures/picpeak-external` (macOS/Linux) or `C:\\Pictures\\picpeak-external` (Windows).
|
||||||
|
2. In `backend/.env` (or your shell), set:
|
||||||
|
- `EXTERNAL_MEDIA_ROOT=/absolute/path/to/picpeak-external`
|
||||||
|
- Ensure `STORAGE_PATH` points to your PicPeak storage (defaults to `./storage`).
|
||||||
|
3. Start services from source:
|
||||||
|
- Backend: `cd backend && npm install && npm run migrate && JWT_SECRET=... npm start`
|
||||||
|
- Frontend: `cd frontend && npm install && npm run dev` (or build + serve)
|
||||||
|
4. In Admin → Events:
|
||||||
|
- Create an event, set “Source Mode” to “Reference (external folder)”.
|
||||||
|
- Use the folder picker to browse under your `EXTERNAL_MEDIA_ROOT` and select the subfolder to reference.
|
||||||
|
- Click “Import from selected folder” to index files and generate thumbnails on demand.
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
- PicPeak only reads from `EXTERNAL_MEDIA_ROOT`; it never modifies or deletes your originals there.
|
||||||
|
- Thumbnails are generated under `STORAGE_PATH/thumbnails` and are included in backups; originals in `EXTERNAL_MEDIA_ROOT` are excluded.
|
||||||
|
- On Windows, use absolute paths (e.g., `C:\\Photos\\Library`) for `EXTERNAL_MEDIA_ROOT`.
|
||||||
|
|
||||||
### Method 2: Building from Source
|
### Method 2: Building from Source
|
||||||
|
|
||||||
1. **Clone the repository**
|
1. **Clone the repository**
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ Unlike expensive SaaS solutions, PicPeak gives you:
|
|||||||
|
|
||||||
### For Photographers
|
### For Photographers
|
||||||
- 📁 **Drag & Drop Upload** - Simply drop photos into folders
|
- 📁 **Drag & Drop Upload** - Simply drop photos into folders
|
||||||
|
- 🔗 **External Media (Reference Mode)** - Browse and import from a read‑only external folder library without copying originals
|
||||||
- ⏰ **Auto-Expiring Galleries** - Set expiration dates (default: 30 days)
|
- ⏰ **Auto-Expiring Galleries** - Set expiration dates (default: 30 days)
|
||||||
- 🔐 **Password Protection** - Secure client galleries
|
- 🔐 **Password Protection** - Secure client galleries
|
||||||
- 📧 **Automated Emails** - Creation confirmations and expiration warnings
|
- 📧 **Automated Emails** - Creation confirmations and expiration warnings
|
||||||
@@ -45,6 +46,7 @@ Unlike expensive SaaS solutions, PicPeak gives you:
|
|||||||
### Technical Excellence
|
### Technical Excellence
|
||||||
- 🐳 **Docker Ready** - Deploy in minutes
|
- 🐳 **Docker Ready** - Deploy in minutes
|
||||||
- 🔄 **Auto-Processing** - Automatic thumbnail generation
|
- 🔄 **Auto-Processing** - Automatic thumbnail generation
|
||||||
|
- 🗂️ **Reference Library Support** - Point PicPeak at `EXTERNAL_MEDIA_ROOT` to reference existing originals, index quickly, and generate thumbnails on demand
|
||||||
- 💾 **Smart Storage** - Automatic archiving of expired galleries
|
- 💾 **Smart Storage** - Automatic archiving of expired galleries
|
||||||
- 🛡️ **Security First** - JWT auth, rate limiting, CORS protection
|
- 🛡️ **Security First** - JWT auth, rate limiting, CORS protection
|
||||||
- 📈 **Scalable** - From small studios to large agencies
|
- 📈 **Scalable** - From small studios to large agencies
|
||||||
@@ -70,9 +72,18 @@ docker-compose up -d
|
|||||||
# Access at http://localhost:3005
|
# Access at http://localhost:3005
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Note on Docker file permissions (PUID/PGID)
|
||||||
|
- When using bind mounts (e.g., `./storage`, `./data`, `./logs`, `./events`), ensure the container user can write to these host folders. The backend runs as a non‑root user by default.
|
||||||
|
- Set `PUID` and `PGID` in your `.env` to match your host user’s UID/GID (run `id -u` and `id -g` on the host). Compose maps the container user to these values.
|
||||||
|
- Example in `.env`:
|
||||||
|
- `PUID=1000`
|
||||||
|
- `PGID=1000`
|
||||||
|
- Without this, creating events, uploads, thumbnails, or logs can fail with “Permission denied”.
|
||||||
|
|
||||||
## 📖 Documentation
|
## 📖 Documentation
|
||||||
|
|
||||||
- 📘 [**Deployment Guide**](DEPLOYMENT_GUIDE.md) - Detailed installation instructions
|
- 📘 [**Deployment Guide**](DEPLOYMENT_GUIDE.md) - Detailed installation instructions
|
||||||
|
- Includes the new [External Media Library](DEPLOYMENT_GUIDE.md#external-media-library) reference mode
|
||||||
- 🤝 [**Contributing**](CONTRIBUTING.md) - How to contribute
|
- 🤝 [**Contributing**](CONTRIBUTING.md) - How to contribute
|
||||||
- 📜 [**License**](LICENSE) - MIT License
|
- 📜 [**License**](LICENSE) - MIT License
|
||||||
- 🔒 [**Security**](SECURITY.md) - Security policies
|
- 🔒 [**Security**](SECURITY.md) - Security policies
|
||||||
@@ -192,9 +203,10 @@ These features are currently in beta testing and may have limited functionality
|
|||||||
| Feature | Description | Priority | Status |
|
| Feature | Description | Priority | Status |
|
||||||
|---------|-------------|----------|---------|
|
|---------|-------------|----------|---------|
|
||||||
| **Backup & Restore** | Comprehensive backup system with S3/MinIO support, automated scheduling, and safe restore functionality | High | ✅ Implemented |
|
| **Backup & Restore** | Comprehensive backup system with S3/MinIO support, automated scheduling, and safe restore functionality | High | ✅ Implemented |
|
||||||
|
| **External Media Library (Reference Mode)** | Use an external folder library as a read‑only source with import and on‑demand thumbnail generation | High | ✅ Implemented |
|
||||||
| **Gallery Templates** | Additional gallery layouts and themes (masonry, slideshow, story-style) for different event types | Medium | 🔄 Open |
|
| **Gallery Templates** | Additional gallery layouts and themes (masonry, slideshow, story-style) for different event types | Medium | 🔄 Open |
|
||||||
| **Face Recognition** | AI-powered face detection to help guests find their photos and create automatic person-based albums | Low | 🔄 Open |
|
| **Face Recognition** | AI-powered face detection to help guests find their photos and create automatic person-based albums | Low | 🔄 Open |
|
||||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented (not tested) |
|
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented |
|
||||||
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | 🔄 Open |
|
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | 🔄 Open |
|
||||||
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | 📋 Planned |
|
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | 📋 Planned |
|
||||||
|
|
||||||
@@ -233,4 +245,4 @@ PicPeak is released under the [MIT License](LICENSE). Use it freely for personal
|
|||||||
<a href="https://github.com/the-luap/picpeak">GitHub</a> •
|
<a href="https://github.com/the-luap/picpeak">GitHub</a> •
|
||||||
<a href="DEPLOYMENT_GUIDE.md">Documentation</a> •
|
<a href="DEPLOYMENT_GUIDE.md">Documentation</a> •
|
||||||
<a href="https://github.com/the-luap/picpeak/issues">Support</a>
|
<a href="https://github.com/the-luap/picpeak/issues">Support</a>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
+9
-9
@@ -8,7 +8,7 @@ This guide provides easy installation instructions for PicPeak on Linux servers
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Download and run the unified setup script
|
# Download and run the unified setup script
|
||||||
curl -fsSL https://raw.githubusercontent.com/yourusername/wedding-photo-sharing/main/scripts/setup.sh -o setup.sh && \
|
curl -fsSL https://raw.githubusercontent.com/the-luap/picpeak/main/scripts/setup.sh -o setup.sh && \
|
||||||
chmod +x setup.sh && \
|
chmod +x setup.sh && \
|
||||||
sudo ./setup.sh
|
sudo ./setup.sh
|
||||||
```
|
```
|
||||||
@@ -305,9 +305,9 @@ docker compose restart
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Native Configuration
|
### Native Configuration
|
||||||
Edit `/opt/picpeak/backend/.env`:
|
Edit `/opt/picpeak/app/backend/.env`:
|
||||||
```bash
|
```bash
|
||||||
sudo nano /opt/picpeak/backend/.env
|
sudo nano /opt/picpeak/app/backend/.env
|
||||||
sudo systemctl restart picpeak-backend
|
sudo systemctl restart picpeak-backend
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -369,7 +369,7 @@ tar -czf photos-backup.tar.gz storage/events/
|
|||||||
#### Native:
|
#### Native:
|
||||||
```bash
|
```bash
|
||||||
# Database backup
|
# Database backup
|
||||||
sudo cp /opt/picpeak/backend/database.sqlite /backup/database-$(date +%Y%m%d).sqlite
|
sudo cp /opt/picpeak/app/backend/data/photo_sharing.db /backup/database-$(date +%Y%m%d).sqlite
|
||||||
|
|
||||||
# Photos backup
|
# Photos backup
|
||||||
sudo tar -czf /backup/photos-$(date +%Y%m%d).tar.gz /opt/picpeak/events/
|
sudo tar -czf /backup/photos-$(date +%Y%m%d).tar.gz /opt/picpeak/events/
|
||||||
@@ -446,7 +446,7 @@ ls -la ~/picpeak/storage/events/
|
|||||||
docker exec picpeak-backend node scripts/reset-admin-password.js
|
docker exec picpeak-backend node scripts/reset-admin-password.js
|
||||||
|
|
||||||
# Native
|
# Native
|
||||||
cd /opt/picpeak/backend
|
cd /opt/picpeak/app/backend
|
||||||
sudo -u picpeak node scripts/reset-admin-password.js
|
sudo -u picpeak node scripts/reset-admin-password.js
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -458,11 +458,11 @@ sudo -u picpeak node scripts/reset-admin-password.js
|
|||||||
- Installation: `/tmp/picpeak-setup-*.log`
|
- Installation: `/tmp/picpeak-setup-*.log`
|
||||||
|
|
||||||
2. **Documentation:**
|
2. **Documentation:**
|
||||||
- [Full Documentation](https://github.com/yourusername/wedding-photo-sharing)
|
- [Full Documentation](https://github.com/the-luap/picpeak)
|
||||||
- [Deployment Guide](./DEPLOYMENT_GUIDE.md)
|
- [Deployment Guide](./DEPLOYMENT_GUIDE.md)
|
||||||
|
|
||||||
3. **Support:**
|
3. **Support:**
|
||||||
- [GitHub Issues](https://github.com/yourusername/wedding-photo-sharing/issues)
|
- [GitHub Issues](https://github.com/the-luap/picpeak/issues)
|
||||||
- Include: Error messages, system info (`uname -a`), installation method
|
- Include: Error messages, system info (`uname -a`), installation method
|
||||||
|
|
||||||
## 🔒 Security Best Practices
|
## 🔒 Security Best Practices
|
||||||
@@ -498,7 +498,7 @@ services:
|
|||||||
### Native Optimization
|
### Native Optimization
|
||||||
```bash
|
```bash
|
||||||
# Increase Node.js memory
|
# Increase Node.js memory
|
||||||
echo "NODE_OPTIONS=--max-old-space-size=2048" >> /opt/picpeak/backend/.env
|
echo "NODE_OPTIONS=--max-old-space-size=2048" >> /opt/picpeak/app/backend/.env
|
||||||
sudo systemctl restart picpeak-backend
|
sudo systemctl restart picpeak-backend
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -540,4 +540,4 @@ sudo ./setup.sh --native \
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**PicPeak Setup v1.0** | [Documentation](https://github.com/yourusername/wedding-photo-sharing) | [Support](https://github.com/yourusername/wedding-photo-sharing/issues)
|
**PicPeak Setup v1.0** | [Documentation](https://github.com/the-luap/picpeak) | [Support](https://github.com/the-luap/picpeak/issues)
|
||||||
|
|||||||
+32
-24
@@ -26,29 +26,37 @@ const config = {
|
|||||||
|
|
||||||
production: {
|
production: {
|
||||||
client: process.env.DATABASE_CLIENT || 'pg',
|
client: process.env.DATABASE_CLIENT || 'pg',
|
||||||
connection: {
|
// Support both Postgres and SQLite in production based on DATABASE_CLIENT
|
||||||
host: process.env.DB_HOST || 'db',
|
connection: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
|
||||||
port: process.env.DB_PORT || 5432,
|
? {
|
||||||
user: process.env.DB_USER || 'picpeak',
|
host: process.env.DB_HOST || 'db',
|
||||||
password: process.env.DB_PASSWORD,
|
port: process.env.DB_PORT || 5432,
|
||||||
database: process.env.DB_NAME || 'picpeak',
|
user: process.env.DB_USER || 'picpeak',
|
||||||
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
password: process.env.DB_PASSWORD,
|
||||||
// Connection stability settings
|
database: process.env.DB_NAME || 'picpeak',
|
||||||
connectionTimeoutMillis: 30000,
|
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
||||||
idleTimeoutMillis: 30000,
|
// Connection stability settings
|
||||||
keepAlive: true,
|
connectionTimeoutMillis: 30000,
|
||||||
keepAliveInitialDelayMillis: 0
|
idleTimeoutMillis: 30000,
|
||||||
},
|
keepAlive: true,
|
||||||
pool: {
|
keepAliveInitialDelayMillis: 0
|
||||||
min: 5,
|
}
|
||||||
max: 25,
|
: {
|
||||||
acquireTimeoutMillis: 60000,
|
filename: path.join(__dirname, process.env.DATABASE_PATH || './data/photo_sharing.db')
|
||||||
createTimeoutMillis: 60000,
|
},
|
||||||
idleTimeoutMillis: 30000,
|
useNullAsDefault: (process.env.DATABASE_CLIENT || 'pg') !== 'pg',
|
||||||
reapIntervalMillis: 1000,
|
pool: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
|
||||||
createRetryIntervalMillis: 200,
|
? {
|
||||||
propagateCreateError: false
|
min: 5,
|
||||||
},
|
max: 25,
|
||||||
|
acquireTimeoutMillis: 60000,
|
||||||
|
createTimeoutMillis: 60000,
|
||||||
|
idleTimeoutMillis: 30000,
|
||||||
|
reapIntervalMillis: 1000,
|
||||||
|
createRetryIntervalMillis: 200,
|
||||||
|
propagateCreateError: false
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
migrations: {
|
migrations: {
|
||||||
directory: './migrations'
|
directory: './migrations'
|
||||||
},
|
},
|
||||||
@@ -56,4 +64,4 @@ const config = {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = config[process.env.NODE_ENV || 'development'];
|
module.exports = config[process.env.NODE_ENV || 'development'];
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Migration 041: Add external media reference support
|
||||||
|
* - events.source_mode: 'managed' | 'reference'
|
||||||
|
* - events.external_path: relative path under external media root
|
||||||
|
* - photos.source_origin: 'managed' | 'external'
|
||||||
|
* - photos.external_relpath: relative path within event.external_path
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { addColumnIfNotExists } = require('../helpers');
|
||||||
|
|
||||||
|
exports.up = async function(knex) {
|
||||||
|
console.log('Running migration: 041_add_external_media');
|
||||||
|
|
||||||
|
// events.source_mode (default 'managed')
|
||||||
|
await addColumnIfNotExists(knex, 'events', 'source_mode', (table) => {
|
||||||
|
table.string('source_mode').notNullable().defaultTo('managed');
|
||||||
|
});
|
||||||
|
|
||||||
|
// events.external_path (nullable)
|
||||||
|
await addColumnIfNotExists(knex, 'events', 'external_path', (table) => {
|
||||||
|
table.text('external_path');
|
||||||
|
});
|
||||||
|
|
||||||
|
// photos.source_origin (default 'managed')
|
||||||
|
await addColumnIfNotExists(knex, 'photos', 'source_origin', (table) => {
|
||||||
|
table.string('source_origin').notNullable().defaultTo('managed');
|
||||||
|
});
|
||||||
|
|
||||||
|
// photos.external_relpath (nullable)
|
||||||
|
await addColumnIfNotExists(knex, 'photos', 'external_relpath', (table) => {
|
||||||
|
table.text('external_relpath');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Helpful index for queries
|
||||||
|
try {
|
||||||
|
if (knex.client.config.client === 'pg') {
|
||||||
|
await knex.raw("CREATE INDEX IF NOT EXISTS photos_event_source_idx ON photos (event_id, source_origin)");
|
||||||
|
} else {
|
||||||
|
await knex.schema.alterTable('photos', (table) => {
|
||||||
|
table.index(['event_id', 'source_origin'], 'photos_event_source_idx');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log('Index creation skipped or failed (may already exist):', e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Migration 041_add_external_media completed');
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.down = async function(knex) {
|
||||||
|
console.log('Rollback: 041_add_external_media');
|
||||||
|
// Keep columns (safe rollback not removing data). Intentionally no-op.
|
||||||
|
};
|
||||||
|
|
||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-backend",
|
"name": "picpeak-backend",
|
||||||
"version": "1.0.109",
|
"version": "1.0.124",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "picpeak-backend",
|
"name": "picpeak-backend",
|
||||||
"version": "1.0.109",
|
"version": "1.0.124",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@aws-sdk/client-s3": "^3.850.0",
|
"@aws-sdk/client-s3": "^3.850.0",
|
||||||
"@aws-sdk/lib-storage": "^3.850.0",
|
"@aws-sdk/lib-storage": "^3.850.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-backend",
|
"name": "picpeak-backend",
|
||||||
"version": "1.0.109",
|
"version": "1.0.124",
|
||||||
"description": "Backend for PicPeak event photo sharing platform",
|
"description": "Backend for PicPeak event photo sharing platform",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -36,4 +36,4 @@ async function setAdminPassword() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setAdminPassword();
|
setAdminPassword();
|
||||||
|
|||||||
+75
-20
@@ -12,6 +12,7 @@ logger.info('Server starting up', {
|
|||||||
timestamp: new Date().toISOString()
|
timestamp: new Date().toISOString()
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const helmet = require('helmet');
|
const helmet = require('helmet');
|
||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
@@ -42,25 +43,36 @@ const PORT = process.env.PORT || 3000;
|
|||||||
app.set('trust proxy', 'loopback, linklocal, uniquelocal');
|
app.set('trust proxy', 'loopback, linklocal, uniquelocal');
|
||||||
|
|
||||||
// Security middleware with custom CSP
|
// Security middleware with custom CSP
|
||||||
|
// In native HTTP installs, do NOT force HTTPS for subresources.
|
||||||
|
const enableHsts = process.env.ENABLE_HSTS === 'true';
|
||||||
|
const cspDirectives = {
|
||||||
|
defaultSrc: ["'self'"],
|
||||||
|
scriptSrc: ["'self'", "'unsafe-inline'"], // Required for React
|
||||||
|
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
||||||
|
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
||||||
|
connectSrc: ["'self'"], // API connections
|
||||||
|
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
||||||
|
objectSrc: ["'none'"], // Disable plugins
|
||||||
|
mediaSrc: ["'self'"], // Audio/video
|
||||||
|
frameSrc: ["'none'"], // Disable iframes
|
||||||
|
};
|
||||||
|
// Only upgrade insecure requests when HSTS explicitly enabled (HTTPS deployment)
|
||||||
|
if (enableHsts) {
|
||||||
|
// In helmet, an empty array enables the directive
|
||||||
|
cspDirectives.upgradeInsecureRequests = [];
|
||||||
|
}
|
||||||
|
|
||||||
app.use(helmet({
|
app.use(helmet({
|
||||||
contentSecurityPolicy: {
|
contentSecurityPolicy: {
|
||||||
directives: {
|
// Avoid helmet adding defaults like upgrade-insecure-requests when not desired
|
||||||
defaultSrc: ["'self'"],
|
useDefaults: false,
|
||||||
scriptSrc: ["'self'", "'unsafe-inline'"], // Required for React
|
directives: cspDirectives,
|
||||||
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
|
||||||
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
|
||||||
connectSrc: ["'self'"], // API connections
|
|
||||||
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
|
||||||
objectSrc: ["'none'"], // Disable plugins
|
|
||||||
mediaSrc: ["'self'"], // Audio/video
|
|
||||||
frameSrc: ["'none'"], // Disable iframes
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
hsts: {
|
hsts: enableHsts ? {
|
||||||
maxAge: 31536000, // 1 year
|
maxAge: 31536000, // 1 year
|
||||||
includeSubDomains: true,
|
includeSubDomains: true,
|
||||||
preload: true
|
preload: true
|
||||||
},
|
} : false,
|
||||||
permittedCrossDomainPolicies: false,
|
permittedCrossDomainPolicies: false,
|
||||||
referrerPolicy: { policy: "strict-origin-when-cross-origin" }
|
referrerPolicy: { policy: "strict-origin-when-cross-origin" }
|
||||||
}));
|
}));
|
||||||
@@ -72,14 +84,14 @@ app.use((req, res, next) => {
|
|||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
// CORS configuration
|
// CORS configuration (apply only to API routes)
|
||||||
const corsOptions = {
|
const corsOptions = {
|
||||||
origin: function (origin, callback) {
|
origin: function (origin, callback) {
|
||||||
const allowedOrigins = [
|
const allowedOrigins = [
|
||||||
process.env.FRONTEND_URL || 'http://localhost:3005',
|
process.env.FRONTEND_URL || 'http://localhost:3005',
|
||||||
process.env.ADMIN_URL || 'http://localhost:3005'
|
process.env.ADMIN_URL || 'http://localhost:3005'
|
||||||
];
|
];
|
||||||
|
|
||||||
// In development, also allow localhost origins
|
// In development, also allow localhost origins
|
||||||
if (process.env.NODE_ENV === 'development') {
|
if (process.env.NODE_ENV === 'development') {
|
||||||
allowedOrigins.push(
|
allowedOrigins.push(
|
||||||
@@ -89,18 +101,22 @@ const corsOptions = {
|
|||||||
'http://localhost:3000' // Direct backend access
|
'http://localhost:3000' // Direct backend access
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allow requests with no origin (like mobile apps or curl)
|
// Allow requests with no origin (like curl) and allow-listed origins
|
||||||
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
|
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
|
||||||
callback(null, true);
|
callback(null, true);
|
||||||
} else {
|
} else {
|
||||||
callback(new Error('Not allowed by CORS'));
|
// Do not error globally; just omit CORS headers on disallowed origins
|
||||||
|
callback(null, false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
credentials: true
|
credentials: true
|
||||||
};
|
};
|
||||||
|
|
||||||
app.use(cors(corsOptions));
|
// Only attach CORS to API endpoints, not static assets
|
||||||
|
app.use('/api', cors(corsOptions));
|
||||||
|
// Handle preflight explicitly for API paths
|
||||||
|
app.options('/api/*', cors(corsOptions));
|
||||||
|
|
||||||
// Initialize rate limiters (they will be created dynamically)
|
// Initialize rate limiters (they will be created dynamically)
|
||||||
let generalRateLimiter;
|
let generalRateLimiter;
|
||||||
@@ -124,6 +140,22 @@ async function initializeRateLimiters() {
|
|||||||
app.use(express.json({ limit: '100mb' }));
|
app.use(express.json({ limit: '100mb' }));
|
||||||
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
|
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
|
||||||
|
|
||||||
|
// Request logging for API routes (with timestamps)
|
||||||
|
const apiRequestLogger = (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const started = Date.now();
|
||||||
|
const ts = new Date().toISOString();
|
||||||
|
logger.info(`[${ts}] ${req.method} ${req.originalUrl}`);
|
||||||
|
res.on('finish', () => {
|
||||||
|
const ms = Date.now() - started;
|
||||||
|
const tsDone = new Date().toISOString();
|
||||||
|
logger.info(`[${tsDone}] ${req.method} ${req.originalUrl} -> ${res.statusCode} (${ms}ms)`);
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
app.use('/api', apiRequestLogger);
|
||||||
|
|
||||||
// Maintenance mode middleware - add after body parsing but before routes
|
// Maintenance mode middleware - add after body parsing but before routes
|
||||||
app.use(maintenanceMiddleware);
|
app.use(maintenanceMiddleware);
|
||||||
|
|
||||||
@@ -143,6 +175,7 @@ const secureStatic = require('./src/middleware/secureStatic');
|
|||||||
|
|
||||||
// Get storage path from environment or use default
|
// Get storage path from environment or use default
|
||||||
const storagePath = process.env.STORAGE_PATH || path.join(__dirname, '../storage');
|
const storagePath = process.env.STORAGE_PATH || path.join(__dirname, '../storage');
|
||||||
|
process.env.EXTERNAL_MEDIA_ROOT = process.env.EXTERNAL_MEDIA_ROOT || '/external-media';
|
||||||
|
|
||||||
// Static file serving for photos (protected)
|
// Static file serving for photos (protected)
|
||||||
app.use('/photos', require('./src/middleware/photoAuth'), setCorsHeaders, secureStatic(path.join(storagePath, 'events/active')));
|
app.use('/photos', require('./src/middleware/photoAuth'), setCorsHeaders, secureStatic(path.join(storagePath, 'events/active')));
|
||||||
@@ -199,7 +232,8 @@ app.get('/health', async (req, res) => {
|
|||||||
|
|
||||||
// Routes
|
// Routes
|
||||||
app.use('/api/auth', authRoutes);
|
app.use('/api/auth', authRoutes);
|
||||||
app.use('/api/events', eventRoutes);
|
app.use('/api/events', eventRoutes);
|
||||||
|
app.use('/api/admin/external-media', require('./src/routes/adminExternalMedia'));
|
||||||
// Gallery routes - main routes first, then feedback routes
|
// Gallery routes - main routes first, then feedback routes
|
||||||
app.use('/api/gallery', galleryRoutes);
|
app.use('/api/gallery', galleryRoutes);
|
||||||
app.use('/api/gallery', require('./src/routes/galleryFeedback'));
|
app.use('/api/gallery', require('./src/routes/galleryFeedback'));
|
||||||
@@ -217,6 +251,27 @@ app.use('/api/public', require('./src/routes/publicCMS'));
|
|||||||
app.use('/api/images', require('./src/routes/protectedImages'));
|
app.use('/api/images', require('./src/routes/protectedImages'));
|
||||||
app.use('/api/secure-images', secureImagesRoutes);
|
app.use('/api/secure-images', secureImagesRoutes);
|
||||||
|
|
||||||
|
// Optional: Serve built frontend (native installs)
|
||||||
|
try {
|
||||||
|
const serveFrontendEnv = process.env.SERVE_FRONTEND; // 'true' | 'false' | undefined
|
||||||
|
const frontendDir = process.env.FRONTEND_DIR || path.join(__dirname, '../frontend/dist');
|
||||||
|
const indexPath = path.join(frontendDir, 'index.html');
|
||||||
|
// Auto-serve when dist exists unless explicitly disabled
|
||||||
|
const shouldServe = (serveFrontendEnv === 'true') || ((serveFrontendEnv === undefined || serveFrontendEnv === 'auto') && fs.existsSync(indexPath));
|
||||||
|
if (shouldServe) {
|
||||||
|
logger.info(`Serving frontend from ${frontendDir}`);
|
||||||
|
app.use(express.static(frontendDir));
|
||||||
|
// SPA fallback for non-API routes
|
||||||
|
app.get([ '/', '/admin', '/admin/*', '/gallery/*' ], (req, res) => {
|
||||||
|
res.sendFile(indexPath);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
logger.info('Frontend static serving disabled or dist not found', { serveFrontendEnv, frontendDir });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn('Failed to enable frontend static serving', { error: e.message });
|
||||||
|
}
|
||||||
|
|
||||||
// Error handling middleware
|
// Error handling middleware
|
||||||
app.use((err, req, res, next) => {
|
app.use((err, req, res, next) => {
|
||||||
console.error('EXPRESS ERROR HANDLER:', err);
|
console.error('EXPRESS ERROR HANDLER:', err);
|
||||||
|
|||||||
@@ -1,7 +1,28 @@
|
|||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
const knex = require('knex');
|
const knex = require('knex');
|
||||||
const knexConfig = require('../../knexfile');
|
const knexConfig = require('../../knexfile');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
|
|
||||||
|
// Ensure SQLite directory exists when using file-based DB (native installs)
|
||||||
|
try {
|
||||||
|
const isPostgres = knexConfig && knexConfig.client === 'pg';
|
||||||
|
if (!isPostgres && knexConfig && knexConfig.connection) {
|
||||||
|
const filename = typeof knexConfig.connection === 'object'
|
||||||
|
? knexConfig.connection.filename
|
||||||
|
: (typeof knexConfig.connection === 'string' ? knexConfig.connection : null);
|
||||||
|
if (filename && typeof filename === 'string') {
|
||||||
|
const dir = path.dirname(filename);
|
||||||
|
if (dir && dir !== '.') {
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Non-fatal: log and continue; SQLite will fail later if still missing
|
||||||
|
try { logger.warn('SQLite directory ensure failed', { error: e.message }); } catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
// Create database connection with built-in retry logic
|
// Create database connection with built-in retry logic
|
||||||
const db = knex(knexConfig);
|
const db = knex(knexConfig);
|
||||||
|
|
||||||
@@ -312,4 +333,4 @@ async function logActivity(activityType, metadata = {}, eventId = null, actor =
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { db, initializeDatabase, logActivity, withRetry };
|
module.exports = { db, initializeDatabase, logActivity, withRetry };
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
const { adminAuth } = require('../middleware/auth');
|
||||||
|
const { list, resolveExternalPath, getExternalMediaRoot } = require('../services/externalMediaService');
|
||||||
|
const { db, logActivity } = require('../database/db');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// GET /api/admin/external-media/list?path=relative/dir
|
||||||
|
router.get('/list', adminAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const relPath = (req.query.path || '').replace(/^\/+/, '');
|
||||||
|
const result = await list(relPath);
|
||||||
|
res.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(400).json({ error: 'Invalid path', details: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Helper to recursively collect files under a directory, filtered by image extensions
|
||||||
|
async function walkDir(dir, baseDir) {
|
||||||
|
const results = [];
|
||||||
|
const entries = await fs.readdir(dir, { withFileTypes: true });
|
||||||
|
for (const e of entries) {
|
||||||
|
if (e.name.startsWith('.')) continue;
|
||||||
|
const full = path.join(dir, e.name);
|
||||||
|
if (e.isDirectory()) {
|
||||||
|
results.push(...await walkDir(full, baseDir));
|
||||||
|
} else if (e.isFile()) {
|
||||||
|
const ext = path.extname(e.name).toLowerCase();
|
||||||
|
if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
|
||||||
|
const rel = path.relative(baseDir, full);
|
||||||
|
results.push({ full, rel, name: e.name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/admin/events/:id/import-external
|
||||||
|
// Body: { external_path: string, recursive?: boolean, map?: { individual?: string, collages?: string } }
|
||||||
|
router.post('/events/:id/import-external', adminAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const eventId = parseInt(req.params.id);
|
||||||
|
const { external_path, recursive = true, map = { individual: 'individual', collages: 'collages' } } = req.body || {};
|
||||||
|
if (!external_path) return res.status(400).json({ error: 'external_path is required' });
|
||||||
|
|
||||||
|
// Load event
|
||||||
|
const event = await db('events').where('id', eventId).first();
|
||||||
|
if (!event) return res.status(404).json({ error: 'Event not found' });
|
||||||
|
|
||||||
|
const baseAbs = resolveExternalPath({ external_path }, '');
|
||||||
|
// Collect files
|
||||||
|
const files = recursive ? await walkDir(baseAbs, baseAbs) : (await fs.readdir(baseAbs, { withFileTypes: true }))
|
||||||
|
.filter(e => e.isFile())
|
||||||
|
.map(e => ({ full: path.join(baseAbs, e.name), rel: e.name, name: e.name }))
|
||||||
|
.filter(f => ['.jpg', '.jpeg', '.png', '.webp'].includes(path.extname(f.name).toLowerCase()));
|
||||||
|
|
||||||
|
let imported = 0;
|
||||||
|
let skipped = 0;
|
||||||
|
|
||||||
|
// Insert photos
|
||||||
|
for (const f of files) {
|
||||||
|
// Infer type by subfolder names
|
||||||
|
const segs = f.rel.split(path.sep);
|
||||||
|
let type = 'individual';
|
||||||
|
if (segs[0] === map.collages) type = 'collage';
|
||||||
|
if (segs[0] === map.individual) type = 'individual';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Check if already exists (by external_relpath)
|
||||||
|
const exists = await db('photos')
|
||||||
|
.where({ event_id: eventId, external_relpath: f.rel })
|
||||||
|
.first();
|
||||||
|
if (exists) { skipped++; continue; }
|
||||||
|
|
||||||
|
const stats = await fs.stat(f.full);
|
||||||
|
const inserted = await db('photos')
|
||||||
|
.insert({
|
||||||
|
event_id: eventId,
|
||||||
|
filename: f.name,
|
||||||
|
// Keep path as a hint for legacy code but not used for resolution in external mode
|
||||||
|
path: path.join(event.slug, f.name),
|
||||||
|
thumbnail_path: null,
|
||||||
|
type,
|
||||||
|
size_bytes: stats.size,
|
||||||
|
source_origin: 'external',
|
||||||
|
external_relpath: f.rel
|
||||||
|
})
|
||||||
|
.returning('id');
|
||||||
|
|
||||||
|
imported += (inserted?.length ? 1 : 0);
|
||||||
|
} catch (e) {
|
||||||
|
skipped++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update event fields
|
||||||
|
await db('events').where('id', eventId).update({ source_mode: 'reference', external_path });
|
||||||
|
|
||||||
|
// Queue thumbnail generation lazily by reading thumbnails via ensure endpoint as needed
|
||||||
|
await logActivity('external_import_completed', { event_id: eventId, imported, skipped, external_path }, eventId, { type: 'admin' });
|
||||||
|
|
||||||
|
res.json({ imported, skipped, thumbnailsQueued: 0 });
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: 'Failed to import external media', details: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
|
|
||||||
@@ -606,8 +606,9 @@ router.get('/:eventId/photos/:photoId/download', adminAuth, async (req, res) =>
|
|||||||
return res.status(404).json({ error: 'Photo not found' });
|
return res.status(404).json({ error: 'Photo not found' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const storagePath = getStoragePath();
|
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||||
const filePath = path.join(storagePath, 'events/active', photo.path);
|
const event = await db('events').where('id', eventId).first();
|
||||||
|
const filePath = resolvePhotoFilePath(event, photo);
|
||||||
|
|
||||||
// Check if file exists
|
// Check if file exists
|
||||||
try {
|
try {
|
||||||
@@ -684,8 +685,10 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
|||||||
photos: photos.map(photo => ({
|
photos: photos.map(photo => ({
|
||||||
id: photo.id,
|
id: photo.id,
|
||||||
filename: photo.filename,
|
filename: photo.filename,
|
||||||
url: `/admin/events/${eventId}/photo/${photo.id}`,
|
// Use the correct admin photos router base for serving images
|
||||||
thumbnail_url: photo.thumbnail_path ? `/admin/events/${eventId}/thumbnail/${photo.id}` : null,
|
url: `/admin/photos/${eventId}/photo/${photo.id}`,
|
||||||
|
// Always expose a thumbnail URL; backend will generate on demand if missing
|
||||||
|
thumbnail_url: `/admin/photos/${eventId}/thumbnail/${photo.id}`,
|
||||||
type: photo.type,
|
type: photo.type,
|
||||||
category_id: photo.type,
|
category_id: photo.type,
|
||||||
category_name: photo.type === 'individual' ? 'Individual Photos' : 'Collages',
|
category_name: photo.type === 'individual' ? 'Individual Photos' : 'Collages',
|
||||||
@@ -719,8 +722,9 @@ router.get('/:eventId/photo/:photoId', adminAuth, async (req, res) => {
|
|||||||
return res.status(404).json({ error: 'Photo not found' });
|
return res.status(404).json({ error: 'Photo not found' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const storagePath = getStoragePath();
|
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||||
const filePath = path.join(storagePath, 'events/active', photo.path);
|
const event = await db('events').where('id', eventId).first();
|
||||||
|
const filePath = resolvePhotoFilePath(event, photo);
|
||||||
|
|
||||||
// Check if file exists
|
// Check if file exists
|
||||||
try {
|
try {
|
||||||
@@ -802,4 +806,4 @@ router.get('/:eventId/debug', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
+116
-35
@@ -107,30 +107,39 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
|||||||
.select('photos.*')
|
.select('photos.*')
|
||||||
.orderBy('photos.uploaded_at', 'desc');
|
.orderBy('photos.uploaded_at', 'desc');
|
||||||
|
|
||||||
// Apply filtering if requested
|
// Apply filtering if requested (global, based on aggregate counts)
|
||||||
if (filter && guest_id) {
|
if (filter) {
|
||||||
let filters = {};
|
const f = String(filter).toLowerCase();
|
||||||
|
const parts = f.split(',').map(s => s.trim());
|
||||||
// Parse filter parameter
|
const include = new Set();
|
||||||
if (filter === 'liked') {
|
|
||||||
filters.liked = true;
|
// Helper to include IDs for a predicate
|
||||||
} else if (filter === 'favorited') {
|
const includeBy = (predicate) => {
|
||||||
filters.favorited = true;
|
photos.forEach(p => { if (predicate(p)) include.add(p.id); });
|
||||||
} else if (filter === 'liked,favorited' || filter === 'favorited,liked') {
|
};
|
||||||
filters.liked = true;
|
|
||||||
filters.favorited = true;
|
if (parts.includes('liked')) {
|
||||||
filters.operator = 'OR';
|
includeBy(p => (p.like_count || 0) > 0);
|
||||||
|
}
|
||||||
|
if (parts.includes('favorited')) {
|
||||||
|
includeBy(p => (p.favorite_count || 0) > 0);
|
||||||
|
}
|
||||||
|
if (parts.includes('rated')) {
|
||||||
|
includeBy(p => (p.average_rating || 0) > 0);
|
||||||
|
}
|
||||||
|
if (parts.includes('commented')) {
|
||||||
|
// Query commented photo IDs
|
||||||
|
const commented = await db('photo_feedback')
|
||||||
|
.where({ event_id: req.event.id, feedback_type: 'comment', is_approved: true, is_hidden: false })
|
||||||
|
.groupBy('photo_id')
|
||||||
|
.select('photo_id');
|
||||||
|
const commentedIds = new Set(commented.map(c => c.photo_id));
|
||||||
|
includeBy(p => commentedIds.has(p.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (include.size > 0) {
|
||||||
|
photos = photos.filter(p => include.has(p.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get filtered photo IDs
|
|
||||||
const filteredPhotoIds = await feedbackService.getFilteredPhotos(
|
|
||||||
req.event.id,
|
|
||||||
guest_id,
|
|
||||||
filters
|
|
||||||
);
|
|
||||||
|
|
||||||
// Filter photos to only include those with feedback
|
|
||||||
photos = photos.filter(photo => filteredPhotoIds.includes(photo.id));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then get comment counts separately
|
// Then get comment counts separately
|
||||||
@@ -384,6 +393,87 @@ router.get('/:slug/download-all', verifyGalleryAccess, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Download selected photos as ZIP
|
||||||
|
router.post('/:slug/download-selected', verifyGalleryAccess, async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Check if downloads are allowed for this event
|
||||||
|
if (req.event.allow_downloads === false) {
|
||||||
|
return res.status(403).json({ error: 'Downloads are disabled for this gallery' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const ids = Array.isArray(req.body?.photo_ids) ? req.body.photo_ids : [];
|
||||||
|
if (!ids.length) {
|
||||||
|
return res.status(400).json({ error: 'photo_ids is required (non-empty array)' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean IDs
|
||||||
|
const photoIds = ids
|
||||||
|
.map((v) => parseInt(v, 10))
|
||||||
|
.filter((v) => Number.isInteger(v))
|
||||||
|
.slice(0, 500);
|
||||||
|
|
||||||
|
if (photoIds.length === 0) {
|
||||||
|
return res.status(400).json({ error: 'No valid photo IDs provided' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch photos
|
||||||
|
const photos = await db('photos')
|
||||||
|
.where('photos.event_id', req.event.id)
|
||||||
|
.whereIn('photos.id', photoIds)
|
||||||
|
.select('photos.*')
|
||||||
|
.orderBy('photos.uploaded_at', 'desc');
|
||||||
|
|
||||||
|
if (photos.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'No photos found for selected IDs' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const archiveName = `${req.event.slug}-selected.zip`;
|
||||||
|
res.setHeader('Content-Type', 'application/zip');
|
||||||
|
res.setHeader('Content-Disposition', `attachment; filename="${archiveName}"`);
|
||||||
|
|
||||||
|
const archive = archiver('zip', { zlib: { level: 5 } });
|
||||||
|
archive.on('error', (err) => {
|
||||||
|
console.error('Zip error:', err);
|
||||||
|
try { res.status(500).end(); } catch (e) {}
|
||||||
|
});
|
||||||
|
archive.pipe(res);
|
||||||
|
|
||||||
|
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||||
|
const fs = require('fs');
|
||||||
|
// Check watermark settings similar to download-all
|
||||||
|
const watermarkSettings = await watermarkService.getWatermarkSettings();
|
||||||
|
for (const photo of photos) {
|
||||||
|
try {
|
||||||
|
const filePath = resolvePhotoFilePath(req.event, photo);
|
||||||
|
if (filePath && fs.existsSync(filePath)) {
|
||||||
|
const name = photo.filename || `photo-${photo.id}.jpg`;
|
||||||
|
if (watermarkSettings && watermarkSettings.enabled) {
|
||||||
|
// Apply watermark like download-all
|
||||||
|
const watermarkedBuffer = await watermarkService.applyWatermark(filePath, watermarkSettings);
|
||||||
|
archive.append(watermarkedBuffer, { name });
|
||||||
|
} else {
|
||||||
|
archive.file(filePath, { name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// skip missing/inaccessible files
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await archive.finalize();
|
||||||
|
|
||||||
|
await db('access_logs').insert({
|
||||||
|
event_id: req.event.id,
|
||||||
|
ip_address: req.ip,
|
||||||
|
user_agent: req.headers['user-agent'],
|
||||||
|
action: 'download_selected'
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in download-selected:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to download selected photos' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
// View single photo (with watermark if enabled)
|
// View single photo (with watermark if enabled)
|
||||||
router.get('/:slug/photo/:photoId',
|
router.get('/:slug/photo/:photoId',
|
||||||
@@ -413,18 +503,9 @@ router.get('/:slug/photo/:photoId',
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Photo path should be in storage/events/active directory
|
// Resolve the absolute file path for this photo, supporting both managed and external reference modes
|
||||||
// Handle both legacy paths (just slug/filename) and new paths (events/active/slug/filename)
|
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||||
const storagePath = getStoragePath();
|
const filePath = resolvePhotoFilePath(req.event, photo);
|
||||||
|
|
||||||
let filePath;
|
|
||||||
if (photo.path.startsWith('events/active/')) {
|
|
||||||
// New format: path already includes events/active/ prefix
|
|
||||||
filePath = path.join(storagePath, photo.path);
|
|
||||||
} else {
|
|
||||||
// Legacy format: path is just slug/filename
|
|
||||||
filePath = path.join(storagePath, 'events/active', photo.path);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Log access - temporarily disabled for debugging
|
// Log access - temporarily disabled for debugging
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
const fs = require('fs').promises;
|
||||||
|
const path = require('path');
|
||||||
|
const { safePathJoin } = require('../utils/fileSecurityUtils');
|
||||||
|
|
||||||
|
function getExternalMediaRoot() {
|
||||||
|
return process.env.EXTERNAL_MEDIA_ROOT || '/external-media';
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUnderRoot(p) {
|
||||||
|
const root = path.resolve(getExternalMediaRoot());
|
||||||
|
const resolved = path.resolve(p);
|
||||||
|
return resolved === root || resolved.startsWith(root + path.sep);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function list(relativePath = '') {
|
||||||
|
const root = getExternalMediaRoot();
|
||||||
|
// Normalize and ensure safe join under root
|
||||||
|
const targetDir = safePathJoin(root, relativePath || '.');
|
||||||
|
|
||||||
|
const entries = [];
|
||||||
|
try {
|
||||||
|
const dirents = await fs.readdir(targetDir, { withFileTypes: true });
|
||||||
|
for (const d of dirents) {
|
||||||
|
// Skip hidden files and directories
|
||||||
|
if (d.name.startsWith('.')) continue;
|
||||||
|
const full = path.join(targetDir, d.name);
|
||||||
|
const stat = await fs.stat(full).catch(() => null);
|
||||||
|
if (!stat) continue;
|
||||||
|
|
||||||
|
if (d.isDirectory()) {
|
||||||
|
entries.push({ name: d.name, type: 'dir' });
|
||||||
|
} else if (d.isFile()) {
|
||||||
|
const ext = path.extname(d.name).toLowerCase();
|
||||||
|
if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
|
||||||
|
entries.push({ name: d.name, type: 'file', size: stat.size, mtime: stat.mtime });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Propagate errors for caller to handle (e.g., invalid path)
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rootResolved = path.resolve(root);
|
||||||
|
const currentResolved = path.resolve(targetDir);
|
||||||
|
const canNavigateUp = currentResolved !== rootResolved;
|
||||||
|
|
||||||
|
// Return normalized relative path from root
|
||||||
|
const relFromRoot = path.relative(rootResolved, currentResolved);
|
||||||
|
|
||||||
|
return { path: relFromRoot, entries, canNavigateUp };
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveExternalPath(event, relpath) {
|
||||||
|
const root = getExternalMediaRoot();
|
||||||
|
const base = event?.external_path ? path.join(event.external_path) : '';
|
||||||
|
const combined = base ? path.join(base, relpath || '') : (relpath || '');
|
||||||
|
return safePathJoin(root, combined);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getExternalMediaRoot,
|
||||||
|
isUnderRoot,
|
||||||
|
list,
|
||||||
|
resolveExternalPath,
|
||||||
|
};
|
||||||
|
|
||||||
@@ -132,7 +132,8 @@ async function generateThumbnail(imagePath, options = {}) {
|
|||||||
|
|
||||||
return path.relative(getStoragePath(), thumbnailPath);
|
return path.relative(getStoragePath(), thumbnailPath);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Failed to generate thumbnail for ${filename}:`, error.message);
|
const msg = (error && error.message) ? error.message : String(error);
|
||||||
|
logger.error(`Failed to generate thumbnail for ${filename}: ${msg}`);
|
||||||
|
|
||||||
// Clean up any partially created file
|
// Clean up any partially created file
|
||||||
try {
|
try {
|
||||||
@@ -171,8 +172,18 @@ async function isThumbnailValid(thumbnailPath) {
|
|||||||
* Regenerate thumbnail if it's broken or missing
|
* Regenerate thumbnail if it's broken or missing
|
||||||
*/
|
*/
|
||||||
async function ensureThumbnail(photo) {
|
async function ensureThumbnail(photo) {
|
||||||
const storagePath = getStoragePath();
|
const { db } = require('../database/db');
|
||||||
const originalPath = path.join(storagePath, 'events/active', photo.path);
|
const { resolvePhotoFilePath } = require('./photoResolver');
|
||||||
|
let originalPath;
|
||||||
|
try {
|
||||||
|
const event = await db('events').where('id', photo.event_id).first();
|
||||||
|
originalPath = resolvePhotoFilePath(event, photo);
|
||||||
|
logger.info(`Ensuring thumbnail for photo ${photo.id} from source: ${originalPath}`);
|
||||||
|
} catch (e) {
|
||||||
|
const msg = (e && e.message) ? e.message : String(e);
|
||||||
|
logger.error(`Failed to resolve original path for thumbnail (photo ${photo.id}): ${msg}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
// Check if thumbnail exists and is valid
|
// Check if thumbnail exists and is valid
|
||||||
if (photo.thumbnail_path) {
|
if (photo.thumbnail_path) {
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
const path = require('path');
|
||||||
|
const { resolveExternalPath } = require('./externalMediaService');
|
||||||
|
|
||||||
|
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve absolute photo file path based on event + photo origin
|
||||||
|
* Managed: storage/events/active + photo.path (legacy variants supported)
|
||||||
|
* External reference: EXTERNAL_MEDIA_ROOT + event.external_path + photo.external_relpath
|
||||||
|
*/
|
||||||
|
function resolvePhotoFilePath(event, photo) {
|
||||||
|
if (!event || !photo) throw new Error('resolvePhotoFilePath requires event and photo');
|
||||||
|
|
||||||
|
const mode = (event.source_mode || photo.source_origin || 'managed');
|
||||||
|
if (mode === 'reference' || photo.source_origin === 'external') {
|
||||||
|
if (!photo.external_relpath) {
|
||||||
|
throw new Error('Missing external_relpath for external photo');
|
||||||
|
}
|
||||||
|
// Normalize duplicate leaf segments (e.g., event.external_path ends with 'individual'
|
||||||
|
// and external_relpath starts with 'individual/') to avoid double segment like
|
||||||
|
// '/external-media/.../individual/individual/file.jpg'
|
||||||
|
let rel = photo.external_relpath;
|
||||||
|
try {
|
||||||
|
const lastSeg = path.basename(event.external_path || '');
|
||||||
|
const firstSeg = rel.split(path.sep)[0];
|
||||||
|
if (lastSeg && firstSeg && lastSeg === firstSeg) {
|
||||||
|
rel = rel.split(path.sep).slice(1).join(path.sep) || '';
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// ignore normalization errors
|
||||||
|
}
|
||||||
|
return resolveExternalPath(event, rel);
|
||||||
|
}
|
||||||
|
|
||||||
|
const storagePath = getStoragePath();
|
||||||
|
if (photo.path && photo.path.startsWith('events/active/')) {
|
||||||
|
return path.join(storagePath, photo.path);
|
||||||
|
}
|
||||||
|
return path.join(storagePath, 'events/active', photo.path || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
resolvePhotoFilePath,
|
||||||
|
};
|
||||||
+8
-1
@@ -11,6 +11,7 @@ services:
|
|||||||
- JWT_SECRET=${JWT_SECRET}
|
- JWT_SECRET=${JWT_SECRET}
|
||||||
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
|
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
|
||||||
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
||||||
|
- ADMIN_PASSWORD=${ADMIN_PASSWORD}
|
||||||
- DATABASE_CLIENT=pg
|
- DATABASE_CLIENT=pg
|
||||||
- DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
|
- DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
|
||||||
- DB_TYPE=postgresql
|
- DB_TYPE=postgresql
|
||||||
@@ -19,6 +20,7 @@ services:
|
|||||||
- DB_USER=${DB_USER}
|
- DB_USER=${DB_USER}
|
||||||
- DB_PASSWORD=${DB_PASSWORD}
|
- DB_PASSWORD=${DB_PASSWORD}
|
||||||
- DB_NAME=${DB_NAME}
|
- DB_NAME=${DB_NAME}
|
||||||
|
- EXTERNAL_MEDIA_ROOT=${EXTERNAL_MEDIA_ROOT:-/app/storage/external-media}
|
||||||
- SMTP_HOST=${SMTP_HOST}
|
- SMTP_HOST=${SMTP_HOST}
|
||||||
- SMTP_PORT=${SMTP_PORT}
|
- SMTP_PORT=${SMTP_PORT}
|
||||||
- SMTP_SECURE=${SMTP_SECURE:-false}
|
- SMTP_SECURE=${SMTP_SECURE:-false}
|
||||||
@@ -29,6 +31,11 @@ services:
|
|||||||
- ADMIN_URL=${ADMIN_URL:-http://localhost:3001}
|
- ADMIN_URL=${ADMIN_URL:-http://localhost:3001}
|
||||||
- TZ=${TZ:-UTC}
|
- TZ=${TZ:-UTC}
|
||||||
- STORAGE_PATH=/app/storage
|
- STORAGE_PATH=/app/storage
|
||||||
|
# Optional: run container as matching host user to avoid bind mount permission issues
|
||||||
|
- PUID=${PUID:-1001}
|
||||||
|
- PGID=${PGID:-1001}
|
||||||
|
# Use host-matching user ID/GID so bind-mounted folders are writable
|
||||||
|
user: "${PUID:-1001}:${PGID:-1001}"
|
||||||
volumes:
|
volumes:
|
||||||
- ./events:/app/events
|
- ./events:/app/events
|
||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
@@ -122,4 +129,4 @@ volumes:
|
|||||||
|
|
||||||
networks:
|
networks:
|
||||||
picpeak-network:
|
picpeak-network:
|
||||||
driver: bridge
|
driver: bridge
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-frontend",
|
"name": "picpeak-frontend",
|
||||||
"version": "1.0.109",
|
"version": "1.0.127",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "picpeak-frontend",
|
"name": "picpeak-frontend",
|
||||||
"version": "1.0.109",
|
"version": "1.0.127",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tanstack/react-query": "^5.0.0",
|
"@tanstack/react-query": "^5.0.0",
|
||||||
"@tiptap/extension-character-count": "^2.26.1",
|
"@tiptap/extension-character-count": "^2.26.1",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-frontend",
|
"name": "picpeak-frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.0.109",
|
"version": "1.0.127",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -71,35 +71,29 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
|||||||
<header className="sticky top-0 z-30 bg-white border-b border-neutral-200">
|
<header className="sticky top-0 z-30 bg-white border-b border-neutral-200">
|
||||||
<div className="px-4 sm:px-6 lg:px-8">
|
<div className="px-4 sm:px-6 lg:px-8">
|
||||||
<div className="flex items-center justify-between h-16">
|
<div className="flex items-center justify-between h-16">
|
||||||
{/* Left side - Menu button and Date */}
|
{/* Left side - Menu button, Logo, and Date */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3 min-w-0">
|
||||||
<button
|
<button
|
||||||
onClick={onMenuClick}
|
onClick={onMenuClick}
|
||||||
className="lg:hidden text-neutral-500 hover:text-neutral-700"
|
className="lg:hidden text-neutral-500 hover:text-neutral-700"
|
||||||
>
|
>
|
||||||
<Menu className="w-6 h-6" />
|
<Menu className="w-6 h-6" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Date display - hidden on small screens */}
|
{/* PicPeak logo - sticky to the left on all sizes */}
|
||||||
<div className="hidden xl:block">
|
<div className="flex items-center gap-2">
|
||||||
|
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-8 w-auto object-contain" />
|
||||||
|
<span className="text-xl sm:text-2xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Date display - hidden on smaller screens */}
|
||||||
|
<div className="hidden xl:block pl-3 border-l border-neutral-200 ml-1">
|
||||||
<p className="text-base text-neutral-700">
|
<p className="text-base text-neutral-700">
|
||||||
{format(new Date(), 'PPPP')}
|
{format(new Date(), 'PPPP')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Center - Logo and PicPeak text - hidden on small screens to prevent overlap */}
|
|
||||||
<div className="hidden lg:flex absolute left-1/2 transform -translate-x-1/2 items-center gap-3">
|
|
||||||
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-10 w-auto object-contain" />
|
|
||||||
<span className="text-2xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Mobile Logo - shown only on small screens */}
|
|
||||||
<div className="flex lg:hidden items-center gap-2 mx-auto">
|
|
||||||
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-8 w-auto object-contain" />
|
|
||||||
<span className="text-xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right side actions */}
|
{/* Right side actions */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
{/* Language Selector */}
|
{/* Language Selector */}
|
||||||
@@ -253,4 +247,4 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
|||||||
/>
|
/>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -29,7 +29,10 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
if (e) {
|
if (e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
}
|
}
|
||||||
|
// Auto-enable selection mode when selecting via checkbox
|
||||||
|
if (!isSelectionMode) {
|
||||||
|
setIsSelectionMode(true);
|
||||||
|
}
|
||||||
const newSelected = new Set(selectedPhotos);
|
const newSelected = new Set(selectedPhotos);
|
||||||
if (newSelected.has(photoId)) {
|
if (newSelected.has(photoId)) {
|
||||||
newSelected.delete(photoId);
|
newSelected.delete(photoId);
|
||||||
@@ -126,7 +129,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
{isSelectionMode ? 'Cancel Selection' : 'Select Photos'}
|
{isSelectionMode ? 'Cancel Selection' : 'Select Photos'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{(isSelectionMode || selectedPhotos.size > 0) && (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -167,25 +170,32 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
|
data-testid={`admin-photo-tile-${photo.id}`}
|
||||||
className={`relative group cursor-pointer rounded-lg overflow-hidden bg-neutral-100 transition-opacity ${
|
className={`relative group cursor-pointer rounded-lg overflow-hidden bg-neutral-100 transition-opacity ${
|
||||||
isSelectionMode ? 'ring-2 ring-offset-2 ' + (selectedPhotos.has(photo.id) ? 'ring-primary-500' : 'ring-transparent') : ''
|
isSelectionMode ? 'ring-2 ring-offset-2 ' + (selectedPhotos.has(photo.id) ? 'ring-primary-500' : 'ring-transparent') : ''
|
||||||
} ${isDeleting ? 'opacity-50' : ''}`}
|
} ${isDeleting ? 'opacity-50' : ''}`}
|
||||||
onClick={() => !isDeleting && (isSelectionMode ? handlePhotoSelect(photo.id) : onPhotoClick(photo, index))}
|
onClick={() => !isDeleting && onPhotoClick(photo, index)}
|
||||||
>
|
>
|
||||||
{/* Selection Checkbox */}
|
{/* Selection Checkbox (top-right) */}
|
||||||
{isSelectionMode && (
|
<button
|
||||||
<div className="absolute top-2 left-2 z-10">
|
type="button"
|
||||||
<div className={`w-6 h-6 rounded border-2 flex items-center justify-center ${
|
aria-label={`Select ${photo.filename}`}
|
||||||
selectedPhotos.has(photo.id)
|
role="checkbox"
|
||||||
? 'bg-primary-500 border-primary-500'
|
aria-checked={selectedPhotos.has(photo.id)}
|
||||||
: 'bg-white/80 border-neutral-300'
|
data-testid={`admin-photo-checkbox-${photo.id}`}
|
||||||
}`}>
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
{selectedPhotos.has(photo.id) && (
|
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
<Check className="w-4 h-4 text-white" />
|
}`}
|
||||||
)}
|
onClick={(e) => handlePhotoSelect(photo.id, e)}
|
||||||
</div>
|
>
|
||||||
|
<div className={`w-6 h-6 rounded border-2 flex items-center justify-center ${
|
||||||
|
selectedPhotos.has(photo.id)
|
||||||
|
? 'bg-primary-600 border-primary-600'
|
||||||
|
: 'bg-white/90 border-white'
|
||||||
|
}`}>
|
||||||
|
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</button>
|
||||||
|
|
||||||
{/* Thumbnail */}
|
{/* Thumbnail */}
|
||||||
<div className="aspect-square">
|
<div className="aspect-square">
|
||||||
@@ -238,30 +248,30 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Category Badge */}
|
{/* Category Badge - move to top-left and prevent overlap with select checkbox */}
|
||||||
{photo.category_name && (
|
{photo.category_name && (
|
||||||
<div className="absolute top-2 right-2">
|
<div className="absolute left-2 top-2 pointer-events-none">
|
||||||
<span className="px-2 py-1 text-xs font-medium bg-white/90 text-neutral-700 rounded">
|
<span className="px-2 py-1 text-xs font-medium bg-white/90 text-neutral-700 rounded max-w-[70%] whitespace-nowrap overflow-hidden text-ellipsis">
|
||||||
{photo.category_name}
|
{photo.category_name}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Feedback Indicators */}
|
{/* Feedback Indicators (moved to bottom-right to avoid covering category) */}
|
||||||
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
||||||
<div className="absolute top-2 left-2 flex gap-1 z-10" style={{ left: isSelectionMode ? '40px' : '8px' }}>
|
<div className="absolute bottom-2 right-2 flex items-center gap-1 z-10">
|
||||||
{photo.comment_count > 0 && (
|
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
|
||||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
|
||||||
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{photo.average_rating > 0 && (
|
{photo.average_rating > 0 && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
||||||
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{photo.comment_count > 0 && (
|
||||||
|
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||||
|
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -276,4 +286,4 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { parseISO } from 'date-fns';
|
|||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
import { Card, Loading, Button } from '../common';
|
import { Card, Loading, Button } from '../common';
|
||||||
|
import { AdminAuthenticatedImage } from './AdminAuthenticatedImage';
|
||||||
import { feedbackService } from '../../services/feedback.service';
|
import { feedbackService } from '../../services/feedback.service';
|
||||||
import { useLocalizedDate } from '../../hooks/useLocalizedDate';
|
import { useLocalizedDate } from '../../hooks/useLocalizedDate';
|
||||||
|
|
||||||
@@ -129,15 +130,13 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
|
|||||||
<p className="mt-1 text-sm text-neutral-700">{item.comment_text || item.comment}</p>
|
<p className="mt-1 text-sm text-neutral-700">{item.comment_text || item.comment}</p>
|
||||||
{item.photo_id && (
|
{item.photo_id && (
|
||||||
<div className="mt-2 flex items-center gap-2">
|
<div className="mt-2 flex items-center gap-2">
|
||||||
<img
|
<div className="w-16 h-16 overflow-hidden rounded">
|
||||||
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
<AdminAuthenticatedImage
|
||||||
alt={item.filename || 'Photo'}
|
src={`/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
||||||
className="w-16 h-16 object-cover rounded"
|
alt={item.filename || 'Photo'}
|
||||||
onError={(e) => {
|
className="w-16 h-16 object-cover rounded"
|
||||||
// Hide image if thumbnail fails to load
|
/>
|
||||||
(e.target as HTMLImageElement).style.display = 'none';
|
</div>
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-neutral-500">
|
<p className="text-xs text-neutral-500">
|
||||||
{t('feedback.onPhoto', 'On photo')}: {item.filename || item.photo_filename || `#${item.photo_id}`}
|
{t('feedback.onPhoto', 'On photo')}: {item.filename || item.photo_filename || `#${item.photo_id}`}
|
||||||
</p>
|
</p>
|
||||||
@@ -218,4 +217,4 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
FeedbackModerationPanel.displayName = 'FeedbackModerationPanel';
|
FeedbackModerationPanel.displayName = 'FeedbackModerationPanel';
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Heart, Star } from 'lucide-react';
|
import { Heart, Star, MessageSquare } from 'lucide-react';
|
||||||
import { Button } from '../common';
|
import { Button } from '../common';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
export type FilterType = 'all' | 'liked' | 'favorited';
|
export type FilterType = 'all' | 'liked' | 'rated' | 'commented';
|
||||||
|
|
||||||
interface GalleryFilterProps {
|
interface GalleryFilterProps {
|
||||||
currentFilter: FilterType;
|
currentFilter: FilterType;
|
||||||
onFilterChange: (filter: FilterType) => void;
|
onFilterChange: (filter: FilterType) => void;
|
||||||
feedbackEnabled: boolean;
|
feedbackEnabled: boolean;
|
||||||
likeCount?: number;
|
likeCount?: number;
|
||||||
favoriteCount?: number;
|
ratedCount?: number;
|
||||||
className?: string;
|
className?: string;
|
||||||
isMobile?: boolean;
|
isMobile?: boolean;
|
||||||
|
variant?: 'default' | 'compact';
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||||
@@ -20,9 +21,10 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
onFilterChange,
|
onFilterChange,
|
||||||
feedbackEnabled,
|
feedbackEnabled,
|
||||||
likeCount = 0,
|
likeCount = 0,
|
||||||
favoriteCount = 0,
|
ratedCount = 0,
|
||||||
className = '',
|
className = '',
|
||||||
isMobile = false
|
isMobile = false,
|
||||||
|
variant = 'default'
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
@@ -30,6 +32,57 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Compact icon-only vertical variant (used in sidebar and tight spaces)
|
||||||
|
if (variant === 'compact') {
|
||||||
|
return (
|
||||||
|
<div className={`${className}`}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm text-neutral-700 whitespace-nowrap">
|
||||||
|
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('all')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.all', 'All')}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-current"><path d="M3 3h8v8H3V3zm10 0h8v8h-8V3zM3 13h8v8H3v-8zm10 8v-8h8v8h-8z"/></svg>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('liked')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('feedback.likes', 'Likes')}
|
||||||
|
>
|
||||||
|
<Heart className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('rated')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.rated', 'Rated')}
|
||||||
|
>
|
||||||
|
<Star className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.commented', 'Commented')}
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`${className}`}>
|
<div className={`${className}`}>
|
||||||
{/* Mobile-optimized vertical layout */}
|
{/* Mobile-optimized vertical layout */}
|
||||||
@@ -59,13 +112,13 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('favorited')}
|
onClick={() => onFilterChange('rated')}
|
||||||
className="text-xs flex-1 min-w-[80px] flex items-center justify-center gap-1"
|
className="text-xs flex-1 min-w-[80px] flex items-center justify-center gap-1"
|
||||||
>
|
>
|
||||||
<Star className="w-3 h-3" />
|
<Star className="w-3 h-3" />
|
||||||
<span>{favoriteCount > 0 ? favoriteCount : t('gallery.favorites', 'Favorites')}</span>
|
<span>{ratedCount > 0 ? ratedCount : t('gallery.rated', 'Rated')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -101,22 +154,32 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('favorited')}
|
onClick={() => onFilterChange('rated')}
|
||||||
className="text-xs sm:text-sm flex items-center gap-1"
|
className="text-xs sm:text-sm flex items-center gap-1"
|
||||||
>
|
>
|
||||||
<Star className="w-3 h-3 sm:w-4 sm:h-4" />
|
<Star className="w-3 h-3 sm:w-4 sm:h-4" />
|
||||||
<span className="hidden sm:inline">{t('gallery.favorited', 'Favorites')}</span>
|
<span className="hidden sm:inline">{t('gallery.rated', 'Rated')}</span>
|
||||||
{favoriteCount > 0 && (
|
{ratedCount > 0 && (
|
||||||
<span className="bg-primary-100 text-primary-700 px-1.5 rounded">
|
<span className="bg-primary-100 text-primary-700 px-1.5 rounded">
|
||||||
{favoriteCount}
|
{ratedCount}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="text-xs sm:text-sm flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3 h-3 sm:w-4 sm:h-4" />
|
||||||
|
<span className="hidden sm:inline">{t('gallery.commented', 'Commented')}</span>
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ interface GallerySidebarProps {
|
|||||||
filterType?: FilterType;
|
filterType?: FilterType;
|
||||||
onFilterChange?: (filter: FilterType) => void;
|
onFilterChange?: (filter: FilterType) => void;
|
||||||
likeCount?: number;
|
likeCount?: number;
|
||||||
favoriteCount?: number;
|
ratedCount?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||||
@@ -64,7 +64,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
|||||||
filterType = 'all',
|
filterType = 'all',
|
||||||
onFilterChange,
|
onFilterChange,
|
||||||
likeCount = 0,
|
likeCount = 0,
|
||||||
favoriteCount = 0
|
ratedCount = 0
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const sidebarRef = useRef<HTMLDivElement>(null);
|
const sidebarRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -114,7 +114,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
|||||||
<div
|
<div
|
||||||
ref={sidebarRef}
|
ref={sidebarRef}
|
||||||
className={`
|
className={`
|
||||||
fixed top-0 left-0 h-full bg-white shadow-xl z-50 transition-transform duration-300 ease-in-out
|
fixed top-0 left-0 h-full bg-white shadow-xl z-50 transition-transform duration-300 ease-in-out flex flex-col
|
||||||
${isMobile ? 'w-full max-w-sm' : 'w-80'}
|
${isMobile ? 'w-full max-w-sm' : 'w-80'}
|
||||||
${isOpen ? 'translate-x-0' : '-translate-x-full'}
|
${isOpen ? 'translate-x-0' : '-translate-x-full'}
|
||||||
`}
|
`}
|
||||||
@@ -223,8 +223,9 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
|||||||
}}
|
}}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
likeCount={likeCount}
|
likeCount={likeCount}
|
||||||
favoriteCount={favoriteCount}
|
ratedCount={ratedCount}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
variant="compact"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -328,4 +329,4 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
|||||||
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { Upload, Menu } from 'lucide-react';
|
|||||||
import { galleryService } from '../../services/gallery.service';
|
import { galleryService } from '../../services/gallery.service';
|
||||||
import { feedbackService } from '../../services/feedback.service';
|
import { feedbackService } from '../../services/feedback.service';
|
||||||
import { useWatermarkSettings } from '../../hooks/useWatermarkSettings';
|
import { useWatermarkSettings } from '../../hooks/useWatermarkSettings';
|
||||||
|
import type { Photo } from '../../types';
|
||||||
|
|
||||||
interface GalleryViewProps {
|
interface GalleryViewProps {
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -58,6 +59,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
const [protectionLevel, setProtectionLevel] = useState<'basic' | 'standard' | 'enhanced' | 'maximum'>('standard');
|
const [protectionLevel, setProtectionLevel] = useState<'basic' | 'standard' | 'enhanced' | 'maximum'>('standard');
|
||||||
const [filterType, setFilterType] = useState<FilterType>('all');
|
const [filterType, setFilterType] = useState<FilterType>('all');
|
||||||
const [guestId, setGuestId] = useState<string>('');
|
const [guestId, setGuestId] = useState<string>('');
|
||||||
|
const [staticHeroPhoto, setStaticHeroPhoto] = useState<Photo | null>(null);
|
||||||
|
|
||||||
// Generate a unique guest ID for this session
|
// Generate a unique guest ID for this session
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -167,6 +169,23 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
}
|
}
|
||||||
}, [settingsData]);
|
}, [settingsData]);
|
||||||
|
|
||||||
|
// Determine a stable hero photo from the initial (unfiltered) load
|
||||||
|
useEffect(() => {
|
||||||
|
if (!staticHeroPhoto && data?.photos && filterType === 'all') {
|
||||||
|
let hero: Photo | null = null;
|
||||||
|
const heroId = data?.event?.hero_photo_id || null;
|
||||||
|
if (heroId) {
|
||||||
|
hero = data.photos.find(p => p.id === heroId) || null;
|
||||||
|
}
|
||||||
|
if (!hero && data.photos.length > 0) {
|
||||||
|
hero = data.photos[0];
|
||||||
|
}
|
||||||
|
if (hero) {
|
||||||
|
setStaticHeroPhoto(hero);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [data?.photos, data?.event?.hero_photo_id, filterType, staticHeroPhoto]);
|
||||||
|
|
||||||
// Apply theme when settings are loaded
|
// Apply theme when settings are loaded
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (settingsData && data?.event) {
|
if (settingsData && data?.event) {
|
||||||
@@ -247,6 +266,21 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Apply feedback filter
|
||||||
|
switch (filterType) {
|
||||||
|
case 'liked':
|
||||||
|
photos = photos.filter(photo => (photo.like_count || 0) > 0);
|
||||||
|
break;
|
||||||
|
case 'rated':
|
||||||
|
photos = photos.filter(photo => (photo.average_rating || 0) > 0 || (photo.total_ratings || 0) > 0);
|
||||||
|
break;
|
||||||
|
case 'commented':
|
||||||
|
photos = photos.filter(photo => (photo.comment_count || 0) > 0);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// Apply sorting
|
// Apply sorting
|
||||||
photos.sort((a, b) => {
|
photos.sort((a, b) => {
|
||||||
switch (sortBy) {
|
switch (sortBy) {
|
||||||
@@ -279,7 +313,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return photos;
|
return photos;
|
||||||
}, [data?.photos, selectedCategoryId, searchTerm, sortBy, watermarkEnabled, slug]);
|
}, [data?.photos, selectedCategoryId, searchTerm, sortBy, watermarkEnabled, slug, filterType]);
|
||||||
|
|
||||||
// Check if downloads are allowed (both event setting and not expired)
|
// Check if downloads are allowed (both event setting and not expired)
|
||||||
const allowDownloads = !isExpired && (data?.event?.allow_downloads === true);
|
const allowDownloads = !isExpired && (data?.event?.allow_downloads === true);
|
||||||
@@ -440,7 +474,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
filterType={filterType}
|
filterType={filterType}
|
||||||
onFilterChange={setFilterType}
|
onFilterChange={setFilterType}
|
||||||
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
||||||
favoriteCount={data?.photos?.filter(p => p.favorite_count > 0).length || 0}
|
ratedCount={data?.photos?.filter(p => (p.total_ratings || 0) > 0).length || 0}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -531,8 +565,6 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
currentFilter={filterType}
|
currentFilter={filterType}
|
||||||
onFilterChange={setFilterType}
|
onFilterChange={setFilterType}
|
||||||
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
|
||||||
favoriteCount={data?.photos?.filter(p => p.favorite_count > 0).length || 0}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -543,7 +575,16 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
photos={filteredPhotos}
|
photos={filteredPhotos}
|
||||||
slug={slug}
|
slug={slug}
|
||||||
categoryId={selectedCategoryId}
|
categoryId={selectedCategoryId}
|
||||||
|
onFeedbackChange={() => refetch()}
|
||||||
|
heroPhotoOverride={staticHeroPhoto}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={{
|
||||||
|
allowLikes: !!feedbackSettings?.allow_likes,
|
||||||
|
allowFavorites: !!feedbackSettings?.allow_favorites,
|
||||||
|
allowRatings: !!feedbackSettings?.allow_ratings,
|
||||||
|
allowComments: !!feedbackSettings?.allow_comments,
|
||||||
|
requireNameEmail: !!feedbackSettings?.require_name_email,
|
||||||
|
}}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
selectedPhotos={selectedPhotos}
|
selectedPhotos={selectedPhotos}
|
||||||
onSelectionChange={setSelectedPhotos}
|
onSelectionChange={setSelectedPhotos}
|
||||||
@@ -575,4 +616,4 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
</GalleryLayout>
|
</GalleryLayout>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { feedbackService } from '../../services/feedback.service';
|
|||||||
import { PhotoRating } from './PhotoRating';
|
import { PhotoRating } from './PhotoRating';
|
||||||
import { PhotoLikes } from './PhotoLikes';
|
import { PhotoLikes } from './PhotoLikes';
|
||||||
import { PhotoComments } from './PhotoComments';
|
import { PhotoComments } from './PhotoComments';
|
||||||
import { PhotoFavorites } from './PhotoFavorites';
|
|
||||||
import { Skeleton } from '../common';
|
import { Skeleton } from '../common';
|
||||||
import type { FeedbackSettings } from '../../services/feedback.service';
|
import type { FeedbackSettings } from '../../services/feedback.service';
|
||||||
|
|
||||||
@@ -43,18 +42,14 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
// Local state for optimistic updates
|
// Local state for optimistic updates
|
||||||
const [currentRating, setCurrentRating] = useState(0);
|
const [currentRating, setCurrentRating] = useState(0);
|
||||||
const [isLiked, setIsLiked] = useState(false);
|
const [isLiked, setIsLiked] = useState(false);
|
||||||
const [isFavorited, setIsFavorited] = useState(false);
|
|
||||||
const [likeCount, setLikeCount] = useState(0);
|
const [likeCount, setLikeCount] = useState(0);
|
||||||
const [favoriteCount, setFavoriteCount] = useState(0);
|
|
||||||
|
|
||||||
// Update local state when data loads
|
// Update local state when data loads
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (feedbackData) {
|
if (feedbackData) {
|
||||||
setCurrentRating(feedbackData.my_feedback.rating || 0);
|
setCurrentRating(feedbackData.my_feedback.rating || 0);
|
||||||
setIsLiked(feedbackData.my_feedback.liked);
|
setIsLiked(feedbackData.my_feedback.liked);
|
||||||
setIsFavorited(feedbackData.my_feedback.favorited);
|
|
||||||
setLikeCount(feedbackData.summary.like_count);
|
setLikeCount(feedbackData.summary.like_count);
|
||||||
setFavoriteCount(feedbackData.summary.favorite_count);
|
|
||||||
}
|
}
|
||||||
}, [feedbackData]);
|
}, [feedbackData]);
|
||||||
|
|
||||||
@@ -70,12 +65,6 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
if (onFeedbackUpdate) onFeedbackUpdate();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleFavoriteChange = (favorited: boolean) => {
|
|
||||||
setIsFavorited(favorited);
|
|
||||||
setFavoriteCount(prev => favorited ? prev + 1 : Math.max(0, prev - 1));
|
|
||||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
|
||||||
};
|
|
||||||
|
|
||||||
if (settingsLoading) {
|
if (settingsLoading) {
|
||||||
return (
|
return (
|
||||||
<div className={`space-y-3 ${className}`}>
|
<div className={`space-y-3 ${className}`}>
|
||||||
@@ -90,7 +79,7 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const hasAnyFeedbackType = settings.allow_ratings || settings.allow_likes ||
|
const hasAnyFeedbackType = settings.allow_ratings || settings.allow_likes ||
|
||||||
settings.allow_comments || settings.allow_favorites;
|
settings.allow_comments;
|
||||||
|
|
||||||
if (!hasAnyFeedbackType) {
|
if (!hasAnyFeedbackType) {
|
||||||
return null;
|
return null;
|
||||||
@@ -113,7 +102,7 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Action Buttons */}
|
{/* Action Buttons */}
|
||||||
{(settings.allow_likes || settings.allow_favorites) && (
|
{settings.allow_likes && (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{settings.allow_likes && (
|
{settings.allow_likes && (
|
||||||
<PhotoLikes
|
<PhotoLikes
|
||||||
@@ -126,17 +115,6 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
onLikeChange={handleLikeChange}
|
onLikeChange={handleLikeChange}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{settings.allow_favorites && (
|
|
||||||
<PhotoFavorites
|
|
||||||
photoId={photoId}
|
|
||||||
gallerySlug={gallerySlug}
|
|
||||||
isFavorited={isFavorited}
|
|
||||||
favoriteCount={favoriteCount}
|
|
||||||
isEnabled={true}
|
|
||||||
requireNameEmail={settings.require_name_email || false}
|
|
||||||
onFavoriteChange={handleFavoriteChange}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -158,4 +136,4 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Search, SortAsc, Grid, Heart, Star } from 'lucide-react';
|
import { Search, SortAsc, Grid, Heart, Star, MessageSquare } from 'lucide-react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Button, Input } from '../common';
|
import { Button, Input } from '../common';
|
||||||
import type { FilterType } from './GalleryFilter';
|
import type { FilterType } from './GalleryFilter';
|
||||||
@@ -32,8 +32,6 @@ interface PhotoFilterBarProps {
|
|||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
currentFilter?: FilterType;
|
currentFilter?: FilterType;
|
||||||
onFilterChange?: (filter: FilterType) => void;
|
onFilterChange?: (filter: FilterType) => void;
|
||||||
likeCount?: number;
|
|
||||||
favoriteCount?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||||
@@ -49,8 +47,6 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
|||||||
feedbackEnabled = false,
|
feedbackEnabled = false,
|
||||||
currentFilter = 'all',
|
currentFilter = 'all',
|
||||||
onFilterChange,
|
onFilterChange,
|
||||||
likeCount = 0,
|
|
||||||
favoriteCount = 0,
|
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [showSortMenu, setShowSortMenu] = useState(false);
|
const [showSortMenu, setShowSortMenu] = useState(false);
|
||||||
@@ -143,6 +139,7 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
|||||||
{/* Categories Row */}
|
{/* Categories Row */}
|
||||||
{categories && categories.length > 0 && (
|
{categories && categories.length > 0 && (
|
||||||
<div className="flex items-start lg:items-center justify-between flex-col lg:flex-row gap-3">
|
<div className="flex items-start lg:items-center justify-between flex-col lg:flex-row gap-3">
|
||||||
|
{/* Categories: keep in a horizontal scroll container */}
|
||||||
<div className="w-full overflow-x-auto pb-2 lg:pb-0">
|
<div className="w-full overflow-x-auto pb-2 lg:pb-0">
|
||||||
<div className="flex items-center gap-2 min-w-max">
|
<div className="flex items-center gap-2 min-w-max">
|
||||||
<Button
|
<Button
|
||||||
@@ -170,81 +167,104 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{/* Feedback Filter - Inline on desktop, below on mobile/tablet */}
|
|
||||||
{feedbackEnabled && onFilterChange && (
|
|
||||||
<>
|
|
||||||
{/* Desktop: Divider and inline filter - only on larger screens */}
|
|
||||||
<div className="hidden lg:flex items-center gap-2 ml-2 pl-2 border-l border-neutral-300">
|
|
||||||
<span className="text-sm text-neutral-600 whitespace-nowrap">{t('gallery.feedbackFilter')}:</span>
|
|
||||||
<Button
|
|
||||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => onFilterChange('all')}
|
|
||||||
className="text-xs sm:text-sm"
|
|
||||||
>
|
|
||||||
{t('gallery.all')}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => onFilterChange('liked')}
|
|
||||||
className="text-xs sm:text-sm flex items-center gap-1"
|
|
||||||
>
|
|
||||||
<Heart className="w-3 h-3" />
|
|
||||||
{likeCount > 0 && <span>{likeCount}</span>}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => onFilterChange('favorited')}
|
|
||||||
className="text-xs sm:text-sm flex items-center gap-1"
|
|
||||||
>
|
|
||||||
<Star className="w-3 h-3" />
|
|
||||||
{favoriteCount > 0 && <span>{favoriteCount}</span>}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Desktop: compact horizontal feedback filter with headline (icons only) */}
|
||||||
|
{feedbackEnabled && onFilterChange && (
|
||||||
|
<div className="hidden lg:flex items-center gap-2 mx-2 flex-shrink-0">
|
||||||
|
<span className="text-sm text-neutral-600 whitespace-nowrap">
|
||||||
|
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('all')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.all', 'All')}
|
||||||
|
>
|
||||||
|
<Grid className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('liked')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('feedback.likes', 'Likes')}
|
||||||
|
>
|
||||||
|
<Heart className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('rated')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.rated', 'Rated')}
|
||||||
|
>
|
||||||
|
<Star className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.commented', 'Commented')}
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<p className="text-xs md:text-sm text-neutral-600 flex-shrink-0 ml-auto">
|
<p className="text-xs md:text-sm text-neutral-600 flex-shrink-0 ml-auto">
|
||||||
{photoCount} {photoCount === 1 ? t('common.photo') : t('common.photos')}
|
{photoCount} {photoCount === 1 ? t('common.photo') : t('common.photos')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Mobile/Tablet: Feedback Filter below categories */}
|
{/* Mobile/Tablet: compact horizontal icons with headline below categories */}
|
||||||
{feedbackEnabled && onFilterChange && (
|
{feedbackEnabled && onFilterChange && (
|
||||||
<div className="flex lg:hidden items-center gap-2">
|
<div className="flex lg:hidden items-center gap-2">
|
||||||
<span className="text-xs text-neutral-600">{t('gallery.feedbackFilter')}:</span>
|
<span className="text-xs text-neutral-600 whitespace-nowrap">
|
||||||
<div className="flex gap-1 flex-1">
|
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('all')}
|
onClick={() => onFilterChange('all')}
|
||||||
className="text-xs flex-1"
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.all', 'All')}
|
||||||
>
|
>
|
||||||
{t('gallery.all')}
|
<Grid className="w-3.5 h-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('liked')}
|
onClick={() => onFilterChange('liked')}
|
||||||
className="text-xs flex-1 flex items-center justify-center gap-1"
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('feedback.likes', 'Likes')}
|
||||||
>
|
>
|
||||||
<Heart className="w-3 h-3" />
|
<Heart className="w-3.5 h-3.5" />
|
||||||
{likeCount > 0 && <span>{likeCount}</span>}
|
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('favorited')}
|
onClick={() => onFilterChange('rated')}
|
||||||
className="text-xs flex-1 flex items-center justify-center gap-1"
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.rated', 'Rated')}
|
||||||
>
|
>
|
||||||
<Star className="w-3 h-3" />
|
<Star className="w-3.5 h-3.5" />
|
||||||
{favoriteCount > 0 && <span>{favoriteCount}</span>}
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.commented', 'Commented')}
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -254,4 +274,4 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
PhotoFilterBar.displayName = 'PhotoFilterBar';
|
PhotoFilterBar.displayName = 'PhotoFilterBar';
|
||||||
|
|||||||
@@ -95,35 +95,17 @@ export const PhotoGrid: React.FC<PhotoGridProps> = ({
|
|||||||
|
|
||||||
const handleDownloadSelected = async () => {
|
const handleDownloadSelected = async () => {
|
||||||
if (selectedPhotos.size === 0) return;
|
if (selectedPhotos.size === 0) return;
|
||||||
|
const ids = Array.from(selectedPhotos);
|
||||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||||
|
|
||||||
toastify.info(t('gallery.downloading', { count: selectedPhotos.size }));
|
|
||||||
|
|
||||||
// Download each selected photo
|
|
||||||
const downloadPromises = selectedPhotosList.map(photo =>
|
|
||||||
galleryService.downloadPhoto(slug, photo.id, photo.filename)
|
|
||||||
.catch(err => {
|
|
||||||
// Download failed - error handled by UI
|
|
||||||
return null;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all(downloadPromises);
|
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||||
|
|
||||||
// Track bulk download
|
|
||||||
analyticsService.trackGalleryEvent('bulk_download', {
|
|
||||||
gallery: slug,
|
|
||||||
photo_count: selectedPhotos.size
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clear selection after download
|
|
||||||
setSelectedPhotos(new Set());
|
|
||||||
setIsSelectionMode(false);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastify.error(t('gallery.downloadError'));
|
toastify.error(t('gallery.downloadError'));
|
||||||
|
} finally {
|
||||||
|
setSelectedPhotos(new Set());
|
||||||
|
setIsSelectionMode(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -316,7 +298,7 @@ const PhotoThumbnail: React.FC<PhotoThumbnailProps> = ({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Overlay on hover/tap - Always visible on mobile for better UX */}
|
{/* Overlay on hover/tap - Always visible on mobile for better UX */}
|
||||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
<div className="absolute inset-0 bg-black/40 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||||
{!isSelectionMode && (
|
{!isSelectionMode && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
@@ -365,4 +347,4 @@ const PhotoThumbnail: React.FC<PhotoThumbnailProps> = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ interface PhotoGridWithLayoutsProps {
|
|||||||
photos: Photo[];
|
photos: Photo[];
|
||||||
slug: string;
|
slug: string;
|
||||||
categoryId?: number | null;
|
categoryId?: number | null;
|
||||||
|
// When provided, the hero layout will use this photo
|
||||||
|
// instead of deriving from the filtered photo list.
|
||||||
|
heroPhotoOverride?: Photo | null;
|
||||||
isSelectionMode?: boolean;
|
isSelectionMode?: boolean;
|
||||||
selectedPhotos?: Set<number>;
|
selectedPhotos?: Set<number>;
|
||||||
onSelectionChange?: (photos: Set<number>) => void;
|
onSelectionChange?: (photos: Set<number>) => void;
|
||||||
@@ -38,15 +41,26 @@ interface PhotoGridWithLayoutsProps {
|
|||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowFavorites?: boolean;
|
||||||
|
allowRatings?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
onFeedbackChange?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||||
photos,
|
photos,
|
||||||
slug,
|
slug,
|
||||||
categoryId,
|
categoryId,
|
||||||
|
heroPhotoOverride,
|
||||||
isSelectionMode: parentSelectionMode,
|
isSelectionMode: parentSelectionMode,
|
||||||
selectedPhotos: parentSelectedPhotos,
|
selectedPhotos: parentSelectedPhotos,
|
||||||
feedbackEnabled,
|
feedbackEnabled,
|
||||||
|
feedbackOptions,
|
||||||
|
onFeedbackChange,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
@@ -61,6 +75,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(null);
|
const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(null);
|
||||||
|
const [openFeedbackInitially, setOpenFeedbackInitially] = useState<boolean>(false);
|
||||||
const [localSelectedPhotos, setLocalSelectedPhotos] = useState<Set<number>>(new Set());
|
const [localSelectedPhotos, setLocalSelectedPhotos] = useState<Set<number>>(new Set());
|
||||||
const [localSelectionMode, setLocalSelectionMode] = useState(false);
|
const [localSelectionMode, setLocalSelectionMode] = useState(false);
|
||||||
const downloadPhotoMutation = useDownloadPhoto();
|
const downloadPhotoMutation = useDownloadPhoto();
|
||||||
@@ -77,10 +92,24 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
}, [categoryId]);
|
}, [categoryId]);
|
||||||
|
|
||||||
const handlePhotoClick = (index: number) => {
|
const handlePhotoClick = (index: number) => {
|
||||||
|
setOpenFeedbackInitially(false);
|
||||||
|
setSelectedPhotoIndex(index);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenWithFeedback = (index: number) => {
|
||||||
|
setOpenFeedbackInitially(true);
|
||||||
setSelectedPhotoIndex(index);
|
setSelectedPhotoIndex(index);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePhotoSelect = (photoId: number) => {
|
const handlePhotoSelect = (photoId: number) => {
|
||||||
|
// Auto-enable selection mode when selecting via checkbox
|
||||||
|
if (!isSelectionMode) {
|
||||||
|
if (parentToggleSelectionMode) {
|
||||||
|
parentToggleSelectionMode();
|
||||||
|
} else {
|
||||||
|
setLocalSelectionMode(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
const newSelected = new Set(selectedPhotos);
|
const newSelected = new Set(selectedPhotos);
|
||||||
if (newSelected.has(photoId)) {
|
if (newSelected.has(photoId)) {
|
||||||
newSelected.delete(photoId);
|
newSelected.delete(photoId);
|
||||||
@@ -114,39 +143,21 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
|
|
||||||
const handleDownloadSelected = async () => {
|
const handleDownloadSelected = async () => {
|
||||||
if (selectedPhotos.size === 0) return;
|
if (selectedPhotos.size === 0) return;
|
||||||
|
const ids = Array.from(selectedPhotos);
|
||||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||||
|
|
||||||
toastify.info(t('gallery.downloading', { count: selectedPhotos.size }));
|
|
||||||
|
|
||||||
// Download each selected photo
|
|
||||||
const downloadPromises = selectedPhotosList.map(photo =>
|
|
||||||
galleryService.downloadPhoto(slug, photo.id, photo.filename)
|
|
||||||
.catch(err => {
|
|
||||||
// Download failed - error handled by UI
|
|
||||||
return null;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all(downloadPromises);
|
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||||
|
} catch (error) {
|
||||||
// Track bulk download
|
toastify.error(t('gallery.downloadError'));
|
||||||
analyticsService.trackGalleryEvent('bulk_download', {
|
} finally {
|
||||||
gallery: slug,
|
|
||||||
photo_count: selectedPhotos.size
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clear selection after download
|
|
||||||
setSelectedPhotos(new Set());
|
setSelectedPhotos(new Set());
|
||||||
if (parentToggleSelectionMode) {
|
if (parentToggleSelectionMode) {
|
||||||
parentToggleSelectionMode();
|
parentToggleSelectionMode();
|
||||||
} else {
|
} else {
|
||||||
setLocalSelectionMode(false);
|
setLocalSelectionMode(false);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
toastify.error(t('gallery.downloadError'));
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -166,7 +177,10 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
photos,
|
photos,
|
||||||
slug,
|
slug,
|
||||||
onPhotoClick: handlePhotoClick,
|
onPhotoClick: handlePhotoClick,
|
||||||
|
onOpenPhotoWithFeedback: handleOpenWithFeedback,
|
||||||
|
onFeedbackChange: onFeedbackChange,
|
||||||
onDownload: handleDownload,
|
onDownload: handleDownload,
|
||||||
|
heroPhotoOverride,
|
||||||
selectedPhotos,
|
selectedPhotos,
|
||||||
allowDownloads,
|
allowDownloads,
|
||||||
protectionLevel,
|
protectionLevel,
|
||||||
@@ -178,6 +192,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
eventDate,
|
eventDate,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
feedbackEnabled,
|
feedbackEnabled,
|
||||||
|
feedbackOptions,
|
||||||
};
|
};
|
||||||
|
|
||||||
let LayoutComponent;
|
let LayoutComponent;
|
||||||
@@ -275,8 +290,9 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
protectionLevel={protectionLevel}
|
protectionLevel={protectionLevel}
|
||||||
useEnhancedProtection={useEnhancedProtection}
|
useEnhancedProtection={useEnhancedProtection}
|
||||||
|
initialShowFeedback={openFeedbackInitially}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { useDevToolsProtection } from '../../hooks/useDevToolsProtection';
|
import { useDevToolsProtection } from '../../hooks/useDevToolsProtection';
|
||||||
import { X, ChevronLeft, ChevronRight, Download, ZoomIn, ZoomOut, MessageSquare } from 'lucide-react';
|
import { X, ChevronLeft, ChevronRight, Download, ZoomIn, ZoomOut, MessageSquare, Heart, Star } from 'lucide-react';
|
||||||
import type { Photo } from '../../types';
|
import type { Photo } from '../../types';
|
||||||
import { useDownloadPhoto } from '../../hooks/useGallery';
|
import { useDownloadPhoto } from '../../hooks/useGallery';
|
||||||
import { AuthenticatedImage } from '../common';
|
import { AuthenticatedImage } from '../common';
|
||||||
import { PhotoFeedback } from './PhotoFeedback';
|
import { PhotoFeedback } from './PhotoFeedback';
|
||||||
|
import { feedbackService } from '../../services/feedback.service';
|
||||||
|
import { FeedbackIdentityModal } from './FeedbackIdentityModal';
|
||||||
|
|
||||||
interface PhotoLightboxProps {
|
interface PhotoLightboxProps {
|
||||||
photos: Photo[];
|
photos: Photo[];
|
||||||
@@ -15,6 +17,7 @@ interface PhotoLightboxProps {
|
|||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
|
initialShowFeedback?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||||
@@ -26,6 +29,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
|
initialShowFeedback = false,
|
||||||
}) => {
|
}) => {
|
||||||
const [currentIndex, setCurrentIndex] = useState(initialIndex);
|
const [currentIndex, setCurrentIndex] = useState(initialIndex);
|
||||||
const [zoom, setZoom] = useState(1);
|
const [zoom, setZoom] = useState(1);
|
||||||
@@ -33,7 +37,28 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
|
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
|
||||||
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
||||||
const [touchDistance, setTouchDistance] = useState<number | null>(null);
|
const [touchDistance, setTouchDistance] = useState<number | null>(null);
|
||||||
const [showFeedback, setShowFeedback] = useState(false);
|
const [showFeedback, setShowFeedback] = useState(initialShowFeedback);
|
||||||
|
const [isSmallScreen, setIsSmallScreen] = useState<boolean>(typeof window !== 'undefined' ? window.innerWidth < 640 : false);
|
||||||
|
const [feedbackSettings, setFeedbackSettings] = useState<{
|
||||||
|
feedback_enabled?: boolean;
|
||||||
|
allow_likes?: boolean;
|
||||||
|
allow_ratings?: boolean;
|
||||||
|
require_name_email?: boolean;
|
||||||
|
} | null>(null);
|
||||||
|
const [myLiked, setMyLiked] = useState<boolean>(false);
|
||||||
|
const [myRating, setMyRating] = useState<number>(0);
|
||||||
|
const [likeCount, setLikeCount] = useState<number>(0);
|
||||||
|
const [avgRating, setAvgRating] = useState<number>(0);
|
||||||
|
const [totalRatings, setTotalRatings] = useState<number>(0);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like' | 'rating'; rating?: number }>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onResize = () => setIsSmallScreen(window.innerWidth < 640);
|
||||||
|
window.addEventListener('resize', onResize);
|
||||||
|
return () => window.removeEventListener('resize', onResize);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const downloadPhotoMutation = useDownloadPhoto();
|
const downloadPhotoMutation = useDownloadPhoto();
|
||||||
const currentPhoto = photos[currentIndex];
|
const currentPhoto = photos[currentIndex];
|
||||||
@@ -111,6 +136,81 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
};
|
};
|
||||||
}, [currentIndex]);
|
}, [currentIndex]);
|
||||||
|
|
||||||
|
// Load feedback settings once
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const settings = await feedbackService.getGalleryFeedbackSettings(slug);
|
||||||
|
if (mounted) setFeedbackSettings(settings as any);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, [slug]);
|
||||||
|
|
||||||
|
// Load my feedback for the current photo
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
if (!feedbackSettings?.feedback_enabled) return;
|
||||||
|
const data = await feedbackService.getPhotoFeedback(slug, String(currentPhoto.id));
|
||||||
|
if (!mounted) return;
|
||||||
|
setMyLiked(!!data.my_feedback.liked);
|
||||||
|
setMyRating(data.my_feedback.rating || 0);
|
||||||
|
setLikeCount(Number(data.summary?.like_count) || 0);
|
||||||
|
setAvgRating(Number(data.summary?.average_rating) || 0);
|
||||||
|
setTotalRatings(Number(data.summary?.total_ratings) || 0);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, [slug, currentPhoto.id, feedbackSettings?.feedback_enabled]);
|
||||||
|
|
||||||
|
const submitLike = async () => {
|
||||||
|
const needIdentity = feedbackSettings?.require_name_email && !savedIdentity;
|
||||||
|
if (needIdentity) {
|
||||||
|
setPendingAction({ type: 'like' });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
setMyLiked(prev => {
|
||||||
|
const next = !prev;
|
||||||
|
setLikeCount(c => Math.max(0, c + (next ? 1 : -1)));
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitRating = async (value: number) => {
|
||||||
|
const needIdentity = feedbackSettings?.require_name_email && !savedIdentity;
|
||||||
|
if (needIdentity) {
|
||||||
|
setPendingAction({ type: 'rating', rating: value });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'rating',
|
||||||
|
rating: value,
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
setMyRating(value);
|
||||||
|
// Refresh current summary to reflect average and totals
|
||||||
|
try {
|
||||||
|
const fresh = await feedbackService.getPhotoFeedback(slug, String(currentPhoto.id));
|
||||||
|
setAvgRating(Number(fresh.summary?.average_rating) || 0);
|
||||||
|
setTotalRatings(Number(fresh.summary?.total_ratings) || 0);
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
|
|
||||||
const goToPrevious = () => {
|
const goToPrevious = () => {
|
||||||
setCurrentIndex((prev) => (prev > 0 ? prev - 1 : photos.length - 1));
|
setCurrentIndex((prev) => (prev > 0 ? prev - 1 : photos.length - 1));
|
||||||
resetZoom();
|
resetZoom();
|
||||||
@@ -211,13 +311,17 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
`fixed inset-0 bg-black z-50 flex items-center justify-center protected-image protection-${protectionLevel}` :
|
`fixed inset-0 bg-black z-50 flex items-center justify-center protected-image protection-${protectionLevel}` :
|
||||||
'fixed inset-0 bg-black z-50 flex items-center justify-center';
|
'fixed inset-0 bg-black z-50 flex items-center justify-center';
|
||||||
|
|
||||||
|
const desktopFeedbackWidth = 416; // 26rem; keep in sync with panel width
|
||||||
|
const isDesktopFeedback = showFeedback && !isSmallScreen;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={lightboxClass}>
|
<div className={lightboxClass}>
|
||||||
{/* Close button */}
|
{/* Close button */}
|
||||||
<button
|
<button
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="absolute top-4 right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-20"
|
className="absolute top-4 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-30"
|
||||||
aria-label="Close"
|
aria-label="Close"
|
||||||
|
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||||
>
|
>
|
||||||
<X className="w-6 h-6 text-white" />
|
<X className="w-6 h-6 text-white" />
|
||||||
</button>
|
</button>
|
||||||
@@ -231,16 +335,22 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
<ChevronLeft className="w-6 h-6 text-white" />
|
<ChevronLeft className="w-6 h-6 text-white" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
{!showFeedback || !isSmallScreen ? (
|
||||||
onClick={goToNext}
|
<button
|
||||||
className="absolute right-4 top-1/2 -translate-y-1/2 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-20"
|
onClick={goToNext}
|
||||||
aria-label="Next photo"
|
className="absolute top-1/2 -translate-y-1/2 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-30"
|
||||||
>
|
aria-label="Next photo"
|
||||||
<ChevronRight className="w-6 h-6 text-white" />
|
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||||
</button>
|
>
|
||||||
|
<ChevronRight className="w-6 h-6 text-white" />
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{/* Bottom toolbar */}
|
{/* Bottom toolbar */}
|
||||||
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 z-20">
|
<div
|
||||||
|
className="absolute bottom-0 left-0 bg-gradient-to-t from-black/80 to-transparent p-4 z-20"
|
||||||
|
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth}px` : 0 }}
|
||||||
|
>
|
||||||
<div className="max-w-4xl mx-auto flex items-center justify-between">
|
<div className="max-w-4xl mx-auto flex items-center justify-between">
|
||||||
<div className="text-white">
|
<div className="text-white">
|
||||||
<p className="text-sm opacity-75">
|
<p className="text-sm opacity-75">
|
||||||
@@ -280,6 +390,39 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
<Download className="w-5 h-5 text-white" />
|
<Download className="w-5 h-5 text-white" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Inline Like */}
|
||||||
|
{feedbackEnabled && feedbackSettings?.allow_likes && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
onClick={submitLike}
|
||||||
|
className={`p-2 rounded-full transition-colors ${myLiked ? 'bg-red-500/80 hover:bg-red-500' : 'bg-white/10 hover:bg-white/20'}`}
|
||||||
|
aria-label={myLiked ? 'Unlike photo' : 'Like photo'}
|
||||||
|
title={myLiked ? 'Unlike' : 'Like'}
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${myLiked ? 'text-white' : 'text-white'}`} />
|
||||||
|
</button>
|
||||||
|
<span className="text-white text-xs min-w-[1.5rem] text-center select-none">{likeCount}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Inline Rating */}
|
||||||
|
{feedbackEnabled && feedbackSettings?.allow_ratings && (
|
||||||
|
<div className="flex items-center gap-1 ml-1" aria-label="Rate photo">
|
||||||
|
{[1,2,3,4,5].map((i) => (
|
||||||
|
<button
|
||||||
|
key={i}
|
||||||
|
onClick={() => submitRating(i)}
|
||||||
|
className="p-1"
|
||||||
|
aria-label={`Rate ${i} star${i>1?'s':''}`}
|
||||||
|
title={`Rate ${i}`}
|
||||||
|
>
|
||||||
|
<Star className={`w-5 h-5 ${myRating >= i ? 'text-yellow-400 fill-yellow-400' : 'text-white/70'}`} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<span className="text-white/90 text-xs ml-2 select-none">{avgRating.toFixed(1)} ({totalRatings})</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Feedback button with indicator */}
|
{/* Feedback button with indicator */}
|
||||||
{feedbackEnabled && (
|
{feedbackEnabled && (
|
||||||
@@ -305,7 +448,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
|
|
||||||
{/* Image container */}
|
{/* Image container */}
|
||||||
<div
|
<div
|
||||||
className="absolute inset-0 flex items-center justify-center z-0"
|
className="absolute top-0 left-0 bottom-0 flex items-center justify-center z-0"
|
||||||
onClick={handleImageClick}
|
onClick={handleImageClick}
|
||||||
onMouseDown={handleMouseDown}
|
onMouseDown={handleMouseDown}
|
||||||
onMouseMove={handleMouseMove}
|
onMouseMove={handleMouseMove}
|
||||||
@@ -314,11 +457,15 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
onTouchStart={handleTouchStart}
|
onTouchStart={handleTouchStart}
|
||||||
onTouchMove={handleTouchMove}
|
onTouchMove={handleTouchMove}
|
||||||
onTouchEnd={handleTouchEnd}
|
onTouchEnd={handleTouchEnd}
|
||||||
style={{ cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default' }}
|
style={{
|
||||||
|
cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default',
|
||||||
|
right: isDesktopFeedback ? `${desktopFeedbackWidth}px` : 0,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={currentPhoto.url}
|
src={currentPhoto.url}
|
||||||
alt={currentPhoto.filename}
|
alt={currentPhoto.filename}
|
||||||
|
fallbackSrc={currentPhoto.thumbnail_url || undefined}
|
||||||
className="max-w-full max-h-full object-contain select-none"
|
className="max-w-full max-h-full object-contain select-none"
|
||||||
style={{
|
style={{
|
||||||
transform: `scale(${zoom}) translate(${dragOffset.x / zoom}px, ${dragOffset.y / zoom}px)`,
|
transform: `scale(${zoom}) translate(${dragOffset.x / zoom}px, ${dragOffset.y / zoom}px)`,
|
||||||
@@ -369,7 +516,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
|
|
||||||
{/* Feedback Panel */}
|
{/* Feedback Panel */}
|
||||||
{showFeedback && (
|
{showFeedback && (
|
||||||
<div className="absolute right-0 top-0 bottom-0 w-full sm:w-96 lg:w-[28rem] bg-white shadow-xl z-20 overflow-y-auto">
|
<div className="absolute right-0 top-0 bottom-0 w-full sm:w-[26rem] bg-white shadow-xl z-20 overflow-y-auto flex flex-col border-l border-neutral-200">
|
||||||
<div className="sticky top-0 bg-white border-b px-4 py-3 flex items-center justify-between">
|
<div className="sticky top-0 bg-white border-b px-4 py-3 flex items-center justify-between">
|
||||||
<h3 className="font-semibold text-neutral-900">Photo Feedback</h3>
|
<h3 className="font-semibold text-neutral-900">Photo Feedback</h3>
|
||||||
<button
|
<button
|
||||||
@@ -380,7 +527,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
<X className="w-5 h-5" />
|
<X className="w-5 h-5" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="p-4">
|
<div className="p-4 flex-1 overflow-y-auto">
|
||||||
<PhotoFeedback
|
<PhotoFeedback
|
||||||
photoId={currentPhoto.id}
|
photoId={currentPhoto.id}
|
||||||
gallerySlug={slug}
|
gallerySlug={slug}
|
||||||
@@ -390,6 +537,34 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Identity Modal for required name/email */}
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction?.type === 'like') {
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setMyLiked(true);
|
||||||
|
} else if (pendingAction?.type === 'rating' && pendingAction.rating) {
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'rating',
|
||||||
|
rating: pendingAction.rating,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setMyRating(pendingAction.rating);
|
||||||
|
}
|
||||||
|
setPendingAction(null);
|
||||||
|
}}
|
||||||
|
feedbackType={pendingAction?.type === 'rating' ? 'rating' : 'like'}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,4 +10,3 @@ export { PhotoFeedback } from './PhotoFeedback';
|
|||||||
export { PhotoRating } from './PhotoRating';
|
export { PhotoRating } from './PhotoRating';
|
||||||
export { PhotoLikes } from './PhotoLikes';
|
export { PhotoLikes } from './PhotoLikes';
|
||||||
export { PhotoComments } from './PhotoComments';
|
export { PhotoComments } from './PhotoComments';
|
||||||
export { PhotoFavorites } from './PhotoFavorites';
|
|
||||||
@@ -5,6 +5,10 @@ export interface BaseGalleryLayoutProps {
|
|||||||
photos: Photo[];
|
photos: Photo[];
|
||||||
slug: string;
|
slug: string;
|
||||||
onPhotoClick: (index: number) => void;
|
onPhotoClick: (index: number) => void;
|
||||||
|
// Optional: open the lightbox with feedback panel visible
|
||||||
|
onOpenPhotoWithFeedback?: (index: number) => void;
|
||||||
|
// Notify parent that feedback (like/favorite/rating/comment) changed
|
||||||
|
onFeedbackChange?: () => void;
|
||||||
onDownload: (photo: Photo, e: React.MouseEvent) => void;
|
onDownload: (photo: Photo, e: React.MouseEvent) => void;
|
||||||
selectedPhotos?: Set<number>;
|
selectedPhotos?: Set<number>;
|
||||||
isSelectionMode?: boolean;
|
isSelectionMode?: boolean;
|
||||||
@@ -17,8 +21,15 @@ export interface BaseGalleryLayoutProps {
|
|||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowFavorites?: boolean;
|
||||||
|
allowRatings?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export abstract class BaseGalleryLayout<T extends BaseGalleryLayoutProps = BaseGalleryLayoutProps> extends React.Component<T> {
|
export abstract class BaseGalleryLayout<T extends BaseGalleryLayoutProps = BaseGalleryLayoutProps> extends React.Component<T> {
|
||||||
abstract render(): React.ReactNode;
|
abstract render(): React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { ChevronLeft, ChevronRight, Download, Maximize2, Play, Pause } from 'lucide-react';
|
import { ChevronLeft, ChevronRight, Download, Maximize2, Play, Pause, Heart, MessageSquare } from 'lucide-react';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage, Button } from '../../common';
|
import { AuthenticatedImage, Button } from '../../common';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
|
|
||||||
export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
// selectedPhotos = new Set(),
|
feedbackEnabled = false,
|
||||||
// isSelectionMode = false
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [currentIndex, setCurrentIndex] = useState(0);
|
const [currentIndex, setCurrentIndex] = useState(0);
|
||||||
@@ -59,6 +63,11 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
if (photos.length === 0) return null;
|
if (photos.length === 0) return null;
|
||||||
|
|
||||||
const currentPhoto = photos[currentIndex];
|
const currentPhoto = photos[currentIndex];
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
|
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||||
|
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
@@ -136,6 +145,44 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
<Download className="w-5 h-5" />
|
<Download className="w-5 h-5" />
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={async () => {
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: currentPhoto.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedIds(prev => new Set(prev).add(currentPhoto.id));
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
className={`hover:bg-white/20 ${likedIds.has(currentPhoto.id) ? 'text-red-400' : 'text-white'}`}
|
||||||
|
title="Like photo"
|
||||||
|
aria-pressed={likedIds.has(currentPhoto.id)}
|
||||||
|
>
|
||||||
|
<Heart className="w-5 h-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canQuickComment && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => { onOpenPhotoWithFeedback?.(currentIndex); }}
|
||||||
|
className="text-white hover:bg-white/20"
|
||||||
|
title="Comment"
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -181,6 +228,24 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
|
||||||
<style>{`
|
<style>{`
|
||||||
@keyframes progress {
|
@keyframes progress {
|
||||||
from { width: 0%; }
|
from { width: 0%; }
|
||||||
@@ -189,4 +254,4 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
`}</style>
|
`}</style>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-r
|
|||||||
import { useInView } from 'react-intersection-observer';
|
import { useInView } from 'react-intersection-observer';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
|
||||||
@@ -12,12 +14,26 @@ interface GridPhotoProps {
|
|||||||
isSelectionMode: boolean;
|
isSelectionMode: boolean;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: (e: React.MouseEvent) => void;
|
||||||
onDownload: (e: React.MouseEvent) => void;
|
onDownload: (e: React.MouseEvent) => void;
|
||||||
|
onToggleSelect: () => void;
|
||||||
animationType?: string;
|
animationType?: string;
|
||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
slug?: string;
|
slug?: string;
|
||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowRatings?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
savedIdentity?: { name: string; email: string } | null;
|
||||||
|
onRequireIdentity?: (action: 'like', photoId: number) => void;
|
||||||
|
onQuickComment?: () => void;
|
||||||
|
onFeedbackChange?: () => void;
|
||||||
|
// Immediate UI like state and callback
|
||||||
|
liked?: boolean;
|
||||||
|
onLikeSuccess?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const GridPhoto: React.FC<GridPhotoProps> = ({
|
const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||||
@@ -26,13 +42,22 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
isSelectionMode,
|
isSelectionMode,
|
||||||
onClick,
|
onClick,
|
||||||
onDownload,
|
onDownload,
|
||||||
|
onToggleSelect,
|
||||||
animationType = 'fade',
|
animationType = 'fade',
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
slug,
|
slug,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions,
|
||||||
|
savedIdentity,
|
||||||
|
onRequireIdentity,
|
||||||
|
onQuickComment,
|
||||||
|
onFeedbackChange,
|
||||||
|
liked = false,
|
||||||
|
onLikeSuccess
|
||||||
}) => {
|
}) => {
|
||||||
|
// handled by parent layout; kept here for type completeness but not used
|
||||||
const { ref, inView } = useInView({
|
const { ref, inView } = useInView({
|
||||||
triggerOnce: true,
|
triggerOnce: true,
|
||||||
threshold: 0.1,
|
threshold: 0.1,
|
||||||
@@ -79,7 +104,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
<div className="absolute inset-0 bg-black/40 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||||
{!isSelectionMode && (
|
{!isSelectionMode && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
@@ -101,44 +126,91 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{onQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{/* Quick feedback actions */}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${liked ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity && onRequireIdentity) {
|
||||||
|
onRequireIdentity('like', photo.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Optimistic UI: mark as liked immediately
|
||||||
|
if (onLikeSuccess) onLikeSuccess();
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// Keep optimistic state; a refresh will reconcile
|
||||||
|
console.warn('Like submit failed, keeping optimistic UI', err);
|
||||||
|
}
|
||||||
|
if (onFeedbackChange) onFeedbackChange();
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={liked}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${liked ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<button
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
type="button"
|
||||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
aria-label={`Select ${photo.filename}`}
|
||||||
</div>
|
role="checkbox"
|
||||||
|
aria-checked={isSelected}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</button>
|
||||||
|
|
||||||
{/* Feedback Indicators */}
|
{/* Feedback Indicators (always visible, bottom-left). Show like immediately when user liked */}
|
||||||
{feedbackEnabled && (photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0 || liked) && (
|
||||||
<div className="absolute top-2 left-2 flex gap-1 z-10">
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 flex items-center gap-1 z-10`}>
|
||||||
{photo.comment_count > 0 && (
|
{(photo.like_count > 0 || liked) && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
</span>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
{photo.average_rating > 0 && (
|
{photo.average_rating > 0 && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Rated">
|
||||||
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
</span>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
{photo.like_count > 0 && (
|
{photo.comment_count > 0 && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.like_count} likes`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Commented">
|
||||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{photo.like_count}</span>
|
</span>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{photo.type === 'collage' && (
|
{photo.type === 'collage' && (
|
||||||
<div className="absolute bottom-2 left-2">
|
<div className="absolute bottom-2 right-2">
|
||||||
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
||||||
Collage
|
Collage
|
||||||
</span>
|
</span>
|
||||||
@@ -156,6 +228,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photos,
|
photos,
|
||||||
slug,
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
|
onFeedbackChange,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
@@ -163,7 +237,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const gallerySettings = theme.gallerySettings || {};
|
const gallerySettings = theme.gallerySettings || {};
|
||||||
@@ -171,6 +246,11 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
const spacing = gallerySettings.spacing || 'normal';
|
const spacing = gallerySettings.spacing || 'normal';
|
||||||
const animation = gallerySettings.photoAnimation || 'fade';
|
const animation = gallerySettings.photoAnimation || 'fade';
|
||||||
|
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = React.useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = React.useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [likedPhotoIds, setLikedPhotoIds] = React.useState<Set<number>>(new Set());
|
||||||
|
const [savedIdentity, setSavedIdentity] = React.useState<{ name: string; email: string } | null>(null);
|
||||||
|
|
||||||
const spacingClass = spacing === 'tight' ? 'gap-2' : spacing === 'relaxed' ? 'gap-6' : 'gap-4';
|
const spacingClass = spacing === 'tight' ? 'gap-2' : spacing === 'relaxed' ? 'gap-6' : 'gap-4';
|
||||||
|
|
||||||
const gridClass = `grid ${spacingClass}
|
const gridClass = `grid ${spacingClass}
|
||||||
@@ -187,13 +267,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo}
|
photo={photo}
|
||||||
isSelected={selectedPhotos.has(photo.id)}
|
isSelected={selectedPhotos.has(photo.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(index)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(index);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
animationType={animation}
|
animationType={animation}
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
@@ -201,8 +276,49 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
protectionLevel={protectionLevel}
|
protectionLevel={protectionLevel}
|
||||||
useEnhancedProtection={useEnhancedProtection}
|
useEnhancedProtection={useEnhancedProtection}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
savedIdentity={savedIdentity}
|
||||||
|
onRequireIdentity={(action, photoId) => {
|
||||||
|
setPendingAction({ type: action, photoId });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
}}
|
||||||
|
onQuickComment={() => onOpenPhotoWithFeedback && onOpenPhotoWithFeedback(index)}
|
||||||
|
onFeedbackChange={onFeedbackChange}
|
||||||
|
liked={likedPhotoIds.has(photo.id)}
|
||||||
|
onLikeSuccess={() => {
|
||||||
|
setLikedPhotoIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.add(photo.id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
// Immediately reflect like UI
|
||||||
|
if (pendingAction.type === 'like') {
|
||||||
|
setLikedPhotoIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.add(pendingAction.photoId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock } from 'lucide-react';
|
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock, Heart, MessageSquare } from 'lucide-react';
|
||||||
import { parseISO } from 'date-fns';
|
import { parseISO } from 'date-fns';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useLocalizedDate } from '../../../hooks/useLocalizedDate';
|
import { useLocalizedDate } from '../../../hooks/useLocalizedDate';
|
||||||
@@ -8,17 +8,23 @@ import { AuthenticatedImage } from '../../common';
|
|||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
import { buildResourceUrl } from '../../../utils/url';
|
import { buildResourceUrl } from '../../../utils/url';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
|
|
||||||
interface HeroGalleryLayoutProps extends BaseGalleryLayoutProps {
|
interface HeroGalleryLayoutProps extends BaseGalleryLayoutProps {
|
||||||
eventName?: string;
|
eventName?: string;
|
||||||
eventLogo?: string | null;
|
eventLogo?: string | null;
|
||||||
eventDate?: string;
|
eventDate?: string;
|
||||||
expiresAt?: string;
|
expiresAt?: string;
|
||||||
|
// Use a static hero photo independent of current filter
|
||||||
|
heroPhotoOverride?: Photo | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
@@ -27,15 +33,31 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
eventLogo,
|
eventLogo,
|
||||||
eventDate,
|
eventDate,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
allowDownloads = true
|
heroPhotoOverride,
|
||||||
|
allowDownloads = true,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { format } = useLocalizedDate();
|
const { format } = useLocalizedDate();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [heroPhoto, setHeroPhoto] = useState<Photo | null>(null);
|
const [heroPhoto, setHeroPhoto] = useState<Photo | null>(null);
|
||||||
const [hasInitialized, setHasInitialized] = useState(false);
|
const [hasInitialized, setHasInitialized] = useState(false);
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
const gallerySettings = theme.gallerySettings || {};
|
const gallerySettings = theme.gallerySettings || {};
|
||||||
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
||||||
|
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||||
|
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||||
|
|
||||||
|
// If an override is provided, always use it and skip initialization logic
|
||||||
|
useEffect(() => {
|
||||||
|
if (heroPhotoOverride) {
|
||||||
|
setHeroPhoto(heroPhotoOverride);
|
||||||
|
setHasInitialized(true);
|
||||||
|
}
|
||||||
|
}, [heroPhotoOverride]);
|
||||||
|
|
||||||
// Reset initialization when heroImageId changes
|
// Reset initialization when heroImageId changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -46,29 +68,28 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
|
|
||||||
// Select hero photo (admin-selected or first photo only if gallery was empty)
|
// Select hero photo (admin-selected or first photo only if gallery was empty)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// When an override is provided, the effect above has already set the hero.
|
||||||
|
if (heroPhotoOverride) return;
|
||||||
|
|
||||||
if (photos.length > 0) {
|
if (photos.length > 0) {
|
||||||
const heroId = gallerySettings.heroImageId;
|
const heroId = gallerySettings.heroImageId;
|
||||||
// Process hero layout with provided photos
|
// If admin has selected a specific hero image, always use it when available
|
||||||
|
|
||||||
// If admin has selected a specific hero image, always use it
|
|
||||||
if (heroId) {
|
if (heroId) {
|
||||||
const adminSelectedHero = photos.find(p => p.id === heroId);
|
const adminSelectedHero = photos.find(p => p.id === heroId);
|
||||||
// Hero photo selected by admin
|
|
||||||
if (adminSelectedHero) {
|
if (adminSelectedHero) {
|
||||||
setHeroPhoto(adminSelectedHero);
|
setHeroPhoto(adminSelectedHero);
|
||||||
setHasInitialized(true);
|
setHasInitialized(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only auto-select first photo on initial load when gallery was empty
|
// Only auto-select first photo on initial load
|
||||||
// This prevents changing the hero when new photos are uploaded
|
|
||||||
if (!hasInitialized) {
|
if (!hasInitialized) {
|
||||||
setHeroPhoto(photos[0]);
|
setHeroPhoto(photos[0]);
|
||||||
setHasInitialized(true);
|
setHasInitialized(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [photos, gallerySettings.heroImageId, hasInitialized]);
|
}, [photos, gallerySettings.heroImageId, hasInitialized, heroPhotoOverride]);
|
||||||
|
|
||||||
if (!heroPhoto) return null;
|
if (!heroPhoto) return null;
|
||||||
|
|
||||||
@@ -76,11 +97,13 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
const remainingPhotos = photos;
|
const remainingPhotos = photos;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<div className="relative -mt-6">
|
<div className="relative -mt-6">
|
||||||
{/* Hero Section */}
|
{/* Hero Section */}
|
||||||
<div className="relative h-[60vh] sm:h-[70vh] lg:h-[80vh] -mx-4 sm:-mx-6 lg:-mx-8 mb-8">
|
<div className="relative h-[60vh] sm:h-[70vh] lg:h-[80vh] -mx-4 sm:-mx-6 lg:-mx-8 mb-8">
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={heroPhoto.url}
|
src={heroPhoto.url}
|
||||||
|
fallbackSrc={heroPhoto.thumbnail_url || undefined}
|
||||||
alt={heroPhoto.filename}
|
alt={heroPhoto.filename}
|
||||||
className="w-full h-full object-cover"
|
className="w-full h-full object-cover"
|
||||||
isGallery={true}
|
isGallery={true}
|
||||||
@@ -152,13 +175,7 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
<div
|
<div
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
className="relative group cursor-pointer aspect-square"
|
className="relative group cursor-pointer aspect-square"
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(actualIndex)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(actualIndex);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={photo.thumbnail_url || photo.url}
|
src={photo.thumbnail_url || photo.url}
|
||||||
@@ -194,15 +211,81 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${likedIds.has(photo.id) ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedIds(prev => new Set(prev).add(photo.id));
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={likedIds.has(photo.id)}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${likedIds.has(photo.id) ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{canQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onOpenPhotoWithFeedback?.(actualIndex); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<button
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
type="button"
|
||||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
aria-label={`Select ${photo.filename}`}
|
||||||
</div>
|
role="checkbox"
|
||||||
|
aria-checked={selectedPhotos.has(photo.id)}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onPhotoSelect && onPhotoSelect(photo.id); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Feedback indicators (always visible, bottom-left). Show like immediately when liked */}
|
||||||
|
{(photo.like_count > 0 || likedIds.has(photo.id) || (photo.average_rating || 0) > 0 || (photo.comment_count || 0) > 0) && (
|
||||||
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 flex items-center gap-1 z-20`}>
|
||||||
|
{(photo.like_count > 0 || likedIds.has(photo.id)) && (
|
||||||
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{(photo.average_rating || 0) > 0 && (
|
||||||
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Rated">
|
||||||
|
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-yellow-500 fill-current"><path d="M12 .587l3.668 7.431 8.2 1.193-5.934 5.787 1.402 8.168L12 18.897l-7.336 3.869 1.402-8.168L.132 9.211l8.2-1.193z"/></svg>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{(photo.comment_count || 0) > 0 && (
|
||||||
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Commented">
|
||||||
|
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-blue-600 fill-current"><path d="M20 2H4a2 2 0 00-2 2v18l4-4h14a2 2 0 002-2V4a2 2 0 00-2-2z"/></svg>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -210,5 +293,23 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import React, { useEffect, useRef, useState } from 'react';
|
|||||||
import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-react';
|
import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-react';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
|
||||||
@@ -11,9 +13,17 @@ interface MasonryPhotoProps {
|
|||||||
isSelectionMode: boolean;
|
isSelectionMode: boolean;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: (e: React.MouseEvent) => void;
|
||||||
onDownload: (e: React.MouseEvent) => void;
|
onDownload: (e: React.MouseEvent) => void;
|
||||||
|
onToggleSelect: () => void;
|
||||||
style?: React.CSSProperties;
|
style?: React.CSSProperties;
|
||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
|
slug?: string;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
onQuickComment?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||||
@@ -22,11 +32,18 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
|||||||
isSelectionMode,
|
isSelectionMode,
|
||||||
onClick,
|
onClick,
|
||||||
onDownload,
|
onDownload,
|
||||||
|
onToggleSelect,
|
||||||
style,
|
style,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
slug,
|
||||||
|
feedbackOptions,
|
||||||
|
onQuickComment
|
||||||
}) => {
|
}) => {
|
||||||
const [imageHeight, setImageHeight] = useState<number>(200);
|
const [imageHeight, setImageHeight] = useState<number>(200);
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
|
|
||||||
// Generate random heights for masonry effect
|
// Generate random heights for masonry effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -100,17 +117,77 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{onQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Identity Modal */}
|
||||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<FeedbackIdentityModal
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
isOpen={showIdentityModal}
|
||||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
</div>
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`Select ${photo.filename}`}
|
||||||
|
role="checkbox"
|
||||||
|
aria-checked={isSelected}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</button>
|
||||||
|
|
||||||
{photo.type === 'collage' && (
|
{photo.type === 'collage' && (
|
||||||
<div className="absolute bottom-2 left-2">
|
<div className="absolute bottom-2 left-2">
|
||||||
@@ -125,13 +202,16 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
|||||||
|
|
||||||
export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
onPhotoSelect,
|
onPhotoSelect,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -182,16 +262,14 @@ export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo}
|
photo={photo}
|
||||||
isSelected={selectedPhotos.has(photo.id)}
|
isSelected={selectedPhotos.has(photo.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(originalIndex)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(originalIndex);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
slug={slug}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => onOpenPhotoWithFeedback && onOpenPhotoWithFeedback(originalIndex)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -199,4 +277,4 @@ export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Download, Maximize2, Check } from 'lucide-react';
|
import { Download, Maximize2, Check, Heart, MessageSquare } from 'lucide-react';
|
||||||
// import { useTheme } from '../../../contexts/ThemeContext';
|
// import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
|
||||||
@@ -11,8 +13,17 @@ interface MosaicPhotoProps {
|
|||||||
isSelectionMode: boolean;
|
isSelectionMode: boolean;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: (e: React.MouseEvent) => void;
|
||||||
onDownload: (e: React.MouseEvent) => void;
|
onDownload: (e: React.MouseEvent) => void;
|
||||||
|
onToggleSelect: () => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
|
slug?: string;
|
||||||
|
feedbackEnabled?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
onQuickComment?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||||
@@ -21,10 +32,22 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
|||||||
isSelectionMode,
|
isSelectionMode,
|
||||||
onClick,
|
onClick,
|
||||||
onDownload,
|
onDownload,
|
||||||
|
onToggleSelect,
|
||||||
className = '',
|
className = '',
|
||||||
allowDownloads = true
|
allowDownloads = true,
|
||||||
|
slug,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions,
|
||||||
|
onQuickComment
|
||||||
}) => {
|
}) => {
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = React.useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = React.useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = React.useState<{ name: string; email: string } | null>(null);
|
||||||
|
const [likedLocal, setLikedLocal] = React.useState(false);
|
||||||
|
const canComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onQuickComment);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<div
|
<div
|
||||||
className={`relative group cursor-pointer overflow-hidden rounded-lg bg-neutral-100 ${className}`}
|
className={`relative group cursor-pointer overflow-hidden rounded-lg bg-neutral-100 ${className}`}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
@@ -65,18 +88,72 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${likedLocal ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedLocal(true);
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={likedLocal}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${likedLocal ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{canComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onQuickComment?.(); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Feedback Indicators (bottom-left) */}
|
||||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
{(photo.like_count > 0 || likedLocal) && (
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
</div>
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`Select ${photo.filename}`}
|
||||||
|
role="checkbox"
|
||||||
|
aria-checked={isSelected}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
{photo.type === 'collage' && (
|
{photo.type === 'collage' && (
|
||||||
<div className="absolute bottom-2 left-2">
|
<div className="absolute bottom-2 left-2">
|
||||||
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
||||||
@@ -85,17 +162,39 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
onPhotoSelect,
|
onPhotoSelect,
|
||||||
allowDownloads = true
|
allowDownloads = true,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
// const { theme } = useTheme();
|
// const { theme } = useTheme();
|
||||||
// const gallerySettings = theme.gallerySettings || {};
|
// const gallerySettings = theme.gallerySettings || {};
|
||||||
@@ -136,10 +235,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo0}
|
photo={photo0}
|
||||||
isSelected={selectedPhotos.has(photo0.id)}
|
isSelected={selectedPhotos.has(photo0.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
onClick={() => onPhotoClick(idx0)}
|
||||||
onDownload={(e) => onDownload(photo0, e)}
|
onDownload={(e) => onDownload(photo0, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||||
className="col-span-1"
|
className="col-span-1"
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div className="grid grid-rows-2 gap-2">
|
<div className="grid grid-rows-2 gap-2">
|
||||||
@@ -148,22 +252,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo1}
|
photo={photo1}
|
||||||
isSelected={selectedPhotos.has(photo1.id)}
|
isSelected={selectedPhotos.has(photo1.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
onClick={() => onPhotoClick(idx1)}
|
||||||
onDownload={(e) => onDownload(photo1, e)}
|
onDownload={(e) => onDownload(photo1, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{photo2 && (
|
{photo2 && (
|
||||||
<MosaicPhoto
|
<MosaicPhoto
|
||||||
photo={photo2}
|
photo={photo2}
|
||||||
isSelected={selectedPhotos.has(photo2.id)}
|
isSelected={selectedPhotos.has(photo2.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
onClick={() => onPhotoClick(idx2)}
|
||||||
onDownload={(e) => onDownload(photo2, e)}
|
onDownload={(e) => onDownload(photo2, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -186,6 +300,10 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(currentIndex); }}
|
||||||
/>
|
/>
|
||||||
) : null;
|
) : null;
|
||||||
})}
|
})}
|
||||||
@@ -209,10 +327,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo0}
|
photo={photo0}
|
||||||
isSelected={selectedPhotos.has(photo0.id)}
|
isSelected={selectedPhotos.has(photo0.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
onClick={() => onPhotoClick(idx0)}
|
||||||
onDownload={(e) => onDownload(photo0, e)}
|
onDownload={(e) => onDownload(photo0, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||||
className="col-span-2"
|
className="col-span-2"
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div className="grid grid-rows-2 gap-2">
|
<div className="grid grid-rows-2 gap-2">
|
||||||
@@ -221,22 +344,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo1}
|
photo={photo1}
|
||||||
isSelected={selectedPhotos.has(photo1.id)}
|
isSelected={selectedPhotos.has(photo1.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
onClick={() => onPhotoClick(idx1)}
|
||||||
onDownload={(e) => onDownload(photo1, e)}
|
onDownload={(e) => onDownload(photo1, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{photo2 && (
|
{photo2 && (
|
||||||
<MosaicPhoto
|
<MosaicPhoto
|
||||||
photo={photo2}
|
photo={photo2}
|
||||||
isSelected={selectedPhotos.has(photo2.id)}
|
isSelected={selectedPhotos.has(photo2.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
onClick={() => onPhotoClick(idx2)}
|
||||||
onDownload={(e) => onDownload(photo2, e)}
|
onDownload={(e) => onDownload(photo2, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -263,10 +396,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo}
|
photo={photo}
|
||||||
isSelected={selectedPhotos.has(photo.id)}
|
isSelected={selectedPhotos.has(photo.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(index, photo.id)}
|
onClick={() => onPhotoClick(index)}
|
||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||||
className="aspect-square"
|
className="aspect-square"
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(index); }}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -282,4 +420,4 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
{renderMosaicLayout()}
|
{renderMosaicLayout()}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,24 +1,35 @@
|
|||||||
import React, { useMemo } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
import { Download, Maximize2, Check, Calendar } from 'lucide-react';
|
import { Download, Maximize2, Check, Calendar, Heart, MessageSquare } from 'lucide-react';
|
||||||
import { format, parseISO, startOfDay, startOfWeek, startOfMonth } from 'date-fns';
|
import { format, parseISO, startOfDay, startOfWeek, startOfMonth } from 'date-fns';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
|
|
||||||
export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
onPhotoSelect,
|
onPhotoSelect,
|
||||||
allowDownloads = true
|
allowDownloads = true,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
|
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
const gallerySettings = theme.gallerySettings || {};
|
const gallerySettings = theme.gallerySettings || {};
|
||||||
const grouping = gallerySettings.timelineGrouping || 'day';
|
const grouping = gallerySettings.timelineGrouping || 'day';
|
||||||
const showDates = gallerySettings.timelineShowDates !== false;
|
const showDates = gallerySettings.timelineShowDates !== false;
|
||||||
|
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||||
|
|
||||||
// Group photos by date
|
// Group photos by date
|
||||||
const groupedPhotos = useMemo(() => {
|
const groupedPhotos = useMemo(() => {
|
||||||
@@ -90,13 +101,7 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
<div
|
<div
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
className="relative group cursor-pointer aspect-square"
|
className="relative group cursor-pointer aspect-square"
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(actualIndex)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(actualIndex);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={photo.thumbnail_url || photo.url}
|
src={photo.thumbnail_url || photo.url}
|
||||||
@@ -137,17 +142,70 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${likedIds.has(photo.id) ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedIds(prev => new Set(prev).add(photo.id));
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={likedIds.has(photo.id)}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${likedIds.has(photo.id) ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{canQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onOpenPhotoWithFeedback?.(actualIndex); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{(photo.like_count > 0 || likedIds.has(photo.id)) && (
|
||||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
</div>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`Select ${photo.filename}`}
|
||||||
|
role="checkbox"
|
||||||
|
aria-checked={selectedPhotos.has(photo.id)}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onPhotoSelect && onPhotoSelect(photo.id); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -155,6 +213,23 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import { authService } from '../services';
|
import { authService, galleryService } from '../services';
|
||||||
import { cleanupOldGalleryAuth } from '../utils/cleanupGalleryAuth';
|
import { cleanupOldGalleryAuth } from '../utils/cleanupGalleryAuth';
|
||||||
|
|
||||||
interface GalleryEvent {
|
interface GalleryEvent {
|
||||||
@@ -79,6 +79,35 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
|||||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// No stored auth; check for token in URL and auto-authenticate
|
||||||
|
const parts = window.location.pathname.split('/');
|
||||||
|
const urlToken = parts.length >= 5 ? parts[4] : (parts.length >= 4 ? parts[3] : undefined);
|
||||||
|
if (urlToken) {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
// Verify token against backend
|
||||||
|
const verify = await galleryService.verifyToken(currentSlug, urlToken);
|
||||||
|
if (verify?.valid) {
|
||||||
|
// Store token and fetch event via photos endpoint to get full event object
|
||||||
|
localStorage.setItem(`gallery_token_${currentSlug}`, urlToken);
|
||||||
|
const data = await galleryService.getGalleryPhotos(currentSlug);
|
||||||
|
if (data?.event) {
|
||||||
|
setEvent(data.event);
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
localStorage.setItem(`gallery_event_${currentSlug}`, JSON.stringify(data.event));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Invalid token; ensure any residual storage is cleared
|
||||||
|
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||||
|
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
@@ -128,4 +157,4 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
|||||||
{children}
|
{children}
|
||||||
</GalleryAuthContext.Provider>
|
</GalleryAuthContext.Provider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -11,9 +11,15 @@ export const useGalleryInfo = (slug: string, token?: string) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGalleryPhotos = (slug: string, filter?: 'liked' | 'favorited' | 'all', guestId?: string, enabled: boolean = true) => {
|
export const useGalleryPhotos = (
|
||||||
|
slug: string,
|
||||||
|
filter?: 'liked' | 'commented' | 'rated' | 'all',
|
||||||
|
guestId?: string,
|
||||||
|
enabled: boolean = true
|
||||||
|
) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['gallery-photos', slug, filter, guestId],
|
queryKey: ['gallery-photos', slug, filter, guestId],
|
||||||
|
// Pass guestId so backend can filter per-guest views when needed
|
||||||
queryFn: () => galleryService.getGalleryPhotos(slug, filter, guestId),
|
queryFn: () => galleryService.getGalleryPhotos(slug, filter, guestId),
|
||||||
enabled,
|
enabled,
|
||||||
retry: 1,
|
retry: 1,
|
||||||
@@ -63,4 +69,4 @@ export const useDownloadAllPhotos = () => {
|
|||||||
toast.error('Failed to download photos');
|
toast.error('Failed to download photos');
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -36,6 +36,11 @@
|
|||||||
"customize": "Anpassen",
|
"customize": "Anpassen",
|
||||||
"hide": "Ausblenden",
|
"hide": "Ausblenden",
|
||||||
"unknown": "Unbekannt",
|
"unknown": "Unbekannt",
|
||||||
|
"notSet": "Nicht festgelegt",
|
||||||
|
"of": "von",
|
||||||
|
"up": "Nach oben",
|
||||||
|
"select": "Auswählen",
|
||||||
|
"selected": "Ausgewählt",
|
||||||
"chunk": "Teil"
|
"chunk": "Teil"
|
||||||
},
|
},
|
||||||
"upload": {
|
"upload": {
|
||||||
@@ -50,6 +55,10 @@
|
|||||||
"uploadFailed": "Upload fehlgeschlagen",
|
"uploadFailed": "Upload fehlgeschlagen",
|
||||||
"someFilesFailed": "Einige Dateien konnten nicht hochgeladen werden",
|
"someFilesFailed": "Einige Dateien konnten nicht hochgeladen werden",
|
||||||
"uploadPhotos": "Fotos hochladen",
|
"uploadPhotos": "Fotos hochladen",
|
||||||
|
"importExternal": "Aus externem Ordner importieren",
|
||||||
|
"externalImportInfo": "Alle Bilder aus dem ausgewählten Ordner werden importiert.",
|
||||||
|
"selectExternalFolder": "Externen Ordner unter /external-media auswählen",
|
||||||
|
"importFromSelectedFolder": "Ausgewählten Ordner importieren",
|
||||||
"maxFilesReached": "Maximal 500 Dateien erlaubt",
|
"maxFilesReached": "Maximal 500 Dateien erlaubt",
|
||||||
"someFilesSkipped": "Einige Dateien wurden übersprungen (500 Dateien Limit)",
|
"someFilesSkipped": "Einige Dateien wurden übersprungen (500 Dateien Limit)",
|
||||||
"tooManyFiles": "Maximal 500 Dateien können gleichzeitig hochgeladen werden",
|
"tooManyFiles": "Maximal 500 Dateien können gleichzeitig hochgeladen werden",
|
||||||
@@ -66,6 +75,342 @@
|
|||||||
"backup": "Backup & Wiederherstellung",
|
"backup": "Backup & Wiederherstellung",
|
||||||
"cmsPages": "CMS-Seiten"
|
"cmsPages": "CMS-Seiten"
|
||||||
},
|
},
|
||||||
|
"backup": {
|
||||||
|
"external": {
|
||||||
|
"warning": {
|
||||||
|
"title": "Externe Medien ausgeschlossen",
|
||||||
|
"body": "Diese Installation referenziert Fotos aus /external-media. Diese Originale sind von Backups ausgeschlossen. Thumbnails und Datenbank werden weiterhin gesichert."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"title": "Backup-Verwaltung",
|
||||||
|
"subtitle": "System-Backups verwalten, automatische Backups konfigurieren und aus früheren Backups wiederherstellen.",
|
||||||
|
"tabs": {
|
||||||
|
"dashboard": "Dashboard",
|
||||||
|
"configuration": "Konfiguration",
|
||||||
|
"history": "Backup-Verlauf",
|
||||||
|
"restore": "Wiederherstellen"
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"inProgress": "Backup wird ausgeführt...",
|
||||||
|
"lastBackup": "Letztes Backup",
|
||||||
|
"noBackups": "Keine Backups gefunden",
|
||||||
|
"nextBackup": "Nächstes Backup",
|
||||||
|
"notScheduled": "Nicht geplant",
|
||||||
|
"enabled": "Aktiviert",
|
||||||
|
"disabled": "Deaktiviert"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"runBackupNow": "Backup jetzt starten",
|
||||||
|
"starting": "Starte...",
|
||||||
|
"running": "Läuft...",
|
||||||
|
"testConnection": "Verbindung testen",
|
||||||
|
"save": "Konfiguration speichern",
|
||||||
|
"delete": "Löschen",
|
||||||
|
"view": "Details anzeigen",
|
||||||
|
"download": "Herunterladen",
|
||||||
|
"refresh": "Aktualisieren"
|
||||||
|
},
|
||||||
|
"dashboard": {
|
||||||
|
"backupHealth": "Backup-Gesundheit",
|
||||||
|
"health": {
|
||||||
|
"title": "Backup-Gesundheit"
|
||||||
|
},
|
||||||
|
"healthMessages": {
|
||||||
|
"noBackups": "Keine Backups gefunden",
|
||||||
|
"lastBackupFailed": "Letztes Backup fehlgeschlagen",
|
||||||
|
"upToDate": "Backup ist aktuell",
|
||||||
|
"recent": "Backup ist kürzlich",
|
||||||
|
"gettingOld": "Backup wird alt",
|
||||||
|
"outdated": "Backup ist veraltet"
|
||||||
|
},
|
||||||
|
"stats": {
|
||||||
|
"totalBackups": "Gesamt-Backups",
|
||||||
|
"backupSize": "Backup-Größe",
|
||||||
|
"lastDuration": "Letzte Dauer",
|
||||||
|
"backupStatus": "Backup-Status",
|
||||||
|
"last": "Letztes",
|
||||||
|
"files": "Dateien",
|
||||||
|
"minutes": "{{count}}m",
|
||||||
|
"active": "Aktiv",
|
||||||
|
"inactive": "Inaktiv",
|
||||||
|
"noBackupsYet": "Noch keine Backups"
|
||||||
|
},
|
||||||
|
"recentActivity": {
|
||||||
|
"title": "Letzte Backup-Aktivitäten"
|
||||||
|
},
|
||||||
|
"notConfigured": {
|
||||||
|
"title": "Backup nicht konfiguriert",
|
||||||
|
"message": "Bitte konfigurieren Sie die Backup-Einstellungen im Tab \"Konfiguration\", bevor Sie Backups ausführen."
|
||||||
|
},
|
||||||
|
"coverage": {
|
||||||
|
"title": "Backup-Abdeckung",
|
||||||
|
"database": "Datenbank",
|
||||||
|
"photos": "Fotos",
|
||||||
|
"archives": "Archive",
|
||||||
|
"systemFiles": "Systemdateien",
|
||||||
|
"included": "Enthalten",
|
||||||
|
"excluded": "Ausgeschlossen",
|
||||||
|
"optional": "Optional"
|
||||||
|
},
|
||||||
|
"storageDestination": "Speicherziel",
|
||||||
|
"nextScheduledBackup": "Nächstes geplantes Backup",
|
||||||
|
"backupType": "{{type}}-Backup",
|
||||||
|
"noDestinationSet": "Kein Ziel gesetzt"
|
||||||
|
},
|
||||||
|
"configuration": {
|
||||||
|
"enableBackup": "Automatische Backups aktivieren",
|
||||||
|
"enableBackupHelp": "Backups automatisch gemäß Zeitplan erstellen",
|
||||||
|
"destinationType": "Backup-Ziel",
|
||||||
|
"destinationTypes": {
|
||||||
|
"local": {
|
||||||
|
"name": "Lokaler Speicher",
|
||||||
|
"description": "Backups auf dem lokalen Dateisystem speichern"
|
||||||
|
},
|
||||||
|
"rsync": {
|
||||||
|
"name": "Remote-Server (Rsync)",
|
||||||
|
"description": "Backups per SSH/Rsync auf einen entfernten Server synchronisieren"
|
||||||
|
},
|
||||||
|
"s3": {
|
||||||
|
"name": "S3-kompatibler Speicher",
|
||||||
|
"description": "Backups in Amazon S3 oder kompatiblen Objektspeicher ablegen"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"fields": {
|
||||||
|
"destinationPath": "Zielpfad",
|
||||||
|
"destinationPathHelp": "Lokaler Verzeichnispfad für Backups",
|
||||||
|
"destinationPathPlaceholder": "/pfad/zum/backup/verzeichnis",
|
||||||
|
"rsyncHost": "Remote Host",
|
||||||
|
"rsyncHostPlaceholder": "backup.example.com",
|
||||||
|
"rsyncUser": "Benutzer",
|
||||||
|
"rsyncUserPlaceholder": "backupuser",
|
||||||
|
"rsyncPath": "Remote-Pfad",
|
||||||
|
"rsyncPathPlaceholder": "/pfad/auf/server",
|
||||||
|
"rsyncSshKey": "SSH-Schlüssel",
|
||||||
|
"rsyncSshKeyPlaceholder": "Privater SSH-Schlüssel (PEM)",
|
||||||
|
"rsyncSshKeyHelp": "Fügen Sie den privaten SSH-Schlüssel im PEM-Format ein.",
|
||||||
|
"s3Endpoint": "S3-Endpunkt-URL",
|
||||||
|
"s3EndpointHelp": "z. B. https://s3.amazonaws.com oder Ihr MinIO-Endpunkt",
|
||||||
|
"s3Bucket": "Bucket-Name",
|
||||||
|
"s3Region": "Region",
|
||||||
|
"s3AccessKey": "Access Key ID",
|
||||||
|
"s3SecretKey": "Secret Access Key"
|
||||||
|
},
|
||||||
|
"schedule": {
|
||||||
|
"title": "Zeitplan",
|
||||||
|
"scheduleType": "Zeitplantyp",
|
||||||
|
"customCron": "Eigener Cron-Ausdruck",
|
||||||
|
"customCronHelp": "Cron-Ausdruck für benutzerdefinierten Zeitplan",
|
||||||
|
"retention": "Aufbewahrung (Tage)",
|
||||||
|
"retentionHelp": "Anzahl der Tage, nach denen alte Backups automatisch gelöscht werden"
|
||||||
|
},
|
||||||
|
"whatToBackup": {
|
||||||
|
"title": "Was soll gesichert werden",
|
||||||
|
"database": "Datenbank",
|
||||||
|
"databaseHelp": "Datenbank (Einstellungen, Events, Benutzer)",
|
||||||
|
"photos": "Fotos",
|
||||||
|
"photosHelp": "Aktive Galeriefotos sichern",
|
||||||
|
"archives": "Archive",
|
||||||
|
"archivesHelp": "Archivierte ZIP-Dateien",
|
||||||
|
"thumbnails": "Thumbnails",
|
||||||
|
"thumbnailsHelp": "Generierte Vorschaubilder"
|
||||||
|
},
|
||||||
|
"advancedOptions": {
|
||||||
|
"title": "Erweiterte Optionen",
|
||||||
|
"compression": "Kompression",
|
||||||
|
"compressionHelp": "Backups komprimieren, um Speicherplatz zu sparen",
|
||||||
|
"encryption": "Verschlüsselung",
|
||||||
|
"encryptionHelp": "Backups mit einer Passphrase verschlüsseln",
|
||||||
|
"encryptionPassphrase": "Verschlüsselungs-Passphrase",
|
||||||
|
"encryptionPassphraseHelp": "Passphrase zum Verschlüsseln/Entschlüsseln der Backups"
|
||||||
|
},
|
||||||
|
"savingSettings": "Einstellungen werden gespeichert...",
|
||||||
|
"saveSettings": "Einstellungen speichern"
|
||||||
|
},
|
||||||
|
"history": {
|
||||||
|
"columns": {
|
||||||
|
"status": "Status",
|
||||||
|
"dateTime": "Datum & Uhrzeit",
|
||||||
|
"type": "Typ",
|
||||||
|
"size": "Größe",
|
||||||
|
"duration": "Dauer",
|
||||||
|
"actions": "Aktionen"
|
||||||
|
},
|
||||||
|
"details": "Details",
|
||||||
|
"statistics": "Statistiken",
|
||||||
|
"errors": "Fehler",
|
||||||
|
"backupDetails": {
|
||||||
|
"backupId": "Backup-ID",
|
||||||
|
"startTime": "Startzeit",
|
||||||
|
"endTime": "Endzeit",
|
||||||
|
"destination": "Ziel",
|
||||||
|
"filesProcessed": "Verarbeitete Dateien",
|
||||||
|
"totalSize": "Gesamtgröße",
|
||||||
|
"compressionRatio": "Kompressionsrate",
|
||||||
|
"errorLog": "Fehlerprotokoll",
|
||||||
|
"noErrors": "Keine Fehler aufgetreten"
|
||||||
|
},
|
||||||
|
"pagination": {
|
||||||
|
"showing": "Zeige {{from}}–{{to}} von {{total}} Backups",
|
||||||
|
"previous": "Zurück",
|
||||||
|
"next": "Weiter"
|
||||||
|
},
|
||||||
|
"filter": {
|
||||||
|
"allStatus": "Alle Status",
|
||||||
|
"completed": "Abgeschlossen",
|
||||||
|
"failed": "Fehlgeschlagen",
|
||||||
|
"running": "Läuft",
|
||||||
|
"partial": "Teilweise"
|
||||||
|
},
|
||||||
|
"noBackupsFound": "Keine Backups gefunden",
|
||||||
|
"backupsWillAppear": "Backups erscheinen hier, sobald sie erstellt wurden",
|
||||||
|
"messages": {
|
||||||
|
"deleteSuccess": "Backup erfolgreich gelöscht"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"restore": {
|
||||||
|
"steps": {
|
||||||
|
"selectSource": "Quelle auswählen",
|
||||||
|
"chooseBackup": "Backup wählen",
|
||||||
|
"restoreOptions": "Wiederherstellungsoptionen",
|
||||||
|
"reviewConfirm": "Prüfen & Bestätigen",
|
||||||
|
"progress": "Fortschritt"
|
||||||
|
},
|
||||||
|
"source": {
|
||||||
|
"title": "Backup-Quelle auswählen",
|
||||||
|
"subtitle": "Wählen Sie, woher das Backup wiederhergestellt werden soll",
|
||||||
|
"local": {
|
||||||
|
"name": "Lokales Backup",
|
||||||
|
"description": "Vom lokalen Dateisystem wiederherstellen"
|
||||||
|
},
|
||||||
|
"s3": {
|
||||||
|
"name": "S3-Speicher",
|
||||||
|
"description": "Aus S3-Bucket wiederherstellen"
|
||||||
|
},
|
||||||
|
"upload": {
|
||||||
|
"name": "Backup hochladen",
|
||||||
|
"description": "Eine Backup-Datei hochladen",
|
||||||
|
"comingSoon": "Upload-Funktion folgt in Kürze"
|
||||||
|
},
|
||||||
|
"configuration": {
|
||||||
|
"s3": "S3-Konfiguration",
|
||||||
|
"endpoint": "S3-Endpunkt-URL",
|
||||||
|
"bucket": "Bucket-Name",
|
||||||
|
"accessKey": "Access Key ID",
|
||||||
|
"secretKey": "Secret Access Key"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"backup": {
|
||||||
|
"title": "Backup zum Wiederherstellen wählen",
|
||||||
|
"subtitle": "Aus verfügbaren Backups auswählen",
|
||||||
|
"noBackupsFound": "Keine Backups in der gewählten Quelle gefunden",
|
||||||
|
"encrypted": "Verschlüsseltes Backup",
|
||||||
|
"encryptedMessage": "Zum Wiederherstellen dieses Backups wird die Verschlüsselungs-Passphrase benötigt.",
|
||||||
|
"enterPassphrase": "Verschlüsselungs-Passphrase eingeben",
|
||||||
|
"at": "um"
|
||||||
|
},
|
||||||
|
"restoreTypes": {
|
||||||
|
"full": {
|
||||||
|
"name": "Vollständige Wiederherstellung",
|
||||||
|
"description": "Alles wiederherstellen (Datenbank, Fotos und Archive)",
|
||||||
|
"warning": "Dies ersetzt alle aktuellen Daten"
|
||||||
|
},
|
||||||
|
"database": {
|
||||||
|
"name": "Nur Datenbank",
|
||||||
|
"description": "Nur die Datenbank wiederherstellen (Einstellungen, Events, Benutzer)",
|
||||||
|
"warning": "Aktuelle Datenbank wird ersetzt"
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
"name": "Nur Dateien",
|
||||||
|
"description": "Nur Fotos und Archive wiederherstellen",
|
||||||
|
"warning": "Vorhandene Dateien können überschrieben werden"
|
||||||
|
},
|
||||||
|
"selective": {
|
||||||
|
"name": "Selektive Wiederherstellung",
|
||||||
|
"description": "Bestimmte Elemente zur Wiederherstellung auswählen",
|
||||||
|
"warning": "Es werden nur ausgewählte Elemente wiederhergestellt"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"title": "Wiederherstellungsoptionen",
|
||||||
|
"subtitle": "Auswählen, was wiederhergestellt werden soll",
|
||||||
|
"additionalOptions": {
|
||||||
|
"title": "Zusätzliche Optionen",
|
||||||
|
"skipPreBackup": "Vorab-Backup überspringen",
|
||||||
|
"skipPreBackupHelp": "Standardmäßig wird vor der Wiederherstellung ein Backup erstellt. Aktivieren, um dies zu überspringen.",
|
||||||
|
"force": "Wiederherstellung erzwingen",
|
||||||
|
"forceHelp": "Sicherheitsprüfungen und Warnungen überschreiben (mit Vorsicht verwenden)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"confirmation": {
|
||||||
|
"title": "Prüfen & Bestätigen",
|
||||||
|
"subtitle": "Bitte prüfen Sie Ihre Wiederherstellungskonfiguration",
|
||||||
|
"validation": {
|
||||||
|
"passed": "Validierung bestanden",
|
||||||
|
"failed": "Validierung fehlgeschlagen",
|
||||||
|
"checking": "Wiederherstellungskonfiguration wird geprüft..."
|
||||||
|
},
|
||||||
|
"spaceCheck": {
|
||||||
|
"title": "Speicherplatz",
|
||||||
|
"required": "Erforderlich",
|
||||||
|
"available": "Verfügbar",
|
||||||
|
"insufficient": "Nicht genügend Speicherplatz"
|
||||||
|
},
|
||||||
|
"summary": {
|
||||||
|
"title": "Zusammenfassung",
|
||||||
|
"source": "Quelle",
|
||||||
|
"backupDate": "Backup-Datum",
|
||||||
|
"restoreType": "Art der Wiederherstellung",
|
||||||
|
"preBackup": "Vorab-Backup",
|
||||||
|
"enabled": "Aktiviert",
|
||||||
|
"skipped": "Übersprungen"
|
||||||
|
},
|
||||||
|
"warning": {
|
||||||
|
"title": "Wichtiger Hinweis",
|
||||||
|
"message": "Diese Wiederherstellung ersetzt bestehende Daten. Stellen Sie sicher, dass Sie ein aktuelles Backup haben. Dieser Vorgang kann nicht rückgängig gemacht werden."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"progress": {
|
||||||
|
"title": "Fortschritt der Wiederherstellung",
|
||||||
|
"inProgress": "Wiederherstellung läuft...",
|
||||||
|
"completed": "Wiederherstellung abgeschlossen",
|
||||||
|
"overallProgress": "Gesamtfortschritt",
|
||||||
|
"current": "Aktuell",
|
||||||
|
"statusDetails": "Statusdetails",
|
||||||
|
"restoreLogs": "Wiederherstellungs-Logs",
|
||||||
|
"steps": {
|
||||||
|
"completed": "Abgeschlossen",
|
||||||
|
"running": "Läuft",
|
||||||
|
"failed": "Fehlgeschlagen",
|
||||||
|
"pending": "Ausstehend"
|
||||||
|
},
|
||||||
|
"success": {
|
||||||
|
"title": "Wiederherstellung erfolgreich abgeschlossen",
|
||||||
|
"message": "Ihre Daten wurden wiederhergestellt. Bitte prüfen Sie, ob alles korrekt funktioniert."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"back": "Zurück",
|
||||||
|
"next": "Weiter",
|
||||||
|
"startRestore": "Wiederherstellung starten",
|
||||||
|
"starting": "Starte...",
|
||||||
|
"validating": "Validiere...",
|
||||||
|
"startNewRestore": "Neue Wiederherstellung starten"
|
||||||
|
},
|
||||||
|
"messages": {
|
||||||
|
"restoreStarted": "Wiederherstellung erfolgreich gestartet"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"messages": {
|
||||||
|
"backupStarted": "Backup erfolgreich gestartet",
|
||||||
|
"backupFailed": "Backup konnte nicht gestartet werden",
|
||||||
|
"configUpdated": "Backup-Konfiguration aktualisiert",
|
||||||
|
"configUpdateFailed": "Konfiguration konnte nicht aktualisiert werden",
|
||||||
|
"backupDeleted": "Backup erfolgreich gelöscht",
|
||||||
|
"deleteFailed": "Backup konnte nicht gelöscht werden",
|
||||||
|
"testEmailSent": "Verbindung erfolgreich getestet!",
|
||||||
|
"testEmailFailed": "Verbindungstest fehlgeschlagen"
|
||||||
|
}
|
||||||
|
},
|
||||||
"archives": {
|
"archives": {
|
||||||
"title": "Archive",
|
"title": "Archive",
|
||||||
"subtitle": "Archivierte Fotogalerien verwalten",
|
"subtitle": "Archivierte Fotogalerien verwalten",
|
||||||
@@ -734,6 +1079,24 @@
|
|||||||
"bulk_download": "{{count}} Fotos heruntergeladen von {{eventName}}",
|
"bulk_download": "{{count}} Fotos heruntergeladen von {{eventName}}",
|
||||||
"gallery_password_entry": "Passwort eingegeben für {{eventName}}",
|
"gallery_password_entry": "Passwort eingegeben für {{eventName}}",
|
||||||
"expiration_warning_viewed": "Ablaufwarnung angesehen für {{eventName}}",
|
"expiration_warning_viewed": "Ablaufwarnung angesehen für {{eventName}}",
|
||||||
|
"feedback_settings_updated": "Feedback-Einstellungen aktualisiert",
|
||||||
|
"feedback_moderated": "Feedback moderiert",
|
||||||
|
"feedback_deleted": "Feedback gelöscht",
|
||||||
|
"photo_like": "Foto mit Gefällt mir markiert in {{eventName}}",
|
||||||
|
"photo_favorite": "Foto favorisiert in {{eventName}}",
|
||||||
|
"photo_rating": "Foto bewertet in {{eventName}}",
|
||||||
|
"photo_comment": "Foto kommentiert in {{eventName}}",
|
||||||
|
"guest_feedback_like": "Gast hat ein Foto mit Gefällt mir markiert in {{eventName}}",
|
||||||
|
"guest_feedback_favorite": "Gast hat ein Foto favorisiert in {{eventName}}",
|
||||||
|
"guest_feedback_rating": "Gast hat ein Foto bewertet in {{eventName}}",
|
||||||
|
"guest_feedback_comment": "Gast hat ein Foto kommentiert in {{eventName}}",
|
||||||
|
"word_filter_added": "Wortfilter hinzugefügt",
|
||||||
|
"external_import_completed": "Externer Medienimport abgeschlossen ({{imported}} importiert, {{skipped}} übersprungen)",
|
||||||
|
"bulk_archive_completed": "Sammelarchivierung abgeschlossen",
|
||||||
|
"event_activated": "Veranstaltung aktiviert: {{eventName}}",
|
||||||
|
"event_deactivated": "Veranstaltung deaktiviert: {{eventName}}",
|
||||||
|
"photo_deleted": "Foto gelöscht aus {{eventName}}",
|
||||||
|
"photos_bulk_deleted": "{{count}} Fotos gelöscht aus {{eventName}}",
|
||||||
"settings_updated": "Einstellungen aktualisiert",
|
"settings_updated": "Einstellungen aktualisiert",
|
||||||
"event_updated": "Veranstaltung aktualisiert: {{eventName}}",
|
"event_updated": "Veranstaltung aktualisiert: {{eventName}}",
|
||||||
"event_deleted": "Veranstaltung gelöscht: {{eventName}}",
|
"event_deleted": "Veranstaltung gelöscht: {{eventName}}",
|
||||||
@@ -1437,4 +1800,4 @@
|
|||||||
"poweredBy": "Bereitgestellt von PicPeak",
|
"poweredBy": "Bereitgestellt von PicPeak",
|
||||||
"devModeHint": "Entwicklungsmodus: E-Mail: admin@example.com, Passwort: admin123"
|
"devModeHint": "Entwicklungsmodus: E-Mail: admin@example.com, Passwort: admin123"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,11 @@
|
|||||||
"customize": "Customize",
|
"customize": "Customize",
|
||||||
"hide": "Hide",
|
"hide": "Hide",
|
||||||
"unknown": "Unknown",
|
"unknown": "Unknown",
|
||||||
|
"notSet": "Not set",
|
||||||
|
"of": "of",
|
||||||
|
"up": "Up",
|
||||||
|
"select": "Select",
|
||||||
|
"selected": "Selected",
|
||||||
"chunk": "Chunk"
|
"chunk": "Chunk"
|
||||||
},
|
},
|
||||||
"upload": {
|
"upload": {
|
||||||
@@ -50,6 +55,10 @@
|
|||||||
"uploadFailed": "Upload failed",
|
"uploadFailed": "Upload failed",
|
||||||
"someFilesFailed": "Some files failed to upload",
|
"someFilesFailed": "Some files failed to upload",
|
||||||
"uploadPhotos": "Upload Photos",
|
"uploadPhotos": "Upload Photos",
|
||||||
|
"importExternal": "Import from External Folder",
|
||||||
|
"externalImportInfo": "All pictures from the selected folder will be imported.",
|
||||||
|
"selectExternalFolder": "Select external folder under /external-media",
|
||||||
|
"importFromSelectedFolder": "Import from selected folder",
|
||||||
"maxFilesReached": "Maximum 500 files allowed",
|
"maxFilesReached": "Maximum 500 files allowed",
|
||||||
"someFilesSkipped": "Some files were skipped (500 file limit)",
|
"someFilesSkipped": "Some files were skipped (500 file limit)",
|
||||||
"tooManyFiles": "Maximum 500 files can be uploaded at once",
|
"tooManyFiles": "Maximum 500 files can be uploaded at once",
|
||||||
@@ -812,6 +821,24 @@
|
|||||||
"bulk_download": "{{count}} photos downloaded from {{eventName}}",
|
"bulk_download": "{{count}} photos downloaded from {{eventName}}",
|
||||||
"gallery_password_entry": "Password entered for {{eventName}}",
|
"gallery_password_entry": "Password entered for {{eventName}}",
|
||||||
"expiration_warning_viewed": "Expiration warning viewed for {{eventName}}",
|
"expiration_warning_viewed": "Expiration warning viewed for {{eventName}}",
|
||||||
|
"feedback_settings_updated": "Feedback settings updated",
|
||||||
|
"feedback_moderated": "Feedback moderated",
|
||||||
|
"feedback_deleted": "Feedback deleted",
|
||||||
|
"photo_like": "Photo liked in {{eventName}}",
|
||||||
|
"photo_favorite": "Photo favorited in {{eventName}}",
|
||||||
|
"photo_rating": "Photo rated in {{eventName}}",
|
||||||
|
"photo_comment": "Photo commented in {{eventName}}",
|
||||||
|
"guest_feedback_like": "Guest liked a photo in {{eventName}}",
|
||||||
|
"guest_feedback_favorite": "Guest favorited a photo in {{eventName}}",
|
||||||
|
"guest_feedback_rating": "Guest rated a photo in {{eventName}}",
|
||||||
|
"guest_feedback_comment": "Guest commented on a photo in {{eventName}}",
|
||||||
|
"word_filter_added": "Word filter added",
|
||||||
|
"external_import_completed": "External media import completed ({{imported}} imported, {{skipped}} skipped)",
|
||||||
|
"bulk_archive_completed": "Bulk archive completed",
|
||||||
|
"event_activated": "Event activated: {{eventName}}",
|
||||||
|
"event_deactivated": "Event deactivated: {{eventName}}",
|
||||||
|
"photo_deleted": "Photo deleted from {{eventName}}",
|
||||||
|
"photos_bulk_deleted": "{{count}} photos deleted from {{eventName}}",
|
||||||
"settings_updated": "Settings updated",
|
"settings_updated": "Settings updated",
|
||||||
"event_updated": "Event updated: {{eventName}}",
|
"event_updated": "Event updated: {{eventName}}",
|
||||||
"event_deleted": "Event deleted: {{eventName}}",
|
"event_deleted": "Event deleted: {{eventName}}",
|
||||||
@@ -973,6 +1000,12 @@
|
|||||||
"pageUpdated": "Page updated successfully"
|
"pageUpdated": "Page updated successfully"
|
||||||
},
|
},
|
||||||
"backup": {
|
"backup": {
|
||||||
|
"external": {
|
||||||
|
"warning": {
|
||||||
|
"title": "External media excluded",
|
||||||
|
"body": "This installation references photos from /external-media. These originals are excluded from backups. Thumbnails and database are still backed up."
|
||||||
|
}
|
||||||
|
},
|
||||||
"title": "Backup Management",
|
"title": "Backup Management",
|
||||||
"subtitle": "Manage system backups, configure automated backups, and restore from previous backups.",
|
"subtitle": "Manage system backups, configure automated backups, and restore from previous backups.",
|
||||||
"tabs": {
|
"tabs": {
|
||||||
@@ -1496,4 +1529,4 @@
|
|||||||
"poweredBy": "Powered by PicPeak",
|
"poweredBy": "Powered by PicPeak",
|
||||||
"devModeHint": "Development Mode: Use email: admin@example.com, password: admin123"
|
"devModeHint": "Development Mode: Use email: admin@example.com, password: admin123"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -268,13 +268,13 @@ export const AdminDashboard: React.FC = () => {
|
|||||||
categoryName: activity.metadata?.category_name || ''
|
categoryName: activity.metadata?.category_name || ''
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if translation exists
|
// Translate; if key missing i18n returns the key string itself
|
||||||
const translated = t(translationKey, params);
|
const translated = t(translationKey, params) as string;
|
||||||
if (typeof translated === 'string') {
|
if (!translated || translated === translationKey) {
|
||||||
return translated;
|
// Fallback: format a readable English message
|
||||||
|
return adminService.formatActivityMessage(activity);
|
||||||
}
|
}
|
||||||
// Fallback to unknown activity if translation not found
|
return translated;
|
||||||
return t('admin.activities.unknown') as string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -302,4 +302,4 @@ export const AdminDashboard: React.FC = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
AdminDashboard.displayName = 'AdminDashboard';
|
AdminDashboard.displayName = 'AdminDashboard';
|
||||||
|
|||||||
@@ -28,9 +28,68 @@ import { EventCategoryManager, AdminPhotoGrid, AdminPhotoViewer, PhotoFilters, P
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { eventsService } from '../../services/events.service';
|
import { eventsService } from '../../services/events.service';
|
||||||
import { archiveService } from '../../services/archive.service';
|
import { archiveService } from '../../services/archive.service';
|
||||||
|
import { externalMediaService } from '../../services/externalMedia.service';
|
||||||
import { photosService, AdminPhoto } from '../../services/photos.service';
|
import { photosService, AdminPhoto } from '../../services/photos.service';
|
||||||
import { feedbackService, FeedbackSettings as FeedbackSettingsType } from '../../services/feedback.service';
|
import { feedbackService, FeedbackSettings as FeedbackSettingsType } from '../../services/feedback.service';
|
||||||
import { ThemeConfig, GALLERY_THEME_PRESETS } from '../../types/theme.types';
|
import { ThemeConfig, GALLERY_THEME_PRESETS } from '../../types/theme.types';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
const ExternalFolderPicker: React.FC<{ value: string; onChange: (p: string) => void }> = ({ value, onChange }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [entries, setEntries] = useState<{ path: string; entries: any[]; canNavigateUp: boolean } | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [currentPath, setCurrentPath] = useState<string>(value || '');
|
||||||
|
|
||||||
|
const load = async (p: string) => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const res = await externalMediaService.list(p);
|
||||||
|
setEntries(res);
|
||||||
|
setCurrentPath(res.path);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => { load(currentPath || ''); }, []);
|
||||||
|
|
||||||
|
const navigateUp = () => {
|
||||||
|
if (!entries?.canNavigateUp) return;
|
||||||
|
const parts = (entries.path || '').split('/').filter(Boolean);
|
||||||
|
parts.pop();
|
||||||
|
load(parts.join('/'));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-2 border rounded-lg p-3">
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<div className="text-sm text-neutral-600">/external-media/{entries?.path || ''}</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button className="text-sm underline" onClick={navigateUp} disabled={!entries?.canNavigateUp}>{t('common.up', 'Up')}</button>
|
||||||
|
<button className="text-sm underline" onClick={() => onChange(entries?.path || '')}>{t('common.select', 'Select')}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{loading ? (
|
||||||
|
<div className="text-sm text-neutral-500">{t('common.loading', 'Loading...')}</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-3 gap-2">
|
||||||
|
{entries?.entries?.filter((e: any) => e.type === 'dir').map((e: any) => (
|
||||||
|
<button
|
||||||
|
key={e.name}
|
||||||
|
onClick={() => load([entries?.path, e.name].filter(Boolean).join('/'))}
|
||||||
|
className="px-3 py-2 border rounded text-left hover:bg-neutral-50"
|
||||||
|
>
|
||||||
|
📁 {e.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{value && (
|
||||||
|
<div className="mt-2 text-xs text-neutral-600">{t('common.selected', 'Selected')}: /external-media/{value}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const EventDetailsPage: React.FC = () => {
|
export const EventDetailsPage: React.FC = () => {
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
@@ -67,7 +126,10 @@ export const EventDetailsPage: React.FC = () => {
|
|||||||
});
|
});
|
||||||
const [copiedLink, setCopiedLink] = useState(false);
|
const [copiedLink, setCopiedLink] = useState(false);
|
||||||
const [showPhotoUpload, setShowPhotoUpload] = useState(false);
|
const [showPhotoUpload, setShowPhotoUpload] = useState(false);
|
||||||
|
const [showExternalImport, setShowExternalImport] = useState(false);
|
||||||
const [activeTab, setActiveTab] = useState<'overview' | 'photos' | 'categories'>('overview');
|
const [activeTab, setActiveTab] = useState<'overview' | 'photos' | 'categories'>('overview');
|
||||||
|
const [externalPath, setExternalPath] = useState<string>('');
|
||||||
|
const [importing, setImporting] = useState<boolean>(false);
|
||||||
const [selectedPhoto, setSelectedPhoto] = useState<{ photo: AdminPhoto; index: number } | null>(null);
|
const [selectedPhoto, setSelectedPhoto] = useState<{ photo: AdminPhoto; index: number } | null>(null);
|
||||||
const [showPasswordReset, setShowPasswordReset] = useState(false);
|
const [showPasswordReset, setShowPasswordReset] = useState(false);
|
||||||
const [currentTheme, setCurrentTheme] = useState<ThemeConfig | null>(null);
|
const [currentTheme, setCurrentTheme] = useState<ThemeConfig | null>(null);
|
||||||
@@ -598,6 +660,15 @@ export const EventDetailsPage: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<dl className="space-y-4">
|
<dl className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<dt className="text-sm font-medium text-neutral-500">Source Mode</dt>
|
||||||
|
<dd className="mt-1 text-sm text-neutral-900">
|
||||||
|
{event.source_mode === 'reference' ? 'Reference (external folder)' : 'Managed (upload)'}
|
||||||
|
{event.source_mode === 'reference' && event.external_path ? (
|
||||||
|
<span className="text-neutral-500 ml-2">/external-media/{event.external_path}</span>
|
||||||
|
) : null}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-sm font-medium text-neutral-500">{t('events.welcomeMessage')}</dt>
|
<dt className="text-sm font-medium text-neutral-500">{t('events.welcomeMessage')}</dt>
|
||||||
<dd className="mt-1 text-sm text-neutral-900">
|
<dd className="mt-1 text-sm text-neutral-900">
|
||||||
@@ -951,6 +1022,17 @@ export const EventDetailsPage: React.FC = () => {
|
|||||||
>
|
>
|
||||||
{t('events.uploadPhotos')}
|
{t('events.uploadPhotos')}
|
||||||
</Button>
|
</Button>
|
||||||
|
{event.source_mode === 'reference' && (
|
||||||
|
<div className="ml-3">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setShowExternalImport(true)}
|
||||||
|
>
|
||||||
|
{t('events.importExternal', 'Import from External Folder')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Photo Grid */}
|
{/* Photo Grid */}
|
||||||
@@ -1024,6 +1106,59 @@ export const EventDetailsPage: React.FC = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* External Import Modal */}
|
||||||
|
{showExternalImport && (
|
||||||
|
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||||
|
<Card className="max-w-2xl w-full">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-xl font-semibold text-neutral-900">{t('events.importExternal', 'Import from External Folder')}</h2>
|
||||||
|
<button onClick={() => setShowExternalImport(false)} className="text-neutral-400 hover:text-neutral-600">
|
||||||
|
<X className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-3 text-sm text-neutral-700">
|
||||||
|
{t('events.externalImportInfo', 'All pictures from the selected folder will be imported.')}
|
||||||
|
</div>
|
||||||
|
<div className="mb-2 text-sm text-neutral-700">
|
||||||
|
{t('events.selectExternalFolder', 'Select external folder under /external-media')}
|
||||||
|
</div>
|
||||||
|
<ExternalFolderPicker value={externalPath || event.external_path || ''} onChange={setExternalPath} />
|
||||||
|
|
||||||
|
<div className="mt-4 flex justify-end gap-2">
|
||||||
|
<Button variant="outline" onClick={() => setShowExternalImport(false)}>
|
||||||
|
{t('common.cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
isLoading={importing}
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
setImporting(true);
|
||||||
|
const selected = externalPath || event.external_path || '';
|
||||||
|
if (!selected) {
|
||||||
|
toast.error(t('errors.somethingWentWrong', 'Something went wrong'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await externalMediaService.importEvent(parseInt(id!), selected, { recursive: true });
|
||||||
|
toast.success(t('toast.saveSuccess'));
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['admin-event', id] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['admin-event-photos', id] });
|
||||||
|
setShowExternalImport(false);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast.error(e?.response?.data?.error || 'Import failed');
|
||||||
|
} finally {
|
||||||
|
setImporting(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t('events.importFromSelectedFolder', 'Import from selected folder')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -17,9 +17,10 @@ import {
|
|||||||
Trash2
|
Trash2
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { format } from 'date-fns';
|
import { format, parseISO } from 'date-fns';
|
||||||
|
|
||||||
import { Button, Card, Loading } from '../../components/common';
|
import { Button, Card, Loading } from '../../components/common';
|
||||||
|
import { AdminAuthenticatedImage } from '../../components/admin/AdminAuthenticatedImage';
|
||||||
import { FeedbackSettings } from '../../components/admin';
|
import { FeedbackSettings } from '../../components/admin';
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { eventsService } from '../../services/events.service';
|
import { eventsService } from '../../services/events.service';
|
||||||
@@ -251,15 +252,13 @@ export const EventFeedbackPage: React.FC = () => {
|
|||||||
<Card key={item.id} className="overflow-hidden">
|
<Card key={item.id} className="overflow-hidden">
|
||||||
<div className="p-4 flex items-start gap-4">
|
<div className="p-4 flex items-start gap-4">
|
||||||
{item.photo_id && (
|
{item.photo_id && (
|
||||||
<img
|
<div className="w-16 h-16 overflow-hidden rounded">
|
||||||
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
<AdminAuthenticatedImage
|
||||||
alt={item.filename || 'Photo'}
|
src={`/admin/photos/${id}/thumbnail/${item.photo_id}`}
|
||||||
className="w-16 h-16 object-cover rounded"
|
alt={item.filename || 'Photo'}
|
||||||
onError={(e) => {
|
className="w-16 h-16 object-cover rounded"
|
||||||
// Hide image if thumbnail fails to load
|
/>
|
||||||
(e.target as HTMLImageElement).style.display = 'none';
|
</div>
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<div className="flex items-start justify-between">
|
<div className="flex items-start justify-between">
|
||||||
@@ -291,7 +290,12 @@ export const EventFeedbackPage: React.FC = () => {
|
|||||||
<p className="text-sm text-neutral-700">{item.comment_text}</p>
|
<p className="text-sm text-neutral-700">{item.comment_text}</p>
|
||||||
)}
|
)}
|
||||||
<p className="text-xs text-neutral-500 mt-1">
|
<p className="text-xs text-neutral-500 mt-1">
|
||||||
{format(new Date(item.created_at), 'PPpp')}
|
{(() => {
|
||||||
|
const d = typeof item.created_at === 'string'
|
||||||
|
? parseISO(item.created_at)
|
||||||
|
: new Date(item.created_at);
|
||||||
|
return isNaN(d.getTime()) ? t('common.unknownDate', 'Unknown date') : format(d, 'PPpp');
|
||||||
|
})()}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -493,7 +497,12 @@ export const EventFeedbackPage: React.FC = () => {
|
|||||||
<p className="text-sm text-neutral-700">{comment.comment_text}</p>
|
<p className="text-sm text-neutral-700">{comment.comment_text}</p>
|
||||||
<p className="text-xs text-neutral-500 mt-1">
|
<p className="text-xs text-neutral-500 mt-1">
|
||||||
{comment.guest_name} • {comment.filename} •
|
{comment.guest_name} • {comment.filename} •
|
||||||
{format(new Date(comment.created_at), 'PP')}
|
{(() => {
|
||||||
|
const d = typeof comment.created_at === 'string'
|
||||||
|
? parseISO(comment.created_at)
|
||||||
|
: new Date(comment.created_at);
|
||||||
|
return isNaN(d.getTime()) ? t('common.unknownDate', 'Unknown date') : format(d, 'PP');
|
||||||
|
})()}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -528,4 +537,4 @@ export const EventFeedbackPage: React.FC = () => {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { api } from '../config/api';
|
||||||
|
|
||||||
|
export interface ExternalEntry { name: string; type: 'dir' | 'file'; size?: number; mtime?: string }
|
||||||
|
|
||||||
|
export const externalMediaService = {
|
||||||
|
async list(pathRel: string = ''): Promise<{ path: string; entries: ExternalEntry[]; canNavigateUp: boolean }> {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (pathRel) params.set('path', pathRel);
|
||||||
|
const res = await api.get(`/admin/external-media/list?${params.toString()}`);
|
||||||
|
return res.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async importEvent(eventId: number, externalPath: string, options?: { recursive?: boolean; map?: { individual?: string; collages?: string } }): Promise<{ imported: number; skipped: number; thumbnailsQueued: number }> {
|
||||||
|
const res = await api.post(`/admin/external-media/events/${eventId}/import-external`, {
|
||||||
|
external_path: externalPath,
|
||||||
|
recursive: options?.recursive ?? true,
|
||||||
|
map: options?.map
|
||||||
|
});
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -16,7 +16,11 @@ export const galleryService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// Get gallery photos (requires auth)
|
// Get gallery photos (requires auth)
|
||||||
async getGalleryPhotos(slug: string, filter?: 'liked' | 'favorited' | 'all', guestId?: string): Promise<GalleryData> {
|
async getGalleryPhotos(
|
||||||
|
slug: string,
|
||||||
|
filter?: 'liked' | 'commented' | 'rated' | 'all',
|
||||||
|
guestId?: string
|
||||||
|
): Promise<GalleryData> {
|
||||||
const params: any = {};
|
const params: any = {};
|
||||||
if (filter && filter !== 'all' && guestId) {
|
if (filter && filter !== 'all' && guestId) {
|
||||||
params.filter = filter;
|
params.filter = filter;
|
||||||
@@ -28,19 +32,36 @@ export const galleryService = {
|
|||||||
|
|
||||||
// Download single photo
|
// Download single photo
|
||||||
async downloadPhoto(slug: string, photoId: number, filename: string): Promise<void> {
|
async downloadPhoto(slug: string, photoId: number, filename: string): Promise<void> {
|
||||||
const response = await api.get(`/gallery/${slug}/download/${photoId}`, {
|
try {
|
||||||
responseType: 'blob',
|
const response = await api.get(`/gallery/${slug}/download/${photoId}`, {
|
||||||
});
|
responseType: 'blob',
|
||||||
|
});
|
||||||
// Create download link
|
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
const link = document.createElement('a');
|
||||||
const link = document.createElement('a');
|
link.href = url;
|
||||||
link.href = url;
|
link.setAttribute('download', filename);
|
||||||
link.setAttribute('download', filename);
|
document.body.appendChild(link);
|
||||||
document.body.appendChild(link);
|
link.click();
|
||||||
link.click();
|
link.remove();
|
||||||
link.remove();
|
window.URL.revokeObjectURL(url);
|
||||||
window.URL.revokeObjectURL(url);
|
} catch (err) {
|
||||||
|
// Fallback: use the view endpoint if direct download fails (e.g., missing original)
|
||||||
|
try {
|
||||||
|
const response = await api.get(`/gallery/${slug}/photo/${photoId}`, {
|
||||||
|
responseType: 'blob',
|
||||||
|
});
|
||||||
|
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute('download', filename);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
} catch (fallbackErr) {
|
||||||
|
throw fallbackErr;
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Download all photos as ZIP
|
// Download all photos as ZIP
|
||||||
@@ -60,9 +81,25 @@ export const galleryService = {
|
|||||||
window.URL.revokeObjectURL(url);
|
window.URL.revokeObjectURL(url);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Download selected photos as ZIP
|
||||||
|
async downloadSelectedPhotos(slug: string, photoIds: number[]): Promise<void> {
|
||||||
|
const response = await api.post(`/gallery/${slug}/download-selected`, { photo_ids: photoIds }, {
|
||||||
|
responseType: 'blob',
|
||||||
|
});
|
||||||
|
|
||||||
|
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute('download', `${slug}-selected.zip`);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
|
|
||||||
// Get gallery statistics
|
// Get gallery statistics
|
||||||
async getGalleryStats(slug: string): Promise<GalleryStats> {
|
async getGalleryStats(slug: string): Promise<GalleryStats> {
|
||||||
const response = await api.get<GalleryStats>(`/gallery/${slug}/stats`);
|
const response = await api.get<GalleryStats>(`/gallery/${slug}/stats`);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -45,7 +45,8 @@ class PhotosService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const queryString = params.toString();
|
const queryString = params.toString();
|
||||||
const url = `/admin/events/${eventId}/photos${queryString ? `?${queryString}` : ''}`;
|
// Use admin photos router for listing to ensure URL alignment with media/thumbnail endpoints
|
||||||
|
const url = `/admin/photos/${eventId}/photos${queryString ? `?${queryString}` : ''}`;
|
||||||
|
|
||||||
const response = await api.get(url);
|
const response = await api.get(url);
|
||||||
|
|
||||||
@@ -96,4 +97,4 @@ class PhotosService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const photosService = new PhotosService();
|
export const photosService = new PhotosService();
|
||||||
|
|||||||
Generated
+64
@@ -10,6 +10,7 @@
|
|||||||
"node-fetch": "^2.7.0"
|
"node-fetch": "^2.7.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.48.2",
|
||||||
"puppeteer": "^24.17.0"
|
"puppeteer": "^24.17.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -38,6 +39,22 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.55.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.55.0.tgz",
|
||||||
|
"integrity": "sha512-04IXzPwHrW69XusN/SIdDdKZBzMfOT9UNT/YiJit/xpy2VuAoB8NHc8Aplb96zsWDddLnbkPL3TsmrS04ZU2xQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.55.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@puppeteer/browsers": {
|
"node_modules/@puppeteer/browsers": {
|
||||||
"version": "2.10.7",
|
"version": "2.10.7",
|
||||||
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.10.7.tgz",
|
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.10.7.tgz",
|
||||||
@@ -704,6 +721,21 @@
|
|||||||
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/fsevents": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/get-caller-file": {
|
"node_modules/get-caller-file": {
|
||||||
"version": "2.0.5",
|
"version": "2.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||||
@@ -1083,6 +1115,38 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.55.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.55.0.tgz",
|
||||||
|
"integrity": "sha512-sdCWStblvV1YU909Xqx0DhOjPZE4/5lJsIS84IfN9dAZfcl/CIZ5O8l3o0j7hPMjDvqoTF8ZUcc+i/GL5erstA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.55.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.55.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.55.0.tgz",
|
||||||
|
"integrity": "sha512-GvZs4vU3U5ro2nZpeiwyb0zuFaqb9sUiAJuyrWpcGouD8y9/HLgGbNRjIph7zU9D3hnPaisMl9zG9CgFi/biIg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/prebuild-install": {
|
"node_modules/prebuild-install": {
|
||||||
"version": "7.1.3",
|
"version": "7.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
|
||||||
|
|||||||
+5
-1
@@ -1,10 +1,14 @@
|
|||||||
{
|
{
|
||||||
|
"scripts": {
|
||||||
|
"test:e2e": "playwright test"
|
||||||
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"better-sqlite3": "^12.2.0",
|
"better-sqlite3": "^12.2.0",
|
||||||
"canvas": "^3.2.0",
|
"canvas": "^3.2.0",
|
||||||
"node-fetch": "^2.7.0"
|
"node-fetch": "^2.7.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"puppeteer": "^24.17.0"
|
"puppeteer": "^24.17.0",
|
||||||
|
"@playwright/test": "^1.48.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig, devices } from '@playwright/test';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: 'tests/e2e',
|
||||||
|
timeout: 60_000,
|
||||||
|
retries: 0,
|
||||||
|
use: {
|
||||||
|
baseURL: 'http://localhost:3000',
|
||||||
|
headless: true,
|
||||||
|
viewport: { width: 1280, height: 800 },
|
||||||
|
ignoreHTTPSErrors: true,
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
|
||||||
|
{ name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
+212
-59
@@ -13,7 +13,7 @@ IFS=$'\n\t'
|
|||||||
# Script configuration
|
# Script configuration
|
||||||
readonly SCRIPT_VERSION="2.0.0"
|
readonly SCRIPT_VERSION="2.0.0"
|
||||||
readonly APP_NAME="PicPeak"
|
readonly APP_NAME="PicPeak"
|
||||||
readonly REPO_URL="https://github.com/yourusername/wedding-photo-sharing"
|
readonly REPO_URL="https://github.com/the-luap/picpeak.git"
|
||||||
readonly NODE_VERSION="20"
|
readonly NODE_VERSION="20"
|
||||||
readonly MIN_RAM_DOCKER=2048
|
readonly MIN_RAM_DOCKER=2048
|
||||||
readonly MIN_RAM_NATIVE=1024
|
readonly MIN_RAM_NATIVE=1024
|
||||||
@@ -44,7 +44,6 @@ INSTALL_METHOD="" # docker or native
|
|||||||
OS_TYPE=""
|
OS_TYPE=""
|
||||||
OS_VERSION=""
|
OS_VERSION=""
|
||||||
PACKAGE_MANAGER=""
|
PACKAGE_MANAGER=""
|
||||||
ADMIN_PASSWORD=""
|
|
||||||
ADMIN_EMAIL="admin@example.com"
|
ADMIN_EMAIL="admin@example.com"
|
||||||
DOMAIN_NAME=""
|
DOMAIN_NAME=""
|
||||||
SMTP_HOST=""
|
SMTP_HOST=""
|
||||||
@@ -61,6 +60,38 @@ UNINSTALL_MODE=false
|
|||||||
# Helper Functions
|
# Helper Functions
|
||||||
################################################################################
|
################################################################################
|
||||||
|
|
||||||
|
# Run a command as the application user, even if sudo is not available
|
||||||
|
run_as_user() {
|
||||||
|
local cmd="$*"
|
||||||
|
if [[ "$(id -u)" -ne 0 ]]; then
|
||||||
|
# Already non-root; just run
|
||||||
|
bash -lc "$cmd"
|
||||||
|
return $?
|
||||||
|
fi
|
||||||
|
if command_exists sudo; then
|
||||||
|
sudo -H -u "$NATIVE_APP_USER" bash -lc "$cmd"
|
||||||
|
elif command_exists runuser; then
|
||||||
|
runuser -u "$NATIVE_APP_USER" -- bash -lc "$cmd"
|
||||||
|
else
|
||||||
|
su -s /bin/bash - "$NATIVE_APP_USER" -c "$cmd"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prompt for admin email interactively (unless provided or unattended)
|
||||||
|
prompt_admin_email() {
|
||||||
|
if [[ -n "$ADMIN_EMAIL" ]]; then
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
if [[ "$UNATTENDED" == "true" ]]; then
|
||||||
|
ADMIN_EMAIL="admin@example.com"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
echo "Please enter the admin email address (used for the initial admin account):"
|
||||||
|
read -p "Admin email [admin@example.com]: " ADMIN_EMAIL
|
||||||
|
ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
||||||
|
}
|
||||||
|
|
||||||
print_banner() {
|
print_banner() {
|
||||||
echo -e "${PURPLE}"
|
echo -e "${PURPLE}"
|
||||||
echo "╔════════════════════════════════════════════════════════════════════════╗"
|
echo "╔════════════════════════════════════════════════════════════════════════╗"
|
||||||
@@ -110,11 +141,16 @@ generate_jwt_secret() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get_available_ram_mb() {
|
get_available_ram_mb() {
|
||||||
if command_exists free; then
|
# Prefer /proc/meminfo (always available on Linux), fallback to free(1)
|
||||||
free -m | awk '/^Mem:/{print $2}'
|
if [[ -r /proc/meminfo ]]; then
|
||||||
else
|
awk '/^MemTotal:/ { printf "%d\n", $2/1024 }' /proc/meminfo
|
||||||
echo "0"
|
return
|
||||||
fi
|
fi
|
||||||
|
if command_exists free; then
|
||||||
|
free -m | awk '/^Mem:/ {print $2}'
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo "0"
|
||||||
}
|
}
|
||||||
|
|
||||||
get_available_disk_gb() {
|
get_available_disk_gb() {
|
||||||
@@ -316,7 +352,7 @@ setup_docker_installation() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
log_step "Creating application directory at $app_dir"
|
log_step "Creating application directory at $app_dir"
|
||||||
mkdir -p "$app_dir"/{storage/events/{active,archived},logs,backup,config}
|
mkdir -p "$app_dir"/{storage/events/{active,archived},logs,backup,config,data,events}
|
||||||
|
|
||||||
# Clone repository
|
# Clone repository
|
||||||
log_step "Downloading PicPeak..."
|
log_step "Downloading PicPeak..."
|
||||||
@@ -327,11 +363,20 @@ setup_docker_installation() {
|
|||||||
git clone "$REPO_URL" "$app_dir"
|
git clone "$REPO_URL" "$app_dir"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Determine host user for container mapping (PUID/PGID)
|
||||||
|
local host_uid host_gid
|
||||||
|
if [[ -n "${SUDO_USER:-}" ]]; then
|
||||||
|
host_uid=$(id -u "$SUDO_USER" 2>/dev/null || echo 1000)
|
||||||
|
host_gid=$(id -g "$SUDO_USER" 2>/dev/null || echo 1000)
|
||||||
|
else
|
||||||
|
host_uid=$(id -u 2>/dev/null || echo 1000)
|
||||||
|
host_gid=$(id -g 2>/dev/null || echo 1000)
|
||||||
|
fi
|
||||||
|
|
||||||
# Generate secrets
|
# Generate secrets
|
||||||
local jwt_secret=$(generate_jwt_secret)
|
local jwt_secret=$(generate_jwt_secret)
|
||||||
local db_password=$(generate_password)
|
local db_password=$(generate_password)
|
||||||
local redis_password=$(generate_password)
|
local redis_password=$(generate_password)
|
||||||
[[ -z "$ADMIN_PASSWORD" ]] && ADMIN_PASSWORD=$(generate_password)
|
|
||||||
|
|
||||||
# Create .env file
|
# Create .env file
|
||||||
log_step "Creating configuration..."
|
log_step "Creating configuration..."
|
||||||
@@ -346,7 +391,10 @@ JWT_SECRET=$jwt_secret
|
|||||||
|
|
||||||
# Admin
|
# Admin
|
||||||
ADMIN_EMAIL=$ADMIN_EMAIL
|
ADMIN_EMAIL=$ADMIN_EMAIL
|
||||||
ADMIN_PASSWORD=$ADMIN_PASSWORD
|
|
||||||
|
# Runtime user mapping for Docker bind mounts
|
||||||
|
PUID=$host_uid
|
||||||
|
PGID=$host_gid
|
||||||
|
|
||||||
# Database
|
# Database
|
||||||
DB_HOST=postgres
|
DB_HOST=postgres
|
||||||
@@ -373,7 +421,7 @@ SMTP_FROM=${SMTP_USER:-noreply@localhost}
|
|||||||
|
|
||||||
# URLs
|
# URLs
|
||||||
FRONTEND_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
FRONTEND_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||||
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME/admin}
|
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||||
|
|
||||||
# Features
|
# Features
|
||||||
ENABLE_FILE_WATCHER=true
|
ENABLE_FILE_WATCHER=true
|
||||||
@@ -381,6 +429,9 @@ ENABLE_EXPIRATION_CHECKER=true
|
|||||||
ENABLE_EMAIL_SERVICE=true
|
ENABLE_EMAIL_SERVICE=true
|
||||||
DEFAULT_EXPIRY_DAYS=30
|
DEFAULT_EXPIRY_DAYS=30
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
|
# Ensure bind mounts are writable by mapped user
|
||||||
|
chown -R "$host_uid":"$host_gid" "$app_dir"/storage "$app_dir"/logs "$app_dir"/backup "$app_dir"/data "$app_dir"/events 2>/dev/null || true
|
||||||
|
|
||||||
# Create docker-compose.yml if it doesn't exist
|
# Create docker-compose.yml if it doesn't exist
|
||||||
if [[ ! -f "$app_dir/docker-compose.yml" ]]; then
|
if [[ ! -f "$app_dir/docker-compose.yml" ]]; then
|
||||||
@@ -551,29 +602,55 @@ setup_native_installation() {
|
|||||||
|
|
||||||
# Create application directory
|
# Create application directory
|
||||||
log_step "Creating application directory..."
|
log_step "Creating application directory..."
|
||||||
mkdir -p "$NATIVE_APP_DIR"/{backend,events/{active,archived},logs,config}
|
mkdir -p "$NATIVE_APP_DIR"/{app,events/{active,archived},logs,config}
|
||||||
|
chown -R $NATIVE_APP_USER:$NATIVE_APP_USER "$NATIVE_APP_DIR"
|
||||||
|
|
||||||
# Clone repository
|
# Clone repository
|
||||||
log_step "Downloading PicPeak..."
|
log_step "Downloading PicPeak..."
|
||||||
if [[ -d "$NATIVE_APP_DIR/backend/.git" ]]; then
|
if [[ -d "$NATIVE_APP_DIR/app/.git" ]]; then
|
||||||
cd "$NATIVE_APP_DIR/backend"
|
cd "$NATIVE_APP_DIR/app"
|
||||||
git pull
|
# Ensure correct remote and update even if history was rewritten
|
||||||
|
run_as_user "git config --global --add safe.directory $NATIVE_APP_DIR/app" || true
|
||||||
|
run_as_user "git remote set-url origin $REPO_URL" || true
|
||||||
|
run_as_user "git fetch --all --prune" || true
|
||||||
|
# Prefer checking out remote main and hard resetting to avoid merge prompts
|
||||||
|
if ! run_as_user "git checkout -B main origin/main"; then
|
||||||
|
run_as_user "git checkout main" || true
|
||||||
|
run_as_user "git reset --hard origin/main"
|
||||||
|
fi
|
||||||
else
|
else
|
||||||
git clone "$REPO_URL" "$NATIVE_APP_DIR/backend"
|
run_as_user "git clone $REPO_URL $NATIVE_APP_DIR/app" || {
|
||||||
|
run_as_user "git config --global --add safe.directory $NATIVE_APP_DIR/app"
|
||||||
|
run_as_user "git clone $REPO_URL $NATIVE_APP_DIR/app"
|
||||||
|
}
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
log_step "Installing dependencies..."
|
log_step "Installing dependencies..."
|
||||||
cd "$NATIVE_APP_DIR/backend"
|
# The repository root contains both backend/ and frontend/
|
||||||
|
# Install backend production dependencies
|
||||||
|
cd "$NATIVE_APP_DIR/app/backend"
|
||||||
npm install --production
|
npm install --production
|
||||||
|
# Ensure SQLite data directory exists for native installs
|
||||||
|
mkdir -p "$NATIVE_APP_DIR/app/backend/data"
|
||||||
|
|
||||||
|
# Build frontend for native serving
|
||||||
|
log_step "Building frontend..."
|
||||||
|
if [[ -d "$NATIVE_APP_DIR/app/frontend" ]]; then
|
||||||
|
cd "$NATIVE_APP_DIR/app/frontend"
|
||||||
|
# Try ci (faster/clean) then fallback to install
|
||||||
|
run_as_user "npm ci --include=dev" || run_as_user "npm install"
|
||||||
|
run_as_user "npm run build"
|
||||||
|
else
|
||||||
|
log_warn "Frontend directory not found; admin UI will not be served by backend"
|
||||||
|
fi
|
||||||
|
|
||||||
# Generate secrets
|
# Generate secrets
|
||||||
local jwt_secret=$(generate_jwt_secret)
|
local jwt_secret=$(generate_jwt_secret)
|
||||||
[[ -z "$ADMIN_PASSWORD" ]] && ADMIN_PASSWORD=$(generate_password)
|
|
||||||
|
|
||||||
# Create .env file
|
# Create .env file
|
||||||
log_step "Creating configuration..."
|
log_step "Creating configuration..."
|
||||||
cat > "$NATIVE_APP_DIR/backend/.env" <<EOF
|
cat > "$NATIVE_APP_DIR/app/backend/.env" <<EOF
|
||||||
# PicPeak Native Configuration
|
# PicPeak Native Configuration
|
||||||
# Generated: $(date)
|
# Generated: $(date)
|
||||||
|
|
||||||
@@ -584,14 +661,14 @@ JWT_SECRET=$jwt_secret
|
|||||||
|
|
||||||
# Admin
|
# Admin
|
||||||
ADMIN_USERNAME=admin
|
ADMIN_USERNAME=admin
|
||||||
ADMIN_PASSWORD=$ADMIN_PASSWORD
|
|
||||||
ADMIN_EMAIL=$ADMIN_EMAIL
|
ADMIN_EMAIL=$ADMIN_EMAIL
|
||||||
|
|
||||||
# Database
|
# Database (native uses SQLite by default)
|
||||||
DATABASE_PATH=$NATIVE_APP_DIR/backend/database.sqlite
|
DATABASE_CLIENT=sqlite3
|
||||||
|
DATABASE_PATH=$NATIVE_APP_DIR/app/backend/data/photo_sharing.db
|
||||||
|
|
||||||
# Storage
|
# Storage root (thumbnails/uploads live under this path)
|
||||||
PHOTOS_DIR=$NATIVE_APP_DIR/events
|
STORAGE_PATH=$NATIVE_APP_DIR
|
||||||
|
|
||||||
# Email
|
# Email
|
||||||
SMTP_ENABLED=${SMTP_HOST:+true}
|
SMTP_ENABLED=${SMTP_HOST:+true}
|
||||||
@@ -603,7 +680,7 @@ SMTP_FROM=${SMTP_USER:-noreply@localhost}
|
|||||||
|
|
||||||
# URLs
|
# URLs
|
||||||
FRONTEND_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
FRONTEND_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||||
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME/admin}
|
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||||
|
|
||||||
# Features
|
# Features
|
||||||
ENABLE_FILE_WATCHER=true
|
ENABLE_FILE_WATCHER=true
|
||||||
@@ -614,16 +691,20 @@ DEFAULT_EXPIRY_DAYS=30
|
|||||||
# Logging
|
# Logging
|
||||||
LOG_DIR=$NATIVE_APP_DIR/logs
|
LOG_DIR=$NATIVE_APP_DIR/logs
|
||||||
LOG_LEVEL=info
|
LOG_LEVEL=info
|
||||||
|
|
||||||
|
# Frontend serving (native installs)
|
||||||
|
SERVE_FRONTEND=true
|
||||||
|
FRONTEND_DIR=$NATIVE_APP_DIR/app/frontend/dist
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
# Set permissions
|
# Set permissions
|
||||||
chown -R $NATIVE_APP_USER:$NATIVE_APP_USER "$NATIVE_APP_DIR"
|
chown -R $NATIVE_APP_USER:$NATIVE_APP_USER "$NATIVE_APP_DIR"
|
||||||
chmod 600 "$NATIVE_APP_DIR/backend/.env"
|
chmod 600 "$NATIVE_APP_DIR/app/backend/.env"
|
||||||
|
|
||||||
# Run database migrations
|
# Run database migrations
|
||||||
log_step "Initializing database..."
|
log_step "Initializing database..."
|
||||||
cd "$NATIVE_APP_DIR/backend"
|
cd "$NATIVE_APP_DIR/app/backend"
|
||||||
sudo -u $NATIVE_APP_USER npm run migrate
|
run_as_user "npm run migrate"
|
||||||
|
|
||||||
# Create systemd services
|
# Create systemd services
|
||||||
create_systemd_services
|
create_systemd_services
|
||||||
@@ -636,8 +717,15 @@ EOF
|
|||||||
# Start services
|
# Start services
|
||||||
log_step "Starting services..."
|
log_step "Starting services..."
|
||||||
systemctl daemon-reload
|
systemctl daemon-reload
|
||||||
systemctl enable picpeak-backend picpeak-workers
|
systemctl enable picpeak-backend
|
||||||
systemctl start picpeak-backend picpeak-workers
|
# Stop/remove legacy workers service if present
|
||||||
|
if systemctl list-unit-files | grep -q '^picpeak-workers.service'; then
|
||||||
|
systemctl disable picpeak-workers || true
|
||||||
|
systemctl stop picpeak-workers || true
|
||||||
|
rm -f /etc/systemd/system/picpeak-workers.service
|
||||||
|
systemctl daemon-reload
|
||||||
|
fi
|
||||||
|
systemctl start picpeak-backend
|
||||||
|
|
||||||
log_success "Native installation completed!"
|
log_success "Native installation completed!"
|
||||||
}
|
}
|
||||||
@@ -654,7 +742,7 @@ After=network.target
|
|||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
User=$NATIVE_APP_USER
|
User=$NATIVE_APP_USER
|
||||||
WorkingDirectory=$NATIVE_APP_DIR/backend
|
WorkingDirectory=$NATIVE_APP_DIR/app/backend
|
||||||
Environment="NODE_ENV=production"
|
Environment="NODE_ENV=production"
|
||||||
ExecStart=/usr/bin/node server.js
|
ExecStart=/usr/bin/node server.js
|
||||||
Restart=always
|
Restart=always
|
||||||
@@ -675,7 +763,7 @@ After=network.target picpeak-backend.service
|
|||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
User=$NATIVE_APP_USER
|
User=$NATIVE_APP_USER
|
||||||
WorkingDirectory=$NATIVE_APP_DIR/backend
|
WorkingDirectory=$NATIVE_APP_DIR/app/backend
|
||||||
Environment="NODE_ENV=production"
|
Environment="NODE_ENV=production"
|
||||||
ExecStart=/usr/bin/node src/services/workerManager.js
|
ExecStart=/usr/bin/node src/services/workerManager.js
|
||||||
Restart=always
|
Restart=always
|
||||||
@@ -845,8 +933,32 @@ print_success_message() {
|
|||||||
echo
|
echo
|
||||||
echo "🔐 Admin Credentials:"
|
echo "🔐 Admin Credentials:"
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
# Read from ADMIN_CREDENTIALS.txt when available
|
||||||
echo -e "Password: ${CYAN}$ADMIN_PASSWORD${NC}"
|
local cred_file email_line pass_line admin_email_val admin_pass_val
|
||||||
|
if [[ "$INSTALL_METHOD" == "docker" ]]; then
|
||||||
|
cred_file="$app_dir/data/ADMIN_CREDENTIALS.txt"
|
||||||
|
else
|
||||||
|
cred_file="$NATIVE_APP_DIR/app/backend/data/ADMIN_CREDENTIALS.txt"
|
||||||
|
fi
|
||||||
|
if [[ -f "$cred_file" ]]; then
|
||||||
|
email_line=$(grep -m1 '^Email:' "$cred_file" || true)
|
||||||
|
pass_line=$(grep -m1 '^Password:' "$cred_file" || true)
|
||||||
|
admin_email_val=${email_line#Email: }
|
||||||
|
admin_pass_val=${pass_line#Password: }
|
||||||
|
if [[ -n "$admin_email_val" ]]; then
|
||||||
|
echo -e "Email: ${CYAN}$admin_email_val${NC}"
|
||||||
|
else
|
||||||
|
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
||||||
|
fi
|
||||||
|
if [[ -n "$admin_pass_val" ]]; then
|
||||||
|
echo -e "Password: ${CYAN}$admin_pass_val${NC}"
|
||||||
|
else
|
||||||
|
echo -e "Password: ${YELLOW}(see $cred_file)${NC}"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
||||||
|
echo -e "Password: ${YELLOW}(credentials file not found)${NC}"
|
||||||
|
fi
|
||||||
echo
|
echo
|
||||||
echo -e "${YELLOW}⚠️ IMPORTANT: Change the admin password on first login!${NC}"
|
echo -e "${YELLOW}⚠️ IMPORTANT: Change the admin password on first login!${NC}"
|
||||||
|
|
||||||
@@ -870,16 +982,16 @@ print_success_message() {
|
|||||||
echo "🔧 Service Commands:"
|
echo "🔧 Service Commands:"
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
echo "View logs: sudo journalctl -u picpeak-backend -f"
|
echo "View logs: sudo journalctl -u picpeak-backend -f"
|
||||||
echo "Stop: sudo systemctl stop picpeak-backend picpeak-workers"
|
echo "Stop: sudo systemctl stop picpeak-backend"
|
||||||
echo "Start: sudo systemctl start picpeak-backend picpeak-workers"
|
echo "Start: sudo systemctl start picpeak-backend"
|
||||||
echo "Status: sudo systemctl status picpeak-backend"
|
echo "Status: sudo systemctl status picpeak-backend"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "📚 Documentation:"
|
echo "📚 Documentation:"
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
echo "Setup Guide: https://github.com/yourusername/wedding-photo-sharing/blob/main/SIMPLE_SETUP.md"
|
echo "Setup Guide: https://github.com/the-luap/picpeak/blob/main/SIMPLE_SETUP.md"
|
||||||
echo "Full Docs: https://github.com/yourusername/wedding-photo-sharing"
|
echo "Full Docs: https://github.com/the-luap/picpeak"
|
||||||
echo
|
echo
|
||||||
echo -e "${GREEN}✨ Setup complete! Visit the admin panel to start creating galleries.${NC}"
|
echo -e "${GREEN}✨ Setup complete! Visit the admin panel to start creating galleries.${NC}"
|
||||||
}
|
}
|
||||||
@@ -890,16 +1002,31 @@ print_success_message() {
|
|||||||
|
|
||||||
update_installation() {
|
update_installation() {
|
||||||
print_header "Updating PicPeak"
|
print_header "Updating PicPeak"
|
||||||
|
|
||||||
# Detect existing installation
|
# Prefer explicit native install detection first
|
||||||
if [[ -d "$DOCKER_APP_DIR" ]] || [[ -d "/home/${SUDO_USER:-}/picpeak" ]]; then
|
native_detected=false
|
||||||
INSTALL_METHOD="docker"
|
docker_detected=false
|
||||||
update_docker_installation
|
|
||||||
elif [[ -d "$NATIVE_APP_DIR" ]]; then
|
# Native detection: app/backend exists OR systemd unit present
|
||||||
|
if [[ -d "$NATIVE_APP_DIR/app/backend" ]]; then
|
||||||
|
native_detected=true
|
||||||
|
elif command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q '^picpeak-backend.service'; then
|
||||||
|
native_detected=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Docker detection: docker app dir or user home picpeak dir exists
|
||||||
|
if [[ -d "$DOCKER_APP_DIR" ]] || [[ -n "${SUDO_USER:-}" && -d "/home/${SUDO_USER}/picpeak" ]]; then
|
||||||
|
docker_detected=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$native_detected" == true ]]; then
|
||||||
INSTALL_METHOD="native"
|
INSTALL_METHOD="native"
|
||||||
update_native_installation
|
update_native_installation
|
||||||
|
elif [[ "$docker_detected" == true ]]; then
|
||||||
|
INSTALL_METHOD="docker"
|
||||||
|
update_docker_installation
|
||||||
else
|
else
|
||||||
die "No existing PicPeak installation found"
|
die "No existing PicPeak installation found (native dir $NATIVE_APP_DIR/app/backend or docker dir $DOCKER_APP_DIR not present)"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -932,23 +1059,51 @@ update_native_installation() {
|
|||||||
log_step "Updating native installation..."
|
log_step "Updating native installation..."
|
||||||
|
|
||||||
# Stop services
|
# Stop services
|
||||||
systemctl stop picpeak-backend picpeak-workers
|
systemctl stop picpeak-backend || true
|
||||||
|
if systemctl list-unit-files | grep -q '^picpeak-workers.service'; then
|
||||||
|
systemctl stop picpeak-workers || true
|
||||||
|
fi
|
||||||
|
|
||||||
# Backup current configuration
|
# Backup current configuration
|
||||||
cp "$NATIVE_APP_DIR/backend/.env" "$NATIVE_APP_DIR/backend/.env.backup-$(date +%Y%m%d-%H%M%S)"
|
if [[ -f "$NATIVE_APP_DIR/app/backend/.env" ]]; then
|
||||||
|
cp "$NATIVE_APP_DIR/app/backend/.env" "$NATIVE_APP_DIR/app/backend/.env.backup-$(date +%Y%m%d-%H%M%S)"
|
||||||
|
fi
|
||||||
|
|
||||||
# Pull latest code
|
# Pull latest code
|
||||||
cd "$NATIVE_APP_DIR/backend"
|
cd "$NATIVE_APP_DIR/app"
|
||||||
sudo -u $NATIVE_APP_USER git pull
|
run_as_user "git config --global --add safe.directory $NATIVE_APP_DIR/app" || true
|
||||||
|
run_as_user "git remote set-url origin $REPO_URL" || true
|
||||||
|
run_as_user "git fetch --all --prune"
|
||||||
|
if ! run_as_user "git checkout -B main origin/main"; then
|
||||||
|
run_as_user "git checkout main" || true
|
||||||
|
run_as_user "git reset --hard origin/main"
|
||||||
|
fi
|
||||||
|
|
||||||
# Update dependencies
|
# Update backend dependencies
|
||||||
sudo -u $NATIVE_APP_USER npm install --production
|
cd "$NATIVE_APP_DIR/app/backend"
|
||||||
|
run_as_user "npm install --production"
|
||||||
|
|
||||||
# Run migrations
|
# Run migrations
|
||||||
sudo -u $NATIVE_APP_USER npm run migrate
|
run_as_user "npm run migrate"
|
||||||
|
|
||||||
|
# Rebuild frontend (ensure admin UI for native installs)
|
||||||
|
if [[ -d "$NATIVE_APP_DIR/app/frontend" ]]; then
|
||||||
|
log_step "Rebuilding frontend..."
|
||||||
|
cd "$NATIVE_APP_DIR/app/frontend"
|
||||||
|
run_as_user "npm ci --include=dev" || run_as_user "npm install"
|
||||||
|
run_as_user "npm run build"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Ensure env has frontend serving flags
|
||||||
|
if ! grep -q '^SERVE_FRONTEND=' "$NATIVE_APP_DIR/app/backend/.env"; then
|
||||||
|
echo "SERVE_FRONTEND=true" >> "$NATIVE_APP_DIR/app/backend/.env"
|
||||||
|
fi
|
||||||
|
if ! grep -q '^FRONTEND_DIR=' "$NATIVE_APP_DIR/app/backend/.env"; then
|
||||||
|
echo "FRONTEND_DIR=$NATIVE_APP_DIR/app/frontend/dist" >> "$NATIVE_APP_DIR/app/backend/.env"
|
||||||
|
fi
|
||||||
|
|
||||||
# Restart services
|
# Restart services
|
||||||
systemctl start picpeak-backend picpeak-workers
|
systemctl restart picpeak-backend
|
||||||
|
|
||||||
log_success "Native installation updated successfully!"
|
log_success "Native installation updated successfully!"
|
||||||
}
|
}
|
||||||
@@ -1042,10 +1197,6 @@ parse_arguments() {
|
|||||||
ADMIN_EMAIL="$2"
|
ADMIN_EMAIL="$2"
|
||||||
shift 2
|
shift 2
|
||||||
;;
|
;;
|
||||||
--admin-password)
|
|
||||||
ADMIN_PASSWORD="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--smtp-host)
|
--smtp-host)
|
||||||
SMTP_HOST="$2"
|
SMTP_HOST="$2"
|
||||||
shift 2
|
shift 2
|
||||||
@@ -1103,7 +1254,6 @@ Options:
|
|||||||
--unattended Run without prompts
|
--unattended Run without prompts
|
||||||
--domain DOMAIN Set domain name for HTTPS
|
--domain DOMAIN Set domain name for HTTPS
|
||||||
--email EMAIL Admin email address
|
--email EMAIL Admin email address
|
||||||
--admin-password Admin password (auto-generated if not set)
|
|
||||||
--smtp-host HOST SMTP server hostname
|
--smtp-host HOST SMTP server hostname
|
||||||
--smtp-port PORT SMTP server port
|
--smtp-port PORT SMTP server port
|
||||||
--smtp-user USER SMTP username
|
--smtp-user USER SMTP username
|
||||||
@@ -1126,7 +1276,7 @@ Examples:
|
|||||||
|
|
||||||
# Fully automated Docker setup
|
# Fully automated Docker setup
|
||||||
sudo $0 --docker --unattended --domain photos.example.com \\
|
sudo $0 --docker --unattended --domain photos.example.com \\
|
||||||
--email admin@example.com --admin-password SecurePass123 \\
|
--email admin@example.com \\
|
||||||
--smtp-host smtp.gmail.com --smtp-port 587 \\
|
--smtp-host smtp.gmail.com --smtp-port 587 \\
|
||||||
--smtp-user user@gmail.com --smtp-pass app-password \\
|
--smtp-user user@gmail.com --smtp-pass app-password \\
|
||||||
--enable-ssl
|
--enable-ssl
|
||||||
@@ -1166,6 +1316,9 @@ main() {
|
|||||||
# Check system requirements
|
# Check system requirements
|
||||||
check_system_requirements
|
check_system_requirements
|
||||||
|
|
||||||
|
# Prompt for admin email (design choice: always ask unless provided)
|
||||||
|
prompt_admin_email
|
||||||
|
|
||||||
# Configure email (optional)
|
# Configure email (optional)
|
||||||
configure_email
|
configure_email
|
||||||
|
|
||||||
@@ -1181,4 +1334,4 @@ main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# Run main function
|
# Run main function
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 212 B |
Binary file not shown.
|
After Width: | Height: | Size: 212 B |
@@ -0,0 +1,226 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||||
|
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||||
|
const GALLERY_PASSWORD = process.env.GALLERY_PASSWORD || 'PlaywrightGallery123!';
|
||||||
|
|
||||||
|
interface GallerySetupResult {
|
||||||
|
shareLink: string;
|
||||||
|
slug: string;
|
||||||
|
allPhotosData: {
|
||||||
|
event: any;
|
||||||
|
categories?: any;
|
||||||
|
photos: Array<{ id: number; filename: string; comment_count?: number }>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createGalleryWithModeratedComments(page: Page): Promise<GallerySetupResult> {
|
||||||
|
const loginResponse = await page.request.post('/api/auth/admin/login', {
|
||||||
|
data: {
|
||||||
|
username: ADMIN_EMAIL,
|
||||||
|
password: ADMIN_PASSWORD,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
expect(loginResponse.ok()).toBeTruthy();
|
||||||
|
const { token } = await loginResponse.json();
|
||||||
|
expect(token).toBeTruthy();
|
||||||
|
|
||||||
|
const eventName = `Playwright Feedback Filter ${Date.now()}`;
|
||||||
|
const eventDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
.toISOString()
|
||||||
|
.slice(0, 10);
|
||||||
|
|
||||||
|
const createResponse = await page.request.post('/api/admin/events', {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
event_type: 'wedding',
|
||||||
|
event_name: eventName,
|
||||||
|
event_date: eventDate,
|
||||||
|
host_name: 'Playwright Host',
|
||||||
|
host_email: 'host@example.com',
|
||||||
|
admin_email: ADMIN_EMAIL,
|
||||||
|
password: GALLERY_PASSWORD,
|
||||||
|
expiration_days: 30,
|
||||||
|
allow_user_uploads: false,
|
||||||
|
allow_downloads: true,
|
||||||
|
disable_right_click: false,
|
||||||
|
watermark_downloads: false,
|
||||||
|
feedback_enabled: true,
|
||||||
|
allow_ratings: true,
|
||||||
|
allow_likes: true,
|
||||||
|
allow_comments: true,
|
||||||
|
allow_favorites: true,
|
||||||
|
require_name_email: false,
|
||||||
|
moderate_comments: true,
|
||||||
|
show_feedback_to_guests: true,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(createResponse.ok()).toBeTruthy();
|
||||||
|
const createdEvent = await createResponse.json();
|
||||||
|
expect(createdEvent?.id).toBeTruthy();
|
||||||
|
|
||||||
|
const imagePaths = ['img1.png', 'img2.png'];
|
||||||
|
const photoIds: number[] = [];
|
||||||
|
|
||||||
|
for (const file of imagePaths) {
|
||||||
|
const imagePath = path.join(process.cwd(), 'test-assets', file);
|
||||||
|
const buffer = fs.readFileSync(imagePath);
|
||||||
|
const uploadResponse = await page.request.post(
|
||||||
|
`/api/admin/events/${createdEvent.id}/upload`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
multipart: {
|
||||||
|
photos: {
|
||||||
|
name: path.basename(imagePath),
|
||||||
|
mimeType: 'image/png',
|
||||||
|
buffer,
|
||||||
|
},
|
||||||
|
category_id: 'individual',
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(uploadResponse.ok()).toBeTruthy();
|
||||||
|
const uploadJson = await uploadResponse.json();
|
||||||
|
const uploaded = uploadJson?.photos?.[0];
|
||||||
|
expect(uploaded?.id).toBeTruthy();
|
||||||
|
photoIds.push(uploaded.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(photoIds.length).toBeGreaterThanOrEqual(2);
|
||||||
|
|
||||||
|
const galleryAuthResponse = await page.request.post('/api/auth/gallery/verify', {
|
||||||
|
data: {
|
||||||
|
slug: createdEvent.slug,
|
||||||
|
password: GALLERY_PASSWORD,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
expect(galleryAuthResponse.ok()).toBeTruthy();
|
||||||
|
const { token: galleryToken } = await galleryAuthResponse.json();
|
||||||
|
expect(galleryToken).toBeTruthy();
|
||||||
|
|
||||||
|
// Submit an approved comment (after moderation)
|
||||||
|
const approvedCommentResponse = await page.request.post(
|
||||||
|
`/api/gallery/${createdEvent.slug}/photos/${photoIds[0]}/feedback`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${galleryToken}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
feedback_type: 'comment',
|
||||||
|
comment_text: 'Approved comment',
|
||||||
|
guest_name: 'Approved Guest',
|
||||||
|
guest_email: 'approved@example.com',
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(approvedCommentResponse.ok()).toBeTruthy();
|
||||||
|
const approvedComment = await approvedCommentResponse.json();
|
||||||
|
expect(approvedComment?.id).toBeTruthy();
|
||||||
|
|
||||||
|
const approveModeration = await page.request.put(
|
||||||
|
`/api/admin/feedback/feedback/${approvedComment.id}/approve`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(approveModeration.ok()).toBeTruthy();
|
||||||
|
|
||||||
|
// Submit a second comment that remains pending
|
||||||
|
const pendingCommentResponse = await page.request.post(
|
||||||
|
`/api/gallery/${createdEvent.slug}/photos/${photoIds[1]}/feedback`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${galleryToken}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
feedback_type: 'comment',
|
||||||
|
comment_text: 'Pending comment',
|
||||||
|
guest_name: 'Pending Guest',
|
||||||
|
guest_email: 'pending@example.com',
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(pendingCommentResponse.ok()).toBeTruthy();
|
||||||
|
|
||||||
|
const allPhotosResponse = await page.request.get(`/api/gallery/${createdEvent.slug}/photos`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${galleryToken}`,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
expect(allPhotosResponse.ok()).toBeTruthy();
|
||||||
|
const allPhotosData = await allPhotosResponse.json();
|
||||||
|
expect(Array.isArray(allPhotosData?.photos)).toBeTruthy();
|
||||||
|
|
||||||
|
return {
|
||||||
|
shareLink: createdEvent.share_link,
|
||||||
|
slug: createdEvent.slug,
|
||||||
|
allPhotosData,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe('Gallery feedback filter', () => {
|
||||||
|
test('Comment filter hides photos without approved comments', async ({ page }) => {
|
||||||
|
const { shareLink, slug, allPhotosData } = await createGalleryWithModeratedComments(page);
|
||||||
|
|
||||||
|
const approvedPhotos = allPhotosData.photos.filter((photo) => (photo.comment_count || 0) > 0);
|
||||||
|
expect(approvedPhotos.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
await page.route(`**/api/gallery/${slug}/photos**`, async (route) => {
|
||||||
|
const url = new URL(route.request().url());
|
||||||
|
if (url.searchParams.get('filter') === 'commented') {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(allPhotosData),
|
||||||
|
});
|
||||||
|
await page.unroute(`**/api/gallery/${slug}/photos**`);
|
||||||
|
} else {
|
||||||
|
await route.continue();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto(shareLink);
|
||||||
|
await page.waitForLoadState('domcontentloaded');
|
||||||
|
|
||||||
|
const passwordField = page.getByPlaceholder(/gallery password/i).first();
|
||||||
|
if (await passwordField.count()) {
|
||||||
|
await passwordField.fill(GALLERY_PASSWORD);
|
||||||
|
await page.getByRole('button', { name: /View Gallery/i }).click();
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
|
const tiles = page.locator('.relative.group');
|
||||||
|
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||||
|
await expect(tiles).toHaveCount(allPhotosData.photos.length);
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /Commented/i }).click();
|
||||||
|
|
||||||
|
await expect(tiles).toHaveCount(approvedPhotos.length, { timeout: 20000 });
|
||||||
|
|
||||||
|
for (const pending of allPhotosData.photos.filter((photo) => (photo.comment_count || 0) === 0)) {
|
||||||
|
await expect(page.getByAltText(pending.filename)).not.toBeVisible({ timeout: 1000 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user