feat: Add and refactor MIME type management

- Added BaseModel with fillable attributes and mergeFillableAttributes method
- Refactored MimeType model to extend BaseModel
- Implemented destroy method in MimetypeController for deleting MIME types
- Updated Create.vue component with refactoring and improved type safety
- Fixed issues with ref usage in Create.vue
- Updated routes to include new and refactored endpoints
This commit is contained in:
Kaimbacher 2025-01-12 15:47:25 +01:00
parent d1480b1240
commit 537c6fd81a
10 changed files with 321 additions and 449 deletions

View File

@ -106,7 +106,7 @@ export default class MimetypeController {
public async down({ request, response }: HttpContext) {
const id = request.param('id');
const mimetype = await MimeType.findOrFail(id);
const mimetype = (await MimeType.findOrFail(id)) as MimeType;
mimetype.enabled = false;
await mimetype.save();
@ -138,4 +138,46 @@ export default class MimetypeController {
// // roleHasPermissions: Object.keys(rolerHasPermissions).map((key) => rolerHasPermissions[key]), //convert object to array with role ids
// });
// }
public async delete({ request, inertia, response, session }: HttpContext) {
const id = request.param('id');
try {
const mimetype = await MimeType.query()
// .preload('user', (builder) => {
// builder.select('id', 'login');
// })
.where('id', id)
// .preload('files')
.firstOrFail();
// const validStates = ['inprogress', 'rejected_editor'];
// if (!validStates.includes(dataset.server_state)) {
// // session.flash('errors', 'Invalid server state!');
// return response
// .flash(
// 'warning',
// `Invalid server state. Dataset with id ${id} cannot be deleted. Datset has server state ${dataset.server_state}.`,
// )
// .redirect()
// .toRoute('dataset.list');
// }
return inertia.render('Admin/Mimetype/Delete', {
mimetype,
});
} catch (error) {
if (error.code == 'E_ROW_NOT_FOUND') {
session.flash({ warning: 'Mimetype is not found in database' });
} else {
session.flash({ warning: 'general error occured, you cannot delete the mimetype' });
}
return response.redirect().toRoute('mimetype.index');
}
}
public async deleteStore({ request, response, session }: HttpContext) {
const id = request.param('id');
const mimetype = await MimeType.findOrFail(id);
await mimetype.delete();
session.flash('message', `Mimetype ${mimetype.name} has been deleted.`);
return response.redirect().toRoute('settings.mimetype.index');
}
}

View File

@ -1,3 +1,4 @@
// import { BaseModel as LucidBaseModel } from '@adonisjs/lucid/orm';
import { BaseModel as LucidBaseModel } from '@adonisjs/lucid/orm';
// import { ManyToManyQueryClient } from '@ioc:Adonis/Lucid/Orm';
@ -29,8 +30,9 @@ export default class BaseModel extends LucidBaseModel {
*/
// private fillInvoked: boolean = false;
[key: string]: any;
// [key: string]: any;
public static fillable: string[] = [];
public fill(attributes: any, allowExtraProperties: boolean = false): this {

View File

@ -36,7 +36,7 @@ export default abstract class DatasetExtension extends LucidBaseModel {
// which fields shoud#t be published
protected internalFields: Record<string, any> = {};
protected fields: Record<string, any> = {};
[key: string]: any;
// [key: string]: any;
private getExternalFields(): Record<string, any> {
// External fields definition

View File

@ -2,10 +2,10 @@ import { ApplicationService } from '@adonisjs/core/types';
// import { Database, DatabaseQueryBuilder } from '@adonisjs/lucid/database';
import { ModelQueryBuilder } from '@adonisjs/lucid/orm';
// import db from '@adonisjs/lucid/services/db';
import { LucidModel, LucidRow } from '@adonisjs/lucid/types/model';
// import { LucidModel, LucidRow } from '@adonisjs/lucid/types/model';
import { ChainableContract, ExcutableQueryBuilderContract } from '@adonisjs/lucid/types/querybuilder';
import { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model';
// import { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model';
/*
|--------------------------------------------------------------------------
| Provider
@ -37,16 +37,23 @@ declare module '@adonisjs/lucid/types/model' {
// selectId(primaryKey?: string): Promise<number | undefined>;
// selectIdOrFail(primaryKey?: string): Promise<number>;
// pluck(valueColumn: string, id?: string): Promise<{ [key: string]: any }>;
pluck<T extends LucidModel>(valueColumn: string, id?: string): Promise<{ [key: string]: any }>;
pluck(valueColumn: string, id?: string): Promise<{ [key: string]: any }>;
}
export interface LucidRow {
[key: string]: any;
}
}
declare module '@adonisjs/lucid/orm' {
class ModelQueryBuilder extends Chainable implements ModelQueryBuilderContract<LucidModel, LucidRow> {
public pluck(valueColumn: string, id?: string): Promise<{ [key: string]: any }>;
interface ModelQueryBuilder {
pluck(valueColumn: string, id?: string): Promise<{ [key: string]: any }>;
}
// class ModelQueryBuilder implements ModelQueryBuilderContract<LucidModel, LucidRow> {
// public pluck(valueColumn: string, id?: string): Promise<{ [key: string]: any }>;
// }
}

View File

@ -5,6 +5,7 @@
"assets/resources_js_apps_settings_l18n_en_js.js": "http://localhost:8080/assets/resources_js_apps_settings_l18n_en_js.js",
"assets/resources_js_Pages_Admin_License_Index_vue.js": "http://localhost:8080/assets/resources_js_Pages_Admin_License_Index_vue.js",
"assets/resources_js_Pages_Admin_Mimetype_Create_vue.js": "http://localhost:8080/assets/resources_js_Pages_Admin_Mimetype_Create_vue.js",
"assets/resources_js_Pages_Admin_Mimetype_Delete_vue.js": "http://localhost:8080/assets/resources_js_Pages_Admin_Mimetype_Delete_vue.js",
"assets/resources_js_Pages_Admin_Mimetype_Index_vue.js": "http://localhost:8080/assets/resources_js_Pages_Admin_Mimetype_Index_vue.js",
"assets/resources_js_Pages_Admin_Permission_Create_vue.js": "http://localhost:8080/assets/resources_js_Pages_Admin_Permission_Create_vue.js",
"assets/resources_js_Pages_Admin_Permission_Edit_vue.js": "http://localhost:8080/assets/resources_js_Pages_Admin_Permission_Edit_vue.js",
@ -97,5 +98,6 @@
"assets/images/marker-icon.png": "http://localhost:8080/assets/images/marker-icon.2b3e1faf.png",
"assets/images/layers-2x.png": "http://localhost:8080/assets/images/layers-2x.8f2c4d11.png",
"assets/images/layers.png": "http://localhost:8080/assets/images/layers.416d9136.png",
"assets/images/Close.svg": "http://localhost:8080/assets/images/Close.e4887675.svg"
"assets/images/Close.svg": "http://localhost:8080/assets/images/Close.e4887675.svg",
"assets/vendors-node_modules_vue-facing-decorator_dist_esm_index_js-node_modules_vue-facing-decorator-818045.js": "http://localhost:8080/assets/vendors-node_modules_vue-facing-decorator_dist_esm_index_js-node_modules_vue-facing-decorator-818045.js"
}

View File

@ -27,23 +27,42 @@ const props = defineProps({
ctrlKFocus: Boolean,
});
const isReadOnly = true;
// Get keys from standardTypes and otherTypes
const isReadOnly: boolean = true;
const standardMimeTypes = Object.keys(standardTypes);
const otherMimeTypes = Object.keys(otherTypes);
// MIME types list (you can expand this as needed)
// const mimeTypes = Object.keys(standardTypes);
// Concatenate the keys from both types
const mimeTypes = [...standardMimeTypes, ...otherMimeTypes];
const file_extensions = reactive({});
const form = useForm({
const file_extensions = reactive<Record<string, string>>({});
interface FormData {
name: string;
file_extension: string[];
enabled: boolean;
}
const form = useForm<FormData>({
name: '',
file_extension: [] as Array<string>,
file_extension: [],
enabled: true,
});
const filteredMimetypes = ref<string[]>([]); // Stores the filtered MIME types for the dropdown
const showDropdown = ref(false); // Controls the visibility of the autocomplete dropdown
const selectedIndex: Ref<number> = ref(0); // Track selected MIME type in the dropdown
const ul: Ref<HTMLLIElement[] | null> = ref<HTMLLIElement[]>([]);
const newExtension: Ref = ref(''); //reactive([] as Array<string>);
const mimetypeError = ref<string | null>(null);
watch(selectedIndex, (selectedIndex: number) => {
if (selectedIndex != null && ul.value != null) {
const currentElement: HTMLLIElement = ul.value[selectedIndex];
currentElement &&
currentElement?.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
}
});
// Function to reset the object
function resetFileExtensions() {
// Reset to an empty object
@ -66,89 +85,15 @@ const inputElClass = computed(() => {
return base;
});
// Handle form submission
const submit = async () => {
if (isValidForm()) {
await form.post(stardust.route('settings.mimetype.store'), form);
}
};
// Form validation before submission
const isValidForm = (): boolean => {
if (!form.name) {
form.errors.name = 'Name is required.';
return false;
} else {
form.errors.name = '';
}
if (!form.file_extension.length) {
form.errors.file_extension = ['At least one file extension is required.'];
return false;
}
return true;
};
const newExtension: Ref = ref(''); //reactive([] as Array<string>);
const filteredMimetypes = ref<string[]>([]); // Stores the filtered MIME types for the dropdown
const showDropdown = ref(false); // Controls the visibility of the autocomplete dropdown
const selectedIndex: Ref<number> = ref(0); // Track selected MIME type in the dropdown
const ul: Ref<Array<HTMLLIElement>> = ref([]);
watch(selectedIndex, (selectedIndex: number) => {
if (selectedIndex != null && ul.value != null) {
const currentElement: HTMLLIElement = ul.value[selectedIndex];
currentElement &&
currentElement.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
}
});
// const extensionError = ref<string | null>(null);
const mimetypeError = ref<string | null>(null);
// const addFileExtension = () => {
// if (newExtension.value && !form.file_extensions.includes(newExtension.value)) {
// if (isValidFileExtension(newExtension.value)) {
// form.file_extensions.push(newExtension.value);
// newExtension.value = ''; // Clear the input field
// extensionError.value = null; // Clear any existing error
// } else {
// extensionError.value = 'Invalid file extension or MIME type.';
// }
// }
// };
// // Helper to validate file extension
// const isValidFileExtension = (extension: string): boolean => {
// const mimeType = mime.getType(extension); // e.g. 'application/pdf'
// return mimeType !== null;
// };
// const removeFileExtension = (index: number) => {
// file_extensions.splice(index, 1); // Remove the extension at the given index
// };
// Check if the MIME type is valid
const isValidMimeType = (mimeType: string): boolean => {
let extensions = mime.getExtension(mimeType)
return extensions !== null;
};
// watch(newExtension, (value) => {
// if (value) {
// filteredMimetypes.value = mimeTypes.filter(mimeType =>
// mimeType.toLowerCase().includes(value.toLowerCase())
// );
// showDropdown.value = true;
// } else {
// showDropdown.value = false;
// }
// });
async function handleInputChange(e: Event) {
// const target = <HTMLInputElement>e.target;
const target = <HTMLInputElement>e.target;
newExtension.value = target.value;
if (newExtension.value.length >= 2) {
showDropdown.value = true;
@ -172,15 +117,10 @@ const selectResult = (mimeType: string) => {
if (form.name && isValidMimeType(form.name)) {
const extensions = mime.getAllExtensions(form.name) as Set<string>;
// Convert the Set to an array of objects
// Convert the Set to an object
// Iterate over each extension and set both key and value to the extension
Array.from(extensions).forEach(extension => {
file_extensions[extension] = extension;
});
// file_extensions.push(...Array.from(formattedExtensions));
} else {
mimetypeError.value = 'Invalid MIME type.';
}
@ -201,7 +141,6 @@ function onArrowUp() {
function onEnter() {
if (Array.isArray(filteredMimetypes.value) && filteredMimetypes.value.length && selectedIndex.value !== -1 && selectedIndex.value < filteredMimetypes.value.length) {
//this.display = this.results[this.selectedIndex];
const mimeType = filteredMimetypes.value[selectedIndex.value];
// this.$emit('person', person);
form.name = mimeType;
@ -221,7 +160,7 @@ function onEnter() {
// Convert the Set to an object
Array.from(extensions).forEach(extension => {
file_extensions[extension] = extension;
});
});
// file_extensions.push(...formattedExtensions);
} else {
@ -230,6 +169,31 @@ function onEnter() {
}
}
}
// Handle form submission
const submit = async () => {
if (isValidForm()) {
await form.post(stardust.route('settings.mimetype.store'), {
preserveScroll: true,
});
}
};
// Form validation before submission
const isValidForm = (): boolean => {
if (!form.name) {
form.errors.name = 'Name is required.';
return false;
} else {
form.errors.name = '';
}
if (!form.file_extension.length) {
form.errors.file_extension = 'At least one file extension is required.';
return false;
}
return true;
};
</script>
<template>
@ -268,11 +232,6 @@ function onEnter() {
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
<!-- <button type="button" @click="addDefaultFileExtensions"
class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300"
:disabled="!form.name">
+
</button> -->
<ul v-if="showDropdown && filteredMimetypes.length"
class="bg-white dark:bg-slate-800 w-full mt-2 max-h-28 overflow-y-auto scroll-smooth">
<li v-for="(mimeType, index) in filteredMimetypes" :key="index" @click="selectResult(mimeType)"
@ -280,10 +239,11 @@ function onEnter() {
:class="{
'bg-blue-500 text-white': selectedIndex === index,
'bg-white text-gray-900': selectedIndex !== index
}" :ref="(el: HTMLLIElement) => {
ul[index] = el;
}
">
}" :ref="(el) => {
if (ul) {
ul[index] = el as HTMLLIElement;
}
}">
<svg class="absolute w-4 h-4 left-2 top-2" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd"
@ -298,21 +258,9 @@ function onEnter() {
{{ mimetypeError }}
</div>
<!-- Enabled (Boolean) Input Field -->
<!-- <div class="mb-4 flex items-center">
<input
type="checkbox"
v-model="form.enabled"
id="enabled"
class="focus:ring-blue-500 h-4 w-4 text-blue-600 border-gray-300 rounded"
/>
<label for="enabled" class="ml-2 block text-sm font-medium text-gray-700">Enabled</label>
</div> -->
<FormField v-if="form.name" label="Mimetype Name" :class="{ 'text-red-400': form.errors.name }">
<FormControl v-model="form.name" name="display_name" :error="form.errors.name"
:is-read-only="isReadOnly">
:is-read-only=isReadOnly>
<div class="text-red-400 text-sm" v-if="form.errors.name">
{{ form.errors.name }}
</div>
@ -330,51 +278,15 @@ function onEnter() {
</label>
</FormField>
<!-- File Extensions Input Field -->
<!-- <div class="space-y-2">
<label for="newExtension" class="block text-sm font-medium text-gray-700">
File Extensions
</label>
<div class="flex items-center gap-2">
<input v-model="newExtension" type="text" id="newExtension"
placeholder="Enter file extension (e.g., pdf)"
class="block w-full border border-gray-300 rounded-lg px-4 py-2 focus:ring-blue-500 focus:border-blue-500" />
<button type="button" @click="addFileExtension"
class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300"
:disabled="!newExtension">
+
</button>
</div>
<div v-if="extensionError" class="text-red-400 text-sm mt-1">
{{ extensionError }}
</div>
</div> -->
<!-- File Extensions List -->
<!-- <div class="mt-4">
<h3 v-if="form.file_extensions.length > 0" class="text-lg font-medium text-gray-900">Added File
Extensions</h3>
<ul class="space-y-2 mt-2">
<li v-for="(extension, index) in form.file_extensions" :key="index"
class="flex justify-between items-center p-2 bg-gray-100 rounded-lg">
<span class="text-gray-800">{{ extension }}</span>
<button @click.prevent="removeFileExtension(index)"
class="text-red-500 hover:text-red-700 text-sm font-medium">
Remove
</button>
</li>
</ul>
</div> -->
<FormField label="Extensions" wrap-body>
<FormCheckRadioGroup v-model="form.file_extension" :options="file_extensions" name="file_extensions"
is-column />
</FormField>
<div class="text-red-400 text-sm"
v-if="form.errors.file_extension && Array.isArray(form.errors.file_extension)">
<!-- {{ errors.password_confirmation }} -->
{{ form.errors.file_extension.join(', ') }}
</div>
<BaseDivider />

View File

@ -0,0 +1,80 @@
<script setup lang="ts">
import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
import SectionMain from '@/Components/SectionMain.vue';
import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.vue';
import { useForm, Head, usePage } from '@inertiajs/vue3';
import { computed, Ref } from 'vue';
import CardBox from '@/Components/CardBox.vue';
import BaseButton from '@/Components/BaseButton.vue';
import BaseButtons from '@/Components/BaseButtons.vue';
import { stardust } from '@eidellev/adonis-stardust/client';
import { mdiArrowLeftBoldOutline, mdiDeleteForever, mdiTrashCan } from '@mdi/js';
import FormValidationErrors from '@/Components/FormValidationErrors.vue';
const props = defineProps({
mimetype: {
type: Object,
default: () => ({}),
},
});
const flash: Ref<any> = computed(() => {
return usePage().props.flash;
});
const errors: Ref<any> = computed(() => {
return usePage().props.errors;
});
const form = useForm({
preferred_reviewer: '',
preferred_reviewer_email: '',
preferation: 'yes_preferation',
// preferation: '',
// isPreferationRequired: false,
});
const handleSubmit = async (e) => {
e.preventDefault();
await form.delete(stardust.route('settings.mimetype.deleteStore', [props.mimetype.id]));
};
</script>
<template>
<LayoutAuthenticated>
<Head title="Delete mimetype" />
<SectionMain>
<SectionTitleLineWithButton :icon="mdiDeleteForever" title="Delete Mimetype" main>
<BaseButton :route-name="stardust.route('settings.mimetype.index')" :icon="mdiArrowLeftBoldOutline" label="Back"
color="white" rounded-full small />
</SectionTitleLineWithButton>
<CardBox form @submit.prevent="handleSubmit">
<FormValidationErrors v-bind:errors="errors" />
<div class="modal-content py-4 text-left px-6">
<div class="text-xl font-bold mb-4">Confirm Deletion</div>
<p>Are you sure you want to delete the mimetype?</p>
<ul class="mt-4 space-y-4 text-left text-gray-500 dark:text-gray-400">
<li class="flex items-center space-x-3">
<svg class="flex-shrink-0 w-3.5 h-3.5 text-green-500 dark:text-green-400" aria-hidden="true"
xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 12">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M1 5.917 5.724 10.5 15 1.5" />
</svg>
<span>{{ props.mimetype.name }} ({{ props.mimetype.file_extension }})</span>
</li>
</ul>
</div>
<div v-if="flash && flash.warning" class="flex flex-col mt-6 animate-fade-in">
<div class="bg-yellow-500 border-l-4 border-orange-400 text-white p-4" role="alert">
<p class="font-bold">Be Warned</p>
<p>{{ flash.warning }}</p>
</div>
</div>
<template #footer>
<BaseButtons>
<BaseButton type="submit" color="danger" :icon="mdiTrashCan" :small="true"
:class="{ 'opacity-25': form.processing }" :disabled="form.processing" label="Confirm Delete" />
</BaseButtons>
</template>
</CardBox>
</SectionMain>
</LayoutAuthenticated>
</template>

View File

@ -1,6 +1,6 @@
<script lang="ts" setup>
import { Head, usePage } from '@inertiajs/vue3';
import { mdiAccountKey, mdiSquareEditOutline, mdiAlertBoxOutline, mdiPlus } from '@mdi/js';
import { mdiAccountKey, mdiSquareEditOutline, mdiAlertBoxOutline, mdiPlus, mdiTrashCan } from '@mdi/js';
import { computed, ComputedRef } from 'vue';
import type { PropType } from "vue";
import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
@ -33,19 +33,12 @@ defineProps({
const flash: ComputedRef<any> = computed(() => {
return usePage().props.flash;
});
</script>
<template>
<LayoutAuthenticated>
<Head title="Mime Types" />
<SectionMain>
<!--
<SectionTitleLineWithButton :icon="mdiAccountKey" title="Mime Types" main>
</SectionTitleLineWithButton> -->
<SectionTitleLineWithButton :icon="mdiAccountKey" title="Mime Types" main>
<BaseButton
v-if="can.create"
@ -61,24 +54,14 @@ const flash: ComputedRef<any> = computed(() => {
{{ flash.message }}
</NotificationBar>
<CardBox class="mb-6" has-table>
</CardBox>
<CardBox class="mb-6" has-form-data>
<table>
<thead>
<tr>
<th>
<!-- <Sort label="Name" attribute="name" /> -->
Name
</th>
<th>
<!-- <Sort label="Sort Order" attribute="sort_order" /> -->
Status
</th>
<th>Name</th>
<th>Status</th>
<th v-if="can.edit">Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="mimetype in mimetypes" :key="mimetype.id">
<td data-label="Name">
@ -88,7 +71,6 @@ const flash: ComputedRef<any> = computed(() => {
<template v-if="mimetype.enabled">Active</template>
<template v-else>Inactive</template>
</td>
<td v-if="can.edit" class="before:hidden lg:w-1 whitespace-nowrap">
<BaseButtons type="justify-start lg:justify-end" no-wrap>
<BaseButton v-if="mimetype.enabled"
@ -97,6 +79,9 @@ const flash: ComputedRef<any> = computed(() => {
<BaseButton v-else
:route-name="stardust.route('settings.mimetype.up', [mimetype.id])"
color="success" :icon="mdiSquareEditOutline" label="enable" small />
<BaseButton v-if="can.edit" color="danger"
:route-name="stardust.route('settings.mimetype.delete', [mimetype.id])" :icon="mdiTrashCan"
small />
</BaseButtons>
</td>
</tr>

View File

@ -15,4 +15,5 @@
},
},
"include": ["./**/*.ts", "./**/*.vue"],
"exclude": ["./utils/*.js"],
}

View File

@ -19,14 +19,9 @@
*/
import OaiController from '#controllers/Http/Oai/OaiController';
import router from '@adonisjs/core/services/router';
import type { HttpContext } from '@adonisjs/core/http';
// import Inertia from '@ioc:EidelLev/Inertia';
// import AuthValidator from '#validators/auth_validator';
import { authValidator } from '#validators/auth';
// import HealthCheck from '@ioc:Adonis/Core/HealthCheck';
import User from '#models/user';
import AuthController from '#controllers/Http/Auth/AuthController';
import UserController from '#controllers/Http/Auth/UserController';
@ -35,315 +30,161 @@ import RoleController from '#controllers/Http/Admin/RoleController';
import LicenseController from '#controllers/Http/Admin/LicenseController';
import MimetypeController from '#controllers/Http/Admin/MimetypeController';
import MailSettingsController from '#controllers/Http/Admin/mailsettings_controller';
import DatasetController from '#app/Controllers/Http/Submitter/DatasetController';
import PersonController from '#app/Controllers/Http/Submitter/PersonController';
import EditorDatasetController from '#app/Controllers/Http/Editor/DatasetController';
import ReviewerDatasetController from '#app/Controllers/Http/Reviewer/DatasetController';
import EditorDatasetController from '#app/Controllers/Http/Editor/DatasetController';
import ReviewerDatasetController from '#app/Controllers/Http/Reviewer/DatasetController';
import './routes/api.js';
import { middleware } from './kernel.js'
import { middleware } from './kernel.js';
import db from '@adonisjs/lucid/services/db'; // Import the DB service
// router.get('health', async ({ response }) => {
// const report = await HealthCheck.getReport();
// return report.healthy ? response.ok(report) : response.badRequest(report);
// });
router.get('/health', ({ response }: HttpContext) => response.noContent());
//oai:
// Route.get( '/oai', 'Oai/RequestController.index').as('oai');
// OAI routes
router.group(() => {
router.get('/oai', [OaiController, 'index']).as('get');
router.post('/oai', [OaiController, 'index']).as('post');
})
.as('oai');
router.get('/oai', [OaiController, 'index']).as('get');
router.post('/oai', [OaiController, 'index']).as('post');
}).as('oai');
//old solution:
// Welcome route
router.get('/welcome', async ({ view }: HttpContext) => {
return view.render('welcome');
})
.as('welcome');
return view.render('welcome');
}).as('welcome');
// Dashboard route
router.get('/', async ({ response }: HttpContext) => {
return response.redirect().toRoute('apps.dashboard');
})
.as('dashboard');
return response.redirect().toRoute('apps.dashboard');
}).as('dashboard');
// apps group
// Apps group
router.group(() => {
router.get('/dashboard', async ({ inertia }: HttpContext) => {
return inertia.render('Dashboard');
})
.as('dashboard');
router.get('/dashboard', async ({ inertia }: HttpContext) => {
return inertia.render('Dashboard');
}).as('dashboard');
router.get('/map', async ({ inertia }: HttpContext) => {
return inertia.render('Map');
})
.as('map');
router.get('/map', async ({ inertia }: HttpContext) => {
return inertia.render('Map');
}).as('map');
router.get('/', async ({ inertia }: HttpContext) => {
const users = await User.query().orderBy('login');
return inertia.render('App', {
testing: 'this is a test',
users: users,
});
})
.as('index');
router.get('/', async ({ inertia }: HttpContext) => {
const users = await User.query().orderBy('login');
return inertia.render('App', {
testing: 'this is a test',
users: users,
});
}).as('index');
// Route.get('/login', async ({ inertia }) => {
// return inertia.render('Auth/Login');
// }).as('login.show');
router.get('/register', async ({ inertia }: HttpContext) => {
return inertia.render('register-view/register-view-component');
}).as('register.show');
router.get('/register', async ({ inertia }: HttpContext) => {
return inertia.render('register-view/register-view-component');
})
.as('register.show');
router.post('/register', async ({ request, response }: HttpContext) => {
const data = await request.validateUsing(authValidator);
return response.redirect().toRoute('app.index');
}).as('register.store');
}).prefix('apps').as('apps').use(middleware.auth());
router.post('/register', async ({ request, response }: HttpContext) => {
console.log({
registerBody: request.body(),
});
const data = await request.validateUsing(authValidator);
console.log({ data });
return response.redirect().toRoute('app.index');
})
.as('register.store');
})
.prefix('apps')
.as('apps')
.use(middleware.auth());
// Route.on("/login").render("signin");
// Auth routes
router.get('/app/login', ({ inertia }: HttpContext) => {
return inertia.render('Auth/Login');
return inertia.render('Auth/Login');
}).as('app.login.show');
router.post('/app/login', [AuthController, 'login']).as('login.store');
router.post('/app/twoFactorChallenge', [AuthController, 'twoFactorChallenge']).as('login.twoFactorChallenge');
router.post('/signout', [AuthController, 'logout']).as('logout');
// administrator
// Administrator routes
router.group(() => {
router.get('/settings', async ({ inertia }: HttpContext) => {
const updatedConfigValue = await db.from('appconfigs')
router.get('/settings', async ({ inertia }: HttpContext) => {
const updatedConfigValue = await db.from('appconfigs')
.select('configvalue')
.where('appid', 'backgroundjob')
.where('configkey', 'lastjob')
.first();
// return inertia.render('Admin/Settings', {
// lastCron: updatedConfigValue.configvalue,
// });
if (updatedConfigValue != null) {
return inertia.render('Admin/Settings', {
lastCron: updatedConfigValue.configvalue,
});
} else {
// Handle the case where the config value is null
// For example, you can return a default value or render an error view
return inertia.render('Admin/Settings', {
lastCron: '', // Provide a default value if necessary
// error: 'Configuration not found', // Optional: provide an error message
});
}
})
.as('overview');
router.post('/mail/store', [MailSettingsController, 'setMailSettings']).as('mail.store').use(middleware.can(['user-create']));
router.post('/mail/send', [MailSettingsController, 'sendTestMail']).as('mail.send').use(middleware.can(['user-create']));
return inertia.render('Admin/Settings', {
lastCron: updatedConfigValue?.configvalue || '',
});
}).as('overview');
// user routes
router.get('/user', [AdminuserController, 'index']).as('user.index').use(middleware.can(['user-list']));
router.get('/user/create', [AdminuserController, 'create']).as('user.create').use(middleware.can(['user-create']));
router.post('/user/store', [AdminuserController, 'store']).as('user.store').use(middleware.can(['user-create']));
router.get('/user/:id', [AdminuserController, 'show']).as('user.show').where('id', router.matchers.number());
router.get('/user/:id/edit', [AdminuserController, 'edit']).as('user.edit').where('id', router.matchers.number()).use(middleware.can(['user-edit']));
router.put('/user/:id/update', [AdminuserController, 'update'])
.as('user.update')
.where('id', router.matchers.number())
.use(middleware.can(['user-edit']));
router.delete('/user/:id', [AdminuserController, 'destroy'])
.as('user.destroy')
.where('id', router.matchers.number())
.use(middleware.can(['user-delete']));
// // Route.resource('user', 'AdminuserController');
router.post('/mail/store', [MailSettingsController, 'setMailSettings']).as('mail.store').use(middleware.can(['user-create']));
router.post('/mail/send', [MailSettingsController, 'sendTestMail']).as('mail.send').use(middleware.can(['user-create']));
router.get('/role', [RoleController, 'index']).as('role.index').use(middleware.can(['user-list']));
router.get('/role/create', [RoleController, 'create']).as('role.create').use(middleware.can(['user-create']));
router.post('/role/store', [RoleController, 'store']).as('role.store').use(middleware.can(['user-create']));
router.get('/role/:id', [RoleController, 'show']).as('role.show').where('id', router.matchers.number());
router.get('/role/:id/edit', [RoleController, 'edit']).as('role.edit').where('id', router.matchers.number()).use(middleware.can(['user-edit']));
router.put('/role/:id/update', [RoleController, 'update'])
.as('role.update')
.where('id', router.matchers.number())
.use(middleware.can(['user-edit']));
// // Route.delete('/role/:id', [RoleController, 'destroy'])
// // .as('role.destroy')
// // .where('id', Route.matchers.number())
// // .use(middleware.can(['user-delete']));
// User routes
router.get('/user', [AdminuserController, 'index']).as('user.index').use(middleware.can(['user-list']));
router.get('/user/create', [AdminuserController, 'create']).as('user.create').use(middleware.can(['user-create']));
router.post('/user/store', [AdminuserController, 'store']).as('user.store').use(middleware.can(['user-create']));
router.get('/user/:id', [AdminuserController, 'show']).as('user.show').where('id', router.matchers.number());
router.get('/user/:id/edit', [AdminuserController, 'edit']).as('user.edit').where('id', router.matchers.number()).use(middleware.can(['user-edit']));
router.put('/user/:id/update', [AdminuserController, 'update']).as('user.update').where('id', router.matchers.number()).use(middleware.can(['user-edit']));
router.delete('/user/:id', [AdminuserController, 'destroy']).as('user.destroy').where('id', router.matchers.number()).use(middleware.can(['user-delete']));
router.get('/license', [LicenseController, 'index']).as('license.index');
// router.get('/license/:id/edit', [LicenseController, 'edit']).as('license.edit').where('id', router.matchers.number()).use(middleware.can(['settings']));
router.get('/license/:id/down', [LicenseController, 'down']).as('license.down').where('id', router.matchers.number()).use(middleware.can(['settings']));
router.get('/license/:id/up', [LicenseController, 'up']).as('license.up').where('id', router.matchers.number()).use(middleware.can(['settings']));
// Role routes
router.get('/role', [RoleController, 'index']).as('role.index').use(middleware.can(['user-list']));
router.get('/role/create', [RoleController, 'create']).as('role.create').use(middleware.can(['user-create']));
router.post('/role/store', [RoleController, 'store']).as('role.store').use(middleware.can(['user-create']));
router.get('/role/:id', [RoleController, 'show']).as('role.show').where('id', router.matchers.number());
router.get('/role/:id/edit', [RoleController, 'edit']).as('role.edit').where('id', router.matchers.number()).use(middleware.can(['user-edit']));
router.put('/role/:id/update', [RoleController, 'update']).as('role.update').where('id', router.matchers.number()).use(middleware.can(['user-edit']));
router.get('/mimetype', [MimetypeController, 'index']).as('mimetype.index');
// router.get('/mimetype/:id/edit', [MimetypeController, 'edit']).as('mimetype.edit').where('id', router.matchers.number()).use(middleware.can(['settings']));
router.get('/mimetype/create', [MimetypeController, 'create']).as('mimetype.create').use(middleware.can(['settings']));
router.post('/mimetype/store', [MimetypeController, 'store']).as('mimetype.store').use(middleware.can(['settings']));
router.get('/mimetype/:id/down', [MimetypeController, 'down']).as('mimetype.down').where('id', router.matchers.number()).use(middleware.can(['settings']));
router.get('/mimetype/:id/up', [MimetypeController, 'up']).as('mimetype.up').where('id', router.matchers.number()).use(middleware.can(['settings']));
// License routes
router.get('/license', [LicenseController, 'index']).as('license.index');
router.get('/license/:id/down', [LicenseController, 'down']).as('license.down').where('id', router.matchers.number()).use(middleware.can(['settings']));
router.get('/license/:id/up', [LicenseController, 'up']).as('license.up').where('id', router.matchers.number()).use(middleware.can(['settings']));
})
.prefix('admin')
.as('settings')
.use([middleware.auth(), middleware.is(['administrator', 'moderator'])])
// .middleware(['auth', 'is:administrator,moderator']);
// Mimetype routes
router.get('/mimetype', [MimetypeController, 'index']).as('mimetype.index');
router.get('/mimetype/create', [MimetypeController, 'create']).as('mimetype.create').use(middleware.can(['settings']));
router.post('/mimetype/store', [MimetypeController, 'store']).as('mimetype.store').use(middleware.can(['settings']));
router.get('/mimetype/:id/down', [MimetypeController, 'down']).as('mimetype.down').where('id', router.matchers.number()).use(middleware.can(['settings']));
router.get('/mimetype/:id/up', [MimetypeController, 'up']).as('mimetype.up').where('id', router.matchers.number()).use(middleware.can(['settings']));
router.get('/mimetype/:id/delete', [MimetypeController, 'delete']).as('mimetype.delete').use([middleware.auth(), middleware.can(['dataset-delete'])]);
router.delete('/mimetype/:id/deleteStore', [MimetypeController, 'deleteStore']).as('mimetype.deleteStore').use([middleware.auth(), middleware.can(['settings'])]);
}).prefix('admin').as('settings').use([middleware.auth(), middleware.is(['administrator', 'moderator'])]);
router.get('/settings/user/security', [UserController, 'accountInfo'])
.as('settings.user')
.use(middleware.auth());
router.get('/settings/user/security', [UserController, 'accountInfo']).as('settings.user').use(middleware.auth());
router.post('/settings/user/store', [UserController, 'accountInfoStore']).as('account.password.store').use(middleware.auth());
router.post('/settings/user/store', [UserController, 'accountInfoStore'])
.as('account.password.store')
.use(middleware.auth());
// Route::post('change-password', 'UserController@changePasswordStore')->name('admin.account.password.store');
// submitter:
// Submitter routes
router.group(() => {
router.get('/dataset', [DatasetController, 'index']).as('dataset.list').use([middleware.auth(), middleware.can(['dataset-list'])]);
router.get('/dataset/create', [DatasetController, 'create']).as('dataset.create').use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.post('/dataset/first/first-step', [DatasetController, 'firstStep'])
.as('dataset.first.step')
.use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.post('/dataset/second/second-step', [DatasetController, 'secondStep'])
.as('dataset.second.step')
.use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.post('/dataset/second/third-step', [DatasetController, 'thirdStep'])
.as('dataset.third.step')
.use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.get('/dataset/create', [DatasetController, 'create']).as('dataset.create').use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.post('/dataset/first/first-step', [DatasetController, 'firstStep']).as('dataset.first.step').use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.post('/dataset/second/second-step', [DatasetController, 'secondStep']).as('dataset.second.step').use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.post('/dataset/second/third-step', [DatasetController, 'thirdStep']).as('dataset.third.step').use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.post('/dataset/submit', [DatasetController, 'store']).as('dataset.submit').use([middleware.auth(), middleware.can(['dataset-submit'])]);
router.get('/dataset/:id/release', [DatasetController, 'release'])
.as('dataset.release')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.put('/dataset/:id/releaseupdate', [DatasetController, 'releaseUpdate'])
.as('dataset.releaseUpdate')
.use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.get('/dataset/:id/edit', [DatasetController, 'edit'])
.as('dataset.edit')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.put('/dataset/:id/update', [DatasetController,'update'])
.as('dataset.update')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.get('/dataset/:id/release', [DatasetController, 'release']).as('dataset.release').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.put('/dataset/:id/releaseupdate', [DatasetController, 'releaseUpdate']).as('dataset.releaseUpdate').use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.get('/dataset/:id/edit', [DatasetController, 'edit']).as('dataset.edit').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.put('/dataset/:id/update', [DatasetController, 'update']).as('dataset.update').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-edit'])]);
router.get('/dataset/:id/delete', [DatasetController, 'delete']).as('dataset.delete').use([middleware.auth(), middleware.can(['dataset-delete'])]);
router.put('/dataset/:id/deleteupdate', [DatasetController, 'deleteUpdate'])
.as('dataset.deleteUpdate')
.use([middleware.auth(), middleware.can(['dataset-delete'])]);
router.put('/dataset/:id/deleteupdate', [DatasetController, 'deleteUpdate']).as('dataset.deleteUpdate').use([middleware.auth(), middleware.can(['dataset-delete'])]);
router.get('/person', [PersonController, 'index']).as('person.index').use([middleware.auth()]);
router.get('/dataset/categorize', ({ inertia }: HttpContext) => {
return inertia.render('Submitter/Dataset/Category');
})
})
.prefix('submitter');
// .middleware(['auth', 'can:dataset-list,dataset-publish']);
// .middleware(['auth', 'is:submitter']);
});
}).prefix('submitter');
// editor:
// Editor routes
router.group(() => {
router.get('/dataset', [EditorDatasetController, 'index']).as('editor.dataset.list').use([middleware.auth(), middleware.can(['dataset-editor-list'])]);
router.get('dataset/:id/receive', [EditorDatasetController, 'receive'])
.as('editor.dataset.receive')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-receive'])]);
router.put('dataset/:id/receive', [EditorDatasetController, 'receiveUpdate'])
.as('editor.dataset.receiveUpdate')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-receive'])]);
router.get('dataset/:id/approve', [EditorDatasetController, 'approve'])
.as('editor.dataset.approve')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-approve'])]);
router.put('dataset/:id/approve', [EditorDatasetController, 'approveUpdate'])
.as('editor.dataset.approveUpdate')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-approve'])]);
router.get('dataset/:id/receive', [EditorDatasetController, 'receive']).as('editor.dataset.receive').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-receive'])]);
router.put('dataset/:id/receive', [EditorDatasetController, 'receiveUpdate']).as('editor.dataset.receiveUpdate').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-receive'])]);
router.get('dataset/:id/approve', [EditorDatasetController, 'approve']).as('editor.dataset.approve').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-approve'])]);
router.put('dataset/:id/approve', [EditorDatasetController, 'approveUpdate']).as('editor.dataset.approveUpdate').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-approve'])]);
router.get('dataset/:id/reject', [EditorDatasetController, 'reject']).as('editor.dataset.reject').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-editor-reject'])]);
router.put('dataset/:id/reject', [EditorDatasetController, 'rejectUpdate']).as('editor.dataset.rejectUpdate').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-editor-reject'])]);
router.get('dataset/:id/publish', [EditorDatasetController, 'publish']).as('editor.dataset.publish').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.put('dataset/:id/publish', [EditorDatasetController, 'publishUpdate']).as('editor.dataset.publishUpdate').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.get('dataset/:id/doi', [EditorDatasetController, 'doiCreate']).as('editor.dataset.doi').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.put('dataset/:publish_id/doi', [EditorDatasetController, 'doiStore']).as('editor.dataset.doiStore').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.put('/dataset/:id/update', [EditorDatasetController, 'update']).as('editor.dataset.update').use([middleware.auth(), middleware.can(['dataset-editor-edit'])]);
}).prefix('editor');
router.get('dataset/:id/reject', [EditorDatasetController, 'reject'])
.as('editor.dataset.reject')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-editor-reject'])]);
router.put('dataset/:id/reject', [EditorDatasetController, 'rejectUpdate'])
.as('editor.dataset.rejectUpdate')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-editor-reject'])]);
router.get('dataset/:id/publish', [EditorDatasetController, 'publish'])
.as('editor.dataset.publish')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.put('dataset/:id/publish', [EditorDatasetController, 'publishUpdate'])
.as('editor.dataset.publishUpdate')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.get('dataset/:id/doi', [EditorDatasetController, 'doiCreate'])
.as('editor.dataset.doi')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.put('dataset/:publish_id/doi', [EditorDatasetController, 'doiStore'])
.as('editor.dataset.doiStore')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-publish'])]);
router.put('/dataset/:id/update', [EditorDatasetController, 'update'])
.as('editor.dataset.update')
.use([middleware.auth(), middleware.can(['dataset-editor-edit'])]);
})
.prefix('editor');
// reviewer:
// Reviewer routes
router.group(() => {
router.get('/dataset', [ReviewerDatasetController, 'index']).as('reviewer.dataset.list').use([middleware.auth(), middleware.can(['dataset-review-list'])]);
router.get('dataset/:id/review', [ReviewerDatasetController, 'review'])
.as('reviewer.dataset.review')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-review'])]);
router.put('dataset/:id/review', [ReviewerDatasetController, 'reviewUpdate'])
.as('reviewer.dataset.reviewUpdate')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-review'])]);
router.get('dataset/:id/reject', [ReviewerDatasetController, 'reject'])
.as('reviewer.dataset.reject')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-review-reject'])]);
router.put('dataset/:id/reject', [ReviewerDatasetController, 'rejectUpdate'])
.as('reviewer.dataset.rejectUpdate')
.where('id', router.matchers.number())
.use([middleware.auth(), middleware.can(['dataset-review-reject'])]);
// Route.put('dataset/:id/approve', [ReviewerDatasetController, 'approveUpdate'])
// .as('editor.dataset.approveUpdate')
// .where('id', Route.matchers.number())
// .middleware(['auth', 'can:dataset-approve']);
// Route.put('/dataset/:id/update', [ReviewerDatasetController, 'update')
// .as('editor.dataset.update')
// .middleware(['auth', 'can:dataset-editor-edit']);
})
.prefix('reviewer');
router.get('dataset/:id/review', [ReviewerDatasetController, 'review']).as('reviewer.dataset.review').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-review'])]);
router.put('dataset/:id/review', [ReviewerDatasetController, 'reviewUpdate']).as('reviewer.dataset.reviewUpdate').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-review'])]);
router.get('dataset/:id/reject', [ReviewerDatasetController, 'reject']).as('reviewer.dataset.reject').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-review-reject'])]);
router.put('dataset/:id/reject', [ReviewerDatasetController, 'rejectUpdate']).as('reviewer.dataset.rejectUpdate').where('id', router.matchers.number()).use([middleware.auth(), middleware.can(['dataset-review-reject'])]);
}).prefix('reviewer');