Compare commits

..

No commits in common. "5dd508c559c933be5ccf15e928cd8299d4a8bc44" and "095c1f477f376bf03e6b9de8a484b52be069ec97" have entirely different histories.

91 changed files with 1571 additions and 1109 deletions

View File

@ -1,7 +1,4 @@
const { defineConfig } = require('cypress'); const { defineConfig } = require('cypress');
// https://docs.cypress.io/app/tooling/reporters
// https://docs.cypress.io/app/references/configuration
// https://www.npmjs.com/package/cypress-mochawesome-reporter
module.exports = defineConfig({ module.exports = defineConfig({
e2e: { e2e: {
@ -19,7 +16,6 @@ module.exports = defineConfig({
reporterOptions: { reporterOptions: {
charts: true, charts: true,
reportPageTitle: 'Cypress Inline Reporter', reportPageTitle: 'Cypress Inline Reporter',
reportFilename: '[status]_[datetime]-report',
embeddedScreenshots: true, embeddedScreenshots: true,
reportDir: 'test/cypress/reports', reportDir: 'test/cypress/reports',
inlineAssets: true, inlineAssets: true,

View File

@ -17,6 +17,10 @@ const $props = defineProps({
type: Number, type: Number,
default: null, default: null,
}, },
provinces: {
type: Array,
default: () => [],
},
}); });
const { t } = useI18n(); const { t } = useI18n();
@ -52,6 +56,7 @@ const onDataSaved = (...args) => {
:province-selected="$props.provinceSelected" :province-selected="$props.provinceSelected"
:country-fk="$props.countryFk" :country-fk="$props.countryFk"
v-model="data.provinceFk" v-model="data.provinceFk"
:provinces="$props.provinces"
/> />
</VnRow> </VnRow>
</template> </template>

View File

@ -56,10 +56,10 @@ async function onCityCreated(newTown, formData) {
} }
function setTown(newTown, data) { function setTown(newTown, data) {
data.provinceFk = newTown.provinceFk;
data.countryFk = newTown.province.countryFk;
if (!newTown) return; if (!newTown) return;
town.value = newTown; town.value = newTown;
data.provinceFk = newTown.provinceFk;
data.countryFk = newTown.province.countryFk;
} }
async function setProvince(id, data) { async function setProvince(id, data) {
@ -73,7 +73,7 @@ async function onProvinceCreated(data) {
await provincesFetchDataRef.value.fetch({ await provincesFetchDataRef.value.fetch({
where: { countryFk: postcodeFormData.countryFk }, where: { countryFk: postcodeFormData.countryFk },
}); });
postcodeFormData.provinceFk = data.id; postcodeFormData.provinceFk.value = data.id;
} }
watch( watch(
@ -90,33 +90,22 @@ watch(
postcodeFormData.townFk = null; postcodeFormData.townFk = null;
} }
if (oldValueFk !== newCountryFk) { if (oldValueFk !== newCountryFk) {
await fetchProvinces(newCountryFk); await provincesFetchDataRef.value.fetch({
await fetchTowns(newCountryFk); where: {
countryFk: newCountryFk,
},
});
await townsFetchDataRef.value.fetch({
where: {
provinceFk: {
inq: provincesOptions.value.map(({ id }) => id),
},
},
});
} }
} }
); );
async function fetchTowns(countryFk) {
const townsFilter = countryFk
? {
where: {
provinceFk: {
inq: provincesOptions.value.map(({ id }) => id),
},
},
}
: {};
await townsFetchDataRef.value.fetch(townsFilter);
}
async function fetchProvinces(countryFk) {
const provincesFilter = countryFk
? {
where: {
countryFk: countryFk,
},
}
: {};
await provincesFetchDataRef.value.fetch(provincesFilter);
}
watch( watch(
() => postcodeFormData.provinceFk, () => postcodeFormData.provinceFk,
async (newProvinceFk, oldValueFk) => { async (newProvinceFk, oldValueFk) => {
@ -158,13 +147,6 @@ async function handleCountries(data) {
auto-load auto-load
url="Towns/location" url="Towns/location"
/> />
<FetchData
ref="CountriesFetchDataRef"
:sort-by="['name ASC']"
@on-fetch="handleCountries"
auto-load
url="Countries"
/>
<FormModelPopup <FormModelPopup
url-create="postcodes" url-create="postcodes"
@ -211,6 +193,7 @@ async function handleCountries(data) {
<CreateNewCityForm <CreateNewCityForm
:country-fk="data.countryFk" :country-fk="data.countryFk"
:province-selected="data.provinceFk" :province-selected="data.provinceFk"
:provinces="provincesOptions"
@on-data-saved=" @on-data-saved="
(_, requestResponse) => (_, requestResponse) =>
onCityCreated(requestResponse, data) onCityCreated(requestResponse, data)
@ -226,12 +209,14 @@ async function handleCountries(data) {
@update:model-value="(value) => setProvince(value, data)" @update:model-value="(value) => setProvince(value, data)"
v-model="data.provinceFk" v-model="data.provinceFk"
:clearable="true" :clearable="true"
:provinces="provincesOptions"
@on-province-created="onProvinceCreated" @on-province-created="onProvinceCreated"
/> />
<VnSelect <VnSelect
url="Countries"
:sort-by="['name ASC']"
:label="t('Country')" :label="t('Country')"
@update:options="handleCountries" @update:options="handleCountries"
:options="countriesOptions"
hide-selected hide-selected
option-label="name" option-label="name"
option-value="id" option-value="id"

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { computed, reactive, ref } from 'vue'; import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue'; import FetchData from 'components/FetchData.vue';
@ -34,12 +34,6 @@ const onDataSaved = (dataSaved, requestResponse) => {
); );
emit('onDataSaved', dataSaved, requestResponse); emit('onDataSaved', dataSaved, requestResponse);
}; };
const where = computed(() => {
if (!$props.countryFk) {
return {};
}
return { countryFk: $props.countryFk };
});
</script> </script>
<template> <template>
@ -47,7 +41,9 @@ const where = computed(() => {
@on-fetch="(data) => (autonomiesOptions = data)" @on-fetch="(data) => (autonomiesOptions = data)"
auto-load auto-load
:filter="{ :filter="{
where, where: {
countryFk: $props.countryFk,
},
}" }"
url="Autonomies/location" url="Autonomies/location"
:sort-by="['name ASC']" :sort-by="['name ASC']"

View File

@ -156,22 +156,26 @@ const rotateRight = () => {
}; };
const onSubmit = () => { const onSubmit = () => {
if (!newPhoto.files && !newPhoto.url) { try {
notify(t('Select an image'), 'negative'); if (!newPhoto.files && !newPhoto.url) {
return; notify(t('Select an image'), 'negative');
return;
}
const options = {
type: 'blob',
};
editor.value
.result(options)
.then((result) => {
const file = new File([result], newPhoto.files?.name || '');
newPhoto.blob = file;
})
.then(() => makeRequest());
} catch (err) {
console.error('Error uploading image');
} }
const options = {
type: 'blob',
};
editor.value
.result(options)
.then((result) => {
const file = new File([result], newPhoto.files?.name || '');
newPhoto.blob = file;
})
.then(() => makeRequest());
}; };
const makeRequest = async () => { const makeRequest = async () => {

View File

@ -51,17 +51,21 @@ const onDataSaved = () => {
}; };
const onSubmit = async () => { const onSubmit = async () => {
isLoading.value = true; try {
const rowsToEdit = $props.rows.map((row) => ({ id: row.id, itemFk: row.itemFk })); isLoading.value = true;
const payload = { const rowsToEdit = $props.rows.map((row) => ({ id: row.id, itemFk: row.itemFk }));
field: selectedField.value.field, const payload = {
newValue: newValue.value, field: selectedField.value.field,
lines: rowsToEdit, newValue: newValue.value,
}; lines: rowsToEdit,
};
await axios.post($props.editUrl, payload); await axios.post($props.editUrl, payload);
onDataSaved(); onDataSaved();
isLoading.value = false; isLoading.value = false;
} catch (err) {
console.error('Error submitting table cell edit');
}
}; };
const closeForm = () => { const closeForm = () => {

View File

@ -84,30 +84,34 @@ const tableColumns = computed(() => [
]); ]);
const onSubmit = async () => { const onSubmit = async () => {
let filter = itemFilter; try {
const params = itemFilterParams; let filter = itemFilter;
const where = {}; const params = itemFilterParams;
for (let key in params) { const where = {};
const value = params[key]; for (let key in params) {
if (!value) continue; const value = params[key];
if (!value) continue;
switch (key) { switch (key) {
case 'name': case 'name':
where[key] = { like: `%${value}%` }; where[key] = { like: `%${value}%` };
break; break;
case 'producerFk': case 'producerFk':
case 'typeFk': case 'typeFk':
case 'size': case 'size':
case 'inkFk': case 'inkFk':
where[key] = value; where[key] = value;
}
} }
} filter.where = where;
filter.where = where;
const { data } = await axios.get(props.url, { const { data } = await axios.get(props.url, {
params: { filter: JSON.stringify(filter) }, params: { filter: JSON.stringify(filter) },
}); });
tableRows.value = data; tableRows.value = data;
} catch (err) {
console.error('Error fetching entries items');
}
}; };
const closeForm = () => { const closeForm = () => {

View File

@ -86,28 +86,32 @@ const tableColumns = computed(() => [
]); ]);
const onSubmit = async () => { const onSubmit = async () => {
let filter = travelFilter; try {
const params = travelFilterParams; let filter = travelFilter;
const where = {}; const params = travelFilterParams;
for (let key in params) { const where = {};
const value = params[key]; for (let key in params) {
if (!value) continue; const value = params[key];
if (!value) continue;
switch (key) { switch (key) {
case 'agencyModeFk': case 'agencyModeFk':
case 'warehouseInFk': case 'warehouseInFk':
case 'warehouseOutFk': case 'warehouseOutFk':
case 'shipped': case 'shipped':
case 'landed': case 'landed':
where[key] = value; where[key] = value;
}
} }
}
filter.where = where; filter.where = where;
const { data } = await axios.get('Travels', { const { data } = await axios.get('Travels', {
params: { filter: JSON.stringify(filter) }, params: { filter: JSON.stringify(filter) },
}); });
tableRows.value = data; tableRows.value = data;
} catch (err) {
console.error('Error fetching travels');
}
}; };
const closeForm = () => { const closeForm = () => {

View File

@ -4,7 +4,7 @@ import { useI18n } from 'vue-i18n';
const emit = defineEmits(['onSubmit']); const emit = defineEmits(['onSubmit']);
const $props = defineProps({ defineProps({
title: { title: {
type: String, type: String,
default: '', default: '',
@ -25,21 +25,16 @@ const $props = defineProps({
type: String, type: String,
default: '', default: '',
}, },
submitOnEnter: {
type: Boolean,
default: true,
},
}); });
const { t } = useI18n(); const { t } = useI18n();
const closeButton = ref(null); const closeButton = ref(null);
const isLoading = ref(false); const isLoading = ref(false);
const onSubmit = () => { const onSubmit = () => {
if ($props.submitOnEnter) { emit('onSubmit');
emit('onSubmit'); closeForm();
closeForm();
}
}; };
const closeForm = () => { const closeForm = () => {

View File

@ -88,16 +88,20 @@ const applyTags = (params, search) => {
}; };
const fetchItemTypes = async (id) => { const fetchItemTypes = async (id) => {
const filter = { try {
fields: ['id', 'name', 'categoryFk'], const filter = {
where: { categoryFk: id }, fields: ['id', 'name', 'categoryFk'],
include: 'category', where: { categoryFk: id },
order: 'name ASC', include: 'category',
}; order: 'name ASC',
const { data } = await axios.get('ItemTypes', { };
params: { filter: JSON.stringify(filter) }, const { data } = await axios.get('ItemTypes', {
}); params: { filter: JSON.stringify(filter) },
itemTypesOptions.value = data; });
itemTypesOptions.value = data;
} catch (err) {
console.error('Error fetching item types', err);
}
}; };
const getCategoryClass = (category, params) => { const getCategoryClass = (category, params) => {
@ -107,19 +111,23 @@ const getCategoryClass = (category, params) => {
}; };
const getSelectedTagValues = async (tag) => { const getSelectedTagValues = async (tag) => {
if (!tag?.selectedTag?.id) return; try {
tag.value = null; if (!tag?.selectedTag?.id) return;
const filter = { tag.value = null;
fields: ['value'], const filter = {
order: 'value ASC', fields: ['value'],
limit: 30, order: 'value ASC',
}; limit: 30,
};
const params = { filter: JSON.stringify(filter) }; const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, { const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, {
params, params,
}); });
tag.valueOptions = data; tag.valueOptions = data;
} catch (err) {
console.error('Error getting selected tag values');
}
}; };
const removeTag = (index, params, search) => { const removeTag = (index, params, search) => {

View File

@ -39,10 +39,14 @@ const refund = async () => {
invoiceCorrectionTypeFk: invoiceParams.invoiceCorrectionTypeFk, invoiceCorrectionTypeFk: invoiceParams.invoiceCorrectionTypeFk,
}; };
const { data } = await axios.post('InvoiceOuts/refundAndInvoice', params); try {
notify(t('Refunded invoice'), 'positive'); const { data } = await axios.post('InvoiceOuts/refundAndInvoice', params);
const [id] = data?.refundId || []; notify(t('Refunded invoice'), 'positive');
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } }); const [id] = data?.refundId || [];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
} catch (err) {
console.error('Error refunding invoice', err);
}
}; };
</script> </script>

View File

@ -49,32 +49,36 @@ const makeInvoice = async () => {
makeInvoice: checked.value, makeInvoice: checked.value,
}; };
if (checked.value && hasToInvoiceByAddress) { try {
const response = await new Promise((resolve) => { if (checked.value && hasToInvoiceByAddress) {
quasar const response = await new Promise((resolve) => {
.dialog({ quasar
component: VnConfirm, .dialog({
componentProps: { component: VnConfirm,
title: t('Bill destination client'), componentProps: {
message: t('transferInvoiceInfo'), title: t('Bill destination client'),
}, message: t('transferInvoiceInfo'),
}) },
.onOk(() => { })
resolve(true); .onOk(() => {
}) resolve(true);
.onCancel(() => { })
resolve(false); .onCancel(() => {
}); resolve(false);
}); });
if (!response) { });
return; if (!response) {
return;
}
} }
}
const { data } = await axios.post('InvoiceOuts/transfer', params); const { data } = await axios.post('InvoiceOuts/transfer', params);
notify(t('Transferred invoice'), 'positive'); notify(t('Transferred invoice'), 'positive');
const id = data?.[0]; const id = data?.[0];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } }); if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
} catch (err) {
console.error('Error transfering invoice', err);
}
}; };
</script> </script>

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref, watch } from 'vue'; import { ref } from 'vue';
import { useValidator } from 'src/composables/useValidator'; import { useValidator } from 'src/composables/useValidator';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@ -17,23 +17,20 @@ const $props = defineProps({
type: Number, type: Number,
default: null, default: null,
}, },
provinces: {
type: Array,
default: () => [],
},
}); });
const provinceFk = defineModel({ type: Number, default: null }); const provinceFk = defineModel({ type: Number, default: null });
const { validate } = useValidator(); const { validate } = useValidator();
const { t } = useI18n(); const { t } = useI18n();
const filter = ref({
include: { relation: 'country' },
where: {
countryFk: $props.countryFk,
},
});
const provincesOptions = ref($props.provinces); const provincesOptions = ref($props.provinces);
const provincesFetchDataRef = ref();
provinceFk.value = $props.provinceSelected; provinceFk.value = $props.provinceSelected;
if (!$props.countryFk) { const provincesFetchDataRef = ref();
filter.value.where = {};
}
async function onProvinceCreated(_, data) { async function onProvinceCreated(_, data) {
await provincesFetchDataRef.value.fetch({ where: { countryFk: $props.countryFk } }); await provincesFetchDataRef.value.fetch({ where: { countryFk: $props.countryFk } });
provinceFk.value = data.id; provinceFk.value = data.id;
@ -42,29 +39,23 @@ async function onProvinceCreated(_, data) {
async function handleProvinces(data) { async function handleProvinces(data) {
provincesOptions.value = data; provincesOptions.value = data;
} }
watch(
() => $props.countryFk,
async () => {
if ($props.countryFk) {
filter.value.where.countryFk = $props.countryFk;
} else filter.value.where = {};
await provincesFetchDataRef.value.fetch({});
}
);
</script> </script>
<template> <template>
<FetchData <FetchData
ref="provincesFetchDataRef" ref="provincesFetchDataRef"
:filter="filter" :filter="{
include: { relation: 'country' },
where: {
countryFk: $props.countryFk,
},
}"
@on-fetch="handleProvinces" @on-fetch="handleProvinces"
url="Provinces" url="Provinces"
auto-load
/> />
<VnSelectDialog <VnSelectDialog
:label="t('Province')" :label="t('Province')"
:options="provincesOptions" :options="$props.provinces"
:tooltip="t('Create province')" :tooltip="t('Create province')"
hide-selected hide-selected
v-model="provinceFk" v-model="provinceFk"

View File

@ -58,71 +58,79 @@ const getConfig = async (url, filter) => {
}; };
const fetchViewConfigData = async () => { const fetchViewConfigData = async () => {
const userConfigFilter = { try {
where: { tableCode: $props.tableCode, userFk: user.value.id }, const userConfigFilter = {
}; where: { tableCode: $props.tableCode, userFk: user.value.id },
const userConfig = await getConfig('UserConfigViews', userConfigFilter); };
const userConfig = await getConfig('UserConfigViews', userConfigFilter);
if (userConfig) { if (userConfig) {
initialUserConfigViewData.value = userConfig; initialUserConfigViewData.value = userConfig;
setUserConfigViewData(userConfig.configuration); setUserConfigViewData(userConfig.configuration);
return; return;
} }
const defaultConfigFilter = { where: { tableCode: $props.tableCode } }; const defaultConfigFilter = { where: { tableCode: $props.tableCode } };
const defaultConfig = await getConfig('DefaultViewConfigs', defaultConfigFilter); const defaultConfig = await getConfig('DefaultViewConfigs', defaultConfigFilter);
if (defaultConfig) { if (defaultConfig) {
// Si el backend devuelve una configuración por defecto la usamos // Si el backend devuelve una configuración por defecto la usamos
setUserConfigViewData(defaultConfig.columns); setUserConfigViewData(defaultConfig.columns);
return; return;
} else { } else {
// Si no hay configuración por defecto mostramos todas las columnas // Si no hay configuración por defecto mostramos todas las columnas
const defaultColumns = {}; const defaultColumns = {};
$props.allColumns.forEach((col) => (defaultColumns[col] = true)); $props.allColumns.forEach((col) => (defaultColumns[col] = true));
setUserConfigViewData(defaultColumns); setUserConfigViewData(defaultColumns);
}
} catch (err) {
console.error('Error fetching config view data', err);
} }
}; };
const saveConfig = async () => { const saveConfig = async () => {
const params = {}; try {
const configuration = {}; const params = {};
const configuration = {};
formattedCols.value.forEach((col) => { formattedCols.value.forEach((col) => {
const { name, active } = col; const { name, active } = col;
configuration[name] = active; configuration[name] = active;
}); });
// Si existe una view config del usuario hacemos un update si no la creamos // Si existe una view config del usuario hacemos un update si no la creamos
if (initialUserConfigViewData.value) { if (initialUserConfigViewData.value) {
params.updates = [ params.updates = [
{ {
data: { data: {
configuration: configuration,
},
where: {
id: initialUserConfigViewData.value.id,
},
},
];
} else {
params.creates = [
{
userFk: user.value.id,
tableCode: $props.tableCode,
tableConfig: $props.tableCode,
configuration: configuration, configuration: configuration,
}, },
where: { ];
id: initialUserConfigViewData.value.id, }
},
},
];
} else {
params.creates = [
{
userFk: user.value.id,
tableCode: $props.tableCode,
tableConfig: $props.tableCode,
configuration: configuration,
},
];
}
const response = await axios.post('UserConfigViews/crud', params); const response = await axios.post('UserConfigViews/crud', params);
if (response.data && response.data[0]) { if (response.data && response.data[0]) {
initialUserConfigViewData.value = response.data[0]; initialUserConfigViewData.value = response.data[0];
}
emitSavedConfig();
notify('globals.dataSaved', 'positive');
popupProxyRef.value.hide();
} catch (err) {
console.error('Error saving user view config', err);
} }
emitSavedConfig();
notify('globals.dataSaved', 'positive');
popupProxyRef.value.hide();
}; };
const emitSavedConfig = () => { const emitSavedConfig = () => {

View File

@ -74,9 +74,6 @@ const arrayData = useArrayData($props.dataKey, {
const route = useRoute(); const route = useRoute();
const store = arrayData.store; const store = arrayData.store;
const userParams = ref({}); const userParams = ref({});
defineExpose({ search, sanitizer, params: userParams });
onMounted(() => { onMounted(() => {
userParams.value = $props.modelValue ?? {}; userParams.value = $props.modelValue ?? {};
emit('init', { params: userParams.value }); emit('init', { params: userParams.value });
@ -200,7 +197,7 @@ const customTags = computed(() =>
async function remove(key) { async function remove(key) {
userParams.value[key] = undefined; userParams.value[key] = undefined;
await search(); search();
emit('remove', key); emit('remove', key);
emit('update:modelValue', userParams.value); emit('update:modelValue', userParams.value);
} }
@ -226,6 +223,8 @@ function sanitizer(params) {
} }
return params; return params;
} }
defineExpose({ search, sanitizer, userParams });
</script> </script>
<template> <template>

View File

@ -132,24 +132,10 @@ 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.reset(['filter.skip', 'skip']);
await arrayData.fetch({ append: false }); await arrayData.fetch({ append: false });
return emitStoreData();
}
async function update(params) {
useArrayData(props.dataKey, params);
const { limit, skip } = store;
store.limit = limit + skip;
store.skip = 0;
await arrayData.fetch({ append: false });
store.limit = limit;
store.skip = skip;
return emitStoreData();
}
function emitStoreData() {
if (!store.hasMoreData) isLoading.value = false; if (!store.hasMoreData) isLoading.value = false;
emit('onFetch', store.data); emit('onFetch', store.data);
return store.data; return store.data;
} }
@ -195,7 +181,7 @@ async function onLoad(index, done) {
done(isDone); done(isDone);
} }
defineExpose({ fetch, update, addFilter, paginate }); defineExpose({ fetch, addFilter, paginate });
</script> </script>
<template> <template>

View File

@ -1,24 +1,11 @@
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
import { getUrl } from './getUrl'; import { getUrl } from './getUrl';
import axios from 'axios';
import { exportFile } from 'quasar';
const { getTokenMultimedia } = useSession(); const { getTokenMultimedia } = useSession();
const token = getTokenMultimedia(); const token = getTokenMultimedia();
export async function downloadFile(id, model = 'dms', urlPath = '/downloadFile', url) { export async function downloadFile(id, model = 'dms', urlPath = '/downloadFile', url) {
const appUrl = (await getUrl('', 'lilium')).replace('/#/', ''); let appUrl = await getUrl('', 'lilium');
const response = await axios.get( appUrl = appUrl.replace('/#/', '');
url ?? `${appUrl}/${model}/${id}${urlPath}?access_token=${token}`, window.open(url ?? `${appUrl}/api/${model}/${id}${urlPath}?access_token=${token}`);
{ responseType: 'blob' }
);
const contentDisposition = response.headers['content-disposition'];
const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
const filename =
matches != null && matches[1]
? matches[1].replace(/['"]/g, '')
: 'downloaded-file';
exportFile(filename, response.data);
} }

View File

@ -87,7 +87,7 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
const params = { filter }; const params = { filter };
Object.assign(params, userParams); Object.assign(params, userParams);
if (params.filter) params.filter.skip = store.skip; params.filter.skip = store.skip;
if (store?.order && typeof store?.order == 'string') store.order = [store.order]; if (store?.order && typeof store?.order == 'string') store.order = [store.order];
if (store.order?.length) params.filter.order = [...store.order]; if (store.order?.length) params.filter.order = [...store.order];
else delete params.filter.order; else delete params.filter.order;

View File

@ -769,7 +769,6 @@ travel:
hb: HB hb: HB
basicData: basicData:
daysInForward: Days in forward daysInForward: Days in forward
isRaid: Raid
thermographs: thermographs:
temperature: Temperature temperature: Temperature
destination: Destination destination: Destination

View File

@ -763,7 +763,6 @@ travel:
hb: HB hb: HB
basicData: basicData:
daysInForward: Días redada daysInForward: Días redada
isRaid: Redada
thermographs: thermographs:
temperature: Temperatura temperature: Temperatura
destination: Destino destination: Destino

View File

@ -11,13 +11,21 @@ const { t } = useI18n();
const { notify } = useNotify(); const { notify } = useNotify();
const onSynchronizeAll = async () => { const onSynchronizeAll = async () => {
notify(t('Synchronizing in the background'), 'positive'); try {
await axios.patch(`Accounts/syncAll`); notify(t('Synchronizing in the background'), 'positive');
await axios.patch(`Accounts/syncAll`);
} catch (error) {
console.error('Error synchronizing all accounts', error);
}
}; };
const onSynchronizeRoles = async () => { const onSynchronizeRoles = async () => {
await axios.patch(`RoleInherits/sync`); try {
notify(t('Roles synchronized!'), 'positive'); await axios.patch(`RoleInherits/sync`);
notify(t('Roles synchronized!'), 'positive');
} catch (error) {
console.error('Error synchronizing roles', error);
}
}; };
</script> </script>

View File

@ -111,25 +111,29 @@ const columns = computed(() => [
}, },
]); ]);
const deleteAcl = async ({ id }) => { const deleteAcl = async ({ id }) => {
await new Promise((resolve) => { try {
quasar await new Promise((resolve) => {
.dialog({ quasar
component: VnConfirm, .dialog({
componentProps: { component: VnConfirm,
title: t('Remove ACL'), componentProps: {
message: t('Do you want to remove this ACL?'), title: t('Remove ACL'),
}, message: t('Do you want to remove this ACL?'),
}) },
.onOk(() => { })
resolve(true); .onOk(() => {
}) resolve(true);
.onCancel(() => { })
resolve(false); .onCancel(() => {
}); resolve(false);
}); });
await axios.delete(`ACLs/${id}`); });
tableRef.value.reload(); await axios.delete(`ACLs/${id}`);
notify('ACL removed', 'positive'); tableRef.value.reload();
notify('ACL removed', 'positive');
} catch (error) {
console.error('Error deleting Acl: ', error);
}
}; };
</script> </script>

View File

@ -34,9 +34,13 @@ const refresh = () => paginateRef.value.fetch();
const navigate = (id) => router.push({ name: 'AccountSummary', params: { id } }); const navigate = (id) => router.push({ name: 'AccountSummary', params: { id } });
const killSession = async ({ userId, created }) => { const killSession = async ({ userId, created }) => {
await axios.post(`${urlPath}/killSession`, { userId, created }); try {
paginateRef.value.fetch(); await axios.post(`${urlPath}/killSession`, { userId, created });
notify(t('Session killed'), 'positive'); paginateRef.value.fetch();
notify(t('Session killed'), 'positive');
} catch (error) {
console.error('Error killing session', error);
}
}; };
</script> </script>

View File

@ -40,8 +40,12 @@ const formUrlCreate = ref(null);
const formUrlUpdate = ref(null); const formUrlUpdate = ref(null);
const formCustomFn = ref(null); const formCustomFn = ref(null);
const onTestConection = async () => { const onTestConection = async () => {
await axios.get(`LdapConfigs/test`); try {
notify(t('LDAP connection established!'), 'positive'); await axios.get(`LdapConfigs/test`);
notify(t('LDAP connection established!'), 'positive');
} catch (error) {
console.error('Error testing connection', error);
}
}; };
const getInitialLdapConfig = async () => { const getInitialLdapConfig = async () => {
try { try {
@ -68,10 +72,14 @@ const getInitialLdapConfig = async () => {
} }
}; };
const deleteMailForward = async () => { const deleteMailForward = async () => {
await axios.delete(URL_UPDATE); try {
initialData.value = { ...DEFAULT_DATA }; await axios.delete(URL_UPDATE);
hasData.value = false; initialData.value = { ...DEFAULT_DATA };
notify(t('globals.dataSaved'), 'positive'); hasData.value = false;
notify(t('globals.dataSaved'), 'positive');
} catch (err) {
console.error('Error deleting mail forward', err);
}
}; };
onMounted(async () => await getInitialLdapConfig()); onMounted(async () => await getInitialLdapConfig());

View File

@ -46,8 +46,12 @@ const formUrlUpdate = ref(null);
const formCustomFn = ref(null); const formCustomFn = ref(null);
const onTestConection = async () => { const onTestConection = async () => {
await axios.get(`SambaConfigs/test`); try {
notify(t('Samba connection established!'), 'positive'); await axios.get(`SambaConfigs/test`);
notify(t('Samba connection established!'), 'positive');
} catch (error) {
console.error('Error testing connection', error);
}
}; };
const getInitialSambaConfig = async () => { const getInitialSambaConfig = async () => {
@ -75,10 +79,14 @@ const getInitialSambaConfig = async () => {
}; };
const deleteMailForward = async () => { const deleteMailForward = async () => {
await axios.delete(URL_UPDATE); try {
initialData.value = { ...DEFAULT_DATA }; await axios.delete(URL_UPDATE);
hasData.value = false; initialData.value = { ...DEFAULT_DATA };
notify(t('globals.dataSaved'), 'positive'); hasData.value = false;
notify(t('globals.dataSaved'), 'positive');
} catch (err) {
console.error('Error deleting mail forward', err);
}
}; };
onMounted(async () => await getInitialSambaConfig()); onMounted(async () => await getInitialSambaConfig());

View File

@ -44,9 +44,13 @@ const removeAlias = () => {
cancel: true, cancel: true,
}) })
.onOk(async () => { .onOk(async () => {
await axios.delete(`MailAliases/${entityId.value}`); try {
notify(t('Alias removed'), 'positive'); await axios.delete(`MailAliases/${entityId.value}`);
router.push({ name: 'AccountAlias' }); notify(t('Alias removed'), 'positive');
router.push({ name: 'AccountAlias' });
} catch (err) {
console.error('Error removing alias');
}
}); });
}; };
</script> </script>

