Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8c690155bf | |||
| 1b1e4f715d | |||
| 68eb9ba552 | |||
| 7040865154 | |||
| 013be18d98 | |||
| 3c2a79a31a | |||
| f20472ca26 | |||
| 87f4526220 | |||
| d42a11680f | |||
| 38dd74b893 |
@@ -1,207 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
|
||||
describe('Admin photos in reference mode', () => {
|
||||
let tmpDir;
|
||||
let storagePath;
|
||||
let db;
|
||||
let app;
|
||||
let categoryId;
|
||||
|
||||
const resetModules = () => {
|
||||
jest.resetModules();
|
||||
jest.clearAllMocks();
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-admin-photos-'));
|
||||
storagePath = path.join(tmpDir, 'storage');
|
||||
await fs.promises.mkdir(storagePath, { recursive: true });
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'photo_sharing_test.db');
|
||||
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
|
||||
try {
|
||||
await fs.promises.unlink(process.env.TEST_DATABASE_PATH);
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
process.env.STORAGE_PATH = storagePath;
|
||||
|
||||
resetModules();
|
||||
|
||||
jest.doMock('../../src/middleware/auth', () => ({
|
||||
adminAuth: (req, _res, next) => {
|
||||
req.admin = { id: 1, username: 'tester' };
|
||||
next();
|
||||
}
|
||||
}));
|
||||
|
||||
jest.doMock('../../src/services/imageProcessor', () => ({
|
||||
generateThumbnail: jest.fn().mockResolvedValue('thumbnails/mock-thumb.jpg'),
|
||||
ensureThumbnail: jest.fn()
|
||||
}));
|
||||
|
||||
jest.doMock('../../src/middleware/uploadValidation', () => ({
|
||||
validateUploadedFiles: (_req, _res, next) => next()
|
||||
}));
|
||||
|
||||
jest.doMock('../../src/utils/fileSecurityUtils', () => {
|
||||
const actual = jest.requireActual('../../src/utils/fileSecurityUtils');
|
||||
return {
|
||||
...actual,
|
||||
validateFileType: () => true,
|
||||
createFileUploadValidator: () => (_req, _res, next) => next()
|
||||
};
|
||||
});
|
||||
|
||||
jest.doMock('../../src/utils/logger', () => ({
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn()
|
||||
}));
|
||||
|
||||
const dbModule = require('../../src/database/db');
|
||||
db = dbModule.db;
|
||||
|
||||
await db.schema.dropTableIfExists('photo_feedback');
|
||||
await db.schema.dropTableIfExists('photos');
|
||||
await db.schema.dropTableIfExists('photo_categories');
|
||||
await db.schema.dropTableIfExists('events');
|
||||
|
||||
await db.schema.createTable('events', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('slug').notNullable();
|
||||
table.string('event_name').notNullable();
|
||||
table.string('source_mode').notNullable();
|
||||
table.string('external_path');
|
||||
});
|
||||
|
||||
await db.schema.createTable('photo_categories', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('name').notNullable();
|
||||
table.string('slug').notNullable();
|
||||
table.boolean('is_global').defaultTo(true);
|
||||
table.integer('event_id');
|
||||
});
|
||||
|
||||
await db.schema.createTable('photos', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('event_id').notNullable();
|
||||
table.string('filename').notNullable();
|
||||
table.string('path').notNullable();
|
||||
table.string('thumbnail_path');
|
||||
table.string('type').notNullable();
|
||||
table.integer('size_bytes');
|
||||
table.integer('category_id');
|
||||
table.string('source_origin');
|
||||
table.string('external_relpath');
|
||||
table.datetime('uploaded_at').defaultTo(db.fn.now());
|
||||
table.float('average_rating').defaultTo(0);
|
||||
table.integer('like_count').defaultTo(0);
|
||||
table.integer('favorite_count').defaultTo(0);
|
||||
});
|
||||
|
||||
await db.schema.createTable('photo_feedback', (table) => {
|
||||
table.increments('id');
|
||||
table.integer('photo_id');
|
||||
table.string('feedback_type');
|
||||
table.boolean('is_approved');
|
||||
table.boolean('is_hidden');
|
||||
});
|
||||
|
||||
await db('events').insert({
|
||||
id: 1,
|
||||
slug: 'test-event',
|
||||
event_name: 'Test Event',
|
||||
source_mode: 'reference',
|
||||
external_path: 'external/library'
|
||||
});
|
||||
|
||||
const insertedCategory = await db('photo_categories').insert({
|
||||
name: 'Highlights',
|
||||
slug: 'highlights',
|
||||
is_global: true
|
||||
});
|
||||
categoryId = Array.isArray(insertedCategory) ? insertedCategory[0] : insertedCategory;
|
||||
|
||||
const router = require('../../src/routes/adminPhotos');
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin/events', router);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (db) {
|
||||
await db.destroy();
|
||||
}
|
||||
resetModules();
|
||||
delete process.env.TEST_DATABASE_PATH;
|
||||
delete process.env.STORAGE_PATH;
|
||||
if (tmpDir) {
|
||||
await fs.promises.rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('stores managed uploads with category information and managed origin', async () => {
|
||||
const uploadResponse = await request(app)
|
||||
.post(`/api/admin/events/1/upload`)
|
||||
.field('category_id', String(categoryId))
|
||||
.attach('photos', Buffer.from('fake image data'), 'photo.jpg');
|
||||
|
||||
expect(uploadResponse.status).toBe(200);
|
||||
expect(uploadResponse.body).toHaveProperty('photos');
|
||||
expect(Array.isArray(uploadResponse.body.photos)).toBe(true);
|
||||
|
||||
const photo = await db('photos').first();
|
||||
expect(photo).toBeTruthy();
|
||||
expect(photo.category_id).toBe(categoryId);
|
||||
expect(photo.source_origin).toBe('managed');
|
||||
expect(photo.external_relpath).toBeNull();
|
||||
});
|
||||
|
||||
it('returns numeric category metadata when listing photos', async () => {
|
||||
await db('photos').insert({
|
||||
event_id: 1,
|
||||
filename: 'external.jpg',
|
||||
path: 'test-event/external.jpg',
|
||||
thumbnail_path: null,
|
||||
type: 'individual',
|
||||
size_bytes: 123,
|
||||
source_origin: 'external',
|
||||
external_relpath: 'individual/external.jpg'
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.get(`/api/admin/events/1/photos`)
|
||||
.expect(200);
|
||||
|
||||
expect(Array.isArray(response.body.photos)).toBe(true);
|
||||
const managedPhoto = response.body.photos.find((p) => p.category_id === categoryId);
|
||||
expect(managedPhoto).toBeTruthy();
|
||||
expect(managedPhoto.category_name).toBe('Highlights');
|
||||
|
||||
const filtered = await request(app)
|
||||
.get(`/api/admin/events/1/photos`)
|
||||
.query({ category_id: String(categoryId) })
|
||||
.expect(200);
|
||||
|
||||
expect(filtered.body.photos.every((p) => p.category_id === categoryId)).toBe(true);
|
||||
});
|
||||
|
||||
it('normalizes category updates', async () => {
|
||||
const photo = await db('photos').first();
|
||||
|
||||
await request(app)
|
||||
.patch(`/api/admin/events/1/photos/${photo.id}`)
|
||||
.send({ category_id: '0' })
|
||||
.expect(200);
|
||||
|
||||
const updated = await db('photos').where({ id: photo.id }).first();
|
||||
expect(updated.category_id).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -66,16 +66,6 @@ describe('resolvePhotoFilePath', () => {
|
||||
expect(result).toBe(path.join('/mock/external', 'picsum-demo/individual', 'look-02.jpg'));
|
||||
});
|
||||
|
||||
it('falls back to managed storage when external metadata is missing', () => {
|
||||
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
|
||||
const photo = { path: 'fashion-show/new-upload.jpg' };
|
||||
|
||||
const result = resolvePhotoFilePath(event, photo);
|
||||
|
||||
expect(resolveExternalPath).not.toHaveBeenCalled();
|
||||
expect(result).toBe(path.join(backendRoot, 'storage', 'events/active', 'fashion-show', 'new-upload.jpg'));
|
||||
});
|
||||
|
||||
it('throws when external photo is missing relative path data', () => {
|
||||
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
|
||||
const photo = { source_origin: 'external' };
|
||||
|
||||
Generated
+31
-31
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.1.5",
|
||||
"version": "1.1.11",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.1.5",
|
||||
"version": "1.1.11",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.850.0",
|
||||
"@aws-sdk/lib-storage": "^3.850.0",
|
||||
@@ -35,7 +35,7 @@
|
||||
"mime-types": "^3.0.1",
|
||||
"multer": "^2.0.2",
|
||||
"node-cron": "^3.0.2",
|
||||
"nodemailer": "^7.0.10",
|
||||
"nodemailer": "7.0.5",
|
||||
"pg": "^8.16.3",
|
||||
"react-i18next": "^15.6.0",
|
||||
"sanitize-html": "^2.17.0",
|
||||
@@ -5620,13 +5620,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/express-validator": {
|
||||
"version": "7.3.0",
|
||||
"resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.3.0.tgz",
|
||||
"integrity": "sha512-ujK2BX5JUun5NR4JuBo83YSXoDDIpoGz3QxgHTzQcHFevkKnwV1in4K7YNuuXQ1W3a2ObXB/P4OTnTZpUyGWiw==",
|
||||
"version": "7.2.1",
|
||||
"resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.2.1.tgz",
|
||||
"integrity": "sha512-CjNE6aakfpuwGaHQZ3m8ltCG2Qvivd7RHtVMS/6nVxOM7xVGqr4bhflsm4+N5FP5zI7Zxp+Hae+9RE+o8e3ZOQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lodash": "^4.17.21",
|
||||
"validator": "~13.15.15"
|
||||
"validator": "~13.12.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0.0"
|
||||
@@ -8355,9 +8355,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "7.0.10",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.10.tgz",
|
||||
"integrity": "sha512-Us/Se1WtT0ylXgNFfyFSx4LElllVLJXQjWi2Xz17xWw7amDKO2MLtFnVp1WACy7GkVGs+oBlRopVNUzlrGSw1w==",
|
||||
"version": "7.0.5",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.5.tgz",
|
||||
"integrity": "sha512-nsrh2lO3j4GkLLXoeEksAMgAOqxOv6QumNRVQTJwKH4nuiww6iC2y7GyANs9kRAxCexg3+lTWM3PZ91iLlVjfg==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
@@ -9008,6 +9008,24 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/prebuild-install/node_modules/chownr": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
|
||||
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/prebuild-install/node_modules/tar-fs": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.3.tgz",
|
||||
"integrity": "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chownr": "^1.1.1",
|
||||
"mkdirp-classic": "^0.5.2",
|
||||
"pump": "^3.0.0",
|
||||
"tar-stream": "^2.1.4"
|
||||
}
|
||||
},
|
||||
"node_modules/prelude-ls": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
||||
@@ -10228,24 +10246,6 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/tar-fs": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
|
||||
"integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chownr": "^1.1.1",
|
||||
"mkdirp-classic": "^0.5.2",
|
||||
"pump": "^3.0.0",
|
||||
"tar-stream": "^2.1.4"
|
||||
}
|
||||
},
|
||||
"node_modules/tar-fs/node_modules/chownr": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
|
||||
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/tar-stream": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
|
||||
@@ -10624,9 +10624,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/validator": {
|
||||
"version": "13.15.20",
|
||||
"resolved": "https://registry.npmjs.org/validator/-/validator-13.15.20.tgz",
|
||||
"integrity": "sha512-KxPOq3V2LmfQPP4eqf3Mq/zrT0Dqp2Vmx2Bn285LwVahLc+CsxOM0crBHczm8ijlcjZ0Q5Xd6LW3z3odTPnlrw==",
|
||||
"version": "13.12.0",
|
||||
"resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz",
|
||||
"integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.1.5",
|
||||
"version": "1.1.11",
|
||||
"description": "Backend for PicPeak event photo sharing platform",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
@@ -39,7 +39,7 @@
|
||||
"mime-types": "^3.0.1",
|
||||
"multer": "^2.0.2",
|
||||
"node-cron": "^3.0.2",
|
||||
"nodemailer": "^7.0.10",
|
||||
"nodemailer": "7.0.5",
|
||||
"pg": "^8.16.3",
|
||||
"react-i18next": "^15.6.0",
|
||||
"sanitize-html": "^2.17.0",
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
|
||||
const buildChain = ({ firstResult, updateResult } = {}) => {
|
||||
const chain = {
|
||||
where: jest.fn().mockReturnThis(),
|
||||
whereNot: jest.fn().mockReturnThis(),
|
||||
select: jest.fn().mockReturnThis(),
|
||||
update: jest.fn().mockResolvedValue(updateResult ?? 1),
|
||||
first: jest.fn().mockResolvedValue(firstResult),
|
||||
};
|
||||
return chain;
|
||||
};
|
||||
|
||||
jest.mock('../../database/db', () => {
|
||||
const dbMock = jest.fn();
|
||||
dbMock.raw = jest.fn();
|
||||
dbMock.__setImplementations = (...chains) => {
|
||||
dbMock.mockReset();
|
||||
chains.forEach((chain) => {
|
||||
dbMock.mockImplementationOnce(() => chain);
|
||||
});
|
||||
};
|
||||
return {
|
||||
db: dbMock,
|
||||
logActivity: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('../../middleware/auth-enhanced-v2', () => ({
|
||||
adminAuth: (_req, _res, next) => {
|
||||
_req.admin = { id: 1, username: 'admin' };
|
||||
next();
|
||||
},
|
||||
}));
|
||||
|
||||
const { db, logActivity } = require('../../database/db');
|
||||
const adminAuthRouter = require('../adminAuth');
|
||||
|
||||
describe('adminAuth profile updates', () => {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/auth/admin', adminAuthRouter);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('updates the admin profile', async () => {
|
||||
const updatedUser = {
|
||||
id: 1,
|
||||
username: 'newadmin',
|
||||
email: 'newadmin@example.com',
|
||||
must_change_password: false,
|
||||
};
|
||||
|
||||
db.__setImplementations(
|
||||
buildChain({ firstResult: null }), // email check
|
||||
buildChain({ firstResult: null }), // username check
|
||||
buildChain({ updateResult: 1 }), // update
|
||||
buildChain({ firstResult: updatedUser }), // fetch updated user
|
||||
);
|
||||
|
||||
const response = await request(app)
|
||||
.put('/auth/admin/profile')
|
||||
.send({ username: updatedUser.username, email: updatedUser.email })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body).toEqual({ user: updatedUser });
|
||||
expect(logActivity).toHaveBeenCalledWith(
|
||||
'admin_profile_updated',
|
||||
{ admin_id: 1, updated_fields: ['username', 'email'] },
|
||||
null,
|
||||
{ type: 'admin', id: 1, name: updatedUser.username }
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects email conflicts', async () => {
|
||||
db.__setImplementations(
|
||||
buildChain({ firstResult: { id: 2 } })
|
||||
);
|
||||
|
||||
const response = await request(app)
|
||||
.put('/auth/admin/profile')
|
||||
.send({ username: 'newadmin', email: 'taken@example.com' })
|
||||
.expect(409);
|
||||
|
||||
expect(response.body).toEqual({ error: 'Email is already in use by another admin' });
|
||||
});
|
||||
|
||||
it('validates input', async () => {
|
||||
const response = await request(app)
|
||||
.put('/auth/admin/profile')
|
||||
.send({ username: '', email: 'not-an-email' })
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
|
||||
jest.mock('../../database/db', () => {
|
||||
const deleteMock = jest.fn().mockResolvedValue(5);
|
||||
const chain = {
|
||||
select: jest.fn().mockReturnThis(),
|
||||
leftJoin: jest.fn().mockReturnThis(),
|
||||
orderBy: jest.fn().mockReturnThis(),
|
||||
limit: jest.fn().mockReturnThis(),
|
||||
whereNull: jest.fn().mockReturnThis(),
|
||||
whereNotNull: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
update: jest.fn().mockReturnThis(),
|
||||
delete: deleteMock,
|
||||
count: jest.fn().mockReturnThis(),
|
||||
first: jest.fn().mockResolvedValue({ count: 0 }),
|
||||
};
|
||||
|
||||
const dbMock = jest.fn(() => chain);
|
||||
dbMock.raw = jest.fn();
|
||||
dbMock.__chain = chain;
|
||||
dbMock.__deleteMock = deleteMock;
|
||||
return { db: dbMock };
|
||||
});
|
||||
|
||||
jest.mock('../../middleware/auth-enhanced-v2', () => ({
|
||||
adminAuth: (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
const { db } = require('../../database/db');
|
||||
const notificationsRouter = require('../adminNotifications');
|
||||
|
||||
describe('adminNotifications routes', () => {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/admin/notifications', notificationsRouter);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('clears all notifications', async () => {
|
||||
db.__deleteMock.mockResolvedValueOnce(8);
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/admin/notifications/clear-all')
|
||||
.expect(200);
|
||||
|
||||
expect(db).toHaveBeenCalledWith('activity_logs');
|
||||
expect(db.__deleteMock).toHaveBeenCalledTimes(1);
|
||||
expect(response.body).toEqual({
|
||||
message: 'All notifications cleared',
|
||||
deletedCount: 8,
|
||||
});
|
||||
});
|
||||
|
||||
it('handles database errors when clearing notifications', async () => {
|
||||
db.__deleteMock.mockRejectedValueOnce(new Error('boom'));
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/admin/notifications/clear-all')
|
||||
.expect(500);
|
||||
|
||||
expect(response.body).toEqual({ error: 'Failed to clear notifications' });
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,93 @@ const { validatePasswordStrength } = require('../utils/passwordGenerator');
|
||||
const router = express.Router();
|
||||
|
||||
// Change password
|
||||
router.get('/profile', adminAuth, async (req, res) => {
|
||||
try {
|
||||
const admin = await db('admin_users')
|
||||
.where('id', req.admin.id)
|
||||
.select('id', 'username', 'email', 'last_login', 'last_login_ip', 'created_at', 'updated_at', 'must_change_password as mustChangePassword')
|
||||
.first();
|
||||
|
||||
if (!admin) {
|
||||
return res.status(404).json({ error: 'Admin user not found' });
|
||||
}
|
||||
|
||||
res.json(admin);
|
||||
} catch (error) {
|
||||
console.error('Admin profile fetch error:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch admin profile' });
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/profile', [
|
||||
adminAuth,
|
||||
body('username')
|
||||
.trim()
|
||||
.isLength({ min: 3, max: 50 })
|
||||
.withMessage('Username must be between 3 and 50 characters'),
|
||||
body('email')
|
||||
.trim()
|
||||
.isEmail()
|
||||
.withMessage('A valid email address is required')
|
||||
.normalizeEmail()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ errors: errors.array() });
|
||||
}
|
||||
|
||||
const username = req.body.username.trim();
|
||||
const email = req.body.email.trim().toLowerCase();
|
||||
const adminId = req.admin.id;
|
||||
|
||||
const existingUsername = await db('admin_users')
|
||||
.where('username', username)
|
||||
.whereNot('id', adminId)
|
||||
.first();
|
||||
|
||||
if (existingUsername) {
|
||||
return res.status(409).json({ error: 'Username is already in use' });
|
||||
}
|
||||
|
||||
const existingEmail = await db('admin_users')
|
||||
.where('email', email)
|
||||
.whereNot('id', adminId)
|
||||
.first();
|
||||
|
||||
if (existingEmail) {
|
||||
return res.status(409).json({ error: 'Email address is already in use' });
|
||||
}
|
||||
|
||||
await db('admin_users')
|
||||
.where('id', adminId)
|
||||
.update({
|
||||
username,
|
||||
email,
|
||||
updated_at: new Date()
|
||||
});
|
||||
|
||||
await logActivity('admin_profile_updated',
|
||||
{ username, email },
|
||||
null,
|
||||
{ type: 'admin', id: adminId, name: req.admin.username }
|
||||
);
|
||||
|
||||
const updatedAdmin = await db('admin_users')
|
||||
.where('id', adminId)
|
||||
.select('id', 'username', 'email', 'must_change_password as mustChangePassword')
|
||||
.first();
|
||||
|
||||
res.json({
|
||||
message: 'Admin profile updated successfully',
|
||||
user: updatedAdmin
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Admin profile update error:', error);
|
||||
res.status(500).json({ error: 'Failed to update admin profile' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/change-password', [
|
||||
adminAuth,
|
||||
body('currentPassword').notEmpty().withMessage('Current password is required'),
|
||||
@@ -72,68 +159,6 @@ router.post('/change-password', [
|
||||
}
|
||||
});
|
||||
|
||||
// Update admin profile
|
||||
router.put('/profile', [
|
||||
adminAuth,
|
||||
body('username').trim().notEmpty().withMessage('Username is required'),
|
||||
body('email').trim().isEmail().withMessage('Valid email is required')
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ errors: errors.array() });
|
||||
}
|
||||
|
||||
const { username, email } = req.body;
|
||||
const userId = req.admin.id;
|
||||
|
||||
// Check for email conflicts
|
||||
const existingEmail = await db('admin_users')
|
||||
.where('email', email)
|
||||
.whereNot('id', userId)
|
||||
.first();
|
||||
|
||||
if (existingEmail) {
|
||||
return res.status(409).json({ error: 'Email is already in use by another admin' });
|
||||
}
|
||||
|
||||
// Check username conflict (if multiple admins are supported)
|
||||
const existingUsername = await db('admin_users')
|
||||
.where('username', username)
|
||||
.whereNot('id', userId)
|
||||
.first();
|
||||
|
||||
if (existingUsername) {
|
||||
return res.status(409).json({ error: 'Username is already in use by another admin' });
|
||||
}
|
||||
|
||||
await db('admin_users')
|
||||
.where('id', userId)
|
||||
.update({
|
||||
username,
|
||||
email,
|
||||
updated_at: new Date()
|
||||
});
|
||||
|
||||
const updatedUser = await db('admin_users')
|
||||
.select('id', 'username', 'email', 'must_change_password')
|
||||
.where('id', userId)
|
||||
.first();
|
||||
|
||||
await logActivity(
|
||||
'admin_profile_updated',
|
||||
{ admin_id: userId, updated_fields: ['username', 'email'] },
|
||||
null,
|
||||
{ type: 'admin', id: userId, name: username }
|
||||
);
|
||||
|
||||
res.json({ user: updatedUser });
|
||||
} catch (error) {
|
||||
console.error('Admin profile update error:', error);
|
||||
res.status(500).json({ error: 'Failed to update admin profile' });
|
||||
}
|
||||
});
|
||||
|
||||
// Logout
|
||||
router.post('/logout', adminAuth, async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -103,14 +103,51 @@ router.delete('/clear-old', adminAuth, async (req, res) => {
|
||||
// Use database-agnostic date calculation
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
|
||||
const deletedCount = await db('activity_logs')
|
||||
.whereNotNull('read_at')
|
||||
.where('created_at', '<', thirtyDaysAgo)
|
||||
.delete();
|
||||
|
||||
let deletedCount = 0;
|
||||
const client = db?.client?.config?.client;
|
||||
|
||||
if (client === 'pg') {
|
||||
const primaryResult = await db.raw(
|
||||
`
|
||||
WITH deleted AS (
|
||||
DELETE FROM activity_logs
|
||||
WHERE read_at IS NOT NULL OR created_at < ?
|
||||
RETURNING id
|
||||
)
|
||||
SELECT COUNT(*)::int AS count FROM deleted
|
||||
`,
|
||||
[thirtyDaysAgo.toISOString()]
|
||||
);
|
||||
deletedCount = primaryResult.rows?.[0]?.count || 0;
|
||||
|
||||
if (deletedCount === 0) {
|
||||
const fallbackResult = await db.raw(
|
||||
`
|
||||
WITH deleted AS (
|
||||
DELETE FROM activity_logs
|
||||
RETURNING id
|
||||
)
|
||||
SELECT COUNT(*)::int AS count FROM deleted
|
||||
`
|
||||
);
|
||||
deletedCount = fallbackResult.rows?.[0]?.count || 0;
|
||||
}
|
||||
} else {
|
||||
deletedCount = await db('activity_logs')
|
||||
.where(function () {
|
||||
this.whereNotNull('read_at')
|
||||
.orWhere('created_at', '<', thirtyDaysAgo);
|
||||
})
|
||||
.delete();
|
||||
|
||||
if (deletedCount === 0) {
|
||||
deletedCount = await db('activity_logs').delete();
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
message: 'Old notifications cleared',
|
||||
message: deletedCount > 0 ? 'Old notifications cleared' : 'No notifications to clear',
|
||||
deletedCount
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -119,18 +156,4 @@ router.delete('/clear-old', adminAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Delete all notifications
|
||||
router.delete('/clear-all', adminAuth, async (req, res) => {
|
||||
try {
|
||||
const deletedCount = await db('activity_logs').delete();
|
||||
res.json({
|
||||
message: 'All notifications cleared',
|
||||
deletedCount
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Clear all notifications error:', error);
|
||||
res.status(500).json({ error: 'Failed to clear notifications' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -13,24 +13,6 @@ const router = express.Router();
|
||||
// Get storage path from environment or default
|
||||
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
||||
|
||||
const parseCategoryId = (value) => {
|
||||
if (value === undefined || value === null) return null;
|
||||
if (typeof value === 'number' && Number.isInteger(value)) {
|
||||
return value === 0 ? null : value;
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed || trimmed === 'null') return null;
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const parsed = parseInt(trimmed, 10);
|
||||
if (!Number.isNaN(parsed)) {
|
||||
return parsed === 0 ? null : parsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Configure multer for file uploads
|
||||
// IMPORTANT: Using synchronous functions to prevent file corruption
|
||||
const storage = multer.diskStorage({
|
||||
@@ -176,16 +158,16 @@ router.post('/:eventId/upload', adminAuth, uploadTimeout(600000), (req, res, nex
|
||||
}
|
||||
|
||||
// Parse category_id to number if provided
|
||||
const numericCategoryId = parseCategoryId(category_id);
|
||||
const parsedCategoryId = category_id ? parseInt(category_id, 10) : null;
|
||||
|
||||
// Determine photo type from category_id parameter (for backwards compatibility)
|
||||
let photoType = 'individual'; // default
|
||||
let categoryName = 'individual';
|
||||
|
||||
if (numericCategoryId === 1 || category_id === 'collage') {
|
||||
if (parsedCategoryId === 1 || category_id === 'collage') {
|
||||
photoType = 'collage';
|
||||
categoryName = 'collages';
|
||||
} else if (numericCategoryId === 2 || category_id === 'individual') {
|
||||
} else if (parsedCategoryId === 2 || category_id === 'individual') {
|
||||
photoType = 'individual';
|
||||
categoryName = 'individual';
|
||||
}
|
||||
@@ -257,9 +239,7 @@ router.post('/:eventId/upload', adminAuth, uploadTimeout(600000), (req, res, nex
|
||||
path: relativePath,
|
||||
thumbnail_path: null, // Will generate after successful commit
|
||||
type: photoType,
|
||||
size_bytes: tempStats.size, // Use actual file size from stat
|
||||
category_id: numericCategoryId,
|
||||
source_origin: 'managed'
|
||||
size_bytes: tempStats.size // Use actual file size from stat
|
||||
};
|
||||
|
||||
batchPhotos.push(photoData);
|
||||
@@ -495,11 +475,9 @@ router.patch('/:eventId/photos/:photoId', adminAuth, async (req, res) => {
|
||||
}
|
||||
|
||||
// Update photo
|
||||
const normalizedCategoryId = parseCategoryId(category_id);
|
||||
|
||||
await db('photos')
|
||||
.where({ id: photoId })
|
||||
.update({ category_id: normalizedCategoryId });
|
||||
.update({ category_id: category_id || null });
|
||||
|
||||
res.json({ message: 'Photo updated successfully' });
|
||||
} catch (error) {
|
||||
@@ -600,7 +578,7 @@ router.post('/:eventId/photos/bulk-update', adminAuth, async (req, res) => {
|
||||
// Update photos
|
||||
const updateData = {};
|
||||
if (updates.category_id !== undefined) {
|
||||
updateData.category_id = parseCategoryId(updates.category_id);
|
||||
updateData.category_id = updates.category_id || null;
|
||||
}
|
||||
|
||||
await db('photos')
|
||||
@@ -654,22 +632,14 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
||||
const { category_id, type, search, sort = 'date', order = 'desc' } = req.query;
|
||||
|
||||
let query = db('photos')
|
||||
.leftJoin('photo_categories as pc', 'pc.id', 'photos.category_id')
|
||||
.where({ 'photos.event_id': eventId })
|
||||
.select(
|
||||
'photos.*',
|
||||
'pc.name as category_display_name',
|
||||
'pc.slug as category_display_slug'
|
||||
);
|
||||
.select('photos.*');
|
||||
|
||||
// Filter by type (individual/collage) - category_id maps to type
|
||||
if (category_id !== undefined) {
|
||||
if (category_id === '') {
|
||||
// No filter when empty string is provided
|
||||
} else if (category_id === '0') {
|
||||
query = query.whereNull('photos.category_id');
|
||||
} else if (/^\d+$/.test(category_id)) {
|
||||
query = query.where('photos.category_id', parseInt(category_id, 10));
|
||||
if (category_id === '' || category_id === '0') {
|
||||
// For backwards compatibility, empty category means no filter
|
||||
// Don't filter anything
|
||||
} else if (category_id === 'individual' || category_id === 'collage') {
|
||||
query = query.where({ 'photos.type': category_id });
|
||||
}
|
||||
@@ -695,11 +665,7 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
||||
}
|
||||
|
||||
const photos = await query.orderBy(orderByColumn, order);
|
||||
|
||||
if (photos.length === 0) {
|
||||
return res.json({ photos: [] });
|
||||
}
|
||||
|
||||
|
||||
// Get comment counts separately
|
||||
const commentCounts = await db('photo_feedback')
|
||||
.whereIn('photo_id', photos.map(p => p.id))
|
||||
@@ -724,11 +690,9 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
||||
// Always expose a thumbnail URL; backend will generate on demand if missing
|
||||
thumbnail_url: `/admin/photos/${eventId}/thumbnail/${photo.id}`,
|
||||
type: photo.type,
|
||||
category_id: photo.category_id !== null && photo.category_id !== undefined
|
||||
? Number(photo.category_id)
|
||||
: null,
|
||||
category_name: photo.category_display_name || (photo.type === 'individual' ? 'Individual Photos' : 'Collages'),
|
||||
category_slug: photo.category_display_slug || photo.type,
|
||||
category_id: photo.type,
|
||||
category_name: photo.type === 'individual' ? 'Individual Photos' : 'Collages',
|
||||
category_slug: photo.type,
|
||||
size: photo.size_bytes,
|
||||
uploaded_at: photo.uploaded_at,
|
||||
// Feedback data
|
||||
|
||||
@@ -12,10 +12,8 @@ const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '.
|
||||
function resolvePhotoFilePath(event, photo) {
|
||||
if (!event || !photo) throw new Error('resolvePhotoFilePath requires event and photo');
|
||||
|
||||
const isExternal = photo.source_origin === 'external' ||
|
||||
(!!photo.external_relpath && (event.source_mode === 'reference' || event.source_mode === 'external'));
|
||||
|
||||
if (isExternal) {
|
||||
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');
|
||||
}
|
||||
|
||||
+5
-31
@@ -3,45 +3,19 @@
|
||||
|
||||
set -e
|
||||
|
||||
host="${DB_HOST:-postgres}"
|
||||
host="$DB_HOST"
|
||||
port="${DB_PORT:-5432}"
|
||||
user="${DB_USER:-picpeak}"
|
||||
target_db="${DB_NAME:-picpeak}"
|
||||
default_db="${DB_CHECK_DB:-postgres}"
|
||||
|
||||
sanitize_identifier() {
|
||||
printf '%s' "$1" | sed "s/'/''/g"
|
||||
}
|
||||
|
||||
echo "Waiting for PostgreSQL at $host:$port..."
|
||||
|
||||
# Wait for PostgreSQL server to accept connections (using the default database)
|
||||
until PGPASSWORD="$DB_PASSWORD" psql -h "$host" -p "$port" -U "$user" -d "$default_db" -c '\q' >/dev/null 2>&1; do
|
||||
# Wait for PostgreSQL to be ready
|
||||
until PGPASSWORD=$DB_PASSWORD psql -h "$host" -p "$port" -U "$user" -d "${DB_NAME:-picpeak}" -c '\q' 2>/dev/null; do
|
||||
>&2 echo "PostgreSQL is unavailable - sleeping"
|
||||
sleep 2
|
||||
done
|
||||
|
||||
>&2 echo "PostgreSQL is up - verifying target database \"$target_db\""
|
||||
|
||||
# Ensure the target database exists (helps when volumes are reused or DB_NAME is customised)
|
||||
db_exists=$(PGPASSWORD="$DB_PASSWORD" psql -h "$host" -p "$port" -U "$user" -d "$default_db" -tAc "SELECT 1 FROM pg_database WHERE datname = '$(sanitize_identifier "$target_db")'" 2>/dev/null || echo 0)
|
||||
|
||||
if [ "$db_exists" != "1" ]; then
|
||||
>&2 echo "Database \"$target_db\" not found. Attempting to create..."
|
||||
if ! PGPASSWORD="$DB_PASSWORD" psql -h "$host" -p "$port" -U "$user" -d "$default_db" -c "CREATE DATABASE \"$target_db\";" >/dev/null 2>&1; then
|
||||
>&2 echo "Failed to create database \"$target_db\". Please ensure it exists and is accessible."
|
||||
exit 1
|
||||
fi
|
||||
>&2 echo "Database \"$target_db\" created successfully."
|
||||
fi
|
||||
|
||||
# Wait until the target database itself is ready to accept connections
|
||||
until PGPASSWORD="$DB_PASSWORD" psql -h "$host" -p "$port" -U "$user" -d "$target_db" -c '\q' >/dev/null 2>&1; do
|
||||
>&2 echo "Waiting for database \"$target_db\" to accept connections..."
|
||||
sleep 2
|
||||
done
|
||||
|
||||
>&2 echo "Target database \"$target_db\" is ready."
|
||||
>&2 echo "PostgreSQL is up - executing command"
|
||||
|
||||
# Run migrations (use safe runner in production)
|
||||
echo "Running database migrations..."
|
||||
@@ -52,4 +26,4 @@ else
|
||||
fi
|
||||
|
||||
# Execute the main command
|
||||
exec "$@"
|
||||
exec "$@"
|
||||
+1
-1
@@ -101,7 +101,7 @@ services:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
- VITE_API_URL=${VITE_API_URL:-/api}
|
||||
- VITE_API_URL=${VITE_API_URL:-http://localhost:3001/api}
|
||||
- VITE_UMAMI_URL=${VITE_UMAMI_URL:-}
|
||||
- VITE_UMAMI_WEBSITE_ID=${VITE_UMAMI_WEBSITE_ID:-}
|
||||
- VITE_UMAMI_SHARE_URL=${VITE_UMAMI_SHARE_URL:-}
|
||||
|
||||
@@ -19,28 +19,5 @@ export default tseslint.config([
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
|
||||
'react-hooks/rules-of-hooks': 'off',
|
||||
'react-hooks/exhaustive-deps': 'warn',
|
||||
'no-useless-escape': 'off',
|
||||
'no-case-declarations': 'off',
|
||||
'prefer-const': 'off',
|
||||
'no-control-regex': 'off',
|
||||
'no-useless-catch': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'no-empty': 'off',
|
||||
'no-debugger': 'off',
|
||||
'@typescript-eslint/no-unused-expressions': 'off',
|
||||
'@typescript-eslint/ban-ts-comment': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.d.ts'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-unused-vars': 'off',
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
Generated
+10
-1289
File diff suppressed because it is too large
Load Diff
+6
-13
@@ -1,15 +1,14 @@
|
||||
{
|
||||
"name": "picpeak-frontend",
|
||||
"private": true,
|
||||
"version": "1.1.7",
|
||||
"version": "1.1.12",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "cross-env ROLLUP_USE_NODE_JS=true vite build",
|
||||
"build:check": "tsc -b && cross-env ROLLUP_USE_NODE_JS=true vite build",
|
||||
"build": "vite build",
|
||||
"build:check": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run src/components/admin/__tests__/ThemeCustomizerEnhanced.test.tsx"
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
@@ -48,24 +47,18 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.1.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.5.3",
|
||||
"@vitejs/plugin-react": "^4.5.2",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^9.29.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.20",
|
||||
"globals": "^16.2.0",
|
||||
"jsdom": "^25.0.1",
|
||||
"postcss": "^8.4.21",
|
||||
"tailwindcss": "^3.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.34.1",
|
||||
"vite": "^7.1.12",
|
||||
"vitest": "^3.2.4"
|
||||
"vite": "^7.1.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ export const MaintenanceMode: React.FC = () => {
|
||||
try {
|
||||
const response = await api.get('/public/settings');
|
||||
return response.data;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// Return empty object if settings can't be fetched
|
||||
return {};
|
||||
}
|
||||
@@ -110,4 +110,4 @@ export const MaintenanceMode: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -31,7 +31,7 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
||||
if (isMounted) {
|
||||
setHasAdminSession(Boolean(response.data?.valid && response.data.type === 'admin'));
|
||||
}
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (isMounted) {
|
||||
setHasAdminSession(false);
|
||||
}
|
||||
|
||||
@@ -18,13 +18,11 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let objectUrl: string | null = null;
|
||||
|
||||
const loadImage = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(false);
|
||||
setImageSrc(null);
|
||||
|
||||
// Make authenticated request to get the image
|
||||
const response = await api.get(src, {
|
||||
@@ -33,11 +31,11 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
||||
|
||||
if (!cancelled) {
|
||||
// Create object URL from blob
|
||||
objectUrl = URL.createObjectURL(response.data);
|
||||
setImageSrc(objectUrl);
|
||||
const imageUrl = URL.createObjectURL(response.data);
|
||||
setImageSrc(imageUrl);
|
||||
setLoading(false);
|
||||
}
|
||||
} catch {
|
||||
} catch (err: any) {
|
||||
// Image loading failed - handled by error state
|
||||
if (!cancelled) {
|
||||
setError(true);
|
||||
@@ -53,8 +51,8 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
||||
// Cleanup function
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
if (imageSrc) {
|
||||
URL.revokeObjectURL(imageSrc);
|
||||
}
|
||||
};
|
||||
}, [src]);
|
||||
@@ -76,4 +74,4 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
||||
}
|
||||
|
||||
return <img src={imageSrc || ''} alt={alt} {...props} />;
|
||||
};
|
||||
};
|
||||
@@ -55,12 +55,12 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
},
|
||||
});
|
||||
|
||||
// Clear notifications mutation
|
||||
const clearAllMutation = useMutation({
|
||||
mutationFn: notificationsService.clearAllNotifications,
|
||||
// Clear old notifications mutation
|
||||
const clearOldMutation = useMutation({
|
||||
mutationFn: notificationsService.clearOldNotifications,
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['notifications'] });
|
||||
toast.success(t('admin.notificationToasts.clearedAll', { count: data.deletedCount }));
|
||||
toast.success(t('admin.notificationToasts.clearedOld', { count: data.deletedCount }));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -128,12 +128,12 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => clearAllMutation.mutate()}
|
||||
onClick={() => clearOldMutation.mutate()}
|
||||
className="text-xs text-neutral-600 hover:text-neutral-700 flex items-center gap-1"
|
||||
title={t('admin.clearAll')}
|
||||
title={t('admin.clearOld')}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
{t('admin.clearAll')}
|
||||
{t('admin.clearOld')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -62,7 +62,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
await photosService.deletePhoto(eventId, photo.id);
|
||||
toast.success('Photo deleted successfully');
|
||||
onPhotosDeleted();
|
||||
} catch {
|
||||
} catch (error) {
|
||||
toast.error('Failed to delete photo');
|
||||
setDeletingPhotos(prev => {
|
||||
const newSet = new Set(prev);
|
||||
@@ -90,7 +90,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
setSelectedPhotos(new Set());
|
||||
setIsSelectionMode(false);
|
||||
onPhotosDeleted();
|
||||
} catch {
|
||||
} catch (error) {
|
||||
toast.error('Failed to delete photos');
|
||||
setDeletingPhotos(new Set());
|
||||
} finally {
|
||||
@@ -103,7 +103,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
try {
|
||||
await photosService.downloadPhoto(eventId, photo.id, photo.filename);
|
||||
toast.success('Download started');
|
||||
} catch {
|
||||
} catch (error) {
|
||||
toast.error('Failed to download photo');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -14,8 +14,6 @@ interface ThemeCustomizerEnhancedProps {
|
||||
isPreviewMode?: boolean;
|
||||
showGalleryLayouts?: boolean;
|
||||
hideActions?: boolean;
|
||||
onApply?: (theme: ThemeConfig, metadata: { presetName: string }) => Promise<void> | void;
|
||||
isApplying?: boolean;
|
||||
}
|
||||
|
||||
const layoutIcons: Record<GalleryLayoutType, React.ReactNode> = {
|
||||
@@ -36,9 +34,7 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
||||
onPresetChange,
|
||||
isPreviewMode = false,
|
||||
showGalleryLayouts = true,
|
||||
hideActions = false,
|
||||
onApply,
|
||||
isApplying = false
|
||||
hideActions = false
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [localTheme, setLocalTheme] = useState<ThemeConfig>(value);
|
||||
@@ -84,13 +80,8 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
||||
}
|
||||
};
|
||||
|
||||
const handleApply = async () => {
|
||||
const themeWithCss = { ...localTheme, customCss };
|
||||
onChange(themeWithCss);
|
||||
|
||||
if (onApply) {
|
||||
await onApply(themeWithCss, { presetName: selectedPreset });
|
||||
}
|
||||
const handleApply = () => {
|
||||
onChange({ ...localTheme, customCss });
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
@@ -596,12 +587,11 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
||||
variant="primary"
|
||||
leftIcon={<Palette className="w-4 h-4" />}
|
||||
onClick={handleApply}
|
||||
disabled={isApplying}
|
||||
>
|
||||
{isApplying ? t('common.applying', 'Applying...') : t('branding.applyTheme')}
|
||||
{t('branding.applyTheme')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,70 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
import { ThemeCustomizerEnhanced } from '../ThemeCustomizerEnhanced';
|
||||
import type { ThemeConfig } from '../../../types/theme.types';
|
||||
|
||||
vi.mock('react-i18next', async () => {
|
||||
const actual = await vi.importActual<typeof import('react-i18next')>('react-i18next');
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: () => ({
|
||||
t: (_key: string, fallback?: string) => fallback ?? _key
|
||||
})
|
||||
};
|
||||
});
|
||||
|
||||
describe('ThemeCustomizerEnhanced', () => {
|
||||
const baseTheme: ThemeConfig = {
|
||||
primaryColor: '#000000',
|
||||
accentColor: '#ffffff',
|
||||
backgroundColor: '#eeeeee',
|
||||
textColor: '#111111',
|
||||
galleryLayout: 'grid',
|
||||
gallerySettings: {
|
||||
spacing: 'normal'
|
||||
}
|
||||
};
|
||||
|
||||
it('invokes onApply when Apply Theme is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const handleChange = vi.fn();
|
||||
const handleApply = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
render(
|
||||
<ThemeCustomizerEnhanced
|
||||
value={baseTheme}
|
||||
onChange={handleChange}
|
||||
presetName="default"
|
||||
onApply={handleApply}
|
||||
/>
|
||||
);
|
||||
|
||||
const applyButton = screen.getByRole('button', { name: /branding\.applyTheme/i });
|
||||
await user.click(applyButton);
|
||||
|
||||
expect(handleChange).toHaveBeenCalled();
|
||||
expect(handleApply).toHaveBeenCalledTimes(1);
|
||||
expect(handleApply).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ primaryColor: '#000000' }),
|
||||
expect.objectContaining({ presetName: 'default' })
|
||||
);
|
||||
});
|
||||
|
||||
it('disables the Apply button while applying', () => {
|
||||
const handleChange = vi.fn();
|
||||
|
||||
render(
|
||||
<ThemeCustomizerEnhanced
|
||||
value={baseTheme}
|
||||
onChange={handleChange}
|
||||
presetName="default"
|
||||
isApplying={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const applyButton = screen.getByRole('button', { name: /applying/i });
|
||||
expect(applyButton).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -209,7 +209,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// Invalid theme format - use default
|
||||
// Fall back to global theme
|
||||
if (settingsData.theme_config) {
|
||||
|
||||
@@ -12,7 +12,7 @@ interface GridPhotoProps {
|
||||
photo: Photo;
|
||||
isSelected: boolean;
|
||||
isSelectionMode: boolean;
|
||||
onClick: () => void;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onDownload: (e: React.MouseEvent) => void;
|
||||
onToggleSelect: () => void;
|
||||
animationType?: string;
|
||||
@@ -57,79 +57,6 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
liked = false,
|
||||
onLikeSuccess
|
||||
}) => {
|
||||
const [overlayVisible, setOverlayVisible] = React.useState(false);
|
||||
const [isTouchDevice, setIsTouchDevice] = React.useState(false);
|
||||
const overlayTimeoutRef = React.useRef<number | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const mediaQuery = window.matchMedia('(hover: none) and (pointer: coarse)');
|
||||
const updateTouchState = () => {
|
||||
const hasNavigator = typeof navigator !== 'undefined';
|
||||
setIsTouchDevice(
|
||||
mediaQuery.matches ||
|
||||
('ontouchstart' in window) ||
|
||||
(hasNavigator && navigator.maxTouchPoints > 0)
|
||||
);
|
||||
};
|
||||
|
||||
updateTouchState();
|
||||
|
||||
const listener = (event: MediaQueryListEvent) => {
|
||||
setIsTouchDevice(event.matches);
|
||||
};
|
||||
|
||||
if (mediaQuery.addEventListener) {
|
||||
mediaQuery.addEventListener('change', listener);
|
||||
} else if (mediaQuery.addListener) {
|
||||
mediaQuery.addListener(listener);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (mediaQuery.removeEventListener) {
|
||||
mediaQuery.removeEventListener('change', listener);
|
||||
} else if (mediaQuery.removeListener) {
|
||||
mediaQuery.removeListener(listener);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const hideOverlay = React.useCallback(() => {
|
||||
if (overlayTimeoutRef.current !== null && typeof window !== 'undefined') {
|
||||
window.clearTimeout(overlayTimeoutRef.current);
|
||||
}
|
||||
overlayTimeoutRef.current = null;
|
||||
setOverlayVisible(false);
|
||||
}, []);
|
||||
|
||||
const showOverlayTemporarily = React.useCallback(() => {
|
||||
setOverlayVisible(true);
|
||||
if (overlayTimeoutRef.current !== null && typeof window !== 'undefined') {
|
||||
window.clearTimeout(overlayTimeoutRef.current);
|
||||
}
|
||||
if (typeof window !== 'undefined') {
|
||||
overlayTimeoutRef.current = window.setTimeout(() => {
|
||||
overlayTimeoutRef.current = null;
|
||||
setOverlayVisible(false);
|
||||
}, 2500);
|
||||
}
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
if (overlayTimeoutRef.current !== null && typeof window !== 'undefined') {
|
||||
window.clearTimeout(overlayTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isSelectionMode) {
|
||||
hideOverlay();
|
||||
}
|
||||
}, [isSelectionMode, hideOverlay]);
|
||||
|
||||
// handled by parent layout; kept here for type completeness but not used
|
||||
const { ref, inView } = useInView({
|
||||
triggerOnce: true,
|
||||
@@ -146,34 +73,11 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
const commentCount = photo.comment_count ?? 0;
|
||||
const showFeedbackActions = feedbackEnabled && Boolean(feedbackOptions);
|
||||
|
||||
const overlayVisibilityClass = overlayVisible
|
||||
? 'opacity-100 md:opacity-100'
|
||||
: 'opacity-0 md:opacity-0';
|
||||
|
||||
const checkboxVisibilityClass =
|
||||
isSelected || isSelectionMode || overlayVisible
|
||||
? 'opacity-100 md:opacity-100'
|
||||
: 'opacity-0 md:opacity-0';
|
||||
|
||||
const handlePhotoClick = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (isTouchDevice && !overlayVisible && !isSelectionMode) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
showOverlayTemporarily();
|
||||
return;
|
||||
}
|
||||
|
||||
onClick();
|
||||
if (isTouchDevice) {
|
||||
hideOverlay();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`relative group cursor-pointer aspect-square ${animationClass}`}
|
||||
onClick={handlePhotoClick}
|
||||
onClick={onClick}
|
||||
style={{
|
||||
opacity: !inView && animationType === 'fade' ? 0 : 1
|
||||
}}
|
||||
@@ -204,15 +108,14 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className={`absolute inset-0 bg-black/40 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2 ${overlayVisibilityClass} md:group-hover:opacity-100`}>
|
||||
<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 && (
|
||||
<>
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClick();
|
||||
hideOverlay();
|
||||
onClick(e);
|
||||
}}
|
||||
aria-label="View full size"
|
||||
>
|
||||
@@ -221,11 +124,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
{allowDownloads && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDownload(e);
|
||||
hideOverlay();
|
||||
}}
|
||||
onClick={onDownload}
|
||||
aria-label="Download photo"
|
||||
>
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
@@ -234,11 +133,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
{showFeedbackActions && onQuickComment && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onQuickComment();
|
||||
hideOverlay();
|
||||
}}
|
||||
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
||||
aria-label="Comment on photo"
|
||||
title="Comment"
|
||||
>
|
||||
@@ -253,7 +148,6 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
e.stopPropagation();
|
||||
if (feedbackOptions?.requireNameEmail && !savedIdentity && onRequireIdentity) {
|
||||
onRequireIdentity('like', photo.id);
|
||||
hideOverlay();
|
||||
return;
|
||||
}
|
||||
// Optimistic UI: mark as liked immediately
|
||||
@@ -269,7 +163,6 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
console.warn('Like submit failed, keeping optimistic UI', err);
|
||||
}
|
||||
if (onFeedbackChange) onFeedbackChange();
|
||||
hideOverlay();
|
||||
}}
|
||||
aria-label="Like photo"
|
||||
aria-pressed={liked}
|
||||
@@ -289,7 +182,9 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
role="checkbox"
|
||||
aria-checked={isSelected}
|
||||
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||
className={`absolute top-2 right-2 z-20 transition-opacity ${checkboxVisibilityClass} md:group-hover:opacity-100`}
|
||||
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`}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock, Heart, MessageSquare } from 'lucide-react';
|
||||
import { parseISO } from 'date-fns';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
@@ -50,12 +50,6 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
||||
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||
const gridRef = useRef<HTMLDivElement | null>(null);
|
||||
const handleScrollToGrid = useCallback(() => {
|
||||
if (gridRef.current) {
|
||||
gridRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
}, []);
|
||||
|
||||
// If an override is provided, always use it and skip initialization logic
|
||||
useEffect(() => {
|
||||
@@ -169,40 +163,30 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
|
||||
{/* Scroll Indicator */}
|
||||
<div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 animate-bounce">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleScrollToGrid}
|
||||
className="rounded-full border border-white/30 bg-white/10 p-3 text-white transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 hover:bg-white/20"
|
||||
aria-label={t('gallery.scrollToGallery', 'Scroll to gallery')}
|
||||
>
|
||||
<ChevronDown className="w-8 h-8 drop-shadow-lg" />
|
||||
</button>
|
||||
<ChevronDown className="w-8 h-8 text-white drop-shadow-lg" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Grid Section */}
|
||||
<div
|
||||
ref={gridRef}
|
||||
className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4"
|
||||
>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
|
||||
{remainingPhotos.map((photo) => {
|
||||
const actualIndex = photos.findIndex(p => p.id === photo.id);
|
||||
return (
|
||||
<div
|
||||
key={photo.id}
|
||||
className="relative group cursor-pointer overflow-hidden rounded-lg"
|
||||
className="relative group cursor-pointer aspect-square"
|
||||
onClick={() => onPhotoClick(actualIndex)}
|
||||
>
|
||||
<AuthenticatedImage
|
||||
src={photo.thumbnail_url || photo.url}
|
||||
alt={photo.filename}
|
||||
className="w-full h-auto object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
className="w-full h-full object-cover rounded-lg transition-transform duration-300 group-hover:scale-105"
|
||||
loading="lazy"
|
||||
isGallery={true}
|
||||
protectFromDownload={!allowDownloads}
|
||||
/>
|
||||
|
||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center gap-2">
|
||||
|
||||
<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">
|
||||
{!isSelectionMode && (
|
||||
<>
|
||||
<button
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
inferGallerySlugFromLocation,
|
||||
resolveSlugFromRequestUrl,
|
||||
} from '../utils/galleryAuthStorage';
|
||||
import { getApiBaseUrl } from '../utils/url';
|
||||
|
||||
// Maintenance mode callback
|
||||
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
||||
@@ -16,7 +15,7 @@ export const setMaintenanceModeCallback = (callback: (enabled: boolean) => void)
|
||||
|
||||
// Create axios instance
|
||||
export const api = axios.create({
|
||||
baseURL: getApiBaseUrl(),
|
||||
baseURL: import.meta.env.VITE_API_URL || '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
|
||||
@@ -13,7 +13,7 @@ interface AdminAuthContextType {
|
||||
error: string | null;
|
||||
mustChangePassword: boolean;
|
||||
updatePasswordChanged: () => void;
|
||||
updateProfile: (user: AdminUser) => void;
|
||||
updateUserProfile: (updates: Partial<AdminUser>) => void;
|
||||
}
|
||||
|
||||
const AdminAuthContext = createContext<AdminAuthContextType | undefined>(undefined);
|
||||
@@ -105,9 +105,15 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
}
|
||||
};
|
||||
|
||||
const updateProfile = (updatedUser: AdminUser) => {
|
||||
setUser(updatedUser);
|
||||
sessionStorage.setItem('admin_user', JSON.stringify(updatedUser));
|
||||
const updateUserProfile = (updates: Partial<AdminUser>) => {
|
||||
setUser((prev) => {
|
||||
if (!prev) {
|
||||
return prev;
|
||||
}
|
||||
const nextUser = { ...prev, ...updates };
|
||||
sessionStorage.setItem('admin_user', JSON.stringify(nextUser));
|
||||
return nextUser;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -121,7 +127,7 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
error,
|
||||
mustChangePassword,
|
||||
updatePasswordChanged,
|
||||
updateProfile,
|
||||
updateUserProfile,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -566,8 +566,8 @@
|
||||
"eventName": "Veranstaltungsname",
|
||||
"eventType": "Veranstaltungstyp",
|
||||
"eventDate": "Veranstaltungsdatum",
|
||||
"hostEmail": "Gastgeber-E-Mail",
|
||||
"hostName": "Name des Gastgebers",
|
||||
"hostEmail": "E-Mail des Kunden",
|
||||
"hostName": "Name des Kunden",
|
||||
"hostNamePlaceholder": "Max Mustermann",
|
||||
"adminEmail": "Admin-E-Mail",
|
||||
"expirationDate": "Ablaufdatum",
|
||||
@@ -589,8 +589,8 @@
|
||||
"eventExpired": "Diese Veranstaltung ist abgelaufen",
|
||||
"eventExpiresIn": "Diese Veranstaltung läuft in {{days}} Tagen ab",
|
||||
"guestsNoAccess": "Gäste können nicht mehr auf die Galerie zugreifen. Erwägen Sie, diese Veranstaltung zu archivieren.",
|
||||
"warningEmailsSent": "Warn-E-Mails wurden an den Gastgeber gesendet.",
|
||||
"warningEmailsHaveBeenSent": "Warn-E-Mails wurden an den Gastgeber gesendet.",
|
||||
"warningEmailsSent": "Warn-E-Mails wurden an den Kunden gesendet.",
|
||||
"warningEmailsHaveBeenSent": "Warn-E-Mails wurden an den Kunden gesendet.",
|
||||
"extendSevenDays": "Um 7 Tage verlängern",
|
||||
"overview": "Übersicht",
|
||||
"photos": "Fotos",
|
||||
@@ -631,7 +631,7 @@
|
||||
"organizeCategoriesInfo": "Organisieren Sie Ihre Fotos in Kategorien. Kategorien helfen Gästen, bestimmte Fototypen zu navigieren und zu finden.",
|
||||
"categoriesTip": "Tipp: Kategorien sind spezifisch für jede Veranstaltung. Sie können auch globale Kategorien in den Einstellungen erstellen.",
|
||||
"contactInformation": "Kontaktinformationen",
|
||||
"hostEmailHelp": "Erhält Benachrichtigungen zur Galerie-Erstellung und zum Ablauf",
|
||||
"hostEmailHelp": "Der Kunde erhält Benachrichtigungen zur Galerie-Erstellung und zum Ablauf",
|
||||
"adminEmailHelp": "Erhält Systembenachrichtigungen und Archivbestätigungen",
|
||||
"securityAccess": "Sicherheit & Zugriff",
|
||||
"galleryPassword": "Galerie-Passwort",
|
||||
@@ -686,7 +686,7 @@
|
||||
"eventNamePlaceholder": "z.B. Max & Maria's Hochzeit",
|
||||
"welcomeMessageOptional": "Willkommensnachricht (Optional)",
|
||||
"welcomeMessagePlaceholder": "Willkommen zu unserem besonderen Tag! Laden Sie diese Erinnerungen gerne herunter und teilen Sie sie...",
|
||||
"hostEmailPlaceholder": "gastgeber@beispiel.de",
|
||||
"hostEmailPlaceholder": "kunde@beispiel.de",
|
||||
"adminEmailPlaceholder": "admin@beispiel.de",
|
||||
"securityAndAccess": "Sicherheit & Zugriff",
|
||||
"accessAndSecurity": "Zugriff & Sicherheit",
|
||||
@@ -791,7 +791,18 @@
|
||||
"saveGeneralSettings": "Allgemeine Einstellungen speichern",
|
||||
"dateTimeFormat": "Datums- & Zeitformat",
|
||||
"dateFormat": "Datumsformat",
|
||||
"dateFormatHelp": "Wie Daten in E-Mails und in der gesamten Anwendung angezeigt werden"
|
||||
"dateFormatHelp": "Wie Daten in E-Mails und in der gesamten Anwendung angezeigt werden",
|
||||
"accountSection": "Admin-Konto",
|
||||
"accountUsername": "Admin-Benutzername",
|
||||
"accountUsernameHelp": "Wird im Admin-Bereich angezeigt und in Aktivitätsprotokollen verwendet.",
|
||||
"accountUsernameRequired": "Benutzername ist erforderlich",
|
||||
"accountUsernameLength": "Benutzername muss mindestens 3 Zeichen lang sein",
|
||||
"accountEmail": "Admin-E-Mail",
|
||||
"accountEmailHelp": "Wird für die Anmeldung und für Sicherheitsbenachrichtigungen verwendet.",
|
||||
"accountEmailRequired": "E-Mail-Adresse ist erforderlich",
|
||||
"accountEmailInvalid": "Bitte eine gültige E-Mail-Adresse eingeben",
|
||||
"accountSaveButton": "Kontodaten speichern",
|
||||
"accountSaveSuccess": "Kontodaten aktualisiert"
|
||||
},
|
||||
"publicSite": {
|
||||
"tabLabel": "Öffentliche Seite",
|
||||
@@ -1080,7 +1091,7 @@
|
||||
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
||||
"noNotifications": "Keine neuen Benachrichtigungen",
|
||||
"markAllRead": "Alle als gelesen markieren",
|
||||
"clearAll": "Alle löschen",
|
||||
"clearOld": "Alte löschen",
|
||||
"close": "Schließen",
|
||||
"noNotificationsMessage": "Keine Benachrichtigungen",
|
||||
"notificationMessages": {
|
||||
@@ -1113,13 +1124,11 @@
|
||||
"archiveDownloaded": "Archiv für \"{{eventName}}\" heruntergeladen",
|
||||
"archiveDeleted": "Archiv für \"{{eventName}}\" gelöscht",
|
||||
"archiveRestored": "Archiv für \"{{eventName}}\" wiederhergestellt",
|
||||
"systemActivity": "Systemaktivität: {{type}}",
|
||||
"adminProfileUpdated": "Admin-Profil aktualisiert von {{actorName}}"
|
||||
"systemActivity": "Systemaktivität: {{type}}"
|
||||
},
|
||||
"notificationToasts": {
|
||||
"markedAllRead": "Alle Benachrichtigungen als gelesen markiert",
|
||||
"clearedAll": "{{count}} Benachrichtigungen gelöscht",
|
||||
"profileUpdated": "Admin-Profil aktualisiert"
|
||||
"clearedOld": "{{count}} alte Benachrichtigungen gelöscht"
|
||||
},
|
||||
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
||||
"noNotifications": "Keine neuen Benachrichtigungen",
|
||||
@@ -1127,16 +1136,6 @@
|
||||
"markAllAsRead": "Alle als gelesen markieren",
|
||||
"notificationSettings": "Benachrichtigungseinstellungen",
|
||||
"changePassword": "Passwort ändern",
|
||||
"accountSettings": {
|
||||
"title": "Admin-Konto",
|
||||
"description": "Aktualisiere die Zugangsdaten für die PicPeak-Administration.",
|
||||
"username": "Benutzername",
|
||||
"usernamePlaceholder": "Admin",
|
||||
"email": "E-Mail",
|
||||
"emailPlaceholder": "admin@example.com",
|
||||
"updateButton": "Profil aktualisieren"
|
||||
},
|
||||
"profileUpdateError": "Admin-Profil konnte nicht aktualisiert werden. Bitte versuche es erneut.",
|
||||
"loadingDashboard": "Dashboard wird geladen...",
|
||||
"activeEvents": "Aktive Veranstaltungen",
|
||||
"expiringSoon": "Demnächst ablaufend",
|
||||
@@ -1362,8 +1361,8 @@
|
||||
},
|
||||
"validation": {
|
||||
"eventNameRequired": "Veranstaltungsname ist erforderlich",
|
||||
"hostEmailRequired": "Gastgeber-E-Mail ist erforderlich",
|
||||
"hostNameRequired": "Der Name des Gastgebers ist erforderlich",
|
||||
"hostEmailRequired": "Die E-Mail des Kunden ist erforderlich",
|
||||
"hostNameRequired": "Der Name des Kunden ist erforderlich",
|
||||
"adminEmailRequired": "Admin-E-Mail ist erforderlich",
|
||||
"invalidEmailFormat": "Ungültiges E-Mail-Format",
|
||||
"passwordRequired": "Passwort ist erforderlich",
|
||||
|
||||
@@ -225,7 +225,7 @@
|
||||
"eventNamePlaceholder": "e.g., John & Jane's Wedding",
|
||||
"welcomeMessageOptional": "Welcome Message (Optional)",
|
||||
"welcomeMessagePlaceholder": "Welcome to our special day! Feel free to download and share these memories...",
|
||||
"hostEmailPlaceholder": "host@example.com",
|
||||
"hostEmailPlaceholder": "customer@example.com",
|
||||
"adminEmailPlaceholder": "admin@example.com",
|
||||
"securityAndAccess": "Security & Access",
|
||||
"accessAndSecurity": "Access & Security",
|
||||
@@ -251,8 +251,8 @@
|
||||
"eventName": "Event Name",
|
||||
"eventType": "Event Type",
|
||||
"eventDate": "Event Date",
|
||||
"hostEmail": "Host Email",
|
||||
"hostName": "Host Name",
|
||||
"hostEmail": "Customer Email",
|
||||
"hostName": "Customer Name",
|
||||
"hostNamePlaceholder": "John Smith",
|
||||
"adminEmail": "Admin Email",
|
||||
"adminNotificationEmail": "Admin Notification Email",
|
||||
@@ -275,7 +275,7 @@
|
||||
"eventExpired": "This event has expired",
|
||||
"eventExpiresIn": "This event expires in {{days}} days",
|
||||
"guestsNoAccess": "Guests can no longer access the gallery. Consider archiving this event.",
|
||||
"warningEmailsSent": "Warning emails have been sent to the host.",
|
||||
"warningEmailsSent": "Warning emails have been sent to the customer.",
|
||||
"overview": "Overview",
|
||||
"photos": "Photos",
|
||||
"categories": "Categories",
|
||||
@@ -315,7 +315,7 @@
|
||||
"organizeCategoriesInfo": "Organize your photos into categories. Categories help guests navigate and find specific types of photos.",
|
||||
"categoriesTip": "Tip: Categories are specific to each event. You can also create global categories in Settings.",
|
||||
"contactInformation": "Contact Information",
|
||||
"hostEmailHelp": "Will receive gallery creation and expiration notifications",
|
||||
"hostEmailHelp": "Customer will receive gallery creation and expiration notifications",
|
||||
"adminEmailHelp": "Will receive system notifications and archive confirmations",
|
||||
"securityAccess": "Security & Access",
|
||||
"galleryPassword": "Gallery Password",
|
||||
@@ -406,13 +406,13 @@
|
||||
"tryAgain": "Try Again",
|
||||
"eventExpiredMessage": "This event has expired",
|
||||
"guestsCannotAccessGallery": "Guests can no longer access the gallery. Consider archiving this event.",
|
||||
"warningEmailsHaveBeenSent": "Warning emails have been sent to the host.",
|
||||
"warningEmailsHaveBeenSent": "Warning emails have been sent to the customer.",
|
||||
"extendSevenDays": "Extend 7 Days",
|
||||
"overview": "Overview",
|
||||
"eventInformation": "Event Information",
|
||||
"welcomeMessageLabel": "Welcome Message",
|
||||
"noWelcomeMessageSet": "No welcome message set",
|
||||
"hostEmail": "Host Email",
|
||||
"hostEmail": "Customer Email",
|
||||
"adminEmail": "Admin Email",
|
||||
"createdOn": "Created",
|
||||
"expires": "Expires",
|
||||
@@ -471,7 +471,18 @@
|
||||
"saveGeneralSettings": "Save General Settings",
|
||||
"dateTimeFormat": "Date & Time Format",
|
||||
"dateFormat": "Date Format",
|
||||
"dateFormatHelp": "How dates are displayed in emails and throughout the application"
|
||||
"dateFormatHelp": "How dates are displayed in emails and throughout the application",
|
||||
"accountSection": "Admin Account",
|
||||
"accountUsername": "Admin Username",
|
||||
"accountUsernameHelp": "Displayed in the admin interface and used in activity logs.",
|
||||
"accountUsernameRequired": "Username is required",
|
||||
"accountUsernameLength": "Username must be at least 3 characters",
|
||||
"accountEmail": "Admin Email",
|
||||
"accountEmailHelp": "Used for login and receiving security notifications.",
|
||||
"accountEmailRequired": "Email address is required",
|
||||
"accountEmailInvalid": "Enter a valid email address",
|
||||
"accountSaveButton": "Save account details",
|
||||
"accountSaveSuccess": "Account details updated"
|
||||
},
|
||||
"publicSite": {
|
||||
"tabLabel": "Public Site",
|
||||
@@ -818,7 +829,7 @@
|
||||
"viewAllNotifications": "View all notifications",
|
||||
"noNotifications": "No new notifications",
|
||||
"markAllRead": "Mark all read",
|
||||
"clearAll": "Clear all",
|
||||
"clearOld": "Clear old",
|
||||
"close": "Close",
|
||||
"noNotificationsMessage": "No notifications",
|
||||
"notificationMessages": {
|
||||
@@ -851,28 +862,16 @@
|
||||
"archiveDownloaded": "Archive downloaded for \"{{eventName}}\"",
|
||||
"archiveDeleted": "Archive deleted for \"{{eventName}}\"",
|
||||
"archiveRestored": "Archive restored for \"{{eventName}}\"",
|
||||
"systemActivity": "System activity: {{type}}",
|
||||
"adminProfileUpdated": "Admin profile updated by {{actorName}}"
|
||||
"systemActivity": "System activity: {{type}}"
|
||||
},
|
||||
"notificationToasts": {
|
||||
"markedAllRead": "All notifications marked as read",
|
||||
"clearedAll": "Cleared {{count}} notifications",
|
||||
"profileUpdated": "Admin profile updated"
|
||||
"clearedOld": "Cleared {{count}} old notifications"
|
||||
},
|
||||
"markAsRead": "Mark as read",
|
||||
"markAllAsRead": "Mark all as read",
|
||||
"notificationSettings": "Notification Settings",
|
||||
"changePassword": "Change Password",
|
||||
"accountSettings": {
|
||||
"title": "Admin account",
|
||||
"description": "Update the credentials used to sign in to PicPeak.",
|
||||
"username": "Username",
|
||||
"usernamePlaceholder": "Admin",
|
||||
"email": "Email",
|
||||
"emailPlaceholder": "admin@example.com",
|
||||
"updateButton": "Update profile"
|
||||
},
|
||||
"profileUpdateError": "Unable to update admin profile. Please try again.",
|
||||
"loadingDashboard": "Loading dashboard...",
|
||||
"activeEvents": "Active Events",
|
||||
"expiringSoon": "Expiring Soon",
|
||||
@@ -967,8 +966,8 @@
|
||||
},
|
||||
"validation": {
|
||||
"eventNameRequired": "Event name is required",
|
||||
"hostEmailRequired": "Host email is required",
|
||||
"hostNameRequired": "Host name is required",
|
||||
"hostEmailRequired": "Customer email is required",
|
||||
"hostNameRequired": "Customer name is required",
|
||||
"adminEmailRequired": "Admin email is required",
|
||||
"invalidEmailFormat": "Invalid email format",
|
||||
"passwordRequired": "Password is required",
|
||||
|
||||
@@ -388,7 +388,7 @@ export const CreateEventPage: React.FC = () => {
|
||||
<h2 className="text-lg font-semibold text-neutral-900 mb-4">{t('events.contactInformation')}</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Host Email */}
|
||||
{/* Customer Email */}
|
||||
<div>
|
||||
<label htmlFor="host_email" className="block text-sm font-medium text-neutral-700 mb-1">
|
||||
{t('events.hostEmail')}
|
||||
|
||||
@@ -236,28 +236,6 @@ export const EventDetailsPage: React.FC = () => {
|
||||
},
|
||||
});
|
||||
|
||||
const applyThemeMutation = useMutation({
|
||||
mutationFn: async ({ theme, presetName }: { theme: ThemeConfig; presetName: string }) => {
|
||||
if (!id) {
|
||||
throw new Error('Missing event identifier');
|
||||
}
|
||||
|
||||
const colorThemeValue = presetName && presetName !== 'custom'
|
||||
? presetName
|
||||
: JSON.stringify(theme);
|
||||
|
||||
return eventsService.updateEvent(parseInt(id), { color_theme: colorThemeValue });
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-event', id] });
|
||||
toast.success(t('branding.themeApplied', 'Theme updated'));
|
||||
},
|
||||
onError: (error: any) => {
|
||||
const message = error?.response?.data?.error || t('branding.themeApplyError', 'Failed to apply theme');
|
||||
toast.error(message);
|
||||
}
|
||||
});
|
||||
|
||||
// Archive mutation
|
||||
const archiveMutation = useMutation({
|
||||
mutationFn: () => eventsService.archiveEvent(parseInt(id!)),
|
||||
@@ -1146,20 +1124,6 @@ export const EventDetailsPage: React.FC = () => {
|
||||
}}
|
||||
isPreviewMode={false}
|
||||
showGalleryLayouts={true}
|
||||
onApply={async (theme, { presetName }) => {
|
||||
const resolvedPreset = presetName || 'custom';
|
||||
setCurrentTheme(theme);
|
||||
setCurrentPresetName(resolvedPreset);
|
||||
|
||||
const themeValue = resolvedPreset !== 'custom'
|
||||
? resolvedPreset
|
||||
: JSON.stringify(theme);
|
||||
|
||||
setEditForm(prev => ({ ...prev, color_theme: themeValue }));
|
||||
|
||||
await applyThemeMutation.mutateAsync({ theme, presetName: resolvedPreset });
|
||||
}}
|
||||
isApplying={applyThemeMutation.isPending}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Save,
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Save,
|
||||
Database,
|
||||
Globe,
|
||||
Key,
|
||||
@@ -10,7 +10,9 @@ import {
|
||||
CheckCircle,
|
||||
Clock,
|
||||
HardDrive,
|
||||
Activity
|
||||
Activity,
|
||||
Mail,
|
||||
User
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
@@ -19,7 +21,7 @@ import { CategoryManager } from '../../components/admin/CategoryManager';
|
||||
import { WordFilterManager } from '../../components/admin/WordFilterManager';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { settingsService } from '../../services/settings.service';
|
||||
import { authService } from '../../services/auth.service';
|
||||
import { adminService } from '../../services/admin.service';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAdminAuth } from '../../contexts';
|
||||
|
||||
@@ -58,23 +60,7 @@ export const SettingsPage: React.FC = () => {
|
||||
const [activeTab, setActiveTab] = useState<'general' | 'status' | 'security' | 'categories' | 'analytics' | 'moderation'>('general');
|
||||
const queryClient = useQueryClient();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { user, updateProfile: updateAuthProfile } = useAdminAuth();
|
||||
|
||||
const [profileForm, setProfileForm] = useState({
|
||||
username: user?.username ?? '',
|
||||
email: user?.email ?? '',
|
||||
});
|
||||
const [profileError, setProfileError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setProfileForm({ username: user.username, email: user.email });
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const isProfileDirty = user
|
||||
? (profileForm.username !== user.username || profileForm.email !== user.email)
|
||||
: Boolean(profileForm.username.trim() || profileForm.email.trim());
|
||||
const { updateUserProfile } = useAdminAuth();
|
||||
|
||||
// Fetch settings
|
||||
const { data: settings, isLoading } = useQuery({
|
||||
@@ -82,6 +68,11 @@ export const SettingsPage: React.FC = () => {
|
||||
queryFn: () => settingsService.getAllSettings(),
|
||||
});
|
||||
|
||||
const { data: adminProfile, isLoading: adminProfileLoading } = useQuery({
|
||||
queryKey: ['admin-profile'],
|
||||
queryFn: () => adminService.getAdminProfile(),
|
||||
});
|
||||
|
||||
// Fetch storage info
|
||||
const { data: storageInfo } = useQuery({
|
||||
queryKey: ['admin-storage-info'],
|
||||
@@ -97,20 +88,6 @@ export const SettingsPage: React.FC = () => {
|
||||
refetchInterval: 30000 // Refresh every 30 seconds
|
||||
});
|
||||
|
||||
const updateProfileMutation = useMutation({
|
||||
mutationFn: authService.updateAdminProfile,
|
||||
onSuccess: (updatedUser) => {
|
||||
updateAuthProfile(updatedUser);
|
||||
setProfileError(null);
|
||||
toast.success(t('admin.notificationToasts.profileUpdated'));
|
||||
},
|
||||
onError: (error: any) => {
|
||||
const message = error?.response?.data?.error || t('admin.profileUpdateError');
|
||||
setProfileError(message);
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
|
||||
// General settings state
|
||||
const [generalSettings, setGeneralSettings] = useState({
|
||||
site_url: '',
|
||||
@@ -150,6 +127,11 @@ export const SettingsPage: React.FC = () => {
|
||||
const [capacityOverrideGb, setCapacityOverrideGb] = useState<number | ''>('');
|
||||
const [availableOverrideGb, setAvailableOverrideGb] = useState<number | ''>('');
|
||||
const [overrideDirty, setOverrideDirty] = useState(false);
|
||||
const [accountForm, setAccountForm] = useState({
|
||||
username: '',
|
||||
email: ''
|
||||
});
|
||||
const [accountErrors, setAccountErrors] = useState<Record<string, string>>({});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (settings) {
|
||||
@@ -198,6 +180,15 @@ export const SettingsPage: React.FC = () => {
|
||||
}
|
||||
}, [settings, i18n]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (adminProfile) {
|
||||
setAccountForm({
|
||||
username: adminProfile.username || '',
|
||||
email: adminProfile.email || ''
|
||||
});
|
||||
}
|
||||
}, [adminProfile]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!settings || overrideDirty) {
|
||||
return;
|
||||
@@ -318,6 +309,83 @@ export const SettingsPage: React.FC = () => {
|
||||
}
|
||||
});
|
||||
|
||||
const updateAdminProfileMutation = useMutation({
|
||||
mutationFn: (payload: { username: string; email: string }) => adminService.updateAdminProfile(payload),
|
||||
onSuccess: (updatedUser) => {
|
||||
toast.success(t('settings.general.accountSaveSuccess'));
|
||||
setAccountErrors({});
|
||||
setAccountForm({
|
||||
username: updatedUser.username,
|
||||
email: updatedUser.email
|
||||
});
|
||||
updateUserProfile(updatedUser);
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-profile'] });
|
||||
},
|
||||
onError: (error: any) => {
|
||||
if (error.response?.data?.errors) {
|
||||
const fieldErrors: Record<string, string> = {};
|
||||
for (const err of error.response.data.errors) {
|
||||
if (err.path === 'username') {
|
||||
fieldErrors.username = err.msg;
|
||||
}
|
||||
if (err.path === 'email') {
|
||||
fieldErrors.email = err.msg;
|
||||
}
|
||||
}
|
||||
setAccountErrors(fieldErrors);
|
||||
return;
|
||||
}
|
||||
|
||||
if (error.response?.data?.error) {
|
||||
toast.error(error.response.data.error);
|
||||
} else {
|
||||
toast.error(t('toast.saveError'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const handleAccountChange = (field: 'username' | 'email') => (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = event.target.value;
|
||||
setAccountForm((prev) => ({ ...prev, [field]: value }));
|
||||
if (accountErrors[field]) {
|
||||
setAccountErrors((prev) => ({ ...prev, [field]: '' }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleAccountSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (updateAdminProfileMutation.isPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
const trimmedUsername = accountForm.username.trim();
|
||||
const trimmedEmail = accountForm.email.trim();
|
||||
const errors: Record<string, string> = {};
|
||||
|
||||
if (!trimmedUsername) {
|
||||
errors.username = t('settings.general.accountUsernameRequired');
|
||||
} else if (trimmedUsername.length < 3) {
|
||||
errors.username = t('settings.general.accountUsernameLength');
|
||||
}
|
||||
|
||||
if (!trimmedEmail) {
|
||||
errors.email = t('settings.general.accountEmailRequired');
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedEmail)) {
|
||||
errors.email = t('settings.general.accountEmailInvalid');
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
setAccountErrors(errors);
|
||||
return;
|
||||
}
|
||||
|
||||
updateAdminProfileMutation.mutate({
|
||||
username: trimmedUsername,
|
||||
email: trimmedEmail
|
||||
});
|
||||
};
|
||||
|
||||
const saveSoftLimitMutation = useMutation({
|
||||
mutationFn: async (limitBytes: number | null) => {
|
||||
return settingsService.updateSettings({
|
||||
@@ -376,19 +444,6 @@ export const SettingsPage: React.FC = () => {
|
||||
}
|
||||
});
|
||||
|
||||
const handleProfileSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!isProfileDirty || updateProfileMutation.isPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
setProfileError(null);
|
||||
updateProfileMutation.mutate({
|
||||
username: profileForm.username.trim(),
|
||||
email: profileForm.email.trim(),
|
||||
});
|
||||
};
|
||||
|
||||
const handleSaveCapacityOverride = () => {
|
||||
if (saveCapacityOverrideMutation.isPending) {
|
||||
return;
|
||||
@@ -513,43 +568,61 @@ export const SettingsPage: React.FC = () => {
|
||||
{activeTab === 'general' && (
|
||||
<div className="space-y-6">
|
||||
<Card padding="md">
|
||||
<h2 className="text-lg font-semibold text-neutral-900 mb-2">{t('admin.accountSettings.title')}</h2>
|
||||
<p className="text-sm text-neutral-500 mb-4">{t('admin.accountSettings.description')}</p>
|
||||
<form className="space-y-4" onSubmit={handleProfileSubmit}>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-neutral-700 mb-1">
|
||||
{t('admin.accountSettings.username')}
|
||||
</label>
|
||||
<Input
|
||||
value={profileForm.username}
|
||||
onChange={(e) => setProfileForm(prev => ({ ...prev, username: e.target.value }))}
|
||||
placeholder={t('admin.accountSettings.usernamePlaceholder')}
|
||||
maxLength={120}
|
||||
/>
|
||||
<h2 className="text-lg font-semibold text-neutral-900 mb-4">{t('settings.general.accountSection')}</h2>
|
||||
{adminProfileLoading ? (
|
||||
<div className="py-8 flex justify-center">
|
||||
<Loading size="md" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-neutral-700 mb-1">
|
||||
{t('admin.accountSettings.email')}
|
||||
</label>
|
||||
<Input
|
||||
type="email"
|
||||
value={profileForm.email}
|
||||
onChange={(e) => setProfileForm(prev => ({ ...prev, email: e.target.value }))}
|
||||
placeholder={t('admin.accountSettings.emailPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
{profileError && (
|
||||
<p className="text-sm text-red-600">{profileError}</p>
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!isProfileDirty || updateProfileMutation.isPending}
|
||||
>
|
||||
{updateProfileMutation.isPending ? t('common.saving') : t('admin.accountSettings.updateButton')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<form className="space-y-4" onSubmit={handleAccountSubmit}>
|
||||
<div>
|
||||
<label htmlFor="admin-account-username" className="block text-sm font-medium text-neutral-700 mb-1">
|
||||
{t('settings.general.accountUsername')}
|
||||
</label>
|
||||
<Input
|
||||
id="admin-account-username"
|
||||
type="text"
|
||||
value={accountForm.username}
|
||||
onChange={handleAccountChange('username')}
|
||||
placeholder="admin"
|
||||
leftIcon={<User className="w-5 h-5 text-neutral-400" />}
|
||||
error={accountErrors.username}
|
||||
/>
|
||||
<p className="text-xs text-neutral-500 mt-1">
|
||||
{t('settings.general.accountUsernameHelp')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="admin-account-email" className="block text-sm font-medium text-neutral-700 mb-1">
|
||||
{t('settings.general.accountEmail')}
|
||||
</label>
|
||||
<Input
|
||||
id="admin-account-email"
|
||||
type="email"
|
||||
value={accountForm.email}
|
||||
onChange={handleAccountChange('email')}
|
||||
placeholder="admin@example.com"
|
||||
leftIcon={<Mail className="w-5 h-5 text-neutral-400" />}
|
||||
error={accountErrors.email}
|
||||
/>
|
||||
<p className="text-xs text-neutral-500 mt-1">
|
||||
{t('settings.general.accountEmailHelp')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
leftIcon={<Save className="w-5 h-5" />}
|
||||
isLoading={updateAdminProfileMutation.isPending}
|
||||
>
|
||||
{t('settings.general.accountSaveButton')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card padding="md">
|
||||
|
||||
@@ -47,6 +47,17 @@ export interface Activity {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface AdminProfile {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
mustChangePassword?: boolean;
|
||||
last_login?: string | null;
|
||||
last_login_ip?: string | null;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface AnalyticsData {
|
||||
chartData: Array<{
|
||||
date: string;
|
||||
@@ -130,5 +141,15 @@ export const adminService = {
|
||||
// Change password
|
||||
async changePassword(data: { currentPassword: string; newPassword: string }): Promise<void> {
|
||||
await api.post('/admin/auth/change-password', data);
|
||||
},
|
||||
|
||||
async getAdminProfile(): Promise<AdminProfile> {
|
||||
const response = await api.get<AdminProfile>('/admin/auth/profile');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
async updateAdminProfile(data: { username: string; email: string }): Promise<AdminProfile> {
|
||||
const response = await api.put<{ user: AdminProfile }>('/admin/auth/profile', data);
|
||||
return response.data.user;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { api } from '../config/api';
|
||||
import type { LoginResponse, GalleryAuthResponse, AdminUser } from '../types';
|
||||
import type { LoginResponse, GalleryAuthResponse } from '../types';
|
||||
import { normalizeRequirePassword } from '../utils/accessControl';
|
||||
|
||||
const normalizeGalleryResponse = (response: GalleryAuthResponse): GalleryAuthResponse => ({
|
||||
@@ -61,9 +61,4 @@ export const authService = {
|
||||
// Ignore; cookie will naturally expire if removal fails
|
||||
}
|
||||
},
|
||||
|
||||
async updateAdminProfile(profile: { username: string; email: string }): Promise<AdminUser> {
|
||||
const response = await api.put<{ user: AdminUser }>('/auth/admin/profile', profile);
|
||||
return response.data.user;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -38,9 +38,9 @@ export const notificationsService = {
|
||||
await api.put('/admin/notifications/read-all');
|
||||
},
|
||||
|
||||
// Clear all notifications
|
||||
async clearAllNotifications(): Promise<{ deletedCount: number }> {
|
||||
const response = await api.delete('/admin/notifications/clear-all');
|
||||
// Clear old notifications
|
||||
async clearOldNotifications(): Promise<{ deletedCount: number }> {
|
||||
const response = await api.delete('/admin/notifications/clear-old');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
@@ -133,10 +133,6 @@ export const notificationsService = {
|
||||
return t('admin.notificationMessages.generalSettingsUpdated');
|
||||
case 'security_settings_updated':
|
||||
return t('admin.notificationMessages.securitySettingsUpdated');
|
||||
case 'admin_profile_updated':
|
||||
return t('admin.notificationMessages.adminProfileUpdated', {
|
||||
actorName: notification.actorName,
|
||||
});
|
||||
case 'theme_updated':
|
||||
return t('admin.notificationMessages.themeUpdated');
|
||||
case 'archive_downloaded':
|
||||
@@ -188,8 +184,6 @@ export const notificationsService = {
|
||||
case 'security_settings_updated':
|
||||
case 'theme_updated':
|
||||
return { icon: 'Settings', color: 'text-gray-600' };
|
||||
case 'admin_profile_updated':
|
||||
return { icon: 'User', color: 'text-primary-600' };
|
||||
case 'email_template_updated':
|
||||
case 'email_config_updated':
|
||||
return { icon: 'Mail', color: 'text-teal-600' };
|
||||
@@ -215,4 +209,4 @@ export const notificationsService = {
|
||||
return { icon: 'Bell', color: 'text-gray-600' };
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,58 +0,0 @@
|
||||
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { getApiBaseUrl, buildResourceUrl } from '../url';
|
||||
const originalLocation = window.location;
|
||||
|
||||
const setLocation = (origin: string) => {
|
||||
const parsed = new URL(origin);
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: {
|
||||
origin: parsed.origin,
|
||||
hostname: parsed.hostname,
|
||||
href: parsed.href,
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
};
|
||||
|
||||
describe('url utilities', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
setLocation('https://example.com');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: originalLocation,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns relative API base by default', () => {
|
||||
vi.unstubAllEnvs();
|
||||
expect(getApiBaseUrl()).toBe('/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('https://example.com/api/gallery/test');
|
||||
});
|
||||
|
||||
it('honours absolute API URLs for non-local hosts', () => {
|
||||
vi.stubEnv('VITE_API_URL', 'https://api.picpeak.cloud/api');
|
||||
expect(getApiBaseUrl()).toBe('https://api.picpeak.cloud/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('https://api.picpeak.cloud/api/gallery/test');
|
||||
expect(buildResourceUrl('/uploads/logo.png')).toBe('https://api.picpeak.cloud/uploads/logo.png');
|
||||
});
|
||||
|
||||
it('falls back to relative when build-time URL is localhost but browser host is remote', () => {
|
||||
vi.stubEnv('VITE_API_URL', 'http://localhost:3001/api');
|
||||
setLocation('https://photos.example.com');
|
||||
expect(getApiBaseUrl()).toBe('/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('https://photos.example.com/api/gallery/test');
|
||||
expect(buildResourceUrl('uploads/logo.png')).toBe('https://photos.example.com/uploads/logo.png');
|
||||
});
|
||||
|
||||
it('keeps localhost API URL when browser is also localhost', () => {
|
||||
vi.stubEnv('VITE_API_URL', 'http://127.0.0.1:3001/api');
|
||||
setLocation('http://127.0.0.1:3000');
|
||||
expect(getApiBaseUrl()).toBe('http://127.0.0.1:3001/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('http://127.0.0.1:3001/api/gallery/test');
|
||||
});
|
||||
});
|
||||
+20
-108
@@ -2,126 +2,39 @@
|
||||
* Utility functions for URL handling in production environments
|
||||
*/
|
||||
|
||||
const ABSOLUTE_URL_REGEX = /^https?:\/\//i;
|
||||
const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);
|
||||
|
||||
const isBrowser = typeof window !== 'undefined' && typeof window.location !== 'undefined';
|
||||
|
||||
const normalizeBase = (value: string): string => value.replace(/\/+$/, '');
|
||||
|
||||
const getEnvApiUrl = (): string | undefined => {
|
||||
const raw = import.meta.env?.VITE_API_URL;
|
||||
if (!raw || raw === '') {
|
||||
return undefined;
|
||||
}
|
||||
if (raw === '/') {
|
||||
return '/api';
|
||||
}
|
||||
return raw;
|
||||
};
|
||||
|
||||
const isLocalHostname = (hostname: string): boolean => LOCAL_HOSTNAMES.has(hostname.toLowerCase());
|
||||
|
||||
const shouldFallbackToRelative = (url: string): boolean => {
|
||||
if (!ABSOLUTE_URL_REGEX.test(url)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isBrowser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const envHostIsLocal = isLocalHostname(parsed.hostname);
|
||||
const browserHost = window.location.hostname?.toLowerCase?.() ?? '';
|
||||
const browserHostIsLocal = isLocalHostname(browserHost);
|
||||
|
||||
// Only fallback when the build-time URL points to localhost/loopback
|
||||
// but the runtime browser location is remote (non-local).
|
||||
return envHostIsLocal && !browserHostIsLocal;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const buildFromOrigin = (path: string): string => {
|
||||
if (!isBrowser) {
|
||||
return path;
|
||||
}
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
return `${window.location.origin}${normalizedPath}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the base API URL, preferring relative URLs for production and
|
||||
* falling back to relative when the build was created with localhost
|
||||
* endpoints but is being accessed from a remote browser.
|
||||
* Get the base API URL, preferring relative URLs for production
|
||||
* @returns The API base URL
|
||||
*/
|
||||
export const getApiBaseUrl = (): string => {
|
||||
const envUrl = getEnvApiUrl();
|
||||
|
||||
if (envUrl && envUrl !== '/api') {
|
||||
if (ABSOLUTE_URL_REGEX.test(envUrl) && shouldFallbackToRelative(envUrl)) {
|
||||
return '/api';
|
||||
}
|
||||
return envUrl;
|
||||
// If VITE_API_URL is explicitly set, use it
|
||||
if (import.meta.env.VITE_API_URL && import.meta.env.VITE_API_URL !== '/api') {
|
||||
return import.meta.env.VITE_API_URL;
|
||||
}
|
||||
|
||||
|
||||
// In production, use relative URL
|
||||
return '/api';
|
||||
};
|
||||
|
||||
const buildFromAbsoluteApi = (base: string, path: string): string => {
|
||||
const trimmedBase = normalizeBase(base);
|
||||
|
||||
// When the path already targets /api we want to preserve the suffix
|
||||
if (path.startsWith('/api')) {
|
||||
const pathWithoutLeadingApi = path.replace(/^\/api/, '');
|
||||
return `${trimmedBase}${pathWithoutLeadingApi}`;
|
||||
}
|
||||
|
||||
// For non-API assets (uploads, thumbnails, etc.) drop any /api suffix
|
||||
const origin = trimmedBase.replace(/\/api$/, '');
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
return `${origin}${normalizedPath}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a full URL for resources (images, files, etc.)
|
||||
* In production, this will prefer the current origin unless an absolute
|
||||
* API URL is explicitly configured and applicable.
|
||||
* In production, this will use the current origin
|
||||
* @param path - The resource path
|
||||
* @returns The full URL
|
||||
*/
|
||||
export const buildResourceUrl = (path: string): string => {
|
||||
if (!path) {
|
||||
return '';
|
||||
// Remove leading slash if present
|
||||
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
|
||||
|
||||
// If we have an explicit API URL that's not relative, use it
|
||||
const apiUrl = import.meta.env.VITE_API_URL;
|
||||
if (apiUrl && apiUrl !== '/api' && apiUrl.startsWith('http')) {
|
||||
const baseUrl = apiUrl.replace(/\/api\/?$/, ''); // Remove /api suffix if present
|
||||
return `${baseUrl}/${cleanPath}`;
|
||||
}
|
||||
|
||||
// Absolute paths (http/https) should generally be respected,
|
||||
// except when they point to localhost but we're running remotely.
|
||||
if (ABSOLUTE_URL_REGEX.test(path)) {
|
||||
if (!shouldFallbackToRelative(path)) {
|
||||
return path;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(path);
|
||||
return buildFromOrigin(`${parsed.pathname}${parsed.search}${parsed.hash}`);
|
||||
} catch {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
const apiBase = getApiBaseUrl();
|
||||
|
||||
if (ABSOLUTE_URL_REGEX.test(apiBase)) {
|
||||
return buildFromAbsoluteApi(apiBase, normalizedPath);
|
||||
}
|
||||
|
||||
return buildFromOrigin(normalizedPath);
|
||||
|
||||
// In production (relative API), use current origin
|
||||
return `${window.location.origin}/${cleanPath}`;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -129,6 +42,5 @@ export const buildResourceUrl = (path: string): string => {
|
||||
* @returns True if in production mode
|
||||
*/
|
||||
export const isProductionMode = (): boolean => {
|
||||
const apiBase = getApiBaseUrl();
|
||||
return !ABSOLUTE_URL_REGEX.test(apiBase);
|
||||
};
|
||||
return !import.meta.env.VITE_API_URL || import.meta.env.VITE_API_URL === '/api';
|
||||
};
|
||||
Vendored
-1
@@ -1,2 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vitest" />
|
||||
|
||||
+3
-14
@@ -1,12 +1,8 @@
|
||||
/// <reference types="vitest" />
|
||||
// @ts-nocheck
|
||||
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import type { UserConfig as VitestUserConfig } from 'vitest/config'
|
||||
|
||||
// https://vite.dev/config/
|
||||
const config: VitestUserConfig = {
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
rollupOptions: {
|
||||
@@ -19,11 +15,6 @@ const config: VitestUserConfig = {
|
||||
},
|
||||
sourcemap: true,
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
setupFiles: './vitest.setup.ts',
|
||||
globals: true
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
host: true,
|
||||
@@ -37,7 +28,5 @@ const config: VitestUserConfig = {
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default defineConfig(config as any)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { expect, vi } from 'vitest';
|
||||
import * as matchers from '@testing-library/jest-dom/matchers';
|
||||
|
||||
expect.extend(matchers);
|
||||
|
||||
// Provide Jest-compatible globals for existing tests that rely on jest.fn
|
||||
(globalThis as any).jest = vi;
|
||||
+24
-33
@@ -64,17 +64,19 @@ FORCE_ADMIN_PASSWORD_RESET=false
|
||||
# Run a command as the application user, even if sudo is not available
|
||||
run_as_user() {
|
||||
local cmd="$*"
|
||||
local current_dir_escaped
|
||||
current_dir_escaped=$(printf '%q' "$(pwd)")
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
# Already non-root; just run
|
||||
bash -lc "$cmd"
|
||||
# Already non-root; preserve working directory
|
||||
bash -lc "cd $current_dir_escaped && $cmd"
|
||||
return $?
|
||||
fi
|
||||
if command_exists sudo; then
|
||||
sudo -H -u "$NATIVE_APP_USER" bash -lc "$cmd"
|
||||
sudo -H -u "$NATIVE_APP_USER" bash -lc "cd $current_dir_escaped && $cmd"
|
||||
elif command_exists runuser; then
|
||||
runuser -u "$NATIVE_APP_USER" -- bash -lc "$cmd"
|
||||
runuser -u "$NATIVE_APP_USER" -- bash -lc "cd $current_dir_escaped && $cmd"
|
||||
else
|
||||
su -s /bin/bash - "$NATIVE_APP_USER" -c "$cmd"
|
||||
su -s /bin/bash - "$NATIVE_APP_USER" -c "cd $current_dir_escaped && $cmd"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -383,27 +385,17 @@ setup_docker_installation() {
|
||||
app_dir="/home/$SUDO_USER/picpeak"
|
||||
fi
|
||||
|
||||
log_step "Preparing application directory at $app_dir"
|
||||
local app_parent_dir
|
||||
app_parent_dir=$(dirname "$app_dir")
|
||||
mkdir -p "$app_parent_dir"
|
||||
|
||||
log_step "Creating application directory at $app_dir"
|
||||
mkdir -p "$app_dir"/{storage/events/{active,archived},logs,backup,config,data,events}
|
||||
|
||||
# Clone repository
|
||||
log_step "Downloading PicPeak..."
|
||||
if [[ -d "$app_dir/.git" ]]; then
|
||||
log_step "Existing PicPeak repository detected; pulling latest changes"
|
||||
cd "$app_dir"
|
||||
git pull --rebase --autostash || git pull
|
||||
git pull
|
||||
else
|
||||
if [[ -d "$app_dir" && -n "$(find "$app_dir" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ]]; then
|
||||
die "Target directory $app_dir already exists and is not empty. Remove it or specify --install-dir before retrying."
|
||||
fi
|
||||
|
||||
log_step "Cloning PicPeak..."
|
||||
rm -rf "$app_dir"
|
||||
git clone "$REPO_URL" "$app_dir"
|
||||
fi
|
||||
|
||||
# Ensure storage layout exists after cloning
|
||||
mkdir -p "$app_dir"/{storage/events/{active,archived},logs,backup,config,data,events}
|
||||
|
||||
# Determine host user for container mapping (PUID/PGID)
|
||||
local host_uid host_gid
|
||||
@@ -639,14 +631,17 @@ setup_native_installation() {
|
||||
apt)
|
||||
apt-get install -y build-essential python3
|
||||
;;
|
||||
dnf|yum)
|
||||
if "$PACKAGE_MANAGER" --version 2>/dev/null | grep -Ei 'dnf( |-)5' >/dev/null; then
|
||||
$PACKAGE_MANAGER install -y @development-tools
|
||||
else
|
||||
dnf)
|
||||
if ! $PACKAGE_MANAGER install -y @development-tools; then
|
||||
log_warn "dnf @development-tools group install failed, retrying with legacy groupinstall syntax..."
|
||||
$PACKAGE_MANAGER groupinstall -y "Development Tools"
|
||||
fi
|
||||
$PACKAGE_MANAGER install -y python3
|
||||
;;
|
||||
yum)
|
||||
$PACKAGE_MANAGER groupinstall -y "Development Tools"
|
||||
$PACKAGE_MANAGER install -y python3
|
||||
;;
|
||||
esac
|
||||
|
||||
# Create system user
|
||||
@@ -967,15 +962,17 @@ configure_email() {
|
||||
}
|
||||
|
||||
print_success_message() {
|
||||
local app_dir port
|
||||
local app_dir port manual_reset_hint
|
||||
|
||||
if [[ "$INSTALL_METHOD" == "docker" ]]; then
|
||||
app_dir="$DOCKER_APP_DIR"
|
||||
[[ -n "${SUDO_USER:-}" ]] && app_dir="/home/$SUDO_USER/picpeak"
|
||||
port="${CUSTOM_PORT:-$DEFAULT_PORT}"
|
||||
manual_reset_hint="cd $(printf %q "$app_dir") && docker compose exec -T backend node scripts/reset-admin-password.js --force --credentials-file data/ADMIN_CREDENTIALS.txt"
|
||||
else
|
||||
app_dir="$NATIVE_APP_DIR"
|
||||
port="${CUSTOM_PORT:-$DEFAULT_PORT}"
|
||||
manual_reset_hint="cd $(printf %q "${NATIVE_APP_DIR}/app/backend") && sudo -H -u $(printf %q "$NATIVE_APP_USER") node scripts/reset-admin-password.js --force --credentials-file data/ADMIN_CREDENTIALS.txt"
|
||||
fi
|
||||
|
||||
print_header "🎉 Installation Complete!"
|
||||
@@ -1020,13 +1017,7 @@ print_success_message() {
|
||||
fi
|
||||
else
|
||||
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
||||
local reset_hint
|
||||
if [[ "$INSTALL_METHOD" == "docker" ]]; then
|
||||
reset_hint="docker compose exec backend node scripts/reset-admin-password.js"
|
||||
else
|
||||
reset_hint="cd $NATIVE_APP_DIR/app/backend && node scripts/reset-admin-password.js"
|
||||
fi
|
||||
echo -e "Password: ${YELLOW}(credentials file not found - rerun setup with --force-admin-password-reset or run $reset_hint)${NC}"
|
||||
echo -e "Password: ${YELLOW}(credentials file not found - rerun setup with --force-admin-password-reset or run '${manual_reset_hint}')${NC}"
|
||||
fi
|
||||
echo
|
||||
echo -e "${YELLOW}⚠️ IMPORTANT: Change the admin password on first login!${NC}"
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||
|
||||
test('admin can update account email via settings page', async ({ page }, testInfo) => {
|
||||
if (testInfo.project.name === 'mobile-chrome') {
|
||||
test.skip('Account settings UI is validated on desktop viewport');
|
||||
}
|
||||
|
||||
const newEmail = `admin+playwright-${Date.now()}@example.com`;
|
||||
|
||||
await page.goto('/admin/login');
|
||||
await page.getByLabel(/Email|E-Mail/i).fill(ADMIN_EMAIL);
|
||||
await page.getByLabel(/Password|Passwort/i).fill(ADMIN_PASSWORD);
|
||||
await page.getByRole('button', { name: /Sign In|Log in|Anmelden/i }).click();
|
||||
await expect(page.getByRole('heading', { name: /Dashboard|Übersicht/i })).toBeVisible({ timeout: 20000 });
|
||||
|
||||
await page.goto('/admin/settings');
|
||||
const emailInput = page.getByLabel(/Admin (Email|E-Mail)/i);
|
||||
const usernameInput = page.getByLabel(/Admin (Username|Benutzername)/i);
|
||||
|
||||
await expect(emailInput).toBeVisible();
|
||||
const originalEmail = await emailInput.inputValue();
|
||||
const originalUsername = await usernameInput.inputValue();
|
||||
|
||||
const saveButton = page.getByRole('button', { name: /(Save account details|Kontodaten speichern)/i });
|
||||
|
||||
const revertChanges = async () => {
|
||||
await emailInput.fill(originalEmail);
|
||||
await usernameInput.fill(originalUsername);
|
||||
await saveButton.click();
|
||||
await expect(emailInput).toHaveValue(originalEmail, { timeout: 10000 });
|
||||
await expect(page.locator('.Toastify__toast').filter({ hasText: /(Account details updated|Kontodaten aktualisiert)/i })).toBeVisible({ timeout: 10000 });
|
||||
};
|
||||
|
||||
try {
|
||||
await emailInput.fill(newEmail);
|
||||
await saveButton.click();
|
||||
|
||||
await expect(emailInput).toHaveValue(newEmail, { timeout: 10000 });
|
||||
await expect(page.locator('.Toastify__toast').filter({ hasText: /(Account details updated|Kontodaten aktualisiert)/i })).toBeVisible({ timeout: 10000 });
|
||||
await expect(page.getByText(newEmail, { exact: false })).toBeVisible();
|
||||
} finally {
|
||||
await revertChanges();
|
||||
}
|
||||
});
|
||||
@@ -29,9 +29,9 @@ test('admin can create event via UI', async ({ page }) => {
|
||||
await expect(page.getByRole('heading', { name: /^Create$/i })).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await page.getByLabel(/Event Name/i).fill(eventName);
|
||||
await page.getByLabel(/Host Name/i).fill('Host User');
|
||||
await page.getByLabel(/Customer Name/i).fill('Host User');
|
||||
await page.getByLabel(/Event Date/i).fill('2025-12-31');
|
||||
await page.getByLabel(/Host Email/i).fill(hostEmail);
|
||||
await page.getByLabel(/Customer Email/i).fill(hostEmail);
|
||||
await page.getByLabel(/Admin Email/i).fill(ADMIN_EMAIL);
|
||||
await page.getByLabel(/Gallery Password/i).fill('UiPlay123!');
|
||||
await page.getByLabel(/Confirm Password/i).fill('UiPlay123!');
|
||||
|
||||
@@ -86,8 +86,22 @@ test('admin login and gallery viewing smoke test', async ({ page }) => {
|
||||
// Visit gallery share link and authenticate
|
||||
await page.goto(shareLink);
|
||||
const passwordField = page.getByPlaceholder(/gallery password/i);
|
||||
await passwordField.fill(GALLERY_PASSWORD);
|
||||
await page.getByRole('button', { name: /View Gallery/i }).click();
|
||||
if (await passwordField.count()) {
|
||||
try {
|
||||
await passwordField.fill(GALLERY_PASSWORD, { timeout: 2000 });
|
||||
} catch {
|
||||
// Field may disappear if gallery bypasses password; ignore.
|
||||
}
|
||||
}
|
||||
|
||||
const viewButton = page.getByRole('button', { name: /View Gallery/i });
|
||||
if (await viewButton.count()) {
|
||||
try {
|
||||
await viewButton.click({ noWaitAfter: true, timeout: 2000 });
|
||||
} catch {
|
||||
// Already inside gallery view.
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for photos grid to appear
|
||||
const tiles = page.locator('.relative.group');
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
import { test, expect } 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 || 'ExternalMediaPass!1';
|
||||
|
||||
async function createExternalGallery(page) {
|
||||
const externalRoot = path.join(process.cwd(), 'storage', 'external-media', 'picsum-demo', 'individual');
|
||||
if (!fs.existsSync(externalRoot)) {
|
||||
fs.mkdirSync(externalRoot, { recursive: true });
|
||||
}
|
||||
|
||||
const sampleImages = ['img1.png', 'img2.png'];
|
||||
for (const imageName of sampleImages) {
|
||||
const source = path.join(process.cwd(), 'test-assets', imageName);
|
||||
const target = path.join(externalRoot, imageName);
|
||||
if (!fs.existsSync(target)) {
|
||||
fs.copyFileSync(source, target);
|
||||
}
|
||||
}
|
||||
|
||||
const loginResponse = await page.request.post('/api/auth/admin/login', {
|
||||
data: {
|
||||
username: ADMIN_EMAIL,
|
||||
@@ -72,7 +88,10 @@ async function createExternalGallery(page) {
|
||||
failOnStatusCode: false,
|
||||
});
|
||||
|
||||
expect(importResponse.ok()).toBeTruthy();
|
||||
if (!importResponse.ok()) {
|
||||
const bodyText = await importResponse.text();
|
||||
throw new Error(`Failed to import external media: ${importResponse.status()} ${bodyText}`);
|
||||
}
|
||||
const importBody = await importResponse.json();
|
||||
expect(importBody.imported).toBeGreaterThan(0);
|
||||
|
||||
@@ -113,9 +132,13 @@ test.describe('External media gallery behavior', () => {
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
|
||||
const passwordField = page.getByPlaceholder(/gallery password/i).first();
|
||||
await expect(passwordField).toBeVisible();
|
||||
await passwordField.fill(GALLERY_PASSWORD);
|
||||
await page.getByRole('button', { name: /View Gallery/i }).click();
|
||||
if (await passwordField.count()) {
|
||||
await passwordField.fill(GALLERY_PASSWORD);
|
||||
const viewButton = page.getByRole('button', { name: /View Gallery/i });
|
||||
if (await viewButton.count()) {
|
||||
await viewButton.click({ noWaitAfter: true, timeout: 2000 });
|
||||
}
|
||||
}
|
||||
|
||||
const tiles = page.locator('.relative.group');
|
||||
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||
|
||||
test('clearing old notifications removes read entries', async ({ request }) => {
|
||||
const loginResponse = await request.post('/api/auth/admin/login', {
|
||||
data: {
|
||||
username: ADMIN_EMAIL,
|
||||
password: ADMIN_PASSWORD,
|
||||
},
|
||||
});
|
||||
expect(loginResponse.ok()).toBeTruthy();
|
||||
const { token } = await loginResponse.json();
|
||||
|
||||
const authHeaders = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
const eventName = `Notification Clear ${Date.now()}`;
|
||||
const eventDate = new Date().toISOString().slice(0, 10);
|
||||
|
||||
const createEventResponse = await request.post('/api/admin/events', {
|
||||
headers: authHeaders,
|
||||
data: {
|
||||
event_type: 'wedding',
|
||||
event_name: eventName,
|
||||
event_date: eventDate,
|
||||
host_name: 'Notification Test',
|
||||
host_email: 'notify@example.com',
|
||||
admin_email: ADMIN_EMAIL,
|
||||
password: 'NotifyClearPass!1',
|
||||
expiration_days: 30,
|
||||
allow_user_uploads: false,
|
||||
allow_downloads: true,
|
||||
disable_right_click: false,
|
||||
watermark_downloads: false,
|
||||
},
|
||||
});
|
||||
expect(createEventResponse.ok()).toBeTruthy();
|
||||
const createdEvent = await createEventResponse.json();
|
||||
const eventId = createdEvent.id;
|
||||
|
||||
const collectedNotifications = async () => {
|
||||
const notificationsResponse = await request.get('/api/admin/notifications', {
|
||||
headers: authHeaders,
|
||||
params: { includeRead: true, limit: 200 },
|
||||
});
|
||||
expect(notificationsResponse.ok()).toBeTruthy();
|
||||
return notificationsResponse.json();
|
||||
};
|
||||
|
||||
let notificationsPayload = await collectedNotifications();
|
||||
const start = Date.now();
|
||||
while (notificationsPayload.notifications.length === 0 && Date.now() - start < 5000) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
notificationsPayload = await collectedNotifications();
|
||||
}
|
||||
|
||||
const targetEventNotifications = notificationsPayload.notifications.filter(
|
||||
(notification: any) => notification.eventId === eventId
|
||||
);
|
||||
expect(targetEventNotifications.length).toBeGreaterThan(0);
|
||||
|
||||
const markReadResponse = await request.put('/api/admin/notifications/read-all', {
|
||||
headers: authHeaders,
|
||||
});
|
||||
expect(markReadResponse.ok()).toBeTruthy();
|
||||
|
||||
const postMarkPayload = await collectedNotifications();
|
||||
const postMarkEventNotifications = postMarkPayload.notifications.filter(
|
||||
(notification: any) => notification.eventId === eventId
|
||||
);
|
||||
const readNotificationIds = postMarkEventNotifications
|
||||
.filter((notification: any) => notification.isRead)
|
||||
.map((notification: any) => notification.id);
|
||||
expect(readNotificationIds.length).toBeGreaterThan(0);
|
||||
|
||||
const clearResponse = await request.delete('/api/admin/notifications/clear-old', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(clearResponse.ok()).toBeTruthy();
|
||||
const clearPayload = await clearResponse.json();
|
||||
expect(clearPayload.deletedCount).toBeGreaterThanOrEqual(0);
|
||||
|
||||
const afterClearPayload = await collectedNotifications();
|
||||
expect(Array.isArray(afterClearPayload.notifications)).toBe(true);
|
||||
const remainingIds = new Set(afterClearPayload.notifications.map((notification: any) => notification.id));
|
||||
readNotificationIds.forEach((id) => {
|
||||
expect(remainingIds.has(id)).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user