Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f6f1c31369 | |||
| a1e9fb6ffc | |||
| 665ce5a6e7 | |||
| 8c41dd626d | |||
| 775e417e55 |
@@ -0,0 +1,207 @@
|
|||||||
|
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,6 +66,16 @@ describe('resolvePhotoFilePath', () => {
|
|||||||
expect(result).toBe(path.join('/mock/external', 'picsum-demo/individual', 'look-02.jpg'));
|
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', () => {
|
it('throws when external photo is missing relative path data', () => {
|
||||||
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
|
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
|
||||||
const photo = { source_origin: 'external' };
|
const photo = { source_origin: 'external' };
|
||||||
|
|||||||
Generated
+29
-29
@@ -35,7 +35,7 @@
|
|||||||
"mime-types": "^3.0.1",
|
"mime-types": "^3.0.1",
|
||||||
"multer": "^2.0.2",
|
"multer": "^2.0.2",
|
||||||
"node-cron": "^3.0.2",
|
"node-cron": "^3.0.2",
|
||||||
"nodemailer": "7.0.5",
|
"nodemailer": "^7.0.10",
|
||||||
"pg": "^8.16.3",
|
"pg": "^8.16.3",
|
||||||
"react-i18next": "^15.6.0",
|
"react-i18next": "^15.6.0",
|
||||||
"sanitize-html": "^2.17.0",
|
"sanitize-html": "^2.17.0",
|
||||||
@@ -5620,13 +5620,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/express-validator": {
|
"node_modules/express-validator": {
|
||||||
"version": "7.2.1",
|
"version": "7.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.3.0.tgz",
|
||||||
"integrity": "sha512-CjNE6aakfpuwGaHQZ3m8ltCG2Qvivd7RHtVMS/6nVxOM7xVGqr4bhflsm4+N5FP5zI7Zxp+Hae+9RE+o8e3ZOQ==",
|
"integrity": "sha512-ujK2BX5JUun5NR4JuBo83YSXoDDIpoGz3QxgHTzQcHFevkKnwV1in4K7YNuuXQ1W3a2ObXB/P4OTnTZpUyGWiw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"validator": "~13.12.0"
|
"validator": "~13.15.15"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 8.0.0"
|
"node": ">= 8.0.0"
|
||||||
@@ -8355,9 +8355,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/nodemailer": {
|
"node_modules/nodemailer": {
|
||||||
"version": "7.0.5",
|
"version": "7.0.10",
|
||||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.10.tgz",
|
||||||
"integrity": "sha512-nsrh2lO3j4GkLLXoeEksAMgAOqxOv6QumNRVQTJwKH4nuiww6iC2y7GyANs9kRAxCexg3+lTWM3PZ91iLlVjfg==",
|
"integrity": "sha512-Us/Se1WtT0ylXgNFfyFSx4LElllVLJXQjWi2Xz17xWw7amDKO2MLtFnVp1WACy7GkVGs+oBlRopVNUzlrGSw1w==",
|
||||||
"license": "MIT-0",
|
"license": "MIT-0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.0.0"
|
"node": ">=6.0.0"
|
||||||
@@ -9008,24 +9008,6 @@
|
|||||||
"node": ">=10"
|
"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": {
|
"node_modules/prelude-ls": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
||||||
@@ -10246,6 +10228,24 @@
|
|||||||
"node": ">=10"
|
"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": {
|
"node_modules/tar-stream": {
|
||||||
"version": "2.2.0",
|
"version": "2.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
|
||||||
@@ -10624,9 +10624,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/validator": {
|
"node_modules/validator": {
|
||||||
"version": "13.12.0",
|
"version": "13.15.20",
|
||||||
"resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz",
|
"resolved": "https://registry.npmjs.org/validator/-/validator-13.15.20.tgz",
|
||||||
"integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==",
|
"integrity": "sha512-KxPOq3V2LmfQPP4eqf3Mq/zrT0Dqp2Vmx2Bn285LwVahLc+CsxOM0crBHczm8ijlcjZ0Q5Xd6LW3z3odTPnlrw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 0.10"
|
"node": ">= 0.10"
|
||||||
|
|||||||
@@ -39,7 +39,7 @@
|
|||||||
"mime-types": "^3.0.1",
|
"mime-types": "^3.0.1",
|
||||||
"multer": "^2.0.2",
|
"multer": "^2.0.2",
|
||||||
"node-cron": "^3.0.2",
|
"node-cron": "^3.0.2",
|
||||||
"nodemailer": "7.0.5",
|
"nodemailer": "^7.0.10",
|
||||||
"pg": "^8.16.3",
|
"pg": "^8.16.3",
|
||||||
"react-i18next": "^15.6.0",
|
"react-i18next": "^15.6.0",
|
||||||
"sanitize-html": "^2.17.0",
|
"sanitize-html": "^2.17.0",
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
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' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -72,6 +72,68 @@ 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
|
// Logout
|
||||||
router.post('/logout', adminAuth, async (req, res) => {
|
router.post('/logout', adminAuth, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@@ -96,4 +158,4 @@ router.post('/logout', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -119,4 +119,18 @@ router.delete('/clear-old', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
// 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,6 +13,24 @@ const router = express.Router();
|
|||||||
// Get storage path from environment or default
|
// Get storage path from environment or default
|
||||||
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
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
|
// Configure multer for file uploads
|
||||||
// IMPORTANT: Using synchronous functions to prevent file corruption
|
// IMPORTANT: Using synchronous functions to prevent file corruption
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
@@ -158,16 +176,16 @@ router.post('/:eventId/upload', adminAuth, uploadTimeout(600000), (req, res, nex
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parse category_id to number if provided
|
// Parse category_id to number if provided
|
||||||
const parsedCategoryId = category_id ? parseInt(category_id, 10) : null;
|
const numericCategoryId = parseCategoryId(category_id);
|
||||||
|
|
||||||
// Determine photo type from category_id parameter (for backwards compatibility)
|
// Determine photo type from category_id parameter (for backwards compatibility)
|
||||||
let photoType = 'individual'; // default
|
let photoType = 'individual'; // default
|
||||||
let categoryName = 'individual';
|
let categoryName = 'individual';
|
||||||
|
|
||||||
if (parsedCategoryId === 1 || category_id === 'collage') {
|
if (numericCategoryId === 1 || category_id === 'collage') {
|
||||||
photoType = 'collage';
|
photoType = 'collage';
|
||||||
categoryName = 'collages';
|
categoryName = 'collages';
|
||||||
} else if (parsedCategoryId === 2 || category_id === 'individual') {
|
} else if (numericCategoryId === 2 || category_id === 'individual') {
|
||||||
photoType = 'individual';
|
photoType = 'individual';
|
||||||
categoryName = 'individual';
|
categoryName = 'individual';
|
||||||
}
|
}
|
||||||
@@ -239,7 +257,9 @@ router.post('/:eventId/upload', adminAuth, uploadTimeout(600000), (req, res, nex
|
|||||||
path: relativePath,
|
path: relativePath,
|
||||||
thumbnail_path: null, // Will generate after successful commit
|
thumbnail_path: null, // Will generate after successful commit
|
||||||
type: photoType,
|
type: photoType,
|
||||||
size_bytes: tempStats.size // Use actual file size from stat
|
size_bytes: tempStats.size, // Use actual file size from stat
|
||||||
|
category_id: numericCategoryId,
|
||||||
|
source_origin: 'managed'
|
||||||
};
|
};
|
||||||
|
|
||||||
batchPhotos.push(photoData);
|
batchPhotos.push(photoData);
|
||||||
@@ -475,9 +495,11 @@ router.patch('/:eventId/photos/:photoId', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update photo
|
// Update photo
|
||||||
|
const normalizedCategoryId = parseCategoryId(category_id);
|
||||||
|
|
||||||
await db('photos')
|
await db('photos')
|
||||||
.where({ id: photoId })
|
.where({ id: photoId })
|
||||||
.update({ category_id: category_id || null });
|
.update({ category_id: normalizedCategoryId });
|
||||||
|
|
||||||
res.json({ message: 'Photo updated successfully' });
|
res.json({ message: 'Photo updated successfully' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -578,7 +600,7 @@ router.post('/:eventId/photos/bulk-update', adminAuth, async (req, res) => {
|
|||||||
// Update photos
|
// Update photos
|
||||||
const updateData = {};
|
const updateData = {};
|
||||||
if (updates.category_id !== undefined) {
|
if (updates.category_id !== undefined) {
|
||||||
updateData.category_id = updates.category_id || null;
|
updateData.category_id = parseCategoryId(updates.category_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
await db('photos')
|
await db('photos')
|
||||||
@@ -632,14 +654,22 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
|||||||
const { category_id, type, search, sort = 'date', order = 'desc' } = req.query;
|
const { category_id, type, search, sort = 'date', order = 'desc' } = req.query;
|
||||||
|
|
||||||
let query = db('photos')
|
let query = db('photos')
|
||||||
|
.leftJoin('photo_categories as pc', 'pc.id', 'photos.category_id')
|
||||||
.where({ 'photos.event_id': eventId })
|
.where({ 'photos.event_id': eventId })
|
||||||
.select('photos.*');
|
.select(
|
||||||
|
'photos.*',
|
||||||
|
'pc.name as category_display_name',
|
||||||
|
'pc.slug as category_display_slug'
|
||||||
|
);
|
||||||
|
|
||||||
// Filter by type (individual/collage) - category_id maps to type
|
// Filter by type (individual/collage) - category_id maps to type
|
||||||
if (category_id !== undefined) {
|
if (category_id !== undefined) {
|
||||||
if (category_id === '' || category_id === '0') {
|
if (category_id === '') {
|
||||||
// For backwards compatibility, empty category means no filter
|
// No filter when empty string is provided
|
||||||
// Don't filter anything
|
} 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));
|
||||||
} else if (category_id === 'individual' || category_id === 'collage') {
|
} else if (category_id === 'individual' || category_id === 'collage') {
|
||||||
query = query.where({ 'photos.type': category_id });
|
query = query.where({ 'photos.type': category_id });
|
||||||
}
|
}
|
||||||
@@ -665,7 +695,11 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const photos = await query.orderBy(orderByColumn, order);
|
const photos = await query.orderBy(orderByColumn, order);
|
||||||
|
|
||||||
|
if (photos.length === 0) {
|
||||||
|
return res.json({ photos: [] });
|
||||||
|
}
|
||||||
|
|
||||||
// Get comment counts separately
|
// Get comment counts separately
|
||||||
const commentCounts = await db('photo_feedback')
|
const commentCounts = await db('photo_feedback')
|
||||||
.whereIn('photo_id', photos.map(p => p.id))
|
.whereIn('photo_id', photos.map(p => p.id))
|
||||||
@@ -690,9 +724,11 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
|||||||
// Always expose a thumbnail URL; backend will generate on demand if missing
|
// Always expose a thumbnail URL; backend will generate on demand if missing
|
||||||
thumbnail_url: `/admin/photos/${eventId}/thumbnail/${photo.id}`,
|
thumbnail_url: `/admin/photos/${eventId}/thumbnail/${photo.id}`,
|
||||||
type: photo.type,
|
type: photo.type,
|
||||||
category_id: photo.type,
|
category_id: photo.category_id !== null && photo.category_id !== undefined
|
||||||
category_name: photo.type === 'individual' ? 'Individual Photos' : 'Collages',
|
? Number(photo.category_id)
|
||||||
category_slug: photo.type,
|
: null,
|
||||||
|
category_name: photo.category_display_name || (photo.type === 'individual' ? 'Individual Photos' : 'Collages'),
|
||||||
|
category_slug: photo.category_display_slug || photo.type,
|
||||||
size: photo.size_bytes,
|
size: photo.size_bytes,
|
||||||
uploaded_at: photo.uploaded_at,
|
uploaded_at: photo.uploaded_at,
|
||||||
// Feedback data
|
// Feedback data
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '.
|
|||||||
function resolvePhotoFilePath(event, photo) {
|
function resolvePhotoFilePath(event, photo) {
|
||||||
if (!event || !photo) throw new Error('resolvePhotoFilePath requires event and photo');
|
if (!event || !photo) throw new Error('resolvePhotoFilePath requires event and photo');
|
||||||
|
|
||||||
const mode = (event.source_mode || photo.source_origin || 'managed');
|
const isExternal = photo.source_origin === 'external' ||
|
||||||
if (mode === 'reference' || photo.source_origin === 'external') {
|
(!!photo.external_relpath && (event.source_mode === 'reference' || event.source_mode === 'external'));
|
||||||
|
|
||||||
|
if (isExternal) {
|
||||||
if (!photo.external_relpath) {
|
if (!photo.external_relpath) {
|
||||||
throw new Error('Missing external_relpath for external photo');
|
throw new Error('Missing external_relpath for external photo');
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-5
@@ -3,19 +3,45 @@
|
|||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
host="$DB_HOST"
|
host="${DB_HOST:-postgres}"
|
||||||
port="${DB_PORT:-5432}"
|
port="${DB_PORT:-5432}"
|
||||||
user="${DB_USER:-picpeak}"
|
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..."
|
echo "Waiting for PostgreSQL at $host:$port..."
|
||||||
|
|
||||||
# Wait for PostgreSQL to be ready
|
# Wait for PostgreSQL server to accept connections (using the default database)
|
||||||
until PGPASSWORD=$DB_PASSWORD psql -h "$host" -p "$port" -U "$user" -d "${DB_NAME:-picpeak}" -c '\q' 2>/dev/null; do
|
until PGPASSWORD="$DB_PASSWORD" psql -h "$host" -p "$port" -U "$user" -d "$default_db" -c '\q' >/dev/null 2>&1; do
|
||||||
>&2 echo "PostgreSQL is unavailable - sleeping"
|
>&2 echo "PostgreSQL is unavailable - sleeping"
|
||||||
sleep 2
|
sleep 2
|
||||||
done
|
done
|
||||||
|
|
||||||
>&2 echo "PostgreSQL is up - executing command"
|
>&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."
|
||||||
|
|
||||||
# Run migrations (use safe runner in production)
|
# Run migrations (use safe runner in production)
|
||||||
echo "Running database migrations..."
|
echo "Running database migrations..."
|
||||||
@@ -26,4 +52,4 @@ else
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Execute the main command
|
# Execute the main command
|
||||||
exec "$@"
|
exec "$@"
|
||||||
|
|||||||
+1
-1
@@ -101,7 +101,7 @@ services:
|
|||||||
context: ./frontend
|
context: ./frontend
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
args:
|
args:
|
||||||
- VITE_API_URL=${VITE_API_URL:-http://localhost:3001/api}
|
- VITE_API_URL=${VITE_API_URL:-/api}
|
||||||
- VITE_UMAMI_URL=${VITE_UMAMI_URL:-}
|
- VITE_UMAMI_URL=${VITE_UMAMI_URL:-}
|
||||||
- VITE_UMAMI_WEBSITE_ID=${VITE_UMAMI_WEBSITE_ID:-}
|
- VITE_UMAMI_WEBSITE_ID=${VITE_UMAMI_WEBSITE_ID:-}
|
||||||
- VITE_UMAMI_SHARE_URL=${VITE_UMAMI_SHARE_URL:-}
|
- VITE_UMAMI_SHARE_URL=${VITE_UMAMI_SHARE_URL:-}
|
||||||
|
|||||||
@@ -19,5 +19,28 @@ export default tseslint.config([
|
|||||||
ecmaVersion: 2020,
|
ecmaVersion: 2020,
|
||||||
globals: globals.browser,
|
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
+1287
-8
File diff suppressed because it is too large
Load Diff
+12
-5
@@ -5,10 +5,11 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "cross-env ROLLUP_USE_NODE_JS=true vite build",
|
||||||
"build:check": "tsc -b && vite build",
|
"build:check": "tsc -b && cross-env ROLLUP_USE_NODE_JS=true vite build",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run src/components/admin/__tests__/ThemeCustomizerEnhanced.test.tsx"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tanstack/react-query": "^5.0.0",
|
"@tanstack/react-query": "^5.0.0",
|
||||||
@@ -47,18 +48,24 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.29.0",
|
"@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": "^18.3.12",
|
||||||
"@types/react-dom": "^18.3.1",
|
"@types/react-dom": "^18.3.1",
|
||||||
"@vitejs/plugin-react": "^4.5.2",
|
"@vitejs/plugin-react": "^4.5.3",
|
||||||
"autoprefixer": "^10.4.13",
|
"autoprefixer": "^10.4.13",
|
||||||
|
"cross-env": "^10.1.0",
|
||||||
"eslint": "^9.29.0",
|
"eslint": "^9.29.0",
|
||||||
"eslint-plugin-react-hooks": "^5.2.0",
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
"eslint-plugin-react-refresh": "^0.4.20",
|
"eslint-plugin-react-refresh": "^0.4.20",
|
||||||
"globals": "^16.2.0",
|
"globals": "^16.2.0",
|
||||||
|
"jsdom": "^25.0.1",
|
||||||
"postcss": "^8.4.21",
|
"postcss": "^8.4.21",
|
||||||
"tailwindcss": "^3.3.0",
|
"tailwindcss": "^3.3.0",
|
||||||
"typescript": "~5.8.3",
|
"typescript": "~5.8.3",
|
||||||
"typescript-eslint": "^8.34.1",
|
"typescript-eslint": "^8.34.1",
|
||||||
"vite": "^7.1.6"
|
"vite": "^7.1.12",
|
||||||
|
"vitest": "^3.2.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export const MaintenanceMode: React.FC = () => {
|
|||||||
try {
|
try {
|
||||||
const response = await api.get('/public/settings');
|
const response = await api.get('/public/settings');
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch {
|
||||||
// Return empty object if settings can't be fetched
|
// Return empty object if settings can't be fetched
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -110,4 +110,4 @@ export const MaintenanceMode: React.FC = () => {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
|||||||
if (isMounted) {
|
if (isMounted) {
|
||||||
setHasAdminSession(Boolean(response.data?.valid && response.data.type === 'admin'));
|
setHasAdminSession(Boolean(response.data?.valid && response.data.type === 'admin'));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch {
|
||||||
if (isMounted) {
|
if (isMounted) {
|
||||||
setHasAdminSession(false);
|
setHasAdminSession(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,13 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
let objectUrl: string | null = null;
|
||||||
|
|
||||||
const loadImage = async () => {
|
const loadImage = async () => {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(false);
|
setError(false);
|
||||||
|
setImageSrc(null);
|
||||||
|
|
||||||
// Make authenticated request to get the image
|
// Make authenticated request to get the image
|
||||||
const response = await api.get(src, {
|
const response = await api.get(src, {
|
||||||
@@ -31,11 +33,11 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
|||||||
|
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
// Create object URL from blob
|
// Create object URL from blob
|
||||||
const imageUrl = URL.createObjectURL(response.data);
|
objectUrl = URL.createObjectURL(response.data);
|
||||||
setImageSrc(imageUrl);
|
setImageSrc(objectUrl);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch {
|
||||||
// Image loading failed - handled by error state
|
// Image loading failed - handled by error state
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
setError(true);
|
setError(true);
|
||||||
@@ -51,8 +53,8 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
|||||||
// Cleanup function
|
// Cleanup function
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
if (imageSrc) {
|
if (objectUrl) {
|
||||||
URL.revokeObjectURL(imageSrc);
|
URL.revokeObjectURL(objectUrl);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, [src]);
|
}, [src]);
|
||||||
@@ -74,4 +76,4 @@ export const AdminAuthenticatedImage: React.FC<AdminAuthenticatedImageProps> = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
return <img src={imageSrc || ''} alt={alt} {...props} />;
|
return <img src={imageSrc || ''} alt={alt} {...props} />;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -55,12 +55,12 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Clear old notifications mutation
|
// Clear notifications mutation
|
||||||
const clearOldMutation = useMutation({
|
const clearAllMutation = useMutation({
|
||||||
mutationFn: notificationsService.clearOldNotifications,
|
mutationFn: notificationsService.clearAllNotifications,
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['notifications'] });
|
queryClient.invalidateQueries({ queryKey: ['notifications'] });
|
||||||
toast.success(t('admin.notificationToasts.clearedOld', { count: data.deletedCount }));
|
toast.success(t('admin.notificationToasts.clearedAll', { count: data.deletedCount }));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -128,12 +128,12 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => clearOldMutation.mutate()}
|
onClick={() => clearAllMutation.mutate()}
|
||||||
className="text-xs text-neutral-600 hover:text-neutral-700 flex items-center gap-1"
|
className="text-xs text-neutral-600 hover:text-neutral-700 flex items-center gap-1"
|
||||||
title={t('admin.clearOld')}
|
title={t('admin.clearAll')}
|
||||||
>
|
>
|
||||||
<Trash2 className="w-3 h-3" />
|
<Trash2 className="w-3 h-3" />
|
||||||
{t('admin.clearOld')}
|
{t('admin.clearAll')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
await photosService.deletePhoto(eventId, photo.id);
|
await photosService.deletePhoto(eventId, photo.id);
|
||||||
toast.success('Photo deleted successfully');
|
toast.success('Photo deleted successfully');
|
||||||
onPhotosDeleted();
|
onPhotosDeleted();
|
||||||
} catch (error) {
|
} catch {
|
||||||
toast.error('Failed to delete photo');
|
toast.error('Failed to delete photo');
|
||||||
setDeletingPhotos(prev => {
|
setDeletingPhotos(prev => {
|
||||||
const newSet = new Set(prev);
|
const newSet = new Set(prev);
|
||||||
@@ -90,7 +90,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
setSelectedPhotos(new Set());
|
setSelectedPhotos(new Set());
|
||||||
setIsSelectionMode(false);
|
setIsSelectionMode(false);
|
||||||
onPhotosDeleted();
|
onPhotosDeleted();
|
||||||
} catch (error) {
|
} catch {
|
||||||
toast.error('Failed to delete photos');
|
toast.error('Failed to delete photos');
|
||||||
setDeletingPhotos(new Set());
|
setDeletingPhotos(new Set());
|
||||||
} finally {
|
} finally {
|
||||||
@@ -103,7 +103,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
try {
|
try {
|
||||||
await photosService.downloadPhoto(eventId, photo.id, photo.filename);
|
await photosService.downloadPhoto(eventId, photo.id, photo.filename);
|
||||||
toast.success('Download started');
|
toast.success('Download started');
|
||||||
} catch (error) {
|
} catch {
|
||||||
toast.error('Failed to download photo');
|
toast.error('Failed to download photo');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ interface ThemeCustomizerEnhancedProps {
|
|||||||
isPreviewMode?: boolean;
|
isPreviewMode?: boolean;
|
||||||
showGalleryLayouts?: boolean;
|
showGalleryLayouts?: boolean;
|
||||||
hideActions?: boolean;
|
hideActions?: boolean;
|
||||||
|
onApply?: (theme: ThemeConfig, metadata: { presetName: string }) => Promise<void> | void;
|
||||||
|
isApplying?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const layoutIcons: Record<GalleryLayoutType, React.ReactNode> = {
|
const layoutIcons: Record<GalleryLayoutType, React.ReactNode> = {
|
||||||
@@ -34,7 +36,9 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
|||||||
onPresetChange,
|
onPresetChange,
|
||||||
isPreviewMode = false,
|
isPreviewMode = false,
|
||||||
showGalleryLayouts = true,
|
showGalleryLayouts = true,
|
||||||
hideActions = false
|
hideActions = false,
|
||||||
|
onApply,
|
||||||
|
isApplying = false
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [localTheme, setLocalTheme] = useState<ThemeConfig>(value);
|
const [localTheme, setLocalTheme] = useState<ThemeConfig>(value);
|
||||||
@@ -80,8 +84,13 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleApply = () => {
|
const handleApply = async () => {
|
||||||
onChange({ ...localTheme, customCss });
|
const themeWithCss = { ...localTheme, customCss };
|
||||||
|
onChange(themeWithCss);
|
||||||
|
|
||||||
|
if (onApply) {
|
||||||
|
await onApply(themeWithCss, { presetName: selectedPreset });
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleReset = () => {
|
const handleReset = () => {
|
||||||
@@ -587,11 +596,12 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
|||||||
variant="primary"
|
variant="primary"
|
||||||
leftIcon={<Palette className="w-4 h-4" />}
|
leftIcon={<Palette className="w-4 h-4" />}
|
||||||
onClick={handleApply}
|
onClick={handleApply}
|
||||||
|
disabled={isApplying}
|
||||||
>
|
>
|
||||||
{t('branding.applyTheme')}
|
{isApplying ? t('common.applying', 'Applying...') : t('branding.applyTheme')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
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 (e) {
|
} catch {
|
||||||
// Invalid theme format - use default
|
// Invalid theme format - use default
|
||||||
// Fall back to global theme
|
// Fall back to global theme
|
||||||
if (settingsData.theme_config) {
|
if (settingsData.theme_config) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ interface GridPhotoProps {
|
|||||||
photo: Photo;
|
photo: Photo;
|
||||||
isSelected: boolean;
|
isSelected: boolean;
|
||||||
isSelectionMode: boolean;
|
isSelectionMode: boolean;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: () => void;
|
||||||
onDownload: (e: React.MouseEvent) => void;
|
onDownload: (e: React.MouseEvent) => void;
|
||||||
onToggleSelect: () => void;
|
onToggleSelect: () => void;
|
||||||
animationType?: string;
|
animationType?: string;
|
||||||
@@ -57,6 +57,79 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
liked = false,
|
liked = false,
|
||||||
onLikeSuccess
|
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
|
// handled by parent layout; kept here for type completeness but not used
|
||||||
const { ref, inView } = useInView({
|
const { ref, inView } = useInView({
|
||||||
triggerOnce: true,
|
triggerOnce: true,
|
||||||
@@ -73,11 +146,34 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
const commentCount = photo.comment_count ?? 0;
|
const commentCount = photo.comment_count ?? 0;
|
||||||
const showFeedbackActions = feedbackEnabled && Boolean(feedbackOptions);
|
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 (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={`relative group cursor-pointer aspect-square ${animationClass}`}
|
className={`relative group cursor-pointer aspect-square ${animationClass}`}
|
||||||
onClick={onClick}
|
onClick={handlePhotoClick}
|
||||||
style={{
|
style={{
|
||||||
opacity: !inView && animationType === 'fade' ? 0 : 1
|
opacity: !inView && animationType === 'fade' ? 0 : 1
|
||||||
}}
|
}}
|
||||||
@@ -108,14 +204,15 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<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">
|
<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`}>
|
||||||
{!isSelectionMode && (
|
{!isSelectionMode && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
onClick(e);
|
onClick();
|
||||||
|
hideOverlay();
|
||||||
}}
|
}}
|
||||||
aria-label="View full size"
|
aria-label="View full size"
|
||||||
>
|
>
|
||||||
@@ -124,7 +221,11 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
{allowDownloads && (
|
{allowDownloads && (
|
||||||
<button
|
<button
|
||||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
onClick={onDownload}
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onDownload(e);
|
||||||
|
hideOverlay();
|
||||||
|
}}
|
||||||
aria-label="Download photo"
|
aria-label="Download photo"
|
||||||
>
|
>
|
||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
@@ -133,7 +234,11 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
{showFeedbackActions && onQuickComment && (
|
{showFeedbackActions && onQuickComment && (
|
||||||
<button
|
<button
|
||||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onQuickComment();
|
||||||
|
hideOverlay();
|
||||||
|
}}
|
||||||
aria-label="Comment on photo"
|
aria-label="Comment on photo"
|
||||||
title="Comment"
|
title="Comment"
|
||||||
>
|
>
|
||||||
@@ -148,6 +253,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (feedbackOptions?.requireNameEmail && !savedIdentity && onRequireIdentity) {
|
if (feedbackOptions?.requireNameEmail && !savedIdentity && onRequireIdentity) {
|
||||||
onRequireIdentity('like', photo.id);
|
onRequireIdentity('like', photo.id);
|
||||||
|
hideOverlay();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Optimistic UI: mark as liked immediately
|
// Optimistic UI: mark as liked immediately
|
||||||
@@ -163,6 +269,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
console.warn('Like submit failed, keeping optimistic UI', err);
|
console.warn('Like submit failed, keeping optimistic UI', err);
|
||||||
}
|
}
|
||||||
if (onFeedbackChange) onFeedbackChange();
|
if (onFeedbackChange) onFeedbackChange();
|
||||||
|
hideOverlay();
|
||||||
}}
|
}}
|
||||||
aria-label="Like photo"
|
aria-label="Like photo"
|
||||||
aria-pressed={liked}
|
aria-pressed={liked}
|
||||||
@@ -182,9 +289,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
role="checkbox"
|
role="checkbox"
|
||||||
aria-checked={isSelected}
|
aria-checked={isSelected}
|
||||||
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
className={`absolute top-2 right-2 z-20 transition-opacity ${checkboxVisibilityClass} md:group-hover:opacity-100`}
|
||||||
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
|
||||||
}`}
|
|
||||||
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
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`}>
|
<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 } from 'react';
|
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock, Heart, MessageSquare } from 'lucide-react';
|
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock, Heart, MessageSquare } from 'lucide-react';
|
||||||
import { parseISO } from 'date-fns';
|
import { parseISO } from 'date-fns';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
@@ -50,6 +50,12 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
||||||
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||||
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
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
|
// If an override is provided, always use it and skip initialization logic
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -163,30 +169,40 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
|
|
||||||
{/* Scroll Indicator */}
|
{/* Scroll Indicator */}
|
||||||
<div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 animate-bounce">
|
<div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 animate-bounce">
|
||||||
<ChevronDown className="w-8 h-8 text-white drop-shadow-lg" />
|
<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>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Grid Section */}
|
{/* Grid Section */}
|
||||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
|
<div
|
||||||
|
ref={gridRef}
|
||||||
|
className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4"
|
||||||
|
>
|
||||||
{remainingPhotos.map((photo) => {
|
{remainingPhotos.map((photo) => {
|
||||||
const actualIndex = photos.findIndex(p => p.id === photo.id);
|
const actualIndex = photos.findIndex(p => p.id === photo.id);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
className="relative group cursor-pointer aspect-square"
|
className="relative group cursor-pointer overflow-hidden rounded-lg"
|
||||||
onClick={() => onPhotoClick(actualIndex)}
|
onClick={() => onPhotoClick(actualIndex)}
|
||||||
>
|
>
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={photo.thumbnail_url || photo.url}
|
src={photo.thumbnail_url || photo.url}
|
||||||
alt={photo.filename}
|
alt={photo.filename}
|
||||||
className="w-full h-full object-cover rounded-lg transition-transform duration-300 group-hover:scale-105"
|
className="w-full h-auto object-cover transition-transform duration-300 group-hover:scale-105"
|
||||||
loading="lazy"
|
loading="lazy"
|
||||||
isGallery={true}
|
isGallery={true}
|
||||||
protectFromDownload={!allowDownloads}
|
protectFromDownload={!allowDownloads}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center gap-2">
|
||||||
{!isSelectionMode && (
|
{!isSelectionMode && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
inferGallerySlugFromLocation,
|
inferGallerySlugFromLocation,
|
||||||
resolveSlugFromRequestUrl,
|
resolveSlugFromRequestUrl,
|
||||||
} from '../utils/galleryAuthStorage';
|
} from '../utils/galleryAuthStorage';
|
||||||
|
import { getApiBaseUrl } from '../utils/url';
|
||||||
|
|
||||||
// Maintenance mode callback
|
// Maintenance mode callback
|
||||||
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
||||||
@@ -15,7 +16,7 @@ export const setMaintenanceModeCallback = (callback: (enabled: boolean) => void)
|
|||||||
|
|
||||||
// Create axios instance
|
// Create axios instance
|
||||||
export const api = axios.create({
|
export const api = axios.create({
|
||||||
baseURL: import.meta.env.VITE_API_URL || '/api',
|
baseURL: getApiBaseUrl(),
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ interface AdminAuthContextType {
|
|||||||
error: string | null;
|
error: string | null;
|
||||||
mustChangePassword: boolean;
|
mustChangePassword: boolean;
|
||||||
updatePasswordChanged: () => void;
|
updatePasswordChanged: () => void;
|
||||||
|
updateProfile: (user: AdminUser) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const AdminAuthContext = createContext<AdminAuthContextType | undefined>(undefined);
|
const AdminAuthContext = createContext<AdminAuthContextType | undefined>(undefined);
|
||||||
@@ -104,6 +105,11 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const updateProfile = (updatedUser: AdminUser) => {
|
||||||
|
setUser(updatedUser);
|
||||||
|
sessionStorage.setItem('admin_user', JSON.stringify(updatedUser));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AdminAuthContext.Provider
|
<AdminAuthContext.Provider
|
||||||
value={{
|
value={{
|
||||||
@@ -115,6 +121,7 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
|||||||
error,
|
error,
|
||||||
mustChangePassword,
|
mustChangePassword,
|
||||||
updatePasswordChanged,
|
updatePasswordChanged,
|
||||||
|
updateProfile,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -1080,7 +1080,7 @@
|
|||||||
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
||||||
"noNotifications": "Keine neuen Benachrichtigungen",
|
"noNotifications": "Keine neuen Benachrichtigungen",
|
||||||
"markAllRead": "Alle als gelesen markieren",
|
"markAllRead": "Alle als gelesen markieren",
|
||||||
"clearOld": "Alte löschen",
|
"clearAll": "Alle löschen",
|
||||||
"close": "Schließen",
|
"close": "Schließen",
|
||||||
"noNotificationsMessage": "Keine Benachrichtigungen",
|
"noNotificationsMessage": "Keine Benachrichtigungen",
|
||||||
"notificationMessages": {
|
"notificationMessages": {
|
||||||
@@ -1113,11 +1113,13 @@
|
|||||||
"archiveDownloaded": "Archiv für \"{{eventName}}\" heruntergeladen",
|
"archiveDownloaded": "Archiv für \"{{eventName}}\" heruntergeladen",
|
||||||
"archiveDeleted": "Archiv für \"{{eventName}}\" gelöscht",
|
"archiveDeleted": "Archiv für \"{{eventName}}\" gelöscht",
|
||||||
"archiveRestored": "Archiv für \"{{eventName}}\" wiederhergestellt",
|
"archiveRestored": "Archiv für \"{{eventName}}\" wiederhergestellt",
|
||||||
"systemActivity": "Systemaktivität: {{type}}"
|
"systemActivity": "Systemaktivität: {{type}}",
|
||||||
|
"adminProfileUpdated": "Admin-Profil aktualisiert von {{actorName}}"
|
||||||
},
|
},
|
||||||
"notificationToasts": {
|
"notificationToasts": {
|
||||||
"markedAllRead": "Alle Benachrichtigungen als gelesen markiert",
|
"markedAllRead": "Alle Benachrichtigungen als gelesen markiert",
|
||||||
"clearedOld": "{{count}} alte Benachrichtigungen gelöscht"
|
"clearedAll": "{{count}} Benachrichtigungen gelöscht",
|
||||||
|
"profileUpdated": "Admin-Profil aktualisiert"
|
||||||
},
|
},
|
||||||
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
||||||
"noNotifications": "Keine neuen Benachrichtigungen",
|
"noNotifications": "Keine neuen Benachrichtigungen",
|
||||||
@@ -1125,6 +1127,16 @@
|
|||||||
"markAllAsRead": "Alle als gelesen markieren",
|
"markAllAsRead": "Alle als gelesen markieren",
|
||||||
"notificationSettings": "Benachrichtigungseinstellungen",
|
"notificationSettings": "Benachrichtigungseinstellungen",
|
||||||
"changePassword": "Passwort ändern",
|
"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...",
|
"loadingDashboard": "Dashboard wird geladen...",
|
||||||
"activeEvents": "Aktive Veranstaltungen",
|
"activeEvents": "Aktive Veranstaltungen",
|
||||||
"expiringSoon": "Demnächst ablaufend",
|
"expiringSoon": "Demnächst ablaufend",
|
||||||
|
|||||||
@@ -818,7 +818,7 @@
|
|||||||
"viewAllNotifications": "View all notifications",
|
"viewAllNotifications": "View all notifications",
|
||||||
"noNotifications": "No new notifications",
|
"noNotifications": "No new notifications",
|
||||||
"markAllRead": "Mark all read",
|
"markAllRead": "Mark all read",
|
||||||
"clearOld": "Clear old",
|
"clearAll": "Clear all",
|
||||||
"close": "Close",
|
"close": "Close",
|
||||||
"noNotificationsMessage": "No notifications",
|
"noNotificationsMessage": "No notifications",
|
||||||
"notificationMessages": {
|
"notificationMessages": {
|
||||||
@@ -851,16 +851,28 @@
|
|||||||
"archiveDownloaded": "Archive downloaded for \"{{eventName}}\"",
|
"archiveDownloaded": "Archive downloaded for \"{{eventName}}\"",
|
||||||
"archiveDeleted": "Archive deleted for \"{{eventName}}\"",
|
"archiveDeleted": "Archive deleted for \"{{eventName}}\"",
|
||||||
"archiveRestored": "Archive restored for \"{{eventName}}\"",
|
"archiveRestored": "Archive restored for \"{{eventName}}\"",
|
||||||
"systemActivity": "System activity: {{type}}"
|
"systemActivity": "System activity: {{type}}",
|
||||||
|
"adminProfileUpdated": "Admin profile updated by {{actorName}}"
|
||||||
},
|
},
|
||||||
"notificationToasts": {
|
"notificationToasts": {
|
||||||
"markedAllRead": "All notifications marked as read",
|
"markedAllRead": "All notifications marked as read",
|
||||||
"clearedOld": "Cleared {{count}} old notifications"
|
"clearedAll": "Cleared {{count}} notifications",
|
||||||
|
"profileUpdated": "Admin profile updated"
|
||||||
},
|
},
|
||||||
"markAsRead": "Mark as read",
|
"markAsRead": "Mark as read",
|
||||||
"markAllAsRead": "Mark all as read",
|
"markAllAsRead": "Mark all as read",
|
||||||
"notificationSettings": "Notification Settings",
|
"notificationSettings": "Notification Settings",
|
||||||
"changePassword": "Change Password",
|
"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...",
|
"loadingDashboard": "Loading dashboard...",
|
||||||
"activeEvents": "Active Events",
|
"activeEvents": "Active Events",
|
||||||
"expiringSoon": "Expiring Soon",
|
"expiringSoon": "Expiring Soon",
|
||||||
|
|||||||
@@ -236,6 +236,28 @@ 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
|
// Archive mutation
|
||||||
const archiveMutation = useMutation({
|
const archiveMutation = useMutation({
|
||||||
mutationFn: () => eventsService.archiveEvent(parseInt(id!)),
|
mutationFn: () => eventsService.archiveEvent(parseInt(id!)),
|
||||||
@@ -1124,6 +1146,20 @@ export const EventDetailsPage: React.FC = () => {
|
|||||||
}}
|
}}
|
||||||
isPreviewMode={false}
|
isPreviewMode={false}
|
||||||
showGalleryLayouts={true}
|
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>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Save,
|
Save,
|
||||||
Database,
|
Database,
|
||||||
@@ -19,7 +19,9 @@ import { CategoryManager } from '../../components/admin/CategoryManager';
|
|||||||
import { WordFilterManager } from '../../components/admin/WordFilterManager';
|
import { WordFilterManager } from '../../components/admin/WordFilterManager';
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { settingsService } from '../../services/settings.service';
|
import { settingsService } from '../../services/settings.service';
|
||||||
|
import { authService } from '../../services/auth.service';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useAdminAuth } from '../../contexts';
|
||||||
|
|
||||||
const BYTES_PER_GB = 1024 * 1024 * 1024;
|
const BYTES_PER_GB = 1024 * 1024 * 1024;
|
||||||
|
|
||||||
@@ -56,6 +58,23 @@ export const SettingsPage: React.FC = () => {
|
|||||||
const [activeTab, setActiveTab] = useState<'general' | 'status' | 'security' | 'categories' | 'analytics' | 'moderation'>('general');
|
const [activeTab, setActiveTab] = useState<'general' | 'status' | 'security' | 'categories' | 'analytics' | 'moderation'>('general');
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { t, i18n } = useTranslation();
|
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());
|
||||||
|
|
||||||
// Fetch settings
|
// Fetch settings
|
||||||
const { data: settings, isLoading } = useQuery({
|
const { data: settings, isLoading } = useQuery({
|
||||||
@@ -78,6 +97,20 @@ export const SettingsPage: React.FC = () => {
|
|||||||
refetchInterval: 30000 // Refresh every 30 seconds
|
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
|
// General settings state
|
||||||
const [generalSettings, setGeneralSettings] = useState({
|
const [generalSettings, setGeneralSettings] = useState({
|
||||||
site_url: '',
|
site_url: '',
|
||||||
@@ -343,6 +376,19 @@ 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 = () => {
|
const handleSaveCapacityOverride = () => {
|
||||||
if (saveCapacityOverrideMutation.isPending) {
|
if (saveCapacityOverrideMutation.isPending) {
|
||||||
return;
|
return;
|
||||||
@@ -466,6 +512,46 @@ export const SettingsPage: React.FC = () => {
|
|||||||
{/* General Settings Tab */}
|
{/* General Settings Tab */}
|
||||||
{activeTab === 'general' && (
|
{activeTab === 'general' && (
|
||||||
<div className="space-y-6">
|
<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}
|
||||||
|
/>
|
||||||
|
</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>
|
||||||
|
</Card>
|
||||||
|
|
||||||
<Card padding="md">
|
<Card padding="md">
|
||||||
<h2 className="text-lg font-semibold text-neutral-900 mb-4">{t('settings.general.siteConfiguration')}</h2>
|
<h2 className="text-lg font-semibold text-neutral-900 mb-4">{t('settings.general.siteConfiguration')}</h2>
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { api } from '../config/api';
|
import { api } from '../config/api';
|
||||||
import type { LoginResponse, GalleryAuthResponse } from '../types';
|
import type { LoginResponse, GalleryAuthResponse, AdminUser } from '../types';
|
||||||
import { normalizeRequirePassword } from '../utils/accessControl';
|
import { normalizeRequirePassword } from '../utils/accessControl';
|
||||||
|
|
||||||
const normalizeGalleryResponse = (response: GalleryAuthResponse): GalleryAuthResponse => ({
|
const normalizeGalleryResponse = (response: GalleryAuthResponse): GalleryAuthResponse => ({
|
||||||
@@ -61,4 +61,9 @@ export const authService = {
|
|||||||
// Ignore; cookie will naturally expire if removal fails
|
// 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');
|
await api.put('/admin/notifications/read-all');
|
||||||
},
|
},
|
||||||
|
|
||||||
// Clear old notifications
|
// Clear all notifications
|
||||||
async clearOldNotifications(): Promise<{ deletedCount: number }> {
|
async clearAllNotifications(): Promise<{ deletedCount: number }> {
|
||||||
const response = await api.delete('/admin/notifications/clear-old');
|
const response = await api.delete('/admin/notifications/clear-all');
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -133,6 +133,10 @@ export const notificationsService = {
|
|||||||
return t('admin.notificationMessages.generalSettingsUpdated');
|
return t('admin.notificationMessages.generalSettingsUpdated');
|
||||||
case 'security_settings_updated':
|
case 'security_settings_updated':
|
||||||
return t('admin.notificationMessages.securitySettingsUpdated');
|
return t('admin.notificationMessages.securitySettingsUpdated');
|
||||||
|
case 'admin_profile_updated':
|
||||||
|
return t('admin.notificationMessages.adminProfileUpdated', {
|
||||||
|
actorName: notification.actorName,
|
||||||
|
});
|
||||||
case 'theme_updated':
|
case 'theme_updated':
|
||||||
return t('admin.notificationMessages.themeUpdated');
|
return t('admin.notificationMessages.themeUpdated');
|
||||||
case 'archive_downloaded':
|
case 'archive_downloaded':
|
||||||
@@ -184,6 +188,8 @@ export const notificationsService = {
|
|||||||
case 'security_settings_updated':
|
case 'security_settings_updated':
|
||||||
case 'theme_updated':
|
case 'theme_updated':
|
||||||
return { icon: 'Settings', color: 'text-gray-600' };
|
return { icon: 'Settings', color: 'text-gray-600' };
|
||||||
|
case 'admin_profile_updated':
|
||||||
|
return { icon: 'User', color: 'text-primary-600' };
|
||||||
case 'email_template_updated':
|
case 'email_template_updated':
|
||||||
case 'email_config_updated':
|
case 'email_config_updated':
|
||||||
return { icon: 'Mail', color: 'text-teal-600' };
|
return { icon: 'Mail', color: 'text-teal-600' };
|
||||||
@@ -209,4 +215,4 @@ export const notificationsService = {
|
|||||||
return { icon: 'Bell', color: 'text-gray-600' };
|
return { icon: 'Bell', color: 'text-gray-600' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
+108
-20
@@ -2,39 +2,126 @@
|
|||||||
* Utility functions for URL handling in production environments
|
* 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
|
* 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.
|
||||||
* @returns The API base URL
|
* @returns The API base URL
|
||||||
*/
|
*/
|
||||||
export const getApiBaseUrl = (): string => {
|
export const getApiBaseUrl = (): string => {
|
||||||
// If VITE_API_URL is explicitly set, use it
|
const envUrl = getEnvApiUrl();
|
||||||
if (import.meta.env.VITE_API_URL && import.meta.env.VITE_API_URL !== '/api') {
|
|
||||||
return import.meta.env.VITE_API_URL;
|
if (envUrl && envUrl !== '/api') {
|
||||||
|
if (ABSOLUTE_URL_REGEX.test(envUrl) && shouldFallbackToRelative(envUrl)) {
|
||||||
|
return '/api';
|
||||||
|
}
|
||||||
|
return envUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
// In production, use relative URL
|
|
||||||
return '/api';
|
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.)
|
* Build a full URL for resources (images, files, etc.)
|
||||||
* In production, this will use the current origin
|
* In production, this will prefer the current origin unless an absolute
|
||||||
|
* API URL is explicitly configured and applicable.
|
||||||
* @param path - The resource path
|
* @param path - The resource path
|
||||||
* @returns The full URL
|
* @returns The full URL
|
||||||
*/
|
*/
|
||||||
export const buildResourceUrl = (path: string): string => {
|
export const buildResourceUrl = (path: string): string => {
|
||||||
// Remove leading slash if present
|
if (!path) {
|
||||||
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
|
return '';
|
||||||
|
|
||||||
// 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}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// In production (relative API), use current origin
|
// Absolute paths (http/https) should generally be respected,
|
||||||
return `${window.location.origin}/${cleanPath}`;
|
// 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);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -42,5 +129,6 @@ export const buildResourceUrl = (path: string): string => {
|
|||||||
* @returns True if in production mode
|
* @returns True if in production mode
|
||||||
*/
|
*/
|
||||||
export const isProductionMode = (): boolean => {
|
export const isProductionMode = (): boolean => {
|
||||||
return !import.meta.env.VITE_API_URL || import.meta.env.VITE_API_URL === '/api';
|
const apiBase = getApiBaseUrl();
|
||||||
};
|
return !ABSOLUTE_URL_REGEX.test(apiBase);
|
||||||
|
};
|
||||||
|
|||||||
Vendored
+1
@@ -1 +1,2 @@
|
|||||||
/// <reference types="vite/client" />
|
/// <reference types="vite/client" />
|
||||||
|
/// <reference types="vitest" />
|
||||||
|
|||||||
+14
-3
@@ -1,8 +1,12 @@
|
|||||||
|
/// <reference types="vitest" />
|
||||||
|
// @ts-nocheck
|
||||||
|
|
||||||
import { defineConfig } from 'vite'
|
import { defineConfig } from 'vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
|
import type { UserConfig as VitestUserConfig } from 'vitest/config'
|
||||||
|
|
||||||
// https://vite.dev/config/
|
// https://vite.dev/config/
|
||||||
export default defineConfig({
|
const config: VitestUserConfig = {
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
build: {
|
build: {
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
@@ -15,6 +19,11 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
sourcemap: true,
|
sourcemap: true,
|
||||||
},
|
},
|
||||||
|
test: {
|
||||||
|
environment: 'jsdom',
|
||||||
|
setupFiles: './vitest.setup.ts',
|
||||||
|
globals: true
|
||||||
|
},
|
||||||
server: {
|
server: {
|
||||||
port: 5173,
|
port: 5173,
|
||||||
host: true,
|
host: true,
|
||||||
@@ -28,5 +37,7 @@ export default defineConfig({
|
|||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
})
|
}
|
||||||
|
|
||||||
|
export default defineConfig(config as any)
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
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;
|
||||||
+28
-8
@@ -383,17 +383,27 @@ setup_docker_installation() {
|
|||||||
app_dir="/home/$SUDO_USER/picpeak"
|
app_dir="/home/$SUDO_USER/picpeak"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
log_step "Creating application directory at $app_dir"
|
log_step "Preparing application directory at $app_dir"
|
||||||
mkdir -p "$app_dir"/{storage/events/{active,archived},logs,backup,config,data,events}
|
local app_parent_dir
|
||||||
|
app_parent_dir=$(dirname "$app_dir")
|
||||||
# Clone repository
|
mkdir -p "$app_parent_dir"
|
||||||
log_step "Downloading PicPeak..."
|
|
||||||
if [[ -d "$app_dir/.git" ]]; then
|
if [[ -d "$app_dir/.git" ]]; then
|
||||||
|
log_step "Existing PicPeak repository detected; pulling latest changes"
|
||||||
cd "$app_dir"
|
cd "$app_dir"
|
||||||
git pull
|
git pull --rebase --autostash || git pull
|
||||||
else
|
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"
|
git clone "$REPO_URL" "$app_dir"
|
||||||
fi
|
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)
|
# Determine host user for container mapping (PUID/PGID)
|
||||||
local host_uid host_gid
|
local host_uid host_gid
|
||||||
@@ -630,7 +640,11 @@ setup_native_installation() {
|
|||||||
apt-get install -y build-essential python3
|
apt-get install -y build-essential python3
|
||||||
;;
|
;;
|
||||||
dnf|yum)
|
dnf|yum)
|
||||||
$PACKAGE_MANAGER groupinstall -y "Development Tools"
|
if "$PACKAGE_MANAGER" --version 2>/dev/null | grep -Ei 'dnf( |-)5' >/dev/null; then
|
||||||
|
$PACKAGE_MANAGER install -y @development-tools
|
||||||
|
else
|
||||||
|
$PACKAGE_MANAGER groupinstall -y "Development Tools"
|
||||||
|
fi
|
||||||
$PACKAGE_MANAGER install -y python3
|
$PACKAGE_MANAGER install -y python3
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
@@ -1006,7 +1020,13 @@ print_success_message() {
|
|||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
||||||
echo -e "Password: ${YELLOW}(credentials file not found - rerun setup with --force-admin-password-reset or run node scripts/reset-admin-password.js manually)${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}"
|
||||||
fi
|
fi
|
||||||
echo
|
echo
|
||||||
echo -e "${YELLOW}⚠️ IMPORTANT: Change the admin password on first login!${NC}"
|
echo -e "${YELLOW}⚠️ IMPORTANT: Change the admin password on first login!${NC}"
|
||||||
|
|||||||
Reference in New Issue
Block a user