Merge branch 'dev' into 8266-changeExpeditionItemNameFront
gitea/salix-front/pipeline/pr-dev This commit looks good Details

This commit is contained in:
JOSE ANTONIO TUBAU RODRIGUEZ 2024-12-24 12:03:14 +00:00
commit 87cf722c5f
251 changed files with 3595 additions and 2613 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "salix-front", "name": "salix-front",
"version": "24.52.0", "version": "25.02.0",
"description": "Salix frontend", "description": "Salix frontend",
"productName": "Salix", "productName": "Salix",
"author": "Verdnatura", "author": "Verdnatura",

View File

@ -1,4 +1,3 @@
import { Notify } from 'quasar';
import { onRequest, onResponseError } from 'src/boot/axios'; import { onRequest, onResponseError } from 'src/boot/axios';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
@ -27,6 +26,7 @@ describe('Axios boot', () => {
expect(resultConfig).toEqual( expect(resultConfig).toEqual(
expect.objectContaining({ expect.objectContaining({
headers: { headers: {
'Accept-Language': 'en-US',
Authorization: 'DEFAULT_TOKEN', Authorization: 'DEFAULT_TOKEN',
}, },
}) })

View File

@ -3,12 +3,12 @@ import { useSession } from 'src/composables/useSession';
import { Router } from 'src/router'; import { Router } from 'src/router';
import useNotify from 'src/composables/useNotify.js'; import useNotify from 'src/composables/useNotify.js';
import { useStateQueryStore } from 'src/stores/useStateQueryStore'; import { useStateQueryStore } from 'src/stores/useStateQueryStore';
import { i18n } from 'src/boot/i18n';
const session = useSession(); const session = useSession();
const { notify } = useNotify(); const { notify } = useNotify();
const stateQuery = useStateQueryStore(); const stateQuery = useStateQueryStore();
const baseUrl = '/api/'; const baseUrl = '/api/';
axios.defaults.baseURL = baseUrl; axios.defaults.baseURL = baseUrl;
const axiosNoError = axios.create({ baseURL: baseUrl }); const axiosNoError = axios.create({ baseURL: baseUrl });
@ -16,6 +16,7 @@ const onRequest = (config) => {
const token = session.getToken(); const token = session.getToken();
if (token.length && !config.headers.Authorization) { if (token.length && !config.headers.Authorization) {
config.headers.Authorization = token; config.headers.Authorization = token;
config.headers['Accept-Language'] = i18n.global.locale.value;
} }
stateQuery.add(config); stateQuery.add(config);
return config; return config;

View File

@ -1,9 +1,11 @@
import { boot } from 'quasar/wrappers'; import { boot } from 'quasar/wrappers';
import { createI18n } from 'vue-i18n'; import { createI18n } from 'vue-i18n';
import messages from 'src/i18n'; import messages from 'src/i18n';
import { useState } from 'src/composables/useState';
const user = useState().getUser();
const i18n = createI18n({ const i18n = createI18n({
locale: navigator.language || navigator.userLanguage, locale: user.value.lang || navigator.language || navigator.userLanguage,
fallbackLocale: 'en', fallbackLocale: 'en',
globalInjection: true, globalInjection: true,
messages, messages,

View File

@ -1,6 +1,5 @@
function focusFirstInput(input) { function focusFirstInput(input) {
input.focus(); input.focus();
return;
} }
export default { export default {
mounted: function () { mounted: function () {

View File

@ -1,20 +1,18 @@
import axios from 'axios';
import { boot } from 'quasar/wrappers'; import { boot } from 'quasar/wrappers';
import qFormMixin from './qformMixin'; import qFormMixin from './qformMixin';
import keyShortcut from './keyShortcut'; import keyShortcut from './keyShortcut';
import useNotify from 'src/composables/useNotify.js';
import { CanceledError } from 'axios';
import { QForm } from 'quasar'; import { QForm } from 'quasar';
import { QLayout } from 'quasar'; import { QLayout } from 'quasar';
import mainShortcutMixin from './mainShortcutMixin'; import mainShortcutMixin from './mainShortcutMixin';
import { useCau } from 'src/composables/useCau';
const { notify } = useNotify();
export default boot(({ app }) => { export default boot(({ app }) => {
QForm.mixins = [qFormMixin]; QForm.mixins = [qFormMixin];
QLayout.mixins = [mainShortcutMixin]; QLayout.mixins = [mainShortcutMixin];
app.directive('shortcut', keyShortcut); app.directive('shortcut', keyShortcut);
app.config.errorHandler = (error) => { app.config.errorHandler = async (error) => {
let message; let message;
const response = error.response; const response = error.response;
const responseData = response?.data; const responseData = response?.data;
@ -45,12 +43,12 @@ export default boot(({ app }) => {
} }
console.error(error); console.error(error);
if (error instanceof CanceledError) { if (error instanceof axios.CanceledError) {
const env = process.env.NODE_ENV; const env = process.env.NODE_ENV;
if (env && env !== 'development') return; if (env && env !== 'development') return;
message = 'Duplicate request'; message = 'Duplicate request';
} }
notify(message ?? 'globals.error', 'negative', 'error'); await useCau(response, message);
}; };
}); });

View File

@ -293,6 +293,7 @@ defineExpose({
class="q-pa-md" class="q-pa-md"
:style="maxWidth ? 'max-width: ' + maxWidth : ''" :style="maxWidth ? 'max-width: ' + maxWidth : ''"
id="formModel" id="formModel"
:prevent-submit="$attrs['prevent-submit']"
> >
<QCard> <QCard>
<slot <slot

View File

@ -92,15 +92,15 @@ function findMatches(search, item) {
} }
function addChildren(module, route, parent) { function addChildren(module, route, parent) {
if (route.menus) { const menus = route?.meta?.menu ?? route?.menus?.[props.source]; //backwards compatible
const mainMenus = route.menus[props.source]; if (!menus) return;
const matches = findMatches(mainMenus, route);
const matches = findMatches(menus, route);
for (const child of matches) { for (const child of matches) {
navigation.addMenuItem(module, child, parent); navigation.addMenuItem(module, child, parent);
} }
} }
}
function getRoutes() { function getRoutes() {
if (props.source === 'main') { if (props.source === 'main') {
@ -122,16 +122,26 @@ function getRoutes() {
if (props.source === 'card') { if (props.source === 'card') {
const currentRoute = route.matched[1]; const currentRoute = route.matched[1];
const currentModule = toLowerCamel(currentRoute.name); const currentModule = toLowerCamel(currentRoute.name);
const moduleDef = routes.find( let moduleDef = routes.find(
(route) => toLowerCamel(route.name) === currentModule (route) => toLowerCamel(route.name) === currentModule
); );
if (!moduleDef) return; if (!moduleDef) return;
if (!moduleDef?.menus) moduleDef = betaGetRoutes();
addChildren(currentModule, moduleDef, items.value); addChildren(currentModule, moduleDef, items.value);
} }
} }
function betaGetRoutes() {
let menuRoute;
let index = route.matched.length - 1;
while (!menuRoute && index > 0) {
if (route.matched[index]?.meta?.menu) menuRoute = route.matched[index];
index--;
}
return menuRoute;
}
async function togglePinned(item, event) { async function togglePinned(item, event) {
if (event.defaultPrevented) return; if (event.defaultPrevented) return;
event.preventDefault(); event.preventDefault();

View File

@ -17,12 +17,10 @@ const stateQuery = useStateQueryStore();
const state = useState(); const state = useState();
const user = state.getUser(); const user = state.getUser();
const appName = 'Lilium'; const appName = 'Lilium';
const pinnedModulesRef = ref();
onMounted(() => stateStore.setMounted()); onMounted(() => stateStore.setMounted());
const pinnedModulesRef = ref();
</script> </script>
<template> <template>
<QHeader color="white" elevated> <QHeader color="white" elevated>
<QToolbar class="q-py-sm q-px-md"> <QToolbar class="q-py-sm q-px-md">
@ -59,22 +57,13 @@ const pinnedModulesRef = ref();
'no-visible': !stateQuery.isLoading().value, 'no-visible': !stateQuery.isLoading().value,
}" }"
size="xs" size="xs"
data-cy="loading-spinner"
/> />
<QSpace /> <QSpace />
<div id="searchbar" class="searchbar"></div> <div id="searchbar" class="searchbar"></div>
<QSpace /> <QSpace />
<div class="q-pl-sm q-gutter-sm row items-center no-wrap"> <div class="q-pl-sm q-gutter-sm row items-center no-wrap">
<div id="actions-prepend"></div> <div id="actions-prepend"></div>
<QBtn
flat
v-if="!quasar.platform.is.mobile"
@click="pinnedModulesRef.redirect($route.params.id)"
icon="more_up"
>
<QTooltip>
{{ t('Go to Salix') }}
</QTooltip>
</QBtn>
<QBtn <QBtn
:class="{ 'q-pa-none': quasar.platform.is.mobile }" :class="{ 'q-pa-none': quasar.platform.is.mobile }"
id="pinnedModules" id="pinnedModules"
@ -106,7 +95,6 @@ const pinnedModulesRef = ref();
<VnBreadcrumbs v-if="$q.screen.lt.md" class="q-ml-md" /> <VnBreadcrumbs v-if="$q.screen.lt.md" class="q-ml-md" />
</QHeader> </QHeader>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.searchbar { .searchbar {
width: max-content; width: max-content;
@ -115,9 +103,3 @@ const pinnedModulesRef = ref();
background-color: var(--vn-section-color); background-color: var(--vn-section-color);
} }
</style> </style>
<i18n>
en:
Go to Salix: Go to Salix
es:
Go to Salix: Ir a Salix
</i18n>

View File

@ -87,10 +87,10 @@ async function saveDarkMode(value) {
async function saveLanguage(value) { async function saveLanguage(value) {
const query = `/VnUsers/${user.value.id}`; const query = `/VnUsers/${user.value.id}`;
try { try {
await axios.patch(query, { await axios.patch(query, { lang: value });
lang: value,
});
user.value.lang = value; user.value.lang = value;
useState().setUser(user.value);
onDataSaved(); onDataSaved();
} catch (error) { } catch (error) {
onDataError(); onDataError();

View File

@ -32,7 +32,10 @@ const $props = defineProps({
defineExpose({ addFilter, props: $props }); defineExpose({ addFilter, props: $props });
const model = defineModel(undefined, { required: true }); const model = defineModel(undefined, { required: true });
const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl }); const arrayData = useArrayData(
$props.dataKey,
$props.searchUrl ? { searchUrl: $props.searchUrl } : null
);
const columnFilter = computed(() => $props.column?.columnFilter); const columnFilter = computed(() => $props.column?.columnFilter);
const updateEvent = { 'update:modelValue': addFilter }; const updateEvent = { 'update:modelValue': addFilter };

View File

@ -1,20 +1,21 @@
<script setup> <script setup>
import { ref, onBeforeMount, onMounted, computed, watch } from 'vue'; import { ref, onBeforeMount, onMounted, computed, watch, useAttrs } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import { useFilterParams } from 'src/composables/useFilterParams';
import CrudModel from 'src/components/CrudModel.vue'; import CrudModel from 'src/components/CrudModel.vue';
import FormModelPopup from 'components/FormModelPopup.vue'; import FormModelPopup from 'components/FormModelPopup.vue';
import VnFilterPanel from 'components/ui/VnFilterPanel.vue';
import VnTableColumn from 'components/VnTable/VnColumn.vue'; import VnTableColumn from 'components/VnTable/VnColumn.vue';
import VnFilter from 'components/VnTable/VnFilter.vue'; import VnFilter from 'components/VnTable/VnFilter.vue';
import VnTableChip from 'components/VnTable/VnChip.vue'; import VnTableChip from 'components/VnTable/VnChip.vue';
import VnVisibleColumn from 'src/components/VnTable/VnVisibleColumn.vue'; import VnVisibleColumn from 'src/components/VnTable/VnVisibleColumn.vue';
import VnLv from 'components/ui/VnLv.vue'; import VnLv from 'components/ui/VnLv.vue';
import VnTableOrder from 'src/components/VnTable/VnOrder.vue'; import VnTableOrder from 'src/components/VnTable/VnOrder.vue';
import VnTableFilter from './VnTableFilter.vue';
const $props = defineProps({ const $props = defineProps({
columns: { columns: {
@ -33,6 +34,10 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: true, default: true,
}, },
rightSearchIcon: {
type: Boolean,
default: true,
},
rowClick: { rowClick: {
type: [Function, Boolean], type: [Function, Boolean],
default: null, default: null,
@ -101,10 +106,6 @@ const $props = defineProps({
type: String, type: String,
default: '90vh', default: '90vh',
}, },
chipLocale: {
type: String,
default: null,
},
footer: { footer: {
type: Boolean, type: Boolean,
default: false, default: false,
@ -119,22 +120,21 @@ const stateStore = useStateStore();
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const quasar = useQuasar(); const quasar = useQuasar();
const $attrs = useAttrs();
const CARD_MODE = 'card'; const CARD_MODE = 'card';
const TABLE_MODE = 'table'; const TABLE_MODE = 'table';
const mode = ref(CARD_MODE); const mode = ref(CARD_MODE);
const selected = ref([]); const selected = ref([]);
const hasParams = ref(false); const hasParams = ref(false);
const routeQuery = JSON.parse(route?.query[$props.searchUrl] ?? '{}');
const params = ref({ ...routeQuery, ...routeQuery.filter?.where });
const orders = ref(parseOrder(routeQuery.filter?.order));
const CrudModelRef = ref({}); const CrudModelRef = ref({});
const showForm = ref(false); const showForm = ref(false);
const splittedColumns = ref({ columns: [] }); const splittedColumns = ref({ columns: [] });
const columnsVisibilitySkipped = ref(); const columnsVisibilitySkipped = ref();
const createForm = ref(); const createForm = ref();
const tableFilterRef = ref([]);
const tableRef = ref(); const tableRef = ref();
const params = ref(useFilterParams($attrs['data-key']).params);
const orders = ref(useFilterParams($attrs['data-key']).orders);
const tableModes = [ const tableModes = [
{ {
@ -150,6 +150,7 @@ const tableModes = [
disable: $props.disableOption?.card, disable: $props.disableOption?.card,
}, },
]; ];
onBeforeMount(() => { onBeforeMount(() => {
const urlParams = route.query[$props.searchUrl]; const urlParams = route.query[$props.searchUrl];
hasParams.value = urlParams && Object.keys(urlParams).length !== 0; hasParams.value = urlParams && Object.keys(urlParams).length !== 0;
@ -162,7 +163,9 @@ onMounted(() => {
: $props.defaultMode; : $props.defaultMode;
stateStore.rightDrawer = quasar.screen.gt.xs; stateStore.rightDrawer = quasar.screen.gt.xs;
columnsVisibilitySkipped.value = [ columnsVisibilitySkipped.value = [
...splittedColumns.value.columns.filter((c) => !c.visible).map((c) => c.name), ...splittedColumns.value.columns
.filter((c) => c.visible === false)
.map((c) => c.name),
...['tableActions'], ...['tableActions'],
]; ];
createForm.value = $props.create; createForm.value = $props.create;
@ -181,41 +184,8 @@ watch(
{ immediate: true } { immediate: true }
); );
watch(
() => route.query[$props.searchUrl],
(val) => setUserParams(val),
{ immediate: true, deep: true }
);
const isTableMode = computed(() => mode.value == TABLE_MODE); const isTableMode = computed(() => mode.value == TABLE_MODE);
const showRightIcon = computed(() => $props.rightSearch || $props.rightSearchIcon);
function setUserParams(watchedParams, watchedOrder) {
if (!watchedParams) return;
if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
const filter =
typeof watchedParams?.filter == 'string'
? JSON.parse(watchedParams?.filter ?? '{}')
: watchedParams?.filter;
const where = filter?.where;
const order = watchedOrder ?? filter?.order;
watchedParams = { ...watchedParams, ...where };
delete watchedParams.filter;
delete params.value?.filter;
params.value = { ...params.value, ...sanitizer(watchedParams) };
orders.value = parseOrder(order);
}
function sanitizer(params) {
for (const [key, value] of Object.entries(params)) {
if (value && typeof value == 'object') {
const param = Object.values(value)[0];
if (typeof param == 'string') params[key] = param.replaceAll('%', '');
}
}
return params;
}
function splitColumns(columns) { function splitColumns(columns) {
splittedColumns.value = { splittedColumns.value = {
@ -296,17 +266,6 @@ function getColAlign(col) {
return 'text-' + (col.align ?? 'left'); return 'text-' + (col.align ?? 'left');
} }
function parseOrder(urlOrders) {
const orderObject = {};
if (!urlOrders) return orderObject;
if (typeof urlOrders == 'string') urlOrders = [urlOrders];
for (const [index, orders] of urlOrders.entries()) {
const [name, direction] = orders.split(' ');
orderObject[name] = { direction, index: index + 1 };
}
return orderObject;
}
const emit = defineEmits(['onFetch', 'update:selected', 'saveChanges']); const emit = defineEmits(['onFetch', 'update:selected', 'saveChanges']);
defineExpose({ defineExpose({
create: createForm, create: createForm,
@ -355,61 +314,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
show-if-above show-if-above
> >
<QScrollArea class="fit"> <QScrollArea class="fit">
<VnFilterPanel <VnTableFilter :data-key="$attrs['data-key']" :columns="columns" />
:data-key="$attrs['data-key']"
:search-button="true"
v-model="params"
:search-url="searchUrl"
:redirect="!!redirect"
@set-user-params="setUserParams"
:disable-submit-event="true"
@remove="
(key) =>
tableFilterRef
.find((f) => f.props?.column.name == key)
?.addFilter()
"
>
<template #body>
<div
class="row no-wrap flex-center"
v-for="col of splittedColumns.columns.filter(
(c) => c.columnFilter ?? true
)"
:key="col.id"
>
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
<VnTableOrder
v-if="
col?.columnFilter !== false &&
col?.name !== 'tableActions'
"
v-model="orders[col.orderBy ?? col.name]"
:name="col.orderBy ?? col.name"
:data-key="$attrs['data-key']"
:search-url="searchUrl"
:vertical="false"
/>
</div>
<slot
name="moreFilterPanel"
:params="params"
:columns="splittedColumns.columns"
/>
</template>
<template #tags="{ tag, formatFn }" v-if="chipLocale">
<div class="q-gutter-x-xs">
<strong>{{ t(`${chipLocale}.${tag.label}`) }}: </strong>
<span>{{ formatFn(tag.value) }}</span>
</div>
</template>
</VnFilterPanel>
</QScrollArea> </QScrollArea>
</QDrawer> </QDrawer>
<CrudModel <CrudModel
@ -465,7 +370,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
:options="tableModes.filter((mode) => !mode.disable)" :options="tableModes.filter((mode) => !mode.disable)"
/> />
<QBtn <QBtn
v-if="$props.rightSearch" v-if="showRightIcon"
icon="filter_alt" icon="filter_alt"
class="bg-vn-section-color q-ml-sm" class="bg-vn-section-color q-ml-sm"
dense dense
@ -479,7 +384,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
:class="col.headerClass" :class="col.headerClass"
> >
<div <div
class="column self-start q-ml-xs ellipsis" class="column ellipsis"
:class="`text-${col?.align ?? 'left'}`" :class="`text-${col?.align ?? 'left'}`"
:style="$props.columnSearch ? 'height: 75px' : ''" :style="$props.columnSearch ? 'height: 75px' : ''"
> >
@ -521,7 +426,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
<!-- Columns --> <!-- Columns -->
<QTd <QTd
auto-width auto-width
class="no-margin q-px-xs" class="no-margin"
:class="[getColAlign(col), col.columnClass]" :class="[getColAlign(col), col.columnClass]"
:style="col.style" :style="col.style"
v-if="col.visible ?? true" v-if="col.visible ?? true"
@ -656,13 +561,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
:key="col.name" :key="col.name"
class="fields" class="fields"
> >
<VnLv <VnLv :label="col.label + ':'">
:label="
!col.component && col.label
? `${col.label}:`
: ''
"
>
<template #value> <template #value>
<span <span
@click="stopEventPropagation($event)" @click="stopEventPropagation($event)"
@ -803,7 +702,7 @@ es:
.grid-three { .grid-three {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(400px, max-content)); grid-template-columns: repeat(auto-fit, minmax(350px, max-content));
max-width: 100%; max-width: 100%;
grid-gap: 20px; grid-gap: 20px;
margin: 0 auto; margin: 0 auto;
@ -852,21 +751,6 @@ es:
top: 0; top: 0;
padding: 12px 0; padding: 12px 0;
} }
tbody {
.q-checkbox {
display: flex;
margin-bottom: 9px;
& .q-checkbox__label {
margin-left: 31px;
color: var(--vn-text-color);
}
& .q-checkbox__inner {
position: absolute;
left: 0;
color: var(--vn-label-color);
}
}
}
.sticky { .sticky {
position: sticky; position: sticky;
right: 0; right: 0;

View File

@ -0,0 +1,72 @@
<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import VnFilterPanel from 'components/ui/VnFilterPanel.vue';
import VnFilter from 'components/VnTable/VnFilter.vue';
import VnTableOrder from 'src/components/VnTable/VnOrder.vue';
defineProps({
columns: {
type: Array,
required: true,
},
chipLocale: {
type: String,
default: null,
},
searchUrl: {
type: [String, Boolean],
default: 'table',
},
});
const { t } = useI18n();
const tableFilterRef = ref([]);
function columnName(col) {
const column = { ...col, ...col.columnFilter };
let name = column.name;
if (column.alias) name = column.alias + '.' + name;
return name;
}
</script>
<template>
<VnFilterPanel v-bind="$attrs" :search-button="true" :disable-submit-event="true">
<template #body="{ params, orders }">
<div
class="row no-wrap flex-center"
v-for="col of columns.filter((c) => c.columnFilter ?? true)"
:key="col.id"
>
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
<VnTableOrder
v-if="col?.columnFilter !== false && col?.name !== 'tableActions'"
v-model="orders[col.orderBy ?? col.name]"
:name="col.orderBy ?? col.name"
:data-key="$attrs['data-key']"
:search-url="searchUrl"
:vertical="true"
/>
</div>
<slot
name="moreFilterPanel"
:params="params"
:orders="orders"
:columns="columns"
/>
</template>
<template #tags="{ tag, formatFn }" v-if="chipLocale">
<div class="q-gutter-x-xs">
<strong>{{ t(`${chipLocale}.${tag.label}`) }}: </strong>
<span>{{ formatFn(tag.value) }}</span>
</div>
</template>
</VnFilterPanel>
</template>

View File

@ -152,7 +152,7 @@ onMounted(async () => {
<QCheckbox <QCheckbox
v-for="col in localColumns" v-for="col in localColumns"
:key="col.name" :key="col.name"
:label="col.label" :label="col.label ?? col.name"
v-model="col.visible" v-model="col.visible"
/> />
</div> </div>

View File

@ -1,4 +1,4 @@
import { describe, expect, it, beforeAll, beforeEach } from 'vitest'; import { describe, expect, it, beforeAll, beforeEach, vi } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import VnTable from 'src/components/VnTable/VnTable.vue'; import VnTable from 'src/components/VnTable/VnTable.vue';
@ -13,6 +13,15 @@ describe('VnTable', () => {
}, },
}); });
vm = wrapper.vm; vm = wrapper.vm;
vi.mock('src/composables/useFilterParams', () => {
return {
useFilterParams: vi.fn(() => ({
params: {},
orders: {},
})),
};
});
}); });
beforeEach(() => (vm.selected = [])); beforeEach(() => (vm.selected = []));

View File

@ -2,7 +2,11 @@
import { ref, onMounted, useSlots } from 'vue'; import { ref, onMounted, useSlots } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import { useQuasar } from 'quasar';
const { t } = useI18n();
const quasar = useQuasar();
const stateStore = useStateStore();
const slots = useSlots(); const slots = useSlots();
const hasContent = ref(false); const hasContent = ref(false);
const rightPanel = ref(null); const rightPanel = ref(null);
@ -11,7 +15,6 @@ onMounted(() => {
rightPanel.value = document.querySelector('#right-panel'); rightPanel.value = document.querySelector('#right-panel');
if (!rightPanel.value) return; if (!rightPanel.value) return;
// Check if there's content to display
const observer = new MutationObserver(() => { const observer = new MutationObserver(() => {
hasContent.value = rightPanel.value.childNodes.length; hasContent.value = rightPanel.value.childNodes.length;
}); });
@ -21,12 +24,9 @@ onMounted(() => {
childList: true, childList: true,
attributes: true, attributes: true,
}); });
if ((!slots['right-panel'] && !hasContent.value) || quasar.platform.is.mobile)
if (!slots['right-panel'] && !hasContent.value) stateStore.rightDrawer = false; stateStore.rightDrawer = false;
}); });
const { t } = useI18n();
const stateStore = useStateStore();
</script> </script>
<template> <template>
<Teleport to="#actions-append" v-if="stateStore.isHeaderMounted()"> <Teleport to="#actions-append" v-if="stateStore.isHeaderMounted()">
@ -45,7 +45,7 @@ const stateStore = useStateStore();
</QBtn> </QBtn>
</div> </div>
</Teleport> </Teleport>
<QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above> <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256">
<QScrollArea class="fit"> <QScrollArea class="fit">
<div id="right-panel"></div> <div id="right-panel"></div>
<slot v-if="!hasContent" name="right-panel" /> <slot v-if="!hasContent" name="right-panel" />

View File

@ -15,7 +15,7 @@ let root = ref(null);
watchEffect(() => { watchEffect(() => {
matched.value = currentRoute.value.matched.filter( matched.value = currentRoute.value.matched.filter(
(matched) => Object.keys(matched.meta).length (matched) => !!matched?.meta?.title || !!matched?.meta?.icon
); );
breadcrumbs.value.length = 0; breadcrumbs.value.length = 0;
if (!matched.value[0]) return; if (!matched.value[0]) return;

View File

@ -0,0 +1,67 @@
<script setup>
import { onBeforeMount, computed } from 'vue';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';
import { useArrayData } from 'src/composables/useArrayData';
import { useStateStore } from 'stores/useStateStore';
import useCardSize from 'src/composables/useCardSize';
import LeftMenu from 'components/LeftMenu.vue';
import VnSubToolbar from '../ui/VnSubToolbar.vue';
const props = defineProps({
dataKey: { type: String, required: true },
baseUrl: { type: String, default: undefined },
customUrl: { type: String, default: undefined },
filter: { type: Object, default: () => {} },
descriptor: { type: Object, required: true },
filterPanel: { type: Object, default: undefined },
searchDataKey: { type: String, default: undefined },
searchbarProps: { type: Object, default: undefined },
redirectOnError: { type: Boolean, default: false },
});
const stateStore = useStateStore();
const route = useRoute();
const router = useRouter();
const url = computed(() => {
if (props.baseUrl) {
return `${props.baseUrl}/${route.params.id}`;
}
return props.customUrl;
});
const arrayData = useArrayData(props.dataKey, {
url: url.value,
filter: props.filter,
});
onBeforeMount(async () => {
try {
if (!props.baseUrl) arrayData.store.filter.where = { id: route.params.id };
await arrayData.fetch({ append: false, updateRouter: false });
} catch {
const { matched: matches } = router.currentRoute.value;
const { path } = matches.at(-1);
router.push({ path: path.replace(/:id.*/, '') });
}
});
if (props.baseUrl) {
onBeforeRouteUpdate(async (to, from) => {
if (to.params.id !== from.params.id) {
arrayData.store.url = `${props.baseUrl}/${to.params.id}`;
await arrayData.fetch({ append: false, updateRouter: false });
}
});
}
</script>
<template>
<Teleport to="#left-panel" v-if="stateStore.isHeaderMounted()">
<component :is="descriptor" />
<QSeparator />
<LeftMenu source="card" />
</Teleport>
<VnSubToolbar />
<div :class="[useCardSize(), $attrs.class]">
<RouterView :key="route.path" />
</div>
</template>

View File

@ -0,0 +1,31 @@
<script setup>
import { toDateFormat } from 'src/filters/date.js';
defineProps({ date: { type: [Date, String], required: true } });
function getBadgeAttrs(date) {
let today = Date.vnNew();
today.setHours(0, 0, 0, 0);
let timeTicket = new Date(date);
timeTicket.setHours(0, 0, 0, 0);
let timeDiff = today - timeTicket;
if (timeDiff == 0) return { color: 'warning', 'text-color': 'black' };
if (timeDiff < 0) return { color: 'success', 'text-color': 'black' };
return { color: 'transparent', 'text-color': 'white' };
}
function formatShippedDate(date) {
if (!date) return '-';
const dateSplit = date.split('T');
const [year, month, day] = dateSplit[0].split('-');
const newDate = new Date(year, month - 1, day);
return toDateFormat(newDate);
}
</script>
<template>
<QBadge v-bind="getBadgeAttrs(date)" class="q-pa-sm" style="font-size: 14px">
{{ formatShippedDate(date) }}
</QBadge>
</template>

View File

@ -106,7 +106,7 @@ const manageDate = (date) => {
:class="{ required: isRequired }" :class="{ required: isRequired }"
:rules="mixinRules" :rules="mixinRules"
:clearable="false" :clearable="false"
@click="isPopupOpen = true" @click="isPopupOpen = !isPopupOpen"
hide-bottom-space hide-bottom-space
> >
<template #append> <template #append>
@ -125,13 +125,6 @@ const manageDate = (date) => {
isPopupOpen = false; isPopupOpen = false;
" "
/> />
<QIcon
v-if="showEvent"
name="event"
class="cursor-pointer"
@click="isPopupOpen = !isPopupOpen"
:title="t('Open date')"
/>
</template> </template>
<QMenu <QMenu
v-if="$q.screen.gt.xs" v-if="$q.screen.gt.xs"
@ -151,15 +144,6 @@ const manageDate = (date) => {
</QInput> </QInput>
</div> </div>
</template> </template>
<style lang="scss">
.vn-input-date.q-field--standard.q-field--readonly .q-field__control:before {
border-bottom-style: solid;
}
.vn-input-date.q-field--outlined.q-field--readonly .q-field__control:before {
border-style: solid;
}
</style>
<i18n> <i18n>
es: es:
Open date: Abrir fecha Open date: Abrir fecha

View File

@ -1,13 +1,28 @@
<script setup> <script setup>
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import { ref } from 'vue';
import { useAttrs } from 'vue'; defineProps({
step: { type: Number, default: 0.01 },
decimalPlaces: { type: Number, default: 2 },
positive: { type: Boolean, default: true },
});
const model = defineModel({ type: [Number, String] }); const model = defineModel({ type: [Number, String] });
const $attrs = useAttrs();
const step = ref($attrs.step || 0.01);
</script> </script>
<template> <template>
<VnInput v-bind="$attrs" v-model.number="model" type="number" :step="step" /> <VnInput
v-bind="$attrs"
v-model.number="model"
type="number"
:step="step"
@input="
(evt) => {
const val = evt.target.value;
if (positive && val < 0) return (model = 0);
const [, decimal] = val.split('.');
if (val && decimal?.length > decimalPlaces)
model = parseFloat(val).toFixed(decimalPlaces);
}
"
/>
</template> </template>

View File

@ -80,7 +80,7 @@ function dateToTime(newDate) {
:class="{ required: isRequired }" :class="{ required: isRequired }"
style="min-width: 100px" style="min-width: 100px"
:rules="mixinRules" :rules="mixinRules"
@click="isPopupOpen = false" @click="isPopupOpen = !isPopupOpen"
type="time" type="time"
hide-bottom-space hide-bottom-space
> >
@ -100,12 +100,6 @@ function dateToTime(newDate) {
isPopupOpen = false; isPopupOpen = false;
" "
/> />
<QIcon
name="Schedule"
class="cursor-pointer"
@click="isPopupOpen = !isPopupOpen"
:title="t('Open time')"
/>
</template> </template>
<QMenu <QMenu
v-if="$q.screen.gt.xs" v-if="$q.screen.gt.xs"

View File

@ -1,8 +1,8 @@
<script setup> <script setup>
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import LeftMenu from 'components/LeftMenu.vue'; import { onMounted, ref } from 'vue';
import { onMounted } from 'vue';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import LeftMenu from '../LeftMenu.vue';
const stateStore = useStateStore(); const stateStore = useStateStore();
const $props = defineProps({ const $props = defineProps({
@ -14,12 +14,30 @@ const $props = defineProps({
onMounted( onMounted(
() => (stateStore.leftDrawer = useQuasar().screen.gt.xs ? $props.leftDrawer : false) () => (stateStore.leftDrawer = useQuasar().screen.gt.xs ? $props.leftDrawer : false)
); );
const teleportRef = ref({});
const hasContent = ref();
let observer;
onMounted(() => {
if (teleportRef.value) {
const checkContent = () => {
hasContent.value = teleportRef.value.innerHTML.trim() !== '';
};
observer = new MutationObserver(checkContent);
observer.observe(teleportRef.value, { childList: true, subtree: true });
checkContent();
}
});
</script> </script>
<template> <template>
<QDrawer v-model="stateStore.leftDrawer" show-if-above :width="256"> <QDrawer v-model="stateStore.leftDrawer" show-if-above :width="256">
<QScrollArea class="fit text-grey-8"> <QScrollArea class="fit text-grey-8">
<LeftMenu /> <div id="left-panel" ref="teleportRef"></div>
<LeftMenu v-if="!hasContent" />
</QScrollArea> </QScrollArea>
</QDrawer> </QDrawer>
<QPageContainer> <QPageContainer>

View File

@ -0,0 +1,79 @@
<script setup>
import RightMenu from './RightMenu.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnTableFilter from '../VnTable/VnTableFilter.vue';
import { onBeforeMount, computed } from 'vue';
import { useArrayData } from 'src/composables/useArrayData';
const $props = defineProps({
section: {
type: String,
required: true,
},
dataKey: {
type: String,
default: null,
},
searchBar: {
type: Boolean,
default: true,
},
prefix: {
type: String,
default: null,
},
rightFilter: {
type: Boolean,
default: true,
},
columns: {
type: Array,
default: null,
},
arrayDataProps: {
type: Object,
default: null,
},
redirect: {
type: Boolean,
default: true,
},
});
const sectionValue = computed(() => $props.section ?? $props.dataKey);
let arrayData;
onBeforeMount(() => {
if ($props.dataKey)
arrayData = useArrayData($props.dataKey, {
searchUrl: 'table',
...$props.arrayDataProps,
navigate: $props.redirect,
});
});
</script>
<template>
<slot name="searchbar">
<VnSearchbar
v-if="searchBar"
v-bind="arrayDataProps"
:data-key="dataKey"
:label="$t(`${prefix}.search`)"
:info="$t(`${prefix}.searchInfo`)"
/>
</slot>
<RightMenu>
<template #right-panel v-if="$slots['rightMenu'] || rightFilter">
<slot name="rightMenu">
<VnTableFilter
v-if="rightFilter && columns"
:data-key="dataKey"
:array-data="arrayData"
:columns="columns"
/>
</slot>
</template>
</RightMenu>
<slot name="body" v-if="sectionValue == $route.name" />
<RouterView v-else />
</template>

View File

@ -4,6 +4,7 @@ import { useI18n } from 'vue-i18n';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { useRequired } from 'src/composables/useRequired'; import { useRequired } from 'src/composables/useRequired';
import dataByOrder from 'src/utils/dataByOrder'; import dataByOrder from 'src/utils/dataByOrder';
import { QItemLabel } from 'quasar';
const emit = defineEmits(['update:modelValue', 'update:options', 'remove']); const emit = defineEmits(['update:modelValue', 'update:options', 'remove']);
const $attrs = useAttrs(); const $attrs = useAttrs();
@ -33,6 +34,10 @@ const $props = defineProps({
type: String, type: String,
default: 'id', default: 'id',
}, },
optionCaption: {
type: String,
default: null,
},
optionFilter: { optionFilter: {
type: String, type: String,
default: null, default: null,
@ -101,6 +106,10 @@ const $props = defineProps({
type: String, type: String,
default: null, default: null,
}, },
isOutlined: {
type: Boolean,
default: false,
},
}); });
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])]; const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])];
@ -115,6 +124,15 @@ const noOneOpt = ref({
[optionValue.value]: false, [optionValue.value]: false,
[optionLabel.value]: noOneText, [optionLabel.value]: noOneText,
}); });
const styleAttrs = computed(() => {
return $props.isOutlined
? {
dense: true,
outlined: true,
rounded: true,
}
: {};
});
const isLoading = ref(false); const isLoading = ref(false);
const useURL = computed(() => $props.url); const useURL = computed(() => $props.url);
const value = computed({ const value = computed({
@ -206,7 +224,7 @@ async function fetchFilter(val) {
const fetchOptions = { where, include, limit }; const fetchOptions = { where, include, limit };
if (fields) fetchOptions.fields = fields; if (fields) fetchOptions.fields = fields;
if (sortBy) fetchOptions.order = sortBy; if (sortBy) fetchOptions.order = sortBy;
arrayData.reset(['skip', 'filter.skip', 'page']); arrayData.resetPagination();
const { data } = await arrayData.applyFilter({ filter: fetchOptions }); const { data } = await arrayData.applyFilter({ filter: fetchOptions });
setOptions(data); setOptions(data);
@ -288,7 +306,7 @@ function handleKeyDown(event) {
} }
const focusableElements = document.querySelectorAll( const focusableElements = document.querySelectorAll(
'a, button, input, textarea, select, details, [tabindex]:not([tabindex="-1"])' 'a:not([disabled]), button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), details:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])'
); );
const currentIndex = Array.prototype.indexOf.call( const currentIndex = Array.prototype.indexOf.call(
focusableElements, focusableElements,
@ -307,9 +325,8 @@ function handleKeyDown(event) {
:options="myOptions" :options="myOptions"
:option-label="optionLabel" :option-label="optionLabel"
:option-value="optionValue" :option-value="optionValue"
v-bind="$attrs" v-bind="{ ...$attrs, ...styleAttrs }"
@filter="filterHandler" @filter="filterHandler"
@keydown="handleKeyDown"
:emit-value="nullishToTrue($attrs['emit-value'])" :emit-value="nullishToTrue($attrs['emit-value'])"
:map-options="nullishToTrue($attrs['map-options'])" :map-options="nullishToTrue($attrs['map-options'])"
:use-input="nullishToTrue($attrs['use-input'])" :use-input="nullishToTrue($attrs['use-input'])"
@ -324,13 +341,15 @@ function handleKeyDown(event) {
:input-debounce="useURL ? '300' : '0'" :input-debounce="useURL ? '300' : '0'"
:loading="isLoading" :loading="isLoading"
@virtual-scroll="onScroll" @virtual-scroll="onScroll"
@keydown="handleKeyDown"
:data-cy="$attrs.dataCy ?? $attrs.label + '_select'" :data-cy="$attrs.dataCy ?? $attrs.label + '_select'"
:data-url="url"
> >
<template #append> <template #append>
<QIcon <QIcon
v-show="isClearable && value" v-show="isClearable && value"
name="close" name="close"
@click.stop=" @click="
() => { () => {
value = null; value = null;
emit('remove'); emit('remove');
@ -358,6 +377,22 @@ function handleKeyDown(event) {
</div> </div>
<slot v-else :name="slotName" v-bind="slotData ?? {}" :key="slotName" /> <slot v-else :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template> </template>
<template #option="{ opt, itemProps }">
<QItem v-bind="itemProps">
<QItemSection v-if="typeof opt !== 'object'"> {{ opt }}</QItemSection>
<QItemSection v-else-if="opt[optionValue] == opt[optionLabel]">
<QItemLabel>{{ opt[optionLabel] }}</QItemLabel>
</QItemSection>
<QItemSection v-else>
<QItemLabel>
{{ opt[optionLabel] }}
</QItemLabel>
<QItemLabel caption v-if="optionCaption !== false">
{{ `#${opt[optionCaption] || opt[optionValue]}` }}
</QItemLabel>
</QItemSection>
</QItem>
</template>
</QSelect> </QSelect>
</template> </template>

View File

@ -0,0 +1,28 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import VnDiscount from 'components/common/vnDiscount.vue';
describe('VnDiscount', () => {
let vm;
beforeAll(() => {
vm = createWrapper(VnDiscount, {
props: {
data: {},
price: 100,
quantity: 2,
discount: 10,
}
}).vm;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('total', () => {
it('should calculate total correctly', () => {
expect(vm.total).toBe(180);
});
});
});

View File

@ -0,0 +1,87 @@
import { createWrapper, axios } from 'app/test/vitest/helper';
import VnDmsList from 'src/components/common/VnDmsList.vue';
import { vi, afterEach, beforeAll, describe, expect, it } from 'vitest';
describe('VnDmsList', () => {
let vm;
const dms = {
userFk: 1,
name: 'DMS 1'
};
beforeAll(() => {
vi.spyOn(axios, 'get').mockResolvedValue({ data: [] });
vm = createWrapper(VnDmsList, {
props: {
model: 'WorkerDms/1110/filter',
defaultDmsCode: 'hhrrData',
filter: 'wd.workerFk',
updateModel: 'Workers',
deleteModel: 'WorkerDms',
downloadModel: 'WorkerDms'
}
}).vm;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('setData()', () => {
const data = [
{
userFk: 1,
name: 'Jessica',
lastName: 'Jones',
file: '4.jpg',
created: '2021-07-28 21:00:00'
},
{
userFk: 2,
name: 'Bruce',
lastName: 'Banner',
created: '2022-07-28 21:00:00',
dms: {
userFk: 2,
name: 'Bruce',
lastName: 'BannerDMS',
created: '2022-07-28 21:00:00',
file: '4.jpg',
}
},
{
userFk: 3,
name: 'Natasha',
lastName: 'Romanoff',
file: '4.jpg',
created: '2021-10-28 21:00:00'
}
]
it('Should replace objects that contain the "dms" property with the value of the same and sort by creation date', () => {
vm.setData(data);
expect([vm.rows][0][0].lastName).toEqual('BannerDMS');
expect([vm.rows][0][1].lastName).toEqual('Romanoff');
});
});
describe('parseDms()', () => {
const resultDms = { ...dms, userId:1};
it('Should add properties that end with "Fk" by changing the suffix to "Id"', () => {
const parsedDms = vm.parseDms(dms);
expect(parsedDms).toEqual(resultDms);
});
});
describe('showFormDialog()', () => {
const resultDms = { ...dms, userId:1};
it('should call fn parseDms() and set show true if dms is defined', () => {
vm.showFormDialog(dms);
expect(vm.formDialog.show).toEqual(true);
expect(vm.formDialog.dms).toEqual(resultDms);
});
});
});

View File

@ -222,8 +222,8 @@ const toModule = computed(() =>
/> />
</template> </template>
<style lang="scss"> <style lang="scss" scoped>
.body { :deep(.body) {
background-color: var(--vn-section-color); background-color: var(--vn-section-color);
.text-h5 { .text-h5 {
font-size: 20px; font-size: 20px;
@ -262,9 +262,7 @@ const toModule = computed(() =>
} }
} }
} }
</style>
<style lang="scss" scoped>
.title { .title {
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;

View File

@ -1,10 +1,10 @@
<script setup> <script setup>
import { ref, computed, watch, onBeforeMount } from 'vue'; import { ref, computed, watch, onBeforeMount, onMounted } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import SkeletonSummary from 'components/ui/SkeletonSummary.vue'; import SkeletonSummary from 'components/ui/SkeletonSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { isDialogOpened } from 'src/filters'; import { isDialogOpened } from 'src/filters';
import { useStateStore } from 'src/stores/useStateStore';
const props = defineProps({ const props = defineProps({
url: { url: {
@ -40,6 +40,7 @@ const { store } = arrayData;
const entity = computed(() => (Array.isArray(store.data) ? store.data[0] : store.data)); const entity = computed(() => (Array.isArray(store.data) ? store.data[0] : store.data));
const isLoading = ref(false); const isLoading = ref(false);
const stateStore = useStateStore();
defineExpose({ defineExpose({
entity, entity,
fetch, fetch,
@ -51,6 +52,9 @@ onBeforeMount(async () => {
watch(props, async () => await fetch()); watch(props, async () => await fetch());
}); });
onMounted(() => {
stateStore.rightDrawerChangeValue(false);
});
async function fetch() { async function fetch() {
store.url = props.url; store.url = props.url;
store.filter = props.filter ?? {}; store.filter = props.filter ?? {};
@ -60,7 +64,6 @@ async function fetch() {
isLoading.value = false; isLoading.value = false;
} }
</script> </script>
<template> <template>
<div class="summary container"> <div class="summary container">
<QCard class="cardSummary"> <QCard class="cardSummary">
@ -81,7 +84,7 @@ async function fetch() {
<span v-else></span> <span v-else></span>
</slot> </slot>
<slot name="header" :entity="entity" dense> <slot name="header" :entity="entity" dense>
<VnLv :label="`${entity.id} -`" :value="entity.name" /> {{ entity.id + ' - ' + entity.name }}
</slot> </slot>
<slot name="header-right" :entity="entity"> <slot name="header-right" :entity="entity">
<span></span> <span></span>
@ -94,7 +97,6 @@ async function fetch() {
</QCard> </QCard>
</div> </div>
</template> </template>
<style lang="scss"> <style lang="scss">
.summary.container { .summary.container {
display: flex; display: flex;

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref } from 'vue'; import { ref, toRef } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import VnLv from 'components/ui/VnLv.vue'; import VnLv from 'components/ui/VnLv.vue';
@ -13,7 +13,7 @@ const DEFAULT_PRICE_KG = 0;
const { t } = useI18n(); const { t } = useI18n();
defineProps({ const props = defineProps({
item: { item: {
type: Object, type: Object,
required: true, required: true,
@ -25,57 +25,63 @@ defineProps({
}); });
const dialog = ref(null); const dialog = ref(null);
const card = toRef(props, 'item');
</script> </script>
<template> <template>
<div class="container order-catalog-item overflow-hidden"> <div class="container order-catalog-item overflow-hidden">
<QCard class="card shadow-6"> <QCard class="card shadow-6">
<div class="img-wrapper"> <div class="img-wrapper">
<VnImg :id="item.id" class="image" zoom-resolution="1600x900" /> <VnImg :id="card.id" class="image" zoom-resolution="1600x900" />
<div v-if="item.hex && isCatalog" class="item-color-container"> <div v-if="card.hex && isCatalog" class="item-color-container">
<div <div
class="item-color" class="item-color"
:style="{ backgroundColor: `#${item.hex}` }" :style="{ backgroundColor: `#${card.hex}` }"
></div> ></div>
</div> </div>
</div> </div>
<div class="content"> <div class="content">
<span class="link"> <span class="link">
{{ item.name }} {{ card.name }}
<ItemDescriptorProxy :id="item.id" /> <ItemDescriptorProxy :id="card.id" />
</span> </span>
<p class="subName">{{ item.subName }}</p> <p class="subName">{{ card.subName }}</p>
<template v-for="index in 4" :key="`tag-${index}`"> <template v-for="index in 4" :key="`tag-${index}`">
<VnLv <VnLv
v-if="item?.[`tag${index + 4}`]" v-if="card?.[`tag${index + 4}`]"
:label="item?.[`tag${index + 4}`] + ':'" :label="card?.[`tag${index + 4}`] + ':'"
:value="item?.[`value${index + 4}`]" :value="card?.[`value${index + 4}`]"
/> />
</template> </template>
<div v-if="item.minQuantity" class="min-quantity"> <div v-if="card.minQuantity" class="min-quantity">
<QIcon name="production_quantity_limits" size="xs" /> <QIcon name="production_quantity_limits" size="xs" />
{{ item.minQuantity }} {{ card.minQuantity }}
</div> </div>
<div class="footer"> <div class="footer">
<div class="price"> <div class="price">
<p v-if="isCatalog"> <p v-if="isCatalog">
{{ item.available }} {{ t('to') }} {{ card.available }} {{ t('to') }}
{{ toCurrency(item.price) }} {{ toCurrency(card.price) }}
</p> </p>
<slot name="price" /> <slot name="price" />
<QIcon v-if="isCatalog" name="add_circle" class="icon"> <QIcon v-if="isCatalog" name="add_circle" class="icon">
<QTooltip>{{ t('globals.add') }}</QTooltip> <QTooltip>{{ t('globals.add') }}</QTooltip>
<QPopupProxy ref="dialog"> <QPopupProxy ref="dialog">
<OrderCatalogItemDialog <OrderCatalogItemDialog
:item="item" :item="card"
@added="() => dialog.hide()" @added="
(quantityAdded) => {
card.available += quantityAdded;
dialog.hide();
}
"
/> />
</QPopupProxy> </QPopupProxy>
</QIcon> </QIcon>
</div> </div>
<p v-if="item.priceKg" class="price-kg"> <p v-if="card.priceKg" class="price-kg">
{{ t('price-kg') }} {{ t('price-kg') }}
{{ toCurrency(item.priceKg) || DEFAULT_PRICE_KG }} {{ toCurrency(card.priceKg) || DEFAULT_PRICE_KG }}
</p> </p>
</div> </div>
</div> </div>

View File

@ -16,7 +16,13 @@ const $props = defineProps({
required: false, required: false,
default: 'value', default: 'value',
}, },
columns: {
type: Number,
required: false,
default: null,
},
}); });
const tags = computed(() => { const tags = computed(() => {
return Object.keys($props.item) return Object.keys($props.item)
.filter((i) => i.startsWith(`${$props.tag}`)) .filter((i) => i.startsWith(`${$props.tag}`))
@ -28,10 +34,21 @@ const tags = computed(() => {
return acc; return acc;
}, {}); }, {});
}); });
const columnStyle = computed(() => {
if ($props.columns) {
return {
'grid-template-columns': `repeat(${$props.columns}, 1fr)`,
'max-width': `${$props.columns * 4}rem`,
};
}
return {};
});
</script> </script>
<template> <template>
<div class="fetchedTags"> <div class="fetchedTags">
<div class="wrap"> <div class="wrap" :style="columnStyle">
<div <div
v-for="(val, key) in tags" v-for="(val, key) in tags"
:key="key" :key="key"
@ -39,37 +56,43 @@ const tags = computed(() => {
:title="`${key}: ${val}`" :title="`${key}: ${val}`"
:class="{ empty: !val }" :class="{ empty: !val }"
> >
{{ val }} <span class="text">{{ val }} </span>
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.fetchedTags { .fetchedTags {
align-items: center; align-items: center;
.wrap { .wrap {
width: 100%; display: grid;
flex-wrap: wrap;
display: flex;
} }
.inline-tag { .inline-tag {
display: flex;
align-items: center;
justify-content: center;
height: 1rem; height: 1rem;
margin: 0.05rem; margin: 0.05rem;
color: $color-font-secondary; color: var(--vn-label-color);
text-align: center; text-align: center;
font-size: smaller; font-size: smaller;
padding: 1px; padding: 1px;
flex: 1; border: 1px solid var(--vn-label-color);
border: 1px solid $color-spacer;
text-overflow: ellipsis; text-overflow: ellipsis;
overflow: hidden; overflow: hidden;
min-width: 4rem; min-width: 4rem;
max-width: 4rem; max-width: 4rem;
} }
.text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: smaller;
}
.empty { .empty {
border: 1px solid #2b2b2b; border: 1px solid var(--vn-empty-tag);
} }
} }
</style> </style>

View File

@ -98,6 +98,7 @@ function cancel() {
/> />
<QBtn <QBtn
:label="t('globals.confirm')" :label="t('globals.confirm')"
:title="t('globals.confirm')"
color="primary" color="primary"
:loading="isLoading" :loading="isLoading"
@click="confirm()" @click="confirm()"

View File

@ -1,12 +1,14 @@
<script setup> <script setup>
import { onMounted, ref, computed, watch } from 'vue'; import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useArrayData } from 'composables/useArrayData'; import { useArrayData } from 'composables/useArrayData';
import { useRoute } from 'vue-router';
import toDate from 'filters/toDate'; import toDate from 'filters/toDate';
import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue'; import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue';
import { useFilterParams } from 'src/composables/useFilterParams';
import { useRoute } from 'vue-router';
const { t } = useI18n(); const { t, te } = useI18n();
const route = useRoute();
const $props = defineProps({ const $props = defineProps({
modelValue: { modelValue: {
type: Object, type: Object,
@ -55,6 +57,10 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: true, default: true,
}, },
arrayData: {
type: Object,
default: null,
},
}); });
const emit = defineEmits([ const emit = defineEmits([
@ -67,52 +73,19 @@ const emit = defineEmits([
'setUserParams', 'setUserParams',
]); ]);
const arrayData = useArrayData($props.dataKey, { const arrayData =
$props.arrayData ??
useArrayData($props.dataKey, {
exprBuilder: $props.exprBuilder, exprBuilder: $props.exprBuilder,
searchUrl: $props.searchUrl, searchUrl: $props.searchUrl,
navigate: $props.redirect ? {} : null, navigate: $props.redirect ? {} : null,
}); });
const route = useRoute();
const store = arrayData.store; const store = arrayData.store;
const userParams = ref({}); const userParams = ref(useFilterParams($props.dataKey).params);
const userOrders = ref(useFilterParams($props.dataKey).orders);
defineExpose({ search, sanitizer, params: userParams }); defineExpose({ search, params: userParams, remove });
onMounted(() => {
if (!userParams.value) userParams.value = $props.modelValue ?? {};
emit('init', { params: userParams.value });
});
function setUserParams(watchedParams) {
if (!watchedParams || Object.keys(watchedParams).length == 0) return;
if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
if (typeof watchedParams?.filter == 'string')
watchedParams.filter = JSON.parse(watchedParams.filter);
watchedParams = { ...watchedParams, ...watchedParams.filter?.where };
const order = watchedParams.filter?.order;
delete watchedParams.filter;
userParams.value = sanitizer(watchedParams);
emit('setUserParams', userParams.value, order);
}
watch(
() => route.query[$props.searchUrl],
(val, oldValue) => (val || oldValue) && setUserParams(val)
);
watch(
() => arrayData.store.userParams,
(val, oldValue) => (val || oldValue) && setUserParams(val),
{ immediate: true }
);
watch(
() => $props.modelValue,
(val) => (userParams.value = val ?? {})
);
const isLoading = ref(false); const isLoading = ref(false);
async function search(evt) { async function search(evt) {
@ -123,10 +96,9 @@ async function search(evt) {
isLoading.value = true; isLoading.value = true;
const filter = { ...userParams.value, ...$props.modelValue }; const filter = { ...userParams.value, ...$props.modelValue };
store.userParamsChanged = true; store.userParamsChanged = true;
const { params: newParams } = await arrayData.addFilter({ await arrayData.addFilter({
params: filter, params: filter,
}); });
userParams.value = newParams;
if (!$props.showAll && !Object.values(filter).length) store.data = []; if (!$props.showAll && !Object.values(filter).length) store.data = [];
emit('search'); emit('search');
@ -139,7 +111,7 @@ async function clearFilters() {
try { try {
isLoading.value = true; isLoading.value = true;
store.userParamsChanged = true; store.userParamsChanged = true;
arrayData.reset(['skip', 'filter.skip', 'page']); arrayData.resetPagination();
// Filtrar los params no removibles // Filtrar los params no removibles
const removableFilters = Object.keys(userParams.value).filter((param) => const removableFilters = Object.keys(userParams.value).filter((param) =>
$props.unremovableParams.includes(param) $props.unremovableParams.includes(param)
@ -149,9 +121,8 @@ async function clearFilters() {
for (const key of removableFilters) { for (const key of removableFilters) {
newParams[key] = userParams.value[key]; newParams[key] = userParams.value[key];
} }
userParams.value = {};
userParams.value = { ...newParams }; // Actualizar los params con los removibles await arrayData.applyFilter({ params: { ...newParams } });
await arrayData.applyFilter({ params: userParams.value });
if (!$props.showAll) { if (!$props.showAll) {
store.data = []; store.data = [];
@ -214,20 +185,13 @@ function formatValue(value) {
return `"${value}"`; return `"${value}"`;
} }
function sanitizer(params) { const getLocale = (label) => {
for (const [key, value] of Object.entries(params)) { const param = label.split('.').at(-1);
if (key === 'and' && Array.isArray(value)) { const globalLocale = `globals.params.${param}`;
value.forEach((item) => { if (te(globalLocale)) return t(globalLocale);
Object.assign(params, item); else if (te(t(`params.${param}`)));
}); else return t(`${route.meta.moduleName}.params.${param}`);
delete params[key]; };
} else if (value && typeof value === 'object') {
const param = Object.values(value)[0];
if (typeof param == 'string') params[key] = param.replaceAll('%', '');
}
}
return params;
}
</script> </script>
<template> <template>
@ -277,7 +241,12 @@ function sanitizer(params) {
@remove="remove(chip.label)" @remove="remove(chip.label)"
data-cy="vnFilterPanelChip" data-cy="vnFilterPanelChip"
> >
<slot name="tags" :tag="chip" :format-fn="formatValue"> <slot
name="tags"
:tag="chip"
:format-fn="formatValue"
:get-locale="getLocale"
>
<div class="q-gutter-x-xs"> <div class="q-gutter-x-xs">
<strong>{{ chip.label }}:</strong> <strong>{{ chip.label }}:</strong>
<span>"{{ formatValue(chip.value) }}"</span> <span>"{{ formatValue(chip.value) }}"</span>
@ -290,6 +259,7 @@ function sanitizer(params) {
:params="userParams" :params="userParams"
:tags="customTags" :tags="customTags"
:format-fn="formatValue" :format-fn="formatValue"
:get-locale="getLocale"
:search-fn="search" :search-fn="search"
/> />
</div> </div>
@ -297,7 +267,13 @@ function sanitizer(params) {
<QSeparator /> <QSeparator />
</QList> </QList>
<QList dense class="list q-gutter-y-sm q-mt-sm"> <QList dense class="list q-gutter-y-sm q-mt-sm">
<slot name="body" :params="sanitizer(userParams)" :search-fn="search"></slot> <slot
name="body"
:get-locale="getLocale"
:params="userParams"
:orders="userOrders"
:search-fn="search"
></slot>
</QList> </QList>
</QForm> </QForm>
<QInnerLoading <QInnerLoading

View File

@ -39,7 +39,7 @@ const val = computed(() => $props.value);
<template v-else> <template v-else>
<div v-if="label || $slots.label" class="label"> <div v-if="label || $slots.label" class="label">
<slot name="label"> <slot name="label">
<span>{{ label }}</span> <span style="color: var(--vn-label-color)">{{ label }}</span>
</slot> </slot>
</div> </div>
<div class="value"> <div class="value">

View File

@ -74,6 +74,10 @@ const props = defineProps({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
mapKey: {
type: String,
default: '',
},
}); });
const emit = defineEmits(['onFetch', 'onPaginate', 'onChange']); const emit = defineEmits(['onFetch', 'onPaginate', 'onChange']);
@ -96,15 +100,19 @@ const arrayData = useArrayData(props.dataKey, {
exprBuilder: props.exprBuilder, exprBuilder: props.exprBuilder,
keepOpts: props.keepOpts, keepOpts: props.keepOpts,
searchUrl: props.searchUrl, searchUrl: props.searchUrl,
mapKey: props.mapKey,
}); });
const store = arrayData.store; const store = arrayData.store;
onMounted(async () => { onMounted(async () => {
if (props.autoLoad && !store.data?.length) await fetch(); if (props.autoLoad && !store.data?.length) await fetch();
else emit('onFetch', store.data);
mounted.value = true; mounted.value = true;
}); });
onBeforeUnmount(() => arrayData.reset()); onBeforeUnmount(() => {
arrayData.resetPagination();
});
watch( watch(
() => props.data, () => props.data,
@ -132,8 +140,8 @@ const addFilter = async (filter, params) => {
async function fetch(params) { async function fetch(params) {
useArrayData(props.dataKey, params); useArrayData(props.dataKey, params);
arrayData.reset(['filter.skip', 'skip', 'page']); arrayData.resetPagination();
await arrayData.fetch({ append: false, updateRouter: mounted.value }); await arrayData.fetch({ append: false });
return emitStoreData(); return emitStoreData();
} }
@ -195,13 +203,20 @@ async function onLoad(index, done) {
done(isDone); done(isDone);
} }
defineExpose({ fetch, update, addFilter, paginate }); defineExpose({
fetch,
update,
addFilter,
paginate,
userParams: arrayData.store.userParams,
currentFilter: arrayData.store.currentFilter,
});
</script> </script>
<template> <template>
<div class="full-width"> <div class="full-width">
<div <div
v-if="!props.autoLoad && !store.data && !isLoading" v-if="!store.data && !store.data?.length && !isLoading"
class="info-row q-pa-md text-center" class="info-row q-pa-md text-center"
> >
<h5> <h5>

View File

@ -51,10 +51,6 @@ const props = defineProps({
type: Object, type: Object,
default: null, default: null,
}, },
staticParams: {
type: Array,
default: () => [],
},
exprBuilder: { exprBuilder: {
type: Function, type: Function,
default: null, default: null,
@ -67,6 +63,10 @@ const props = defineProps({
type: Function, type: Function,
default: undefined, default: undefined,
}, },
searchRemoveParams: {
type: Boolean,
default: true,
},
}); });
const searchText = ref(); const searchText = ref();
@ -100,17 +100,25 @@ onMounted(() => {
}); });
async function search() { async function search() {
const staticParams = Object.entries(store.userParams); const staticParams = Object.keys(store.userParams ?? {}).length
arrayData.reset(['skip', 'page']); ? store.userParams
: store.defaultParams;
arrayData.resetPagination();
const filter = { const filter = {
params: { params: {
...Object.fromEntries(staticParams),
search: searchText.value, search: searchText.value,
}, },
...{ filter: props.filter }, filter: props.filter,
}; };
if (!props.searchRemoveParams || !searchText.value) {
filter.params = {
...staticParams,
search: searchText.value,
};
}
if (props.whereFilter) { if (props.whereFilter) {
filter.filter = { filter.filter = {
where: props.whereFilter(searchText.value), where: props.whereFilter(searchText.value),

View File

@ -4,7 +4,11 @@ import VnPaginate from 'src/components/ui/VnPaginate.vue';
describe('VnPaginate', () => { describe('VnPaginate', () => {
const expectedUrl = '/api/customers'; const expectedUrl = '/api/customers';
const defaultData = [
{ id: 1, name: 'Tony Stark' },
{ id: 2, name: 'Jessica Jones' },
{ id: 3, name: 'Bruce Wayne' },
];
let vm; let vm;
beforeAll(() => { beforeAll(() => {
const options = { const options = {
@ -28,11 +32,7 @@ describe('VnPaginate', () => {
describe('paginate()', () => { describe('paginate()', () => {
it('should call to the paginate() method and set the data on the rows property', async () => { it('should call to the paginate() method and set the data on the rows property', async () => {
vi.spyOn(vm.arrayData, 'loadMore'); vi.spyOn(vm.arrayData, 'loadMore');
vm.store.data = [ vm.store.data = defaultData;
{ id: 1, name: 'Tony Stark' },
{ id: 2, name: 'Jessica Jones' },
{ id: 3, name: 'Bruce Wayne' },
];
await vm.paginate(); await vm.paginate();
@ -42,26 +42,25 @@ describe('VnPaginate', () => {
it('should call to the paginate() method and then call it again to paginate', async () => { it('should call to the paginate() method and then call it again to paginate', async () => {
vi.spyOn(axios, 'get').mockResolvedValue({ vi.spyOn(axios, 'get').mockResolvedValue({
data: [ data: defaultData,
{ id: 1, name: 'Tony Stark' },
{ id: 2, name: 'Jessica Jones' },
{ id: 3, name: 'Bruce Wayne' },
],
}); });
vm.store.hasMoreData = true; vm.store.hasMoreData = true;
await vm.$nextTick(); await vm.$nextTick();
vm.store.data = [ vm.store.data = defaultData;
{ id: 1, name: 'Tony Stark' },
{ id: 2, name: 'Jessica Jones' },
{ id: 3, name: 'Bruce Wayne' },
];
await vm.paginate(); await vm.paginate();
expect(vm.store.skip).toEqual(3); expect(vm.store.skip).toEqual(3);
expect(vm.store.data.length).toEqual(6); expect(vm.store.data.length).toEqual(6);
vi.spyOn(axios, 'get').mockResolvedValue({
data: [
{ id: 4, name: 'Peter Parker' },
{ id: 5, name: 'Clark Kent' },
{ id: 6, name: 'Barry Allen' },
],
});
await vm.paginate(); await vm.paginate();
expect(vm.store.skip).toEqual(6); expect(vm.store.skip).toEqual(6);
@ -85,11 +84,7 @@ describe('VnPaginate', () => {
const index = 1; const index = 1;
const done = vi.fn(); const done = vi.fn();
vm.store.data = [ vm.store.data = defaultData;
{ id: 1, name: 'Tony Stark' },
{ id: 2, name: 'Jessica Jones' },
{ id: 3, name: 'Bruce Wayne' },
];
await vm.onLoad(index, done); await vm.onLoad(index, done);
@ -105,11 +100,7 @@ describe('VnPaginate', () => {
], ],
}); });
vm.store.data = [ vm.store.data = defaultData;
{ id: 1, name: 'Tony Stark' },
{ id: 2, name: 'Jessica Jones' },
{ id: 3, name: 'Bruce Wayne' },
];
expect(vm.pagination.page).toEqual(1); expect(vm.pagination.page).toEqual(1);

View File

@ -0,0 +1,45 @@
import { describe, expect, it, vi } from 'vitest';
import axios from 'axios';
import { getExchange } from 'src/composables/getExchange';
vi.mock('axios');
describe('getExchange()', () => {
it('should return the correct exchange rate', async () => {
axios.get.mockResolvedValue({
data: { value: 1.2 },
});
const amount = 100;
const currencyFk = 1;
const dated = '2023-01-01';
const result = await getExchange(amount, currencyFk, dated);
expect(result).toBe('83.33');
});
it('should return the correct exchange rate with custom decimal places', async () => {
axios.get.mockResolvedValue({
data: { value: 1.2 },
});
const amount = 100;
const currencyFk = 1;
const dated = '2023-01-01';
const decimalPlaces = 3;
const result = await getExchange(amount, currencyFk, dated, decimalPlaces);
expect(result).toBe('83.333');
});
it('should return null if the API call fails', async () => {
axios.get.mockRejectedValue(new Error('Network error'));
const amount = 100;
const currencyFk = 1;
const dated = '2023-01-01';
const result = await getExchange(amount, currencyFk, dated);
expect(result).toBeNull();
});
});

View File

@ -0,0 +1,55 @@
import { vi, describe, expect, it } from 'vitest';
import { getTotal } from 'src/composables/getTotal';
vi.mock('src/filters', () => ({
toCurrency: vi.fn((value, currency) => `${currency} ${value.toFixed(2)}`),
}));
describe('getTotal()', () => {
const rows = [
{ amount: 10.5, tax: 2.1 },
{ amount: 20.75, tax: 3.25 },
{ amount: 30.25, tax: 4.75 },
];
it('should calculate the total for a given key', () => {
const total = getTotal(rows, 'amount');
expect(total).toBe('61.50');
});
it('should calculate the total with a callback function', () => {
const total = getTotal(rows, null, { cb: (row) => row.amount + row.tax });
expect(total).toBe('71.60');
});
it('should format the total as currency', () => {
const total = getTotal(rows, 'amount', { currency: 'USD' });
expect(total).toBe('USD 61.50');
});
it('should format the total as currency with default currency', () => {
const total = getTotal(rows, 'amount', { currency: 'default' });
expect(total).toBe('undefined 61.50');
});
it('should calculate the total with integer formatting', () => {
const total = getTotal(rows, 'amount', { decimalPlaces: 0 });
expect(total).toBe('62');
});
it('should calculate the total with custom decimal places', () => {
const total = getTotal(rows, 'amount', { decimalPlaces: 1 });
expect(total).toBe('61.5');
});
it('should handle rows with missing keys', () => {
const rowsWithMissingKeys = [{ amount: 10.5 }, { amount: 20.75 }, {}];
const total = getTotal(rowsWithMissingKeys, 'amount');
expect(total).toBe('31.25');
});
it('should handle empty rows', () => {
const total = getTotal([], 'amount');
expect(total).toBe('0.00');
});
});

View File

@ -0,0 +1,9 @@
import { describe, expect, it } from 'vitest';
import { useAccountShortToStandard } from 'src/composables/useAccountShortToStandard';
describe('useAccountShortToStandard()', () => {
it('should pad the decimal part with zeros for short numbers', () => {
expect(useAccountShortToStandard('123.45')).toBe('1230000045');
expect(useAccountShortToStandard('123.')).toBe('1230000000');
});
});

View File

@ -0,0 +1,16 @@
import axios from 'axios';
export async function getExchange(amount, currencyFk, dated, decimalPlaces = 2) {
try {
const { data } = await axios.get('ReferenceRates/findOne', {
params: {
filter: {
fields: ['value'],
where: { currencyFk, dated },
},
},
});
return (amount / data.value).toFixed(decimalPlaces);
} catch (e) {
return null;
}
}

View File

@ -1,10 +1,10 @@
import { toCurrency } from 'src/filters'; import { toCurrency } from 'src/filters';
export function getTotal(rows, key, opts = {}) { export function getTotal(rows, key, opts = {}) {
const { currency, cb } = opts; const { currency, cb, decimalPlaces } = opts;
const total = rows.reduce((acc, row) => acc + +(cb ? cb(row) : row[key] || 0), 0); const total = rows.reduce((acc, row) => acc + +(cb ? cb(row) : row[key] || 0), 0);
return currency return currency
? toCurrency(total, currency == 'default' ? undefined : currency) ? toCurrency(total, currency == 'default' ? undefined : currency)
: total; : parseFloat(total).toFixed(decimalPlaces ?? 2);
} }

View File

@ -0,0 +1,4 @@
export function useAccountShortToStandard(val) {
if (!val || !/^\d+(\.\d*)$/.test(val)) return;
return val?.replace('.', '0'.repeat(11 - val.length));
}

View File

@ -25,11 +25,14 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
const searchUrl = store.searchUrl; const searchUrl = store.searchUrl;
if (query[searchUrl]) { if (query[searchUrl]) {
const params = JSON.parse(query[searchUrl]); const params = JSON.parse(query[searchUrl]);
const filter = params?.filter && JSON.parse(params?.filter ?? '{}'); const filter =
params?.filter && typeof params?.filter == 'object'
? params?.filter
: JSON.parse(params?.filter ?? '{}');
delete params.filter; delete params.filter;
store.userParams = { ...store.userParams, ...params }; store.userParams = { ...store.userParams, ...params };
store.userFilter = { ...filter, ...store.userFilter }; store.filter = { ...filter, ...store.userFilter };
if (filter?.order) store.order = filter.order; if (filter?.order) store.order = filter.order;
} }
}); });
@ -49,6 +52,7 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
'exprBuilder', 'exprBuilder',
'searchUrl', 'searchUrl',
'navigate', 'navigate',
'mapKey',
]; ];
if (typeof userOptions === 'object') { if (typeof userOptions === 'object') {
for (const option in userOptions) { for (const option in userOptions) {
@ -60,6 +64,7 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
store[option] = userOptions.keepOpts?.includes(option) store[option] = userOptions.keepOpts?.includes(option)
? Object.assign(defaultOpts, store[option]) ? Object.assign(defaultOpts, store[option])
: defaultOpts; : defaultOpts;
if (option === 'userParams') store.defaultParams = store[option];
} }
} }
} }
@ -74,7 +79,6 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
const filter = { const filter = {
limit: store.limit, limit: store.limit,
}; };
let userParams = { ...store.userParams }; let userParams = { ...store.userParams };
Object.assign(filter, store.userFilter); Object.assign(filter, store.userFilter);
@ -119,17 +123,12 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
const { limit } = filter; const { limit } = filter;
store.hasMoreData = limit && response.data.length >= limit; store.hasMoreData = limit && response.data.length >= limit;
if (append) { processData(response.data, { map: !!store.mapKey, append });
if (!store.data) store.data = []; if (!append && !isDialogOpened()) updateRouter && updateStateParams();
for (const row of response.data) store.data.push(row);
} else {
store.data = response.data;
if (!isDialogOpened()) updateRouter && updateStateParams();
}
store.isLoading = false; store.isLoading = false;
canceller = null; canceller = null;
return response; return response;
} }
@ -147,6 +146,10 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
if (arrayDataStore.get(key)) arrayDataStore.reset(key, opts); if (arrayDataStore.get(key)) arrayDataStore.reset(key, opts);
} }
function resetPagination() {
if (arrayDataStore.get(key)) arrayDataStore.resetPagination(key);
}
function cancelRequest() { function cancelRequest() {
if (canceller) { if (canceller) {
canceller.abort(); canceller.abort();
@ -170,7 +173,7 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
userParams = sanitizerParams(userParams, store?.exprBuilder); userParams = sanitizerParams(userParams, store?.exprBuilder);
store.userParams = userParams; store.userParams = userParams;
reset(['skip', 'filter.skip', 'page']); resetPagination();
await fetch({}); await fetch({});
return { filter, params }; return { filter, params };
@ -197,7 +200,7 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
} }
store.order = order; store.order = order;
reset(['skip', 'filter.skip', 'page']); resetPagination();
fetch({}); fetch({});
index++; index++;
@ -280,7 +283,6 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
const pushUrl = { path: to }; const pushUrl = { path: to };
if (to.endsWith('/list') || to.endsWith('/')) if (to.endsWith('/list') || to.endsWith('/'))
pushUrl.query = newUrl.query; pushUrl.query = newUrl.query;
else destroy();
return router.push(pushUrl); return router.push(pushUrl);
} }
} }
@ -288,6 +290,31 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
router.replace(newUrl); router.replace(newUrl);
} }
function processData(data, { map = true, append = true }) {
if (!append) {
store.data = [];
store.map = new Map();
}
if (!Array.isArray(data)) store.data = data;
else if (!map && append) for (const row of data) store.data.push(row);
else
for (const row of data) {
const key = row[store.mapKey];
const val = { ...row, key };
if (store.map.has(key)) {
const { position } = store.map.get(key);
val.position = position;
store.map.set(key, val);
store.data[position] = val;
} else {
val.position = store.map.size;
store.map.set(key, val);
store.data.push(val);
}
}
}
const totalRows = computed(() => (store.data && store.data.length) || 0); const totalRows = computed(() => (store.data && store.data.length) || 0);
const isLoading = computed(() => store.isLoading || false); const isLoading = computed(() => store.isLoading || false);
@ -307,5 +334,6 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
isLoading, isLoading,
deleteOption, deleteOption,
reset, reset,
resetPagination,
}; };
} }

73
src/composables/useCau.js Normal file
View File

@ -0,0 +1,73 @@
import VnInput from 'src/components/common/VnInput.vue';
import { useVnConfirm } from 'src/composables/useVnConfirm';
import axios from 'axios';
import { ref } from 'vue';
import { i18n } from 'src/boot/i18n';
import useNotify from 'src/composables/useNotify.js';
export async function useCau(res, message) {
const { notify } = useNotify();
const { openConfirmationModal } = useVnConfirm();
const { config, headers, request, status, statusText, data } = res || {};
const { params, url, method, signal, headers: confHeaders } = config || {};
const { message: resMessage, code, name } = data?.error || {};
const additionalData = {
path: location.hash,
message: resMessage,
code,
request: request?.responseURL,
status,
name,
statusText: statusText,
config: {
url,
method,
params,
headers: confHeaders,
aborted: signal?.aborted,
version: headers?.['salix-version'],
},
};
const opts = {
actions: [
{
icon: 'support_agent',
color: 'primary',
dense: true,
flat: false,
round: true,
handler: async () => {
const locale = i18n.global.t;
const reason = ref(
code == 'ACCESS_DENIED' ? locale('cau.askPrivileges') : ''
);
openConfirmationModal(
locale('cau.title'),
locale('cau.subtitle'),
async () => {
await axios.post('OsTickets/send-to-support', {
reason: reason.value,
additionalData,
});
},
null,
{
component: VnInput,
props: {
modelValue: reason,
'onUpdate:modelValue': (val) => (reason.value = val),
label: locale('cau.inputLabel'),
class: 'full-width',
required: true,
autofocus: true,
},
}
);
},
},
],
};
notify(message ?? 'globals.error', 'negative', 'error', opts);
}

View File

@ -0,0 +1,65 @@
import { useArrayData } from 'src/composables/useArrayData';
import { onBeforeMount, ref, watch } from 'vue';
export function useFilterParams(key) {
if (!key) throw new Error('ArrayData: A key is required to use this composable');
const params = ref({});
const orders = ref({});
const arrayData = ref({});
onBeforeMount(() => {
arrayData.value = useArrayData(key);
});
watch(
() => arrayData.value.store?.currentFilter,
(val, oldValue) => (val || oldValue) && setUserParams(val),
{ immediate: true, deep: true }
);
function parseOrder(urlOrders) {
const orderObject = {};
if (urlOrders) {
if (typeof urlOrders == 'string') urlOrders = [urlOrders];
for (const [index, orders] of urlOrders.entries()) {
const [name, direction] = orders.split(' ');
orderObject[name] = { direction, index: index + 1 };
}
}
orders.value = orderObject;
}
function setUserParams(watchedParams) {
if (!watchedParams || Object.keys(watchedParams).length == 0) return;
if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
if (typeof watchedParams?.filter == 'string')
watchedParams.filter = JSON.parse(watchedParams.filter);
watchedParams = { ...watchedParams, ...watchedParams.filter?.where };
parseOrder(watchedParams.filter?.order);
delete watchedParams.filter;
params.value = sanitizer(watchedParams);
}
function sanitizer(params) {
for (const [key, value] of Object.entries(params)) {
if (key === 'and' && Array.isArray(value)) {
value.forEach((item) => {
Object.assign(params, item);
});
delete params[key];
} else if (value && typeof value === 'object') {
const param = Object.values(value)[0];
if (typeof param == 'string') params[key] = param.replaceAll('%', '');
}
}
return params;
}
return {
params,
orders,
};
}

View File

@ -2,7 +2,7 @@ import { Notify } from 'quasar';
import { i18n } from 'src/boot/i18n'; import { i18n } from 'src/boot/i18n';
export default function useNotify() { export default function useNotify() {
const notify = (message, type, icon) => { const notify = (message, type, icon, opts = {}) => {
const defaultIcons = { const defaultIcons = {
warning: 'warning', warning: 'warning',
negative: 'error', negative: 'error',
@ -13,6 +13,7 @@ export default function useNotify() {
message: i18n.global.t(message), message: i18n.global.t(message),
type: type, type: type,
icon: icon ? icon : defaultIcons[type], icon: icon ? icon : defaultIcons[type],
...opts,
}); });
}; };

View File

@ -1,20 +1,27 @@
import { h } from 'vue';
import { Dialog } from 'quasar';
import VnConfirm from 'components/ui/VnConfirm.vue'; import VnConfirm from 'components/ui/VnConfirm.vue';
import { useQuasar } from 'quasar';
export function useVnConfirm() { export function useVnConfirm() {
const quasar = useQuasar(); const openConfirmationModal = (
title,
const openConfirmationModal = (title, message, promise, successFn) => { message,
quasar promise,
.dialog({ successFn,
component: VnConfirm, customHTML = {}
componentProps: { ) => {
const { component, props } = customHTML;
Dialog.create({
component: h(
VnConfirm,
{
title: title, title: title,
message: message, message: message,
promise: promise, promise: promise,
}, },
}) { customHTML: () => h(component, props) }
.onOk(async () => { ),
}).onOk(async () => {
if (successFn) successFn(); if (successFn) successFn();
}); });
}; };

View File

@ -11,6 +11,7 @@ body.body--light {
--vn-text-color: var(--font-color); --vn-text-color: var(--font-color);
--vn-label-color: #5f5f5f; --vn-label-color: #5f5f5f;
--vn-accent-color: #e7e3e3; --vn-accent-color: #e7e3e3;
--vn-empty-tag: #acacac;
background-color: var(--vn-page-color); background-color: var(--vn-page-color);
@ -26,6 +27,7 @@ body.body--dark {
--vn-text-color: white; --vn-text-color: white;
--vn-label-color: #a8a8a8; --vn-label-color: #a8a8a8;
--vn-accent-color: #424242; --vn-accent-color: #424242;
--vn-empty-tag: #2d2d2d;
background-color: var(--vn-page-color); background-color: var(--vn-page-color);
} }
@ -240,7 +242,7 @@ input::-webkit-inner-spin-button {
.q-table { .q-table {
th, th,
td { td {
padding: 1px 10px 1px 10px; padding: 1px 3px 1px 3px;
max-width: 130px; max-width: 130px;
div span { div span {
overflow: hidden; overflow: hidden;
@ -264,6 +266,10 @@ input::-webkit-inner-spin-button {
.shrink { .shrink {
max-width: 75px; max-width: 75px;
} }
.number {
text-align: right;
width: 96px;
}
.expand { .expand {
max-width: 400px; max-width: 400px;
} }
@ -292,3 +298,20 @@ input::-webkit-inner-spin-button {
.no-visible { .no-visible {
visibility: hidden; visibility: hidden;
} }
.q-field__inner {
.q-field__control {
min-height: auto !important;
display: flex;
align-items: flex-end;
padding-bottom: 2px;
.q-field__native.row {
min-height: auto !important;
}
}
}
.q-date__header-today {
border-radius: 12px;
border: 1px solid;
box-shadow: 0 4px 6px #00000000;
}

View File

@ -129,6 +129,7 @@ globals:
small: Small small: Small
medium: Medium medium: Medium
big: Big big: Big
email: Email
pageTitles: pageTitles:
logIn: Login logIn: Login
addressEdit: Update address addressEdit: Update address
@ -141,7 +142,7 @@ globals:
workCenters: Work centers workCenters: Work centers
modes: Modes modes: Modes
zones: Zones zones: Zones
zonesList: Zones zonesList: List
deliveryDays: Delivery days deliveryDays: Delivery days
upcomingDeliveries: Upcoming deliveries upcomingDeliveries: Upcoming deliveries
role: Role role: Role
@ -329,13 +330,26 @@ globals:
email: Email email: Email
SSN: SSN SSN: SSN
fi: FI fi: FI
packing: ITP
myTeam: My team myTeam: My team
departmentFk: Department departmentFk: Department
from: From
to: To
supplierFk: Supplier
supplierRef: Supplier ref
serial: Serial
amount: Importe
awbCode: AWB
correctedFk: Rectified
correctingFk: Rectificative
daysOnward: Days onward
countryFk: Country countryFk: Country
companyFk: Company
changePass: Change password changePass: Change password
deleteConfirmTitle: Delete selected elements deleteConfirmTitle: Delete selected elements
changeState: Change state changeState: Change state
raid: 'Raid {daysInForward} days' raid: 'Raid {daysInForward} days'
isVies: Vies
errors: errors:
statusUnauthorized: Access denied statusUnauthorized: Access denied
statusInternalServerError: An internal server error has ocurred statusInternalServerError: An internal server error has ocurred
@ -369,6 +383,11 @@ resetPassword:
repeatPassword: Repeat password repeatPassword: Repeat password
passwordNotMatch: Passwords don't match passwordNotMatch: Passwords don't match
passwordChanged: Password changed passwordChanged: Password changed
cau:
title: Send cau
subtitle: By sending this ticket, all the data related to the error, the section, the user, etc., are already sent.
inputLabel: Explain why this error should not appear
askPrivileges: Ask for privileges
entry: entry:
list: list:
newEntry: New entry newEntry: New entry
@ -724,7 +743,6 @@ supplier:
sageTransactionTypeFk: Sage transaction type sageTransactionTypeFk: Sage transaction type
supplierActivityFk: Supplier activity supplierActivityFk: Supplier activity
isTrucker: Trucker isTrucker: Trucker
isVies: Vies
billingData: billingData:
payMethodFk: Billing data payMethodFk: Billing data
payDemFk: Payment deadline payDemFk: Payment deadline
@ -843,6 +861,7 @@ components:
ended: To ended: To
mine: For me mine: For me
hasMinPrice: Minimum price hasMinPrice: Minimum price
warehouseFk: Warehouse
# LatestBuysFilter # LatestBuysFilter
salesPersonFk: Buyer salesPersonFk: Buyer
from: From from: From

View File

@ -131,6 +131,7 @@ globals:
small: Pequeño/a small: Pequeño/a
medium: Mediano/a medium: Mediano/a
big: Grande big: Grande
email: Correo
pageTitles: pageTitles:
logIn: Inicio de sesión logIn: Inicio de sesión
addressEdit: Modificar consignatario addressEdit: Modificar consignatario
@ -143,7 +144,7 @@ globals:
workCenters: Centros de trabajo workCenters: Centros de trabajo
modes: Modos modes: Modos
zones: Zonas zones: Zonas
zonesList: Zonas zonesList: Listado
deliveryDays: Días de entrega deliveryDays: Días de entrega
upcomingDeliveries: Próximos repartos upcomingDeliveries: Próximos repartos
role: Role role: Role
@ -335,11 +336,22 @@ globals:
SSN: NSS SSN: NSS
fi: NIF fi: NIF
myTeam: Mi equipo myTeam: Mi equipo
from: Desde
to: Hasta
supplierFk: Proveedor
supplierRef: Ref. proveedor
serial: Serie
amount: Importe
awbCode: AWB
daysOnward: Días adelante
packing: ITP
countryFk: País countryFk: País
companyFk: Empresa
changePass: Cambiar contraseña changePass: Cambiar contraseña
deleteConfirmTitle: Eliminar los elementos seleccionados deleteConfirmTitle: Eliminar los elementos seleccionados
changeState: Cambiar estado changeState: Cambiar estado
raid: 'Redada {daysInForward} días' raid: 'Redada {daysInForward} días'
isVies: Vies
errors: errors:
statusUnauthorized: Acceso denegado statusUnauthorized: Acceso denegado
statusInternalServerError: Ha ocurrido un error interno del servidor statusInternalServerError: Ha ocurrido un error interno del servidor
@ -371,6 +383,11 @@ resetPassword:
repeatPassword: Repetir contraseña repeatPassword: Repetir contraseña
passwordNotMatch: Las contraseñas no coinciden passwordNotMatch: Las contraseñas no coinciden
passwordChanged: Contraseña cambiada passwordChanged: Contraseña cambiada
cau:
title: Enviar cau
subtitle: Al enviar este cau ya se envían todos los datos relacionados con el error, la sección, el usuario, etc
inputLabel: Explique el motivo por el que no deberia aparecer este fallo
askPrivileges: Solicitar permisos
entry: entry:
list: list:
newEntry: Nueva entrada newEntry: Nueva entrada
@ -492,7 +509,7 @@ invoiceOut:
ticketList: Listado de tickets ticketList: Listado de tickets
summary: summary:
issued: Fecha issued: Fecha
dued: Vencimiento dued: Fecha límite
booked: Contabilizada booked: Contabilizada
taxBreakdown: Desglose impositivo taxBreakdown: Desglose impositivo
taxableBase: Base imp. taxableBase: Base imp.
@ -719,7 +736,6 @@ supplier:
sageTransactionTypeFk: Tipo de transacción sage sageTransactionTypeFk: Tipo de transacción sage
supplierActivityFk: Actividad proveedor supplierActivityFk: Actividad proveedor
isTrucker: Transportista isTrucker: Transportista
isVies: Vies
billingData: billingData:
payMethodFk: Forma de pago payMethodFk: Forma de pago
payDemFk: Plazo de pago payDemFk: Plazo de pago
@ -837,6 +853,7 @@ components:
ended: Hasta ended: Hasta
mine: Para mi mine: Para mi
hasMinPrice: Precio mínimo hasMinPrice: Precio mínimo
wareHouseFk: Almacén
# LatestBuysFilter # LatestBuysFilter
salesPersonFk: Comprador salesPersonFk: Comprador
active: Activo active: Activo

View File

@ -1,16 +1,15 @@
<script setup> <script setup>
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ref, computed } from 'vue'; import { ref, computed } from 'vue';
import { useStateStore } from 'stores/useStateStore';
import axios from 'axios'; import axios from 'axios';
import useNotify from 'src/composables/useNotify.js'; import useNotify from 'src/composables/useNotify.js';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import VnTable from 'components/VnTable/VnTable.vue'; import VnTable from 'components/VnTable/VnTable.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnConfirm from 'components/ui/VnConfirm.vue'; import VnConfirm from 'components/ui/VnConfirm.vue';
import FetchData from 'src/components/FetchData.vue'; import FetchData from 'src/components/FetchData.vue';
import { useValidator } from 'src/composables/useValidator'; import { useValidator } from 'src/composables/useValidator';
import VnSection from 'src/components/common/VnSection.vue';
defineProps({ defineProps({
id: { id: {
@ -21,13 +20,13 @@ defineProps({
const { notify } = useNotify(); const { notify } = useNotify();
const { t } = useI18n(); const { t } = useI18n();
const stateStore = useStateStore();
const quasar = useQuasar(); const quasar = useQuasar();
const tableRef = ref(); const tableRef = ref();
const roles = ref(); const roles = ref();
const validationsStore = useValidator(); const validationsStore = useValidator();
const { models } = validationsStore; const { models } = validationsStore;
const dataKey = 'AccountAcls';
const exprBuilder = (param, value) => { const exprBuilder = (param, value) => {
switch (param) { switch (param) {
case 'search': case 'search':
@ -134,39 +133,41 @@ const deleteAcl = async ({ id }) => {
</script> </script>
<template> <template>
<VnSearchbar
data-key="AccountAcls"
url="ACLs"
:expr-builder="exprBuilder"
:label="t('acls.search')"
:info="t('acls.searchInfo')"
/>
<QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
</QDrawer>
<FetchData <FetchData
url="VnRoles?fields=['name']" url="VnRoles?fields=['name']"
auto-load auto-load
@on-fetch="(data) => (roles = data)" @on-fetch="(data) => (roles = data)"
/> />
<VnSection
:data-key="dataKey"
:columns="columns"
prefix="acls"
:array-data-props="{
url: 'ACLs',
order: 'id DESC',
exprBuilder,
}"
>
<template #body>
<VnTable <VnTable
ref="tableRef" ref="tableRef"
data-key="AccountAcls" :data-key="dataKey"
:url="`ACLs`"
:create="{ :create="{
urlCreate: 'ACLs', urlCreate: 'ACLs',
title: 'Create ACL', title: 'Create ACL',
onDataSaved: () => tableRef.reload(), onDataSaved: () => tableRef.reload(),
formInitialData: {}, formInitialData: {},
}" }"
order="id DESC"
:disable-option="{ card: true }" :disable-option="{ card: true }"
:columns="columns" :columns="columns"
default-mode="table" default-mode="table"
:right-search="true" :right-search="false"
:is-editable="true" :is-editable="true"
:use-model="true" :use-model="true"
/> />
</template> </template>
</VnSection>
</template>
<i18n> <i18n>
es: es:

View File

@ -2,21 +2,12 @@
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ref, computed } from 'vue'; import { ref, computed } from 'vue';
import VnTable from 'components/VnTable/VnTable.vue'; import VnTable from 'components/VnTable/VnTable.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue'; import VnSection from 'src/components/common/VnSection.vue';
import { useStateStore } from 'stores/useStateStore';
const tableRef = ref(); const tableRef = ref();
const { t } = useI18n(); const { t } = useI18n();
const stateStore = useStateStore(); const dataKey = 'AccountAliasList';
const exprBuilder = (param, value) => {
switch (param) {
case 'search':
return /^\d+$/.test(value)
? { id: value }
: { alias: { like: `%${value}%` } };
}
};
const columns = computed(() => [ const columns = computed(() => [
{ {
align: 'left', align: 'left',
@ -40,40 +31,45 @@ const columns = computed(() => [
create: true, create: true,
}, },
]); ]);
const exprBuilder = (param, value) => {
switch (param) {
case 'search':
return /^\d+$/.test(value)
? { id: value }
: { alias: { like: `%${value}%` } };
}
};
</script> </script>
<template> <template>
<template v-if="stateStore.isHeaderMounted()"> <VnSection
<Teleport to="#searchbar"> :data-key="dataKey"
<VnSearchbar :columns="columns"
data-key="AccountAliasList" prefix="mailAlias"
url="MailAliases" :array-data-props="{ url: 'MailAliases', order: 'id DESC', exprBuilder }"
:expr-builder="exprBuilder" >
:label="t('mailAlias.search')" <template #body>
:info="t('mailAlias.searchInfo')"
/>
</Teleport>
</template>
<VnTable <VnTable
:data-key="dataKey"
ref="tableRef" ref="tableRef"
data-key="AccountAliasList"
url="MailAliases"
:create="{ :create="{
urlCreate: 'MailAliases', urlCreate: 'MailAliases',
title: 'Create MailAlias', title: 'Create MailAlias',
onDataSaved: ({ id }) => tableRef.redirect(id), onDataSaved: ({ id }) => tableRef.redirect(id),
formInitialData: {}, formInitialData: {},
}" }"
order="id DESC"
:columns="columns" :columns="columns"
:disable-option="{ card: true }" :disable-option="{ card: true }"
default-mode="table" default-mode="table"
redirect="account/alias" redirect="account/alias"
:is-editable="true" :is-editable="true"
:use-model="true" :use-model="true"
:right-search="false"
/> />
</template> </template>
</VnSection>
</template>
<i18n> <i18n>
es: es:
Id: Id Id: Id

View File

@ -1,19 +1,20 @@
<script setup> <script setup>
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ref, computed } from 'vue'; import { computed, ref } from 'vue';
import VnTable from 'components/VnTable/VnTable.vue'; import VnTable from 'components/VnTable/VnTable.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import AccountSummary from './Card/AccountSummary.vue'; import AccountSummary from './Card/AccountSummary.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog'; import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import AccountFilter from './AccountFilter.vue';
import RightMenu from 'src/components/common/RightMenu.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import VnSection from 'src/components/common/VnSection.vue';
import FetchData from 'src/components/FetchData.vue';
const { t } = useI18n(); const { t } = useI18n();
const { viewSummary } = useSummaryDialog(); const { viewSummary } = useSummaryDialog();
const tableRef = ref();
const filter = { const filter = {
include: { relation: 'role', scope: { fields: ['id', 'name'] } }, include: { relation: 'role', scope: { fields: ['id', 'name'] } },
}; };
const dataKey = 'AccountList';
const roles = ref([]);
const columns = computed(() => [ const columns = computed(() => [
{ {
align: 'left', align: 'left',
@ -48,7 +49,7 @@ const columns = computed(() => [
component: 'select', component: 'select',
name: 'roleFk', name: 'roleFk',
attrs: { attrs: {
url: 'VnRoles', options: roles,
optionValue: 'id', optionValue: 'id',
optionLabel: 'name', optionLabel: 'name',
}, },
@ -116,7 +117,8 @@ const columns = computed(() => [
], ],
}, },
]); ]);
const exprBuilder = (param, value) => {
function exprBuilder(param, value) {
switch (param) { switch (param) {
case 'search': case 'search':
return /^\d+$/.test(value) return /^\d+$/.test(value)
@ -133,39 +135,36 @@ const exprBuilder = (param, value) => {
case 'roleFk': case 'roleFk':
return { [param]: value }; return { [param]: value };
} }
}; }
</script> </script>
<template> <template>
<VnSearchbar <FetchData url="VnRoles" @on-fetch="(data) => (roles = data)" auto-load />
data-key="AccountList" <VnSection
:expr-builder="exprBuilder" :data-key="dataKey"
:label="t('account.search')" :columns="columns"
:info="t('account.searchInfo')" prefix="account"
:filter="filter" :array-data-props="{
/> url: 'VnUsers/preview',
<RightMenu> userFilter: filter,
<template #right-panel> order: 'id DESC',
<AccountFilter data-key="AccountList" /> exprBuilder,
</template> }"
</RightMenu> >
<template #body>
<VnTable <VnTable
ref="tableRef" ref="tableRef"
data-key="AccountList" :data-key="dataKey"
url="VnUsers/preview" :columns="columns"
:create="{ :create="{
urlCreate: 'VnUsers', urlCreate: 'VnUsers',
title: t('Create user'), title: t('Create user'),
onDataSaved: ({ id }) => tableRef.redirect(id), onDataSaved: ({ id }) => $refs.tableRef.redirect(id),
formInitialData: {}, formInitialData: {},
}" }"
:filter="filter"
order="id DESC"
:columns="columns"
default-mode="table" default-mode="table"
redirect="account" redirect="account"
:use-model="true" :use-model="true"
:right-search="false" :right-search="false"
auto-load
> >
<template #more-create-dialog="{ data }"> <template #more-create-dialog="{ data }">
<QCardSection> <QCardSection>
@ -180,6 +179,8 @@ const exprBuilder = (param, value) => {
</template> </template>
</VnTable> </VnTable>
</template> </template>
</VnSection>
</template>
<i18n> <i18n>
es: es:

View File

@ -1,12 +1,12 @@
<script setup> <script setup>
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import VnCard from 'components/common/VnCard.vue'; import VnCardBeta from 'components/common/VnCardBeta.vue';
import AliasDescriptor from './AliasDescriptor.vue'; import AliasDescriptor from './AliasDescriptor.vue';
const { t } = useI18n(); const { t } = useI18n();
</script> </script>
<template> <template>
<VnCard <VnCardBeta
data-key="Alias" data-key="Alias"
base-url="MailAliases" base-url="MailAliases"
:descriptor="AliasDescriptor" :descriptor="AliasDescriptor"

View File

@ -1,20 +1,8 @@
<script setup> <script setup>
import { useI18n } from 'vue-i18n'; import VnCardBeta from 'components/common/VnCardBeta.vue';
import VnCard from 'components/common/VnCard.vue';
import AccountDescriptor from './AccountDescriptor.vue'; import AccountDescriptor from './AccountDescriptor.vue';
const { t } = useI18n();
</script> </script>
<template> <template>
<VnCard <VnCardBeta data-key="AccountId" :descriptor="AccountDescriptor" />
data-key="Account"
:descriptor="AccountDescriptor"
search-data-key="AccountList"
:searchbar-props="{
url: 'VnUsers/preview',
label: t('account.search'),
info: t('account.searchInfo'),
}"
/>
</template> </template>

View File

@ -41,7 +41,7 @@ const hasAccount = ref(false);
/> />
<CardDescriptor <CardDescriptor
ref="descriptor" ref="descriptor"
:url="`VnUsers/preview`" url="VnUsers/preview"
:filter="filter" :filter="filter"
module="Account" module="Account"
@on-fetch="setData" @on-fetch="setData"

View File

@ -30,7 +30,7 @@ const filter = {
<template> <template>
<CardSummary <CardSummary
data-key="AccountSummary" data-key="AccountId"
ref="AccountSummary" ref="AccountSummary"
url="VnUsers/preview" url="VnUsers/preview"
:filter="filter" :filter="filter"

View File

@ -3,11 +3,13 @@ import { useI18n } from 'vue-i18n';
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import VnTable from 'components/VnTable/VnTable.vue'; import VnTable from 'components/VnTable/VnTable.vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog'; import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import RoleSummary from './Card/RoleSummary.vue'; import RoleSummary from './Card/RoleSummary.vue';
import VnSection from 'src/components/common/VnSection.vue';
const route = useRoute(); const route = useRoute();
const { t } = useI18n(); const { t } = useI18n();
const { viewSummary } = useSummaryDialog();
const $props = defineProps({ const $props = defineProps({
id: { id: {
type: Number, type: Number,
@ -15,8 +17,10 @@ const $props = defineProps({
}, },
}); });
const tableRef = ref(); const tableRef = ref();
const url = 'VnRoles';
const dataKey = 'AccountRoleList';
const entityId = computed(() => $props.id || route.params.id); const entityId = computed(() => $props.id || route.params.id);
const { viewSummary } = useSummaryDialog();
const columns = computed(() => [ const columns = computed(() => [
{ {
align: 'left', align: 'left',
@ -81,16 +85,16 @@ const exprBuilder = (param, value) => {
</script> </script>
<template> <template>
<VnSearchbar <VnSection
data-key="AccountRolesList" :data-key="dataKey"
:expr-builder="exprBuilder" :columns="columns"
:label="t('role.searchRoles')" prefix="role"
:info="t('role.searchInfo')" :array-data-props="{ url, exprBuilder, order: 'id ASC' }"
/> >
<template #body>
<VnTable <VnTable
ref="tableRef" ref="tableRef"
data-key="AccountRolesList" :data-key="dataKey"
:url="`VnRoles`"
:create="{ :create="{
urlCreate: 'VnRoles', urlCreate: 'VnRoles',
title: t('Create rol'), title: t('Create rol'),
@ -99,13 +103,15 @@ const exprBuilder = (param, value) => {
editorFk: entityId, editorFk: entityId,
}, },
}" }"
order="id ASC"
:disable-option="{ card: true }" :disable-option="{ card: true }"
:columns="columns" :columns="columns"
default-mode="table" default-mode="table"
redirect="account/role" redirect="account/role"
:right-search="false"
/> />
</template> </template>
</VnSection>
</template>
<i18n> <i18n>
es: es:

View File

@ -1,20 +1,7 @@
<script setup> <script setup>
import { useI18n } from 'vue-i18n'; import VnCardBeta from 'components/common/VnCardBeta.vue';
import VnCard from 'components/common/VnCard.vue';
import RoleDescriptor from './RoleDescriptor.vue'; import RoleDescriptor from './RoleDescriptor.vue';
const { t } = useI18n();
</script> </script>
<template> <template>
<VnCard <VnCardBeta data-key="Role" :descriptor="RoleDescriptor" />
data-key="Role"
:descriptor="RoleDescriptor"
search-data-key="AccountRolesList"
:searchbar-props="{
url: 'VnRoles',
label: t('role.searchRoles'),
info: t('role.searchInfo'),
searchUrl: 'table',
}"
/>
</template> </template>

View File

@ -43,7 +43,7 @@ const removeRole = async () => {
:filter="filter" :filter="filter"
module="Role" module="Role"
@on-fetch="setData" @on-fetch="setData"
data-key="accountData" data-key="Role"
:title="data.title" :title="data.title"
:subtitle="data.subtitle" :subtitle="data.subtitle"
:summary="$props.summary" :summary="$props.summary"

View File

@ -27,10 +27,10 @@ const filter = {
<template> <template>
<CardSummary <CardSummary
ref="summary" ref="summary"
:url="`VnRoles`" :url="`VnRoles/${entityId}`"
:filter="filter" :filter="filter"
@on-fetch="(data) => (role = data)" @on-fetch="(data) => (role = data)"
data-key="RoleSummary" data-key="Role"
> >
<template #header> {{ role.id }} - {{ role.name }} </template> <template #header> {{ role.id }} - {{ role.name }} </template>
<template #body> <template #body>

View File

@ -66,7 +66,7 @@ account:
mailInputInfo: All emails will be forwarded to the specified address. mailInputInfo: All emails will be forwarded to the specified address.
role: role:
newRole: New role newRole: New role
searchRoles: Search role search: Search role
searchInfo: Search role by id or name searchInfo: Search role by id or name
description: Description description: Description
id: Id id: Id

View File

@ -6,6 +6,7 @@ import CrudModel from 'components/CrudModel.vue';
import FetchData from 'components/FetchData.vue'; import FetchData from 'components/FetchData.vue';
import VnSelect from 'components/common/VnSelect.vue'; import VnSelect from 'components/common/VnSelect.vue';
import { tMobile } from 'composables/tMobile'; import { tMobile } from 'composables/tMobile';
import VnSelectWorker from 'src/components/common/VnSelectWorker.vue';
const route = useRoute(); const route = useRoute();
@ -157,19 +158,14 @@ const columns = computed(() => [
auto-width auto-width
@keyup.ctrl.enter.stop="claimDevelopmentForm.saveChanges()" @keyup.ctrl.enter.stop="claimDevelopmentForm.saveChanges()"
> >
<VnSelect <VnSelectWorker
v-if="col.name == 'worker'"
v-model="row[col.model]" v-model="row[col.model]"
:url="col.url"
:where="col.where"
:sort-by="col.sortBy"
:options="col.options"
:option-value="col.optionValue"
:option-label="col.optionLabel"
:autofocus="col.tabIndex == 1" :autofocus="col.tabIndex == 1"
input-debounce="0" input-debounce="0"
hide-selected hide-selected
> >
<template #option="scope" v-if="col.name == 'worker'"> <template #option="scope">
<QItem v-bind="scope.itemProps"> <QItem v-bind="scope.itemProps">
<QItemSection> <QItemSection>
<QItemLabel>{{ scope.opt?.name }}</QItemLabel> <QItemLabel>{{ scope.opt?.name }}</QItemLabel>
@ -180,7 +176,20 @@ const columns = computed(() => [
</QItemSection> </QItemSection>
</QItem> </QItem>
</template> </template>
</VnSelect> </VnSelectWorker>
<VnSelect
v-else
v-model="row[col.model]"
:url="col.url"
:where="col.where"
:sort-by="col.sortBy"
:options="col.options"
:option-value="col.optionValue"
:option-label="col.optionLabel"
:autofocus="col.tabIndex == 1"
input-debounce="0"
hide-selected
/>
</QTd> </QTd>
</template> </template>
<template #item="props"> <template #item="props">

View File

@ -57,6 +57,7 @@ function onFetch(rows, newRows) {
const price = row.quantity * sale.price; const price = row.quantity * sale.price;
const discount = (sale.discount * price) / 100; const discount = (sale.discount * price) / 100;
amountClaimed.value = amountClaimed.value + (price - discount); amountClaimed.value = amountClaimed.value + (price - discount);
} }
} }
@ -207,9 +208,10 @@ async function saveWhenHasChanges() {
selection="multiple" selection="multiple"
v-model:selected="selected" v-model:selected="selected"
:grid="$q.screen.lt.md" :grid="$q.screen.lt.md"
> >
<template #body-cell-claimed="{ row }"> <template #body-cell-claimed="{ row }">
<QTd auto-width align="right" class="text-primary"> <QTd auto-width align="right" class="text-primary shrink">
<QInput <QInput
v-model.number="row.quantity" v-model.number="row.quantity"
type="number" type="number"
@ -220,7 +222,7 @@ async function saveWhenHasChanges() {
</QTd> </QTd>
</template> </template>
<template #body-cell-description="{ row, value }"> <template #body-cell-description="{ row, value }">
<QTd auto-width align="right" class="text-primary"> <QTd auto-width align="right" class="link expand">
{{ value }} {{ value }}
<ItemDescriptorProxy <ItemDescriptorProxy
:id="row.sale.itemFk" :id="row.sale.itemFk"
@ -228,7 +230,7 @@ async function saveWhenHasChanges() {
</QTd> </QTd>
</template> </template>
<template #body-cell-discount="{ row, value, rowIndex }"> <template #body-cell-discount="{ row, value, rowIndex }">
<QTd auto-width align="right" class="text-primary"> <QTd auto-width align="right" class="text-primary shrink">
{{ value }} {{ value }}
<VnDiscount <VnDiscount
:quantity="row.quantity" :quantity="row.quantity"
@ -264,7 +266,7 @@ async function saveWhenHasChanges() {
</QItemSection> </QItemSection>
<QItemSection side> <QItemSection side>
<template v-if="column.name === 'claimed'"> <template v-if="column.name === 'claimed'">
<QItemLabel class="text-primary"> <QItemLabel class="text-primary shrink">
<QInput <QInput
v-model.number=" v-model.number="
props.row.quantity props.row.quantity
@ -282,7 +284,7 @@ async function saveWhenHasChanges() {
<template <template
v-else-if="column.name === 'discount'" v-else-if="column.name === 'discount'"
> >
<QItemLabel class="text-primary"> <QItemLabel class="text-primary shrink">
{{ column.value }} {{ column.value }}
<VnDiscount <VnDiscount
:quantity="props.row.quantity" :quantity="props.row.quantity"
@ -330,6 +332,7 @@ async function saveWhenHasChanges() {
.grid-style-transition { .grid-style-transition {
transition: transform 0.28s, background-color 0.28s; transition: transform 0.28s, background-color 0.28s;
} }
</style> </style>
<i18n> <i18n>

View File

@ -120,13 +120,13 @@ const developmentColumns = ref([
{ {
name: 'claimReason', name: 'claimReason',
label: 'claim.reason', label: 'claim.reason',
field: (row) => row.claimReason.description, field: (row) => row.claimReason?.description,
sortable: true, sortable: true,
}, },
{ {
name: 'claimResult', name: 'claimResult',
label: 'claim.result', label: 'claim.result',
field: (row) => row.claimResult.description, field: (row) => row.claimResult?.description,
sortable: true, sortable: true,
}, },
{ {
@ -345,12 +345,9 @@ function claimUrl(section) {
<span v-if="col.name != 'description'">{{ <span v-if="col.name != 'description'">{{
t(col.value) t(col.value)
}}</span> }}</span>
<QBtn <span class="link" v-if="col.name === 'description'">{{
v-if="col.name == 'description'" t(col.value)
flat }}</span>
color="blue"
>{{ col.value }}</QBtn
>
<ItemDescriptorProxy <ItemDescriptorProxy
v-if="col.name == 'description'" v-if="col.name == 'description'"
:id="props.row.sale.itemFk" :id="props.row.sale.itemFk"

View File

@ -30,7 +30,7 @@ defineExpose({ states });
<span>{{ formatFn(tag.value) }}</span> <span>{{ formatFn(tag.value) }}</span>
</div> </div>
</template> </template>
<template #body="{ params, searchFn }"> <template #body="{ params }">
<div class="q-pa-sm q-gutter-y-sm"> <div class="q-pa-sm q-gutter-y-sm">
<VnInput <VnInput
:label="t('claim.customerId')" :label="t('claim.customerId')"
@ -49,12 +49,9 @@ defineExpose({ states });
<VnSelect <VnSelect
:label="t('Salesperson')" :label="t('Salesperson')"
v-model="params.salesPersonFk" v-model="params.salesPersonFk"
@update:model-value="searchFn()"
url="Workers/activeWithInheritedRole" url="Workers/activeWithInheritedRole"
:filter="{ where: { role: 'salesPerson' } }" :filter="{ where: { role: 'salesPerson' } }"
:use-like="false" :use-like="false"
option-value="id"
option-label="name"
option-filter="firstName" option-filter="firstName"
dense dense
outlined outlined
@ -63,12 +60,9 @@ defineExpose({ states });
<VnSelect <VnSelect
:label="t('claim.attendedBy')" :label="t('claim.attendedBy')"
v-model="params.attenderFk" v-model="params.attenderFk"
@update:model-value="searchFn()"
url="Workers/activeWithInheritedRole" url="Workers/activeWithInheritedRole"
:filter="{ where: { role: 'salesPerson' } }" :filter="{ where: { role: 'salesPerson' } }"
:use-like="false" :use-like="false"
option-value="id"
option-label="name"
option-filter="firstName" option-filter="firstName"
dense dense
outlined outlined
@ -77,9 +71,7 @@ defineExpose({ states });
<VnSelect <VnSelect
:label="t('claim.state')" :label="t('claim.state')"
v-model="params.claimStateFk" v-model="params.claimStateFk"
@update:model-value="searchFn()"
:options="states" :options="states"
option-value="id"
option-label="description" option-label="description"
dense dense
outlined outlined
@ -87,7 +79,6 @@ defineExpose({ states });
/> />
<VnInputDate <VnInputDate
v-model="params.created" v-model="params.created"
@update:model-value="searchFn()"
:label="t('claim.created')" :label="t('claim.created')"
outlined outlined
rounded rounded
@ -96,10 +87,7 @@ defineExpose({ states });
<VnSelect <VnSelect
:label="t('Item')" :label="t('Item')"
v-model="params.itemFk" v-model="params.itemFk"
@update:model-value="searchFn()"
url="Items/withName" url="Items/withName"
option-value="id"
option-label="name"
:use-like="false" :use-like="false"
sort-by="id DESC" sort-by="id DESC"
outlined outlined
@ -118,21 +106,26 @@ defineExpose({ states });
<VnSelect <VnSelect
:label="t('claim.responsible')" :label="t('claim.responsible')"
v-model="params.claimResponsibleFk" v-model="params.claimResponsibleFk"
@update:model-value="searchFn()"
url="Workers/activeWithInheritedRole" url="Workers/activeWithInheritedRole"
:filter="{ where: { role: 'salesPerson' } }" :filter="{ where: { role: 'salesPerson' } }"
:use-like="false" :use-like="false"
option-value="id"
option-label="name"
option-filter="firstName" option-filter="firstName"
dense dense
outlined outlined
rounded rounded
/> />
<VnSelect
:label="t('claim.zone')"
v-model="params.zoneFk"
url="Zones"
:use-like="false"
outlined
rounded
dense
/>
<QCheckbox <QCheckbox
v-model="params.myTeam" v-model="params.myTeam"
:label="t('params.myTeam')" :label="t('params.myTeam')"
@update:model-value="searchFn()"
toggle-indeterminate toggle-indeterminate
/> />
</div> </div>
@ -153,6 +146,7 @@ en:
created: Created created: Created
myTeam: My team myTeam: My team
itemFk: Item itemFk: Item
zoneFk: Zone
es: es:
params: params:
search: Contiene search: Contiene
@ -165,6 +159,7 @@ es:
created: Creada created: Creada
myTeam: Mi equipo myTeam: Mi equipo
itemFk: Artículo itemFk: Artículo
zoneFk: Zona
Client Name: Nombre del cliente Client Name: Nombre del cliente
Salesperson: Comercial Salesperson: Comercial
Item: Artículo Item: Artículo

View File

@ -10,6 +10,7 @@ import ClaimSummary from './Card/ClaimSummary.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog'; import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import RightMenu from 'src/components/common/RightMenu.vue'; import RightMenu from 'src/components/common/RightMenu.vue';
import VnTable from 'src/components/VnTable/VnTable.vue'; import VnTable from 'src/components/VnTable/VnTable.vue';
import ZoneDescriptorProxy from '../Zone/Card/ZoneDescriptorProxy.vue';
const { t } = useI18n(); const { t } = useI18n();
const { viewSummary } = useSummaryDialog(); const { viewSummary } = useSummaryDialog();
@ -95,7 +96,12 @@ const columns = computed(() => [
optionLabel: 'description', optionLabel: 'description',
}, },
}, },
orderBy: 'priority', orderBy: 'cs.priority',
},
{
align: 'left',
label: t('claim.zone'),
name: 'zoneFk',
}, },
{ {
align: 'right', align: 'right',
@ -105,6 +111,7 @@ const columns = computed(() => [
title: t('components.smartCard.viewSummary'), title: t('components.smartCard.viewSummary'),
icon: 'preview', icon: 'preview',
action: (row) => viewSummary(row.id, ClaimSummary), action: (row) => viewSummary(row.id, ClaimSummary),
isPrimary: true,
}, },
], ],
}, },
@ -131,11 +138,10 @@ const STATE_COLOR = {
<VnTable <VnTable
data-key="ClaimList" data-key="ClaimList"
url="Claims/filter" url="Claims/filter"
:order="['priority ASC', 'created ASC']" :order="['cs.priority ASC', 'created ASC']"
:columns="columns" :columns="columns"
redirect="claim" redirect="claim"
:right-search="false" :right-search="false"
auto-load
> >
<template #column-clientFk="{ row }"> <template #column-clientFk="{ row }">
<span class="link" @click.stop> <span class="link" @click.stop>
@ -148,6 +154,12 @@ const STATE_COLOR = {
<VnUserLink :name="row.workerName" :worker-id="row.workerFk" /> <VnUserLink :name="row.workerName" :worker-id="row.workerFk" />
</span> </span>
</template> </template>
<template #column-zoneFk="{ row }">
<span class="link" @click.stop>
{{ row.zoneName }}
<ZoneDescriptorProxy :id="row.zoneId" />
</span>
</template>
</VnTable> </VnTable>
</template> </template>

View File

@ -16,14 +16,17 @@ const { t } = useI18n();
const businessTypes = ref([]); const businessTypes = ref([]);
const contactChannels = ref([]); const contactChannels = ref([]);
const handleSalesModelValue = (val) => ({ const handleSalesModelValue = (val) => {
if (!val) val = '';
return {
or: [ or: [
{ id: val }, { id: val },
{ name: val }, { name: val },
{ nickname: { like: '%' + val + '%' } }, { nickname: { like: '%' + val + '%' } },
{ code: { like: `${val}%` } }, { code: { like: `${val}%` } },
], ],
}); };
};
const exprBuilder = (param, value) => { const exprBuilder = (param, value) => {
return { return {

View File

@ -110,7 +110,7 @@ function handleLocation(data, location) {
<VnRow> <VnRow>
<QCheckbox :label="t('Has to invoice')" v-model="data.hasToInvoice" /> <QCheckbox :label="t('Has to invoice')" v-model="data.hasToInvoice" />
<div> <div>
<QCheckbox :label="t('Vies')" v-model="data.isVies" /> <QCheckbox :label="t('globals.isVies')" v-model="data.isVies" />
<QIcon name="info" class="cursor-info q-ml-sm" size="sm"> <QIcon name="info" class="cursor-info q-ml-sm" size="sm">
<QTooltip> <QTooltip>
{{ t('whenActivatingIt') }} {{ t('whenActivatingIt') }}
@ -169,7 +169,6 @@ es:
Active: Activo Active: Activo
Frozen: Congelado Frozen: Congelado
Has to invoice: Factura Has to invoice: Factura
Vies: Vies
Notify by email: Notificar vía e-mail Notify by email: Notificar vía e-mail
Invoice by address: Facturar por consignatario Invoice by address: Facturar por consignatario
Is equalizated: Recargo de equivalencia Is equalizated: Recargo de equivalencia

View File

@ -173,7 +173,7 @@ const sumRisk = ({ clientRisks }) => {
:label="t('customer.summary.notifyByEmail')" :label="t('customer.summary.notifyByEmail')"
:value="entity.isToBeMailed" :value="entity.isToBeMailed"
/> />
<VnLv :label="t('customer.summary.vies')" :value="entity.isVies" /> <VnLv :label="t('globals.isVies')" :value="entity.isVies" />
</VnRow> </VnRow>
</QCard> </QCard>
<QCard class="vn-one"> <QCard class="vn-one">

View File

@ -12,14 +12,17 @@ defineProps({
required: true, required: true,
}, },
}); });
const handleSalesModelValue = (val) => ({ const handleSalesModelValue = (val) => {
if (!val) val = '';
return {
or: [ or: [
{ id: val }, { id: val },
{ name: val }, { name: val },
{ nickname: { like: '%' + val + '%' } }, { nickname: { like: '%' + val + '%' } },
{ code: { like: `${val}%` } }, { code: { like: `${val}%` } },
], ],
}); };
};
const exprBuilder = (param, value) => { const exprBuilder = (param, value) => {
return { return {

View File

@ -2,22 +2,21 @@
import { ref, computed, markRaw } from 'vue'; import { ref, computed, markRaw } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { toDate } from 'src/filters';
import RightMenu from 'src/components/common/RightMenu.vue';
import CustomerSummary from './Card/CustomerSummary.vue';
import CustomerFilter from './CustomerFilter.vue';
import VnTable from 'components/VnTable/VnTable.vue'; import VnTable from 'components/VnTable/VnTable.vue';
import VnLocation from 'src/components/common/VnLocation.vue'; import VnLocation from 'src/components/common/VnLocation.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue'; import VnSearchbar from 'components/ui/VnSearchbar.vue';
import CustomerSummary from './Card/CustomerSummary.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import RightMenu from 'src/components/common/RightMenu.vue';
import VnLinkPhone from 'src/components/ui/VnLinkPhone.vue'; import VnLinkPhone from 'src/components/ui/VnLinkPhone.vue';
import { toDate } from 'src/filters';
import CustomerFilter from './CustomerFilter.vue';
import VnSelectWorker from 'src/components/common/VnSelectWorker.vue'; import VnSelectWorker from 'src/components/common/VnSelectWorker.vue';
const { t } = useI18n(); const { t } = useI18n();
const router = useRouter(); const router = useRouter();
const tableRef = ref(); const tableRef = ref();
const columns = computed(() => [ const columns = computed(() => [
{ {
align: 'left', align: 'left',
@ -263,7 +262,7 @@ const columns = computed(() => [
}, },
{ {
align: 'left', align: 'left',
label: t('customer.extendedList.tableVisibleColumns.isVies'), label: t('globals.isVies'),
name: 'isVies', name: 'isVies',
columnFilter: { columnFilter: {
inWhere: true, inWhere: true,
@ -405,6 +404,7 @@ function handleLocation(data, location) {
ref="tableRef" ref="tableRef"
data-key="CustomerList" data-key="CustomerList"
url="Clients/filter" url="Clients/filter"
order="id DESC"
:create="{ :create="{
urlCreate: 'Clients/createWithUser', urlCreate: 'Clients/createWithUser',
title: t('globals.pageTitles.customerCreate'), title: t('globals.pageTitles.customerCreate'),
@ -414,11 +414,9 @@ function handleLocation(data, location) {
isEqualizated: false, isEqualizated: false,
}, },
}" }"
order="id DESC"
:columns="columns" :columns="columns"
redirect="customer"
:right-search="false" :right-search="false"
auto-load redirect="customer"
> >
<template #more-create-dialog="{ data }"> <template #more-create-dialog="{ data }">
<VnSelectWorker <VnSelectWorker
@ -431,7 +429,26 @@ function handleLocation(data, location) {
:id-value="data.salesPersonFk" :id-value="data.salesPersonFk"
emit-value emit-value
auto-load auto-load
>
<template #prepend>
<VnAvatar
:worker-id="data.salesPersonFk"
color="primary"
:title="title"
/> />
</template>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>{{ scope.opt?.name }}</QItemLabel>
<QItemLabel caption
>{{ scope.opt?.nickname }},
{{ scope.opt?.code }}</QItemLabel
>
</QItemSection>
</QItem>
</template>
</VnSelectWorker>
<VnLocation <VnLocation
:acls="[{ model: 'Province', props: '*', accessType: 'WRITE' }]" :acls="[{ model: 'Province', props: '*', accessType: 'WRITE' }]"
v-model="data.location" v-model="data.location"
@ -452,7 +469,7 @@ function handleLocation(data, location) {
</template> </template>
<i18n> <i18n>
es: es:
Web user: Usuario Web Web user: Usuario web
</i18n> </i18n>
<style lang="scss" scoped> <style lang="scss" scoped>
.col-content { .col-content {

View File

@ -12,6 +12,7 @@ import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnSelectDialog from 'src/components/common/VnSelectDialog.vue'; import VnSelectDialog from 'src/components/common/VnSelectDialog.vue';
import CustomerNewCustomsAgent from 'src/pages/Customer/components/CustomerNewCustomsAgent.vue'; import CustomerNewCustomsAgent from 'src/pages/Customer/components/CustomerNewCustomsAgent.vue';
import VnInputNumber from 'src/components/common/VnInputNumber.vue';
const { t } = useI18n(); const { t } = useI18n();
const route = useRoute(); const route = useRoute();
@ -144,7 +145,6 @@ function handleLocation(data, location) {
:url="`Addresses/${route.params.addressId}`" :url="`Addresses/${route.params.addressId}`"
@on-data-saved="onDataSaved()" @on-data-saved="onDataSaved()"
auto-load auto-load
model="customer"
> >
<template #moreActions> <template #moreActions>
<QBtn <QBtn
@ -220,7 +220,6 @@ function handleLocation(data, location) {
</div> </div>
</VnRow> </VnRow>
<VnRow> <VnRow>
<div class="col">
<VnSelect <VnSelect
:label="t('Incoterms')" :label="t('Incoterms')"
:options="incoterms" :options="incoterms"
@ -229,8 +228,6 @@ function handleLocation(data, location) {
option-value="code" option-value="code"
v-model="data.incotermsFk" v-model="data.incotermsFk"
/> />
</div>
<div class="col">
<VnSelectDialog <VnSelectDialog
:label="t('Customs agent')" :label="t('Customs agent')"
:options="customsAgents" :options="customsAgents"
@ -244,7 +241,14 @@ function handleLocation(data, location) {
<CustomerNewCustomsAgent /> <CustomerNewCustomsAgent />
</template> </template>
</VnSelectDialog> </VnSelectDialog>
</div> </VnRow>
<VnRow>
<VnInputNumber
:label="t('Longitude')"
clearable
v-model="data.longitude"
/>
<VnInputNumber :label="t('Latitude')" clearable v-model="data.latitude" />
</VnRow> </VnRow>
<h4 class="q-mb-xs">{{ t('Notes') }}</h4> <h4 class="q-mb-xs">{{ t('Notes') }}</h4>
<VnRow <VnRow
@ -322,4 +326,6 @@ es:
Description: Descripción Description: Descripción
Add note: Añadir nota Add note: Añadir nota
Remove note: Eliminar nota Remove note: Eliminar nota
Longitude: Longitud
Latitude: Latitud
</i18n> </i18n>

View File

@ -189,6 +189,7 @@ async function getAmountPaid() {
:url-create="urlCreate" :url-create="urlCreate"
:mapper="onBeforeSave" :mapper="onBeforeSave"
@on-data-saved="onDataSaved" @on-data-saved="onDataSaved"
:prevent-submit="true"
> >
<template #form="{ data, validate }"> <template #form="{ data, validate }">
<span ref="closeButton" class="row justify-end close-icon" v-close-popup> <span ref="closeButton" class="row justify-end close-icon" v-close-popup>
@ -303,7 +304,7 @@ async function getAmountPaid() {
:label="t('globals.save')" :label="t('globals.save')"
:loading="formModelRef.isLoading" :loading="formModelRef.isLoading"
color="primary" color="primary"
type="submit" @click="formModelRef.save()"
/> />
</div> </div>
</template> </template>

View File

@ -107,7 +107,7 @@ const setParams = (params) => {
const getPreview = async () => { const getPreview = async () => {
const params = { const params = {
recipientId: entityId, recipientId: entityId.value,
}; };
const validationMessage = validateMessage(); const validationMessage = validateMessage();
if (validationMessage) return notify(t(validationMessage), 'negative'); if (validationMessage) return notify(t(validationMessage), 'negative');

View File

@ -88,7 +88,6 @@ customer:
businessTypeFk: Business type businessTypeFk: Business type
sageTaxTypeFk: Sage tax type sageTaxTypeFk: Sage tax type
sageTransactionTypeFk: Sage tr. type sageTransactionTypeFk: Sage tr. type
isVies: Vies
isTaxDataChecked: Verified data isTaxDataChecked: Verified data
isFreezed: Freezed isFreezed: Freezed
hasToInvoice: Invoice hasToInvoice: Invoice

View File

@ -90,7 +90,6 @@ customer:
businessTypeFk: Tipo de negocio businessTypeFk: Tipo de negocio
sageTaxTypeFk: Tipo de impuesto Sage sageTaxTypeFk: Tipo de impuesto Sage
sageTransactionTypeFk: Tipo tr. sage sageTransactionTypeFk: Tipo tr. sage
isVies: Vies
isTaxDataChecked: Datos comprobados isTaxDataChecked: Datos comprobados
isFreezed: Congelado isFreezed: Congelado
hasToInvoice: Factura hasToInvoice: Factura

View File

@ -83,7 +83,7 @@ const { openConfirmationModal } = useVnConfirm();
</template> </template>
<template #body="{ entity }"> <template #body="{ entity }">
<VnLv :label="t('department.chat')" :value="entity.chatName" /> <VnLv :label="t('department.chat')" :value="entity.chatName" />
<VnLv :label="t('department.email')" :value="entity.notificationEmail" copy /> <VnLv :label="t('globals.email')" :value="entity.notificationEmail" copy />
<VnLv <VnLv
:label="t('department.selfConsumptionCustomer')" :label="t('department.selfConsumptionCustomer')"
:value="entity.client?.name" :value="entity.client?.name"

View File

@ -58,7 +58,7 @@ onMounted(async () => {
dash dash
/> />
<VnLv <VnLv
:label="t('department.email')" :label="t('globals.email')"
:value="department.notificationEmail" :value="department.notificationEmail"
dash dash
/> />

View File

@ -1,8 +1,6 @@
<script setup> <script setup>
import { ref } from 'vue'; import { ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { onMounted } from 'vue';
import { useStateStore } from 'stores/useStateStore';
import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue'; import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
@ -20,11 +18,6 @@ const props = defineProps({
const currenciesOptions = ref([]); const currenciesOptions = ref([]);
const companiesOptions = ref([]); const companiesOptions = ref([]);
const stateStore = useStateStore();
onMounted(async () => {
stateStore.rightDrawer = true;
});
</script> </script>
<template> <template>

View File

@ -49,8 +49,10 @@ const columns = computed(() => [
align: 'left', align: 'left',
label: t('globals.id'), label: t('globals.id'),
name: 'id', name: 'id',
isTitle: true, isId: true,
cardVisible: true, chip: {
condition: () => true,
},
}, },
{ {
align: 'left', align: 'left',
@ -177,9 +179,6 @@ const columns = computed(() => [
], ],
}, },
]); ]);
onMounted(async () => {
stateStore.rightDrawer = true;
});
</script> </script>
<template> <template>
<VnSearchbar <VnSearchbar
@ -207,7 +206,6 @@ onMounted(async () => {
order="id DESC" order="id DESC"
:columns="columns" :columns="columns"
redirect="entry" redirect="entry"
auto-load
:right-search="false" :right-search="false"
> >
<template #column-status="{ row }"> <template #column-status="{ row }">

Some files were not shown because too many files have changed in this diff Show More