forked from geolba/tethys.backend
feat: implement activity logging and related features
Merge branch 'fix/version-chain-api' into develop - Add ActivityLogger service for logging user activities. - Create activities table migration for storing activity logs. - Update Dataset model to log dataset uploads and publications. - Enhance User model to include activities relationship. - Introduce command to fix version-related IDs in dataset references. - Modify Inertia configuration to include OpenSearch host. - Update Dashboard page to display recent activities. - Extend main store to manage activities state. - Add API route for fetching activities. - updatet Api/DatasetController.ts for correct version chaining of related datasets
This commit is contained in:
commit
f0a45a929f
21 changed files with 1101 additions and 322 deletions
|
|
@ -168,7 +168,7 @@ export default class MimetypeController {
|
||||||
mimetype,
|
mimetype,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.code == 'E_ROW_NOT_FOUND') {
|
if (error.code === 'E_ROW_NOT_FOUND') {
|
||||||
session.flash({ warning: 'Mimetype is not found in database' });
|
session.flash({ warning: 'Mimetype is not found in database' });
|
||||||
} else {
|
} else {
|
||||||
session.flash({ warning: 'general error occured, you cannot delete the mimetype' });
|
session.flash({ warning: 'general error occured, you cannot delete the mimetype' });
|
||||||
|
|
|
||||||
|
|
@ -85,8 +85,7 @@ export default class MailSettingsController {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await mail.send(
|
await mail.send((message) => {
|
||||||
(message) => {
|
|
||||||
message
|
message
|
||||||
// .from(Config.get('mail.from.address'))
|
// .from(Config.get('mail.from.address'))
|
||||||
.from('tethys@geosphere.at')
|
.from('tethys@geosphere.at')
|
||||||
|
|
|
||||||
|
|
@ -210,13 +210,13 @@ export default class DatasetController {
|
||||||
*/
|
*/
|
||||||
private async buildVersionChain(dataset: Dataset) {
|
private async buildVersionChain(dataset: Dataset) {
|
||||||
const versionChain = {
|
const versionChain = {
|
||||||
current: {
|
// current: {
|
||||||
id: dataset.id,
|
// id: dataset.id,
|
||||||
publish_id: dataset.publish_id,
|
// publish_id: dataset.publish_id,
|
||||||
doi: dataset.identifier?.value || null,
|
// doi: dataset.identifier?.value || null,
|
||||||
main_title: dataset.mainTitle || null,
|
// main_title: dataset.mainTitle || null,
|
||||||
server_date_published: dataset.server_date_published,
|
// server_date_published: dataset.server_date_published,
|
||||||
},
|
// },
|
||||||
previousVersions: [] as any[],
|
previousVersions: [] as any[],
|
||||||
newerVersions: [] as any[],
|
newerVersions: [] as any[],
|
||||||
};
|
};
|
||||||
|
|
@ -233,92 +233,181 @@ export default class DatasetController {
|
||||||
/**
|
/**
|
||||||
* Recursively get all previous versions
|
* Recursively get all previous versions
|
||||||
*/
|
*/
|
||||||
|
// private async getPreviousVersions(datasetId: number, visited: Set<number> = new Set()): Promise<any[]> {
|
||||||
|
// // Prevent infinite loops
|
||||||
|
// if (visited.has(datasetId)) {
|
||||||
|
// return [];
|
||||||
|
// }
|
||||||
|
// visited.add(datasetId);
|
||||||
|
|
||||||
|
// const previousVersions: any[] = [];
|
||||||
|
|
||||||
|
// // Find references where this dataset "IsNewVersionOf" another dataset
|
||||||
|
// const previousRefs = await DatasetReference.query()
|
||||||
|
// .where('document_id', datasetId)
|
||||||
|
// .where('relation', 'IsNewVersionOf')
|
||||||
|
// .whereNotNull('related_document_id');
|
||||||
|
|
||||||
|
// for (const ref of previousRefs) {
|
||||||
|
// if (!ref.related_document_id) continue;
|
||||||
|
|
||||||
|
// const previousDataset = await Dataset.query()
|
||||||
|
// .where('id', ref.related_document_id)
|
||||||
|
// .preload('identifier')
|
||||||
|
// .preload('titles')
|
||||||
|
// .first();
|
||||||
|
|
||||||
|
// if (previousDataset) {
|
||||||
|
// const versionInfo = {
|
||||||
|
// id: previousDataset.id,
|
||||||
|
// publish_id: previousDataset.publish_id,
|
||||||
|
// doi: previousDataset.identifier?.value || null,
|
||||||
|
// main_title: previousDataset.mainTitle || null,
|
||||||
|
// server_date_published: previousDataset.server_date_published,
|
||||||
|
// relation: 'IsPreviousVersionOf', // From perspective of current dataset
|
||||||
|
// };
|
||||||
|
|
||||||
|
// previousVersions.push(versionInfo);
|
||||||
|
|
||||||
|
// // Recursively get even older versions
|
||||||
|
// const olderVersions = await this.getPreviousVersions(previousDataset.id, visited);
|
||||||
|
// previousVersions.push(...olderVersions);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return previousVersions;
|
||||||
|
// }
|
||||||
|
|
||||||
private async getPreviousVersions(datasetId: number, visited: Set<number> = new Set()): Promise<any[]> {
|
private async getPreviousVersions(datasetId: number, visited: Set<number> = new Set()): Promise<any[]> {
|
||||||
// Prevent infinite loops
|
if (visited.has(datasetId)) return [];
|
||||||
if (visited.has(datasetId)) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
visited.add(datasetId);
|
visited.add(datasetId);
|
||||||
|
|
||||||
const previousVersions: any[] = [];
|
const result: any[] = [];
|
||||||
|
|
||||||
// Find references where this dataset "IsNewVersionOf" another dataset
|
// A dataset points to its OLDER version via relation 'IsNewVersionOf'
|
||||||
const previousRefs = await DatasetReference.query()
|
const refs = await DatasetReference.query()
|
||||||
.where('document_id', datasetId)
|
.where('document_id', datasetId)
|
||||||
.where('relation', 'IsNewVersionOf')
|
.where('relation', 'IsNewVersionOf'); // ← removed .whereNotNull('related_document_id')
|
||||||
.whereNotNull('related_document_id');
|
|
||||||
|
|
||||||
for (const ref of previousRefs) {
|
for (const ref of refs) {
|
||||||
if (!ref.related_document_id) continue;
|
const related = await this.resolveReferencedDataset(ref, datasetId);
|
||||||
|
if (!related) continue;
|
||||||
|
|
||||||
const previousDataset = await Dataset.query()
|
result.push({
|
||||||
.where('id', ref.related_document_id)
|
id: related.id,
|
||||||
.preload('identifier')
|
publish_id: related.publish_id,
|
||||||
.preload('titles')
|
doi: related.identifier?.value || null,
|
||||||
.first();
|
main_title: related.mainTitle || null,
|
||||||
|
server_date_published: related.server_date_published,
|
||||||
|
relation: 'IsPreviousVersionOf',
|
||||||
|
});
|
||||||
|
|
||||||
if (previousDataset) {
|
result.push(...(await this.getPreviousVersions(related.id, visited)));
|
||||||
const versionInfo = {
|
|
||||||
id: previousDataset.id,
|
|
||||||
publish_id: previousDataset.publish_id,
|
|
||||||
doi: previousDataset.identifier?.value || null,
|
|
||||||
main_title: previousDataset.mainTitle || null,
|
|
||||||
server_date_published: previousDataset.server_date_published,
|
|
||||||
relation: 'IsPreviousVersionOf', // From perspective of current dataset
|
|
||||||
};
|
|
||||||
|
|
||||||
previousVersions.push(versionInfo);
|
|
||||||
|
|
||||||
// Recursively get even older versions
|
|
||||||
const olderVersions = await this.getPreviousVersions(previousDataset.id, visited);
|
|
||||||
previousVersions.push(...olderVersions);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return previousVersions;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recursively get all newer versions
|
* Recursively get all newer versions
|
||||||
*/
|
*/
|
||||||
|
// private async getNewerVersions(datasetId: number, visited: Set<number> = new Set()): Promise<any[]> {
|
||||||
|
// // Prevent infinite loops
|
||||||
|
// if (visited.has(datasetId)) {
|
||||||
|
// return [];
|
||||||
|
// }
|
||||||
|
// visited.add(datasetId);
|
||||||
|
|
||||||
|
// const newerVersions: any[] = [];
|
||||||
|
|
||||||
|
// // Find references where this dataset "IsPreviousVersionOf" another dataset
|
||||||
|
// const newerRefs = await DatasetReference.query()
|
||||||
|
// .where('document_id', datasetId)
|
||||||
|
// .where('relation', 'IsPreviousVersionOf')
|
||||||
|
// .whereNotNull('related_document_id');
|
||||||
|
|
||||||
|
// for (const ref of newerRefs) {
|
||||||
|
// if (!ref.related_document_id) continue;
|
||||||
|
|
||||||
|
// const newerDataset = await Dataset.query().where('id', ref.related_document_id).preload('identifier').preload('titles').first();
|
||||||
|
|
||||||
|
// if (newerDataset) {
|
||||||
|
// const versionInfo = {
|
||||||
|
// id: newerDataset.id,
|
||||||
|
// publish_id: newerDataset.publish_id,
|
||||||
|
// doi: newerDataset.identifier?.value || null,
|
||||||
|
// main_title: newerDataset.mainTitle || null,
|
||||||
|
// server_date_published: newerDataset.server_date_published,
|
||||||
|
// relation: 'IsNewVersionOf', // From perspective of current dataset
|
||||||
|
// };
|
||||||
|
|
||||||
|
// newerVersions.push(versionInfo);
|
||||||
|
|
||||||
|
// // Recursively get even newer versions
|
||||||
|
// const evenNewerVersions = await this.getNewerVersions(newerDataset.id, visited);
|
||||||
|
// newerVersions.push(...evenNewerVersions);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return newerVersions;
|
||||||
|
// }
|
||||||
private async getNewerVersions(datasetId: number, visited: Set<number> = new Set()): Promise<any[]> {
|
private async getNewerVersions(datasetId: number, visited: Set<number> = new Set()): Promise<any[]> {
|
||||||
// Prevent infinite loops
|
if (visited.has(datasetId)) return [];
|
||||||
if (visited.has(datasetId)) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
visited.add(datasetId);
|
visited.add(datasetId);
|
||||||
|
|
||||||
const newerVersions: any[] = [];
|
const result: any[] = [];
|
||||||
|
|
||||||
// Find references where this dataset "IsPreviousVersionOf" another dataset
|
// A dataset points to its NEWER version via relation 'IsPreviousVersionOf'
|
||||||
const newerRefs = await DatasetReference.query()
|
const refs = await DatasetReference.query()
|
||||||
.where('document_id', datasetId)
|
.where('document_id', datasetId)
|
||||||
.where('relation', 'IsPreviousVersionOf')
|
.where('relation', 'IsPreviousVersionOf'); // ← removed .whereNotNull(...)
|
||||||
.whereNotNull('related_document_id');
|
|
||||||
|
|
||||||
for (const ref of newerRefs) {
|
for (const ref of refs) {
|
||||||
if (!ref.related_document_id) continue;
|
const related = await this.resolveReferencedDataset(ref, datasetId);
|
||||||
|
if (!related) continue;
|
||||||
|
|
||||||
const newerDataset = await Dataset.query().where('id', ref.related_document_id).preload('identifier').preload('titles').first();
|
result.push({
|
||||||
|
id: related.id,
|
||||||
|
publish_id: related.publish_id,
|
||||||
|
doi: related.identifier?.value || null,
|
||||||
|
main_title: related.mainTitle || null,
|
||||||
|
server_date_published: related.server_date_published,
|
||||||
|
relation: 'IsNewVersionOf',
|
||||||
|
});
|
||||||
|
|
||||||
if (newerDataset) {
|
result.push(...(await this.getNewerVersions(related.id, visited)));
|
||||||
const versionInfo = {
|
|
||||||
id: newerDataset.id,
|
|
||||||
publish_id: newerDataset.publish_id,
|
|
||||||
doi: newerDataset.identifier?.value || null,
|
|
||||||
main_title: newerDataset.mainTitle || null,
|
|
||||||
server_date_published: newerDataset.server_date_published,
|
|
||||||
relation: 'IsNewVersionOf', // From perspective of current dataset
|
|
||||||
};
|
|
||||||
|
|
||||||
newerVersions.push(versionInfo);
|
|
||||||
|
|
||||||
// Recursively get even newer versions
|
|
||||||
const evenNewerVersions = await this.getNewerVersions(newerDataset.id, visited);
|
|
||||||
newerVersions.push(...evenNewerVersions);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return newerVersions;
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveReferencedDataset(ref: DatasetReference, currentDatasetId: number) {
|
||||||
|
const doi = this.normalizeDoi(ref.value);
|
||||||
|
|
||||||
|
if (doi) {
|
||||||
|
const byDoi = await Dataset.query()
|
||||||
|
.whereHas('identifier', (q) => q.where('value', doi))
|
||||||
|
.preload('identifier')
|
||||||
|
.preload('titles') // needed so mainTitle computes
|
||||||
|
.first();
|
||||||
|
if (byDoi) return byDoi;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ref.related_document_id && ref.related_document_id !== currentDatasetId) {
|
||||||
|
return await Dataset.query()
|
||||||
|
.where('id', ref.related_document_id)
|
||||||
|
.preload('identifier')
|
||||||
|
.preload('titles')
|
||||||
|
.first();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
private normalizeDoi(value: string | null): string | null {
|
||||||
|
if (!value) return null;
|
||||||
|
return value
|
||||||
|
.trim()
|
||||||
|
.replace(/^https?:\/\/(dx\.)?doi\.org\//i, '')
|
||||||
|
.replace(/^doi:/i, '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,70 +1,46 @@
|
||||||
import type { HttpContext } from '@adonisjs/core/http';
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
import User from '#models/user';
|
import User from '#models/user';
|
||||||
import BackupCode from '#models/backup_code';
|
import BackupCode from '#models/backup_code';
|
||||||
// import Hash from '@ioc:Adonis/Core/Hash';
|
|
||||||
// import InvalidCredentialException from 'App/Exceptions/InvalidCredentialException';
|
|
||||||
import { authValidator } from '#validators/auth';
|
import { authValidator } from '#validators/auth';
|
||||||
import hash from '@adonisjs/core/services/hash';
|
import hash from '@adonisjs/core/services/hash';
|
||||||
import db from '@adonisjs/lucid/services/db';
|
import db from '@adonisjs/lucid/services/db';
|
||||||
import TwoFactorAuthProvider from '#app/services/TwoFactorAuthProvider';
|
import TwoFactorAuthProvider from '#app/services/TwoFactorAuthProvider';
|
||||||
// import { Authenticator } from '@adonisjs/auth';
|
import ActivityLogger from '#services/activity_logger';
|
||||||
// import { LoginState } from 'Contracts/enums';
|
import logger from '@adonisjs/core/services/logger';
|
||||||
// import { StatusCodes } from 'http-status-codes';
|
|
||||||
|
|
||||||
// interface MyHttpsContext extends HttpContext {
|
|
||||||
// auth: Authenticator<User>
|
|
||||||
// }
|
|
||||||
export default class AuthController {
|
export default class AuthController {
|
||||||
// login function{ request, auth, response }:HttpContext
|
|
||||||
public async login({ request, response, auth, session }: HttpContext) {
|
public async login({ request, response, auth, session }: HttpContext) {
|
||||||
// console.log({
|
|
||||||
// registerBody: request.body(),
|
|
||||||
// });
|
|
||||||
// await request.validate(AuthValidator);
|
|
||||||
await request.validateUsing(authValidator);
|
await request.validateUsing(authValidator);
|
||||||
|
|
||||||
// const plainPassword = await request.input('password');
|
|
||||||
// const email = await request.input('email');
|
|
||||||
// grab uid and password values off request body
|
|
||||||
const { email, password } = request.only(['email', 'password']);
|
const { email, password } = request.only(['email', 'password']);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
await db.connection().rawQuery('SELECT 1');
|
||||||
|
|
||||||
await db.connection().rawQuery('SELECT 1')
|
|
||||||
|
|
||||||
|
|
||||||
// // attempt to verify credential and login user
|
|
||||||
// await auth.use('web').attempt(email, plainPassword);
|
|
||||||
|
|
||||||
// const user = await auth.use('web').verifyCredentials(email, password);
|
|
||||||
const user = await User.verifyCredentials(email, password);
|
const user = await User.verifyCredentials(email, password);
|
||||||
|
|
||||||
if (user.isTwoFactorEnabled) {
|
if (user.isTwoFactorEnabled) {
|
||||||
// session.put("login.id", user.id);
|
// Noch KEIN abgeschlossenes Login -> nicht loggen.
|
||||||
// return view.render("pages/two-factor-challenge");
|
|
||||||
|
|
||||||
session.flash('user_id', user.id);
|
session.flash('user_id', user.id);
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
|
|
||||||
// let state = LoginState.STATE_VALIDATED;
|
|
||||||
// return response.status(StatusCodes.OK).json({
|
|
||||||
// state: state,
|
|
||||||
// new_user_id: user.id,
|
|
||||||
// });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await auth.use('web').login(user);
|
await auth.use('web').login(user);
|
||||||
} catch (error) {
|
this.recordAuthEvent('auth.login', { user, ip: request.ip() });
|
||||||
|
} catch (error: any) {
|
||||||
|
// DB nicht erreichbar -> kein fehlgeschlagener Login-Versuch, weiterwerfen
|
||||||
if (error.code === 'ECONNREFUSED') {
|
if (error.code === 'ECONNREFUSED') {
|
||||||
throw error
|
throw error;
|
||||||
}
|
}
|
||||||
// if login fails, return vague form message and redirect back
|
|
||||||
|
// Echter Credential-Fehler -> als fehlgeschlagenen Versuch protokollieren
|
||||||
|
this.recordAuthEvent('auth.login_failed', { email, ip: request.ip() });
|
||||||
|
|
||||||
session.flash('message', 'Your username, email, or password is incorrect');
|
session.flash('message', 'Your username, email, or password is incorrect');
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
|
|
||||||
// otherwise, redirect todashboard
|
return response.redirect('/apps/dashboard');
|
||||||
response.redirect('/apps/dashboard');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async twoFactorChallenge({ request, session, auth, response }: HttpContext) {
|
public async twoFactorChallenge({ request, session, auth, response }: HttpContext) {
|
||||||
|
|
@ -74,27 +50,19 @@ export default class AuthController {
|
||||||
if (code) {
|
if (code) {
|
||||||
const isValid = await TwoFactorAuthProvider.validate(user, code);
|
const isValid = await TwoFactorAuthProvider.validate(user, code);
|
||||||
if (isValid) {
|
if (isValid) {
|
||||||
// login user and redirect to dashboard
|
|
||||||
await auth.use('web').login(user);
|
await auth.use('web').login(user);
|
||||||
response.redirect('/apps/dashboard');
|
this.recordAuthEvent('auth.login', { user, email: user.email, ip: request.ip(), method: '2fa_totp' });
|
||||||
} else {
|
return response.redirect('/apps/dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
session.flash('message', 'Your two-factor code is incorrect');
|
session.flash('message', 'Your two-factor code is incorrect');
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
} else if (backup_code) {
|
|
||||||
|
if (backup_code) {
|
||||||
const codes: BackupCode[] = await user.getBackupCodes();
|
const codes: BackupCode[] = await user.getBackupCodes();
|
||||||
|
|
||||||
// const verifiedBackupCodes = await Promise.all(
|
let backupCodeToDelete: BackupCode | null = null;
|
||||||
// codes.map(async (backupCode) => {
|
|
||||||
// let isVerified = await hash.verify(backupCode.code, backup_code);
|
|
||||||
// if (isVerified) {
|
|
||||||
// return backupCode;
|
|
||||||
// }
|
|
||||||
// }),
|
|
||||||
// );
|
|
||||||
// const backupCodeToDelete = verifiedBackupCodes.find(Boolean);
|
|
||||||
|
|
||||||
let backupCodeToDelete = null;
|
|
||||||
for (const backupCode of codes) {
|
for (const backupCode of codes) {
|
||||||
const isVerified = await hash.verify(backupCode.code, backup_code);
|
const isVerified = await hash.verify(backupCode.code, backup_code);
|
||||||
if (isVerified) {
|
if (isVerified) {
|
||||||
|
|
@ -103,29 +71,68 @@ export default class AuthController {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (backupCodeToDelete) {
|
if (!backupCodeToDelete) {
|
||||||
if (backupCodeToDelete.used === false) {
|
|
||||||
backupCodeToDelete.used = true;
|
|
||||||
await backupCodeToDelete.save();
|
|
||||||
console.log(`BackupCode with id ${backupCodeToDelete.id} has been marked as used.`);
|
|
||||||
await auth.use('web').login(user);
|
|
||||||
response.redirect('/apps/dashboard');
|
|
||||||
} else {
|
|
||||||
session.flash('message', 'BackupCode already used');
|
|
||||||
return response.redirect().back();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
session.flash('message', 'BackupCode not found');
|
session.flash('message', 'BackupCode not found');
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
if (backupCodeToDelete.used) {
|
||||||
|
session.flash('message', 'BackupCode already used');
|
||||||
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
|
|
||||||
// logout function
|
backupCodeToDelete.used = true;
|
||||||
public async logout({ auth, response }: HttpContext) {
|
await backupCodeToDelete.save();
|
||||||
// await auth.logout();
|
|
||||||
|
await auth.use('web').login(user);
|
||||||
|
this.recordAuthEvent('auth.login', { user, email: user.email, ip: request.ip(), method: '2fa_backup_code' });
|
||||||
|
|
||||||
|
return response.redirect('/apps/dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Weder code noch backup_code übergeben
|
||||||
|
session.flash('message', 'No verification code provided');
|
||||||
|
return response.redirect().back();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async logout({ auth, request, response }: HttpContext) {
|
||||||
|
// Session auflösen -> füllt auth.user, falls eingeloggt
|
||||||
|
await auth.use('web').check();
|
||||||
|
const user = auth.use('web').user;
|
||||||
|
|
||||||
await auth.use('web').logout();
|
await auth.use('web').logout();
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
this.recordAuthEvent('auth.logout', { user, email: user.email, ip: request.ip() });
|
||||||
|
}
|
||||||
|
|
||||||
return response.redirect('/app/login');
|
return response.redirect('/app/login');
|
||||||
// return response.status(200);
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zentraler Audit-Logger für Auth-Events.
|
||||||
|
* Fire-and-forget: ein Fehler beim Schreiben darf Login/Logout nie blockieren.
|
||||||
|
*/
|
||||||
|
private recordAuthEvent(
|
||||||
|
type: 'auth.login' | 'auth.logout' | 'auth.login_failed',
|
||||||
|
opts: { user?: User; email?: string; ip: string; method?: string },
|
||||||
|
) {
|
||||||
|
const { user, email, ip, method } = opts;
|
||||||
|
|
||||||
|
const description =
|
||||||
|
type === 'auth.login'
|
||||||
|
? `${user!.firstName} ${user!.lastName} signed in`
|
||||||
|
: type === 'auth.logout'
|
||||||
|
? `${user!.firstName} ${user!.lastName} signed out`
|
||||||
|
: `Failed login attempt for ${email ?? 'unknown'}`;
|
||||||
|
|
||||||
|
void ActivityLogger.log({
|
||||||
|
type,
|
||||||
|
description,
|
||||||
|
userId: user?.id ?? null,
|
||||||
|
subjectType: user ? 'User' : null,
|
||||||
|
subjectId: user?.id ?? null,
|
||||||
|
properties: { ip, ...(method ? { method } : {}) },
|
||||||
|
}).catch((err) => logger.error({ err }, `failed to record ${type} activity`));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import type { HttpContext } from '@adonisjs/core/http';
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
// import { RequestContract } from '@ioc:Adonis/Core/Request';
|
|
||||||
import { Request } from '@adonisjs/core/http';
|
import { Request } from '@adonisjs/core/http';
|
||||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||||
import { create } from 'xmlbuilder2';
|
import { create } from 'xmlbuilder2';
|
||||||
|
|
@ -18,11 +17,8 @@ import { getDomain, preg_match } from '#app/utils/utility-functions';
|
||||||
import DatasetXmlSerializer from '#app/Library/DatasetXmlSerializer';
|
import DatasetXmlSerializer from '#app/Library/DatasetXmlSerializer';
|
||||||
import logger from '@adonisjs/core/services/logger';
|
import logger from '@adonisjs/core/services/logger';
|
||||||
import ResumptionToken from '#app/Library/Oai/ResumptionToken';
|
import ResumptionToken from '#app/Library/Oai/ResumptionToken';
|
||||||
// import Config from '@ioc:Adonis/Core/Config';
|
|
||||||
import config from '@adonisjs/core/services/config';
|
import config from '@adonisjs/core/services/config';
|
||||||
// import { inject } from '@adonisjs/fold';
|
|
||||||
import { inject } from '@adonisjs/core';
|
import { inject } from '@adonisjs/core';
|
||||||
// import { TokenWorkerContract } from "MyApp/Models/TokenWorker";
|
|
||||||
import TokenWorkerContract from '#library/Oai/TokenWorkerContract';
|
import TokenWorkerContract from '#library/Oai/TokenWorkerContract';
|
||||||
import { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model';
|
import { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model';
|
||||||
|
|
||||||
|
|
@ -83,13 +79,13 @@ export default class OaiController {
|
||||||
xsltParameter['oai_error_message'] = 'Only POST and GET methods are allowed for OAI-PMH.';
|
xsltParameter['oai_error_message'] = 'Only POST and GET methods are allowed for OAI-PMH.';
|
||||||
}
|
}
|
||||||
|
|
||||||
let earliestDateFromDb;
|
|
||||||
// const oaiRequest: OaiParameter = request.body;
|
// const oaiRequest: OaiParameter = request.body;
|
||||||
try {
|
try {
|
||||||
this.firstPublishedDataset = await Dataset.earliestPublicationDate();
|
this.firstPublishedDataset = await Dataset.earliestPublicationDate();
|
||||||
this.firstPublishedDataset != null &&
|
// Pflichtfeld laut OAI-PMH: auch bei leerem Repository einen validen
|
||||||
(earliestDateFromDb = this.firstPublishedDataset.server_date_published.toFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
|
// UTCdatetime liefern, sonst entsteht ein ungültiges leeres Element.
|
||||||
this.xsltParameter['earliestDatestamp'] = earliestDateFromDb;
|
this.xsltParameter['earliestDatestamp'] =
|
||||||
|
this.firstPublishedDataset?.server_date_published.toFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") ?? '1970-01-01T00:00:00Z';
|
||||||
// start the request
|
// start the request
|
||||||
await this.handleRequest(oaiRequest, request);
|
await this.handleRequest(oaiRequest, request);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -122,7 +118,7 @@ export default class OaiController {
|
||||||
// logLevel: 10,
|
// logLevel: 10,
|
||||||
});
|
});
|
||||||
xmlOutput = result.principalResult;
|
xmlOutput = result.principalResult;
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
return response.status(500).json({
|
return response.status(500).json({
|
||||||
message: 'An error occurred while creating the user',
|
message: 'An error occurred while creating the user',
|
||||||
error: error.message,
|
error: error.message,
|
||||||
|
|
@ -157,7 +153,7 @@ export default class OaiController {
|
||||||
const verb = oaiRequest['verb'];
|
const verb = oaiRequest['verb'];
|
||||||
this.xsltParameter['oai_verb'] = verb;
|
this.xsltParameter['oai_verb'] = verb;
|
||||||
if (verb === 'Identify') {
|
if (verb === 'Identify') {
|
||||||
this.handleIdentify();
|
this.handleIdentify(oaiRequest);
|
||||||
} else if (verb === 'ListMetadataFormats') {
|
} else if (verb === 'ListMetadataFormats') {
|
||||||
this.handleListMetadataFormats();
|
this.handleListMetadataFormats();
|
||||||
} else if (verb == 'GetRecord') {
|
} else if (verb == 'GetRecord') {
|
||||||
|
|
@ -184,7 +180,10 @@ export default class OaiController {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected handleIdentify() {
|
protected handleIdentify(oaiRequest: Dictionary) {
|
||||||
|
// OAI-PMH: Identify akzeptiert außer `verb` keine Argumente.
|
||||||
|
this.assertOnlyVerb(oaiRequest);
|
||||||
|
|
||||||
// Get configuration values from environment or a dedicated configuration service
|
// Get configuration values from environment or a dedicated configuration service
|
||||||
const email = process.env.OAI_EMAIL ?? 'repository@geosphere.at';
|
const email = process.env.OAI_EMAIL ?? 'repository@geosphere.at';
|
||||||
const repositoryName = process.env.OAI_REPOSITORY_NAME ?? 'Tethys RDR';
|
const repositoryName = process.env.OAI_REPOSITORY_NAME ?? 'Tethys RDR';
|
||||||
|
|
@ -203,6 +202,21 @@ export default class OaiController {
|
||||||
this.xml.root().ele('Datasets');
|
this.xml.root().ele('Datasets');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wirft badArgument, wenn der Request andere Parameter als `verb` enthält.
|
||||||
|
* Für Verben ohne zusätzliche Argumente (Identify, ListSets, ListMetadataFormats).
|
||||||
|
*/
|
||||||
|
private assertOnlyVerb(oaiRequest: Dictionary) {
|
||||||
|
const illegalKeys = Object.keys(oaiRequest).filter((key) => key !== 'verb');
|
||||||
|
if (illegalKeys.length > 0) {
|
||||||
|
throw new OaiModelException(
|
||||||
|
StatusCodes.BAD_REQUEST,
|
||||||
|
`The request includes illegal arguments: ${illegalKeys.join(', ')}.`,
|
||||||
|
OaiErrorCodes.BADARGUMENT,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protected handleListMetadataFormats() {
|
protected handleListMetadataFormats() {
|
||||||
this.xml.root().ele('Datasets');
|
this.xml.root().ele('Datasets');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,8 @@ import type { Multipart } from '@adonisjs/bodyparser';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import { parseBytesSize, getConfigFor, getTmpPath, formatBytes, errorMessage } from '#app/utils/utility-functions';
|
import { parseBytesSize, getConfigFor, getTmpPath, formatBytes, errorMessage } from '#app/utils/utility-functions';
|
||||||
import validation from '#services/validation_service';
|
import validation from '#services/validation_service';
|
||||||
|
import ActivityLogger from '#services/activity_logger';
|
||||||
|
import logger from '@adonisjs/core/services/logger';
|
||||||
|
|
||||||
interface Dictionary {
|
interface Dictionary {
|
||||||
[index: string]: string;
|
[index: string]: string;
|
||||||
|
|
@ -469,9 +471,7 @@ export default class DatasetController {
|
||||||
console.error('Error cleaning up temporary file:', cleanupError);
|
console.error('Error cleaning up temporary file:', cleanupError);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
request.multipart.abort(
|
request.multipart.abort(validation.make('files', `Upload limit of ${formatBytes(aggregatedLimit)} exceeded.`, 'limit'));
|
||||||
validation.make('files', `Upload limit of ${formatBytes(aggregatedLimit)} exceeded.`, 'limit')
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -513,10 +513,21 @@ export default class DatasetController {
|
||||||
trx = await db.transaction();
|
trx = await db.transaction();
|
||||||
const user = (await User.find(auth.user?.id)) as User;
|
const user = (await User.find(auth.user?.id)) as User;
|
||||||
|
|
||||||
await this.createDatasetAndAssociations(user, request, trx);
|
// await this.createDatasetAndAssociations(user, request, trx);
|
||||||
|
const { dataset, mainTitle } = await this.createDatasetAndAssociations(user, request, trx);
|
||||||
|
|
||||||
await trx.commit();
|
await trx.commit();
|
||||||
console.log('Dataset and related models created successfully');
|
console.log('Dataset and related models created successfully');
|
||||||
|
|
||||||
|
// NACH dem Commit: Dataset ist garantiert persistiert, keine Waisen-Gefahr.
|
||||||
|
// Fire-and-forget, damit ein Log-Fehler den bereits erfolgreichen Upload nicht kippt.
|
||||||
|
void ActivityLogger.log({
|
||||||
|
type: 'dataset.uploaded',
|
||||||
|
description: `New publication uploaded: ${mainTitle ?? 'Untitled'}`,
|
||||||
|
userId: user.id,
|
||||||
|
subjectType: 'Dataset',
|
||||||
|
subjectId: dataset.id,
|
||||||
|
}).catch((err) => logger.error({ err }, 'failed to record dataset.uploaded activity'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Clean up temporary files if validation or later steps fail
|
// Clean up temporary files if validation or later steps fail
|
||||||
uploadedTmpFiles.forEach((tmpPath) => {
|
uploadedTmpFiles.forEach((tmpPath) => {
|
||||||
|
|
@ -564,6 +575,15 @@ export default class DatasetController {
|
||||||
await this.savePersons(dataset, request.input('contributors', []), 'contributor', trx);
|
await this.savePersons(dataset, request.input('contributors', []), 'contributor', trx);
|
||||||
|
|
||||||
//save main and additional titles
|
//save main and additional titles
|
||||||
|
// const titles = request.input('titles', []);
|
||||||
|
// for (const titleData of titles) {
|
||||||
|
// const title = new Title();
|
||||||
|
// title.value = titleData.value;
|
||||||
|
// title.language = titleData.language;
|
||||||
|
// title.type = titleData.type;
|
||||||
|
// await dataset.useTransaction(trx).related('titles').save(title);
|
||||||
|
// }
|
||||||
|
let mainTitle: string | null = null;
|
||||||
const titles = request.input('titles', []);
|
const titles = request.input('titles', []);
|
||||||
for (const titleData of titles) {
|
for (const titleData of titles) {
|
||||||
const title = new Title();
|
const title = new Title();
|
||||||
|
|
@ -571,6 +591,11 @@ export default class DatasetController {
|
||||||
title.language = titleData.language;
|
title.language = titleData.language;
|
||||||
title.type = titleData.type;
|
title.type = titleData.type;
|
||||||
await dataset.useTransaction(trx).related('titles').save(title);
|
await dataset.useTransaction(trx).related('titles').save(title);
|
||||||
|
|
||||||
|
if (titleData.type === 'Main') {
|
||||||
|
// <-- an eure Typ-Konvention anpassen
|
||||||
|
mainTitle = titleData.value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// save descriptions
|
// save descriptions
|
||||||
|
|
@ -664,6 +689,8 @@ export default class DatasetController {
|
||||||
await dataset.useTransaction(trx).related('files').save(newFile);
|
await dataset.useTransaction(trx).related('files').save(newFile);
|
||||||
await newFile.createHashValues(trx);
|
await newFile.createHashValues(trx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return { dataset, mainTitle }; // <-- statt void
|
||||||
}
|
}
|
||||||
|
|
||||||
private generateRandomString(length: number): string {
|
private generateRandomString(length: number): string {
|
||||||
|
|
@ -1095,7 +1122,7 @@ export default class DatasetController {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const error = new errors.E_VALIDATION_ERROR({
|
const error = new errors.E_VALIDATION_ERROR({
|
||||||
'files': `Aggregated upload limit of ${formatBytes(aggregatedLimit)} exceeded. The total size of files being uploaded would exceed the limit.`,
|
files: `Aggregated upload limit of ${formatBytes(aggregatedLimit)} exceeded. The total size of files being uploaded would exceed the limit.`,
|
||||||
});
|
});
|
||||||
request.multipart.abort(error);
|
request.multipart.abort(error);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
43
app/controllers/activities_controller.ts
Normal file
43
app/controllers/activities_controller.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
// app/controllers/activities_controller.ts
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import Activity from '#models/activity';
|
||||||
|
|
||||||
|
export default class ActivitiesController {
|
||||||
|
async index({ response }: HttpContext) {
|
||||||
|
// const activities = await Activity.query()
|
||||||
|
// .preload('user', (q) => q.select('id', 'login'))
|
||||||
|
// .orderBy('created_at', 'desc')
|
||||||
|
// .limit(10);
|
||||||
|
|
||||||
|
// return response.json(
|
||||||
|
// activities.map((a) => ({
|
||||||
|
// id: a.id,
|
||||||
|
// type: a.type,
|
||||||
|
// description: a.description,
|
||||||
|
// user: a.user?.login ?? null,
|
||||||
|
// created_at: a.createdAt.toISO(), // relativeTime() expects ISO
|
||||||
|
// })),
|
||||||
|
// );
|
||||||
|
try {
|
||||||
|
const activities = await Activity.query()
|
||||||
|
.preload('user', (q) => q.select('id', 'login'))
|
||||||
|
.orderBy('created_at', 'desc')
|
||||||
|
.limit(10);
|
||||||
|
|
||||||
|
return response.json(
|
||||||
|
activities.map((a) => ({
|
||||||
|
id: a.id,
|
||||||
|
type: a.type,
|
||||||
|
description: a.description,
|
||||||
|
user: a.user?.login ?? null,
|
||||||
|
created_at: a.createdAt.toISO(), // relativeTime() expects ISO
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching activities:', error);
|
||||||
|
return response.status(500).json({ error: 'Internal Server Error' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
57
app/models/activity.ts
Normal file
57
app/models/activity.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
// app/models/activity.ts
|
||||||
|
import { DateTime } from 'luxon';
|
||||||
|
import { belongsTo, column } from '@adonisjs/lucid/orm';
|
||||||
|
import BaseModel from './base_model.js';
|
||||||
|
import type { BelongsTo } from '@adonisjs/lucid/types/relations';
|
||||||
|
import User from '#models/user';
|
||||||
|
import { SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||||
|
|
||||||
|
export default class Activity extends BaseModel {
|
||||||
|
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||||
|
public static primaryKey = 'id';
|
||||||
|
public static table = 'activities';
|
||||||
|
|
||||||
|
@column({ isPrimary: true })
|
||||||
|
declare id: number;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare type: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare userId: number | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare subjectType: string | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare subjectId: number | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare description: string;
|
||||||
|
|
||||||
|
// Manual JSON (de)serialization keeps this working on SQLite/MySQL.
|
||||||
|
// On Postgres json/jsonb the driver already parses — drop the `consume`
|
||||||
|
// JSON.parse there to avoid double-handling.
|
||||||
|
// @column({
|
||||||
|
// prepare: (value: Record<string, any> | null) => (value ? JSON.stringify(value) : null),
|
||||||
|
// consume: (value: string | null) => (value ? JSON.parse(value) : null),
|
||||||
|
// })
|
||||||
|
// declare properties: Record<string, any> | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare properties: Record<string, any> | null;
|
||||||
|
|
||||||
|
@column.dateTime({ autoCreate: true })
|
||||||
|
declare createdAt: DateTime;
|
||||||
|
|
||||||
|
@column.dateTime({ autoCreate: true, autoUpdate: true })
|
||||||
|
declare updatedAt: DateTime;
|
||||||
|
|
||||||
|
// @belongsTo(() => User)
|
||||||
|
// declare user: BelongsTo<typeof User>;
|
||||||
|
|
||||||
|
@belongsTo(() => User, {
|
||||||
|
foreignKey: 'userId',
|
||||||
|
})
|
||||||
|
declare user: BelongsTo<typeof User>;
|
||||||
|
}
|
||||||
|
|
@ -5,7 +5,10 @@ import {
|
||||||
belongsTo,
|
belongsTo,
|
||||||
hasMany,
|
hasMany,
|
||||||
computed,
|
computed,
|
||||||
hasOne
|
hasOne,
|
||||||
|
afterCreate,
|
||||||
|
beforeUpdate,
|
||||||
|
afterUpdate,
|
||||||
} from '@adonisjs/lucid/orm';
|
} from '@adonisjs/lucid/orm';
|
||||||
import { DateTime } from 'luxon';
|
import { DateTime } from 'luxon';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
|
|
@ -23,10 +26,11 @@ import DatasetIdentifier from './dataset_identifier.js';
|
||||||
import Project from './project.js';
|
import Project from './project.js';
|
||||||
import DocumentXmlCache from './DocumentXmlCache.js';
|
import DocumentXmlCache from './DocumentXmlCache.js';
|
||||||
import DatasetExtension from '#models/traits/dataset_extension';
|
import DatasetExtension from '#models/traits/dataset_extension';
|
||||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
import type { ManyToMany } from '@adonisjs/lucid/types/relations';
|
||||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
import type { BelongsTo } from '@adonisjs/lucid/types/relations';
|
||||||
import type { HasMany } from "@adonisjs/lucid/types/relations";
|
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
||||||
import type { HasOne } from "@adonisjs/lucid/types/relations";
|
import type { HasOne } from '@adonisjs/lucid/types/relations';
|
||||||
|
import ActivityLogger from '#services/activity_logger';
|
||||||
|
|
||||||
export default class Dataset extends DatasetExtension {
|
export default class Dataset extends DatasetExtension {
|
||||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||||
|
|
@ -267,7 +271,9 @@ export default class Dataset extends DatasetExtension {
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getMax(column: string) {
|
static async getMax(column: string) {
|
||||||
let dataset = await this.query().max(column + ' as max_publish_id').firstOrFail();
|
let dataset = await this.query()
|
||||||
|
.max(column + ' as max_publish_id')
|
||||||
|
.firstOrFail();
|
||||||
return dataset.$extras.max_publish_id;
|
return dataset.$extras.max_publish_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -284,4 +290,34 @@ export default class Dataset extends DatasetExtension {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// @afterCreate()
|
||||||
|
// static async logUploaded(dataset: Dataset) {
|
||||||
|
// await dataset.preload('titles');
|
||||||
|
|
||||||
|
// await ActivityLogger.log({
|
||||||
|
// type: 'dataset.uploaded',
|
||||||
|
// description: `New publication uploaded: ${dataset.mainTitle ?? 'Untitled'}`,
|
||||||
|
// subjectType: 'Dataset',
|
||||||
|
// subjectId: dataset.id,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
@beforeUpdate()
|
||||||
|
static capturePublish(dataset: Dataset) {
|
||||||
|
// $dirty is populated here, before persistence
|
||||||
|
(dataset as any).$becamePublished = dataset.$dirty.status !== undefined && dataset.status === 'published';
|
||||||
|
}
|
||||||
|
|
||||||
|
@afterUpdate()
|
||||||
|
static async logPublished(dataset: Dataset) {
|
||||||
|
if ((dataset as any).$becamePublished) {
|
||||||
|
await ActivityLogger.log({
|
||||||
|
type: 'dataset.published',
|
||||||
|
description: `Publication published: ${dataset.mainTitle}`,
|
||||||
|
subjectType: 'Dataset',
|
||||||
|
subjectId: dataset.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import type { ManyToMany } from '@adonisjs/lucid/types/relations';
|
||||||
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
||||||
import { compose } from '@adonisjs/core/helpers';
|
import { compose } from '@adonisjs/core/helpers';
|
||||||
import BackupCode from './backup_code.js';
|
import BackupCode from './backup_code.js';
|
||||||
|
import Activity from './activity.js';
|
||||||
|
|
||||||
const AuthFinder = withAuthFinder(() => hash.use('laravel'), {
|
const AuthFinder = withAuthFinder(() => hash.use('laravel'), {
|
||||||
uids: ['email'],
|
uids: ['email'],
|
||||||
|
|
@ -111,6 +112,11 @@ export default class User extends compose(BaseModel, AuthFinder) {
|
||||||
})
|
})
|
||||||
public backupcodes: HasMany<typeof BackupCode>;
|
public backupcodes: HasMany<typeof BackupCode>;
|
||||||
|
|
||||||
|
@hasMany(() => Activity, {
|
||||||
|
foreignKey: 'user_id',
|
||||||
|
})
|
||||||
|
public activities: HasMany<typeof Activity>;
|
||||||
|
|
||||||
@computed({
|
@computed({
|
||||||
serializeAs: 'is_admin',
|
serializeAs: 'is_admin',
|
||||||
})
|
})
|
||||||
|
|
|
||||||
27
app/services/activity_logger.ts
Normal file
27
app/services/activity_logger.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
// app/services/activity_logger.ts
|
||||||
|
import Activity from '#models/activity'
|
||||||
|
|
||||||
|
interface LogOptions {
|
||||||
|
type: string
|
||||||
|
description: string
|
||||||
|
userId?: number | null
|
||||||
|
subjectType?: string | null
|
||||||
|
subjectId?: number | string | null
|
||||||
|
properties?: Record<string, any>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class ActivityLogger {
|
||||||
|
static async log(options: LogOptions): Promise<void> {
|
||||||
|
await Activity.create({
|
||||||
|
type: options.type,
|
||||||
|
description: options.description,
|
||||||
|
userId: options.userId ?? null,
|
||||||
|
subjectType: options.subjectType ?? null,
|
||||||
|
subjectId: options.subjectId != null ? Number(options.subjectId) : null,
|
||||||
|
properties: options.properties ?? null,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Invalidate the cache if you add one (see Redis section).
|
||||||
|
// await redis.del('activities:recent')
|
||||||
|
}
|
||||||
|
}
|
||||||
189
commands/fix_version_related_ids.ts
Normal file
189
commands/fix_version_related_ids.ts
Normal file
|
|
@ -0,0 +1,189 @@
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| node ace make:command fix-version-related-ids
|
||||||
|
| DONE: create commands/fix_version_related_ids.ts
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Repairs the `related_document_id` foreign key on version references
|
||||||
|
| (IsNewVersionOf / IsPreviousVersionOf, both directions).
|
||||||
|
|
|
||||||
|
| The DOI stored in `value` is the reliable link; `related_document_id`
|
||||||
|
| is frequently NULL or self-referential. This command resolves the target
|
||||||
|
| dataset via its DOI and sets `related_document_id` accordingly, correcting
|
||||||
|
| both NULL and wrong-but-non-null values.
|
||||||
|
|
|
||||||
|
| Examples:
|
||||||
|
| node ace fix:version-related-ids // dry run, all datasets
|
||||||
|
| node ace fix:version-related-ids --verbose // dry run with per-row detail
|
||||||
|
| node ace fix:version-related-ids --fix // apply changes
|
||||||
|
| node ace fix:version-related-ids --fix -p 226 // apply, only refs owned by publish_id 226
|
||||||
|
*/
|
||||||
|
import { BaseCommand, flags } from '@adonisjs/core/ace';
|
||||||
|
import type { CommandOptions } from '@adonisjs/core/types/ace';
|
||||||
|
import Dataset from '#models/dataset';
|
||||||
|
import DatasetReference from '#models/dataset_reference';
|
||||||
|
|
||||||
|
export default class FixVersionRelatedIds extends BaseCommand {
|
||||||
|
static commandName = 'fix:version-related-ids';
|
||||||
|
static description =
|
||||||
|
'Backfill/repair related_document_id on IsNewVersionOf / IsPreviousVersionOf references by resolving the target dataset via its DOI';
|
||||||
|
|
||||||
|
public static needsApplication = true;
|
||||||
|
|
||||||
|
@flags.boolean({ alias: 'f', description: 'Apply changes. Without this flag the command runs as a dry run.' })
|
||||||
|
public fix: boolean = false;
|
||||||
|
|
||||||
|
@flags.boolean({ alias: 'v', description: 'Verbose output (per-reference detail)' })
|
||||||
|
public verbose: boolean = false;
|
||||||
|
|
||||||
|
@flags.number({ alias: 'p', description: 'Only process references owned by this publish_id' })
|
||||||
|
public publish_id?: number;
|
||||||
|
|
||||||
|
public static options: CommandOptions = {
|
||||||
|
startApp: true,
|
||||||
|
staysAlive: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Only the version relations, both directions.
|
||||||
|
private readonly VERSION_RELATIONS = ['IsNewVersionOf', 'IsPreviousVersionOf'];
|
||||||
|
|
||||||
|
async run() {
|
||||||
|
this.logger.info(`🔍 Scanning ${this.VERSION_RELATIONS.join(' / ')} references...`);
|
||||||
|
this.logger.info(this.fix ? '✏️ Mode: APPLY (changes will be written)' : '👀 Mode: DRY RUN (no changes written)');
|
||||||
|
if (typeof this.publish_id === 'number') {
|
||||||
|
this.logger.info(`🎯 Filtering by owning publish_id: ${this.publish_id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const query = DatasetReference.query()
|
||||||
|
.whereIn('relation', this.VERSION_RELATIONS)
|
||||||
|
.whereIn('type', ['DOI', 'URL'])
|
||||||
|
.where((q) => {
|
||||||
|
q.where('value', 'like', '%doi.org/10.24341/tethys.%').orWhere('value', 'like', '%tethys.at/dataset/%');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Restrict to references owned by a specific dataset (by publish_id), if requested.
|
||||||
|
if (typeof this.publish_id === 'number') {
|
||||||
|
query.whereHas('dataset', (d) => d.where('publish_id', this.publish_id as number));
|
||||||
|
}
|
||||||
|
|
||||||
|
const refs = await query.exec();
|
||||||
|
this.logger.info(`🔗 Found ${refs.length} version reference(s) to inspect`);
|
||||||
|
|
||||||
|
let alreadyCorrect = 0;
|
||||||
|
let filledFromNull = 0;
|
||||||
|
let correctedWrong = 0;
|
||||||
|
let unresolved = 0;
|
||||||
|
|
||||||
|
for (const ref of refs) {
|
||||||
|
const target = await this.resolveTarget(ref);
|
||||||
|
|
||||||
|
if (!target) {
|
||||||
|
unresolved++;
|
||||||
|
if (this.verbose) {
|
||||||
|
this.logger.warning(`⚠️ Reference ${ref.id}: could not resolve target (value: ${ref.value})`);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Never let a reference point at its own owning document.
|
||||||
|
if (target.id === ref.document_id) {
|
||||||
|
unresolved++;
|
||||||
|
if (this.verbose) {
|
||||||
|
this.logger.warning(
|
||||||
|
`⚠️ Reference ${ref.id}: target resolves to its own document (${ref.document_id}); skipping self-link`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ref.related_document_id === target.id) {
|
||||||
|
alreadyCorrect++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const previous = ref.related_document_id;
|
||||||
|
const wasNull = previous === null || previous === undefined;
|
||||||
|
|
||||||
|
if (this.fix) {
|
||||||
|
ref.related_document_id = target.id;
|
||||||
|
await ref.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasNull) {
|
||||||
|
filledFromNull++;
|
||||||
|
} else {
|
||||||
|
correctedWrong++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.verbose) {
|
||||||
|
const action = this.fix ? 'Updated' : '📝 Would update';
|
||||||
|
this.logger.info(
|
||||||
|
`${action} reference ${ref.id} (doc ${ref.document_id}, ${ref.relation}): ` +
|
||||||
|
`related_document_id ${previous ?? 'NULL'} → ${target.id} (publish_id ${target.publish_id})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.info('────────────────────────────────────────');
|
||||||
|
this.logger.info(`✔️ Already correct: ${alreadyCorrect}`);
|
||||||
|
this.logger.info(`➕ Filled from NULL: ${filledFromNull}`);
|
||||||
|
this.logger.info(`🔧 Corrected wrong value: ${correctedWrong}`);
|
||||||
|
this.logger.info(`⚠️ Unresolved/skipped: ${unresolved}`);
|
||||||
|
this.logger.info('────────────────────────────────────────');
|
||||||
|
|
||||||
|
const changes = filledFromNull + correctedWrong;
|
||||||
|
if (!this.fix && changes > 0) {
|
||||||
|
this.logger.info(`💡 Dry run only. Re-run with --fix to write ${changes} change(s).`);
|
||||||
|
} else if (this.fix) {
|
||||||
|
this.logger.success(`Done. ${changes} reference(s) updated.`);
|
||||||
|
} else {
|
||||||
|
this.logger.success('Nothing to change — all version references already linked correctly.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('Error fixing version related_document_id values:', error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the dataset a version reference points to.
|
||||||
|
* Prefers the DOI in `value` (reliable); falls back to a tethys publish_id URL.
|
||||||
|
*/
|
||||||
|
private async resolveTarget(ref: DatasetReference): Promise<Dataset | null> {
|
||||||
|
const doi = this.normalizeDoi(ref.value);
|
||||||
|
if (doi) {
|
||||||
|
const byDoi = await Dataset.query()
|
||||||
|
.whereHas('identifier', (q) => q.where('value', doi))
|
||||||
|
.first();
|
||||||
|
if (byDoi) return byDoi;
|
||||||
|
}
|
||||||
|
|
||||||
|
const publishId = this.extractPublishId(ref.value);
|
||||||
|
if (publishId) {
|
||||||
|
const byPublishId = await Dataset.query().where('publish_id', publishId).first();
|
||||||
|
if (byPublishId) return byPublishId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strip the resolver prefix so a reference value like
|
||||||
|
* "https://doi.org/10.24341/tethys.108.2" matches the identifier
|
||||||
|
* table value "10.24341/tethys.108.2". Returns null if it isn't a DOI.
|
||||||
|
*/
|
||||||
|
private normalizeDoi(value: string | null): string | null {
|
||||||
|
if (!value) return null;
|
||||||
|
const cleaned = value
|
||||||
|
.trim()
|
||||||
|
.replace(/^https?:\/\/(dx\.)?doi\.org\//i, '')
|
||||||
|
.replace(/^doi:/i, '');
|
||||||
|
return /^10\.\d{4,}\//.test(cleaned) ? cleaned : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractPublishId(value: string | null): number | null {
|
||||||
|
if (!value) return null;
|
||||||
|
const urlMatch = value.match(/tethys\.at\/dataset\/(\d+)/);
|
||||||
|
return urlMatch ? parseInt(urlMatch[1], 10) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { defineConfig } from '@adonisjs/inertia';
|
import { defineConfig } from '@adonisjs/inertia';
|
||||||
import type { HttpContext } from '@adonisjs/core/http';
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
import type { InferSharedProps } from '@adonisjs/inertia/types'
|
import type { InferSharedProps } from '@adonisjs/inertia/types';
|
||||||
|
import env from '#start/env';
|
||||||
|
|
||||||
const inertiaConfig = defineConfig({
|
const inertiaConfig = defineConfig({
|
||||||
/**
|
/**
|
||||||
|
|
@ -21,6 +22,8 @@ const inertiaConfig = defineConfig({
|
||||||
return ctx.session?.flashMessages.get('user_id');
|
return ctx.session?.flashMessages.get('user_id');
|
||||||
},
|
},
|
||||||
|
|
||||||
|
opensearch_host: env.get('OPENSEARCH_HOST'),
|
||||||
|
|
||||||
flash: (ctx) => {
|
flash: (ctx) => {
|
||||||
return {
|
return {
|
||||||
message: ctx.session?.flashMessages.get('message'),
|
message: ctx.session?.flashMessages.get('message'),
|
||||||
|
|
|
||||||
25
database/migrations/1782294801884_create_activities_table.ts
Normal file
25
database/migrations/1782294801884_create_activities_table.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class extends BaseSchema {
|
||||||
|
protected tableName = 'activities';
|
||||||
|
|
||||||
|
async up() {
|
||||||
|
this.schema.createTable(this.tableName, (table) => {
|
||||||
|
table.increments('id');
|
||||||
|
table.string('type').notNullable().index(); // 'dataset.uploaded', 'auth.login'
|
||||||
|
table.integer('user_id').unsigned().nullable().references('id').inTable('accounts').onDelete('SET NULL');
|
||||||
|
table.string('subject_type').nullable(); // manual morph: model name
|
||||||
|
table.bigInteger('subject_id').unsigned().nullable();
|
||||||
|
table.string('description').notNullable();
|
||||||
|
table.json('properties').nullable();
|
||||||
|
table.timestamp('created_at');
|
||||||
|
table.timestamp('updated_at');
|
||||||
|
table.index(['subject_type', 'subject_id'])
|
||||||
|
table.index('created_at')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.dropTable(this.tableName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, onUnmounted, ref, Ref, computed } from 'vue';
|
import { onMounted, onUnmounted, ref, computed } from 'vue';
|
||||||
import SectionMain from '@/Components/SectionMain.vue';
|
import SectionMain from '@/Components/SectionMain.vue';
|
||||||
import L, {
|
import L, {
|
||||||
Map as LeafletMap,
|
Map as LeafletMap,
|
||||||
|
|
@ -11,63 +11,63 @@ import L, {
|
||||||
type LatLngBounds,
|
type LatLngBounds,
|
||||||
type LatLngBoundsExpression,
|
type LatLngBoundsExpression,
|
||||||
type MapOptions,
|
type MapOptions,
|
||||||
type Renderer,
|
|
||||||
type RendererOptions,
|
|
||||||
type LeafletEvent,
|
type LeafletEvent,
|
||||||
|
TileLayer,
|
||||||
} from 'leaflet';
|
} from 'leaflet';
|
||||||
import { tileLayerWMS } from 'leaflet/src/layer/tile/TileLayer.WMS';
|
// import { tileLayerWMS } from 'leaflet/src/layer/tile/TileLayer.WMS';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import DrawControlComponent from '@/Components/Map/draw.component.vue';
|
import DrawControlComponent from '@/Components/Map/draw.component.vue';
|
||||||
import ZoomControlComponent from '@/Components/Map/zoom.component.vue';
|
import ZoomControlComponent from '@/Components/Map/zoom.component.vue';
|
||||||
import { MapService } from '@/Stores/map.service';
|
import { MapService } from '@/Stores/map.service';
|
||||||
import { OpensearchDocument } from '@/Dataset';
|
import { OpensearchDocument } from '@/Dataset';
|
||||||
|
import { usePage } from '@inertiajs/vue3';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Leaflet's internal renderer machinery is not part of the public @types/leaflet
|
* Leaflet's internal renderer machinery is not part of the public @types/leaflet
|
||||||
* surface, so we describe the bits we touch here. This keeps the mixin body typed
|
* surface, so we describe the bits we touch here. This keeps the mixin body typed
|
||||||
* instead of falling back to `any`.
|
* instead of falling back to `any`.
|
||||||
*/
|
*/
|
||||||
interface RendererCapableMap extends LeafletMap {
|
// interface RendererCapableMap extends LeafletMap {
|
||||||
options: MapOptions & { renderer?: Renderer; preferCanvas?: boolean };
|
// options: MapOptions & { renderer?: Renderer; preferCanvas?: boolean };
|
||||||
_renderer?: Renderer;
|
// _renderer?: Renderer;
|
||||||
_paneRenderers: Record<string, Renderer | undefined>;
|
// _paneRenderers: Record<string, Renderer | undefined>;
|
||||||
_getPaneRenderer(name?: string): Renderer | false;
|
// _getPaneRenderer(name?: string): Renderer | false;
|
||||||
_createRenderer(options?: RendererOptions): Renderer;
|
// _createRenderer(options?: RendererOptions): Renderer;
|
||||||
}
|
// }
|
||||||
|
|
||||||
LeafletMap.include({
|
// LeafletMap.include({
|
||||||
getRenderer(this: RendererCapableMap, layer: Layer): Renderer {
|
// getRenderer(this: RendererCapableMap, layer: Layer): Renderer {
|
||||||
const layerOptions = layer.options as { renderer?: Renderer; pane?: string };
|
// const layerOptions = layer.options as { renderer?: Renderer; pane?: string };
|
||||||
let renderer: Renderer | false | undefined =
|
// let renderer: Renderer | false | undefined =
|
||||||
layerOptions.renderer || this._getPaneRenderer(layerOptions.pane) || this.options.renderer || this._renderer;
|
// layerOptions.renderer || this._getPaneRenderer(layerOptions.pane) || this.options.renderer || this._renderer;
|
||||||
|
|
||||||
if (!renderer) {
|
// if (!renderer) {
|
||||||
renderer = this._renderer = this._createRenderer();
|
// renderer = this._renderer = this._createRenderer();
|
||||||
}
|
// }
|
||||||
|
|
||||||
if (!this.hasLayer(renderer)) {
|
// if (!this.hasLayer(renderer)) {
|
||||||
this.addLayer(renderer);
|
// this.addLayer(renderer);
|
||||||
}
|
// }
|
||||||
return renderer;
|
// return renderer;
|
||||||
},
|
// },
|
||||||
|
|
||||||
_getPaneRenderer(this: RendererCapableMap, name?: string): Renderer | false {
|
// _getPaneRenderer(this: RendererCapableMap, name?: string): Renderer | false {
|
||||||
if (name === 'overlayPane' || name === undefined) {
|
// if (name === 'overlayPane' || name === undefined) {
|
||||||
return false;
|
// return false;
|
||||||
}
|
// }
|
||||||
|
|
||||||
let renderer = this._paneRenderers[name];
|
// let renderer = this._paneRenderers[name];
|
||||||
if (renderer === undefined) {
|
// if (renderer === undefined) {
|
||||||
renderer = this._createRenderer({ pane: name });
|
// renderer = this._createRenderer({ pane: name });
|
||||||
this._paneRenderers[name] = renderer;
|
// this._paneRenderers[name] = renderer;
|
||||||
}
|
// }
|
||||||
return renderer;
|
// return renderer;
|
||||||
},
|
// },
|
||||||
|
|
||||||
_createRenderer(this: RendererCapableMap, options?: RendererOptions): Renderer {
|
// _createRenderer(this: RendererCapableMap, options?: RendererOptions): Renderer {
|
||||||
return (this.options.preferCanvas && L.canvas(options)) || L.svg(options);
|
// return (this.options.preferCanvas && L.canvas(options)) || L.svg(options);
|
||||||
},
|
// },
|
||||||
});
|
// });
|
||||||
|
|
||||||
const DEFAULT_BASE_LAYER_NAME = 'BaseLayer';
|
const DEFAULT_BASE_LAYER_NAME = 'BaseLayer';
|
||||||
const DEFAULT_BASE_LAYER_ATTRIBUTION = '© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors';
|
const DEFAULT_BASE_LAYER_ATTRIBUTION = '© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors';
|
||||||
|
|
@ -86,10 +86,10 @@ const props = defineProps({
|
||||||
},
|
},
|
||||||
// OpenSearch host is provided by the server (prop / shared data), never imported
|
// OpenSearch host is provided by the server (prop / shared data), never imported
|
||||||
// from server-only modules into client code.
|
// from server-only modules into client code.
|
||||||
opensearchHost: {
|
// opensearchHost: {
|
||||||
type: String,
|
// type: String,
|
||||||
default: 'localhost',
|
// default: 'http://localhost:9200',
|
||||||
},
|
// },
|
||||||
mapOptions: {
|
mapOptions: {
|
||||||
type: Object,
|
type: Object,
|
||||||
default: () => ({
|
default: () => ({
|
||||||
|
|
@ -101,7 +101,8 @@ const props = defineProps({
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const OPENSEARCH_HOST = computed(() => `${window.location.protocol}//${props.opensearchHost}:9200`);
|
// const OPENSEARCH_HOST = computed(() => `${props.opensearchHost}`);
|
||||||
|
const opensearchHost = computed(() => usePage().props.opensearch_host)
|
||||||
|
|
||||||
const items = computed<OpensearchDocument[]>({
|
const items = computed<OpensearchDocument[]>({
|
||||||
get() {
|
get() {
|
||||||
|
|
@ -170,7 +171,7 @@ const initMap = async (): Promise<void> => {
|
||||||
const attributionControl = new Control.Attribution().addTo(map);
|
const attributionControl = new Control.Attribution().addTo(map);
|
||||||
attributionControl.setPrefix(false);
|
attributionControl.setPrefix(false);
|
||||||
|
|
||||||
const osmGray = tileLayerWMS('https://ows.terrestris.de/osm-gray/service', {
|
const osmGray = new TileLayer.WMS('https://ows.terrestris.de/osm-gray/service', {
|
||||||
format: 'image/png',
|
format: 'image/png',
|
||||||
attribution: DEFAULT_BASE_LAYER_ATTRIBUTION,
|
attribution: DEFAULT_BASE_LAYER_ATTRIBUTION,
|
||||||
layers: 'OSM-WMS',
|
layers: 'OSM-WMS',
|
||||||
|
|
@ -199,7 +200,7 @@ const handleDrawEventCreated = async (event: DrawCreatedEvent): Promise<void> =>
|
||||||
// drop the request body on GET, which would send an empty query.
|
// drop the request body on GET, which would send an empty query.
|
||||||
const response = await axios<OpenSearchSearchResponse>({
|
const response = await axios<OpenSearchSearchResponse>({
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
url: OPENSEARCH_HOST.value + '/tethys-records/_search',
|
url: opensearchHost.value + '/tethys-records/_search',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
data: {
|
data: {
|
||||||
size: 1000,
|
size: 1000,
|
||||||
|
|
|
||||||
|
|
@ -210,3 +210,12 @@ export interface Identifier {
|
||||||
// STATE_VALIDATED = 1,
|
// STATE_VALIDATED = 1,
|
||||||
// STATE_2FA_AUTHENTICATED = 1,
|
// STATE_2FA_AUTHENTICATED = 1,
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
// resources/js/Dataset.ts (oder wo User definiert ist)
|
||||||
|
export interface Activity {
|
||||||
|
id: number | string;
|
||||||
|
type: string;
|
||||||
|
description: string;
|
||||||
|
user: string | null;
|
||||||
|
created_at: string; // ISO-String, relativeTime() erwartet das
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { Head, usePage } from '@inertiajs/vue3';
|
import { Head, Link, usePage } from '@inertiajs/vue3';
|
||||||
import { computed, ref } from 'vue';
|
import { computed, onMounted, ref } from 'vue';
|
||||||
import { MainService } from '@/Stores/main';
|
import { MainService } from '@/Stores/main';
|
||||||
import {
|
import {
|
||||||
mdiAccountMultiple,
|
mdiAccountMultiple,
|
||||||
|
|
@ -11,6 +11,16 @@ import {
|
||||||
mdiReload,
|
mdiReload,
|
||||||
mdiChartPie,
|
mdiChartPie,
|
||||||
mdiTrendingUp,
|
mdiTrendingUp,
|
||||||
|
mdiShieldCrownOutline,
|
||||||
|
mdiClipboardClockOutline,
|
||||||
|
mdiAccountCheckOutline,
|
||||||
|
mdiLightningBoltOutline,
|
||||||
|
mdiHistory,
|
||||||
|
mdiAccountCogOutline,
|
||||||
|
mdiAccountEditOutline,
|
||||||
|
mdiFileDocumentEditOutline,
|
||||||
|
mdiMapSearchOutline,
|
||||||
|
mdiArrowRight,
|
||||||
} from '@mdi/js';
|
} from '@mdi/js';
|
||||||
import LineChart from '@/Components/Charts/LineChart.vue';
|
import LineChart from '@/Components/Charts/LineChart.vue';
|
||||||
import SectionMain from '@/Components/SectionMain.vue';
|
import SectionMain from '@/Components/SectionMain.vue';
|
||||||
|
|
@ -21,12 +31,25 @@ import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
|
||||||
import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.vue';
|
import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.vue';
|
||||||
import CardBoxDataset from '@/Components/CardBoxDataset.vue';
|
import CardBoxDataset from '@/Components/CardBoxDataset.vue';
|
||||||
import type { User } from '@/Dataset';
|
import type { User } from '@/Dataset';
|
||||||
|
import { stardust } from '@eidellev/adonis-stardust/client';
|
||||||
|
import type { Activity } from '@/Dataset';
|
||||||
|
|
||||||
const mainService = MainService();
|
const mainService = MainService();
|
||||||
|
|
||||||
const isLoadingChart = ref(false);
|
const isLoadingChart = ref(false);
|
||||||
|
const loadError = ref<string | null>(null);
|
||||||
|
|
||||||
const fillChartData = async () => {
|
const chartData = computed(() => mainService.graphData);
|
||||||
|
const authors = computed(() => mainService.authors);
|
||||||
|
const datasets = computed(() => mainService.datasets);
|
||||||
|
const recentDatasets = computed(() => mainService.datasets.slice(0, 5));
|
||||||
|
const submitters = computed(() => mainService.clients);
|
||||||
|
const user = computed(() => usePage().props.authUser as User);
|
||||||
|
|
||||||
|
// Single source of truth for chart loading, used by both the initial
|
||||||
|
// fetch and the manual refresh so the loading state is always shown.
|
||||||
|
const loadChart = async () => {
|
||||||
|
if (isLoadingChart.value) return; // guard against overlapping requests
|
||||||
isLoadingChart.value = true;
|
isLoadingChart.value = true;
|
||||||
try {
|
try {
|
||||||
await mainService.fetchChartData();
|
await mainService.fetchChartData();
|
||||||
|
|
@ -35,35 +58,149 @@ const fillChartData = async () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const chartData = computed(() => mainService.graphData);
|
// Fetch everything once the component is mounted (avoids running during SSR
|
||||||
const authors = computed(() => mainService.authors);
|
// and as unhandled top-level side effects). Requests run in parallel.
|
||||||
const datasets = computed(() => mainService.datasets);
|
onMounted(async () => {
|
||||||
const datasetBarItems = computed(() => mainService.datasets.slice(0, 5));
|
try {
|
||||||
const submitters = computed(() => mainService.clients);
|
await Promise.all([
|
||||||
const user = computed(() => usePage().props.authUser as User);
|
mainService.fetchApi('clients'),
|
||||||
|
mainService.fetchApi('authors'),
|
||||||
// Initialize data
|
mainService.fetchApi('datasets'),
|
||||||
mainService.fetchApi('clients');
|
mainService.fetchApi('activities'),
|
||||||
mainService.fetchApi('authors');
|
loadChart(),
|
||||||
mainService.fetchApi('datasets');
|
]);
|
||||||
mainService.fetchChartData();
|
} catch (e) {
|
||||||
|
loadError.value = 'Failed to load dashboard data. Please try refreshing.';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Safe role check: authUser or its roles may be absent depending on auth state
|
// Safe role check: authUser or its roles may be absent depending on auth state
|
||||||
const userHasRoles = (roleNames: Array<string>): boolean => {
|
const userHasRoles = (roleNames: Array<string>): boolean => {
|
||||||
return user.value?.roles?.some((role) => roleNames.includes(role)) ?? false;
|
return user.value?.roles?.some((role) => roleNames.includes(role)) ?? false;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Greeting that adapts to the time of day
|
const isAdmin = computed(() => userHasRoles(['administrator']));
|
||||||
const greeting = computed(() => {
|
|
||||||
const h = new Date().getHours();
|
// Evaluated once at setup — these don't need to be reactive for a dashboard
|
||||||
|
// that isn't expected to stay open across a time-of-day boundary.
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
const greeting = (() => {
|
||||||
|
const h = now.getHours();
|
||||||
if (h < 12) return 'Good morning';
|
if (h < 12) return 'Good morning';
|
||||||
if (h < 18) return 'Good afternoon';
|
if (h < 18) return 'Good afternoon';
|
||||||
return 'Good evening';
|
return 'Good evening';
|
||||||
|
})();
|
||||||
|
|
||||||
|
const today = now.toLocaleDateString(undefined, {
|
||||||
|
weekday: 'long',
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric',
|
||||||
});
|
});
|
||||||
|
|
||||||
const today = computed(() =>
|
// ---------------------------------------------------------------------------
|
||||||
new Date().toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }),
|
// Admin overview
|
||||||
);
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Derived from data already in the store. `status` is read defensively; if your
|
||||||
|
// dataset model doesn't expose it these fall back to 0 — point them at real
|
||||||
|
// store fields (e.g. a dedicated `mainService.pendingCount`) when available.
|
||||||
|
const pendingCount = computed(() => mainService.datasets.filter((d: any) => d?.status === 'approved').length);
|
||||||
|
|
||||||
|
const adminStats = computed(() => [
|
||||||
|
{
|
||||||
|
label: 'Active Submitters',
|
||||||
|
value: submitters.value.length,
|
||||||
|
icon: mdiAccountCheckOutline,
|
||||||
|
border: 'border-emerald-500',
|
||||||
|
iconColor: 'text-emerald-500',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Publications',
|
||||||
|
value: datasets.value.length,
|
||||||
|
icon: mdiDatabaseOutline,
|
||||||
|
border: 'border-blue-500',
|
||||||
|
iconColor: 'text-blue-500',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Authors',
|
||||||
|
value: authors.value.length,
|
||||||
|
icon: mdiAccountMultiple,
|
||||||
|
border: 'border-purple-500',
|
||||||
|
iconColor: 'text-purple-500',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Pending Review',
|
||||||
|
value: pendingCount.value,
|
||||||
|
icon: mdiClipboardClockOutline,
|
||||||
|
border: 'border-amber-500',
|
||||||
|
iconColor: 'text-amber-500',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Ziggy's route() throws for unknown names and may be undefined if Ziggy isn't
|
||||||
|
// installed — resolve safely so a missing route never crashes the dashboard.
|
||||||
|
const safeRoute = (name: string, params?: any): string => {
|
||||||
|
try {
|
||||||
|
// @ts-ignore - Ziggy global
|
||||||
|
return typeof stardust.route === 'function' ? stardust.route(name, params) : '#';
|
||||||
|
} catch {
|
||||||
|
return '#';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Adjust the route names below to match your application's named routes.
|
||||||
|
const quickActions = [
|
||||||
|
{
|
||||||
|
label: 'Manage Tethys Accounts',
|
||||||
|
description: 'View and edit Tethys accounts',
|
||||||
|
icon: mdiAccountCogOutline,
|
||||||
|
href: safeRoute('settings.user.index'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Manage Tethys Roles',
|
||||||
|
description: 'Edit Tethys roles',
|
||||||
|
icon: mdiAccountEditOutline,
|
||||||
|
href: safeRoute('settings.role.index'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Review Publications',
|
||||||
|
description: 'Approve or reject submissions',
|
||||||
|
icon: mdiFileDocumentEditOutline,
|
||||||
|
href: safeRoute('editor.dataset.list'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Geographic Search',
|
||||||
|
description: 'Search datasets by location',
|
||||||
|
icon: mdiMapSearchOutline,
|
||||||
|
href: safeRoute('apps.map'),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// type Activity = {
|
||||||
|
// id: number | string;
|
||||||
|
// description: string;
|
||||||
|
// user?: string;
|
||||||
|
// created_at: string;
|
||||||
|
// };
|
||||||
|
|
||||||
|
// Reads from the store if your backend provides it; otherwise renders an empty
|
||||||
|
// state. Populate via e.g. mainService.fetchApi('activities') in onMounted.
|
||||||
|
const recentActivity = computed<Activity[]>(() => mainService.activities);
|
||||||
|
|
||||||
|
const relativeTime = (iso: string): string => {
|
||||||
|
const then = new Date(iso).getTime();
|
||||||
|
if (Number.isNaN(then)) return '';
|
||||||
|
const mins = Math.round((Date.now() - then) / 60000);
|
||||||
|
if (mins < 1) return 'just now';
|
||||||
|
if (mins < 60) return `${mins}m ago`;
|
||||||
|
const hrs = Math.round(mins / 60);
|
||||||
|
if (hrs < 24) return `${hrs}h ago`;
|
||||||
|
const days = Math.round(hrs / 24);
|
||||||
|
if (days < 7) return `${days}d ago`;
|
||||||
|
return new Date(iso).toLocaleDateString();
|
||||||
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
@ -75,10 +212,10 @@ const today = computed(() =>
|
||||||
<div
|
<div
|
||||||
class="reveal relative overflow-hidden rounded-2xl mb-8 p-6 md:p-8 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white shadow-xl ring-1 ring-white/5"
|
class="reveal relative overflow-hidden rounded-2xl mb-8 p-6 md:p-8 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white shadow-xl ring-1 ring-white/5"
|
||||||
>
|
>
|
||||||
<!-- grüner Akzent-Glow statt weißer Kreise -->
|
<!-- green accent glow -->
|
||||||
<div class="absolute -right-10 -top-10 w-48 h-48 rounded-full bg-emerald-500/15 blur-3xl"></div>
|
<div class="absolute -right-10 -top-10 w-48 h-48 rounded-full bg-emerald-500/15 blur-3xl"></div>
|
||||||
<div class="absolute -left-8 -bottom-12 w-40 h-40 rounded-full bg-green-400/10 blur-3xl"></div>
|
<div class="absolute -left-8 -bottom-12 w-40 h-40 rounded-full bg-green-400/10 blur-3xl"></div>
|
||||||
<!-- schmale Akzentkante links -->
|
<!-- thin accent edge on the left -->
|
||||||
<div class="absolute inset-y-0 left-0 w-1 bg-gradient-to-b from-green-400 to-emerald-600"></div>
|
<div class="absolute inset-y-0 left-0 w-1 bg-gradient-to-b from-green-400 to-emerald-600"></div>
|
||||||
<div class="relative">
|
<div class="relative">
|
||||||
<p class="text-sm font-medium text-slate-400">{{ today }}</p>
|
<p class="text-sm font-medium text-slate-400">{{ today }}</p>
|
||||||
|
|
@ -91,48 +228,152 @@ const today = computed(() =>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Stats Grid -->
|
<!-- Load error banner -->
|
||||||
<div class="reveal reveal-1 grid grid-cols-1 gap-6 lg:grid-cols-3 mb-8">
|
<div
|
||||||
<div class="rounded-xl border-l-4 border-emerald-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
|
v-if="loadError"
|
||||||
<CardBoxWidget
|
role="alert"
|
||||||
trend="12%"
|
class="reveal mb-8 rounded-xl border-l-4 border-red-500 bg-red-50 dark:bg-red-900/20 p-4 text-sm text-red-700 dark:text-red-300"
|
||||||
trend-type="up"
|
>
|
||||||
color="text-emerald-500"
|
{{ loadError }}
|
||||||
:icon="mdiAccountMultiple"
|
|
||||||
:number="authors.length"
|
|
||||||
label="Authors"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="rounded-xl border-l-4 border-blue-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
|
|
||||||
<CardBoxWidget
|
<!-- ============================== Admin ============================== -->
|
||||||
trend-type="info"
|
<template v-if="isAdmin">
|
||||||
color="text-blue-500"
|
<SectionTitleLineWithButton :icon="mdiShieldCrownOutline" title="Admin Overview" class="mt-10">
|
||||||
:icon="mdiDatabaseOutline"
|
<span class="text-sm text-gray-500 dark:text-gray-400">Administrator view</span>
|
||||||
:number="datasets.length"
|
</SectionTitleLineWithButton>
|
||||||
label="Publications"
|
|
||||||
/>
|
<!-- Admin KPI cards -->
|
||||||
|
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
|
||||||
|
<div
|
||||||
|
v-for="stat in adminStats"
|
||||||
|
:key="stat.label"
|
||||||
|
class="rounded-xl border-l-4 bg-white dark:bg-slate-900/40 shadow-sm p-4 flex items-center gap-4 transition-all duration-300 hover:shadow-md"
|
||||||
|
:class="stat.border"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-gray-50 dark:bg-slate-800"
|
||||||
|
:class="stat.iconColor"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" class="w-6 h-6" fill="currentColor" aria-hidden="true">
|
||||||
|
<path :d="stat.icon" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<p class="text-2xl font-bold text-gray-800 dark:text-white leading-none">
|
||||||
|
{{ stat.value }}
|
||||||
|
</p>
|
||||||
|
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ stat.label }}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="rounded-xl border-l-4 border-purple-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
|
|
||||||
<CardBoxWidget
|
|
||||||
trend-type="up"
|
|
||||||
color="text-purple-500"
|
|
||||||
:icon="mdiChartTimelineVariant"
|
|
||||||
:number="submitters.length"
|
|
||||||
label="Submitters"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Quick actions + Recent activity -->
|
||||||
|
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
|
||||||
|
<!-- Quick actions -->
|
||||||
|
<CardBox
|
||||||
|
:icon="mdiLightningBoltOutline"
|
||||||
|
:show-header-icon="false"
|
||||||
|
title="Quick Actions"
|
||||||
|
class="lg:col-span-1 shadow-lg"
|
||||||
|
>
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<Link
|
||||||
|
v-for="action in quickActions"
|
||||||
|
:key="action.label"
|
||||||
|
:href="action.href"
|
||||||
|
class="group flex items-center gap-3 rounded-lg border border-gray-100 dark:border-slate-700 p-3 hover:border-emerald-300 dark:hover:border-emerald-700 hover:bg-emerald-50/50 dark:hover:bg-emerald-900/10 transition-colors"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" class="w-5 h-5" fill="currentColor" aria-hidden="true">
|
||||||
|
<path :d="action.icon" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
<span class="min-w-0 flex-1">
|
||||||
|
<span class="block text-sm font-medium text-gray-800 dark:text-gray-100">
|
||||||
|
{{ action.label }}
|
||||||
|
</span>
|
||||||
|
<span class="block text-xs text-gray-400 truncate">{{ action.description }}</span>
|
||||||
|
</span>
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
class="w-5 h-5 text-gray-300 group-hover:text-emerald-500 group-hover:translate-x-0.5 transition-all"
|
||||||
|
fill="currentColor"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path :d="mdiArrowRight" />
|
||||||
|
</svg>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</CardBox>
|
||||||
|
|
||||||
|
<!-- Recent activity feed -->
|
||||||
|
<CardBox :icon="mdiHistory" :show-header-icon="false" title="Recent Activity" class="lg:col-span-2 shadow-lg">
|
||||||
|
<ul
|
||||||
|
v-if="recentActivity.length > 0"
|
||||||
|
class="relative space-y-5 before:absolute before:left-[7px] before:top-1 before:bottom-1 before:w-px before:bg-gray-200 dark:before:bg-slate-700"
|
||||||
|
>
|
||||||
|
<li v-for="item in recentActivity" :key="item.id" class="relative pl-7">
|
||||||
|
<span
|
||||||
|
class="absolute left-0 top-1 w-3.5 h-3.5 rounded-full bg-emerald-500 ring-4 ring-white dark:ring-slate-900"
|
||||||
|
></span>
|
||||||
|
<p class="text-sm text-gray-800 dark:text-gray-200">{{ item.description }}</p>
|
||||||
|
<p class="text-xs text-gray-400 mt-0.5">
|
||||||
|
<span v-if="item.user">{{ item.user }} · </span>
|
||||||
|
{{ relativeTime(item.created_at) }}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div v-else class="flex flex-col items-center justify-center py-10 text-center text-gray-400 dark:text-gray-500">
|
||||||
|
<svg viewBox="0 0 24 24" class="w-10 h-10 mb-2 opacity-60" fill="currentColor" aria-hidden="true">
|
||||||
|
<path :d="mdiHistory" />
|
||||||
|
</svg>
|
||||||
|
<p class="text-sm">No recent activity</p>
|
||||||
|
</div>
|
||||||
|
</CardBox>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Submitters table -->
|
||||||
|
<SectionTitleLineWithButton :icon="mdiAccountMultiple" title="Submitters Management" class="mt-8">
|
||||||
|
<span class="text-sm text-gray-500 dark:text-gray-400">All registered submitters</span>
|
||||||
|
</SectionTitleLineWithButton>
|
||||||
|
|
||||||
|
<CardBox :icon="mdiMonitorCellphone" title="All Submitters" has-table class="shadow-lg">
|
||||||
|
<TableSampleClients />
|
||||||
|
</CardBox>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Stats Grid -->
|
||||||
|
<!-- <div class="reveal reveal-1 grid grid-cols-1 gap-6 lg:grid-cols-3 mb-8">
|
||||||
|
<div
|
||||||
|
class="rounded-xl border-l-4 border-emerald-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
||||||
|
>
|
||||||
|
<CardBoxWidget color="text-emerald-500" :icon="mdiAccountMultiple" :number="authors.length" label="Authors" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="rounded-xl border-l-4 border-blue-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
||||||
|
>
|
||||||
|
<CardBoxWidget color="text-blue-500" :icon="mdiDatabaseOutline" :number="datasets.length" label="Publications" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="rounded-xl border-l-4 border-purple-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
||||||
|
>
|
||||||
|
<CardBoxWidget color="text-purple-500" :icon="mdiChartTimelineVariant" :number="submitters.length" label="Submitters" />
|
||||||
|
</div>
|
||||||
|
</div> -->
|
||||||
|
|
||||||
<!-- Recent Datasets Section -->
|
<!-- Recent Datasets Section -->
|
||||||
<div v-if="datasetBarItems.length > 0" class="reveal reveal-2 mb-8">
|
<div v-if="recentDatasets.length > 0" class="reveal reveal-2 mb-8">
|
||||||
<SectionTitleLineWithButton :icon="mdiTrendingUp" title="Recent Publications">
|
<SectionTitleLineWithButton :icon="mdiTrendingUp" title="Recent Publications">
|
||||||
<span class="text-sm text-gray-500 dark:text-gray-400">Latest {{ datasetBarItems.length }} publications</span>
|
<span class="text-sm text-gray-500 dark:text-gray-400"> Latest {{ recentDatasets.length }} publications </span>
|
||||||
</SectionTitleLineWithButton>
|
</SectionTitleLineWithButton>
|
||||||
|
|
||||||
<div class="grid grid-cols-1 gap-4">
|
<div class="grid grid-cols-1 gap-4">
|
||||||
<CardBoxDataset
|
<CardBoxDataset
|
||||||
v-for="(dataset, index) in datasetBarItems"
|
v-for="dataset in recentDatasets"
|
||||||
:key="index"
|
:key="dataset.id"
|
||||||
:dataset="dataset"
|
:dataset="dataset"
|
||||||
class="hover:shadow-md transition-all duration-300"
|
class="hover:shadow-md transition-all duration-300"
|
||||||
/>
|
/>
|
||||||
|
|
@ -149,9 +390,9 @@ const today = computed(() =>
|
||||||
:icon="mdiFinance"
|
:icon="mdiFinance"
|
||||||
:header-icon="mdiReload"
|
:header-icon="mdiReload"
|
||||||
class="reveal reveal-3 mb-6 shadow-lg"
|
class="reveal reveal-3 mb-6 shadow-lg"
|
||||||
@header-icon-click="fillChartData"
|
@header-icon-click="loadChart"
|
||||||
>
|
>
|
||||||
<div v-if="isLoadingChart" class="flex items-center justify-center h-96">
|
<div v-if="isLoadingChart" role="status" aria-live="polite" class="flex items-center justify-center h-96">
|
||||||
<div class="flex flex-col items-center gap-3">
|
<div class="flex flex-col items-center gap-3">
|
||||||
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
|
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
|
||||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading chart data...</p>
|
<p class="text-sm text-gray-500 dark:text-gray-400">Loading chart data...</p>
|
||||||
|
|
@ -164,17 +405,6 @@ const today = computed(() =>
|
||||||
<p>No chart data available</p>
|
<p>No chart data available</p>
|
||||||
</div>
|
</div>
|
||||||
</CardBox>
|
</CardBox>
|
||||||
|
|
||||||
<!-- Admin Section -->
|
|
||||||
<template v-if="userHasRoles(['administrator'])">
|
|
||||||
<SectionTitleLineWithButton :icon="mdiAccountMultiple" title="Submitters Management" class="mt-8">
|
|
||||||
<span class="text-sm text-gray-500 dark:text-gray-400">Administrator view</span>
|
|
||||||
</SectionTitleLineWithButton>
|
|
||||||
|
|
||||||
<CardBox :icon="mdiMonitorCellphone" title="All Submitters" has-table class="shadow-lg">
|
|
||||||
<TableSampleClients />
|
|
||||||
</CardBox>
|
|
||||||
</template>
|
|
||||||
</SectionMain>
|
</SectionMain>
|
||||||
</LayoutAuthenticated>
|
</LayoutAuthenticated>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { defineStore } from 'pinia';
|
import { defineStore } from 'pinia';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { Dataset } from '@/Dataset';
|
import { Activity, Dataset } from '@/Dataset';
|
||||||
import menu from '@/menu';
|
import menu from '@/menu';
|
||||||
// import type Person from '#models/person';
|
// import type Person from '#models/person';
|
||||||
|
|
||||||
|
|
@ -133,6 +133,8 @@ export const MainService = defineStore('main', {
|
||||||
used: 0,
|
used: 0,
|
||||||
codes: [],
|
codes: [],
|
||||||
|
|
||||||
|
activities: [] as Array<Activity>, // <-- neu
|
||||||
|
|
||||||
graphData: {},
|
graphData: {},
|
||||||
}),
|
}),
|
||||||
actions: {
|
actions: {
|
||||||
|
|
@ -203,6 +205,17 @@ export const MainService = defineStore('main', {
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// async fetchApi(resource: string) {
|
||||||
|
// try {
|
||||||
|
// const { data } = await axios.get(`/api/${resource}`);
|
||||||
|
// // @ts-ignore – dynamischer Key
|
||||||
|
// this[resource] = data;
|
||||||
|
// } catch (error) {
|
||||||
|
// console.error(`Failed to fetch ${resource}`, error);
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
|
||||||
|
|
||||||
setState(state: any) {
|
setState(state: any) {
|
||||||
this.totpState = state;
|
this.totpState = state;
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,7 @@ export default await Env.create(new URL('../', import.meta.url), {
|
||||||
|
|
||||||
HASH_DRIVER: Env.schema.enum(['scrypt', 'argon', 'bcrypt', 'laravel', undefined] as const),
|
HASH_DRIVER: Env.schema.enum(['scrypt', 'argon', 'bcrypt', 'laravel', undefined] as const),
|
||||||
OAI_LIST_SIZE: Env.schema.number(),
|
OAI_LIST_SIZE: Env.schema.number(),
|
||||||
|
OPENSEARCH_HOST: Env.schema.string(),
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|----------------------------------------------------------
|
|----------------------------------------------------------
|
||||||
|
|
|
||||||
|
|
@ -8,12 +8,15 @@ import AvatarController from '#controllers/Http/Api/AvatarController';
|
||||||
import UserController from '#controllers/Http/Api/UserController';
|
import UserController from '#controllers/Http/Api/UserController';
|
||||||
import CollectionsController from '#controllers/Http/Api/collections_controller';
|
import CollectionsController from '#controllers/Http/Api/collections_controller';
|
||||||
import { middleware } from '../kernel.js';
|
import { middleware } from '../kernel.js';
|
||||||
|
import ActivitiesController from '#app/controllers/activities_controller';
|
||||||
|
|
||||||
// Clean DOI URL routes (no /api prefix)
|
// Clean DOI URL routes (no /api prefix)
|
||||||
|
|
||||||
// API routes with /api prefix
|
// API routes with /api prefix
|
||||||
router
|
router
|
||||||
.group(() => {
|
.group(() => {
|
||||||
|
router.get('activities', [ActivitiesController, 'index']).as('activities.index');
|
||||||
|
|
||||||
router.get('clients', [UserController, 'getSubmitters']).as('client.index').use(middleware.auth());
|
router.get('clients', [UserController, 'getSubmitters']).as('client.index').use(middleware.auth());
|
||||||
router.get('authors', [AuthorsController, 'index']).as('author.index').use(middleware.auth());
|
router.get('authors', [AuthorsController, 'index']).as('author.index').use(middleware.auth());
|
||||||
router.get('datasets', [DatasetController, 'index']).as('dataset.index');
|
router.get('datasets', [DatasetController, 'index']).as('dataset.index');
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue