feat(VnLog): refs #8449 use VnTableFilter

This commit is contained in:
Alex Moreno 2025-03-25 08:08:58 +01:00
parent 97ceffc96c
commit 443ac77f5d
7 changed files with 288 additions and 346 deletions

View File

@ -26,7 +26,12 @@ function columnName(col) {
}
</script>
<template>
<VnFilterPanel v-bind="$attrs" :search-button="true" :disable-submit-event="true">
<VnFilterPanel
v-bind="$attrs"
:search-button="true"
:disable-submit-event="true"
:search-url
>
<template #body="{ params, orders, searchFn }">
<div
class="container"
@ -34,13 +39,20 @@ function columnName(col) {
:key="col.id"
>
<div class="filter">
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
<slot
:name="`filter-${col.name}`"
:params="params"
:column-name="columnName(col)"
:search-fn
>
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
</slot>
</div>
<div class="order">
<VnTableOrder
@ -77,13 +89,13 @@ function columnName(col) {
display: flex;
justify-content: center;
align-items: center;
height: 45px;
min-height: 45px;
gap: 10px;
}
.filter {
width: 70%;
height: 40px;
min-height: 40px;
text-align: center;
}
.order {

View File

@ -1,5 +1,5 @@
<script setup>
import { ref, onUnmounted, watch } from 'vue';
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
@ -11,10 +11,9 @@ import { useCapitalize } from 'src/composables/useCapitalize';
import { useValidator } from 'src/composables/useValidator';
import VnAvatar from '../ui/VnAvatar.vue';
import VnLogValue from './VnLogValue.vue';
import FetchData from '../FetchData.vue';
import VnSelect from './VnSelect.vue';
import VnUserLink from '../ui/VnUserLink.vue';
import VnPaginate from '../ui/VnPaginate.vue';
import VnLogFilter from 'src/components/common/VnLogFilter.vue';
import RightMenu from './RightMenu.vue';
const stateStore = useStateStore();
@ -78,15 +77,8 @@ const searchInput = ref();
const userRadio = ref();
const userSelect = ref();
const dateFrom = ref();
const dateFromDialog = ref(false);
const dateTo = ref();
const dateToDialog = ref(false);
const selectedFilters = ref({});
const userTypes = [
{ label: 'All', value: undefined },
{ label: 'User', value: { neq: null } },
{ label: 'System', value: null },
];
const checkboxOptions = ref({
insert: {
label: 'Creates',
@ -134,6 +126,8 @@ const validDate = new RegExp(
/T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/.source,
);
const dataKey = computed(() => `${props.model}Log`);
function castJsonValue(value) {
return typeof value === 'string' && validDate.test(value) ? new Date(value) : value;
}
@ -271,91 +265,30 @@ async function applyFilter() {
paginate.value.fetch({ filter });
}
function setDate(type) {
let from = dateFrom.value
? date.formatDate(dateFrom.value.split('-').reverse().join('-'), 'YYYY-MM-DD')
: undefined;
from = date.adjustDate(from, { hour: 0, minute: 0, second: 0, millisecond: 0 }, true);
let to = dateTo.value
? date.formatDate(dateTo.value.split('-').reverse().join('-'), 'YYYY-MM-DD')
: date.formatDate(dateFrom.value.split('-').reverse().join('-'), 'YYYY-MM-DD');
to = date.adjustDate(
to,
{ hour: 21, minute: 59, second: 59, millisecond: 999 },
true,
);
switch (type) {
case 'from':
return { between: [from, to] };
case 'to': {
if (dateFrom.value) {
function exprBuilder(param, value) {
switch (param) {
case 'change':
if (value)
return {
between: [from, to],
or: [
{ oldJson: { like: `%${value}%` } },
{ newJson: { like: `%${value}%` } },
{ description: { like: `%${value}%` } },
],
};
}
return { lte: to };
}
break;
case 'action':
if (value?.length) return { [param]: { inq: value } };
break;
case 'from':
return { creationDate: { gt: value } };
case 'to':
return { creationDate: { lt: value } };
default:
return { [param]: value };
}
}
function selectFilter(type, dateType) {
const filter = {};
const actions = { inq: [] };
let reload = true;
if (type === 'search') {
if (/^\s*[0-9]+\s*$/.test(searchInput.value) || props.byRecord) {
selectedFilters.value.changedModelId = searchInput.value.trim();
} else if (!searchInput.value) {
selectedFilters.value.changedModelId = undefined;
selectedFilters.value.changedModelValue = undefined;
} else {
selectedFilters.value.changedModelValue = { like: `%${searchInput.value}%` };
}
}
if (type === 'action' && selectedFilters.value.changedModel === null) {
selectedFilters.value.changedModel = undefined;
}
if (type === 'userRadio') {
selectedFilters.value.userFk = userRadio.value;
}
if (type === 'change') {
if (changeInput.value)
selectedFilters.value.or = [
{ oldJson: { like: `%${changeInput.value}%` } },
{ newJson: { like: `%${changeInput.value}%` } },
{ description: { like: `%${changeInput.value}%` } },
];
else selectedFilters.value.or = undefined;
}
if (type === 'userSelect') {
selectedFilters.value.userFk =
userSelect.value !== null ? userSelect.value : undefined;
}
if (type === 'date') {
if (!dateFrom.value && !dateTo.value) {
selectedFilters.value.creationDate = undefined;
} else if (dateType === 'to') {
selectedFilters.value.creationDate = setDate('to');
} else if (dateType === 'from') {
selectedFilters.value.creationDate = setDate('from');
}
}
Object.keys(checkboxOptions.value).forEach((key) => {
if (checkboxOptions.value[key].selected) actions.inq.push(key);
});
selectedFilters.value.action = actions.inq.length ? actions : undefined;
Object.keys(selectedFilters.value).forEach((key) => {
if (selectedFilters.value[key]) filter[key] = selectedFilters.value[key];
});
if (reload) applyFilter(filter);
}
async function clearFilter() {
selectedFilters.value = {};
byRecord.value = false;
@ -371,6 +304,9 @@ async function clearFilter() {
await applyFilter();
}
onMounted(() => {
stateStore.rightDrawerChangeValue(true);
});
onUnmounted(() => {
stateStore.rightDrawer = false;
});
@ -383,32 +319,17 @@ watch(
);
</script>
<template>
<FetchData
:url="`${props.model}Logs/${route.params.id}/models`"
:filter="{ order: ['changedModel'] }"
@on-fetch="
(data) =>
(actions = data.map((item) => {
const changedModel = item.changedModel;
return {
locale: useCapitalize(
validations[changedModel]?.locale?.name ?? changedModel,
),
value: changedModel,
};
}))
"
auto-load
/>
<VnPaginate
ref="paginate"
:data-key="`${model}Log`"
:url="`${model}Logs`"
:data-key
:url="dataKey + 's'"
:user-filter="filter"
:skeleton="false"
auto-load
@on-fetch="setLogTree"
@on-change="setLogTree"
search-url="logs"
:exprBuilder
>
<template #body>
<div
@ -699,178 +620,9 @@ watch(
</VnPaginate>
<RightMenu>
<template #right-panel>
<QList dense>
<QSeparator />
<QItem class="q-mt-sm">
<QInput
:label="t('globals.search')"
v-model="searchInput"
class="full-width"
clearable
filled
clear-icon="close"
@keyup.enter="() => selectFilter('search')"
@focusout="() => selectFilter('search')"
@clear="() => selectFilter('search')"
>
<template #append>
<QIcon name="info" class="cursor-pointer">
<QTooltip>{{ t('tooltips.search') }}</QTooltip>
</QIcon>
</template>
</QInput>
</QItem>
<QItem>
<VnSelect
class="full-width"
:label="t('globals.entity')"
v-model="selectedFilters.changedModel"
option-label="locale"
option-value="value"
filled
:options="actions"
@update:model-value="selectFilter('action')"
hide-selected
/>
</QItem>
<QItem class="q-mt-sm">
<QOptionGroup
size="sm"
v-model="userRadio"
:options="userTypes"
color="primary"
@update:model-value="selectFilter('userRadio')"
right-label
>
<template #label="{ label }">
{{ t(`Users.${label}`) }}
</template>
</QOptionGroup>
</QItem>
<QItem class="q-mt-sm">
<QItemSection v-if="userRadio !== null">
<VnSelect
class="full-width"
:label="t('globals.user')"
v-model="userSelect"
filled
:url="`${model}Logs/${route.params.id}/editors`"
:fields="['id', 'nickname', 'name', 'image']"
sort-by="nickname"
@update:model-value="selectFilter('userSelect')"
hide-selected
>
<template #option="{ opt, itemProps }">
<QItem
v-bind="itemProps"
class="q-pa-xs row items-center"
>
<QItemSection class="col-3 items-center">
<VnAvatar :worker-id="opt.id" />
</QItemSection>
<QItemSection class="col-9 justify-center">
<span>{{ opt.name }}</span>
<span class="text-grey">{{ opt.nickname }}</span>
</QItemSection>
</QItem>
</template>
</VnSelect>
</QItemSection>
</QItem>
<QItem class="q-mt-sm">
<QInput
:label="t('globals.changes')"
v-model="changeInput"
class="full-width"
filled
clearable
clear-icon="close"
@keyup.enter="selectFilter('change')"
@focusout="selectFilter('change')"
@clear="selectFilter('change')"
>
<template #append>
<QIcon name="info" class="cursor-pointer">
<QTooltip max-width="250px">{{
t('tooltips.changes')
}}</QTooltip>
</QIcon>
</template>
</QInput>
</QItem>
<QItem
:class="index == 'create' ? 'q-mt-md' : 'q-mt-xs'"
v-for="(checkboxOption, index) in checkboxOptions"
:key="index"
>
<QCheckbox
size="sm"
v-model="checkboxOption.selected"
:label="t(`actions.${checkboxOption.label}`)"
@update:model-value="selectFilter"
/>
</QItem>
<QItem class="q-mt-sm">
<QInput
class="full-width"
:label="t('globals.date')"
@click="dateFromDialog = true"
@focus="(evt) => evt.target.blur()"
@clear="selectFilter('date', 'to')"
v-model="dateFrom"
clearable
filled
clear-icon="close"
/>
</QItem>
<QItem class="q-mt-sm">
<QInput
class="full-width"
:label="t('globals.to')"
@click="dateToDialog = true"
@focus="(evt) => evt.target.blur()"
@clear="selectFilter('date', 'from')"
v-model="dateTo"
clearable
filled
clear-icon="close"
/>
</QItem>
</QList>
<VnLogFilter :data-key />
</template>
</RightMenu>
<QDialog v-model="dateFromDialog">
<QDate
:years-in-month-view="false"
v-model="dateFrom"
dense
flat
minimal
filled
@update:model-value="
(value) => {
dateFromDialog = false;
dateFrom = date.formatDate(value, 'DD-MM-YYYY');
selectFilter('date', 'from');
}
"
/>
</QDialog>
<QDialog v-model="dateToDialog">
<QDate
v-model="dateTo"
dense
flat
minimal
@update:model-value="
(value) => {
dateToDialog = false;
dateTo = date.formatDate(value, 'DD-MM-YYYY');
selectFilter('date', 'to');
}
"
/>
</QDialog>
<QPageSticky position="bottom-right" :offset="[25, 25]">
<QBtn
v-if="Object.values(selectedFilters).some((filter) => filter !== undefined)"

View File

@ -1,77 +1,248 @@
<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnTableFilter from '../VnTable/VnTableFilter.vue';
import VnSelect from './VnSelect.vue';
import { useRoute } from 'vue-router';
import VnInput from './VnInput.vue';
import { ref, computed, watch } from 'vue';
import VnInputDate from './VnInputDate.vue';
import { useFilterParams } from 'src/composables/useFilterParams';
import FetchData from '../FetchData.vue';
import { useValidator } from 'src/composables/useValidator';
import { useCapitalize } from 'src/composables/useCapitalize';
const { t } = useI18n();
const props = defineProps({
const $props = defineProps({
dataKey: {
type: String,
required: true,
default: null,
},
});
const workers = ref();
const { t } = useI18n();
const route = useRoute();
const validationsStore = useValidator();
const { models } = validationsStore;
const entities = ref([]);
const editors = ref([]);
const userParams = ref(useFilterParams($props.dataKey).params);
const checkboxOptions = ref([
{ name: 'insert', label: 'Creates', selected: false },
{ name: 'update', label: 'Edits', selected: false },
{ name: 'delete', label: 'Deletes', selected: false },
{ name: 'select', label: 'Accesses', selected: false },
]);
const creationDate = ref({
from: null,
to: null,
});
let validations = models;
const columns = computed(() => [
{
name: 'search',
label: t('globals.search'),
},
{ name: 'changedModel' },
{ name: 'userFk' },
{ name: 'change' },
{ name: 'action' },
{ name: 'from' },
{ name: 'to' },
]);
const userParamsWatcher = watch(
() => userParams.value,
(params) => {
if (params.action) {
params.action.forEach((option) => {
checkboxOptions.value.find((o) => o.name === option).selected = true;
});
userParamsWatcher();
}
},
);
function calculateDate() {
const { from } = creationDate.value;
const to = creationDate.value.to ?? Date.vnNew();
if (from) return { between: [from, to] };
if (creationDate.value.to) return { lte: to };
}
function getActions() {
const actions = checkboxOptions.value
.filter((option) => option.selected)
?.map((o) => o.name);
return actions.length ? actions : null;
}
</script>
<template>
<FetchData
url="Workers/activeWithInheritedRole"
:filter="{ where: { role: 'salesPerson' } }"
@on-fetch="(data) => (workers = data)"
:url="`${dataKey}s/${route.params.id}/models`"
:filter="{ order: ['changedModel'] }"
@on-fetch="
(data) =>
(entities = data.map((item) => {
const changedModel = item.changedModel;
return {
locale: useCapitalize(
validations[changedModel]?.locale?.name ?? changedModel,
),
value: changedModel,
};
}))
"
auto-load
/>
<VnFilterPanel :data-key="props.dataKey" :search-button="true">
<template #tags="{ tag, formatFn }">
<div class="q-gutter-x-xs">
<strong>{{ t(`params.${tag.label}`) }}: </strong>
<span>{{ formatFn(tag.value) }}</span>
<FetchData
:url="`${dataKey}s/${route.params.id}/editors`"
:filter="{ fields: ['id', 'nickname', 'name', 'image'] }"
sort-by="nickname"
@on-fetch="(data) => (editors = data)"
auto-load
/>
<VnTableFilter
v-if="dataKey"
:dataKey
:columns="columns"
:redirect="false"
:hiddenTags="['originFk', 'creationDate']"
:exprBuilder
search-url="logs"
>
<template #filter-userFk="{ params, columnName, searchFn }">
<VnSelect
:label="t('globals.user')"
v-model="params[columnName]"
:options="editors"
@update:modelValue="() => searchFn()"
dense
filled
>
<template #option="{ opt, itemProps }">
<QItem v-bind="itemProps" class="q-pa-xs row items-center">
<QItemSection class="col-3 items-center">
<VnAvatar :worker-id="opt.id" />
</QItemSection>
<QItemSection class="col-9 justify-center">
<span>{{ opt.name }}</span>
<span class="text-grey">{{ opt.nickname }}</span>
</QItemSection>
</QItem>
</template>
</VnSelect>
</template>
<template #filter-changedModel="{ params, columnName, searchFn }">
<VnSelect
:label="t('globals.entity')"
v-model="params[columnName]"
option-label="locale"
option-value="value"
:options="entities"
@update:model-value="() => searchFn()"
dense
filled
/>
</template>
<template #filter-change="{ params, columnName, searchFn }">
<VnInput
:label="t('globals.changes')"
v-model="params[columnName]"
@keyup.enter="searchFn"
@blur="searchFn"
@remove="searchFn"
:info="t('tooltips.changes')"
dense
filled
/>
</template>
<template #filter-action="{ searchFn }">
<div class="column">
<QCheckbox
v-for="checkboxOption in checkboxOptions"
:key="checkboxOption"
size="sm"
v-model="checkboxOption.selected"
:label="t(`actions.${checkboxOption.label}`)"
@update:model-value="
() => searchFn(undefined, 'action', getActions())
"
/>
</div>
</template>
<template #body="{ params, searchFn }">
<QDate
v-model="params.created"
@update:model-value="searchFn()"
<!-- <template #filter-from="{ columnName, searchFn }">
<VnInputDate
:label="t('globals.from')"
v-model="creationDate[columnName]"
dense
flat
minimal
>
</QDate>
<QSeparator />
<QItem>
<QItemSection v-if="!workers">
<QSkeleton type="QInput" class="full-width" />
</QItemSection>
<QItemSection v-if="workers">
<QSelect
:label="t('User')"
v-model="params.userFk"
@update:model-value="searchFn()"
:options="workers"
option-value="id"
option-label="name"
emit-value
map-options
use-input
:input-debounce="0"
/>
</QItemSection>
</QItem>
filled
@update:modelValue="
() => searchFn(undefined, 'creationDate', calculateDate())
"
/>
</template>
</VnFilterPanel>
<template #filter-to="{ columnName, searchFn }">
<VnInputDate
:label="t('globals.to')"
v-model="creationDate[columnName]"
dense
filled
@update:modelValue="
() => searchFn(undefined, 'creationDate', calculateDate())
"
/>
</template> -->
<template #filter-from="{ params, columnName, searchFn }">
<VnInputDate
:label="t('globals.from')"
v-model="params[columnName]"
dense
filled
@update:modelValue="() => searchFn()"
/>
</template>
<template #filter-to="{ params, columnName, searchFn }">
<VnInputDate
:label="t('globals.to')"
v-model="params[columnName]"
dense
filled
@update:modelValue="() => searchFn()"
/>
</template>
</VnTableFilter>
</template>
<i18n>
en:
params:
search: Contains
userFk: User
created: Created
es:
tooltips:
search: Buscar por identificador o concepto
changes: Buscar por cambios. Los atributos deben buscarse por su nombre interno, para obtenerlo situar el cursor sobre el atributo.
actions:
Creates: Crea
Edits: Modifica
Deletes: Elimina
Accesses: Accede
Users:
User: Usuario
All: Todo
System: Sistema
params:
search: Contiene
userFk: Usuario
created: Creada
User: Usuario
changedModel: Entity
en:
tooltips:
search: Search by identifier or concept
changes: Search by changes. Attributes must be searched by their internal name, to get it place the cursor over the attribute.
actions:
Creates: Creates
Edits: Edits
Deletes: Deletes
Accesses: Accesses
Users:
User: User
All: All
System: System
params:
changedModel: Entidad
</i18n>

View File

@ -88,13 +88,14 @@ const userOrders = ref(useFilterParams($props.dataKey).orders);
defineExpose({ search, params: userParams, remove });
const isLoading = ref(false);
async function search(evt) {
async function search(evt, name, value) {
try {
if (evt && $props.disableSubmitEvent) return;
store.filter.where = {};
isLoading.value = true;
const filter = { ...userParams.value, ...$props.modelValue };
if (name) filter[name] = value;
store.userParamsChanged = true;
await arrayData.addFilter({
params: filter,

View File

@ -14,7 +14,7 @@ export function useFilterParams(key) {
watch(
() => arrayData.value.store?.currentFilter,
(val, oldValue) => (val || oldValue) && setUserParams(val),
{ immediate: true, deep: true }
{ immediate: true, deep: true },
);
function parseOrder(urlOrders) {
@ -54,7 +54,7 @@ export function useFilterParams(key) {
Object.assign(params, item);
});
delete params[key];
} else if (value && typeof value === 'object') {
} else if (value && typeof value === 'object' && !Array.isArray(value)) {
const param = Object.values(value)[0];
if (typeof param == 'string') params[key] = param.replaceAll('%', '');
}

View File

@ -370,6 +370,9 @@ globals:
countryCodeFk: Country
companyFk: Company
nickname: Alias
changedModel: Entity
userFk: User
action: Action
model: Model
fuel: Fuel
active: Active

View File

@ -371,6 +371,9 @@ globals:
countryCodeFk: País
companyFk: Empresa
nickname: Alias
changedModel: Entidad
userFk: Usuario
action: Acción
errors:
statusUnauthorized: Acceso denegado
statusInternalServerError: Ha ocurrido un error interno del servidor