refactor: refs #8217 clean up code and improve readability in various components and tests
gitea/salix-front/pipeline/pr-dev This commit is unstable Details

This commit is contained in:
Javier Segarra 2025-04-17 22:27:53 +02:00
parent dae5fb5241
commit fe5fdf723b
7 changed files with 102 additions and 38 deletions

View File

@ -98,7 +98,6 @@ defineExpose({
reset,
hasChanges,
saveChanges,
getChanges,
formData,
originalData,

View File

@ -113,7 +113,7 @@ const isLoading = ref(false);
// Si elegimos observar los cambios del form significa que inicialmente las actions estaran deshabilitadas
const isResetting = ref(false);
const hasChanges = ref(!$props.observeFormChanges);
const originalData = computed(() => state.get(modelValue) ?? {});
const originalData = computed(() => state.get(modelValue));
const formData = ref();
const defaultButtons = computed(() => ({
save: {
@ -223,30 +223,49 @@ async function fetch() {
}
}
async function handleResponse(response, showCreatedNotification = false) {
if (showCreatedNotification) {
notify('globals.dataCreated', 'positive');
}
updateAndEmit('onDataSaved', {
val: formData.value,
res: response?.data,
old: originalData.value,
});
if ($props.reload) await arrayData.fetch({});
hasChanges.value = false;
}
async function create() {
formData.value = trimData(formData.value);
const url = $props.urlCreate;
const response = await Promise.resolve(
$props.saveFn ? $props.saveFn(formData.value) : axios.post(url, formData.value),
);
await handleResponse(response, true);
}
async function update() {
formData.value = trimData(formData.value);
const body = $props.mapper(originalData.value, formData.value);
const url = $props.urlUpdate || $props.url || arrayData.store.url;
const response = await Promise.resolve(
$props.saveFn ? $props.saveFn(body) : axios.patch(url, body),
);
await handleResponse(response);
}
async function save() {
if ($props.observeFormChanges && !hasChanges.value)
return notify('globals.noChanges', 'negative');
isLoading.value = true;
try {
formData.value = trimData(formData.value);
const body = $props.mapper(originalData.value, formData.value);
const method = $props.urlCreate ? 'post' : 'patch';
const url =
$props.urlCreate || $props.urlUpdate || $props.url || arrayData.store.url;
const response = await Promise.resolve(
$props.saveFn ? $props.saveFn(body) : axios[method](url, body),
);
if ($props.urlCreate) notify('globals.dataCreated', 'positive');
updateAndEmit('onDataSaved', {
val: formData.value,
res: response?.data,
old: originalData.value,
});
if ($props.reload) await arrayData.fetch({});
hasChanges.value = false;
if ($props.urlCreate != null) {
await create();
} else {
await update();
}
} finally {
isLoading.value = false;
}
@ -326,7 +345,6 @@ defineExpose({
<template>
<div class="column items-center full-width">
<QForm
id="formModel"
v-on="$attrs"
ref="myForm"
v-if="formData"

View File

@ -115,6 +115,7 @@ describe('CrudModel', () => {
expect(result).toEqual({
a: null,
b: 4,
c: 3,
d: 5,
});
});
@ -241,7 +242,7 @@ describe('CrudModel', () => {
await vm.saveChanges(data);
expect(postMock).toHaveBeenCalledWith(vm.url + '/crud', data);
expect(postMock).toHaveBeenCalledWith(`${vm.url}/crud`, data);
expect(vm.isLoading).toBe(false);
expect(vm.hasChanges).toBe(false);
expect(vm.originalData).toEqual(JSON.parse(JSON.stringify(vm.formData)));

View File

@ -3,11 +3,17 @@ import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import FormModel from 'src/components/FormModel.vue';
import { useState } from 'src/composables/useState';
describe('FormModel', () => {
const model = 'mockModel';
const url = 'mockUrl';
const formInitialData = { mockKey: 'mockVal' };
let state;
beforeEach(() => {
state = useState();
state.set(model, formInitialData);
});
describe('modelValue', () => {
it('should use the provided model', () => {
@ -118,7 +124,7 @@ describe('FormModel', () => {
propsData: {
url,
model,
formInitialData: { ...formInitialData, key1: 'valueKey1' },
formInitialData,
},
});
await vm.$nextTick();

View File

@ -21,7 +21,7 @@ watch(
(newValue) => {
if (!modelValue.value) return;
modelValue.value = formatLocation(newValue) ?? null;
}
},
);
const mixinRules = [requiredFieldRule];
@ -45,7 +45,7 @@ const formatLocation = (obj, properties = locationProperties) => {
});
const filteredParts = parts.filter(
(part) => part !== null && part !== undefined && part !== ''
(part) => part !== null && part !== undefined && part !== '',
);
return filteredParts.join(', ');

View File

@ -0,0 +1,41 @@
import getDifferences from '../getDifferences';
describe('getDifferences', () => {
it('should handle empty initialData', () => {
const initialData = {};
const formData = { name: 'John' };
expect(getDifferences(initialData, formData)).toEqual({ name: 'John' });
});
it('should detect when formData has a key not present in initialData', () => {
const initialData = { age: 30 };
const formData = { name: 'John' };
expect(getDifferences(initialData, formData)).toEqual({ age: 30, name: 'John' });
});
it('should detect when formData has different value for existing key', () => {
const initialData = { name: 'John', age: 30 };
const formData = { name: 'Jane', age: 30 };
expect(getDifferences(initialData, formData)).toEqual({ name: 'Jane' });
});
it('should detect when formData has null value for existing key', () => {
const initialData = { name: 'John' };
const formData = { name: null };
expect(getDifferences(initialData, formData)).toEqual({ name: null });
});
it('should handle missing keys in formData', () => {
const initialData = { name: 'John', age: 30 };
const formData = { name: 'John' };
expect(getDifferences(initialData, formData)).toEqual({ age: 30 });
});
it('should handle complex objects', () => {
const initialData = { user: { name: 'John', age: 30 } };
const formData = { user: { name: 'John', age: 31 } };
expect(getDifferences(initialData, formData)).toEqual({
user: { name: 'John', age: 31 },
});
});
});

View File

@ -1,23 +1,22 @@
export default function getDifferences(initialData, formData) {
export default function getDifferences(initialData = {}, formData = {}) {
const diff = {};
if (!initialData) return diff;
if (!formData) return initialData;
delete initialData.$index;
delete formData.$index;
delete initialData?.$index;
delete formData?.$index;
// Añadimos los valores que están en initialData
for (const key in initialData) {
if (
formData[key] &&
JSON.stringify(initialData[key]) !== JSON.stringify(formData[key])
) {
if (!Object.prototype.hasOwnProperty.call(formData, key)) {
// Caso 1: initialData tiene una clave que no tiene formData
diff[key] = initialData[key];
} else if (JSON.stringify(initialData[key]) !== JSON.stringify(formData[key])) {
// Caso 2 y 3: valores diferentes o null en formData
diff[key] = formData[key];
}
}
// Añadimos las claves nuevas de formData
for (const key in formData) {
if (
initialData[key] === undefined ||
JSON.stringify(initialData[key]) !== JSON.stringify(formData[key])
) {
if (!Object.prototype.hasOwnProperty.call(initialData, key)) {
diff[key] = formData[key];
}
}