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

This commit is contained in:
Jose Antonio Tubau 2025-04-16 13:21:14 +00:00
commit 5053dbe1eb
189 changed files with 1522 additions and 987 deletions

View File

@ -1,6 +1,6 @@
{
"name": "salix-front",
"version": "25.16.0",
"version": "25.18.0",
"description": "Salix frontend",
"productName": "Salix",
"author": "Verdnatura",
@ -89,4 +89,4 @@
"vite": "^6.0.11",
"vitest": "^0.31.1"
}
}
}

View File

@ -2,6 +2,7 @@
import { onMounted } from 'vue';
import { useQuasar, Dark } from 'quasar';
import { useI18n } from 'vue-i18n';
import VnScroll from './components/common/VnScroll.vue';
const quasar = useQuasar();
const { availableLocales, locale, fallbackLocale } = useI18n();
@ -38,6 +39,7 @@ quasar.iconMapFn = (iconName) => {
<template>
<RouterView />
<VnScroll/>
</template>
<style lang="scss">

View File

@ -67,7 +67,7 @@ describe('Axios boot', () => {
};
const result = onResponseError(error);
expect(result).rejects.toEqual(expect.objectContaining(error));
await expect(result).rejects.toEqual(expect.objectContaining(error));
});
it('should call to the Notify plugin with a message from the response property', async () => {
@ -83,7 +83,7 @@ describe('Axios boot', () => {
};
const result = onResponseError(error);
expect(result).rejects.toEqual(expect.objectContaining(error));
await expect(result).rejects.toEqual(expect.objectContaining(error));
});
});
});

View File

