Merge pull request 'Warmfix: #6943 addressPropagate' (!1389) from 6943_re_propagate into test
gitea/salix-front/pipeline/head This commit looks good Details
gitea/salix-front/pipeline/pr-master This commit looks good Details

Reviewed-on: #1389
Reviewed-by: Javi Gallego <jgallego@verdnatura.es>
This commit is contained in:
Javier Segarra 2025-02-17 12:20:34 +00:00
commit 38df9c27ae
11 changed files with 201 additions and 43 deletions

View File

@ -97,7 +97,7 @@ const $props = defineProps({
});
const emit = defineEmits(['onFetch', 'onDataSaved']);
const modelValue = computed(
() => $props.model ?? `formModel_${route?.meta?.title ?? route.name}`
() => $props.model ?? `formModel_${route?.meta?.title ?? route.name}`,
).value;
const componentIsRendered = ref(false);
const arrayData = useArrayData(modelValue);
@ -136,7 +136,8 @@ onMounted(async () => {
if (!$props.formInitialData) {
if ($props.autoLoad && $props.url) await fetch();
else if (arrayData.store.data) updateAndEmit('onFetch', arrayData.store.data);
else if (arrayData.store.data)
updateAndEmit('onFetch', { val: arrayData.store.data });
}
if ($props.observeFormChanges) {
watch(
@ -148,7 +149,7 @@ onMounted(async () => {
JSON.stringify(newVal) !== JSON.stringify(originalData.value);
isResetting.value = false;
},
{ deep: true }
{ deep: true },
);
}
});
@ -156,7 +157,7 @@ onMounted(async () => {
if (!$props.url)
watch(
() => arrayData.store.data,
(val) => updateAndEmit('onFetch', val)
(val) => updateAndEmit('onFetch', { val }),
);
watch(
@ -165,7 +166,7 @@ watch(
originalData.value = null;
reset();
await fetch();
}
},
);
onBeforeRouteLeave((to, from, next) => {
@ -194,7 +195,7 @@ async function fetch() {
});
if (Array.isArray(data)) data = data[0] ?? {};
updateAndEmit('onFetch', data);
updateAndEmit('onFetch', { val: data });
} catch (e) {
state.set(modelValue, {});
originalData.value = {};
@ -222,7 +223,11 @@ async function save() {
if ($props.urlCreate) notify('globals.dataCreated', 'positive');
updateAndEmit('onDataSaved', formData.value, response?.data);
updateAndEmit('onDataSaved', {
val: formData.value,
res: response?.data,
old: originalData.value,
});
if ($props.reload) await arrayData.fetch({});
hasChanges.value = false;
} finally {
@ -236,7 +241,7 @@ async function saveAndGo() {
}
function reset() {
updateAndEmit('onFetch', originalData.value);
updateAndEmit('onFetch', { val: originalData.value });
if ($props.observeFormChanges) {
hasChanges.value = false;
isResetting.value = true;
@ -254,16 +259,16 @@ function filter(value, update, filterOptions) {
(ref) => {
ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true);
}
},
);
}
function updateAndEmit(evt, val, res) {
function updateAndEmit(evt, { val, res, old } = { val: null, res: null, old: null }) {
state.set(modelValue, val);
originalData.value = val && JSON.parse(JSON.stringify(val));
if (!$props.url) arrayData.store.data = val;
emit(evt, state.get(modelValue), res);
emit(evt, state.get(modelValue), res, old);
}
function trimData(data) {

View File

@ -49,12 +49,22 @@ onBeforeMount(async () => {
if (props.baseUrl) {
onBeforeRouteUpdate(async (to, from) => {
if (hasRouteParam(to.params)) {
const { matched } = router.currentRoute.value;
const { name } = matched.at(-3);
if (name) {
router.push({ name, params: to.params });
}
}
if (to.params.id !== from.params.id) {
arrayData.store.url = `${props.baseUrl}/${to.params.id}`;
await arrayData.fetch({ append: false, updateRouter: false });
}
});
}
function hasRouteParam(params, valueToCheck = ':addressId') {
return Object.values(params).includes(valueToCheck);
}
</script>
<template>
<Teleport to="#left-panel" v-if="stateStore.isHeaderMounted()">

View File

@ -85,6 +85,7 @@ const handleModelValue = (data) => {
:tooltip="t('Create new location')"
:rules="mixinRules"
:lazy-rules="true"
required
>
<template #form>
<CreateNewPostcode

View File

@ -10,12 +10,7 @@ const emit = defineEmits(['update:modelValue', 'update:options', 'remove']);
const $attrs = useAttrs();
const { t } = useI18n();
const isRequired = computed(() => {
return useRequired($attrs).isRequired;
});
const requiredFieldRule = computed(() => {
return useRequired($attrs).requiredFieldRule;
});
const { isRequired, requiredFieldRule } = useRequired($attrs);
const $props = defineProps({
modelValue: {

View File

@ -0,0 +1,66 @@
import { describe, it, expect, vi } from 'vitest';
import { useRequired } from '../useRequired';
vi.mock('../useValidator', () => ({
useValidator: () => ({
validations: () => ({
required: vi.fn((isRequired, val) => {
if (!isRequired) return true;
return val !== null && val !== undefined && val !== '';
}),
}),
}),
}));
describe('useRequired', () => {
it('should detect required when attr is boolean true', () => {
const attrs = { required: true };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(true);
});
it('should detect required when attr is boolean false', () => {
const attrs = { required: false };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(false);
});
it('should detect required when attr exists without value', () => {
const attrs = { required: '' };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(true);
});
it('should return false when required attr does not exist', () => {
const attrs = { someOtherAttr: 'value' };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(false);
});
describe('requiredFieldRule', () => {
it('should validate required field with value', () => {
const attrs = { required: true };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule('some value')).toBe(true);
});
it('should validate required field with empty value', () => {
const attrs = { required: true };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule('')).toBe(false);
});
it('should pass validation when field is not required', () => {
const attrs = { required: false };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule('')).toBe(true);
});
it('should handle null and undefined values', () => {
const attrs = { required: true };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule(null)).toBe(false);
expect(requiredFieldRule(undefined)).toBe(false);
});
});
});

View File

@ -2,14 +2,10 @@ import { useValidator } from 'src/composables/useValidator';
export function useRequired($attrs) {
const { validations } = useValidator();
const hasRequired = Object.keys($attrs).includes('required');
let isRequired = false;
if (hasRequired) {
const required = $attrs['required'];
if (typeof required === 'boolean') {
isRequired = required;
}
}
const isRequired =
typeof $attrs['required'] === 'boolean'
? $attrs['required']
: Object.keys($attrs).includes('required');
const requiredFieldRule = (val) => validations().required(isRequired, val);
return {

View File

@ -2,7 +2,10 @@
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { useQuasar } from 'quasar';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
@ -10,9 +13,12 @@ import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnLocation from 'src/components/common/VnLocation.vue';
import { getDifferences, getUpdatedValues } from 'src/filters';
import VnConfirm from 'src/components/ui/VnConfirm.vue';
const quasar = useQuasar();
const { t } = useI18n();
const route = useRoute();
const { notify } = useNotify();
const typesTaxes = ref([]);
const typesTransactions = ref([]);
@ -30,6 +36,31 @@ function onBeforeSave(formData, originalData) {
formData,
);
}
async function checkEtChanges(data, _, originalData) {
const equalizatedHasChanged = originalData.isEqualizated != data.isEqualizated;
const hasToInvoiceByAddress =
originalData.hasToInvoiceByAddress || data.hasToInvoiceByAddress;
if (equalizatedHasChanged && hasToInvoiceByAddress) {
quasar.dialog({
component: VnConfirm,
componentProps: {
title: t('You changed the equalization tax'),
message: t('Do you want to spread the change?'),
promise: () => acceptPropagate(data),
},
});
} else if (equalizatedHasChanged) {
await acceptPropagate(data);
}
}
async function acceptPropagate({ isEqualizated }) {
await axios.patch(`Clients/${route.params.id}/addressesPropagateRe`, {
isEqualizated,
});
notify(t('Equivalent tax spreaded'), 'warning');
}
</script>
<template>
@ -44,6 +75,8 @@ function onBeforeSave(formData, originalData) {
auto-load
model="customer"
:mapper="onBeforeSave"
observe-form-changes
@on-data-saved="checkEtChanges"
>
<template #form="{ data, validate }">
<VnRow>
@ -188,6 +221,9 @@ es:
whenActivatingIt: Al activarlo, no informar el código del país en el campo nif
inOrderToInvoice: Para facturar no se consulta este campo, sino el RE de consignatario. Al modificar este campo si no esta marcada la casilla Facturar por consignatario, se propagará automaticamente el cambio a todos lo consignatarios, en caso contrario preguntará al usuario si quiere o no propagar
Daily invoice: Facturación diaria
Equivalent tax spreaded: Recargo de equivalencia propagado
You changed the equalization tax: Has cambiado el recargo de equivalencia
Do you want to spread the change?: ¿Deseas propagar el cambio a sus consignatarios?
en:
onlyLetters: Only letters, numbers and spaces can be used
whenActivatingIt: When activating it, do not enter the country code in the ID field

View File

@ -98,7 +98,6 @@ function onAgentCreated({ id, fiscalName }, data) {
:rules="validate('Worker.postcode')"
:acls="[{ model: 'Town', props: '*', accessType: 'WRITE' }]"
v-model="data.location"
:required="true"
@update:model-value="(location) => handleLocation(data, location)"
/>

View File

@ -49,7 +49,7 @@ const getData = async (observations) => {
notes.value = originalNotes
.map((observation) => {
const type = observationTypes.value.find(
(type) => type.id === observation.observationTypeFk
(type) => type.id === observation.observationTypeFk,
);
return type
? {
@ -96,11 +96,11 @@ const updateObservations = async (payload) => {
await axios.post('AddressObservations/crud', payload);
notes.value = [];
deletes.value = [];
toCustomerAddress();
};
async function updateAll({ data, payload }) {
await updateObservations(payload);
await updateAddress(data);
toCustomerAddress();
}
function getPayload() {
return {
@ -112,8 +112,8 @@ function getPayload() {
(oNote) =>
oNote.id === note.id &&
(note.description !== oNote.description ||
note.observationTypeFk !== oNote.observationTypeFk)
)
note.observationTypeFk !== oNote.observationTypeFk),
),
)
.map((note) => ({
data: note,
@ -130,24 +130,19 @@ async function handleDialog(data) {
.dialog({
component: VnConfirm,
componentProps: {
title: t(
'confirmTicket'
),
title: t('confirmTicket'),
message: t('confirmDeletionMessage'),
},
})
.onOk(async () => {
await updateAddressTicket();
await updateAll(body);
toCustomerAddress();
})
.onCancel(async () => {
await updateAll(body);
toCustomerAddress();
});
} else {
updateAll(body);
toCustomerAddress();
await updateAll(body);
}
}

View File

@ -3,11 +3,46 @@ describe('Client consignee', () => {
beforeEach(() => {
cy.viewport(1280, 720);
cy.login('developer');
cy.visit('#/customer/1110/address', {
timeout: 5000,
});
cy.visit('#/customer/1107/address');
cy.domContentLoad();
});
it('Should load layout', () => {
cy.get('.q-card').should('be.visible');
});
it('check as equalizated', function () {
cy.get('.q-card__section > .address-card').then(($el) => {
let addressCards_before = $el.length;
cy.get('.q-page-sticky > div > .q-btn').click();
const addressName = 'test';
cy.dataCy('Consignee_input').type(addressName);
cy.dataCy('Location_select').click();
cy.get('[role="listbox"] .q-item:nth-child(1)').click();
cy.dataCy('Street address_input').type('TEST ADDRESS');
cy.get('.q-btn-group > .q-btn--standard').click();
cy.location('href').should('contain', '#/customer/1107/address');
cy.get('.q-card__section > .address-card').should(
'have.length',
addressCards_before + 1,
);
cy.get('.q-card__section > .address-card')
.eq(addressCards_before)
.should('be.visible')
.get('.text-weight-bold')
.eq(addressCards_before - 1)
.should('contain', addressName)
.click();
});
cy.get(
'.q-card > :nth-child(1) > :nth-child(2) > .q-checkbox > .q-checkbox__inner',
)
.should('have.class', 'q-checkbox__inner--falsy')
.click();
cy.get('.q-btn-group > .q-btn--standard > .q-btn__content').click();
cy.get(
':nth-child(2) > :nth-child(2) > .flex > .q-mr-lg > .q-checkbox__inner',
).should('have.class', 'q-checkbox__inner--truthy');
});
});

View File

@ -3,9 +3,8 @@ describe('Client fiscal data', () => {
beforeEach(() => {
cy.viewport(1280, 720);
cy.login('developer');
cy.visit('#/customer/1107/fiscal-data', {
timeout: 5000,
});
cy.visit('#/customer/1107/fiscal-data');
cy.domContentLoad();
});
it('Should change required value when change customer', () => {
cy.get('.q-card').should('be.visible');
@ -15,4 +14,25 @@ describe('Client fiscal data', () => {
cy.get('.q-item > .q-item__label').should('have.text', ' #1');
cy.dataCy('sageTaxTypeFk').filter('input').should('have.attr', 'required');
});
it('check as equalizated', () => {
cy.get(
':nth-child(1) > .q-checkbox > .q-checkbox__inner > .q-checkbox__bg',
).click();
cy.get('.q-btn-group > .q-btn--standard > .q-btn__content').click();
cy.get('.q-card > :nth-child(1) > span').should(
'contain',
'You changed the equalization tax',
);
cy.get('.q-card > :nth-child(2) > span').should(
'have.text',
'Do you want to spread the change?',
);
cy.get('[data-cy="VnConfirm_confirm"] > .q-btn__content > .block').click();
cy.get(
'.bg-warning > .q-notification__wrapper > .q-notification__content > .q-notification__message',
).should('have.text', 'Equivalent tax spreaded');
});
});