feat: Enhance Person data structure and improve TablePersons component

- Updated Person interface to include first_name and last_name fields for better clarity and organization handling.
- Modified TablePersons.vue to support new fields, including improved pagination and drag-and-drop functionality.
- Added loading states and error handling for form controls within the table.
- Enhanced the visual layout of the table with responsive design adjustments.
- Updated solr.xslt to correctly reference ServerDateModified and EmbargoDate attributes.
- updated AvatarController
- improved download method for editor, and reviewer
- improved security for officlial download file file API: filterd by server_state
This commit is contained in:
Kaimbacher 2025-09-08 12:28:26 +02:00
parent e1ccf0ddc8
commit 06ed2f3625
12 changed files with 3143 additions and 1387 deletions

View file

@ -5,19 +5,28 @@ import Person from '#models/person';
// node ace make:controller Author // node ace make:controller Author
export default class AuthorsController { export default class AuthorsController {
public async index({}: HttpContext) { public async index({}: HttpContext) {
// select * from gba.persons
// where exists (select * from gba.documents inner join gba.link_documents_persons on "documents"."id" = "link_documents_persons"."document_id"
// where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
const authors = await Person.query() const authors = await Person.query()
.preload('datasets') .select([
.where('name_type', 'Personal') 'id',
.whereHas('datasets', (dQuery) => { 'academic_title',
dQuery.wherePivot('role', 'author'); 'first_name',
}) 'last_name',
.withCount('datasets', (query) => { 'identifier_orcid',
query.as('datasets_count'); 'status',
}) 'name_type',
.orderBy('datasets_count', 'desc'); 'created_at'
// Note: 'email' is omitted
])
.preload('datasets')
.where('name_type', 'Personal')
.whereHas('datasets', (dQuery) => {
dQuery.wherePivot('role', 'author');
})
.withCount('datasets', (query) => {
query.as('datasets_count');
})
.orderBy('datasets_count', 'desc');
return authors; return authors;
} }

View file

@ -2,26 +2,46 @@ import type { HttpContext } from '@adonisjs/core/http';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import redis from '@adonisjs/redis/services/main'; import redis from '@adonisjs/redis/services/main';
const PREFIXES = ['von', 'van']; const PREFIXES = ['von', 'van', 'de', 'del', 'della', 'di', 'da', 'dos', 'du', 'le', 'la'];
const DEFAULT_SIZE = 50; const DEFAULT_SIZE = 50;
const MIN_SIZE = 16;
const MAX_SIZE = 512;
const FONT_SIZE_RATIO = 0.4; const FONT_SIZE_RATIO = 0.4;
const COLOR_LIGHTENING_PERCENT = 60; const COLOR_LIGHTENING_PERCENT = 60;
const COLOR_DARKENING_FACTOR = 0.6; const COLOR_DARKENING_FACTOR = 0.6;
const CACHE_TTL = 24 * 60 * 60; // 24 hours instead of 1 hour
export default class AvatarController { export default class AvatarController {
public async generateAvatar({ request, response }: HttpContext) { public async generateAvatar({ request, response }: HttpContext) {
try { try {
const { name, size = DEFAULT_SIZE } = request.only(['name', 'size']); const { name, size = DEFAULT_SIZE } = request.only(['name', 'size']);
if (!name) {
return response.status(StatusCodes.BAD_REQUEST).json({ error: 'Name is required' }); // Enhanced validation
if (!name || typeof name !== 'string' || name.trim().length === 0) {
return response.status(StatusCodes.BAD_REQUEST).json({
error: 'Name is required and must be a non-empty string',
});
}
const parsedSize = this.validateSize(size);
if (!parsedSize.isValid) {
return response.status(StatusCodes.BAD_REQUEST).json({
error: parsedSize.error,
});
} }
// Build a unique cache key for the given name and size // Build a unique cache key for the given name and size
const cacheKey = `avatar:${name.trim().toLowerCase()}-${size}`; const cacheKey = `avatar:${this.sanitizeName(name)}-${parsedSize.value}`;
const cachedSvg = await redis.get(cacheKey); // const cacheKey = `avatar:${name.trim().toLowerCase()}-${size}`;
if (cachedSvg) { try {
this.setResponseHeaders(response); const cachedSvg = await redis.get(cacheKey);
return response.send(cachedSvg); if (cachedSvg) {
this.setResponseHeaders(response);
return response.send(cachedSvg);
}
} catch (redisError) {
// Log redis error but continue without cache
console.warn('Redis cache read failed:', redisError);
} }
const initials = this.getInitials(name); const initials = this.getInitials(name);
@ -29,41 +49,85 @@ export default class AvatarController {
const svgContent = this.createSvg(size, colors, initials); const svgContent = this.createSvg(size, colors, initials);
// // Cache the generated avatar for future use, e.g. 1 hour expiry // // Cache the generated avatar for future use, e.g. 1 hour expiry
await redis.setex(cacheKey, 3600, svgContent); try {
await redis.setex(cacheKey, CACHE_TTL, svgContent);
} catch (redisError) {
// Log but don't fail the request
console.warn('Redis cache write failed:', redisError);
}
this.setResponseHeaders(response); this.setResponseHeaders(response);
return response.send(svgContent); return response.send(svgContent);
} catch (error) { } catch (error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ error: error.message }); console.error('Avatar generation error:', error);
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
error: 'Failed to generate avatar',
});
} }
} }
private getInitials(name: string): string { private validateSize(size: any): { isValid: boolean; value?: number; error?: string } {
const parts = name const numSize = Number(size);
if (isNaN(numSize)) {
return { isValid: false, error: 'Size must be a valid number' };
}
if (numSize < MIN_SIZE || numSize > MAX_SIZE) {
return {
isValid: false,
error: `Size must be between ${MIN_SIZE} and ${MAX_SIZE}`,
};
}
return { isValid: true, value: Math.floor(numSize) };
}
private sanitizeName(name: string): string {
return name
.trim() .trim()
.toLowerCase()
.replace(/[^a-z0-9\s-]/gi, '');
}
private getInitials(name: string): string {
const sanitized = name.trim().replace(/\s+/g, ' '); // normalize whitespace
const parts = sanitized
.split(' ') .split(' ')
.filter((part) => part.length > 0); .filter((part) => part.length > 0)
.map((part) => part.trim());
if (parts.length === 0) { if (parts.length === 0) {
return 'NA'; return 'NA';
} }
if (parts.length >= 2) { if (parts.length === 1) {
return this.getMultiWordInitials(parts); // For single word, take first 2 characters or first char if only 1 char
return parts[0].substring(0, Math.min(2, parts[0].length)).toUpperCase();
} }
return parts[0].substring(0, 2).toUpperCase();
return this.getMultiWordInitials(parts);
} }
private getMultiWordInitials(parts: string[]): string { private getMultiWordInitials(parts: string[]): string {
const firstName = parts[0]; // Filter out prefixes and short words
const lastName = parts[parts.length - 1]; const significantParts = parts.filter((part) => !PREFIXES.includes(part.toLowerCase()) && part.length > 1);
const firstInitial = firstName.charAt(0).toUpperCase();
const lastInitial = lastName.charAt(0).toUpperCase();
if (PREFIXES.includes(lastName.toLowerCase()) && lastName === lastName.toUpperCase()) { if (significantParts.length === 0) {
return firstInitial + lastName.charAt(1).toUpperCase(); // Fallback to first and last regardless of prefixes
const firstName = parts[0];
const lastName = parts[parts.length - 1];
return (firstName.charAt(0) + lastName.charAt(0)).toUpperCase();
} }
return firstInitial + lastInitial;
if (significantParts.length === 1) {
return significantParts[0].substring(0, 2).toUpperCase();
}
// Take first and last significant parts
const firstName = significantParts[0];
const lastName = significantParts[significantParts.length - 1];
return (firstName.charAt(0) + lastName.charAt(0)).toUpperCase();
} }
private generateColors(name: string): { background: string; text: string } { private generateColors(name: string): { background: string; text: string } {
@ -75,31 +139,44 @@ export default class AvatarController {
} }
private createSvg(size: number, colors: { background: string; text: string }, initials: string): string { private createSvg(size: number, colors: { background: string; text: string }, initials: string): string {
const fontSize = size * FONT_SIZE_RATIO; const fontSize = Math.max(12, Math.floor(size * FONT_SIZE_RATIO)); // Ensure readable font size
return `
<svg width="${size}" height="${size}" xmlns="http://www.w3.org/2000/svg"> // Escape any potential HTML/XML characters in initials
<rect width="100%" height="100%" fill="#${colors.background}"/> const escapedInitials = this.escapeXml(initials);
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-weight="bold" font-family="Arial, sans-serif" font-size="${fontSize}" fill="#${colors.text}">${initials}</text>
</svg> return `<svg width="${size}" height="${size}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}">
`; <rect width="100%" height="100%" fill="#${colors.background}" rx="${size * 0.1}"/>
<text x="50%" y="50%" dominant-baseline="central" text-anchor="middle"
font-weight="600" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif"
font-size="${fontSize}" fill="#${colors.text}">${escapedInitials}</text>
</svg>`;
}
private escapeXml(text: string): string {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
} }
private setResponseHeaders(response: HttpContext['response']): void { private setResponseHeaders(response: HttpContext['response']): void {
response.header('Content-type', 'image/svg+xml'); response.header('Content-Type', 'image/svg+xml');
response.header('Cache-Control', 'no-cache'); response.header('Cache-Control', 'public, max-age=86400'); // Cache for 1 day
response.header('Pragma', 'no-cache'); response.header('ETag', `"${Date.now()}"`); // Simple ETag
response.header('Expires', '0');
} }
private getColorFromName(name: string): string { private getColorFromName(name: string): string {
let hash = 0; let hash = 0;
for (let i = 0; i < name.length; i++) { const normalizedName = name.toLowerCase().trim();
hash = name.charCodeAt(i) + ((hash << 5) - hash);
for (let i = 0; i < normalizedName.length; i++) {
hash = normalizedName.charCodeAt(i) + ((hash << 5) - hash);
hash = hash & hash; // Convert to 32-bit integer
} }
// Ensure we get vibrant colors by constraining the color space
const colorParts = []; const colorParts = [];
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
const value = (hash >> (i * 8)) & 0xff; let value = (hash >> (i * 8)) & 0xff;
// Ensure minimum color intensity for better contrast
value = Math.max(50, value);
colorParts.push(value.toString(16).padStart(2, '0')); colorParts.push(value.toString(16).padStart(2, '0'));
} }
return colorParts.join(''); return colorParts.join('');
@ -110,7 +187,7 @@ export default class AvatarController {
const g = parseInt(hexColor.substring(2, 4), 16); const g = parseInt(hexColor.substring(2, 4), 16);
const b = parseInt(hexColor.substring(4, 6), 16); const b = parseInt(hexColor.substring(4, 6), 16);
const lightenValue = (value: number) => Math.min(255, Math.floor((value * (100 + percent)) / 100)); const lightenValue = (value: number) => Math.min(255, Math.floor(value + (255 - value) * (percent / 100)));
const newR = lightenValue(r); const newR = lightenValue(r);
const newG = lightenValue(g); const newG = lightenValue(g);
@ -124,7 +201,7 @@ export default class AvatarController {
const g = parseInt(hexColor.slice(2, 4), 16); const g = parseInt(hexColor.slice(2, 4), 16);
const b = parseInt(hexColor.slice(4, 6), 16); const b = parseInt(hexColor.slice(4, 6), 16);
const darkenValue = (value: number) => Math.round(value * COLOR_DARKENING_FACTOR); const darkenValue = (value: number) => Math.max(0, Math.floor(value * COLOR_DARKENING_FACTOR));
const darkerR = darkenValue(r); const darkerR = darkenValue(r);
const darkerG = darkenValue(g); const darkerG = darkenValue(g);

View file

@ -9,8 +9,7 @@ export default class DatasetController {
// Select datasets with server_state 'published' or 'deleted' and sort by the last published date // Select datasets with server_state 'published' or 'deleted' and sort by the last published date
const datasets = await Dataset.query() const datasets = await Dataset.query()
.where(function (query) { .where(function (query) {
query.where('server_state', 'published') query.where('server_state', 'published').orWhere('server_state', 'deleted');
.orWhere('server_state', 'deleted');
}) })
.preload('titles') .preload('titles')
.preload('identifier') .preload('identifier')
@ -39,7 +38,9 @@ export default class DatasetController {
.where('publish_id', params.publish_id) .where('publish_id', params.publish_id)
.preload('titles') .preload('titles')
.preload('descriptions') .preload('descriptions')
.preload('user') .preload('user', (builder) => {
builder.select(['id', 'firstName', 'lastName', 'avatar', 'login']);
})
.preload('authors', (builder) => { .preload('authors', (builder) => {
builder.orderBy('pivot_sort_order', 'asc'); builder.orderBy('pivot_sort_order', 'asc');
}) })

View file

@ -2,7 +2,6 @@ import type { HttpContext } from '@adonisjs/core/http';
import File from '#models/file'; import File from '#models/file';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
// node ace make:controller Author // node ace make:controller Author
@ -23,8 +22,13 @@ export default class FileController {
}); });
} }
// Check embargo date const dataset = file.dataset;
const dataset = file.dataset; // or file.dataset // Files from unpublished datasets are now blocked
if (dataset.server_state !== 'published') {
return response.status(StatusCodes.FORBIDDEN).send({
message: `File access denied: Dataset is not published.`,
});
}
if (dataset && this.isUnderEmbargo(dataset.embargo_date)) { if (dataset && this.isUnderEmbargo(dataset.embargo_date)) {
return response.status(StatusCodes.FORBIDDEN).send({ return response.status(StatusCodes.FORBIDDEN).send({
message: `File is under embargo until ${dataset.embargo_date?.toFormat('yyyy-MM-dd')}`, message: `File is under embargo until ${dataset.embargo_date?.toFormat('yyyy-MM-dd')}`,
@ -33,12 +37,15 @@ export default class FileController {
// Proceed with file download // Proceed with file download
const filePath = '/storage/app/data/' + file.pathName; const filePath = '/storage/app/data/' + file.pathName;
const ext = path.extname(filePath); const fileExt = file.filePath.split('.').pop() || '';
const fileName = file.label + ext; // const fileName = file.label + fileExt;
const fileName = file.label.toLowerCase().endsWith(`.${fileExt.toLowerCase()}`)
? file.label
: `${file.label}.${fileExt}`;
try { try {
fs.accessSync(filePath, fs.constants.R_OK); //| fs.constants.W_OK); fs.accessSync(filePath, fs.constants.R_OK); //| fs.constants.W_OK);
// console.log("can read/write:", path); // console.log("can read/write:", filePath);
response response
.header('Cache-Control', 'no-cache private') .header('Cache-Control', 'no-cache private')
@ -47,7 +54,7 @@ export default class FileController {
.header('Content-Disposition', 'inline; filename=' + fileName) .header('Content-Disposition', 'inline; filename=' + fileName)
.header('Content-Transfer-Encoding', 'binary') .header('Content-Transfer-Encoding', 'binary')
.header('Access-Control-Allow-Origin', '*') .header('Access-Control-Allow-Origin', '*')
.header('Access-Control-Allow-Methods', 'GET,POST'); .header('Access-Control-Allow-Methods', 'GET');
response.status(StatusCodes.OK).download(filePath); response.status(StatusCodes.OK).download(filePath);
} catch (err) { } catch (err) {

View file

@ -252,7 +252,6 @@ export default class DatasetsController {
dataset.reject_editor_note = null; dataset.reject_editor_note = null;
} }
//save main and additional titles //save main and additional titles
const reviewer_id = request.input('reviewer_id', null); const reviewer_id = request.input('reviewer_id', null);
dataset.reviewer_id = reviewer_id; dataset.reviewer_id = reviewer_id;
@ -290,8 +289,6 @@ export default class DatasetsController {
}); });
} }
public async rejectUpdate({ request, response, auth }: HttpContext) { public async rejectUpdate({ request, response, auth }: HttpContext) {
const authUser = auth.user!; const authUser = auth.user!;
@ -402,8 +399,6 @@ export default class DatasetsController {
.back(); .back();
} }
return inertia.render('Editor/Dataset/Publish', { return inertia.render('Editor/Dataset/Publish', {
dataset, dataset,
can: { can: {
@ -555,7 +550,6 @@ export default class DatasetsController {
} }
} }
return response return response
.flash( .flash(
`You have successfully rejected dataset ${dataset.id} reviewed by ${dataset.reviewer.login}.${emailStatusMessage}`, `You have successfully rejected dataset ${dataset.id} reviewed by ${dataset.reviewer.login}.${emailStatusMessage}`,
@ -606,10 +600,9 @@ export default class DatasetsController {
doiIdentifier.type = 'doi'; doiIdentifier.type = 'doi';
doiIdentifier.status = 'findable'; doiIdentifier.status = 'findable';
// save updated dataset to db an index to OpenSearch // save updated dataset to db an index to OpenSearch
try { try {
// save modified date of datset for re-caching model in db an update the search index // save modified date of datset for re-caching model in db an update the search index
dataset.server_date_modified = DateTime.now(); dataset.server_date_modified = DateTime.now();
// autoUpdate: true only triggers when dataset.save() is called, not when saving a related model like below // autoUpdate: true only triggers when dataset.save() is called, not when saving a related model like below
await dataset.save(); await dataset.save();
@ -1125,9 +1118,20 @@ export default class DatasetsController {
// const filePath = await drive.use('local').getUrl('/'+ file.filePath) // const filePath = await drive.use('local').getUrl('/'+ file.filePath)
const filePath = file.filePath; const filePath = file.filePath;
const fileExt = file.filePath.split('.').pop() || ''; const fileExt = file.filePath.split('.').pop() || '';
// Check if label already includes the extension
const fileName = file.label.toLowerCase().endsWith(`.${fileExt.toLowerCase()}`) ? file.label : `${file.label}.${fileExt}`;
// Set the response headers and download the file // Set the response headers and download the file
response.header('Content-Type', file.mime_type || 'application/octet-stream'); response
response.attachment(`${file.label}.${fileExt}`); .header('Cache-Control', 'no-cache private')
.header('Content-Description', 'File Transfer')
.header('Content-Type', file.mime_type || 'application/octet-stream')
// .header('Content-Disposition', 'inline; filename=' + fileName)
.header('Content-Transfer-Encoding', 'binary')
.header('Access-Control-Allow-Origin', '*')
.header('Access-Control-Allow-Methods', 'GET');
response.attachment(fileName);
return response.download(filePath); return response.download(filePath);
} }

View file

@ -113,7 +113,6 @@ export default class DatasetsController {
reject: await auth.user?.can(['dataset-review-reject']), reject: await auth.user?.can(['dataset-review-reject']),
}, },
}); });
} }
public async review_old({ request, inertia, response, auth }: HttpContext) { public async review_old({ request, inertia, response, auth }: HttpContext) {
@ -370,6 +369,19 @@ export default class DatasetsController {
.flash(`You have rejected dataset ${dataset.id}! to editor ${dataset.editor.login}`, 'message'); .flash(`You have rejected dataset ${dataset.id}! to editor ${dataset.editor.login}`, 'message');
} }
// public async download({ params, response }: HttpContext) {
// const id = params.id;
// // Find the file by ID
// const file = await File.findOrFail(id);
// // const filePath = await drive.use('local').getUrl('/'+ file.filePath)
// const filePath = file.filePath;
// const fileExt = file.filePath.split('.').pop() || '';
// // Set the response headers and download the file
// response.header('Content-Type', file.mime_type || 'application/octet-stream');
// response.attachment(`${file.label}.${fileExt}`);
// return response.download(filePath);
// }
public async download({ params, response }: HttpContext) { public async download({ params, response }: HttpContext) {
const id = params.id; const id = params.id;
// Find the file by ID // Find the file by ID
@ -377,9 +389,20 @@ export default class DatasetsController {
// const filePath = await drive.use('local').getUrl('/'+ file.filePath) // const filePath = await drive.use('local').getUrl('/'+ file.filePath)
const filePath = file.filePath; const filePath = file.filePath;
const fileExt = file.filePath.split('.').pop() || ''; const fileExt = file.filePath.split('.').pop() || '';
// Check if label already includes the extension
const fileName = file.label.toLowerCase().endsWith(`.${fileExt.toLowerCase()}`) ? file.label : `${file.label}.${fileExt}`;
// Set the response headers and download the file // Set the response headers and download the file
response.header('Content-Type', file.mime_type || 'application/octet-stream'); response
response.attachment(`${file.label}.${fileExt}`); .header('Cache-Control', 'no-cache private')
.header('Content-Description', 'File Transfer')
.header('Content-Type', file.mime_type || 'application/octet-stream')
// .header('Content-Disposition', 'inline; filename=' + fileName)
.header('Content-Transfer-Encoding', 'binary')
.header('Access-Control-Allow-Origin', '*')
.header('Access-Control-Allow-Methods', 'GET');
response.attachment(fileName);
return response.download(filePath); return response.download(filePath);
} }
} }

View file

@ -89,24 +89,11 @@ export default class User extends compose(BaseModel, AuthFinder) {
@column({}) @column({})
public avatar: string; public avatar: string;
// @hasOne(() => TotpSecret, {
// foreignKey: 'user_id',
// })
// public totp_secret: HasOne<typeof TotpSecret>;
// @beforeSave()
// public static async hashPassword(user: User) {
// if (user.$dirty.password) {
// user.password = await hash.use('laravel').make(user.password);
// }
// }
public get isTwoFactorEnabled(): boolean { public get isTwoFactorEnabled(): boolean {
return Boolean(this?.twoFactorSecret && this.state == TotpState.STATE_ENABLED); return Boolean(this?.twoFactorSecret && this.state == TotpState.STATE_ENABLED);
// return Boolean(this.totp_secret?.twoFactorSecret); // return Boolean(this.totp_secret?.twoFactorSecret);
} }
@manyToMany(() => Role, { @manyToMany(() => Role, {
pivotForeignKey: 'account_id', pivotForeignKey: 'account_id',
pivotRelatedForeignKey: 'role_id', pivotRelatedForeignKey: 'role_id',
@ -142,7 +129,9 @@ export default class User extends compose(BaseModel, AuthFinder) {
@beforeFind() @beforeFind()
@beforeFetch() @beforeFetch()
public static preloadRoles(user: User) { public static preloadRoles(user: User) {
user.preload('roles') user.preload('roles', (builder) => {
builder.select(['id', 'name', 'display_name', 'description']);
});
} }
public async getBackupCodes(this: User): Promise<BackupCode[]> { public async getBackupCodes(this: User): Promise<BackupCode[]> {

3573
package-lock.json generated

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -111,7 +111,14 @@
<!--5 server_date_modified --> <!--5 server_date_modified -->
<xsl:if test="ServerDateModified/@UnixTimestamp != ''"> <xsl:if test="ServerDateModified/@UnixTimestamp != ''">
<xsl:text>"server_date_modified": "</xsl:text> <xsl:text>"server_date_modified": "</xsl:text>
<xsl:value-of select="/ServerDateModified/@UnixTimestamp" /> <xsl:value-of select="ServerDateModified/@UnixTimestamp" />
<xsl:text>",</xsl:text>
</xsl:if>
<!--5 embargo_date -->
<xsl:if test="EmbargoDate/@UnixTimestamp != ''">
<xsl:text>"embargo_date": "</xsl:text>
<xsl:value-of select="EmbargoDate/@UnixTimestamp" />
<xsl:text>",</xsl:text> <xsl:text>",</xsl:text>
</xsl:if> </xsl:if>

View file

@ -1,45 +1,69 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue'; import { computed, ref, watch } from 'vue';
// import { MainService } from '@/Stores/main';
// import { StyleService } from '@/Stores/style.service';
import { mdiTrashCan } from '@mdi/js'; import { mdiTrashCan } from '@mdi/js';
import { mdiDragVariant } from '@mdi/js'; import { mdiDragVariant, mdiChevronLeft, mdiChevronRight } from '@mdi/js';
import BaseIcon from '@/Components/BaseIcon.vue'; import BaseIcon from '@/Components/BaseIcon.vue';
// import CardBoxModal from '@/Components/CardBoxModal.vue';
// import TableCheckboxCell from '@/Components/TableCheckboxCell.vue';
// import BaseLevel from '@/Components/BaseLevel.vue';
import BaseButtons from '@/Components/BaseButtons.vue'; import BaseButtons from '@/Components/BaseButtons.vue';
import BaseButton from '@/Components/BaseButton.vue'; import BaseButton from '@/Components/BaseButton.vue';
// import UserAvatar from '@/Components/UserAvatar.vue';
// import Person from 'App/Models/Person';
import { Person } from '@/Dataset'; import { Person } from '@/Dataset';
import Draggable from 'vuedraggable'; import Draggable from 'vuedraggable';
import FormControl from '@/Components/FormControl.vue'; import FormControl from '@/Components/FormControl.vue';
const props = defineProps({ interface Props {
checkable: Boolean, checkable?: boolean;
persons: { persons?: Person[];
type: Array<Person>, relation: string;
default: () => [], contributortypes?: Record<string, string>;
}, errors?: Record<string, string[]>;
relation: { isLoading?: boolean;
type: String, canDelete?: boolean;
required: true, canEdit?: boolean;
}, canReorder?: boolean;
contributortypes: { }
type: Object,
default: () => ({}), // const props = defineProps({
}, // checkable: Boolean,
errors: { // persons: {
type: Object, // type: Array<Person>,
default: () => ({}), // default: () => [],
}, // },
// relation: {
// type: String,
// required: true,
// },
// contributortypes: {
// type: Object,
// default: () => ({}),
// },
// errors: {
// type: Object,
// default: () => ({}),
// },
// });
const props = withDefaults(defineProps<Props>(), {
checkable: false,
persons: () => [],
contributortypes: () => ({}),
errors: () => ({}),
isLoading: false,
canDelete: true,
canEdit: true,
canReorder: true,
}); });
// const styleService = StyleService(); const emit = defineEmits<{
// const mainService = MainService(); 'update:persons': [value: Person[]];
// const items = computed(() => props.persons); 'remove-person': [index: number, person: Person];
'person-updated': [index: number, person: Person];
'reorder': [oldIndex: number, newIndex: number];
}>();
// Local state
const perPage = ref(5);
const currentPage = ref(0);
const dragEnabled = ref(props.canReorder);
// Computed properties
const items = computed({ const items = computed({
get() { get() {
return props.persons; return props.persons;
@ -53,221 +77,393 @@ const items = computed({
}, },
}); });
// const isModalActive = ref(false); const itemsPaginated = computed(() => {
// const isModalDangerActive = ref(false); const start = perPage.value * currentPage.value;
const perPage = ref(5); const end = perPage.value * (currentPage.value + 1);
const currentPage = ref(0); return items.value.slice(start, end);
// const checkedRows = ref([]);
const itemsPaginated = computed({
get() {
return items.value.slice(perPage.value * currentPage.value, perPage.value * (currentPage.value + 1));
},
// setter
set(value) {
// Note: we are using destructuring assignment syntax here.
props.persons.length = 0;
props.persons.push(...value);
},
}); });
const numPages = computed(() => Math.ceil(items.value.length / perPage.value)); const numPages = computed(() => Math.ceil(items.value.length / perPage.value));
const currentPageHuman = computed(() => currentPage.value + 1); const currentPageHuman = computed(() => currentPage.value + 1);
const hasMultiplePages = computed(() => numPages.value > 1);
const showContributorTypes = computed(() => Object.keys(props.contributortypes).length > 0);
const pagesList = computed(() => { const pagesList = computed(() => {
const pagesList: Array<number> = []; const pages: number[] = [];
const maxVisible = 10;
for (let i = 0; i < numPages.value; i++) { if (numPages.value <= maxVisible) {
pagesList.push(i); for (let i = 0; i < numPages.value; i++) {
pages.push(i);
}
} else {
// Smart pagination with ellipsis
if (currentPage.value <= 2) {
for (let i = 0; i < 4; i++) pages.push(i);
pages.push(-1); // Ellipsis marker
pages.push(numPages.value - 1);
} else if (currentPage.value >= numPages.value - 3) {
pages.push(0);
pages.push(-1);
for (let i = numPages.value - 4; i < numPages.value; i++) {
pages.push(i);
}
} else {
pages.push(0);
pages.push(-1);
for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
pages.push(i);
}
pages.push(-1);
pages.push(numPages.value - 1);
}
} }
return pagesList; return pages;
}); });
const removeAuthor = (key: number) => { // const removeAuthor = (key: number) => {
items.value.splice(key, 1); // items.value.splice(key, 1);
// };
// Methods
const removeAuthor = (index: number) => {
const actualIndex = perPage.value * currentPage.value + index;
const person = items.value[actualIndex];
if (confirm(`Are you sure you want to remove ${person.first_name || ''} ${person.last_name || person.email}?`)) {
items.value.splice(actualIndex, 1);
emit('remove-person', actualIndex, person);
// Adjust current page if needed
if (itemsPaginated.value.length === 0 && currentPage.value > 0) {
currentPage.value--;
}
}
}; };
// const remove = (arr, cb) => { const updatePerson = (index: number, field: keyof Person, value: any) => {
// const newArr = []; const actualIndex = perPage.value * currentPage.value + index;
const person = items.value[actualIndex];
(person as any)[field] = value;
emit('person-updated', actualIndex, person);
};
// arr.forEach((item) => { const goToPage = (page: number) => {
// if (!cb(item)) { if (page >= 0 && page < numPages.value) {
// newArr.push(item); currentPage.value = page;
// } }
// }); };
// return newArr; const getFieldError = (index: number, field: string): string => {
// }; const actualIndex = perPage.value * currentPage.value + index;
const errorKey = `${props.relation}.${actualIndex}.${field}`;
return props.errors[errorKey]?.join(', ') || '';
};
// const checked = (isChecked, client) => { const handleDragEnd = (evt: any) => {
// if (isChecked) { if (evt.oldIndex !== evt.newIndex) {
// checkedRows.value.push(client); emit('reorder', evt.oldIndex, evt.newIndex);
// } else { }
// checkedRows.value = remove(checkedRows.value, (row) => row.id === client.id); };
// }
// }; // Watchers
watch(
() => props.persons.length,
() => {
// Reset to first page if current page is out of bounds
if (currentPage.value >= numPages.value && numPages.value > 0) {
currentPage.value = numPages.value - 1;
}
},
);
// Pagination helper
const perPageOptions = [
{ value: 5, label: '5 per page' },
{ value: 10, label: '10 per page' },
{ value: 20, label: '20 per page' },
{ value: 50, label: '50 per page' },
];
</script> </script>
<template> <template>
<!-- <CardBoxModal v-model="isModalActive" title="Sample modal"> <div class="card">
<p>Lorem ipsum dolor sit amet <b>adipiscing elit</b></p> <!-- Table Controls -->
<p>This is sample modal</p> <div v-if="hasMultiplePages" class="flex justify-between items-center p-3 border-b border-gray-200 dark:border-slate-700">
</CardBoxModal> <div class="flex items-center gap-2">
<span class="text-sm text-gray-600 dark:text-gray-400">
Showing {{ currentPage * perPage + 1 }} to
{{ Math.min((currentPage + 1) * perPage, items.length) }}
of {{ items.length }} entries
</span>
</div>
<select
v-model="perPage"
@change="currentPage = 0"
class="px-3 py-1 text-sm border rounded-md dark:bg-slate-800 dark:border-slate-600"
>
<option v-for="option in perPageOptions" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
</div>
<CardBoxModal v-model="isModalDangerActive" large-title="Please confirm" button="danger" has-cancel> <!-- Table -->
<p>Lorem ipsum dolor sit amet <b>adipiscing elit</b></p> <div class="overflow-x-auto">
<p>This is sample modal</p> <table class="w-full">
</CardBoxModal> --> <thead>
<tr class="border-b border-gray-200 dark:border-slate-700">
<th v-if="canReorder" class="w-10 p-3" />
<th scope="col" class="text-left p-3">#</th>
<th scope="col">Id</th>
<th>First Name</th>
<th>Last Name / Organization</th>
<th>Email</th>
<th v-if="showContributorTypes" scope="col" class="text-left p-3">Type</th>
<th v-if="canDelete" class="w-20 p-3">Actions</th>
</tr>
</thead>
<!-- <tbody> -->
<!-- <tr v-for="(client, index) in itemsPaginated" :key="client.id"> -->
<draggable
v-if="canReorder && !hasMultiplePages"
tag="tbody"
v-model="items"
item-key="id"
:disabled="!dragEnabled || isLoading"
@end="handleDragEnd"
handle=".drag-handle"
>
<template #item="{ index, element }">
<tr class="border-b border-gray-100 dark:border-slate-800 hover:bg-gray-50 dark:hover:bg-slate-800">
<td class="p-3">
<div class="drag-handle cursor-move text-gray-400 hover:text-gray-600">
<BaseIcon :path="mdiDragVariant" />
</div>
</td>
<td class="p-3">{{ index + 1 }}</td>
<td data-label="Id" class="p-3 text-sm text-gray-600">{{ element.id || '-' }}</td>
<!-- <div v-if="checkedRows.length" class="p-3 bg-gray-100/50 dark:bg-slate-800"> <!-- First Name - Hidden for Organizational -->
<span v-for="checkedRow in checkedRows" :key="checkedRow.id" <td class="p-3" data-label="First Name" v-if="element.name_type !== 'Organizational'">
class="inline-block px-2 py-1 rounded-sm mr-2 text-sm bg-gray-100 dark:bg-slate-700"> <FormControl
{{ checkedRow.name }} required
</span> v-model="element.first_name"
</div> --> type="text"
:is-read-only="element.status == true"
placeholder="[FIRST NAME]"
/>
<div class="text-red-400 text-sm" v-if="errors && Array.isArray(errors[`${relation}.${index}.first_name`])">
{{ errors[`${relation}.${index}.first_name`].join(', ') }}
</div>
</td>
<td v-else></td>
<!-- Empty cell for organizational entries -->
<table> <!-- Last Name / Organization Name -->
<thead> <td :data-label="element.name_type === 'Organizational' ? 'Organization Name' : 'Last Name'">
<tr> <FormControl
<!-- <th v-if="checkable" /> --> required
<th /> v-model="element.last_name"
<th scope="col">Sort</th> type="text"
<th scope="col">Id</th> :is-read-only="element.status == true"
<!-- <th class="hidden lg:table-cell"></th> --> :placeholder="element.name_type === 'Organizational' ? '[ORGANIZATION NAME]' : '[LAST NAME]'"
<th>First Name</th> />
<th>Last Name</th> <div class="text-red-400 text-sm" v-if="errors && Array.isArray(errors[`${relation}.${index}.last_name`])">
<th>Email</th> {{ errors[`${relation}.${index}.last_name`].join(', ') }}
<th scope="col" v-if="Object.keys(contributortypes).length"> </div>
<span>Type</span> </td>
</th>
<!-- <th>Name Type</th> --> <!-- Email -->
<!-- <th>Progress</th> --> <td data-label="Email">
<!-- <th>Created</th> --> <FormControl
<th /> required
</tr> v-model="element.email"
</thead> type="text"
<!-- <tbody> --> :is-read-only="element.status == true"
<!-- <tr v-for="(client, index) in itemsPaginated" :key="client.id"> --> placeholder="[EMAIL]"
<draggable id="galliwasery" tag="tbody" v-model="items" item-key="id"> />
<template #item="{ index, element }"> <div class="text-red-400 text-sm" v-if="errors && Array.isArray(errors[`${relation}.${index}.email`])">
<tr> {{ errors[`${relation}.${index}.email`].join(', ') }}
<td class="drag-icon"> </div>
<BaseIcon :path="mdiDragVariant" /> </td>
</td>
<td scope="row">{{ index + 1 }}</td> <!-- Contributor Type -->
<td data-label="Id">{{ element.id }}</td> <td v-if="Object.keys(contributortypes).length">
<!-- <TableCheckboxCell v-if="checkable" @checked="checked($event, client)" /> --> <FormControl
<!-- <td v-if="element.name" class="border-b-0 lg:w-6 before:hidden hidden lg:table-cell"> required
<UserAvatar :username="element.name" class="w-24 h-24 mx-auto lg:w-6 lg:h-6" /> v-model="element.pivot_contributor_type"
</td> --> type="select"
<td data-label="First Name"> :options="contributortypes"
<!-- {{ element.first_name }} --> placeholder="[relation type]"
<FormControl >
required <div
v-model="element.first_name" class="text-red-400 text-sm"
type="text" :is-read-only="element.status==true" v-if="errors && Array.isArray(errors[`${relation}.${index}.pivot_contributor_type`])"
placeholder="[FIRST NAME]" >
> {{ errors[`${relation}.${index}.pivot_contributor_type`].join(', ') }}
<div </div>
class="text-red-400 text-sm" </FormControl>
v-if="errors && Array.isArray(errors[`${relation}.${index}.first_name`])" </td>
>
{{ errors[`${relation}.${index}.first_name`].join(', ') }} <!-- Actions -->
<td class="before:hidden lg:w-1 whitespace-nowrap">
<BaseButtons type="justify-start lg:justify-end" no-wrap>
<BaseButton color="danger" :icon="mdiTrashCan" small @click.prevent="removeAuthor(index)" />
</BaseButtons>
</td>
</tr>
</template>
</draggable>
<!-- </tbody> -->
<!-- Non-draggable tbody for paginated view -->
<tbody v-else>
<tr
v-for="(element, index) in itemsPaginated"
:key="element.id || index"
class="border-b border-gray-100 dark:border-slate-800 hover:bg-gray-50 dark:hover:bg-slate-800"
>
<td v-if="canReorder" class="p-3 text-gray-400">
<BaseIcon :path="mdiDragVariant" />
</td>
<td class="p-3">{{ currentPage * perPage + index + 1 }}</td>
<td class="p-3 text-sm text-gray-600">{{ element.id || '-' }}</td>
<!-- Same field structure as draggable version -->
<td class="p-3">
<FormControl
v-if="element.name_type !== 'Organizational'"
required
:model-value="element.first_name"
@update:model-value="updatePerson(index, 'first_name', $event)"
type="text"
:is-read-only="element.status || !canEdit"
placeholder="[FIRST NAME]"
:error="getFieldError(index, 'first_name')"
/>
<span v-else class="text-gray-400">-</span>
<div v-if="getFieldError(index, 'first_name')" class="text-red-400 text-sm">
{{ getFieldError(index, 'first_name') }}
</div> </div>
</FormControl> </td>
</td>
<td data-label="Last Name"> <td class="p-3">
<FormControl <FormControl
required required
v-model="element.last_name" :model-value="element.last_name"
type="text" :is-read-only="element.status==true" @update:model-value="updatePerson(index, 'last_name', $event)"
placeholder="[LAST NAME]" type="text"
> :is-read-only="element.status || !canEdit"
<div :placeholder="element.name_type === 'Organizational' ? '[ORGANIZATION NAME]' : '[LAST NAME]'"
class="text-red-400 text-sm" :error="getFieldError(index, 'last_name')"
v-if="errors && Array.isArray(errors[`${relation}.${index}.last_name`])" />
> <div v-if="getFieldError(index, 'last_name')" class="text-red-400 text-sm">
{{ errors[`${relation}.${index}.last_name`].join(', ') }} {{ getFieldError(index, 'last_name') }}
</div> </div>
</FormControl> </td>
</td>
<td data-label="Email"> <td class="p-3">
<FormControl <FormControl
required required
v-model="element.email" :model-value="element.email"
type="text" :is-read-only="element.status==true" @update:model-value="updatePerson(index, 'email', $event)"
placeholder="[EMAIL]" type="email"
> :is-read-only="element.status || !canEdit"
<div placeholder="[EMAIL]"
class="text-red-400 text-sm" :error="getFieldError(index, 'email')"
v-if="errors && Array.isArray(errors[`${relation}.${index}.email`])" />
> <div v-if="getFieldError(index, 'email')" class="text-red-400 text-sm">
{{ errors[`${relation}.${index}.email`].join(', ') }} {{ getFieldError(index, 'email') }}
</div> </div>
</FormControl> </td>
</td>
<td v-if="Object.keys(contributortypes).length"> <td v-if="showContributorTypes" class="p-3">
<!-- <select type="text" v-model="element.pivot.contributor_type"> <FormControl
<option v-for="(option, i) in contributortypes" :value="option" :key="i"> required
{{ option }} :model-value="element.pivot_contributor_type"
</option> @update:model-value="updatePerson(index, 'pivot_contributor_type', $event)"
</select> --> type="select"
<FormControl :options="contributortypes"
required :is-read-only="element.status || !canEdit"
v-model="element.pivot_contributor_type" placeholder="[Select type]"
type="select" :error="getFieldError(index, 'pivot_contributor_type')"
:options="contributortypes" />
placeholder="[relation type]" <div v-if="getFieldError(index, 'pivot_contributor_type')" class="text-red-400 text-sm">
> {{ getFieldError(index, 'pivot_contributor_type') }}
<div
class="text-red-400 text-sm"
v-if="errors && Array.isArray(errors[`${relation}.${index}.pivot_contributor_type`])"
>
{{ errors[`${relation}.${index}.pivot_contributor_type`].join(', ') }}
</div> </div>
</FormControl> </td>
</td>
<!-- <td data-label="Name Type"> <td v-if="canDelete" class="p-3">
{{ client.name_type }} <BaseButtons type="justify-start lg:justify-end" no-wrap>
</td> --> <BaseButton
<!-- <td data-label="Orcid"> color="danger"
{{ client.identifier_orcid }} :icon="mdiTrashCan"
</td> --> small
<!-- <td data-label="Progress" class="lg:w-32"> @click="removeAuthor(index)"
<progress class="flex w-2/5 self-center lg:w-full" max="100" v-bind:value="client.progress"> :disabled="element.status || !canEdit"
{{ client.progress }} title="Remove person"
</progress> />
</td> --> </BaseButtons>
<td class="before:hidden lg:w-1 whitespace-nowrap"> </td>
<BaseButtons type="justify-start lg:justify-end" no-wrap> </tr>
<!-- <BaseButton color="info" :icon="mdiEye" small @click="isModalActive = true" /> -->
<BaseButton color="danger" :icon="mdiTrashCan" small @click.prevent="removeAuthor(index)" /> <!-- Empty State -->
</BaseButtons> <tr v-if="items.length === 0">
</td> <td :colspan="canReorder ? 8 : 7" class="text-center p-8 text-gray-500">No persons added yet</td>
</tr> </tr>
</template> </tbody>
</draggable> </table>
<!-- </tbody> --> </div>
</table>
<!-- :class="[ pagesList.length > 1 ? 'block' : 'hidden']" --> <!-- Pagination -->
<div class="p-3 lg:px-6 border-t border-gray-100 dark:border-slate-800"> <div v-if="hasMultiplePages" class="flex justify-between items-center p-3 border-t border-gray-200 dark:border-slate-700">
<!-- <BaseLevel> <div class="flex gap-1">
<BaseButtons> <BaseButton :disabled="currentPage === 0" @click="goToPage(currentPage - 1)" :icon="mdiChevronLeft" small outline />
<template v-for="(page, i) in pagesList" :key="i">
<span v-if="page === -1" class="px-3 py-1">...</span>
<BaseButton
v-else
@click="goToPage(page)"
:label="String(page + 1)"
:color="page === currentPage ? 'info' : 'whiteDark'"
small
:outline="page !== currentPage"
/>
</template>
<BaseButton <BaseButton
v-for="page in pagesList" :disabled="currentPage >= numPages - 1"
:key="page" @click="goToPage(currentPage + 1)"
:active="page === currentPage" :icon="mdiChevronRight"
:label="page + 1"
small small
:outline="styleService.darkMode" outline
@click="currentPage = page"
/> />
</BaseButtons> </div>
<small>Page {{ currentPageHuman }} of {{ numPages }}</small>
</BaseLevel> --> <span class="text-sm text-gray-600 dark:text-gray-400"> Page {{ currentPageHuman }} of {{ numPages }} </span>
</div>
</div> </div>
</template> </template>
<style lang="postcss" scoped>
.drag-handle {
transition: color 0.2s;
}
.card {
@apply bg-white dark:bg-slate-900 rounded-lg shadow-sm;
}
/* Improve table responsiveness */
@media (max-width: 768px) {
table {
font-size: 0.875rem;
}
th,
td {
padding: 0.5rem !important;
}
}
</style>

View file

@ -132,13 +132,25 @@ export interface Description {
export interface Person { export interface Person {
id?: number; id?: number;
name?: string; // Name fields
first_name?: string;
last_name?: string; // Also used for organization name
name?: string; // Alternative full name field
email: string; email: string;
name_type?: string; name_type?: string;
// Additional identifiers
identifier_orcid?: string; identifier_orcid?: string;
datasetCount?: string;
// Status and metadata
status: boolean; // true = read-only/locked, false = editable
created_at?: string; created_at?: string;
status: boolean; updated_at?: string;
// Statistics
datasetCount?: string;
// Relationship data (for many-to-many relationships)
pivot_contributor_type?: string; // Type of contribution (e.g., 'Author', 'Editor', 'Contributor')
} }
interface IErrorMessage { interface IErrorMessage {