@ -1,4 +1,6 @@
import { boot } from 'quasar/wrappers';
import { date as quasarDate } from 'quasar';
const { formatDate } = quasarDate;
export default boot(() => {
Date.vnUTC = () => {
@ -25,4 +27,34 @@ export default boot(() => {
const date = new Date(Date.vnUTC());
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
};
Date.getCurrentDateTimeFormatted = (
options = {
startOfDay: false,
endOfDay: true,
iso: true,
mask: 'DD-MM-YYYY HH:mm',
},
) => {
const date = Date.vnUTC();
if (options.startOfDay) {
date.setHours(0, 0, 0);
}
if (options.endOfDay) {
date.setHours(23, 59, 0);
}
if (options.iso) {
return date.toISOString();
}
return formatDate(date, options.mask);
};
Date.convertToISODateTime = (dateTimeStr) => {
const [datePart, timePart] = dateTimeStr.split(' ');
const [day, month, year] = datePart.split('-');
const [hours, minutes] = timePart.split(':');
const isoDate = new Date(year, month - 1, day, hours, minutes);
return isoDate.toISOString();
};
});

View File

@ -20,7 +20,6 @@ const postcodeFormData = reactive({
provinceFk: null,
townFk: null,
});
const townFilter = ref({});
const countriesRef = ref(false);
const provincesOptions = ref([]);
@ -33,11 +32,11 @@ function onDataSaved(formData) {
newPostcode.town = town.value.name;
newPostcode.townFk = town.value.id;
const provinceObject = provincesOptions.value.find(
({ id }) => id === formData.provinceFk
({ id }) => id === formData.provinceFk,
);
newPostcode.province = provinceObject?.name;
const countryObject = countriesRef.value.opts.find(
({ id }) => id === formData.countryFk
({ id }) => id === formData.countryFk,
);
newPostcode.country = countryObject?.name;
emit('onDataSaved', newPostcode);
@ -67,21 +66,11 @@ function setTown(newTown, data) {
}
async function onCityCreated(newTown, formData) {
newTown.province = provincesOptions.value.find(
(province) => province.id === newTown.provinceFk
(province) => province.id === newTown.provinceFk,
);
formData.townFk = newTown;
setTown(newTown, formData);
}
async function filterTowns(name) {
if (name !== '') {
townFilter.value.where = {
name: {
like: `%${name}%`,
},
};
}
}
</script>
<template>
@ -107,7 +96,6 @@ async function filterTowns(name) {
<VnSelectDialog
:label="t('City')"
@update:model-value="(value) => setTown(value, data)"
@filter="filterTowns"
:tooltip="t('Create city')"
v-model="data.townFk"
url="Towns/location"

View File

@ -65,7 +65,7 @@ const $props = defineProps({
default: null,
},
beforeSaveFn: {
type: Function,
type: [String, Function],
default: null,
},
goTo: {

View File

@ -140,7 +140,7 @@ const updatePhotoPreview = (value) => {
img.onerror = () => {
notify(
t("This photo provider doesn't allow remote downloads"),
'negative'
'negative',
);
};
}
@ -219,11 +219,7 @@ const makeRequest = async () => {
color="primary"
class="cursor-pointer"
@click="rotateLeft()"
>
<!-- <QTooltip class="no-pointer-events">
{{ t('Rotate left') }}
</QTooltip> -->
</QIcon>
/>
<div>
<div ref="photoContainerRef" />
</div>
@ -233,11 +229,7 @@ const makeRequest = async () => {
color="primary"
class="cursor-pointer"
@click="rotateRight()"
>
<!-- <QTooltip class="no-pointer-events">
{{ t('Rotate right') }}
</QTooltip> -->
</QIcon>
/>
</div>
<div class="column">
@ -265,7 +257,6 @@ const makeRequest = async () => {
class="cursor-pointer q-mr-sm"
@click="openInputFile()"
>
<!-- <QTooltip>{{ t('globals.selectFile') }}</QTooltip> -->
</QIcon>
<QIcon name="info" class="cursor-pointer">
<QTooltip>{{

View File

@ -22,7 +22,6 @@ const { validate, validations } = useValidator();
const { notify } = useNotify();
const route = useRoute();
const myForm = ref(null);
const attrs = useAttrs();
const $props = defineProps({
url: {
type: String,
@ -99,8 +98,12 @@ const $props = defineProps({
type: Function,
default: () => {},
},
preventSubmit: {
type: Boolean,
default: true,
},
});
const emit = defineEmits(['onFetch', 'onDataSaved']);
const emit = defineEmits(['onFetch', 'onDataSaved', 'submit']);
const modelValue = computed(
() => $props.model ?? `formModel_${route?.meta?.title ?? route.name}`,
).value;
@ -301,7 +304,7 @@ function onBeforeSave(formData, originalData) {
);
}
async function onKeyup(evt) {
if (evt.key === 'Enter' && !('prevent-submit' in attrs)) {
if (evt.key === 'Enter' && !$props.preventSubmit) {
const input = evt.target;
if (input.type == 'textarea' && evt.shiftKey) {
let { selectionStart, selectionEnd } = input;
@ -330,6 +333,7 @@ defineExpose({
<template>
<div class="column items-center full-width">
<QForm
v-on="$attrs"
ref="myForm"
v-if="formData"
@submit.prevent="save"
@ -406,6 +410,7 @@ defineExpose({
</QBtnDropdown>
<QBtn
v-else
data-cy="saveDefaultBtn"
:label="tMobile('globals.save')"
color="primary"
icon="save"

View File

@ -181,7 +181,7 @@ const searchModule = () => {
<template>
<QList padding class="column-max-width">
<template v-if="$props.source === 'main'">
<template v-if="$route?.matched[1]?.name === 'Dashboard'">
<template v-if="route?.matched[1]?.name === 'Dashboard'">
<QItem class="q-pb-md">
<VnInput
v-model="search"
@ -262,7 +262,7 @@ const searchModule = () => {
</template>
<template v-for="item in items" :key="item.name">
<template v-if="item.name === $route?.matched[1]?.name">
<template v-if="item.name === route?.matched[1]?.name">
<QItem class="header">
<QItemSection avatar v-if="item.icon">
<QIcon :name="item.icon" />

View File

@ -69,7 +69,7 @@ const refresh = () => window.location.reload();
'no-visible': !stateQuery.isLoading().value,
}"
size="sm"
data-cy="loading-spinner"
data-cy="navBar-spinner"
/>
<QSpace />
<div id="searchbar" class="searchbar"></div>

View File

@ -1,12 +1,22 @@
<script setup>
import { toCurrency } from 'src/filters';
import { getValueFromPath } from 'src/composables/getValueFromPath';
defineProps({ row: { type: Object, required: true } });
const { row, visibleProblems = null } = defineProps({
row: { type: Object, required: true },
visibleProblems: { type: Array },
});
function showProblem(problem) {
const val = getValueFromPath(row, problem);
if (!visibleProblems) return val;
return !!(visibleProblems?.includes(problem) && val);
}
</script>
<template>
<span class="q-gutter-x-xs">
<router-link
v-if="row.claim?.claimFk"
v-if="showProblem('claim.claimFk')"
:to="{ name: 'ClaimBasicData', params: { id: row.claim?.claimFk } }"
class="link"
>
@ -18,7 +28,7 @@ defineProps({ row: { type: Object, required: true } });
</QIcon>
</router-link>
<QIcon
v-if="row?.isDeleted"
v-if="showProblem('isDeleted')"
color="primary"
name="vn:deletedTicket"
size="xs"
@ -29,7 +39,7 @@ defineProps({ row: { type: Object, required: true } });
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasRisk"
v-if="showProblem('hasRisk')"
name="vn:risk"
:color="row.hasHighRisk ? 'negative' : 'primary'"
size="xs"
@ -40,51 +50,76 @@ defineProps({ row: { type: Object, required: true } });
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasComponentLack"
v-if="showProblem('hasComponentLack')"
name="vn:components"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.componentLack') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.hasItemDelay" color="primary" size="xs" name="vn:hasItemDelay">
<QIcon
v-if="showProblem('hasItemDelay')"
color="primary"
size="xs"
name="vn:hasItemDelay"
>
<QTooltip>
{{ $t('ticket.summary.hasItemDelay') }}
</QTooltip>
</QIcon>
<QIcon v-if="row?.hasItemLost" color="primary" size="xs" name="vn:hasItemLost">
<QIcon
v-if="showProblem('hasItemLost')"
color="primary"
size="xs"
name="vn:hasItemLost"
>
<QTooltip>
{{ $t('salesTicketsTable.hasItemLost') }}
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasItemShortage"
v-if="showProblem('hasItemShortage')"
name="vn:unavailable"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.notVisible') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.hasRounding" color="primary" name="sync_problem" size="xs">
<QIcon
v-if="showProblem('hasRounding')"
color="primary"
name="sync_problem"
size="xs"
>
<QTooltip>
{{ $t('ticketList.rounding') }}
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasTicketRequest"
v-if="showProblem('hasTicketRequest')"
name="vn:buyrequest"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.purchaseRequest') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.isTaxDataChecked" name="vn:no036" color="primary" size="xs">
<QIcon
v-if="showProblem('isTaxDataChecked')"
name="vn:no036"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.noVerifiedData') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.isFreezed" name="vn:frozen" color="primary" size="xs">
<QIcon v-if="showProblem('isFreezed')" name="vn:frozen" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.clientFrozen') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.isTooLittle" name="vn:isTooLittle" color="primary" size="xs">
<QIcon
v-if="showProblem('isTooLittle')"
name="vn:isTooLittle"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.tooLittle') }}</QTooltip>
</QIcon>
</span>

View File

@ -16,7 +16,7 @@ const $props = defineProps({
required: true,
},
searchUrl: {
type: String,
type: [String, Boolean],
default: 'table',
},
vertical: {

View File

@ -33,6 +33,7 @@ import VnTableOrder from 'src/components/VnTable/VnOrder.vue';
import VnTableFilter from './VnTableFilter.vue';
import { getColAlign } from 'src/composables/getColAlign';
import RightMenu from '../common/RightMenu.vue';
import VnScroll from '../common/VnScroll.vue'
const arrayData = useArrayData(useAttrs()['data-key']);
const $props = defineProps({
@ -65,7 +66,7 @@ const $props = defineProps({
default: null,
},
create: {
type: Object,
type: [Boolean, Object],
default: null,
},
createAsDialog: {
@ -168,6 +169,7 @@ const params = ref(useFilterParams($attrs['data-key']).params);
const orders = ref(useFilterParams($attrs['data-key']).orders);
const app = inject('app');
const tableHeight = useTableHeight();
const vnScrollRef = ref(null);
const editingRow = ref(null);
const editingField = ref(null);
@ -189,6 +191,17 @@ const tableModes = [
},
];
const onVirtualScroll = ({ to }) => {
handleScroll();
const virtualScrollContainer = tableRef.value?.$el?.querySelector('.q-table__middle');
if (virtualScrollContainer) {
virtualScrollContainer.dispatchEvent(new CustomEvent('scroll'));
if (vnScrollRef.value) {
vnScrollRef.value.updateScrollContainer(virtualScrollContainer);
}
}
};
onBeforeMount(() => {
const urlParams = route.query[$props.searchUrl];
hasParams.value = urlParams && Object.keys(urlParams).length !== 0;
@ -327,16 +340,13 @@ function handleOnDataSaved(_) {
if (_.onDataSaved) _.onDataSaved({ CrudModelRef: CrudModelRef.value });
else $props.create.onDataSaved(_);
}
function handleScroll() {
if ($props.crudModel.disableInfiniteScroll) return;
const tMiddle = tableRef.value.$el.querySelector('.q-table__middle');
const { scrollHeight, scrollTop, clientHeight } = tMiddle;
const isAtBottom = Math.abs(scrollHeight - scrollTop - clientHeight) <= 40;
if (isAtBottom) CrudModelRef.value.vnPaginateRef.paginate();
if ($props.crudModel.disableInfiniteScroll) return;
const tMiddle = tableRef.value.$el.querySelector('.q-table__middle');
const { scrollHeight, scrollTop, clientHeight } = tMiddle;
const isAtBottom = Math.abs(scrollHeight - scrollTop - clientHeight) <= 40;
if (isAtBottom) CrudModelRef.value.vnPaginateRef.paginate();
}
function handleSelection({ evt, added, rows: selectedRows }, rows) {
if (evt?.shiftKey && added) {
const rowIndex = selectedRows[0].$index;
@ -669,9 +679,9 @@ const rowCtrlClickFunction = computed(() => {
ref="tableRef"
v-bind="table"
:class="[
'vnTable',
table ? 'selection-cell' : '',
$props.footer ? 'last-row-sticky' : '',
'vnTable',
table ? 'selection-cell' : '',
$props.footer ? 'last-row-sticky' : '',
]"
wrap-cells
:columns="splittedColumns.columns"
@ -683,7 +693,7 @@ const rowCtrlClickFunction = computed(() => {
flat
:style="isTableMode && `max-height: ${$props.tableHeight || tableHeight}`"
:virtual-scroll="isTableMode"
@virtual-scroll="handleScroll"
@virtual-scroll="onVirtualScroll"
@row-click="(event, row) => handleRowClick(event, row)"
@update:selected="emit('update:selected', $event)"
@selection="(details) => handleSelection(details, rows)"
@ -741,6 +751,7 @@ const rowCtrlClickFunction = computed(() => {
withFilters
"
:column="col"
:data-cy="`column-filter-${col.name}`"
:show-title="true"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
@ -1087,6 +1098,11 @@ const rowCtrlClickFunction = computed(() => {
</template>
</FormModelPopup>
</QDialog>
<VnScroll
ref="vnScrollRef"
v-if="isTableMode"
:scroll-target="tableRef?.$el?.querySelector('.q-table__middle')"
/>
</template>
<i18n>
en:

View File

@ -30,6 +30,7 @@ function columnName(col) {
v-bind="$attrs"
:search-button="true"
:disable-submit-event="true"
:data-key="$attrs['data-key']"
:search-url
>
<template #body="{ params, orders, searchFn }">

View File

@ -58,7 +58,7 @@ async function getConfig(url, filter) {
const response = await axios.get(url, {
params: { filter: filter },
});
return response.data && response.data.length > 0 ? response.data[0] : null;
return response?.data && response?.data?.length > 0 ? response.data[0] : null;
}
async function fetchViewConfigData() {

View File

@ -11,6 +11,9 @@ describe('VnTable', () => {
propsData: {
columns: [],
},
attrs: {
'data-key': 'test',
},
});
vm = wrapper.vm;

View File

@ -11,13 +11,7 @@ describe('CrudModel', () => {
beforeAll(() => {
wrapper = createWrapper(CrudModel, {
global: {
stubs: [
'vnPaginate',
'useState',
'arrayData',
'useStateStore',
'vue-i18n',
],
stubs: ['vnPaginate', 'vue-i18n'],
mocks: {
validate: vi.fn(),
},
@ -29,7 +23,7 @@ describe('CrudModel', () => {
dataKey: 'crudModelKey',
model: 'crudModel',
url: 'crudModelUrl',
saveFn: '',
saveFn: vi.fn(),
},
});
wrapper = wrapper.wrapper;
@ -231,7 +225,7 @@ describe('CrudModel', () => {
expect(vm.isLoading).toBe(false);
expect(vm.hasChanges).toBe(false);
await wrapper.setProps({ saveFn: '' });
await wrapper.setProps({ saveFn: null });
});
it("should use default url if there's not saveFn", async () => {

View File

@ -170,7 +170,7 @@ describe('LeftMenu as card', () => {
vm = mount('card').vm;
});
it('should get routes for card source', async () => {
it('should get routes for card source', () => {
vm.getRoutes();
});
});
@ -251,7 +251,6 @@ describe('LeftMenu as main', () => {
});
it('should get routes for main source', () => {
vm.props.source = 'main';
vm.getRoutes();
expect(navigation.getModules).toHaveBeenCalled();
});

View File

@ -1,65 +1,63 @@
import { vi, describe, expect, it, beforeEach, afterEach } from 'vitest';
import { vi, describe, expect, it, beforeEach, beforeAll, afterEach } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import UserPanel from 'src/components/UserPanel.vue';
import axios from 'axios';
import { useState } from 'src/composables/useState';
vi.mock('src/utils/quasarLang', () => ({
default: vi.fn(),
}));
describe('UserPanel', () => {
let wrapper;
let vm;
let state;
let wrapper;
let vm;
let state;
beforeEach(() => {
wrapper = createWrapper(UserPanel, {});
state = useState();
state.setUser({
id: 115,
name: 'itmanagement',
nickname: 'itManagementNick',
lang: 'en',
darkMode: false,
companyFk: 442,
warehouseFk: 1,
beforeEach(() => {
wrapper = createWrapper(UserPanel, {});
state = useState();
state.setUser({
id: 115,
name: 'itmanagement',
nickname: 'itManagementNick',
lang: 'en',
darkMode: false,
companyFk: 442,
warehouseFk: 1,
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
});
afterEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.clearAllMocks();
});
it('should fetch warehouses data on mounted', async () => {
const fetchData = wrapper.findComponent({ name: 'FetchData' });
expect(fetchData.props('url')).toBe('Warehouses');
expect(fetchData.props('autoLoad')).toBe(true);
});
it('should fetch warehouses data on mounted', async () => {
const fetchData = wrapper.findComponent({ name: 'FetchData' });
expect(fetchData.props('url')).toBe('Warehouses');
expect(fetchData.props('autoLoad')).toBe(true);
});
it('should toggle dark mode correctly and update preferences', async () => {
await vm.saveDarkMode(true);
expect(axios.patch).toHaveBeenCalledWith('/UserConfigs/115', { darkMode: true });
expect(vm.user.darkMode).toBe(true);
await vm.updatePreferences();
expect(vm.darkMode).toBe(true);
});
it('should toggle dark mode correctly and update preferences', async () => {
await vm.saveDarkMode(true);
expect(axios.patch).toHaveBeenCalledWith('/UserConfigs/115', { darkMode: true });
expect(vm.user.darkMode).toBe(true);
vm.updatePreferences();
expect(vm.darkMode).toBe(true);
});
it('should change user language and update preferences', async () => {
const userLanguage = 'es';
await vm.saveLanguage(userLanguage);
expect(axios.patch).toHaveBeenCalledWith('/VnUsers/115', { lang: userLanguage });
expect(vm.user.lang).toBe(userLanguage);
await vm.updatePreferences();
expect(vm.locale).toBe(userLanguage);
});
it('should change user language and update preferences', async () => {
const userLanguage = 'es';
await vm.saveLanguage(userLanguage);
expect(axios.patch).toHaveBeenCalledWith('/VnUsers/115', { lang: userLanguage });
expect(vm.user.lang).toBe(userLanguage);
vm.updatePreferences();
expect(vm.locale).toBe(userLanguage);
});
it('should update user data', async () => {
const key = 'name';
const value = 'itboss';
await vm.saveUserData(key, value);
expect(axios.post).toHaveBeenCalledWith('UserConfigs/setUserConfig', { [key]: value });
});
});
it('should update user data', async () => {
const key = 'name';
const value = 'itboss';
await vm.saveUserData(key, value);
expect(axios.post).toHaveBeenCalledWith('UserConfigs/setUserConfig', {
[key]: value,
});
});
});

View File

@ -8,7 +8,8 @@ const model = defineModel({ prop: 'modelValue' });
<VnInput
v-model="model"
ref="inputRef"
@keydown.tab="model = useAccountShortToStandard($event.target.value) ?? model"
@keydown.tab="$refs.inputRef.vnInputRef.blur()"
@blur="model = useAccountShortToStandard(model) ?? model"
@input="model = $event.target.value.replace(/[^\d.]/g, '')"
/>
</template>

View File

@ -1,5 +1,5 @@
<script setup>
const model = defineModel({ type: [String, Number], required: true });
const model = defineModel({ type: [String, Number], default: '' });
</script>
<template>
<QDate v-model="model" :today-btn="true" :options="$attrs.options" />

View File

@ -61,8 +61,11 @@ function onFileChange(files) {
function mapperDms(data) {
const formData = new FormData();
const { files } = data;
if (files) formData.append(files?.name, files);
let files = data.files;
if (files) {
files = Array.isArray(files) ? files : [files];
files.forEach((file) => formData.append(file?.name, file));
}
const dms = {
hasFile: !!data.hasFile,

View File

@ -20,12 +20,12 @@ const autofillBic = async (iban) => {
if (ibanCountry != 'ES') return;
const filter = { where: { id: bankEntityId.value } };
const filter = { where: { id: bankEntityId } };
const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`BankEntities`, { params });
emit('updateBic', data[0].id);
emit('updateBic', data[0]?.id);
};
</script>
<template>

View File

@ -0,0 +1,79 @@
<script setup>
import { computed, useAttrs } from 'vue';
import { date } from 'quasar';
import VnDate from './VnDate.vue';
import VnTime from './VnTime.vue';
const $attrs = useAttrs();
const model = defineModel({ type: [Date, String] });
const $props = defineProps({
isOutlined: {
type: Boolean,
default: false,
},
showEvent: {
type: Boolean,
default: true,
},
});
const styleAttrs = computed(() => {
return $props.isOutlined
? {
dense: true,
outlined: true,
rounded: true,
}
: {};
});
const mask = 'DD-MM-YYYY HH:mm';
const selectedDate = computed({
get() {
if (!model.value) return JSON.stringify(new Date(model.value));
return date.formatDate(new Date(model.value), mask);
},
set(value) {
model.value = Date.convertToISODateTime(value);
},
});
const manageDate = (date) => {
selectedDate.value = date;
};
</script>
<template>
<div @mouseover="hover = true" @mouseleave="hover = false">
<QInput
ref="vnInputDateRef"
v-model="selectedDate"
class="vn-input-date"
placeholder="dd/mm/aaaa HH:mm"
v-bind="{ ...$attrs, ...styleAttrs }"
:clearable="false"
@click="isPopupOpen = !isPopupOpen"
@keydown="isPopupOpen = false"
hide-bottom-space
@update:model-value="manageDate"
:data-cy="$attrs.dataCy ?? $attrs.label + '_inputDateTime'"
>
<template #prepend>
<QIcon name="today" size="xs">
<QPopupProxy cover transition-show="scale" transition-hide="scale">
<VnDate :mask="mask" v-model="selectedDate" />
</QPopupProxy>
</QIcon>
</template>
<template #append>
<QIcon name="access_time" size="xs">
<QPopupProxy cover transition-show="scale" transition-hide="scale">
<VnTime format24h :mask="mask" v-model="selectedDate" />
</QPopupProxy>
</QIcon>
</template>
</QInput>
</div>
</template>
<i18n>
es:
Open date: Abrir fecha
</i18n>

View File

@ -68,7 +68,6 @@ const filter = {
},
},
],
where: { and: [{ originFk: route.params.id }] },
};
const paginate = ref();
@ -267,13 +266,6 @@ onMounted(() => {
onUnmounted(() => {
stateStore.rightDrawer = false;
});
watch(
() => router.currentRoute.value.params.id,
() => {
applyFilter();
},
);
</script>
<template>
<VnPaginate
@ -281,6 +273,7 @@ watch(
:data-key
:url="dataKey + 's'"
:user-filter="filter"
:filter="{ where: { and: [{ originFk: route.params.id }] } }"
:skeleton="false"
auto-load
@on-fetch="setLogTree"

View File

@ -39,7 +39,7 @@ const checkboxOptions = ref([
{ name: 'select', label: 'Accesses', selected: false },
]);
const columns = computed(() => [
{ name: 'changedModelValue' },
{ name: 'changedModelValue', orderBy: 'id' },
{ name: 'changedModel' },
{ name: 'userType', orderBy: false },
{ name: 'userFk' },

View File

@ -0,0 +1,100 @@
<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
const props = defineProps({
scrollTarget: { type: [String, Object], default: 'window' }
});
const scrollPosition = ref(0);
const showButton = ref(false);
let scrollContainer = null;
const onScroll = () => {
if (!scrollContainer) return;
scrollPosition.value =
typeof props.scrollTarget === 'object'
? scrollContainer.scrollTop
: window.scrollY;
};
watch(scrollPosition, (newValue) => {
showButton.value = newValue > 0;
});
const scrollToTop = () => {
if (scrollContainer) {
scrollContainer.scrollTo({ top: 0, behavior: 'smooth' });
}
};
const updateScrollContainer = (container) => {
if (container) {
if (scrollContainer) {
scrollContainer.removeEventListener('scroll', onScroll);
}
scrollContainer = container;
scrollContainer.addEventListener('scroll', onScroll);
onScroll();
}
};
defineExpose({
updateScrollContainer
});
const initScrollContainer = async () => {
await nextTick();
if (typeof props.scrollTarget === 'object') {
scrollContainer = props.scrollTarget;
} else {
scrollContainer = window;
}
if (!scrollContainer) return
scrollContainer.addEventListener('scroll', onScroll);
};
onMounted(() => {
initScrollContainer();
});
onUnmounted(() => {
if (scrollContainer) {
scrollContainer.removeEventListener('scroll', onScroll);
scrollContainer = null;
}
});
</script>
<template>
<QIcon
v-if="showButton"
color="primary"
name="keyboard_arrow_up"
class="scroll-to-top"
@click="scrollToTop"
>
<QTooltip>{{ $t('globals.scrollToTop') }}</QTooltip>
</QIcon>
</template>
<style scoped>
.scroll-to-top {
position: fixed;
top: 70px;
font-size: 65px;
left: 50%;
transform: translateX(-50%);
z-index: 1000;
transition: transform 0.2s ease-in-out;
}
.scroll-to-top:hover {
transform: translateX(-50%) scale(1.2);
cursor: pointer;
filter: brightness(0.8);
}
</style>

View File

@ -54,6 +54,10 @@ const $props = defineProps({
type: [Array],
default: () => [],
},
filterFn: {
type: Function,
default: null,
},
exprBuilder: {
type: Function,
default: null,
@ -62,16 +66,12 @@ const $props = defineProps({
type: Boolean,
default: true,
},
defaultFilter: {
type: Boolean,
default: true,
},
fields: {
type: Array,
default: null,
},
include: {
type: [Object, Array],
type: [Object, Array, String],
default: null,
},
where: {
@ -79,7 +79,7 @@ const $props = defineProps({
default: null,
},
sortBy: {
type: String,
type: [String, Array],
default: null,
},
limit: {
@ -152,10 +152,22 @@ const value = computed({
},
});
const arrayDataKey =
$props.dataKey ??
($props.url?.length > 0 ? $props.url : ($attrs.name ?? $attrs.label));
const arrayData = useArrayData(arrayDataKey, {
url: $props.url,
searchUrl: false,
mapKey: $attrs['map-key'],
});
const computedSortBy = computed(() => {
return $props.sortBy || $props.optionLabel + ' ASC';
});
const getVal = (val) => ($props.useLike ? { like: `%${val}%` } : val);
watch(options, (newValue) => {
setOptions(newValue);
});
@ -174,16 +186,6 @@ onMounted(() => {
if ($props.focusOnMount) setTimeout(() => vnSelectRef.value.showPopup(), 300);
});
const arrayDataKey =
$props.dataKey ??
($props.url?.length > 0 ? $props.url : ($attrs.name ?? $attrs.label));
const arrayData = useArrayData(arrayDataKey, {
url: $props.url,
searchUrl: false,
mapKey: $attrs['map-key'],
});
function findKeyInOptions() {
if (!$props.options) return;
return filter($props.modelValue, $props.options)?.length;
@ -252,43 +254,41 @@ async function fetchFilter(val) {
}
async function filterHandler(val, update) {
if (isLoading.value) return update();
if (!val && lastVal.value === val) {
lastVal.value = val;
return update();
}
lastVal.value = val;
let newOptions;
if (!$props.defaultFilter) return update();
if (
$props.url &&
($props.limit || (!$props.limit && Object.keys(myOptions.value).length === 0))
) {
newOptions = await fetchFilter(val);
} else newOptions = filter(val, myOptionsOriginal.value);
update(
() => {
if ($props.noOne && noOneText.toLowerCase().includes(val.toLowerCase()))
newOptions.unshift(noOneOpt.value);
if ($props.filterFn) update($props.filterFn(val));
else if (!val && lastVal.value === val) update();
else {
const makeRequest =
($props.url && $props.limit) ||
(!$props.limit && Object.keys(myOptions.value).length === 0);
newOptions = makeRequest
? await fetchFilter(val)
: filter(val, myOptionsOriginal.value);
myOptions.value = newOptions;
},
(ref) => {
if (val !== '' && ref.options.length > 0) {
ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true);
}
},
);
update(
() => {
if ($props.noOne && noOneText.toLowerCase().includes(val.toLowerCase()))
newOptions.unshift(noOneOpt.value);
myOptions.value = newOptions;
},
(ref) => {
if (val !== '' && ref.options.length > 0) {
ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true);
}
},
);
}
lastVal.value = val;
}
function nullishToTrue(value) {
return value ?? true;
}
const getVal = (val) => ($props.useLike ? { like: `%${val}%` } : val);
async function onScroll({ to, direction, from, index }) {
const lastIndex = myOptions.value.length - 1;

View File

@ -232,7 +232,7 @@ fr:
pt: Portugais
pt:
Send SMS: Enviar SMS
CustomerDefaultLanguage: Este cliente utiliza o <strong>{locale}</strong> como seu idioma padrão
CustomerDefaultLanguage: Este cliente utiliza o {locale} como seu idioma padrão
Language: Linguagem
Phone: Móvel
Subject: Assunto

View File

@ -4,7 +4,7 @@ import VnDiscount from 'components/common/vnDiscount.vue';
describe('VnDiscount', () => {
let vm;
beforeAll(() => {
vm = createWrapper(VnDiscount, {
props: {
@ -12,7 +12,9 @@ describe('VnDiscount', () => {
price: 100,
quantity: 2,
discount: 10,
}
mana: 10,
promise: vi.fn(),
},
}).vm;
});
@ -21,8 +23,8 @@ describe('VnDiscount', () => {
});
describe('total', () => {
it('should calculate total correctly', () => {
it('should calculate total correctly', () => {
expect(vm.total).toBe(180);
});
});
});
});

View File

@ -41,10 +41,12 @@ describe('VnDms', () => {
companyFk: 2,
dmsTypeFk: 3,
description: 'This is a test description',
files: {
name: 'example.txt',
content: new Blob(['file content'], { type: 'text/plain' }),
},
files: [
{
name: 'example.txt',
content: new Blob(['file content'], { type: 'text/plain' }),
},
],
};
const expectedBody = {
@ -83,7 +85,7 @@ describe('VnDms', () => {
it('should map DMS data correctly and add file to FormData', () => {
const [formData, params] = vm.mapperDms(data);
expect(formData.get('example.txt')).toBe(data.files);
expect([formData.get('example.txt')]).toStrictEqual(data.files);
expect(expectedBody).toEqual(params.params);
});

View File

@ -2,7 +2,6 @@ import { createWrapper } from 'app/test/vitest/helper';
import { vi, describe, expect, it } from 'vitest';
import VnInput from 'src/components/common/VnInput.vue';
describe('VnInput', () => {
let vm;
let wrapper;
@ -11,26 +10,28 @@ describe('VnInput', () => {
function generateWrapper(value, isOutlined, emptyToNull, insertable) {
wrapper = createWrapper(VnInput, {
props: {
modelValue: value,
isOutlined, emptyToNull, insertable,
maxlength: 101
modelValue: value,
isOutlined,
emptyToNull,
insertable,
maxlength: 101,
},
attrs: {
label: 'test',
required: true,
maxlength: 101,
maxLength: 10,
'max-length':20
'max-length': 20,
},
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
input = wrapper.find('[data-cy="test_input"]');
};
}
describe('value', () => {
it('should emit update:modelValue when value changes', async () => {
generateWrapper('12345', false, false, true)
generateWrapper('12345', false, false, true);
await input.setValue('123');
expect(wrapper.emitted('update:modelValue')).toBeTruthy();
expect(wrapper.emitted('update:modelValue')[0]).toEqual(['123']);
@ -46,37 +47,36 @@ describe('VnInput', () => {
describe('styleAttrs', () => {
it('should return empty styleAttrs when isOutlined is false', async () => {
generateWrapper('123', false, false, false);
expect(vm.styleAttrs).toEqual({});
expect(vm.styleAttrs).toEqual({});
});
it('should set styleAttrs when isOutlined is true', async () => {
it('should set styleAttrs when isOutlined is true', async () => {
generateWrapper('123', true, false, false);
expect(vm.styleAttrs.outlined).toBe(true);
});
});
describe('handleKeydown', () => {
describe('handleKeydown', () => {
it('should do nothing when "Backspace" key is pressed', async () => {
generateWrapper('12345', false, false, true);
await input.trigger('keydown', { key: 'Backspace' });
expect(wrapper.emitted('update:modelValue')).toBeUndefined();
const spyhandler = vi.spyOn(vm, 'handleInsertMode');
expect(spyhandler).not.toHaveBeenCalled();
});
/*
TODO: #8399 REDMINE
*/
it.skip('handleKeydown respects insertable behavior', async () => {
const expectedValue = '12345';
generateWrapper('1234', false, false, true);
vm.focus()
vm.focus();
await input.trigger('keydown', { key: '5' });
await vm.$nextTick();
expect(wrapper.emitted('update:modelValue')).toBeTruthy();
expect(wrapper.emitted('update:modelValue')[0]).toEqual([expectedValue ]);
expect(vm.value).toBe( expectedValue);
expect(wrapper.emitted('update:modelValue')[0]).toEqual([expectedValue]);
expect(vm.value).toBe(expectedValue);
});
});
@ -86,6 +86,6 @@ describe('VnInput', () => {
const focusSpy = vi.spyOn(input.element, 'focus');
vm.focus();
expect(focusSpy).toHaveBeenCalled();
});
});
});
});

View File

@ -0,0 +1,81 @@
import { createWrapper } from 'app/test/vitest/helper.js';
import { describe, it, expect, beforeAll } from 'vitest';
import VnInputDateTime from 'components/common/VnInputDateTime.vue';
import vnDateBoot from 'src/boot/vnDate';
let vm;
let wrapper;
beforeAll(() => {
// Initialize the vnDate boot
vnDateBoot();
});
function generateWrapper(date, outlined, showEvent) {
wrapper = createWrapper(VnInputDateTime, {
props: {
modelValue: date,
isOutlined: outlined,
showEvent: showEvent,
},
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
}
describe('VnInputDateTime', () => {
describe('selectedDate', () => {
it('formats a valid datetime correctly', async () => {
generateWrapper('2023-12-25T10:30:00', false, true);
await vm.$nextTick();
expect(vm.selectedDate).toBe('25-12-2023 10:30');
});
it('handles null date value', async () => {
generateWrapper(null, false, true);
await vm.$nextTick();
expect(vm.selectedDate).not.toBe(null);
});
it('updates the model value when a new datetime is set', async () => {
vm.selectedDate = '31-12-2023 15:45';
await vm.$nextTick();
expect(wrapper.emitted()['update:modelValue']).toBeTruthy();
});
});
describe('styleAttrs', () => {
it('should return empty styleAttrs when isOutlined is false', async () => {
generateWrapper('2023-12-25T10:30:00', false, true);
await vm.$nextTick();
expect(vm.styleAttrs).toEqual({});
});
it('should set styleAttrs when isOutlined is true', async () => {
generateWrapper('2023-12-25T10:30:00', true, true);
await vm.$nextTick();
expect(vm.styleAttrs).toEqual({
dense: true,
outlined: true,
rounded: true,
});
});
});
describe('component rendering', () => {
it('should render date and time icons', async () => {
generateWrapper('2023-12-25T10:30:00', false, true);
await vm.$nextTick();
const icons = wrapper.findAllComponents({ name: 'QIcon' });
expect(icons.length).toBe(2);
expect(icons[0].props('name')).toBe('today');
expect(icons[1].props('name')).toBe('access_time');
});
it('should render popup proxies for date and time', async () => {
generateWrapper('2023-12-25T10:30:00', false, true);
await vm.$nextTick();
const popups = wrapper.findAllComponents({ name: 'QPopupProxy' });
expect(popups.length).toBe(2);
});
});
});

View File

@ -90,8 +90,10 @@ describe('VnLog', () => {
vm = createWrapper(VnLog, {
global: {
stubs: [],
mocks: {},
stubs: ['FetchData', 'vue-i18n'],
mocks: {
fetch: vi.fn(),
},
},
propsData: {
model: 'Claim',

View File

@ -26,7 +26,7 @@ describe('VnNotes', () => {
) {
vi.spyOn(axios, 'get').mockResolvedValue({ data: [] });
wrapper = createWrapper(VnNotes, {
propsData: options,
propsData: { ...defaultOptions, ...options },
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;

View File

@ -44,7 +44,8 @@ onBeforeMount(async () => {
});
// It enables to load data only once if the module is the same as the dataKey
if (!isSameDataKey.value || !route.params.id) await getData();
if (!isSameDataKey.value || !route.params.id || $props.id !== route.params.id)
await getData();
watch(
() => [$props.url, $props.filter],
async () => {
@ -58,7 +59,8 @@ async function getData() {
store.filter = $props.filter ?? {};
isLoading.value = true;
try {
const { data } = await arrayData.fetch({ append: false, updateRouter: false });
await arrayData.fetch({ append: false, updateRouter: false });
const { data } = store;
state.set($props.dataKey, data);
emit('onFetch', data);
} finally {

View File

@ -6,6 +6,7 @@ import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useRoute, useRouter } from 'vue-router';
import { useClipboard } from 'src/composables/useClipboard';
import VnMoreOptions from './VnMoreOptions.vue';
import { getValueFromPath } from 'src/composables/getValueFromPath';
const entity = defineModel({ type: Object, default: null });
const $props = defineProps({
@ -56,18 +57,6 @@ const routeName = computed(() => {
return `${routeName}Summary`;
});
function getValueFromPath(path) {
if (!path) return;
const keys = path.toString().split('.');
let current = entity.value;
for (const key of keys) {
if (current[key] === undefined) return undefined;
else current = current[key];
}
return current;
}
function copyIdText(id) {
copyText(id, {
component: {
@ -170,10 +159,10 @@ const toModule = computed(() => {
<div class="title">
<span
v-if="title"
:title="getValueFromPath(title)"
:title="getValueFromPath(entity, title)"
:data-cy="`${$attrs['data-cy'] ?? 'vnDescriptor'}_title`"
>
{{ getValueFromPath(title) ?? title }}
{{ getValueFromPath(entity, title) ?? title }}
</span>
<slot v-else name="description" :entity="entity">
<span
@ -189,7 +178,7 @@ const toModule = computed(() => {
class="subtitle"
:data-cy="`${$attrs['data-cy'] ?? 'vnDescriptor'}_subtitle`"
>
#{{ getValueFromPath(subtitle) ?? entity.id }}
#{{ getValueFromPath(entity, subtitle) ?? entity.id }}
</QItemLabel>
<QBtn
round

View File

@ -212,6 +212,7 @@ const getLocale = (label) => {
color="primary"
style="position: fixed; z-index: 1; right: 0; bottom: 0"
icon="search"
data-cy="vnFilterPanel_search"
@click="search()"
>
<QTooltip bottom anchor="bottom right">
@ -229,6 +230,7 @@ const getLocale = (label) => {
<QItemSection top side>
<QBtn
@click="clearFilters"
data-cy="clearFilters"
color="primary"
dense
flat
@ -292,6 +294,7 @@ const getLocale = (label) => {
</QList>
</QForm>
<QInnerLoading
data-cy="filterPanel-spinner"
:label="t('globals.pleaseWait')"
:showing="isLoading"
color="primary"

View File

@ -6,6 +6,7 @@ import { computed } from 'vue';
const $props = defineProps({
label: { type: String, default: null },
tooltip: { type: String, default: null },
value: {
type: [String, Boolean, Number],
default: null,
@ -40,7 +41,10 @@ const val = computed(() => $props.value);
<template v-else>
<div v-if="label || $slots.label" class="label">
<slot name="label">
<span style="color: var(--vn-label-color)">{{ label }}</span>
<QTooltip v-if="tooltip">{{ tooltip }}</QTooltip>
<span style="color: var(--vn-label-color)">
{{ label }}
</span>
</slot>
</div>
<div class="value" v-if="value || $slots.value">

View File

@ -2,7 +2,9 @@
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useArrayData } from 'composables/useArrayData';
import { useAttrs } from 'vue';
const attrs = useAttrs();
const { t } = useI18n();
const props = defineProps({
@ -67,7 +69,7 @@ const props = defineProps({
default: null,
},
searchUrl: {
type: String,
type: [String, Boolean],
default: null,
},
disableInfiniteScroll: {
@ -75,7 +77,7 @@ const props = defineProps({
default: false,
},
mapKey: {
type: String,
type: [String, Boolean],
default: '',
},
keyData: {
@ -220,7 +222,7 @@ defineExpose({
</script>
<template>
<div class="full-width">
<div class="full-width" v-bind="attrs">
<div
v-if="!store.data && !store.data?.length && !isLoading"
class="info-row q-pa-md text-center"

View File

@ -46,7 +46,7 @@ const props = defineProps({
default: null,
},
order: {
type: String,
type: [String, Array],
default: '',
},
limit: {

View File

@ -1,60 +0,0 @@
<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const props = defineProps({
usesMana: {
type: Boolean,
required: true,
},
manaCode: {
type: String,
required: true,
},
manaVal: {
type: String,
default: 'mana',
},
manaLabel: {
type: String,
default: 'Promotion mana',
},
manaClaimVal: {
type: String,
default: 'manaClaim',
},
claimLabel: {
type: String,
default: 'Claim mana',
},
});
const manaCode = ref(props.manaCode);
</script>
<template>
<div class="column q-gutter-y-sm q-mt-sm">
<QRadio
v-model="manaCode"
dense
:val="manaVal"
:label="t(manaLabel)"
:dark="true"
class="q-mb-sm"
/>
<QRadio
v-model="manaCode"
dense
:val="manaClaimVal"
:label="t(claimLabel)"
:dark="true"
class="q-mb-sm"
/>
</div>
</template>
<i18n>
es:
Promotion mana: Maná promoción
Claim mana: Maná reclamación
</i18n>

View File

@ -23,10 +23,15 @@ describe('CardSummary', () => {
beforeEach(() => {
wrapper = createWrapper(CardSummary, {
global: {
mocks: {
validate: vi.fn(),
},
},
propsData: {
dataKey: 'cardSummaryKey',
url: 'cardSummaryUrl',
filter: 'cardFilter',
filter: { key: 'cardFilter' },
},
});
vm = wrapper.vm;
@ -50,7 +55,7 @@ describe('CardSummary', () => {
it('should set correct props to the store', () => {
expect(vm.store.url).toEqual('cardSummaryUrl');
expect(vm.store.filter).toEqual('cardFilter');
expect(vm.store.filter).toEqual({ key: 'cardFilter' });
});
it('should respond to prop changes and refetch data', async () => {

View File

@ -7,7 +7,7 @@ describe('VnSearchbar', () => {
let wrapper;
let applyFilterSpy;
const searchText = 'Bolas de madera';
const userParams = {staticKey: 'staticValue'};
const userParams = { staticKey: 'staticValue' };
beforeEach(async () => {
wrapper = createWrapper(VnSearchbar, {
@ -23,8 +23,9 @@ describe('VnSearchbar', () => {
vm.searchText = searchText;
vm.arrayData.store.userParams = userParams;
applyFilterSpy = vi.spyOn(vm.arrayData, 'applyFilter').mockImplementation(() => {});
applyFilterSpy = vi
.spyOn(vm.arrayData, 'applyFilter')
.mockImplementation(() => {});
});
afterEach(() => {
@ -32,7 +33,9 @@ describe('VnSearchbar', () => {
});
it('search resets pagination and applies filter', async () => {
const resetPaginationSpy = vi.spyOn(vm.arrayData, 'resetPagination').mockImplementation(() => {});
const resetPaginationSpy = vi
.spyOn(vm.arrayData, 'resetPagination')
.mockImplementation(() => {});
await vm.search();
expect(resetPaginationSpy).toHaveBeenCalled();
@ -48,7 +51,7 @@ describe('VnSearchbar', () => {
expect(applyFilterSpy).toHaveBeenCalledWith({
params: { staticKey: 'staticValue', search: searchText },
filter: {skip: 0},
filter: { skip: 0 },
});
});
@ -68,4 +71,4 @@ describe('VnSearchbar', () => {
});
expect(vm.to.query.searchParam).toBe(expectedQuery);
});
});
});

View File

@ -1,5 +1,4 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import VnSms from 'src/components/ui/VnSms.vue';
@ -12,6 +11,9 @@ describe('VnSms', () => {
stubs: ['VnPaginate'],
mocks: {},
},
propsData: {
url: 'SmsUrl',
},
}).vm;
});

View File

@ -4,6 +4,8 @@ import { useArrayData } from 'composables/useArrayData';
import { useRouter } from 'vue-router';
import * as vueRouter from 'vue-router';
import { setActivePinia, createPinia } from 'pinia';
import { defineComponent, h } from 'vue';
import { mount } from '@vue/test-utils';
describe('useArrayData', () => {
const filter = '{"limit":20,"skip":0}';
@ -43,7 +45,7 @@ describe('useArrayData', () => {
it('should fetch and replace url with new params', async () => {
vi.spyOn(axios, 'get').mockResolvedValueOnce({ data: [] });
const arrayData = useArrayData('ArrayData', {
const arrayData = mountArrayData('ArrayData', {
url: 'mockUrl',
searchUrl: 'params',
});
@ -72,7 +74,7 @@ describe('useArrayData', () => {
data: [{ id: 1 }],
});
const arrayData = useArrayData('ArrayData', {
const arrayData = mountArrayData('ArrayData', {
url: 'mockUrl',
navigate: {},
});
@ -94,7 +96,7 @@ describe('useArrayData', () => {
],
});
const arrayData = useArrayData('ArrayData', {
const arrayData = mountArrayData('ArrayData', {
url: 'mockUrl',
oneRecord: true,
});
@ -107,3 +109,17 @@ describe('useArrayData', () => {
});
});
});
function mountArrayData(...args) {
let arrayData;
const TestComponent = defineComponent({
setup() {
arrayData = useArrayData(...args);
return () => h('div');
},
});
const asd = mount(TestComponent);
return arrayData;
}

View File

@ -64,88 +64,84 @@ describe('session', () => {
});
});
describe(
'login',
() => {
const expectedUser = {
id: 999,
name: `T'Challa`,
nickname: 'Black Panther',
lang: 'en',
userConfig: {
darkMode: false,
describe('login', () => {
const expectedUser = {
id: 999,
name: `T'Challa`,
nickname: 'Black Panther',
lang: 'en',
userConfig: {
darkMode: false,
},
worker: { department: { departmentFk: 155 } },
};
const rolesData = [
{
role: {
name: 'salesPerson',
},
worker: { department: { departmentFk: 155 } },
};
const rolesData = [
{
role: {
name: 'salesPerson',
},
},
{
role: {
name: 'admin',
},
{
role: {
name: 'admin',
},
},
];
beforeEach(() => {
vi.spyOn(axios, 'get').mockImplementation((url) => {
if (url === 'VnUsers/acls') return Promise.resolve({ data: [] });
return Promise.resolve({
data: { roles: rolesData, user: expectedUser },
});
},
];
beforeEach(() => {
vi.spyOn(axios, 'get').mockImplementation((url) => {
if (url === 'VnUsers/acls') return Promise.resolve({ data: [] });
return Promise.resolve({
data: { roles: rolesData, user: expectedUser },
});
});
});
it('should fetch the user roles and then set token in the sessionStorage', async () => {
const expectedRoles = ['salesPerson', 'admin'];
const expectedToken = 'mySessionToken';
const expectedTokenMultimedia = 'mySessionTokenMultimedia';
const keepLogin = false;
it('should fetch the user roles and then set token in the sessionStorage', async () => {
const expectedRoles = ['salesPerson', 'admin'];
const expectedToken = 'mySessionToken';
const expectedTokenMultimedia = 'mySessionTokenMultimedia';
const keepLogin = false;
await session.login({
token: expectedToken,
tokenMultimedia: expectedTokenMultimedia,
keepLogin,
});
const roles = state.getRoles();
const localToken = localStorage.getItem('token');
const sessionToken = sessionStorage.getItem('token');
expect(roles.value).toEqual(expectedRoles);
expect(localToken).toBeNull();
expect(sessionToken).toEqual(expectedToken);
await session.destroy(); // this clears token and user for any other test
await session.login({
token: expectedToken,
tokenMultimedia: expectedTokenMultimedia,
keepLogin,
});
it('should fetch the user roles and then set token in the localStorage', async () => {
const expectedRoles = ['salesPerson', 'admin'];
const expectedToken = 'myLocalToken';
const expectedTokenMultimedia = 'myLocalTokenMultimedia';
const keepLogin = true;
const roles = state.getRoles();
const localToken = localStorage.getItem('token');
const sessionToken = sessionStorage.getItem('token');
await session.login({
token: expectedToken,
tokenMultimedia: expectedTokenMultimedia,
keepLogin,
});
expect(roles.value).toEqual(expectedRoles);
expect(localToken).toBeNull();
expect(sessionToken).toEqual(expectedToken);
const roles = state.getRoles();
const localToken = localStorage.getItem('token');
const sessionToken = sessionStorage.getItem('token');
await session.destroy(); // this clears token and user for any other test
});
expect(roles.value).toEqual(expectedRoles);
expect(localToken).toEqual(expectedToken);
expect(sessionToken).toBeNull();
it('should fetch the user roles and then set token in the localStorage', async () => {
const expectedRoles = ['salesPerson', 'admin'];
const expectedToken = 'myLocalToken';
const expectedTokenMultimedia = 'myLocalTokenMultimedia';
const keepLogin = true;
await session.destroy(); // this clears token and user for any other test
await session.login({
token: expectedToken,
tokenMultimedia: expectedTokenMultimedia,
keepLogin,
});
},
{},
);
const roles = state.getRoles();
const localToken = localStorage.getItem('token');
const sessionToken = sessionStorage.getItem('token');
expect(roles.value).toEqual(expectedRoles);
expect(localToken).toEqual(expectedToken);
expect(sessionToken).toBeNull();
await session.destroy(); // this clears token and user for any other test
});
});
describe('RenewToken', () => {
const expectedToken = 'myToken';

View File

@ -0,0 +1,11 @@
export function getValueFromPath(root, path) {
if (!root || !path) return;
const keys = path.toString().split('.');
let current = root;
for (const key of keys) {
if (current[key] === undefined) return undefined;
else current = current[key];
}
return current;
}

View File

@ -18,6 +18,7 @@ $positive: #c8e484;
$negative: #fb5252;
$info: #84d0e2;
$warning: #f4b974;
$neutral: #b0b0b0;
// Pendiente de cuadrar con la base de datos
$success: $positive;
$alert: $negative;
@ -51,3 +52,6 @@ $width-xl: 1600px;
.bg-alert {
background-color: $negative;
}
.bg-neutral {
background-color: $neutral;
}

View File

@ -6,6 +6,7 @@ globals:
quantity: Quantity
entity: Entity
preview: Preview
scrollToTop: Go up
user: User
details: Details
collapseMenu: Collapse lateral menu
@ -19,6 +20,7 @@ globals:
logOut: Log out
date: Date
dataSaved: Data saved
openDetail: Open detail
dataDeleted: Data deleted
delete: Delete
search: Search

View File

@ -6,6 +6,7 @@ globals:
quantity: Cantidad
entity: Entidad
preview: Vista previa
scrollToTop: Ir arriba
user: Usuario
details: Detalles
collapseMenu: Contraer menú lateral
@ -20,10 +21,11 @@ globals:
date: Fecha
dataSaved: Datos guardados
dataDeleted: Datos eliminados
dataCreated: Datos creados
openDetail: Ver detalle
delete: Eliminar
search: Buscar
changes: Cambios
dataCreated: Datos creados
add: Añadir
create: Crear
edit: Modificar

View File

@ -28,14 +28,8 @@ const entityId = computed(() => {
return $props.id || route.params.id;
});
const STATE_COLOR = {
pending: 'warning',
incomplete: 'info',
resolved: 'positive',
canceled: 'negative',
};
function stateColor(code) {
return STATE_COLOR[code];
function stateColor(entity) {
return entity?.claimState?.classColor;
}
onMounted(async () => {
@ -57,9 +51,8 @@ onMounted(async () => {
<VnLv v-if="entity.claimState" :label="t('claim.state')">
<template #value>
<QBadge
:color="stateColor(entity.claimState.code)"
text-color="black"
dense
:color="stateColor(entity)"
style="color: var(--vn-black-text-color)"
>
{{ entity.claimState.description }}
</QBadge>

View File

@ -23,7 +23,7 @@ const claimDms = ref([
]);
const client = ref({});
const inputFile = ref();
const files = ref({});
const files = ref([]);
const spinnerRef = ref();
const claimDmsRef = ref();
const dmsType = ref({});
@ -255,9 +255,8 @@ function onDrag() {
icon="add"
color="primary"
>
<QInput
<QFile
ref="inputFile"
type="file"
style="display: none"
multiple
v-model="files"

View File

@ -108,15 +108,9 @@ const markerLabels = [
{ value: 5, label: t('claim.person') },
];
const STATE_COLOR = {
pending: 'warning',
incomplete: 'info',
resolved: 'positive',
canceled: 'negative',
};
function stateColor(code) {
return STATE_COLOR[code];
const claimState = claimStates.value.find((state) => state.code === code);
return claimState?.classColor;
}
const developmentColumns = ref([
@ -188,7 +182,7 @@ function claimUrl(section) {
<template>
<FetchData
url="ClaimStates"
:filter="{ fields: ['id', 'description'] }"
:filter="{ fields: ['id', 'description', 'code', 'classColor'] }"
@on-fetch="(data) => (claimStates = data)"
auto-load
/>
@ -346,17 +340,18 @@ function claimUrl(section) {
<template #body="props">
<QTr :props="props">
<QTd v-for="col in props.cols" :key="col.name" :props="props">
<span v-if="col.name != 'description'">{{
t(col.value)
}}</span>
<span class="link" v-if="col.name === 'description'">{{
t(col.value)
}}</span>
<ItemDescriptorProxy
v-if="col.name == 'description'"
:id="props.row.sale.itemFk"
:sale-fk="props.row.saleFk"
></ItemDescriptorProxy>
<template v-if="col.name === 'description'">
<span class="link">{{
dashIfEmpty(col.field(props.row))
}}</span>
<ItemDescriptorProxy
:id="props.row.sale.itemFk"
:sale-fk="props.row.saleFk"
/>
</template>
<template v-else>
{{ dashIfEmpty(col.field(props.row)) }}
</template>
</QTd>
</QTr>
</template>

View File

@ -52,7 +52,7 @@ describe('ClaimLines', () => {
expectedData,
{
signal: canceller.signal,
}
},
);
});
});
@ -69,7 +69,7 @@ describe('ClaimLines', () => {
expect.objectContaining({
message: 'Discount updated',
type: 'positive',
})
}),
);
});
});

View File

@ -14,6 +14,9 @@ describe('ClaimLinesImport', () => {
fetch: vi.fn(),
},
},
propsData: {
ticketId: 1,
},
}).vm;
});
@ -40,7 +43,7 @@ describe('ClaimLinesImport', () => {
expect.objectContaining({
message: 'Lines added to claim',
type: 'positive',
})
}),
);
expect(vm.canceller).toEqual(null);
});

View File

@ -41,10 +41,10 @@ describe('ClaimPhoto', () => {
await vm.deleteDms({ index: 0 });
expect(axios.post).toHaveBeenCalledWith(
`ClaimDms/${claimMock.claimDms[0].dmsFk}/removeFile`
`ClaimDms/${claimMock.claimDms[0].dmsFk}/removeFile`,
);
expect(vm.quasar.notify).toHaveBeenCalledWith(
expect.objectContaining({ type: 'positive' })
expect.objectContaining({ type: 'positive' }),
);
});
});
@ -63,7 +63,7 @@ describe('ClaimPhoto', () => {
data: { index: 1 },
promise: vm.deleteDms,
},
})
}),
);
});
});
@ -102,10 +102,10 @@ describe('ClaimPhoto', () => {
new FormData(),
expect.objectContaining({
params: expect.objectContaining({ hasFile: false }),
})
}),
);
expect(vm.quasar.notify).toHaveBeenCalledWith(
expect.objectContaining({ type: 'positive' })
expect.objectContaining({ type: 'positive' }),
);
expect(vm.claimDmsRef.fetch).toHaveBeenCalledOnce();

View File

@ -101,7 +101,10 @@ const columns = computed(() => [
name: 'stateCode',
chip: {
condition: () => true,
color: ({ stateCode }) => STATE_COLOR[stateCode] ?? 'bg-grey',
color: ({ stateCode }) => {
const state = states.value?.find(({ code }) => code === stateCode);
return `bg-${state.classColor}`;
},
},
columnFilter: {
name: 'claimStateFk',
@ -131,12 +134,6 @@ const columns = computed(() => [
],
},
]);
const STATE_COLOR = {
pending: 'bg-warning',
loses: 'bg-negative',
resolved: 'bg-positive',
};
</script>
<template>

View File

@ -131,6 +131,7 @@ const columns = computed(() => [
name: 'isConciliate',
label: t('Conciliated'),
cardVisible: true,
component: 'checkbox',
},
{
align: 'left',

View File

@ -18,7 +18,7 @@ import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
const arrayData = useArrayData('Client');
const arrayData = useArrayData('Customer');
const { t } = useI18n();
const route = useRoute();
const campaignList = ref();
@ -260,7 +260,7 @@ const updateDateParams = (value, params) => {
:label="t('globals.campaign')"
:filled="true"
class="q-px-sm q-pt-none fit"
:option-label="(opt) => t(opt.code)"
:option-label="(opt) => t(opt.code ?? '')"
:fields="['id', 'code', 'dated', 'scopeDays']"
@update:model-value="(data) => updateDateParams(data, params)"
dense

View File

@ -39,7 +39,7 @@ const route = useRoute();
const { t } = useI18n();
const entityId = computed(() => {
return $props.id || route.params.id;
return Number($props.id || route.params.id);
});
const data = ref(useCardDescription());

View File

@ -11,7 +11,7 @@ const $props = defineProps({
</script>
<template>
<QPopupProxy>
<QPopupProxy data-cy="CustomerDescriptor">
<CustomerDescriptor v-if="$props.id" :id="$props.id" :summary="CustomerSummary" />
</QPopupProxy>
</template>

View File

@ -86,7 +86,7 @@ async function acceptPropagate({ isEqualizated }) {
:required="true"
:rules="validate('client.socialName')"
clearable
uppercase="true"
:uppercase="true"
v-model="data.socialName"
>
<template #append>

View File

@ -4,7 +4,6 @@ import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { QBtn, useQuasar } from 'quasar';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import { toDateTimeFormat } from 'src/filters/date';
import VnTable from 'src/components/VnTable/VnTable.vue';
@ -34,7 +33,7 @@ const columns = computed(() => [
},
{
align: 'left',
format: (row) => row.type.description,
format: (row) => row?.type?.description,
label: t('Description'),
name: 'description',
},
@ -74,12 +73,11 @@ const tableRef = ref();
<template>
<VnTable
ref="tableRef"
data-key="ClientSamples"
data-key="CustomerSamples"
auto-load
:filter="filter"
:user-filter="filter"
url="ClientSamples"
:columns="columns"
:pagination="{ rowsPerPage: 12 }"
:disable-option="{ card: true }"
:right-search="false"
:rows="rows"

View File

@ -25,7 +25,7 @@ const $props = defineProps({
},
});
const entityId = computed(() => $props.id || route.params.id);
const entityId = computed(() => Number($props.id || route.params.id));
const customer = computed(() => summary.value.entity);
const summary = ref();
const defaulterAmount = computed(() => customer.value.defaulters[0]?.amount);
@ -185,7 +185,7 @@ const sumRisk = ({ clientRisks }) => {
/>
<VnLv
:label="t('customer.summary.payMethod')"
:value="entity.payMethod.name"
:value="entity.payMethod?.name"
/>
<VnLv :label="t('customer.summary.bankAccount')" :value="entity.iban" />
<VnLv :label="t('customer.summary.dueDay')" :value="entity.dueDay" />
@ -208,7 +208,8 @@ const sumRisk = ({ clientRisks }) => {
:text="t('customer.summary.consignee')"
/>
<VnLv
:label="t('customer.summary.addressName')"
:tooltip="t('customer.summary.addressName')"
:label="t('customer.summary.addressNameAbbr')"
:value="entity.defaultAddress.nickname"
/>
<VnLv
@ -252,7 +253,8 @@ const sumRisk = ({ clientRisks }) => {
/>
<VnLv
v-if="entity.claimsRatio"
:label="t('customer.summary.priceIncreasingRate')"
:tooltip="t('customer.summary.priceIncreasingRate')"
:label="t('customer.summary.priceIncreasingRateAbbr')"
:value="toPercentage(priceIncreasingRate)"
/>
<VnLv
@ -261,7 +263,8 @@ const sumRisk = ({ clientRisks }) => {
/>
<VnLv
v-if="entity.claimsRatio"
:label="t('customer.summary.claimRate')"
:label="t('customer.summary.claimRateAbbr')"
:tooltip="t('customer.summary.claimRate')"
:value="toPercentage(claimRate)"
/>
</QCard>
@ -318,8 +321,9 @@ const sumRisk = ({ clientRisks }) => {
/>
<VnLv
:label="t('customer.summary.recommendCredit')"
:value="entity.recommendedCredit"
:label="t('customer.summary.recommendCreditAbbr')"
:tooltip="t('customer.summary.recommendCredit')"
:value="toCurrency(entity.recommendedCredit)"
/>
</QCard>
<QCard class="vn-max">

View File

@ -72,7 +72,7 @@ const exprBuilder = (param, value) => {
option-value="id"
option-label="name"
url="Departments"
no-one="true"
:no-one="true"
/>
</QItemSection>
</QItem>

View File

@ -111,14 +111,11 @@ const columns = computed(() => [
component: 'number',
},
columnField: {
component: null,
after: {
component: markRaw(VnLinkPhone),
attrs: ({ model }) => {
return {
'phone-number': model,
};
},
component: markRaw(VnLinkPhone),
attrs: ({ model }) => {
return {
'phone-number': model,
};
},
},
},

View File

@ -32,7 +32,7 @@ describe('CustomerPayments', () => {
expect.objectContaining({
message: 'Payment confirmed',
type: 'positive',
})
}),
);
});
});

View File

@ -41,7 +41,6 @@ const sampleType = ref({ hasPreview: false });
const initialData = reactive({});
const entityId = computed(() => route.params.id);
const customer = computed(() => useArrayData('Customer').store?.data);
const filterEmailUsers = { where: { userFk: user.value.id } };
const filterClientsAddresses = {
include: [
{ relation: 'province', scope: { fields: ['name'] } },
@ -73,7 +72,7 @@ onBeforeMount(async () => {
const setEmailUser = (data) => {
optionsEmailUsers.value = data;
initialData.replyTo = data[0]?.email;
initialData.replyTo = data[0]?.notificationEmail;
};
const setClientsAddresses = (data) => {
@ -182,10 +181,12 @@ const toCustomerSamples = () => {
<template>
<FetchData
:filter="filterEmailUsers"
:filter="{
where: { id: customer.departmentFk },
}"
@on-fetch="setEmailUser"
auto-load
url="EmailUsers"
url="Departments"
/>
<FetchData
:filter="filterClientsAddresses"

View File

@ -42,14 +42,17 @@ customer:
hasCoreVnl: Has core VNL
hasB2BVnl: Has B2B VNL
addressName: Address name
addressNameAbbr: A. Name
addressCity: City
username: Username
webAccess: Web access
totalGreuge: Total greuge
mana: Mana
priceIncreasingRate: Price increasing rate
priceIncreasingRateAbbr: Price inc. rate
averageInvoiced: Average invoiced
claimRate: Claming rate
claimRateAbbr: Claim. rate
payMethodFk: Billing data
risk: Risk
maximumRisk: Solunion's maximum risk
@ -68,6 +71,7 @@ customer:
descriptorInfo: Invoices minus payments plus orders not yet
rating: Rating
recommendCredit: Recommended credit
recommendCreditAbbr: Rec. credit
goToLines: Go to lines
basicData:
socialName: Fiscal name

View File

@ -42,14 +42,17 @@ customer:
hasCoreVnl: Recibido core VNL
hasB2BVnl: Recibido B2B VNL
addressName: Nombre de la dirección
addressNameAbbr: N. Dirección
addressCity: Ciudad
username: Usuario
webAccess: Acceso web
totalGreuge: Greuge total
mana: Maná
priceIncreasingRate: Ratio de incremento de precio
priceIncreasingRateAbbr: R. Inc. Precio
averageInvoiced: Facturación media
claimRate: Ratio de reclamaciones
claimRateAbbr: R. Reclamaciones
maximumRisk: Riesgo máximo asumido por Solunion
payMethodFk: Forma de pago
risk: Riesgo
@ -68,6 +71,7 @@ customer:
descriptorInfo: Facturas menos recibos mas pedidos sin facturar
rating: Clasificación
recommendCredit: Crédito recomendado
recommendCreditAbbr: Cr. Recomendado
goToLines: Ir a líneas
basicData:
socialName: Nombre fiscal

View File

@ -5,7 +5,7 @@ import InvoiceInSummary from './InvoiceInSummary.vue';
const $props = defineProps({
id: {
type: Number,
required: true,
default: null,
},
});
</script>

View File

@ -6,10 +6,12 @@ import { toCurrency } from 'filters/index';
import VnStockValueDisplay from 'src/components/ui/VnStockValueDisplay.vue';
import VnTable from 'src/components/VnTable/VnTable.vue';
import axios from 'axios';
import notifyResults from 'src/utils/notifyResults';
import { displayResults } from 'src/pages/Ticket/Negative/composables/notifyResults';
import FetchData from 'components/FetchData.vue';
import { useState } from 'src/composables/useState';
const MATCH = 'match';
const { notifyResults } = displayResults();
const { t } = useI18n();
const $props = defineProps({
@ -18,14 +20,20 @@ const $props = defineProps({
required: true,
default: () => {},
},
filter: {
type: Object,
required: true,
default: () => {},
},
replaceAction: {
type: Boolean,
required: false,
required: true,
default: false,
},
sales: {
type: Array,
required: false,
required: true,
default: () => [],
},
});
@ -36,6 +44,8 @@ const proposalTableRef = ref(null);
const sale = computed(() => $props.sales[0]);
const saleFk = computed(() => sale.value.saleFk);
const filter = computed(() => ({
where: $props.filter,
itemFk: $props.itemLack.itemFk,
sales: saleFk.value,
}));
@ -228,11 +238,15 @@ async function handleTicketConfig(data) {
url="TicketConfigs"
:filter="{ fields: ['lackAlertPrice'] }"
@on-fetch="handleTicketConfig"
auto-load
></FetchData>
<QInnerLoading
:showing="isLoading"
:label="t && t('globals.pleaseWait')"
color="primary"
/>
<VnTable
v-if="ticketConfig"
v-if="!isLoading"
auto-load
data-cy="proposalTable"
ref="proposalTableRef"

View File

@ -1,13 +1,17 @@
<script setup>
import ItemProposal from './ItemProposal.vue';
import { useDialogPluginComponent } from 'quasar';
const $props = defineProps({
itemLack: {
type: Object,
required: true,
default: () => {},
},
filter: {
type: Object,
required: true,
default: () => {},
},
replaceAction: {
type: Boolean,
required: false,
@ -31,7 +35,7 @@ defineExpose({ show: () => dialogRef.value.show(), hide: () => dialogRef.value.h
<QDialog ref="dialogRef" transition-show="scale" transition-hide="scale">
<QCard class="dialog-width">
<QCardSection class="row items-center q-pb-none">
<span class="text-h6 text-grey">{{ $t('Item proposal') }}</span>
<span class="text-h6 text-grey">{{ $t('itemProposal') }}</span>
<QSpace />
<QBtn icon="close" flat round dense v-close-popup />
</QCardSection>

View File

@ -8,14 +8,14 @@ import VnRow from 'src/components/ui/VnRow.vue';
class="q-pa-md"
:style="{ 'flex-direction': $q.screen.lt.lg ? 'column' : 'row', gap: '0px' }"
>
<div style="flex: 0.3">
<div style="flex: 0.3" data-cy="clientsOnWebsite">
<span
class="q-ml-md text-body1"
v-text="$t('salesMonitor.clientsOnWebsite')"
/>
<SalesClientTable />
</div>
<div style="flex: 0.7">
<div style="flex: 0.7" data-cy="recentOrderActions">
<span
class="q-ml-md text-body1"
v-text="$t('salesMonitor.recentOrderActions')"

View File

@ -9,6 +9,7 @@ import { toDateFormat, toDateTimeFormat } from 'src/filters/date.js';
import { toCurrency } from 'src/filters';
import { useVnConfirm } from 'composables/useVnConfirm';
import axios from 'axios';
import VnDateBadge from 'src/components/common/VnDateBadge.vue';
import useOpenURL from 'src/composables/useOpenURL';
const { t } = useI18n();
@ -165,16 +166,7 @@ const openTab = (id) => useOpenURL(`#/order/${id}/summary`);
</div>
</template>
<template #column-dateSend="{ row }">
<QTd>
<QBadge
:color="getBadgeColor(row.date_send)"
text-color="black"
class="q-pa-sm"
style="font-size: 14px"
>
{{ toDateFormat(row.date_send) }}
</QBadge>
</QTd>
<VnDateBadge :date="row.date_send" />
</template>
<template #column-clientFk="{ row }">

View File

@ -9,6 +9,7 @@ import VnInput from 'src/components/common/VnInput.vue';
import VnInputNumber from 'src/components/common/VnInputNumber.vue';
import FetchData from 'src/components/FetchData.vue';
import { dateRange } from 'src/filters';
import VnCheckbox from 'src/components/common/VnCheckbox.vue';
defineProps({ dataKey: { type: String, required: true } });
const { t, te } = useI18n();
@ -209,7 +210,7 @@ const getLocale = (label) => {
</QItem>
<QItem>
<QItemSection>
<QCheckbox
<VnCheckbox
:label="t('params.myTeam')"
v-model="params.myTeam"
toggle-indeterminate
@ -218,7 +219,7 @@ const getLocale = (label) => {
</QItem>
<QItem>
<QItemSection>
<QCheckbox
<VnCheckbox
:label="t('params.problems')"
v-model="params.problems"
toggle-indeterminate
@ -227,7 +228,7 @@ const getLocale = (label) => {
</QItem>
<QItem>
<QItemSection>
<QCheckbox
<VnCheckbox
:label="t('params.pending')"
v-model="params.pending"
toggle-indeterminate

View File

@ -1,7 +1,6 @@
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import DepartmentDescriptorProxy from 'src/pages/Worker/Department/Card/DepartmentDescriptorProxy.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import TicketDescriptorProxy from 'src/pages/Ticket/Card/TicketDescriptorProxy.vue';
@ -168,9 +167,11 @@ const columns = computed(() => [
component: 'select',
name: 'provinceFk',
attrs: {
options: provinceOpts.value,
'option-value': 'id',
'option-label': 'name',
url: 'Provinces',
fields: ['id', 'name'],
sortBy: ['name ASC'],
optionValue: 'id',
optionLabel: 'name',
dense: true,
},
},
@ -183,9 +184,11 @@ const columns = computed(() => [
component: 'select',
name: 'stateFk',
attrs: {
options: stateOpts.value,
'option-value': 'id',
'option-label': 'name',
sortBy: ['name ASC'],
url: 'States',
fields: ['id', 'name'],
optionValue: 'id',
optionLabel: 'name',
dense: true,
},
},
@ -212,9 +215,12 @@ const columns = computed(() => [
component: 'select',
name: 'zoneFk',
attrs: {
options: zoneOpts.value,
'option-value': 'id',
'option-label': 'name',
url: 'Zones',
fields: ['id', 'name'],
sortBy: ['name ASC'],
optionValue: 'id',
optionLabel: 'name',
dense: true,
},
},
@ -225,11 +231,12 @@ const columns = computed(() => [
align: 'left',
columnFilter: {
component: 'select',
url: 'PayMethods',
attrs: {
options: PayMethodOpts.value,
optionValue: 'id',
url: 'PayMethods',
fields: ['id', 'name'],
sortBy: ['id ASC'],
optionLabel: 'name',
optionValue: 'id',
dense: true,
},
},
@ -254,7 +261,9 @@ const columns = computed(() => [
columnFilter: {
component: 'select',
attrs: {
options: DepartmentOpts.value,
url: 'Departments',
fields: ['id', 'name'],
sortBy: ['id ASC'],
dense: true,
},
},
@ -265,11 +274,12 @@ const columns = computed(() => [
align: 'left',
columnFilter: {
component: 'select',
url: 'ItemPackingTypes',
attrs: {
options: ItemPackingTypeOpts.value,
'option-value': 'code',
'option-label': 'code',
url: 'ItemPackingTypes',
fields: ['code'],
sortBy: ['code ASC'],
optionValue: 'code',
optionCode: 'code',
dense: true,
},
},
@ -324,60 +334,6 @@ const totalPriceColor = (ticket) => {
const openTab = (id) => useOpenURL(`#/ticket/${id}/sale`);
</script>
<template>
<FetchData
url="Provinces"
:filter="{
fields: ['id', 'name'],
order: 'name ASC',
}"
auto-load
@on-fetch="(data) => (provinceOpts = data)"
/>
<FetchData
url="States"
:filter="{
fields: ['id', 'name'],
order: 'name ASC',
}"
auto-load
@on-fetch="(data) => (stateOpts = data)"
/>
<FetchData
url="Zones"
:filter="{
fields: ['id', 'name'],
order: 'name ASC',
}"
auto-load
@on-fetch="(data) => (zoneOpts = data)"
/>
<FetchData
url="ItemPackingTypes"
:filter="{
fields: ['code'],
order: 'code ASC',
}"
auto-load
@on-fetch="(data) => (ItemPackingTypeOpts = data)"
/>
<FetchData
url="Departments"
:filter="{
fields: ['id', 'name'],
order: 'id ASC',
}"
auto-load
@on-fetch="(data) => (DepartmentOpts = data)"
/>
<FetchData
url="PayMethods"
:filter="{
fields: ['id', 'name'],
order: 'id ASC',
}"
auto-load
@on-fetch="(data) => (PayMethodOpts = data)"
/>
<MonitorTicketSearchbar />
<RightMenu>
<template #right-panel>

View File

@ -120,7 +120,6 @@ watch(
:data-key="dataKey"
:tag-value="tagValue"
:tags="tags"
:initial-catalog-params="catalogParams"
:arrayData
/>
</template>

View File

@ -27,7 +27,7 @@ const getTotalRef = ref();
const total = ref(0);
const entityId = computed(() => {
return $props.id || route.params.id;
return Number($props.id || route.params.id);
});
const orderTotal = computed(() => state.get('orderTotal') ?? 0);

View File

@ -233,10 +233,10 @@ const ticketColumns = ref([
</span>
</QTd>
</template>
<template #body-cell-client="{ value, row }">
<QTd auto-width>
<template #body-cell-client="{ row }">
<QTd>
<span class="link">
{{ value }}
{{ row.clientFk }}
<CustomerDescriptorProxy :id="row?.clientFk" />
</span>
</QTd>

View File

@ -141,7 +141,7 @@ const setOrderedPriority = async () => {
};
const sortRoutes = async () => {
await axios.patch(`Routes/${route.params?.id}/guessPriority/`);
await axios.patch(`Routes/${route.params?.id}/optimizePriority`);
refreshKey.value++;
};

View File

@ -80,7 +80,7 @@ const columns = computed(() => [
<VnTable
:data-key="dataKey"
:columns="columns"
is-editable="false"
:is-editable="false"
:right-search="false"
:use-model="true"
:disable-option="{ table: true }"

View File

@ -90,7 +90,7 @@ const onDataSaved = ({ id }) => {
<VnTable
:data-key="dataKey"
:columns="columns"
is-editable="false"
:is-editable="false"
:right-search="false"
:use-model="true"
:disable-option="{ table: true }"

View File

@ -65,15 +65,13 @@ function findBankFk(value, row) {
if (bankEntityFk) row.bankEntityFk = bankEntityFk.id;
}
function bankEntityFilter(val, update) {
update(() => {
const needle = val.toLowerCase();
filteredBankEntitiesOptions.value = bankEntitiesOptions.value.filter(
(bank) =>
bank.bic.toLowerCase().startsWith(needle) ||
bank.name.toLowerCase().includes(needle),
);
});
function bankEntityFilter(val) {
const needle = val.toLowerCase();
filteredBankEntitiesOptions.value = bankEntitiesOptions.value.filter(
(bank) =>
bank.bic.toLowerCase().startsWith(needle) ||
bank.name.toLowerCase().includes(needle),
);
}
</script>
<template>
@ -82,7 +80,8 @@ function bankEntityFilter(val, update) {
url="BankEntities"
@on-fetch="
(data) => {
(bankEntitiesOptions = data), (filteredBankEntitiesOptions = data);
bankEntitiesOptions = data;
filteredBankEntitiesOptions = data;
}
"
auto-load
@ -135,10 +134,8 @@ function bankEntityFilter(val, update) {
:label="t('worker.create.bankEntity')"
v-model="row.bankEntityFk"
:options="filteredBankEntitiesOptions"
:default-filter="false"
@filter="(val, update) => bankEntityFilter(val, update)"
:filter-fn="bankEntityFilter"
option-label="bic"
option-value="id"
hide-selected
:required="true"
:roles-allowed-to-create="['financial']"

View File

@ -5,7 +5,7 @@ import SupplierSummary from './SupplierSummary.vue';
const $props = defineProps({
id: {
type: Number,
required: true,
default: null,
},
});
</script>

View File

@ -101,7 +101,7 @@ const onNextStep = async () => {
t('basicData.negativesConfirmMessage'),
submitWithNegatives,
);
else submit();
else await submit();
}
};
</script>

View File

@ -46,7 +46,7 @@ async function getClaims() {
originalTicket.value = data[0]?.originalTicketFk;
}
async function getProblems() {
const { data } = await axios.get(`Tickets/${entityId.value}/getTicketProblems`);
const { data } = await axios.get(`Tickets/getTicketProblems`, {params: { ids: [entityId.value] }});
if (!data) return;
problems.value = data[0];
}

View File

@ -28,6 +28,7 @@ const props = defineProps({
onMounted(() => {
restoreTicket();
hasDocuware();
});
watch(

View File

@ -1,7 +1,6 @@
<script setup>
import TicketDescriptor from './TicketDescriptor.vue';
import TicketSummary from './TicketSummary.vue';
const $props = defineProps({
id: {
type: Number,
@ -10,7 +9,7 @@ const $props = defineProps({
});
</script>
<template>
<QPopupProxy>
<QPopupProxy data-cy="TicketDescriptor">
<TicketDescriptor v-if="$props.id" :id="$props.id" :summary="TicketSummary" />
</QPopupProxy>
</template>

View File

@ -4,7 +4,6 @@ import { useI18n } from 'vue-i18n';
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { toCurrency } from 'src/filters';
import VnUsesMana from 'components/ui/VnUsesMana.vue';
const $props = defineProps({
newPrice: {
@ -15,23 +14,36 @@ const $props = defineProps({
type: Object,
default: null,
},
componentId: {
type: Number,
default: null,
},
});
const emit = defineEmits(['save', 'cancel', 'update:componentId']);
const route = useRoute();
const mana = ref(null);
const usesMana = ref(false);
const emit = defineEmits(['save', 'cancel']);
const usesMana = ref([]);
const { t } = useI18n();
const QPopupProxyRef = ref(null);
const manaCode = ref($props.manaCode);
const componentId = computed({
get: () => $props.componentId,
set: (val) => emit('update:componentId', val),
});
const save = (sale = $props.sale) => {
emit('save', sale);
QPopupProxyRef.value.hide();
};
const cancel = () => {
emit('cancel');
QPopupProxyRef.value.hide();
};
const getMana = async () => {
const { data } = await axios.get(`Tickets/${route.params.id}/getDepartmentMana`);
mana.value = data;
@ -39,15 +51,12 @@ const getMana = async () => {
};
const getUsesMana = async () => {
const { data } = await axios.get('Sales/usesMana');
const { data } = await axios.get('Sales/getComponents');
usesMana.value = data;
};
const cancel = () => {
emit('cancel');
QPopupProxyRef.value.hide();
};
const hasMana = computed(() => typeof mana.value === 'number');
defineExpose({ save });
</script>
@ -59,17 +68,29 @@ defineExpose({ save });
>
<div class="container">
<div class="header">Mana: {{ toCurrency(mana) }}</div>
<QSpinner v-if="!hasMana" color="primary" size="md" />
<QSpinner v-if="!usesMana.length" color="primary" />
<div class="q-pa-md" v-else>
<slot :popup="QPopupProxyRef" />
<div v-if="usesMana" class="column q-gutter-y-sm q-mt-sm">
<VnUsesMana :mana-code="manaCode" />
<div v-if="usesMana.length" class="column q-gutter-y-sm q-mt-sm">
<QRadio
v-for="(item, index) in usesMana"
:key="index"
v-model="componentId"
:val="item.id"
:label="item.name"
dense
:dark="true"
class="q-mb-sm"
:data-cy="`componentOption-${item.id}`"
/>
</div>
<div v-if="newPrice" class="column items-center q-mt-lg">
<span class="text-primary">{{ t('New price') }}</span>
<span class="text-subtitle1">
{{ toCurrency($props.newPrice) }}
</span>
<span class="text-subtitle1">{{ toCurrency(newPrice) }}</span>
</div>
</div>
@ -77,7 +98,6 @@ defineExpose({ save });
<QBtn
color="primary"
class="no-border-radius"
dense
style="width: 50%"
@click="cancel()"
>
@ -86,7 +106,6 @@ defineExpose({ save });
<QBtn
color="primary"
class="no-border-radius"
dense
style="width: 50%"
@click="save()"
data-cy="saveManaBtn"
@ -116,8 +135,3 @@ defineExpose({ save });
min-width: 230px;
}
</style>
<i18n>
es:
New price: Nuevo precio
</i18n>

View File

@ -38,7 +38,9 @@ function handleDelete(row) {
ticketNotesCrudRef.value.remove([row]);
}
async function handleSave() {
async function handleSave(e) {
if (e.shiftKey && e.key === 'Enter') return;
e.preventDefault();
if (!isSaving.value) {
isSaving.value = true;
await ticketNotesCrudRef.value?.saveChanges();
@ -70,7 +72,7 @@ async function handleSave() {
<div
v-for="(row, index) in rows"
:key="index"
class="q-mb-md row items-center q-gutter-x-md"
class="q-mb-md row q-gutter-x-md"
>
<VnSelect
:label="t('ticketNotes.observationType')"
@ -86,7 +88,8 @@ async function handleSave() {
:label="t('basicData.description')"
v-model="row.description"
class="col"
@keyup.enter="handleSave"
@keydown.enter.stop="handleSave"
autogrow
data-cy="ticketNotesDescription"
/>
<QIcon

View File

@ -45,7 +45,7 @@ const isTicketEditable = ref(false);
const sales = ref([]);
const editableStatesOptions = ref([]);
const selectedSales = ref([]);
const manaCode = ref('mana');
const componentId = ref(null);
const ticketState = computed(() => store.data?.ticketState?.state?.code);
const transfer = ref({
lastActiveTickets: [],
@ -187,7 +187,7 @@ const getRowUpdateInputEvents = (sale) => {
};
const resetChanges = async () => {
arrayData.fetch({ append: false });
await arrayData.fetch({ append: false });
tableRef.value.CrudModelRef.hasChanges = false;
await tableRef.value.reload();
@ -308,14 +308,15 @@ const changePrice = async (sale) => {
if (newPrice != null && newPrice != sale.price) {
if (await isSalePrepared(sale)) {
await confirmUpdate(() => updatePrice(sale, newPrice));
} else updatePrice(sale, newPrice);
} else await updatePrice(sale, newPrice);
}
};
const updatePrice = async (sale, newPrice) => {
try {
await axios.post(`Sales/${sale.id}/updatePrice`, { newPrice });
sale.price = newPrice;
edit.value = { ...DEFAULT_EDIT };
await axios.post(`Sales/${sale.id}/updatePrice`, {
newPrice: newPrice,
componentId: componentId.value,
});
notify('globals.dataSaved', 'positive');
resetChanges();
} catch (e) {
@ -327,28 +328,31 @@ const changeDiscount = async (sale) => {
const newDiscount = edit.value.discount;
if (newDiscount != null && newDiscount != sale.discount) {
if (await isSalePrepared(sale))
await confirmUpdate(() => updateDiscount([sale], newDiscount));
else await updateDiscount([sale], newDiscount);
await confirmUpdate(() =>
updateDiscount([sale], newDiscount, componentId.value),
);
else await updateDiscount([sale], newDiscount, componentId.value);
}
};
const updateDiscounts = async (sales, newDiscount) => {
const updateDiscounts = async (sales, newDiscount, componentId) => {
const salesTracking = await fetchSalesTracking();
const someSaleIsPrepared = salesTracking.some((sale) =>
matchSale(salesTracking, sale),
);
if (someSaleIsPrepared) await confirmUpdate(() => updateDiscount(sales, newDiscount));
else updateDiscount(sales, newDiscount);
if (someSaleIsPrepared)
await confirmUpdate(() => updateDiscount(sales, newDiscount, componentId));
else updateDiscount(sales, newDiscount, componentId);
};
const updateDiscount = async (sales, newDiscount = 0) => {
const updateDiscount = async (sales, newDiscount, componentId) => {
try {
const salesIds = sales.map(({ id }) => id);
const params = {
salesIds,
newDiscount,
manaCode: manaCode.value,
newDiscount: newDiscount ?? 0,
componentId,
};
await axios.post(`Tickets/${route.params.id}/updateDiscount`, params);
notify('globals.dataSaved', 'positive');
@ -769,6 +773,7 @@ watch(
v-model="row.itemFk"
:use-like="false"
@update:model-value="changeItem(row)"
autofocus
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
@ -821,10 +826,11 @@ watch(
ref="editPriceProxyRef"
:sale="row"
:new-price="getNewPrice"
v-model:component-id="componentId"
@save="changePrice"
>
<VnInput
@keyup.enter.stop="() => editManaProxyRef.save(row)"
@keyup.enter.stop="() => editPriceProxyRef.save(row)"
v-model.number="edit.price"
:label="t('basicData.price')"
type="number"
@ -843,7 +849,7 @@ watch(
ref="editManaProxyRef"
:sale="row"
:new-price="getNewPrice"
:mana-code="manaCode"
v-model:component-id="componentId"
@save="changeDiscount"
>
<VnInput

View File

@ -47,6 +47,7 @@ const { notify } = useNotify();
const acl = useAcl();
const btnDropdownRef = ref(null);
const editManaProxyRef = ref(null);
const componentId = ref(null);
const { openConfirmationModal } = useVnConfirm();
const newDiscount = ref(null);
@ -112,7 +113,7 @@ const changeMultipleDiscount = () => {
});
if (newDiscount.value != null && hasChanges)
emit('updateDiscounts', props.sales, newDiscount.value);
emit('updateDiscounts', props.sales, newDiscount.value, componentId.value);
btnDropdownRef.value.hide();
};
@ -206,6 +207,7 @@ const createRefund = async (withWarehouse) => {
ref="editManaProxyRef"
:sale="row"
@save="changeMultipleDiscount"
v-model:component-id="componentId"
>
<VnInput
autofocus

View File

@ -3,7 +3,9 @@ import { ref } from 'vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
import split from './components/split';
const emit = defineEmits(['ticketTransfered']);
import { displayResults } from 'src/pages/Ticket/Negative/composables/notifyResults';
const { notifyResults } = displayResults();
const emit = defineEmits(['ticketTransferred']);
const $props = defineProps({
ticket: {
@ -16,13 +18,20 @@ const splitDate = ref(Date.vnNew());
const splitSelectedRows = async () => {
const tickets = Array.isArray($props.ticket) ? $props.ticket : [$props.ticket];
await split(tickets, splitDate.value);
emit('ticketTransfered', tickets);
const results = await split(tickets, splitDate.value);
notifyResults(results, 'ticketFk');
emit('ticketTransferred', tickets);
};
</script>
<template>
<VnInputDate class="q-mr-sm" :label="$t('New date')" v-model="splitDate" clearable />
<VnInputDate
class="q-mr-sm"
:label="$t('New date')"
v-model="splitDate"
clearable
autofocus
/>
<QBtn class="q-mr-sm" color="primary" label="Split" @click="splitSelectedRows"></QBtn>
</template>
<style lang="scss">

View File

@ -241,6 +241,7 @@ onMounted(async () => {
:value="`${entity.address?.nickname} #${entity.address?.id}`"
/>
<VnLv
class="white-space-normal"
:label="t('ticket.summary.consigneeStreet')"
:value="formattedAddress"
/>
@ -524,4 +525,7 @@ onMounted(async () => {
.grafana {
color: $primary-light;
}
.white-space-normal :deep(.value span) {
white-space: normal;
}
</style>

View File

@ -5,7 +5,7 @@ import VnInput from 'src/components/common/VnInput.vue';
import TicketTransferForm from './TicketTransferForm.vue';
import { toDateFormat } from 'src/filters/date.js';
const emit = defineEmits(['ticketTransfered']);
const emit = defineEmits(['ticketTransferred']);
const $props = defineProps({
mana: {

View File

@ -1,8 +1,8 @@
<script setup>
import { ref } from 'vue';
import TicketTransfer from './TicketTransfer.vue';
import Split from './TicketSplit.vue';
const emit = defineEmits(['ticketTransfered']);
import TicketSplit from './TicketSplit.vue';
const emit = defineEmits(['ticketTransferred']);
const $props = defineProps({
mana: {
@ -35,7 +35,7 @@ const transferRef = ref(null);
<template>
<QPopupProxy ref="popupProxyRef" data-cy="ticketTransferPopup">
<div class="flex row items-center q-ma-lg" v-if="$props.split">
<Split
<TicketSplit
ref="splitRef"
@splitSelectedRows="splitSelectedRows"
:ticket="$props.ticket"

View File

@ -1,13 +1,11 @@
import axios from 'axios';
import notifyResults from 'src/utils/notifyResults';
export default async function (data, date) {
const reducedData = data.reduce((acc, item) => {
const existing = acc.find(({ ticketFk }) => ticketFk === item.id);
if (existing) {
existing.sales.push(item.saleFk);
} else {
acc.push({ ticketFk: item.id, sales: [item.saleFk], date });
acc.push({ ticketFk: item.ticketFk, sales: [item.saleFk], date });
}
return acc;
}, []);
@ -16,7 +14,5 @@ export default async function (data, date) {
const results = await Promise.allSettled(promises);
notifyResults(results, 'ticketFk');
return results;
}

View File

@ -23,7 +23,6 @@ const tableRef = ref();
const changeItemDialogRef = ref(null);
const changeStateDialogRef = ref(null);
const changeQuantityDialogRef = ref(null);
const showProposalDialog = ref(false);
const showChangeQuantityDialog = ref(false);
const selectedRows = ref([]);
const route = useRoute();
@ -63,6 +62,7 @@ const showItemProposal = () => {
.dialog({
component: ItemProposalProxy,
componentProps: {
filter: filter.value,
itemLack: tableRef.value.itemLack,
replaceAction: true,
sales: selectedRows.value,
@ -117,21 +117,17 @@ const showItemProposal = () => {
sales: selectedRows,
lastActiveTickets: selectedRows.map((row) => row.id),
}"
@ticket-transfered="reload"
@ticket-transferred="reload"
></TicketTransferProxy>
</template>
</QBtn>
<QBtn
color="primary"
@click="showProposalDialog = true"
:disable="selectedRows.length < 1"
@click="showItemProposal"
:disable="!(selectedRows.length === 1)"
data-cy="itemProposal"
>
<QIcon
name="import_export"
class="rotate-90"
@click="showItemProposal"
></QIcon>
<QIcon name="import_export" class="rotate-90" />
<QTooltip bottom anchor="bottom right">
{{ t('itemProposal') }}
</QTooltip>
@ -139,7 +135,7 @@ const showItemProposal = () => {
<VnPopupProxy
data-cy="changeItem"
icon="sync"
:disable="selectedRows.length < 1"
:disable="!(selectedRows.length === 1)"
:tooltip="t('negative.detail.modal.changeItem.title')"
>
<template #extraIcon> <QIcon name="vn:item" /> </template>
@ -153,7 +149,7 @@ const showItemProposal = () => {
<VnPopupProxy
data-cy="changeState"
icon="sync"
:disable="selectedRows.length < 1"
:disable="!(selectedRows.length === 1)"
:tooltip="t('negative.detail.modal.changeState.title')"
>
<template #extraIcon> <QIcon name="vn:eye" /> </template>
@ -167,7 +163,7 @@ const showItemProposal = () => {
<VnPopupProxy
data-cy="changeQuantity"
icon="sync"
:disable="selectedRows.length < 1"
:disable="!(selectedRows.length === 1)"
:tooltip="t('negative.detail.modal.changeQuantity.title')"
@click="showChangeQuantityDialog = true"
>

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