View File

@ -41,22 +41,35 @@ const fetchAccountExistence = async () => {
}; };
const fetchMailForwards = async () => { const fetchMailForwards = async () => {
const response = await axios.get(`MailForwards/${route.params.id}`); try {
return response.data; const response = await axios.get(`MailForwards/${route.params.id}`);
return response.data;
} catch (err) {
console.error('Error fetching mail forwards', err);
return null;
}
}; };
const deleteMailForward = async () => { const deleteMailForward = async () => {
await axios.delete(`MailForwards/${route.params.id}`); try {
formData.value.forwardTo = null; await axios.delete(`MailForwards/${route.params.id}`);
initialData.value.forwardTo = null; formData.value.forwardTo = null;
initialData.value.hasData = hasData.value; initialData.value.forwardTo = null;
notify(t('globals.dataSaved'), 'positive'); initialData.value.hasData = hasData.value;
notify(t('globals.dataSaved'), 'positive');
} catch (err) {
console.error('Error deleting mail forward', err);
}
}; };
const updateMailForward = async () => { const updateMailForward = async () => {
await axios.patch('MailForwards', formData.value); try {
initialData.value = { ...formData.value }; await axios.patch('MailForwards', formData.value);
initialData.value.hasData = hasData.value; initialData.value = { ...formData.value };
initialData.value.hasData = hasData.value;
} catch (err) {
console.error('Error creating mail forward', err);
}
}; };
const onSubmit = async () => { const onSubmit = async () => {

View File

@ -32,8 +32,12 @@ const filter = {
where: { id: entityId }, where: { id: entityId },
}; };
const removeRole = async () => { const removeRole = async () => {
await axios.delete(`VnRoles/${entityId.value}`); try {
notify(t('Role removed'), 'positive'); await axios.delete(`VnRoles/${entityId.value}`);
notify(t('Role removed'), 'positive');
} catch (error) {
console.error('Error deleting role', error);
}
}; };
</script> </script>

View File

@ -95,7 +95,6 @@ const columns = computed(() => [
optionLabel: 'description', optionLabel: 'description',
}, },
}, },
orderBy: 'priority',
}, },
{ {
align: 'right', align: 'right',

View File

@ -167,7 +167,7 @@ const toCustomerAddressEdit = (addressId) => {
<div>{{ item.street }}</div> <div>{{ item.street }}</div>
<div> <div>
{{ item.postalCode }} - {{ item.city }}, {{ item.postalCode }} - {{ item.city }},
{{ item.province?.name }} {{ item.province.name }}
</div> </div>
<div> <div>
{{ item.phone }} {{ item.phone }}

View File

@ -106,24 +106,28 @@ const setParams = (params) => {
}; };
const getPreview = async () => { const getPreview = async () => {
const params = { try {
recipientId: entityId, const params = {
}; recipientId: entityId,
const validationMessage = validateMessage(); };
if (validationMessage) return notify(t(validationMessage), 'negative'); const validationMessage = validateMessage();
if (validationMessage) return notify(t(validationMessage), 'negative');
setParams(params); setParams(params);
const path = `${sampleType.value.model}/${entityId.value}/${sampleType.value.code}-html`; const path = `${sampleType.value.model}/${entityId.value}/${sampleType.value.code}-html`;
const { data } = await axios.get(path, { params }); const { data } = await axios.get(path, { params });
if (!data) return; if (!data) return;
quasar.dialog({ quasar.dialog({
component: CustomerSamplesPreview, component: CustomerSamplesPreview,
componentProps: { componentProps: {
htmlContent: data, htmlContent: data,
}, },
}); });
} catch (err) {
notify('Errors getting preview', 'negative');
}
}; };
const onSubmit = async () => { const onSubmit = async () => {

View File

@ -42,9 +42,13 @@ const setData = (entity) => {
}; };
const removeDepartment = async () => { const removeDepartment = async () => {
await axios.post(`/Departments/${entityId.value}/removeChild`, entityId.value); try {
router.push({ name: 'WorkerDepartment' }); await axios.post(`/Departments/${entityId.value}/removeChild`, entityId.value);
notify('department.departmentRemoved', 'positive'); router.push({ name: 'WorkerDepartment' });
notify('department.departmentRemoved', 'positive');
} catch (err) {
console.error('Error removing department');
}
}; };
const { openConfirmationModal } = useVnConfirm(); const { openConfirmationModal } = useVnConfirm();

View File

@ -236,9 +236,13 @@ const copyOriginalRowsData = (rows) => {
}; };
const saveChange = async (field, { rowIndex, row }) => { const saveChange = async (field, { rowIndex, row }) => {
if (originalRowDataCopy.value[rowIndex][field] == row[field]) return; try {
await axios.patch(`Buys/${row.id}`, row); if (originalRowDataCopy.value[rowIndex][field] == row[field]) return;
originalRowDataCopy.value[rowIndex][field] = row[field]; await axios.patch(`Buys/${row.id}`, row);
originalRowDataCopy.value[rowIndex][field] = row[field];
} catch (err) {
console.error('Error saving changes', err);
}
}; };
const openRemoveDialog = async () => { const openRemoveDialog = async () => {
@ -256,11 +260,15 @@ const openRemoveDialog = async () => {
}, },
}) })
.onOk(async () => { .onOk(async () => {
await deleteBuys(); try {
const notifyMessage = t( await deleteBuys();
`Buy${rowsSelected.value.length > 1 ? 's' : ''} deleted` const notifyMessage = t(
); `Buy${rowsSelected.value.length > 1 ? 's' : ''} deleted`
notify(notifyMessage, 'positive'); );
notify(notifyMessage, 'positive');
} catch (err) {
console.error('Error deleting buys');
}
}); });
}; };
@ -274,13 +282,17 @@ const importBuys = () => {
}; };
const toggleGroupingMode = async (buy, mode) => { const toggleGroupingMode = async (buy, mode) => {
const groupingMode = mode === 'grouping' ? mode : 'packing'; try {
const newGroupingMode = buy.groupingMode === groupingMode ? null : groupingMode; const groupingMode = mode === 'grouping' ? mode : 'packing';
const params = { const newGroupingMode = buy.groupingMode === groupingMode ? null : groupingMode;
groupingMode: newGroupingMode, const params = {
}; groupingMode: newGroupingMode,
await axios.patch(`Buys/${buy.id}`, params); };
buy.groupingMode = newGroupingMode; await axios.patch(`Buys/${buy.id}`, params);
buy.groupingMode = newGroupingMode;
} catch (err) {
console.error('Error toggling grouping mode');
}
}; };
const lockIconType = (groupingMode, mode) => { const lockIconType = (groupingMode, mode) => {

View File

@ -123,28 +123,36 @@ const fillData = async (rawData) => {
}; };
const fetchBuys = async (buys) => { const fetchBuys = async (buys) => {
const params = { buys }; try {
const { data } = await axios.post( const params = { buys };
`Entries/${route.params.id}/importBuysPreview`, const { data } = await axios.post(
params `Entries/${route.params.id}/importBuysPreview`,
); params
importData.value.buys = data; );
importData.value.buys = data;
} catch (err) {
console.error('Error fetching buys');
}
}; };
const onSubmit = async () => { const onSubmit = async () => {
const params = importData.value; try {
const hasAnyEmptyRow = params.buys.some((buy) => { const params = importData.value;
return buy.itemFk === null; const hasAnyEmptyRow = params.buys.some((buy) => {
}); return buy.itemFk === null;
});
if (hasAnyEmptyRow) { if (hasAnyEmptyRow) {
notify(t('Some of the imported buys does not have an item'), 'negative'); notify(t('Some of the imported buys does not have an item'), 'negative');
return; return;
}
await axios.post(`Entries/${route.params.id}/importBuys`, params);
notify('globals.dataSaved', 'positive');
redirectToBuysView();
} catch (err) {
console.error('Error importing buys', err);
} }
await axios.post(`Entries/${route.params.id}/importBuys`, params);
notify('globals.dataSaved', 'positive');
redirectToBuysView();
}; };
const redirectToBuysView = () => { const redirectToBuysView = () => {

View File

@ -147,9 +147,12 @@ async function setEntryData(data) {
} }
const fetchEntryBuys = async () => { const fetchEntryBuys = async () => {
try {
const { data } = await axios.get(`Entries/${entry.value.id}/getBuys`); const { data } = await axios.get(`Entries/${entry.value.id}/getBuys`);
if (data) entryBuys.value = data; if (data) entryBuys.value = data;
} catch (err) {
console.error('Error fetching entry buys');
}
}; };
</script> </script>

View File

@ -221,7 +221,7 @@ onMounted(async () => {
t('entry.list.tableVisibleColumns.isExcludedFromAvailable') t('entry.list.tableVisibleColumns.isExcludedFromAvailable')
}}</QTooltip> }}</QTooltip>
</QIcon> </QIcon>
<QIcon v-if="!!row.isRaid" name="vn:net" color="primary"> <QIcon v-if="!!row.daysInForward" name="vn:net" color="primary">
<QTooltip> <QTooltip>
{{ {{
t('globals.raid', { daysInForward: row.daysInForward }) t('globals.raid', { daysInForward: row.daysInForward })

View File

@ -30,6 +30,8 @@ const recalc = async () => {
isLoading.value = true; isLoading.value = true;
await axios.post('Applications/waste_addSales/execute-proc', params); await axios.post('Applications/waste_addSales/execute-proc', params);
notify('wasteRecalc.recalcOk', 'positive'); notify('wasteRecalc.recalcOk', 'positive');
} catch (err) {
console.error(err);
} finally { } finally {
isLoading.value = false; isLoading.value = false;
} }

View File

@ -61,18 +61,25 @@ const showSendInvoiceDialog = (type) => {
}; };
const sendEmailInvoice = async ({ address }) => { const sendEmailInvoice = async ({ address }) => {
if (!address) notify(`The email can't be empty`, 'negative'); try {
if (!address) notify(`The email can't be empty`, 'negative');
if (invoiceFormType.value === 'pdf') { if (invoiceFormType.value === 'pdf') {
return sendEmail(`InvoiceOuts/${$props.invoiceOutData.ref}/invoice-email`, { return sendEmail(`InvoiceOuts/${$props.invoiceOutData.ref}/invoice-email`, {
recipientId: $props.invoiceOutData.client.id, recipientId: $props.invoiceOutData.client.id,
recipient: address, recipient: address,
}); });
} else { } else {
return sendEmail(`InvoiceOuts/${$props.invoiceOutData.ref}/invoice-csv-email`, { return sendEmail(
recipientId: $props.invoiceOutData.client.id, `InvoiceOuts/${$props.invoiceOutData.ref}/invoice-csv-email`,
recipient: address, {
}); recipientId: $props.invoiceOutData.client.id,
recipient: address,
}
);
}
} catch (err) {
console.error('Error sending email', err);
} }
}; };
@ -81,30 +88,46 @@ const redirectToInvoiceOutList = () => {
}; };
const deleteInvoice = async () => { const deleteInvoice = async () => {
await axios.post(`InvoiceOuts/${$props.invoiceOutData.id}/delete`); try {
notify(t('InvoiceOut deleted'), 'positive'); await axios.post(`InvoiceOuts/${$props.invoiceOutData.id}/delete`);
notify(t('InvoiceOut deleted'), 'positive');
} catch (err) {
console.error('Error deleting invoice out', err);
}
}; };
const bookInvoice = async () => { const bookInvoice = async () => {
await axios.post(`InvoiceOuts/${$props.invoiceOutData.ref}/book`); try {
notify(t('InvoiceOut booked'), 'positive'); await axios.post(`InvoiceOuts/${$props.invoiceOutData.ref}/book`);
notify(t('InvoiceOut booked'), 'positive');
} catch (err) {
console.error('Error booking invoice out', err);
}
}; };
const generateInvoicePdf = async () => { const generateInvoicePdf = async () => {
await axios.post(`InvoiceOuts/${$props.invoiceOutData.id}/createPdf`); try {
notify(t('The invoice PDF document has been regenerated'), 'positive'); await axios.post(`InvoiceOuts/${$props.invoiceOutData.id}/createPdf`);
notify(t('The invoice PDF document has been regenerated'), 'positive');
} catch (err) {
console.error('Error generating invoice out pdf', err);
}
}; };
const refundInvoice = async (withWarehouse) => { const refundInvoice = async (withWarehouse) => {
const params = { ref: $props.invoiceOutData.ref, withWarehouse: withWarehouse }; try {
const { data } = await axios.post('InvoiceOuts/refund', params); const params = { ref: $props.invoiceOutData.ref, withWarehouse: withWarehouse };
location.href = window.origin + `/#/ticket/${data[0].id}/sale`; const { data } = await axios.post('InvoiceOuts/refund', params);
notify( location.href = window.origin + `/#/ticket/${data[0].id}/sale`;
t('refundInvoiceSuccessMessage', { notify(
refundTicket: data[0].id, t('refundInvoiceSuccessMessage', {
}), refundTicket: data[0].id,
'positive' }),
); 'positive'
);
} catch (err) {
console.error('Error generating invoice out pdf', err);
}
}; };
const showTransferInvoiceForm = async () => { const showTransferInvoiceForm = async () => {

View File

@ -135,10 +135,15 @@ onMounted(() => (stateStore.rightDrawer = true));
onUnmounted(() => (stateStore.rightDrawer = false)); onUnmounted(() => (stateStore.rightDrawer = false));
function openPdf(id) { function openPdf(id) {
openReport(`${MODEL}/${id}/download`); try {
openReport(`${MODEL}/${id}/download`);
} catch (err) {
console.error('Error opening PDF', err);
}
} }
function downloadPdf() { function downloadPdf() {
try {
if (selectedRows.value.size === 0) return; if (selectedRows.value.size === 0) return;
const selectedCardsArray = Array.from(selectedRows.value.values()); const selectedCardsArray = Array.from(selectedRows.value.values());
@ -157,7 +162,9 @@ function downloadPdf() {
openReport(`${MODEL}/downloadZip`, params); openReport(`${MODEL}/downloadZip`, params);
} }
} catch (err) {
console.error('Error opening PDF');
}
} }
watchEffect(selectedRows); watchEffect(selectedRows);

View File

@ -45,9 +45,13 @@ const arrayData = useArrayData('ItemShelvings', {
const rows = computed(() => arrayData.store.data || []); const rows = computed(() => arrayData.store.data || []);
const applyColumnFilter = async (col) => { const applyColumnFilter = async (col) => {
const paramKey = col.columnFilter?.filterParamKey || col.field; try {
params[paramKey] = col.columnFilter.filterValue; const paramKey = col.columnFilter?.filterParamKey || col.field;
await arrayData.addFilter({ filter: null, params }); params[paramKey] = col.columnFilter.filterValue;
await arrayData.addFilter({ filter: null, params });
} catch (err) {
console.error('Error applying column filter', err);
}
}; };
const getInputEvents = (col) => { const getInputEvents = (col) => {
@ -169,11 +173,15 @@ const totalLabels = computed(() =>
); );
const removeLines = async () => { const removeLines = async () => {
const itemShelvingIds = rowsSelected.value.map((row) => row.itemShelvingFk); try {
await axios.post('ItemShelvings/deleteItemShelvings', { itemShelvingIds }); const itemShelvingIds = rowsSelected.value.map((row) => row.itemShelvingFk);
rowsSelected.value = []; await axios.post('ItemShelvings/deleteItemShelvings', { itemShelvingIds });
notify('shelvings.shelvingsRemoved', 'positive'); rowsSelected.value = [];
await arrayData.fetch({ append: false }); notify('shelvings.shelvingsRemoved', 'positive');
await arrayData.fetch({ append: false });
} catch (err) {
console.error('Error removing lines', err);
}
}; };
onMounted(async () => { onMounted(async () => {
await arrayData.fetch({ append: false }); await arrayData.fetch({ append: false });

View File

@ -19,18 +19,22 @@ const tagOptions = ref([]);
const valueOptionsMap = ref(new Map()); const valueOptionsMap = ref(new Map());
const getSelectedTagValues = async (tag) => { const getSelectedTagValues = async (tag) => {
if (!tag.tagFk && tag.tag.isFree) return; try {
const filter = { if (!tag.tagFk && tag.tag.isFree) return;
fields: ['value'], const filter = {
order: 'value ASC', fields: ['value'],
limit: 30, order: 'value ASC',
}; limit: 30,
};
const params = { filter: JSON.stringify(filter) }; const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Tags/${tag.tagFk}/filterValue`, { const { data } = await axios.get(`Tags/${tag.tagFk}/filterValue`, {
params, params,
}); });
valueOptionsMap.value.set(tag.tagFk, data); valueOptionsMap.value.set(tag.tagFk, data);
} catch (err) {
console.error('Error getting selected tag values');
}
}; };
const onItemTagsFetched = async (itemTags) => { const onItemTagsFetched = async (itemTags) => {

View File

@ -32,13 +32,17 @@ const ItemTaxRef = ref(null);
const taxesOptions = ref([]); const taxesOptions = ref([]);
const submitTaxes = async (data) => { const submitTaxes = async (data) => {
let payload = data.map((tax) => ({ try {
id: tax.id, let payload = data.map((tax) => ({
taxClassFk: tax.taxClassFk, id: tax.id,
})); taxClassFk: tax.taxClassFk,
}));
await axios.post(`Items/updateTaxes`, payload); await axios.post(`Items/updateTaxes`, payload);
notify(t('globals.dataSaved'), 'positive'); notify(t('globals.dataSaved'), 'positive');
} catch (err) {
console.error('Error saving taxes', err);
}
}; };
</script> </script>
<template> <template>

View File

@ -221,16 +221,24 @@ const updateMinPrice = async (value, props) => {
}; };
const upsertPrice = async (props, resetMinPrice = false) => { const upsertPrice = async (props, resetMinPrice = false) => {
const { row } = props; try {
if (tableRef.value.CrudModelRef.getChanges().updates.length > 0) { const { row } = props;
if (resetMinPrice) row.hasMinPrice = 0; if (tableRef.value.CrudModelRef.getChanges().updates.length > 0) {
await upsertFixedPrice(row); if (resetMinPrice) row.hasMinPrice = 0;
await upsertFixedPrice(row);
}
} catch (err) {
console.error('Error editing price', err);
} }
}; };
async function upsertFixedPrice(row) { async function upsertFixedPrice(row) {
const { data } = await axios.patch('FixedPrices/upsertFixedPrice', row); try {
return data; const { data } = await axios.patch('FixedPrices/upsertFixedPrice', row);
return data;
} catch (err) {
console.error('Error editing price', err);
}
} }
async function saveOnRowChange(row) { async function saveOnRowChange(row) {
@ -313,10 +321,14 @@ const onEditCellDataSaved = async () => {
}; };
const removeFuturePrice = async () => { const removeFuturePrice = async () => {
rowsSelected.value.forEach(({ id }) => { try {
const rowIndex = fixedPrices.value.findIndex(({ id }) => id === id); rowsSelected.value.forEach(({ id }) => {
removePrice(id, rowIndex); const rowIndex = fixedPrices.value.findIndex(({ id }) => id === id);
}); removePrice(id, rowIndex);
});
} catch (err) {
console.error('Error removing price', err);
}
}; };
function confirmRemove(item, isFuture) { function confirmRemove(item, isFuture) {
@ -333,9 +345,13 @@ function confirmRemove(item, isFuture) {
} }
const removePrice = async (id) => { const removePrice = async (id) => {
await axios.delete(`FixedPrices/${id}`); try {
notify(t('globals.dataSaved'), 'positive'); await axios.delete(`FixedPrices/${id}`);
tableRef.value.reload({}); notify(t('globals.dataSaved'), 'positive');
tableRef.value.reload({});
} catch (err) {
console.error('Error removing price', err);
}
}; };
const dateStyle = (date) => const dateStyle = (date) =>
date date

View File

@ -55,18 +55,22 @@ const onCategoryChange = async (categoryFk, search) => {
}; };
const getSelectedTagValues = async (tag) => { const getSelectedTagValues = async (tag) => {
if (!tag?.selectedTag?.id) return; try {
tag.value = null; if (!tag?.selectedTag?.id) return;
const filter = { tag.value = null;
fields: ['value'], const filter = {
order: 'value ASC', fields: ['value'],
}; order: 'value ASC',
};
const params = { filter: JSON.stringify(filter) }; const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, { const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, {
params, params,
}); });
tag.valueOptions = data; tag.valueOptions = data;
} catch (err) {
console.error('Error getting selected tag values');
}
}; };
const applyTags = (params, search) => { const applyTags = (params, search) => {

View File

@ -173,29 +173,40 @@ const getBadgeColor = (date) => {
}; };
const changeQuantity = async (request) => { const changeQuantity = async (request) => {
if (request.saleFk) { try {
const params = { if (request.saleFk) {
quantity: request.saleQuantity, const params = {
}; quantity: request.saleQuantity,
};
await axios.patch(`Sales/${request.saleFk}`, params); await axios.patch(`Sales/${request.saleFk}`, params);
notify(t('globals.dataSaved'), 'positive'); notify(t('globals.dataSaved'), 'positive');
confirmRequest(request); confirmRequest(request);
} else confirmRequest(request); } else confirmRequest(request);
} catch (error) {
console.error('Error changing quantity:: ', error);
}
}; };
const confirmRequest = async (request) => { const confirmRequest = async (request) => {
if (request.itemFk && request.saleQuantity) { try {
const params = { if (request.itemFk && request.saleQuantity) {
itemFk: request.itemFk, const params = {
quantity: request.saleQuantity, itemFk: request.itemFk,
attenderFk: request.attenderFk, quantity: request.saleQuantity,
}; attenderFk: request.attenderFk,
};
const { data } = await axios.post(`TicketRequests/${request.id}/confirm`, params); const { data } = await axios.post(
request.itemDescription = data.concept; `TicketRequests/${request.id}/confirm`,
request.isOk = true; params
notify(t('globals.dataSaved'), 'positive'); );
request.itemDescription = data.concept;
request.isOk = true;
notify(t('globals.dataSaved'), 'positive');
}
} catch (error) {
console.error('Error confirming request:: ', error);
} }
}; };

View File

@ -103,11 +103,15 @@ const getBadgeColor = (date) => {
}; };
const removeOrders = async () => { const removeOrders = async () => {
const selectedIds = selectedRows.value.map((row) => row.id); try {
const params = { deletes: selectedIds }; const selectedIds = selectedRows.value.map((row) => row.id);
await axios.post('SalesMonitors/deleteOrders', params); const params = { deletes: selectedIds };
selectedRows.value = []; await axios.post('SalesMonitors/deleteOrders', params);
await table.value.reload(); selectedRows.value = [];
await table.value.reload();
} catch (err) {
console.error('Error deleting orders', err);
}
}; };
const openTab = (id) => const openTab = (id) =>

View File

@ -350,7 +350,7 @@ const openTab = (id) =>
class="q-mr-sm" class="q-mr-sm"
dense dense
flat flat
@click="tableRef.CrudModelRef.vnPaginateRef.update()" @click="$refs.tableRef.reload()"
> >
<QTooltip>{{ $t('globals.refresh') }}</QTooltip> <QTooltip>{{ $t('globals.refresh') }}</QTooltip>
</QBtn> </QBtn>

View File

@ -22,17 +22,22 @@ const agencyList = ref([]);
const addressList = ref([]); const addressList = ref([]);
const fetchAddressList = async (addressId) => { const fetchAddressList = async (addressId) => {
const { data } = await axios.get('addresses', { try {
params: { const { data } = await axios.get('addresses', {
filter: JSON.stringify({ params: {
fields: ['id', 'nickname', 'street', 'city'], filter: JSON.stringify({
where: { id: addressId }, fields: ['id', 'nickname', 'street', 'city'],
}), where: { id: addressId },
}, }),
}); },
addressList.value = data; });
if (addressList.value?.length === 1) { addressList.value = data;
state.get(ORDER_MODEL).addressFk = addressList.value[0].id; if (addressList.value?.length === 1) {
state.get(ORDER_MODEL).addressFk = addressList.value[0].id;
}
} catch (err) {
console.error(`Error fetching addresses`, err);
return err.response;
} }
}; };
@ -40,13 +45,18 @@ const fetchAgencyList = async (landed, addressFk) => {
if (!landed || !addressFk) { if (!landed || !addressFk) {
return; return;
} }
const { data } = await axios.get('Agencies/landsThatDay', { try {
params: { const { data } = await axios.get('Agencies/landsThatDay', {
addressFk, params: {
landed: new Date(landed).toISOString(), addressFk,
}, landed: new Date(landed).toISOString(),
}); },
agencyList.value = data; });
agencyList.value = data;
} catch (err) {
console.error(`Error fetching agencies`, err);
return err.response;
}
}; };
const fetchOrderDetails = (order) => { const fetchOrderDetails = (order) => {
@ -82,8 +92,12 @@ const orderFilter = {
}; };
const onClientChange = async (clientId) => { const onClientChange = async (clientId) => {
const { data } = await axios.get(`Clients/${clientId}`); try {
await fetchAddressList(data.defaultAddressFk); const { data } = await axios.get(`Clients/${clientId}`);
await fetchAddressList(data.defaultAddressFk);
} catch (error) {
console.error('Error al cambiar el cliente:', error);
}
}; };
</script> </script>

View File

@ -1,13 +1,14 @@
<script setup> <script setup>
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'; import { onBeforeMount, onMounted, onUnmounted, ref, computed, watch } from 'vue';
import axios from 'axios'; import axios from 'axios';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import VnPaginate from 'src/components/ui/VnPaginate.vue'; import VnPaginate from 'src/components/ui/VnPaginate.vue';
import CatalogItem from 'src/components/ui/CatalogItem.vue'; import CatalogItem from 'src/components/ui/CatalogItem.vue';
import OrderCatalogFilter from 'src/pages/Order/Card/OrderCatalogFilter.vue'; import OrderCatalogFilter from 'src/pages/Order/Card/OrderCatalogFilter.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue'; import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import getParamWhere from 'src/filters/getParamWhere';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
const route = useRoute(); const route = useRoute();
@ -17,6 +18,7 @@ const { t } = useI18n();
const dataKey = 'OrderCatalogList'; const dataKey = 'OrderCatalogList';
const arrayData = useArrayData(dataKey); const arrayData = useArrayData(dataKey);
const store = arrayData.store; const store = arrayData.store;
const showFilter = ref(null);
const tags = ref([]); const tags = ref([]);
let catalogParams = { let catalogParams = {
@ -24,6 +26,27 @@ let catalogParams = {
orderBy: JSON.stringify({ field: 'relevancy DESC, name', way: 'ASC', isTag: false }), orderBy: JSON.stringify({ field: 'relevancy DESC, name', way: 'ASC', isTag: false }),
}; };
onBeforeMount(() => {
const whereParams = getParamWhere(route);
if (whereParams) {
const formattedWhereParams = {};
if (whereParams.and) {
whereParams.and.forEach((item) => {
Object.assign(formattedWhereParams, item);
});
} else {
Object.assign(formattedWhereParams, whereParams);
}
catalogParams = {
...catalogParams,
...formattedWhereParams,
};
} else {
showFilter.value = true;
}
});
onMounted(() => { onMounted(() => {
stateStore.rightDrawer = true; stateStore.rightDrawer = true;
checkOrderConfirmation(); checkOrderConfirmation();
@ -67,7 +90,7 @@ function extractValueTags(items) {
); );
tagValue.value = resultValueTags; tagValue.value = resultValueTags;
} }
const autoLoad = computed(() => !!JSON.parse(route?.query.table ?? '{}')?.categoryFk); const autoLoad = computed(() => !!catalogParams.categoryFk);
watch( watch(
() => store.data, () => store.data,
@ -89,7 +112,7 @@ watch(
:info="t('You can search items by name or id')" :info="t('You can search items by name or id')"
/> />
<QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above> <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
<QScrollArea class="fit text-grey-8"> <QScrollArea v-if="showFilter" class="fit text-grey-8">
<OrderCatalogFilter <OrderCatalogFilter
:data-key="dataKey" :data-key="dataKey"
:tag-value="tagValue" :tag-value="tagValue"
@ -105,6 +128,8 @@ watch(
url="Orders/CatalogFilter" url="Orders/CatalogFilter"
:limit="50" :limit="50"
:user-params="catalogParams" :user-params="catalogParams"
@on-fetch="showFilter = true"
:update-router="false"
:auto-load="autoLoad" :auto-load="autoLoad"
> >
<template #body="{ rows }"> <template #body="{ rows }">

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref } from 'vue'; import { computed, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import axios from 'axios'; import axios from 'axios';
@ -8,6 +8,7 @@ import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnSelect from 'components/common/VnSelect.vue'; import VnSelect from 'components/common/VnSelect.vue';
import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue'; import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import getParamWhere from 'src/filters/getParamWhere';
import CatalogFilterValueDialog from 'src/pages/Order/Card/CatalogFilterValueDialog.vue'; import CatalogFilterValueDialog from 'src/pages/Order/Card/CatalogFilterValueDialog.vue';
import { useArrayData } from 'composables/useArrayData'; import { useArrayData } from 'composables/useArrayData';
@ -31,8 +32,11 @@ const route = useRoute();
const arrayData = useArrayData(props.dataKey); const arrayData = useArrayData(props.dataKey);
const currentParams = ref({});
const categoryList = ref(null); const categoryList = ref(null);
const selectedCategoryFk = ref(null);
const typeList = ref([]); const typeList = ref([]);
const selectedTypeFk = ref(null);
const searchByTag = ref(null); const searchByTag = ref(null);
const vnFilterPanelRef = ref(); const vnFilterPanelRef = ref();
@ -49,32 +53,50 @@ const orderWayList = ref([
const orderBySelected = ref('relevancy DESC, name'); const orderBySelected = ref('relevancy DESC, name');
const orderWaySelected = ref('ASC'); const orderWaySelected = ref('ASC');
onMounted(() => {
selectedCategoryFk.value = getParamWhere(route, 'categoryFk');
selectedTypeFk.value = getParamWhere(route, 'typeFk');
});
const resetCategory = (params, search) => { const resetCategory = (params, search) => {
selectedCategoryFk.value = null;
typeList.value = null; typeList.value = null;
params.categoryFk = null; params.categoryFk = null;
params.typeFk = null; params.typeFk = null;
arrayData.store.userFilter = null; arrayData.store.userFilter = null;
search(); removeTagGroupParam(search);
}; };
const selectCategory = async (params, category, search) => { const selectCategory = (params, category, search) => {
if (vnFilterPanelRef.value.params.categoryFk === category?.id) { if (params.categoryFk === category?.id) {
resetCategory(params, search); resetCategory(params, search);
return; return;
} }
selectedCategoryFk.value = category?.id;
params.categoryFk = category?.id;
params.typeFk = null; params.typeFk = null;
params.categoryFk = category.id; selectedTypeFk.value = null;
await loadTypes(category?.id); loadTypes(category?.id);
await search(); search();
}; };
const loadTypes = async (id) => { const loadTypes = async (categoryFk = selectedCategoryFk.value) => {
const { data } = await axios.get(`Orders/${route.params.id}/getItemTypeAvailable`, { const { data } = await axios.get(`Orders/${route.params.id}/getItemTypeAvailable`, {
params: { itemCategoryId: id }, params: { itemCategoryId: categoryFk },
}); });
typeList.value = data; typeList.value = data;
}; };
const selectedCategory = computed(() => {
return (categoryList.value || []).find(
(category) => category?.id === selectedCategoryFk.value
);
});
const selectedType = computed(() => {
return (typeList.value || []).find((type) => type?.id === selectedTypeFk.value);
});
function exprBuilder(param, value) { function exprBuilder(param, value) {
switch (param) { switch (param) {
case 'categoryFk': case 'categoryFk':
@ -100,21 +122,21 @@ const applyTags = (tagInfo, params, search) => {
async function onSearchByTag(value) { async function onSearchByTag(value) {
if (!value.target.value) return; if (!value.target.value) return;
if (!vnFilterPanelRef.value.params?.tagGroups) { if (!currentParams.value?.tagGroups) {
vnFilterPanelRef.value.params.tagGroups = []; currentParams.value.tagGroups = [];
} }
vnFilterPanelRef.value.params.tagGroups.push({ currentParams.value.tagGroups.push({
values: [{ value: value.target.value }], values: [{ value: value.target.value }],
}); });
searchByTag.value = null; searchByTag.value = null;
} }
const removeTagGroupParam = (params, search, valIndex) => { const removeTagGroupParam = (search, valIndex) => {
if (!valIndex && valIndex !== 0) { if (!valIndex && valIndex !== 0) {
params.tagGroups = null; currentParams.value.tagGroups = null;
} else { } else {
params.tagGroups.splice(valIndex, 1); currentParams.value.tagGroups.splice(valIndex, 1);
} }
}; };
@ -126,8 +148,7 @@ const setCategoryList = (data) => {
icon: `vn:${(category.icon || '').split('-')[1]}`, icon: `vn:${(category.icon || '').split('-')[1]}`,
})); }));
vnFilterPanelRef.value.params.categoryFk && selectedCategoryFk.value && loadTypes();
loadTypes(vnFilterPanelRef.value.params.categoryFk);
}; };
const getCategoryClass = (category, params) => { const getCategoryClass = (category, params) => {
@ -136,6 +157,12 @@ const getCategoryClass = (category, params) => {
} }
}; };
const clearFilter = (key) => {
if (key === 'categoryFk') {
resetCategory();
}
};
function addOrder(value, field, params) { function addOrder(value, field, params) {
let { orderBy } = params; let { orderBy } = params;
orderBy = JSON.parse(orderBy); orderBy = JSON.parse(orderBy);
@ -143,6 +170,11 @@ function addOrder(value, field, params) {
params.orderBy = JSON.stringify(orderBy); params.orderBy = JSON.stringify(orderBy);
vnFilterPanelRef.value.search(); vnFilterPanelRef.value.search();
} }
onMounted(() => {
selectedCategoryFk.value = getParamWhere(route, 'categoryFk');
selectedTypeFk.value = getParamWhere(route, 'typeFk');
});
</script> </script>
<template> <template>
@ -150,22 +182,24 @@ function addOrder(value, field, params) {
<VnFilterPanel <VnFilterPanel
ref="vnFilterPanelRef" ref="vnFilterPanelRef"
:data-key="props.dataKey" :data-key="props.dataKey"
:hidden-tags="['filter', 'orderFk', 'orderBy']" :hidden-tags="['orderFk', 'orderBy']"
:unremovable-params="['orderFk', 'orderBy']" :un-removable-params="['orderFk', 'orderBy']"
:expr-builder="exprBuilder" :expr-builder="exprBuilder"
:custom-tags="['tagGroups', 'categoryFk']" :custom-tags="['tagGroups', 'categoryFk']"
:redirect="false" :redirect="false"
@remove="clearFilter"
v-model="currentParams"
> >
<template #tags="{ tag, formatFn }"> <template #tags="{ tag, formatFn }">
<strong v-if="tag.label === 'typeFk' && typeList"> <strong v-if="tag.label === 'typeFk'">
{{ t(typeList.find((t) => t.id == tag.value)?.name || '') }} {{ t(selectedType?.name || '') }}
</strong> </strong>
<div v-else class="q-gutter-x-xs"> <div v-else class="q-gutter-x-xs">
<strong>{{ t(`params.${tag.label}`) }}: </strong> <strong>{{ t(`params.${tag.label}`) }}: </strong>
<span>{{ formatFn(tag.value) }}</span> <span>{{ formatFn(tag.value) }}</span>
</div> </div>
</template> </template>
<template #customTags="{ params, tags: customTags, searchFn }"> <template #customTags="{ tags: customTags, params, searchFn }">
<template v-for="customTag in customTags" :key="customTag.label"> <template v-for="customTag in customTags" :key="customTag.label">
<VnFilterPanelChip <VnFilterPanelChip
v-for="(tag, valIndex) in Array.isArray(customTag.value) v-for="(tag, valIndex) in Array.isArray(customTag.value)
@ -176,16 +210,11 @@ function addOrder(value, field, params) {
@remove=" @remove="
customTag.label === 'categoryFk' customTag.label === 'categoryFk'
? resetCategory(params, searchFn) ? resetCategory(params, searchFn)
: removeTagGroupParam(params, searchFn, valIndex) : removeTagGroupParam(searchFn, valIndex)
" "
> >
<strong v-if="customTag.label === 'categoryFk' && categoryList"> <strong v-if="customTag.label === 'categoryFk'">
{{ {{ t(selectedCategory?.name || '') }}
t(
categoryList.find((c) => c.id == customTag.value)?.name ||
''
)
}}
</strong> </strong>
<strong v-if="tag?.tagSelection?.name" class="q-mr-xs"> <strong v-if="tag?.tagSelection?.name" class="q-mr-xs">
{{ tag.tagSelection.name }}: {{ tag.tagSelection.name }}:
@ -232,8 +261,13 @@ function addOrder(value, field, params) {
emit-value emit-value
use-input use-input
sort-by="name ASC" sort-by="name ASC"
:disable="!params.categoryFk" :disable="!selectedCategoryFk"
@update:model-value="searchFn()" @update:model-value="
(value) => {
selectedTypeFk = value;
searchFn();
}
"
> >
<template #option="{ itemProps, opt }"> <template #option="{ itemProps, opt }">
<QItem v-bind="itemProps"> <QItem v-bind="itemProps">
@ -303,7 +337,7 @@ function addOrder(value, field, params) {
style="display: inline-block" style="display: inline-block"
:tags="tags" :tags="tags"
@apply-tags=" @apply-tags="
($event) => applyTags($event, params, searchFn) ($event) => applyTags($event, currentParams, searchFn)
" "
/> />
</QPopupProxy> </QPopupProxy>

View File

@ -20,17 +20,22 @@ const addressList = ref([]);
defineEmits(['confirm', ...useDialogPluginComponent.emits]); defineEmits(['confirm', ...useDialogPluginComponent.emits]);
const fetchAddressList = async (addressId) => { const fetchAddressList = async (addressId) => {
const { data } = await axios.get('addresses', { try {
params: { const { data } = await axios.get('addresses', {
filter: JSON.stringify({ params: {
fields: ['id', 'nickname', 'street', 'city'], filter: JSON.stringify({
where: { id: addressId }, fields: ['id', 'nickname', 'street', 'city'],
}), where: { id: addressId },
}, }),
}); },
addressList.value = data; });
if (addressList.value?.length === 1) { addressList.value = data;
state.get(ORDER_MODEL).addressId = addressList.value[0].id; if (addressList.value?.length === 1) {
state.get(ORDER_MODEL).addressId = addressList.value[0].id;
}
} catch (err) {
console.error(`Error fetching addresses`, err);
return err.response;
} }
}; };
@ -38,13 +43,18 @@ const fetchAgencyList = async (landed, addressFk) => {
if (!landed || !addressFk) { if (!landed || !addressFk) {
return; return;
} }
const { data } = await axios.get('Agencies/landsThatDay', { try {
params: { const { data } = await axios.get('Agencies/landsThatDay', {
addressFk, params: {
landed: new Date(landed).toISOString(), addressFk,
}, landed: new Date(landed).toISOString(),
}); },
agencyList.value = data; });
agencyList.value = data;
} catch (err) {
console.error(`Error fetching agencies`, err);
return err.response;
}
}; };
const $props = defineProps({ const $props = defineProps({
@ -60,8 +70,12 @@ const initialFormState = reactive({
}); });
const onClientChange = async (clientId = $props.clientFk) => { const onClientChange = async (clientId = $props.clientFk) => {
const { data } = await axios.get(`Clients/${clientId}`); try {
await fetchAddressList(data.defaultAddressFk); const { data } = await axios.get(`Clients/${clientId}`);
await fetchAddressList(data.defaultAddressFk);
} catch (error) {
console.error('Error al cambiar el cliente:', error);
}
}; };
async function onDataSaved(_, id) { async function onDataSaved(_, id) {

View File

@ -47,13 +47,17 @@ const onChangesSaved = () => {
}; };
const setWireTransfer = async () => { const setWireTransfer = async () => {
const params = { try {
id: route.params.id, const params = {
payMethodFk: wireTransferFk.value, id: route.params.id,
}; payMethodFk: wireTransferFk.value,
};
await axios.patch(`Suppliers/${route.params.id}`, params); await axios.patch(`Suppliers/${route.params.id}`, params);
notify('globals.dataSaved', 'positive'); notify('globals.dataSaved', 'positive');
} catch (err) {
console.error('Error setting wire transfer', err);
}
}; };
</script> </script>
<template> <template>

View File

@ -33,7 +33,6 @@ const canEditZone = useAcl().hasAny([
const agencyFetchRef = ref(); const agencyFetchRef = ref();
const warehousesOptions = ref([]); const warehousesOptions = ref([]);
const companiesOptions = ref([]); const companiesOptions = ref([]);
const currenciesOptions = ref([]);
const agenciesOptions = ref([]); const agenciesOptions = ref([]);
const zonesOptions = ref([]); const zonesOptions = ref([]);
const addresses = ref([]); const addresses = ref([]);

View File

@ -49,7 +49,13 @@ async function handleSave() {
<template> <template>
<FetchData <FetchData
@on-fetch="(data) => (observationTypes = data)" @on-fetch="
(data) =>
(observationTypes = data.map((type) => {
type.label = t(`ticketNotes.observationTypes.${type.description}`);
return type;
}))
"
auto-load auto-load
url="ObservationTypes" url="ObservationTypes"
/> />
@ -76,7 +82,7 @@ async function handleSave() {
:label="t('ticketNotes.observationType')" :label="t('ticketNotes.observationType')"
:options="observationTypes" :options="observationTypes"
hide-selected hide-selected
option-label="description" option-label="label"
option-value="id" option-value="id"
v-model="row.observationTypeFk" v-model="row.observationTypeFk"
:disable="!!row.id" :disable="!!row.id"

View File

@ -172,9 +172,13 @@ const getRequestState = (state) => {
const isEditable = (isOk) => isOk !== null; const isEditable = (isOk) => isOk !== null;
async function removeLine(id) { async function removeLine(id) {
await axios.delete(`TicketRequests/${id}`); try {
notify(t('globals.dataSaved'), 'positive'); await axios.delete(`TicketRequests/${id}`);
location.reload(); notify(t('globals.dataSaved'), 'positive');
location.reload();
} catch (err) {
console.error('Error ', err);
}
} }
onMounted(() => (stateStore.rightDrawer = false)); onMounted(() => (stateStore.rightDrawer = false));

View File

@ -156,11 +156,15 @@ const columns = computed(() => [
]); ]);
const getConfig = async () => { const getConfig = async () => {
let filter = { try {
fields: ['daysForWarningClaim'], let filter = {
}; fields: ['daysForWarningClaim'],
const { data } = await axios.get(`TicketConfigs`, { filter }); };
ticketConfig.value = data; const { data } = await axios.get(`TicketConfigs`, { filter });
ticketConfig.value = data;
} catch (err) {
console.error('Error getting ticket config', err);
}
}; };
const onSalesFetched = (salesData) => { const onSalesFetched = (salesData) => {
@ -183,33 +187,41 @@ const resetChanges = async () => {
}; };
const updateQuantity = async (sale) => { const updateQuantity = async (sale) => {
const payload = { quantity: sale.quantity }; try {
await axios.post(`Sales/${sale.id}/updateQuantity`, payload); const payload = { quantity: sale.quantity };
notify('globals.dataSaved', 'positive'); await axios.post(`Sales/${sale.id}/updateQuantity`, payload);
notify('globals.dataSaved', 'positive');
} catch (err) {
console.error('Error updating quantity', err);
}
}; };
const addSale = async (sale) => { const addSale = async (sale) => {
const payload = { try {
barcode: sale.itemFk, const payload = {
quantity: sale.quantity, barcode: sale.itemFk,
}; quantity: sale.quantity,
};
const { data } = await axios.post(`tickets/${route.params.id}/addSale`, payload); const { data } = await axios.post(`tickets/${route.params.id}/addSale`, payload);
if (!data) return; if (!data) return;
const newSale = data; const newSale = data;
sale.id = newSale.id; sale.id = newSale.id;
sale.image = newSale.item.image; sale.image = newSale.item.image;
sale.subName = newSale.item.subName; sale.subName = newSale.item.subName;
sale.concept = newSale.concept; sale.concept = newSale.concept;
sale.quantity = newSale.quantity; sale.quantity = newSale.quantity;
sale.discount = newSale.discount; sale.discount = newSale.discount;
sale.price = newSale.price; sale.price = newSale.price;
sale.item = newSale.item; sale.item = newSale.item;
notify('globals.dataSaved', 'positive'); notify('globals.dataSaved', 'positive');
window.location.reload(); window.location.reload();
} catch (err) {
console.error('Error adding sale', err);
}
}; };
const changeQuantity = async (sale) => { const changeQuantity = async (sale) => {
@ -228,9 +240,13 @@ const changeQuantity = async (sale) => {
const updateConcept = async (sale) => { const updateConcept = async (sale) => {
canProceed.value = await isSalePrepared(sale); canProceed.value = await isSalePrepared(sale);
if (!canProceed.value) return; if (!canProceed.value) return;
const data = { newConcept: sale.concept }; try {
await axios.post(`Sales/${sale.id}/updateConcept`, data); const data = { newConcept: sale.concept };
notify('globals.dataSaved', 'positive'); await axios.post(`Sales/${sale.id}/updateConcept`, data);
notify('globals.dataSaved', 'positive');
} catch (err) {
console.error('Error updating concept', err);
}
}; };
const DEFAULT_EDIT = { const DEFAULT_EDIT = {
@ -286,15 +302,18 @@ const onOpenEditDiscountPopover = async (sale) => {
const updatePrice = async (sale) => { const updatePrice = async (sale) => {
canProceed.value = await isSalePrepared(sale); canProceed.value = await isSalePrepared(sale);
if (!canProceed.value) return; if (!canProceed.value) return;
const newPrice = edit.value.price; try {
if (newPrice != null && newPrice != sale.price) { const newPrice = edit.value.price;
await axios.post(`Sales/${sale.id}/updatePrice`, { newPrice }); if (newPrice != null && newPrice != sale.price) {
sale.price = newPrice; await axios.post(`Sales/${sale.id}/updatePrice`, { newPrice });
edit.value = { ...DEFAULT_EDIT }; sale.price = newPrice;
notify('globals.dataSaved', 'positive'); edit.value = { ...DEFAULT_EDIT };
notify('globals.dataSaved', 'positive');
}
await getMana();
} catch (err) {
console.error('Error updating price', err);
} }
await getMana();
}; };
const changeDiscount = async (sale) => { const changeDiscount = async (sale) => {
@ -341,11 +360,15 @@ const getNewPrice = computed(() => {
}); });
const newOrderFromTicket = async () => { const newOrderFromTicket = async () => {
const { data } = await axios.post(`Orders/newFromTicket`, { try {
ticketFk: Number(route.params.id), const { data } = await axios.post(`Orders/newFromTicket`, {
}); ticketFk: Number(route.params.id),
const routeData = router.resolve({ name: 'OrderCatalog', params: { id: data } }); });
window.open(routeData.href, '_blank'); const routeData = router.resolve({ name: 'OrderCatalog', params: { id: data } });
window.open(routeData.href, '_blank');
} catch (err) {
console.error('Error creating new order', err);
}
}; };
const goToLog = (saleId) => { const goToLog = (saleId) => {
@ -360,11 +383,15 @@ const goToLog = (saleId) => {
}; };
const changeTicketState = async (val) => { const changeTicketState = async (val) => {
stateBtnDropdownRef.value.hide(); try {
const params = { ticketFk: route.params.id, code: val }; stateBtnDropdownRef.value.hide();
await axios.post('Tickets/state', params); const params = { ticketFk: route.params.id, code: val };
notify('globals.dataSaved', 'positive'); await axios.post('Tickets/state', params);
await resetChanges(); notify('globals.dataSaved', 'positive');
await resetChanges();
} catch (err) {
console.error('Error changing ticket state', err);
}
}; };
const removeSelectedSales = () => { const removeSelectedSales = () => {
@ -375,34 +402,47 @@ const removeSelectedSales = () => {
}; };
const removeSales = async () => { const removeSales = async () => {
const params = { try {
sales: selectedRows.value.filter((sale) => sale.id), const params = {
ticketId: store.data.id, sales: selectedRows.value.filter((sale) => sale.id),
}; ticketId: store.data.id,
selectedRows.value };
.filter((sale) => !sale.id) selectedRows.value
.forEach((sale) => tableRef.value.CrudModelRef.formData.splice(sale.$index, 1)); .filter((sale) => !sale.id)
.forEach((sale) =>
tableRef.value.CrudModelRef.formData.splice(sale.$index, 1)
);
if (params.sales.length == 0) return; if (params.sales.length == 0) return;
await axios.post('Sales/deleteSales', params); await axios.post('Sales/deleteSales', params);
removeSelectedSales(); removeSelectedSales();
notify('globals.dataSaved', 'positive'); notify('globals.dataSaved', 'positive');
window.location.reload(); window.location.reload();
} catch (err) {
console.error('Error deleting sales', err);
}
}; };
const setTransferParams = async () => { const setTransferParams = async () => {
selectedSales.value = selectedValidSales.value; try {
const checkedSales = JSON.parse(JSON.stringify(selectedSales.value)); selectedSales.value = selectedValidSales.value;
transfer.value = { const checkedSales = JSON.parse(JSON.stringify(selectedSales.value));
lastActiveTickets: [], transfer.value = {
sales: checkedSales, lastActiveTickets: [],
}; sales: checkedSales,
};
const params = { ticketId: store.data.id }; const params = { ticketId: store.data.id };
const { data } = await axios.get(`clients/${store.data.clientFk}/lastActiveTickets`, { const { data } = await axios.get(
params, `clients/${store.data.clientFk}/lastActiveTickets`,
}); {
transfer.value.lastActiveTickets = data; params,
}
);
transfer.value.lastActiveTickets = data;
} catch (err) {
console.error('Error setting transfer params', err);
}
}; };
onMounted(async () => { onMounted(async () => {

View File

@ -140,9 +140,13 @@ const createClaim = () => {
}; };
const onCreateClaimAccepted = async () => { const onCreateClaimAccepted = async () => {
const params = { ticketId: ticket.value.id, sales: props.sales }; try {
const { data } = await axios.post(`Claims/createFromSales`, params); const params = { ticketId: ticket.value.id, sales: props.sales };
push({ name: 'ClaimBasicData', params: { id: data.id } }); const { data } = await axios.post(`Claims/createFromSales`, params);
push({ name: 'ClaimBasicData', params: { id: data.id } });
} catch (error) {
console.error('Error creating claim: ', error);
}
}; };
const setReserved = async (reserved) => { const setReserved = async (reserved) => {

View File

@ -69,15 +69,19 @@ function isEditable() {
} }
async function changeState(value) { async function changeState(value) {
stateBtnDropdownRef.value?.hide(); try {
const formData = { stateBtnDropdownRef.value?.hide();
ticketFk: entityId.value, const formData = {
code: value, ticketFk: entityId.value,
}; code: value,
await axios.post(`Tickets/state`, formData); };
notify('globals.dataSaved', 'positive'); await axios.post(`Tickets/state`, formData);
summaryRef.value?.fetch(); notify('globals.dataSaved', 'positive');
descriptorData.fetch({}); summaryRef.value?.fetch();
descriptorData.fetch({});
} catch (err) {
console.error('Error changing ticket state', err);
}
} }
function toTicketUrl(section) { function toTicketUrl(section) {
@ -276,8 +280,13 @@ function toTicketUrl(section) {
" "
> >
<span class="label" style="margin-right: 4px"> <span class="label" style="margin-right: 4px">
({{ item.observationType.description }}): ({{
t(
`ticketNotes.observationTypes.${item.observationType.description}`
)
}}):
</span> </span>
<span>{{ item.description }}</span> <span>{{ item.description }}</span>
</QItem> </QItem>
</QVirtualScroll> </QVirtualScroll>

View File

@ -37,37 +37,46 @@ onBeforeMount(async () => {
}); });
const fetchClient = async (formData) => { const fetchClient = async (formData) => {
const filter = { try {
include: { const filter = {
relation: 'defaultAddress', include: {
scope: { relation: 'defaultAddress',
fields: ['id', 'agencyModeFk'], scope: {
fields: ['id', 'agencyModeFk'],
},
}, },
}, where: { id: formData.clientId },
where: { id: formData.clientId }, };
}; const params = { filter: JSON.stringify(filter) };
const params = { filter: JSON.stringify(filter) }; const { data } = await axios.get('Clients', { params });
const { data } = await axios.get('Clients', { params }); const [client] = data;
const [client] = data; selectedClient.value = client;
selectedClient.value = client; } catch (err) {
console.error('Error fetching client');
}
}; };
const fetchAddresses = async (formData) => { const fetchAddresses = async (formData) => {
if (!formData.clientId) return; try {
if (!formData.clientId) return;
const filter = { const filter = {
fields: ['nickname', 'street', 'city', 'id'], fields: ['nickname', 'street', 'city', 'id'],
where: { isActive: true }, where: { isActive: true },
order: 'nickname ASC', order: 'nickname ASC',
}; };
const params = { filter: JSON.stringify(filter) }; const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Clients/${formData.clientId}/addresses`, { const { data } = await axios.get(`Clients/${formData.clientId}/addresses`, {
params, params,
}); });
addressesOptions.value = data; addressesOptions.value = data;
const { defaultAddress } = selectedClient.value; const { defaultAddress } = selectedClient.value;
formData.addressId = defaultAddress.id; formData.addressId = defaultAddress.id;
} catch (err) {
console.error(`Error fetching addresses`, err);
return err.response;
}
}; };
const onClientSelected = async (formData) => { const onClientSelected = async (formData) => {

View File

@ -37,37 +37,46 @@ onBeforeMount(async () => {
}); });
const fetchClient = async (formData) => { const fetchClient = async (formData) => {
const filter = { try {
include: { const filter = {
relation: 'defaultAddress', include: {
scope: { relation: 'defaultAddress',
fields: ['id', 'agencyModeFk'], scope: {
fields: ['id', 'agencyModeFk'],
},
}, },
}, where: { id: formData.clientId },
where: { id: formData.clientId }, };
}; const params = { filter: JSON.stringify(filter) };
const params = { filter: JSON.stringify(filter) }; const { data } = await axios.get('Clients', { params });
const { data } = await axios.get('Clients', { params }); const [client] = data;
const [client] = data; selectedClient.value = client;
selectedClient.value = client; } catch (err) {
console.error('Error fetching client');
}
}; };
const fetchAddresses = async (formData) => { const fetchAddresses = async (formData) => {
if (!formData.clientId) return; try {
if (!formData.clientId) return;
const filter = { const filter = {
fields: ['nickname', 'street', 'city', 'id'], fields: ['nickname', 'street', 'city', 'id'],
where: { isActive: true }, where: { isActive: true },
order: 'nickname ASC', order: 'nickname ASC',
}; };
const params = { filter: JSON.stringify(filter) }; const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Clients/${formData.clientId}/addresses`, { const { data } = await axios.get(`Clients/${formData.clientId}/addresses`, {
params, params,
}); });
addressesOptions.value = data; addressesOptions.value = data;
const { defaultAddress } = selectedClient.value; const { defaultAddress } = selectedClient.value;
formData.addressId = defaultAddress.id; formData.addressId = defaultAddress.id;
} catch (err) {
console.error(`Error fetching addresses`, err);
return err.response;
}
}; };
const onClientSelected = async (formData) => { const onClientSelected = async (formData) => {

View File

@ -68,9 +68,13 @@ const params = reactive({
}); });
const applyColumnFilter = async (col) => { const applyColumnFilter = async (col) => {
const paramKey = col.columnFilter?.filterParamKey || col.field; try {
params[paramKey] = col.columnFilter.filterValue; const paramKey = col.columnFilter?.filterParamKey || col.field;
await arrayData.addFilter({ params }); params[paramKey] = col.columnFilter.filterValue;
await arrayData.addFilter({ params });
} catch (err) {
console.error('Error applying column filter', err);
}
}; };
const getInputEvents = (col) => { const getInputEvents = (col) => {
@ -244,19 +248,23 @@ const totalPriceColor = (totalWithVat) =>
isLessThan50(totalWithVat) ? 'warning' : 'transparent'; isLessThan50(totalWithVat) ? 'warning' : 'transparent';
const moveTicketsFuture = async () => { const moveTicketsFuture = async () => {
const ticketsToMove = selectedTickets.value.map((ticket) => ({ try {
originId: ticket.id, const ticketsToMove = selectedTickets.value.map((ticket) => ({
destinationId: ticket.futureId, originId: ticket.id,
originShipped: ticket.shipped, destinationId: ticket.futureId,
destinationShipped: ticket.futureShipped, originShipped: ticket.shipped,
workerFk: ticket.workerFk, destinationShipped: ticket.futureShipped,
})); workerFk: ticket.workerFk,
}));
let params = { tickets: ticketsToMove }; let params = { tickets: ticketsToMove };
await axios.post('Tickets/merge', params); await axios.post('Tickets/merge', params);
notify(t('advanceTickets.moveTicketSuccess'), 'positive'); notify(t('advanceTickets.moveTicketSuccess'), 'positive');
selectedTickets.value = []; selectedTickets.value = [];
arrayData.fetch({ append: false }); arrayData.fetch({ append: false });
} catch (error) {
console.error('Error moving tickets to future', error);
}
}; };
onMounted(async () => { onMounted(async () => {
await arrayData.fetch({ append: false }); await arrayData.fetch({ append: false });

View File

@ -254,40 +254,46 @@ const fetchAvailableAgencies = async (formData) => {
}; };
const fetchClient = async (formData) => { const fetchClient = async (formData) => {
const filter = { try {
include: { const filter = {
relation: 'defaultAddress', include: {
scope: { relation: 'defaultAddress',
fields: ['id', 'agencyModeFk'], scope: {
fields: ['id', 'agencyModeFk'],
},
}, },
}, where: { id: formData.clientId },
where: { id: formData.clientId }, };
}; const params = { filter: JSON.stringify(filter) };
const params = { filter: JSON.stringify(filter) }; const { data } = await axios.get('Clients', { params });
const { data } = await axios.get('Clients', { params }); const [client] = data;
const [client] = data; selectedClient.value = client;
selectedClient.value = client; } catch (err) {
console.error('Error fetching client');
}
}; };
const fetchAddresses = async (formData) => { const fetchAddresses = async (formData) => {
if (!formData.clientId) return; try {
if (!formData.clientId) return;
const filter = { const filter = {
fields: ['nickname', 'street', 'city', 'id', 'isActive'], fields: ['nickname', 'street', 'city', 'id', 'isActive'],
order: 'nickname ASC', order: 'nickname ASC',
}; };
const params = { filter: JSON.stringify(filter) }; const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Clients/${formData.clientId}/addresses`, { const { data } = await axios.get(`Clients/${formData.clientId}/addresses`, {
params, params,
}); });
addressesOptions.value = data; addressesOptions.value = data;
addressesOptions.value = data; const { defaultAddress } = selectedClient.value;
formData.addressId = defaultAddress.id;
const { defaultAddress } = selectedClient.value; } catch (err) {
formData.addressId = defaultAddress.id; console.error(`Error fetching addresses`, err);
return err.response;
}
}; };
const getColor = (row) => { const getColor = (row) => {
if (row.alertLevelCode === 'OK') return 'bg-success'; if (row.alertLevelCode === 'OK') return 'bg-success';
else if (row.alertLevelCode === 'FREE') return 'bg-notice'; else if (row.alertLevelCode === 'FREE') return 'bg-notice';

View File

@ -153,16 +153,24 @@ const columns = computed(() => [
]); ]);
const deleteWeekly = async (ticketFk) => { const deleteWeekly = async (ticketFk) => {
await axios.delete(`TicketWeeklies/${ticketFk}`); try {
notify(t('globals.dataSaved'), 'positive'); await axios.delete(`TicketWeeklies/${ticketFk}`);
const ticketIndex = store.data.findIndex((e) => e.ticketFk == ticketFk); notify(t('globals.dataSaved'), 'positive');
store.data.splice(ticketIndex, 1); const ticketIndex = store.data.findIndex((e) => e.ticketFk == ticketFk);
location.reload(); store.data.splice(ticketIndex, 1);
location.reload();
} catch (err) {
console.error('Error deleting weekly', err);
}
}; };
const onUpdate = async (ticketFk, field, value) => { const onUpdate = async (ticketFk, field, value) => {
const params = { ticketFk, [field]: value }; try {
await axios.patch('TicketWeeklies', params); const params = { ticketFk, [field]: value };
await axios.patch('TicketWeeklies', params);
} catch (err) {
console.error('Error updating weekly', err);
}
}; };
onMounted(async () => { onMounted(async () => {

View File

@ -10,6 +10,16 @@ ticketNotes:
observationType: Observation type observationType: Observation type
removeNote: Remove note removeNote: Remove note
addNote: Add note addNote: Add note
observationTypes:
ItemPicker: Item picker
Packager: Packager
Delivery: Delivery
SalesPerson: Sales person
Administrative: Administrative
Weight: Weight
InvoiceOut: Invoice Out
DropOff: Drop Off
Sustitución: Sustitution
ticketSale: ticketSale:
visible: Visible visible: Visible
available: Available available: Available

View File

@ -19,6 +19,18 @@ ticketNotes:
observationType: Tipo de observación observationType: Tipo de observación
removeNote: Quitar nota removeNote: Quitar nota
addNote: Añadir nota addNote: Añadir nota
observationTypes:
ItemPicker: Sacador
Packager: Encajador
Delivery: Envío
SalesPerson: Comercial
Administrative: Administrativa
Weight: Peso
InvoiceOut: Facturas
DropOff: Despacho
Sustitución: Sustitución
Accepted: Aceptado
Denied: Denegado
purchaseRequest: purchaseRequest:
requester: Solicitante requester: Solicitante
atender: Comprador atender: Comprador

View File

@ -21,7 +21,12 @@ const agenciesOptions = ref([]);
@on-fetch="(data) => (agenciesOptions = data)" @on-fetch="(data) => (agenciesOptions = data)"
auto-load auto-load
/> />
<FormModel :url-update="`Travels/${route.params.id}`" model="Travel" auto-load> <FormModel
:url="`Travels/${route.params.id}`"
:url-update="`Travels/${route.params.id}`"
model="Travel"
auto-load
>
<template #form="{ data }"> <template #form="{ data }">
<VnRow> <VnRow>
<VnInput v-model="data.ref" :label="t('globals.reference')" /> <VnInput v-model="data.ref" :label="t('globals.reference')" />
@ -73,7 +78,6 @@ const agenciesOptions = ref([]);
</VnInput> </VnInput>
</VnRow> </VnRow>
<VnRow> <VnRow>
<QCheckbox v-model="data.isRaid" :label="t('travel.basicData.isRaid')" />
<QCheckbox <QCheckbox
:label="t('travel.summary.delivered')" :label="t('travel.summary.delivered')"
v-model="data.isDelivered" v-model="data.isDelivered"
@ -89,7 +93,7 @@ const agenciesOptions = ref([]);
<i18n> <i18n>
es: es:
raidDays: Si se marca "Redada", la fecha de entrega se moverá automáticamente los días indicados (incluido 0). Si se deja vacio, la fecha no cambiará raidDays: Al rellenarlo, generamos una redada. Indica los días que un travel se moverá automáticamente en el tiempo
en: en:
raidDays: If "Raid" is checked, the landing date will automatically shift by the specified number of days (including 0). If left empty, the date will stay the same. raidDays: When filling, a raid is generated. Enter the number of days the travel will automatically forward in time
</i18n> </i18n>

View File

@ -1,7 +1,34 @@
<script setup> <script setup>
import VnCard from 'components/common/VnCard.vue'; import VnCard from 'components/common/VnCard.vue';
import TravelDescriptor from './TravelDescriptor.vue'; import TravelDescriptor from './TravelDescriptor.vue';
import filter from './TravelFilter.js';
const filter = {
fields: [
'id',
'ref',
'shipped',
'landed',
'totalEntries',
'warehouseInFk',
'warehouseOutFk',
'cargoSupplierFk',
'agencyModeFk',
],
include: [
{
relation: 'warehouseIn',
scope: {
fields: ['name'],
},
},
{
relation: 'warehouseOut',
scope: {
fields: ['name'],
},
},
],
};
</script> </script>
<template> <template>
<VnCard <VnCard

View File

@ -7,7 +7,6 @@ import CardDescriptor from 'components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import useCardDescription from 'src/composables/useCardDescription'; import useCardDescription from 'src/composables/useCardDescription';
import TravelDescriptorMenuItems from './TravelDescriptorMenuItems.vue'; import TravelDescriptorMenuItems from './TravelDescriptorMenuItems.vue';
import filter from './TravelFilter.js';
import { toDate } from 'src/filters'; import { toDate } from 'src/filters';
@ -22,6 +21,35 @@ const $props = defineProps({
const route = useRoute(); const route = useRoute();
const { t } = useI18n(); const { t } = useI18n();
const filter = {
fields: [
'id',
'ref',
'shipped',
'landed',
'totalEntries',
'warehouseInFk',
'warehouseOutFk',
'cargoSupplierFk',
'agencyModeFk',
'daysInForward',
],
include: [
{
relation: 'warehouseIn',
scope: {
fields: ['name'],
},
},
{
relation: 'warehouseOut',
scope: {
fields: ['name'],
},
},
],
};
const entityId = computed(() => { const entityId = computed(() => {
return $props.id || route.params.id; return $props.id || route.params.id;
}); });
@ -37,7 +65,7 @@ const setData = (entity) => (data.value = useCardDescription(entity.ref, entity.
:title="data.title" :title="data.title"
:subtitle="data.subtitle" :subtitle="data.subtitle"
:filter="filter" :filter="filter"
data-key="Travel" data-key="travelData"
@on-fetch="setData" @on-fetch="setData"
> >
<template #menu="{ entity }"> <template #menu="{ entity }">
@ -52,7 +80,12 @@ const setData = (entity) => (data.value = useCardDescription(entity.ref, entity.
</template> </template>
<template #icons="{ entity }"> <template #icons="{ entity }">
<QCardActions class="q-gutter-x-md"> <QCardActions class="q-gutter-x-md">
<QIcon v-if="entity.isRaid" name="vn:net" color="primary" size="xs"> <QIcon
v-if="entity.daysInForward"
name="vn:net"
color="primary"
size="xs"
>
<QTooltip> <QTooltip>
{{ {{
t('globals.raid', { daysInForward: entity.daysInForward }) t('globals.raid', { daysInForward: entity.daysInForward })

View File

@ -32,12 +32,16 @@ const cloneTravel = () => {
}; };
const cloneTravelWithEntries = async () => { const cloneTravelWithEntries = async () => {
const { data } = await axios.post(`Travels/${$props.travel.id}/cloneWithEntries`); try {
notify('globals.dataSaved', 'positive'); const { data } = await axios.post(`Travels/${$props.travel.id}/cloneWithEntries`);
router.push({ name: 'TravelBasicData', params: { id: data.id } }); notify('globals.dataSaved', 'positive');
router.push({ name: 'TravelBasicData', params: { id: data.id } });
} catch (err) {
console.error('Error cloning travel with entries');
}
}; };
const canDelete = computed(() => useAcl().hasAny('Travel', '*', 'WRITE')); const canDelete = computed(() => useAcl().hasAny('Travel','*','WRITE'));
const openDeleteEntryDialog = (id) => { const openDeleteEntryDialog = (id) => {
quasar quasar
@ -54,9 +58,13 @@ const openDeleteEntryDialog = (id) => {
}; };
const deleteTravel = async (id) => { const deleteTravel = async (id) => {
await axios.delete(`Travels/${id}`); try {
router.push({ name: 'TravelList' }); await axios.delete(`Travels/${id}`);
notify('globals.dataDeleted', 'positive'); router.push({ name: 'TravelList' });
notify('globals.dataDeleted', 'positive');
} catch (err) {
console.error('Error deleting travel');
}
}; };
</script> </script>

View File

@ -1,29 +0,0 @@
export default {
fields: [
'id',
'ref',
'shipped',
'landed',
'totalEntries',
'warehouseInFk',
'warehouseOutFk',
'cargoSupplierFk',
'agencyModeFk',
'isRaid',
'daysInForward',
],
include: [
{
relation: 'warehouseIn',
scope: {
fields: ['name'],
},
},
{
relation: 'warehouseOut',
scope: {
fields: ['name'],
},
},
],
};

View File

@ -193,32 +193,44 @@ const entriesTotalM3 = computed(() =>
); );
const getTravelEntries = async (id) => { const getTravelEntries = async (id) => {
const { data } = await axios.get(`Travels/${id}/getEntries`); try {
entries.value = data; const { data } = await axios.get(`Travels/${id}/getEntries`);
entries.value = data;
} catch (err) {
console.error('Error fetching travel entries');
}
}; };
const getTravelThermographs = async (id) => { const getTravelThermographs = async (id) => {
const filter = { try {
include: { const filter = {
relation: 'warehouse', include: {
scope: { relation: 'warehouse',
fields: ['id', 'name'], scope: {
fields: ['id', 'name'],
},
}, },
}, where: { travelFk: id },
where: { travelFk: id }, };
};
const { data } = await axios.get('TravelThermographs', { const { data } = await axios.get('TravelThermographs', {
params: { filter: JSON.parse(JSON.stringify(filter)) }, params: { filter: JSON.parse(JSON.stringify(filter)) },
}); });
thermographs.value = data; thermographs.value = data;
} catch (err) {
console.error('Error fetching travel thermographs');
}
}; };
async function setTravelData(travelData) { async function setTravelData(travelData) {
if (travelData) { try {
travel.value = travelData; if (travelData) {
await getTravelEntries(travel.value.id); travel.value = travelData;
await getTravelThermographs(travel.value.id); await getTravelEntries(travel.value.id);
await getTravelThermographs(travel.value.id);
}
} catch (err) {
console.error(`Error setting travel data`, err);
} }
} }
@ -256,11 +268,6 @@ const getLink = (param) => `#/travel/${entityId.value}/${param}`;
:label="t('globals.warehouseOut')" :label="t('globals.warehouseOut')"
:value="travel.warehouseOut?.name" :value="travel.warehouseOut?.name"
/> />
<QCheckbox
:label="t('travel.basicData.isRaid')"
v-model="travel.isRaid"
:disable="true"
/>
<QCheckbox <QCheckbox
:label="t('travel.summary.delivered')" :label="t('travel.summary.delivered')"
v-model="travel.isDelivered" v-model="travel.isDelivered"
@ -279,10 +286,6 @@ const getLink = (param) => `#/travel/${entityId.value}/${param}`;
:label="t('globals.warehouseIn')" :label="t('globals.warehouseIn')"
:value="travel.warehouseIn?.name" :value="travel.warehouseIn?.name"
/> />
<VnLv
:label="t('travel.basicData.daysInForward')"
:value="travel?.daysInForward"
/>
<QCheckbox <QCheckbox
:label="t('travel.summary.received')" :label="t('travel.summary.received')"
v-model="travel.isReceived" v-model="travel.isReceived"
@ -300,6 +303,10 @@ const getLink = (param) => `#/travel/${entityId.value}/${param}`;
<VnLv :label="t('globals.reference')" :value="travel.ref" /> <VnLv :label="t('globals.reference')" :value="travel.ref" />
<VnLv label="m³" :value="travel.m3" /> <VnLv label="m³" :value="travel.m3" />
<VnLv :label="t('globals.totalEntries')" :value="travel.totalEntries" /> <VnLv :label="t('globals.totalEntries')" :value="travel.totalEntries" />
<VnLv
:label="t('travel.basicData.daysInForward')"
:value="travel?.daysInForward"
/>
</QCard> </QCard>
<QCard class="full-width"> <QCard class="full-width">
<VnTitle :text="t('travel.summary.entries')" /> <VnTitle :text="t('travel.summary.entries')" />

View File

@ -122,9 +122,13 @@ const redirectToThermographForm = (action, id) => {
}; };
const removeThermograph = async (id) => { const removeThermograph = async (id) => {
await axios.delete(`Travels/deleteThermograph?id=${id}`); try {
await thermographPaginateRef.value.fetch(); await axios.delete(`Travels/deleteThermograph?id=${id}`);
notify(t('Thermograph removed'), 'positive'); await thermographPaginateRef.value.fetch();
notify(t('Thermograph removed'), 'positive');
} catch (err) {
console.error('Error removing termograph');
}
}; };
</script> </script>

View File

@ -56,13 +56,17 @@ onBeforeMount(async () => {
}); });
const fetchDmsTypes = async () => { const fetchDmsTypes = async () => {
const params = { try {
filter: { const params = {
where: { code: 'thermograph' }, filter: {
}, where: { code: 'thermograph' },
}; },
const { data } = await axios.get('DmsTypes/findOne', { params }); };
return data; const { data } = await axios.get('DmsTypes/findOne', { params });
return data;
} catch (err) {
console.error('Error fetching Dms Types');
}
}; };
const setCreateDefaultParams = async () => { const setCreateDefaultParams = async () => {

View File

@ -293,16 +293,20 @@ const openReportPdf = () => {
}; };
const saveFieldValue = async (val, field, index) => { const saveFieldValue = async (val, field, index) => {
// Evitar la solicitud de guardado si el valor no ha cambiado try {
if (originalRowDataCopy.value[index][field] == val) return; // Evitar la solicitud de guardado si el valor no ha cambiado
if (originalRowDataCopy.value[index][field] == val) return;
const id = rows.value[index].id; const id = rows.value[index].id;
const params = { [field]: val }; const params = { [field]: val };
await axios.patch(`Travels/${id}`, params); await axios.patch(`Travels/${id}`, params);
// Actualizar la copia de los datos originales con el nuevo valor // Actualizar la copia de los datos originales con el nuevo valor
originalRowDataCopy.value[index][field] = val; originalRowDataCopy.value[index][field] = val;
await arrayData.fetch({ append: false }); await arrayData.fetch({ append: false });
} catch (err) {
console.error('Error updating travel');
}
}; };
const stopEventPropagation = (event, col) => { const stopEventPropagation = (event, col) => {

View File

@ -227,12 +227,10 @@ const columns = computed(() => [
> >
<template #column-status="{ row }"> <template #column-status="{ row }">
<div class="row"> <div class="row">
<QIcon v-if="!!row.isRaid" name="vn:net" color="primary"> <QIcon v-if="!!row.daysInForward" name="vn:net" color="primary">
<QTooltip> <QTooltip>
{{ {{
t('globals.raid', { t('globals.raid', { daysInForward: row.daysInForward })
daysInForward: row.daysInForward,
})
}}</QTooltip }}</QTooltip
> >
</QIcon> </QIcon>

View File

@ -19,10 +19,16 @@ const createTrayFormDialogRef = ref();
const selectedEntityId = ref(); const selectedEntityId = ref();
async function loadTrays() { async function loadTrays() {
const res = await axios.get('WagonTypeTrays'); try {
const filteredTrays = res.data.filter((tray) => tray.wagonTypeFk === entityId.value); const res = await axios.get('WagonTypeTrays');
wagonTrays.value = filteredTrays; const filteredTrays = res.data.filter(
return; (tray) => tray.wagonTypeFk === entityId.value
);
wagonTrays.value = filteredTrays;
return;
} catch (err) {
console.error('Error loading trays:', err);
}
} }
async function addTray(newTray) { async function addTray(newTray) {

View File

@ -60,29 +60,40 @@ const updateSelectedDate = (year) => {
}; };
const createEvent = async (date) => { const createEvent = async (date) => {
const params = { try {
dated: date, const params = {
absenceTypeId: props.absenceType.id, dated: date,
businessFk: props.businessFk, absenceTypeId: props.absenceType.id,
}; businessFk: props.businessFk,
};
const { data } = await axios.post(`Workers/${route.params.id}/createAbsence`, params); const { data } = await axios.post(
`Workers/${route.params.id}/createAbsence`,
params
);
if (data) emit('refresh'); if (data) emit('refresh');
} catch (error) {
console.error('error creating event:: ', error);
}
}; };
const editEvent = async (event) => { const editEvent = async (event) => {
const absenceType = props.absenceType; try {
const params = { const absenceType = props.absenceType;
absenceId: event.absenceId, const params = {
absenceTypeId: absenceType.id, absenceId: event.absenceId,
}; absenceTypeId: absenceType.id,
const { data } = await axios.patch( };
`Workers/${route.params.id}/updateAbsence`, const { data } = await axios.patch(
params `Workers/${route.params.id}/updateAbsence`,
); params
);
if (data) emit('refresh'); if (data) emit('refresh');
} catch (error) {
console.error('error editing event:: ', error);
}
}; };
const deleteEvent = async (event, date) => { const deleteEvent = async (event, date) => {

View File

@ -39,9 +39,15 @@ const entityId = computed(() => {
const workerExcluded = ref(false); const workerExcluded = ref(false);
const getIsExcluded = async () => { const getIsExcluded = async () => {
const { data } = await axios.get(`WorkerDisableExcludeds/${entityId.value}/exists`); try {
if (!data) return; const { data } = await axios.get(
workerExcluded.value = data.exists; `WorkerDisableExcludeds/${entityId.value}/exists`
);
if (!data) return;
workerExcluded.value = data.exists;
} catch (err) {
console.error('Error getting worker excluded: ', err);
}
}; };
const handleExcluded = async () => { const handleExcluded = async () => {

View File

@ -32,11 +32,14 @@ const initialData = computed(() => {
}); });
const deallocatePDA = async (deviceProductionFk) => { const deallocatePDA = async (deviceProductionFk) => {
await axios.post(`Workers/${route.params.id}/deallocatePDA`, { try {
pda: deviceProductionFk, await axios.post(`Workers/${route.params.id}/deallocatePDA`, {
}); pda: deviceProductionFk,
notify(t('PDA deallocated'), 'positive'); });
notify(t('PDA deallocated'), 'positive');
} catch (err) {
console.error('Error deallocating PDA');
}
paginate.value.fetch(); paginate.value.fetch();
}; };

View File

@ -251,9 +251,13 @@ const addEvents = (data) => {
}; };
const fetchHours = async () => { const fetchHours = async () => {
await workerHoursRef.value.fetch(); try {
await getWorkedHours(startOfWeek.value, endOfWeek.value); await workerHoursRef.value.fetch();
await getAbsences(); await getWorkedHours(startOfWeek.value, endOfWeek.value);
await getAbsences();
} catch (err) {
console.error('Error fetching worker hours');
}
}; };
const fetchWeekData = async () => { const fetchWeekData = async () => {
@ -261,21 +265,25 @@ const fetchWeekData = async () => {
year: selectedDate.value.getFullYear(), year: selectedDate.value.getFullYear(),
week: selectedWeekNumber.value, week: selectedWeekNumber.value,
}; };
const mail = ( try {
await axiosNoError.get(`Workers/${route.params.id}/mail`, { const mail = (
params: { filter: { where } }, await axiosNoError.get(`Workers/${route.params.id}/mail`, {
}) params: { filter: { where } },
).data[0]; })
).data[0];
if (!mail) state.value = null; if (!mail) state.value = null;
else { else {
state.value = mail.state; state.value = mail.state;
reason.value = mail.reason; reason.value = mail.reason;
}
canResend.value = !!(
await axiosNoError.get('WorkerTimeControlMails/count', { params: { where } })
).data.count;
} catch (err) {
console.error('Error fetching week data');
} }
canResend.value = !!(
await axiosNoError.get('WorkerTimeControlMails/count', { params: { where } })
).data.count;
}; };
const setHours = (data) => { const setHours = (data) => {
@ -349,19 +357,23 @@ const showReasonForm = () => {
}; };
const updateWorkerTimeControlMail = async (state, reason) => { const updateWorkerTimeControlMail = async (state, reason) => {
const params = { try {
year: selectedDate.value.getFullYear(), const params = {
week: selectedWeekNumber.value, year: selectedDate.value.getFullYear(),
state, week: selectedWeekNumber.value,
}; state,
const workerId = Number(route.params.id); };
const workerId = Number(route.params.id);
if (reason) params.reason = reason; if (reason) params.reason = reason;
await axios.post(`WorkerTimeControls/${workerId}/updateMailState`, params); await axios.post(`WorkerTimeControls/${workerId}/updateMailState`, params);
await getMailStates(selectedDate.value); await getMailStates(selectedDate.value);
await fetchWeekData(); await fetchWeekData();
notify(t('globals.dataSaved'), 'positive'); notify(t('globals.dataSaved'), 'positive');
} catch (err) {
console.error('Error updating worker time control mail');
}
}; };
const isSatisfied = async () => { const isSatisfied = async () => {
@ -377,16 +389,20 @@ const isUnsatisfied = async (reason) => {
}; };
const resendEmail = async () => { const resendEmail = async () => {
const params = { try {
recipient: worker.value?.user?.email, const params = {
week: selectedWeekNumber.value, recipient: worker.value?.user?.email,
year: selectedDate.value.getFullYear(), week: selectedWeekNumber.value,
workerId: Number(route.params.id), year: selectedDate.value.getFullYear(),
state: 'SENDED', workerId: Number(route.params.id),
}; state: 'SENDED',
await axios.post('WorkerTimeControls/weekly-hour-record-email', params); };
await getMailStates(selectedDate.value); await axios.post('WorkerTimeControls/weekly-hour-record-email', params);
notify(t('Email sended'), 'positive'); await getMailStates(selectedDate.value);
notify(t('Email sended'), 'positive');
} catch (err) {
console.error('Error sending email');
}
}; };
onBeforeMount(() => { onBeforeMount(() => {

View File

@ -50,11 +50,17 @@ const directionIconName = computed(() => {
}); });
const deleteHourEntry = async () => { const deleteHourEntry = async () => {
const { data } = await axios.post(`WorkerTimeControls/${$props.id}/deleteTimeEntry`); try {
const { data } = await axios.post(
`WorkerTimeControls/${$props.id}/deleteTimeEntry`
);
if (!data) return; if (!data) return;
emit('onHourEntryDeleted'); emit('onHourEntryDeleted');
notify('Entry removed', 'positive'); notify('Entry removed', 'positive');
} catch (err) {
console.error('Error deleting hour entry');
}
}; };
const showWorkerTimeForm = () => emit('showWorkerTimeForm'); const showWorkerTimeForm = () => emit('showWorkerTimeForm');

View File

@ -33,23 +33,28 @@ const onNodeExpanded = (nodeKeysArray) => {
}; };
const fetchNodeLeaves = async (nodeKey) => { const fetchNodeLeaves = async (nodeKey) => {
const node = treeRef.value?.getNodeByKey(nodeKey); try {
const node = treeRef.value?.getNodeByKey(nodeKey);
if (!node || node.sons === 0) return; if (!node || node.sons === 0) return;
const params = { parentId: node.id }; const params = { parentId: node.id };
const response = await axios.get('/departments/getLeaves', { params }); const response = await axios.get('/departments/getLeaves', { params });
if (response.data) { if (response.data) {
node.children = response.data.map((n) => { node.children = response.data.map((n) => {
const hasChildrens = n.sons > 0; const hasChildrens = n.sons > 0;
n.children = hasChildrens ? [{}] : null; n.children = hasChildrens ? [{}] : null;
n.clickable = true; n.clickable = true;
return n; return n;
}); });
}
state.set('Tree', node);
} catch (err) {
console.error('Error fetching department leaves', err);
throw new Error();
} }
state.set('Tree', node);
}; };
const removeNode = (node) => { const removeNode = (node) => {
@ -67,11 +72,15 @@ const removeNode = (node) => {
}; };
async function remove(id) { async function remove(id) {
await axios.post(`/Departments/${id}/removeChild`, { id }); try {
quasar.notify({ await axios.post(`/Departments/${id}/removeChild`, { id });
message: t('department.departmentRemoved'), quasar.notify({
type: 'positive', message: t('department.departmentRemoved'),
}); type: 'positive',
});
} catch (err) {
console.error('Error removing department');
}
} }
const showCreateNodeForm = (nodeId) => { const showCreateNodeForm = (nodeId) => {

View File

@ -43,7 +43,7 @@ const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm(); const { openConfirmationModal } = useVnConfirm();
const isNew = computed(() => props.isNewMode); const isNew = computed(() => props.isNewMode);
const dated = ref(props.date); const dated = ref(null);
const tickedNodes = ref(); const tickedNodes = ref();
const _excludeType = ref('all'); const _excludeType = ref('all');
@ -57,23 +57,34 @@ const excludeType = computed({
const arrayData = useArrayData('ZoneEvents'); const arrayData = useArrayData('ZoneEvents');
const exclusionGeoCreate = async () => { const exclusionGeoCreate = async () => {
const params = { try {
zoneFk: parseInt(route.params.id), const params = {
date: dated.value, zoneFk: parseInt(route.params.id),
geoIds: tickedNodes.value, date: dated.value,
}; geoIds: tickedNodes.value,
await axios.post('Zones/exclusionGeo', params); };
await refetchEvents(); await axios.post('Zones/exclusionGeo', params);
await refetchEvents();
} catch (err) {
console.error('Error creating exclusion geo: ', err);
}
}; };
const exclusionCreate = async () => { const exclusionCreate = async () => {
if (isNew.value) try {
await axios.post(`Zones/${route.params.id}/exclusions`, [{ dated: dated.value }]); if (isNew.value)
else await axios.post(`Zones/${route.params.id}/exclusions`, [
await axios.post(`Zones/${route.params.id}/exclusions`, { { dated: dated.value },
dated: dated.value, ]);
}); else
await refetchEvents(); await axios.post(`Zones/${route.params.id}/exclusions`, {
dated: dated.value,
});
await refetchEvents();
} catch (err) {
console.error('Error creating exclusion: ', err);
}
}; };
const onSubmit = async () => { const onSubmit = async () => {
@ -82,9 +93,13 @@ const onSubmit = async () => {
}; };
const deleteEvent = async () => { const deleteEvent = async () => {
if (!props.event) return; try {
await axios.delete(`Zones/${route.params.id}/exclusions`); if (!props.event) return;
await refetchEvents(); await axios.delete(`Zones/${route.params.id}/exclusions`);
await refetchEvents();
} catch (err) {
console.error('Error deleting event: ', err);
}
}; };
const closeForm = () => emit('closeForm'); const closeForm = () => emit('closeForm');
@ -114,14 +129,13 @@ onMounted(() => {
@on-submit="onSubmit()" @on-submit="onSubmit()"
:default-cancel-button="false" :default-cancel-button="false"
:default-submit-button="false" :default-submit-button="false"
:submit-on-enter="false"
> >
<template #form-inputs> <template #form-inputs>
<VnRow class="row q-gutter-md q-mb-lg"> <VnRow class="row q-gutter-md q-mb-lg">
<VnInputDate <VnInputDate
:label="t('eventsInclusionForm.day')" :label="t('eventsInclusionForm.day')"
v-model="dated" v-model="dated"
:required="true" :model-value="props.date"
/> />
</VnRow> </VnRow>
<div class="column q-gutter-y-sm q-mb-md"> <div class="column q-gutter-y-sm q-mb-md">
@ -182,7 +196,6 @@ onMounted(() => {
:label="isNew ? t('globals.add') : t('globals.save')" :label="isNew ? t('globals.add') : t('globals.save')"
type="submit" type="submit"
color="primary" color="primary"
@click="onSubmit()"
/> />
</template> </template>
</FormPopup> </FormPopup>

View File

@ -57,34 +57,45 @@ const inclusionType = computed({
const arrayData = useArrayData('ZoneEvents'); const arrayData = useArrayData('ZoneEvents');
const createEvent = async () => { const createEvent = async () => {
eventInclusionFormData.value.weekDays = weekdayStore.toSet( try {
eventInclusionFormData.value.wdays eventInclusionFormData.value.weekDays = weekdayStore.toSet(
); eventInclusionFormData.value.wdays
if (inclusionType.value == 'day') eventInclusionFormData.value.weekDays = '';
else eventInclusionFormData.value.dated = null;
if (inclusionType.value != 'range') {
eventInclusionFormData.value.started = null;
eventInclusionFormData.value.ended = null;
}
if (isNew.value)
await axios.post(`Zones/${route.params.id}/events`, eventInclusionFormData.value);
else
await axios.put(
`Zones/${route.params.id}/events/${props.event?.id}`,
eventInclusionFormData.value
); );
await refetchEvents(); if (inclusionType.value == 'day') eventInclusionFormData.value.weekDays = '';
emit('onSubmit'); else eventInclusionFormData.value.dated = null;
if (inclusionType.value != 'range') {
eventInclusionFormData.value.started = null;
eventInclusionFormData.value.ended = null;
}
if (isNew.value)
await axios.post(
`Zones/${route.params.id}/events`,
eventInclusionFormData.value
);
else
await axios.put(
`Zones/${route.params.id}/events/${props.event?.id}`,
eventInclusionFormData.value
);
await refetchEvents();
emit('onSubmit');
} catch (err) {
console.error('Error creating event', err);
}
}; };
const deleteEvent = async () => { const deleteEvent = async () => {
if (!props.event) return; try {
await axios.delete(`Zones/${route.params.id}/events/${props.event?.id}`); if (!props.event) return;
await refetchEvents(); await axios.delete(`Zones/${route.params.id}/events/${props.event?.id}`);
await refetchEvents();
} catch (err) {
console.error('Error deleting event: ', err);
}
}; };
const closeForm = () => { const closeForm = () => {

View File

@ -57,11 +57,15 @@ const arrayData = useArrayData('ZoneEvents', {
}); });
const fetchData = async () => { const fetchData = async () => {
if (!params.value.zoneFk || !params.value.started || !params.value.ended) return; try {
if (!params.value.zoneFk || !params.value.started || !params.value.ended) return;
await arrayData.applyFilter({ await arrayData.applyFilter({
params: params.value, params: params.value,
}); });
} catch (err) {
console.error('Error fetching events: ', err);
}
}; };
watch( watch(
@ -83,9 +87,13 @@ const formatWdays = (event) => {
}; };
const deleteEvent = async (id) => { const deleteEvent = async (id) => {
if (!id) return; try {
await axios.delete(`Zones/${route.params.id}/events/${id}`); if (!id) return;
await fetchData(); await axios.delete(`Zones/${route.params.id}/events/${id}`);
await fetchData();
} catch (err) {
console.error('Error deleting event: ', err);
}
}; };
const openInclusionForm = (event) => { const openInclusionForm = (event) => {

View File

@ -10,9 +10,13 @@ const { t } = useI18n();
const route = useRoute(); const route = useRoute();
const onSelected = async (val, node) => { const onSelected = async (val, node) => {
if (val === null) val = undefined; try {
const params = { geoId: node.id, isIncluded: val }; if (val === null) val = undefined;
await axios.post(`Zones/${route.params.id}/toggleIsIncluded`, params); const params = { geoId: node.id, isIncluded: val };
await axios.post(`Zones/${route.params.id}/toggleIsIncluded`, params);
} catch (err) {
console.error('Error updating included', err);
}
}; };
</script> </script>

View File

@ -38,7 +38,6 @@ const datakey = 'ZoneLocations';
const url = computed(() => `Zones/${route.params.id}/getLeaves`); const url = computed(() => `Zones/${route.params.id}/getLeaves`);
const arrayData = useArrayData(datakey, { const arrayData = useArrayData(datakey, {
url: url.value, url: url.value,
limit: null,
}); });
const store = arrayData.store; const store = arrayData.store;
@ -75,7 +74,6 @@ const onNodeExpanded = async (nodeKeysArray) => {
if (response.data) { if (response.data) {
node.childs = response.data.map((n) => { node.childs = response.data.map((n) => {
if (n.sons > 0) n.childs = [{}]; if (n.sons > 0) n.childs = [{}];
n.selected = isSelected(n.selected);
return n; return n;
}); });
} }
@ -92,16 +90,21 @@ const onNodeExpanded = async (nodeKeysArray) => {
previousExpandedNodes.value = nodeKeysSet; previousExpandedNodes.value = nodeKeysSet;
}; };
const formatNodeSelected = (node) => {
if (node.selected === 1) node.selected = true;
else if (node.selected === 0) node.selected = false;
if (node.sons > 0 && !node.childs) node.childs = [{}];
};
const fetchNodeLeaves = async (nodeKey) => { const fetchNodeLeaves = async (nodeKey) => {
if (!treeRef.value) return; if (!treeRef.value) return;
const node = treeRef.value?.getNodeByKey(nodeKey); const node = treeRef.value?.getNodeByKey(nodeKey);
if (typeof node.selected === 'number') node.selected = !!node.selected; if (node.selected === 1) node.selected = true;
if (node.sons > 0 && !node.childs) { else if (node.selected === 0) node.selected = false;
node.childs = [{}];
const index = expanded.value.indexOf(node.id);
expanded.value.splice(index, 1);
}
if (!node || node.sons === 0) return; if (!node || node.sons === 0) return;
state.set('Tree', node);
}; };
function getNodeIds(node) { function getNodeIds(node) {
@ -116,10 +119,6 @@ function getNodeIds(node) {
return ids; return ids;
} }
function isSelected(selected) {
if (typeof selected === 'number') return !!selected;
}
watch( watch(
() => store.data, () => store.data,
async (val) => { async (val) => {
@ -129,9 +128,18 @@ watch(
nodes.value[0].childs = [...val]; nodes.value[0].childs = [...val];
const fetchedNodeKeys = val.flatMap(getNodeIds); const fetchedNodeKeys = val.flatMap(getNodeIds);
state.set('Tree', [...fetchedNodeKeys]); state.set('Tree', [...fetchedNodeKeys]);
expanded.value = [null, ...fetchedNodeKeys];
for (let n of state.get('Tree')) { if (!store.userParams?.search) {
await fetchNodeLeaves(n); val.forEach((n) => {
formatNodeSelected(n);
});
store.data = null;
expanded.value = [null];
} else {
for (let n of state.get('Tree')) {
await fetchNodeLeaves(n);
}
expanded.value = [null, ...fetchedNodeKeys];
} }
previousExpandedNodes.value = new Set(expanded.value); previousExpandedNodes.value = new Set(expanded.value);
}, },
@ -139,11 +147,13 @@ watch(
); );
const reFetch = async () => { const reFetch = async () => {
await arrayData.fetch({}); const { data } = await arrayData.fetch({ append: false });
nodes.value = data;
expanded.value = [null];
}; };
onMounted(async () => { onMounted(async () => {
await reFetch(); if (store.userParams?.search) await arrayData.fetch({});
}); });
onUnmounted(() => { onUnmounted(() => {
@ -157,13 +167,13 @@ onUnmounted(() => {
v-if="showSearchBar" v-if="showSearchBar"
v-model="store.userParams.search" v-model="store.userParams.search"
:placeholder="$t('globals.search')" :placeholder="$t('globals.search')"
@keydown.enter.stop.prevent="reFetch" @update:model-value="reFetch()"
> >
<template #prepend> <template #prepend>
<QBtn color="primary" icon="search" dense flat @click="reFetch()" /> <QBtn color="primary" icon="search" dense flat @click="reFetch()" />
</template> </template>
</VnInput> </VnInput>
<VnSearchbar v-if="!showSearchBar" :data-key="datakey" :url="url" :redirect="false" /> <VnSearchbar :data-key="datakey" :url="url" :redirect="false" />
<QTree <QTree
ref="treeRef" ref="treeRef"
:nodes="nodes" :nodes="nodes"

View File

@ -21,13 +21,17 @@ const arrayData = useArrayData('ZoneDeliveryDays', {
const deliveryMethodsConfig = { pickUp: ['PICKUP'], delivery: ['AGENCY', 'DELIVERY'] }; const deliveryMethodsConfig = { pickUp: ['PICKUP'], delivery: ['AGENCY', 'DELIVERY'] };
const fetchData = async (params) => { const fetchData = async (params) => {
const { data } = params try {
? await arrayData.applyFilter({ const { data } = params
params, ? await arrayData.applyFilter({
}) params,
: await arrayData.fetch({ append: false }); })
if (!data.events || !data.events.length) : await arrayData.fetch({ append: false });
notify(t('deliveryPanel.noEventsWarning'), 'warning'); if (!data.events || !data.events.length)
notify(t('deliveryPanel.noEventsWarning'), 'warning');
} catch (err) {
console.error('Error fetching events: ', err);
}
}; };
const onSubmit = async () => { const onSubmit = async () => {

View File

@ -99,7 +99,7 @@ describe('VnLocation', () => {
}); });
it('Create postCode', () => { it('Create postCode', () => {
const postCode = Math.floor(100000 + Math.random() * 900000); const postCode = '1234475';
const province = 'Valencia'; const province = 'Valencia';
cy.get(createLocationButton).click(); cy.get(createLocationButton).click();
cy.get('.q-card > h1').should('have.text', 'New postcode'); cy.get('.q-card > h1').should('have.text', 'New postcode');
@ -115,68 +115,20 @@ describe('VnLocation', () => {
checkVnLocation(postCode, province); checkVnLocation(postCode, province);
}); });
it('Create city', () => {
it('Create city without country', () => { const postCode = '9011';
const cityName = 'Saskatchew'.concat(Math.random(1 * 100)); const province = 'Saskatchew';
cy.get(createLocationButton).click(); cy.get(createLocationButton).click();
cy.get(dialogInputs).eq(0).type(postCode);
cy.get( cy.get(
`${createForm.prefix} > :nth-child(4) > .q-select > ${createForm.sufix} > :nth-child(2) > .q-icon` `${createForm.prefix} > :nth-child(4) > .q-select > ${createForm.sufix} > :nth-child(2) > .q-icon`
).click(); ).click();
cy.selectOption('#q-portal--dialog--3 .q-select', 'one'); cy.selectOption('#q-portal--dialog--3 .q-select', 'one');
cy.get('#q-portal--dialog--3 .q-input').type(cityName); cy.get('#q-portal--dialog--3 .q-input').type(province);
cy.get('#q-portal--dialog--3 .q-btn--standard').click(); cy.get('#q-portal--dialog--3 .q-btn--standard').click();
}); cy.get('#q-portal--dialog--1 .q-btn--standard').click();
cy.waitForElement('.q-form');
it('Create province without country', () => { checkVnLocation(postCode, province);
const provinceName = 'Saskatchew'.concat(Math.random(1 * 100));
cy.get(createLocationButton).click();
cy.get(
`${createForm.prefix} > :nth-child(5) > .q-select > ${createForm.sufix} > :nth-child(2) `
)
.eq(0)
.click();
cy.selectOption('#q-portal--dialog--3 .q-select', 'one');
cy.countSelectOptions('#q-portal--dialog--3 .q-select', 4);
cy.get('#q-portal--dialog--3 .q-input').type(provinceName);
cy.get('#q-portal--dialog--3 .q-btn--standard').click();
});
it('Create city with country', () => {
const cityName = 'Saskatchew'.concat(Math.random(1 * 100));
cy.get(createLocationButton).click();
cy.selectOption(
`${createForm.prefix} > :nth-child(5) > :nth-child(3) `,
'Italia'
);
cy.get(
`${createForm.prefix} > :nth-child(4) > .q-select > ${createForm.sufix} > :nth-child(2) > .q-icon`
).click();
cy.selectOption('#q-portal--dialog--4 .q-select', 'Province four');
cy.countSelectOptions('#q-portal--dialog--4 .q-select', 1);
cy.get('#q-portal--dialog--4 .q-input').type(cityName);
cy.get('#q-portal--dialog--4 .q-btn--standard').click();
});
it('Create province with country', () => {
const provinceName = 'Saskatchew'.concat(Math.random(1 * 100));
cy.get(createLocationButton).click();
cy.selectOption(
`${createForm.prefix} > :nth-child(5) > :nth-child(3) `,
'España'
);
cy.get(
`${createForm.prefix} > :nth-child(5) > .q-select > ${createForm.sufix} > :nth-child(2) `
)
.eq(0)
.click();
cy.selectOption('#q-portal--dialog--4 .q-select', 'one');
cy.countSelectOptions('#q-portal--dialog--4 .q-select', 2);
cy.get('#q-portal--dialog--4 .q-input').type(provinceName);
cy.get('#q-portal--dialog--4 .q-btn--standard').click();
}); });
function checkVnLocation(postCode, province) { function checkVnLocation(postCode, province) {

View File

@ -91,11 +91,6 @@ Cypress.Commands.add('selectOption', (selector, option) => {
cy.get(selector).click(); cy.get(selector).click();
cy.get('.q-menu .q-item').contains(option).click(); cy.get('.q-menu .q-item').contains(option).click();
}); });
Cypress.Commands.add('countSelectOptions', (selector, option) => {
cy.waitForElement(selector);
cy.get(selector).click();
cy.get('.q-menu .q-item').should('have.length', option);
});
Cypress.Commands.add('fillInForm', (obj, form = '.q-form > .q-card') => { Cypress.Commands.add('fillInForm', (obj, form = '.q-form > .q-card') => {
cy.waitForElement('.q-form > .q-card'); cy.waitForElement('.q-form > .q-card');

View File

@ -1,36 +1,25 @@
import { vi, describe, expect, it, beforeAll, afterAll } from 'vitest'; import { vi, describe, expect, it } from 'vitest';
import { axios } from 'app/test/vitest/helper'; import { axios } from 'app/test/vitest/helper';
import { downloadFile } from 'src/composables/downloadFile'; import { downloadFile } from 'src/composables/downloadFile';
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
const session = useSession(); const session = useSession();
const token = session.getToken(); const token = session.getToken();
describe('downloadFile', () => { describe('downloadFile', () => {
const baseUrl = 'http://localhost:9000';
let defaulCreateObjectURL;
beforeAll(() => {
defaulCreateObjectURL = window.URL.createObjectURL;
window.URL.createObjectURL = vi.fn(() => 'blob:http://localhost:9000/blob-id');
});
afterAll(() => (window.URL.createObjectURL = defaulCreateObjectURL));
it('should open a new window to download the file', async () => { it('should open a new window to download the file', async () => {
const res = { const url = 'http://localhost:9000';
data: new Blob(['file content'], { type: 'application/octet-stream' }),
headers: { 'content-disposition': 'attachment; filename="test-file.txt"' }, vi.spyOn(axios, 'get').mockResolvedValueOnce({ data: url });
};
vi.spyOn(axios, 'get').mockImplementation((url) => { const mockWindowOpen = vi.spyOn(window, 'open');
if (url == 'Urls/getUrl') return Promise.resolve({ data: baseUrl });
else if (url.includes('downloadFile')) return Promise.resolve(res);
});
await downloadFile(1); await downloadFile(1);
expect(axios.get).toHaveBeenCalledWith( expect(mockWindowOpen).toHaveBeenCalledWith(
`${baseUrl}/dms/1/downloadFile?access_token=${token}`, `${url}/api/dms/1/downloadFile?access_token=${token}`
{ responseType: 'blob' }
); );
mockWindowOpen.mockRestore();
}); });
}); });