Compare commits

..

No commits in common. "4d285499b9ed78446e3bcd2fda4525b4e137f253" and "683940cc24d6e5bfdaa96e57d13cf1777c8efd46" have entirely different histories.

70 changed files with 1399 additions and 871 deletions

View File

@ -156,22 +156,26 @@ const rotateRight = () => {
};
const onSubmit = () => {
if (!newPhoto.files && !newPhoto.url) {
notify(t('Select an image'), 'negative');
return;
try {
if (!newPhoto.files && !newPhoto.url) {
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 () => {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,24 +1,11 @@
import { useSession } from 'src/composables/useSession';
import { getUrl } from './getUrl';
import axios from 'axios';
import { exportFile } from 'quasar';
const { getTokenMultimedia } = useSession();
const token = getTokenMultimedia();
export async function downloadFile(id, model = 'dms', urlPath = '/downloadFile', url) {
const appUrl = (await getUrl('', 'lilium')).replace('/#/', '');
const response = await axios.get(
url ?? `${appUrl}/${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);
let appUrl = await getUrl('', 'lilium');
appUrl = appUrl.replace('/#/', '');
window.open(url ?? `${appUrl}/api/${model}/${id}${urlPath}?access_token=${token}`);
}

View File

@ -87,7 +87,7 @@ export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
const params = { filter };
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?.length) params.filter.order = [...store.order];
else delete params.filter.order;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -173,29 +173,40 @@ const getBadgeColor = (date) => {
};
const changeQuantity = async (request) => {
if (request.saleFk) {
const params = {
quantity: request.saleQuantity,
};
try {
if (request.saleFk) {
const params = {
quantity: request.saleQuantity,
};
await axios.patch(`Sales/${request.saleFk}`, params);
notify(t('globals.dataSaved'), 'positive');
confirmRequest(request);
} else confirmRequest(request);
await axios.patch(`Sales/${request.saleFk}`, params);
notify(t('globals.dataSaved'), 'positive');
confirmRequest(request);
} else confirmRequest(request);
} catch (error) {
console.error('Error changing quantity:: ', error);
}
};
const confirmRequest = async (request) => {
if (request.itemFk && request.saleQuantity) {
const params = {
itemFk: request.itemFk,
quantity: request.saleQuantity,
attenderFk: request.attenderFk,
};
try {
if (request.itemFk && request.saleQuantity) {
const params = {
itemFk: request.itemFk,
quantity: request.saleQuantity,
attenderFk: request.attenderFk,
};
const { data } = await axios.post(`TicketRequests/${request.id}/confirm`, params);
request.itemDescription = data.concept;
request.isOk = true;
notify(t('globals.dataSaved'), 'positive');
const { data } = await axios.post(
`TicketRequests/${request.id}/confirm`,
params
);
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 selectedIds = selectedRows.value.map((row) => row.id);
const params = { deletes: selectedIds };
await axios.post('SalesMonitors/deleteOrders', params);
selectedRows.value = [];
await table.value.reload();
try {
const selectedIds = selectedRows.value.map((row) => row.id);
const params = { deletes: selectedIds };
await axios.post('SalesMonitors/deleteOrders', params);
selectedRows.value = [];
await table.value.reload();
} catch (err) {
console.error('Error deleting orders', err);
}
};
const openTab = (id) =>

View File

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

View File

@ -1,13 +1,14 @@
<script setup>
import { useStateStore } from 'stores/useStateStore';
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 { useI18n } from 'vue-i18n';
import VnPaginate from 'src/components/ui/VnPaginate.vue';
import CatalogItem from 'src/components/ui/CatalogItem.vue';
import OrderCatalogFilter from 'src/pages/Order/Card/OrderCatalogFilter.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import getParamWhere from 'src/filters/getParamWhere';
import { useArrayData } from 'src/composables/useArrayData';
const route = useRoute();
@ -17,6 +18,7 @@ const { t } = useI18n();
const dataKey = 'OrderCatalogList';
const arrayData = useArrayData(dataKey);
const store = arrayData.store;
const showFilter = ref(null);
const tags = ref([]);
let catalogParams = {
@ -24,6 +26,27 @@ let catalogParams = {
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(() => {
stateStore.rightDrawer = true;
checkOrderConfirmation();
@ -67,7 +90,7 @@ function extractValueTags(items) {
);
tagValue.value = resultValueTags;
}
const autoLoad = computed(() => !!JSON.parse(route?.query.table ?? '{}')?.categoryFk);
const autoLoad = computed(() => !!catalogParams.categoryFk);
watch(
() => store.data,
@ -89,7 +112,7 @@ watch(
:info="t('You can search items by name or id')"
/>
<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
:data-key="dataKey"
:tag-value="tagValue"
@ -105,6 +128,8 @@ watch(
url="Orders/CatalogFilter"
:limit="50"
:user-params="catalogParams"
@on-fetch="showFilter = true"
:update-router="false"
:auto-load="autoLoad"
>
<template #body="{ rows }">

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -140,9 +140,13 @@ const createClaim = () => {
};
const onCreateClaimAccepted = async () => {
const params = { ticketId: ticket.value.id, sales: props.sales };
const { data } = await axios.post(`Claims/createFromSales`, params);
push({ name: 'ClaimBasicData', params: { id: data.id } });
try {
const params = { ticketId: ticket.value.id, sales: props.sales };
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) => {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,6 +10,16 @@ ticketNotes:
observationType: Observation type
removeNote: Remove 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:
visible: Visible
available: Available

View File

@ -19,6 +19,18 @@ ticketNotes:
observationType: Tipo de observación
removeNote: Quitar 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:
requester: Solicitante
atender: Comprador

View File

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

View File

@ -193,32 +193,44 @@ const entriesTotalM3 = computed(() =>
);
const getTravelEntries = async (id) => {
const { data } = await axios.get(`Travels/${id}/getEntries`);
entries.value = data;
try {
const { data } = await axios.get(`Travels/${id}/getEntries`);
entries.value = data;
} catch (err) {
console.error('Error fetching travel entries');
}
};
const getTravelThermographs = async (id) => {
const filter = {
include: {
relation: 'warehouse',
scope: {
fields: ['id', 'name'],
try {
const filter = {
include: {
relation: 'warehouse',
scope: {
fields: ['id', 'name'],
},
},
},
where: { travelFk: id },
};
where: { travelFk: id },
};
const { data } = await axios.get('TravelThermographs', {
params: { filter: JSON.parse(JSON.stringify(filter)) },
});
thermographs.value = data;
const { data } = await axios.get('TravelThermographs', {
params: { filter: JSON.parse(JSON.stringify(filter)) },
});
thermographs.value = data;
} catch (err) {
console.error('Error fetching travel thermographs');
}
};
async function setTravelData(travelData) {
if (travelData) {
travel.value = travelData;
await getTravelEntries(travel.value.id);
await getTravelThermographs(travel.value.id);
try {
if (travelData) {
travel.value = travelData;
await getTravelEntries(travel.value.id);
await getTravelThermographs(travel.value.id);
}
} catch (err) {
console.error(`Error setting travel data`, err);
}
}

View File

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

View File

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

View File

@ -293,16 +293,20 @@ const openReportPdf = () => {
};
const saveFieldValue = async (val, field, index) => {
// Evitar la solicitud de guardado si el valor no ha cambiado
if (originalRowDataCopy.value[index][field] == val) return;
try {
// 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 params = { [field]: val };
await axios.patch(`Travels/${id}`, params);
// Actualizar la copia de los datos originales con el nuevo valor
originalRowDataCopy.value[index][field] = val;
const id = rows.value[index].id;
const params = { [field]: val };
await axios.patch(`Travels/${id}`, params);
// Actualizar la copia de los datos originales con el nuevo valor
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) => {

View File

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

View File

@ -60,29 +60,40 @@ const updateSelectedDate = (year) => {
};
const createEvent = async (date) => {
const params = {
dated: date,
absenceTypeId: props.absenceType.id,
businessFk: props.businessFk,
};
try {
const params = {
dated: date,
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 absenceType = props.absenceType;
const params = {
absenceId: event.absenceId,
absenceTypeId: absenceType.id,
};
const { data } = await axios.patch(
`Workers/${route.params.id}/updateAbsence`,
params
);
try {
const absenceType = props.absenceType;
const params = {
absenceId: event.absenceId,
absenceTypeId: absenceType.id,
};
const { data } = await axios.patch(
`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) => {

View File

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

View File

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

View File

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

View File

@ -50,11 +50,17 @@ const directionIconName = computed(() => {
});
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;
emit('onHourEntryDeleted');
notify('Entry removed', 'positive');
if (!data) return;
emit('onHourEntryDeleted');
notify('Entry removed', 'positive');
} catch (err) {
console.error('Error deleting hour entry');
}
};
const showWorkerTimeForm = () => emit('showWorkerTimeForm');

View File

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

View File

@ -57,24 +57,34 @@ const excludeType = computed({
const arrayData = useArrayData('ZoneEvents');
const exclusionGeoCreate = async () => {
const params = {
zoneFk: parseInt(route.params.id),
date: dated.value,
geoIds: tickedNodes.value,
};
await axios.post('Zones/exclusionGeo', params);
await refetchEvents();
try {
const params = {
zoneFk: parseInt(route.params.id),
date: dated.value,
geoIds: tickedNodes.value,
};
await axios.post('Zones/exclusionGeo', params);
await refetchEvents();
} catch (err) {
console.error('Error creating exclusion geo: ', err);
}
};
const exclusionCreate = async () => {
if (isNew.value)
await axios.post(`Zones/${route.params.id}/exclusions`, [{ dated: dated.value }]);
else
await axios.post(`Zones/${route.params.id}/exclusions`, {
dated: dated.value,
});
try {
if (isNew.value)
await axios.post(`Zones/${route.params.id}/exclusions`, [
{ dated: dated.value },
]);
else
await axios.post(`Zones/${route.params.id}/exclusions`, {
dated: dated.value,
});
await refetchEvents();
await refetchEvents();
} catch (err) {
console.error('Error creating exclusion: ', err);
}
};
const onSubmit = async () => {
@ -83,9 +93,13 @@ const onSubmit = async () => {
};
const deleteEvent = async () => {
if (!props.event) return;
await axios.delete(`Zones/${route.params.id}/exclusions`);
await refetchEvents();
try {
if (!props.event) return;
await axios.delete(`Zones/${route.params.id}/exclusions`);
await refetchEvents();
} catch (err) {
console.error('Error deleting event: ', err);
}
};
const closeForm = () => emit('closeForm');

View File

@ -57,34 +57,45 @@ const inclusionType = computed({
const arrayData = useArrayData('ZoneEvents');
const createEvent = async () => {
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
try {
eventInclusionFormData.value.weekDays = weekdayStore.toSet(
eventInclusionFormData.value.wdays
);
await refetchEvents();
emit('onSubmit');
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();
emit('onSubmit');
} catch (err) {
console.error('Error creating event', err);
}
};
const deleteEvent = async () => {
if (!props.event) return;
await axios.delete(`Zones/${route.params.id}/events/${props.event?.id}`);
await refetchEvents();
try {
if (!props.event) return;
await axios.delete(`Zones/${route.params.id}/events/${props.event?.id}`);
await refetchEvents();
} catch (err) {
console.error('Error deleting event: ', err);
}
};
const closeForm = () => {

View File

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

View File

@ -10,9 +10,13 @@ const { t } = useI18n();
const route = useRoute();
const onSelected = async (val, node) => {
if (val === null) val = undefined;
const params = { geoId: node.id, isIncluded: val };
await axios.post(`Zones/${route.params.id}/toggleIsIncluded`, params);
try {
if (val === null) val = undefined;
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>

View File

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

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 { downloadFile } from 'src/composables/downloadFile';
import { useSession } from 'src/composables/useSession';
const session = useSession();
const token = session.getToken();
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 () => {
const res = {
data: new Blob(['file content'], { type: 'application/octet-stream' }),
headers: { 'content-disposition': 'attachment; filename="test-file.txt"' },
};
vi.spyOn(axios, 'get').mockImplementation((url) => {
if (url == 'Urls/getUrl') return Promise.resolve({ data: baseUrl });
else if (url.includes('downloadFile')) return Promise.resolve(res);
});
const url = 'http://localhost:9000';
vi.spyOn(axios, 'get').mockResolvedValueOnce({ data: url });
const mockWindowOpen = vi.spyOn(window, 'open');
await downloadFile(1);
expect(axios.get).toHaveBeenCalledWith(
`${baseUrl}/dms/1/downloadFile?access_token=${token}`,
{ responseType: 'blob' }
expect(mockWindowOpen).toHaveBeenCalledWith(
`${url}/api/dms/1/downloadFile?access_token=${token}`
);
mockWindowOpen.mockRestore();
});
});