refactor(sync) : remove restrictedMode and add sync service + confirmation modal
This commit is contained in:
@@ -10,7 +10,6 @@
|
||||
:locked-type-label="displayedRootTypeLabel"
|
||||
:allow-subcomponents="allowSubcomponents"
|
||||
:max-subcomponent-depth="maxSubcomponentDepth"
|
||||
:restricted-mode="restrictedMode"
|
||||
is-root
|
||||
/>
|
||||
</div>
|
||||
@@ -56,10 +55,6 @@ const props = defineProps({
|
||||
type: Number,
|
||||
default: Infinity,
|
||||
},
|
||||
restrictedMode: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
|
||||
@@ -29,7 +29,6 @@
|
||||
<select
|
||||
v-model="product.typeProductId"
|
||||
class="select select-bordered select-xs"
|
||||
:disabled="isProductLocked(product)"
|
||||
@change="handleProductTypeSelect(product)"
|
||||
>
|
||||
<option value="">
|
||||
@@ -46,26 +45,16 @@
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-if="!isProductLocked(product)"
|
||||
type="button"
|
||||
class="btn btn-error btn-xs btn-square"
|
||||
@click="removeProduct(index)"
|
||||
>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
<div v-else class="tooltip tooltip-left" data-tip="Ce produit ne peut pas être supprimé car des éléments utilisent cette catégorie">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-ghost btn-xs btn-square opacity-30 cursor-not-allowed"
|
||||
disabled
|
||||
>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<button v-if="!restrictedMode" type="button" class="btn btn-outline btn-xs" @click="addProduct">
|
||||
<button type="button" class="btn btn-outline btn-xs" @click="addProduct">
|
||||
<IconLucidePlus class="w-3 h-3 mr-2" aria-hidden="true" />
|
||||
Ajouter
|
||||
</button>
|
||||
@@ -111,7 +100,7 @@
|
||||
class="input input-bordered input-xs"
|
||||
placeholder="Nom du champ"
|
||||
>
|
||||
<select v-model="field.type" class="select select-bordered select-xs" :disabled="isFieldLocked(field)">
|
||||
<select v-model="field.type" class="select select-bordered select-xs">
|
||||
<option value="text">
|
||||
Texte
|
||||
</option>
|
||||
@@ -131,7 +120,7 @@
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 text-xs">
|
||||
<input v-model="field.required" type="checkbox" class="checkbox checkbox-xs" :disabled="isFieldLocked(field)">
|
||||
<input v-model="field.required" type="checkbox" class="checkbox checkbox-xs">
|
||||
Obligatoire
|
||||
</div>
|
||||
|
||||
@@ -140,27 +129,16 @@
|
||||
v-model="field.optionsText"
|
||||
class="textarea textarea-bordered textarea-xs h-20"
|
||||
placeholder="Option 1 Option 2"
|
||||
:disabled="isFieldLocked(field)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="!isFieldLocked(field)"
|
||||
type="button"
|
||||
class="btn btn-error btn-xs btn-square"
|
||||
@click="removeField(index)"
|
||||
>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
<div v-else class="tooltip tooltip-left" data-tip="Ce champ ne peut pas être supprimé car des éléments utilisent cette catégorie">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-ghost btn-xs btn-square opacity-30 cursor-not-allowed"
|
||||
disabled
|
||||
>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
@@ -183,7 +161,6 @@ defineOptions({ name: 'PieceModelStructureEditor' })
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue?: PieceModelStructure | null
|
||||
restrictedMode?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -194,9 +171,6 @@ const {
|
||||
fields,
|
||||
products,
|
||||
productTypeOptions,
|
||||
restrictedMode,
|
||||
isFieldLocked,
|
||||
isProductLocked,
|
||||
formatProductTypeOption,
|
||||
handleProductTypeSelect,
|
||||
addProduct,
|
||||
|
||||
@@ -109,7 +109,7 @@
|
||||
class="input input-bordered input-xs"
|
||||
placeholder="Nom du champ"
|
||||
/>
|
||||
<select v-model="field.type" class="select select-bordered select-xs" :disabled="isCustomFieldLocked(index)">
|
||||
<select v-model="field.type" class="select select-bordered select-xs">
|
||||
<option value="text">Texte</option>
|
||||
<option value="number">Nombre</option>
|
||||
<option value="select">Liste</option>
|
||||
@@ -118,7 +118,7 @@
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-xs">
|
||||
<input v-model="field.required" type="checkbox" class="checkbox checkbox-xs" :disabled="isCustomFieldLocked(index)" />
|
||||
<input v-model="field.required" type="checkbox" class="checkbox checkbox-xs" />
|
||||
Obligatoire
|
||||
</div>
|
||||
<textarea
|
||||
@@ -126,26 +126,15 @@
|
||||
v-model="field.optionsText"
|
||||
class="textarea textarea-bordered textarea-xs h-20"
|
||||
placeholder="Option 1 Option 2"
|
||||
:disabled="isCustomFieldLocked(index)"
|
||||
></textarea>
|
||||
</div>
|
||||
<button
|
||||
v-if="!isCustomFieldLocked(index)"
|
||||
type="button"
|
||||
class="btn btn-error btn-xs btn-square"
|
||||
@click="removeCustomField(index)"
|
||||
>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
<div v-else class="tooltip tooltip-left" data-tip="Ce champ ne peut pas être supprimé car des éléments utilisent cette catégorie">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-ghost btn-xs btn-square opacity-30 cursor-not-allowed"
|
||||
disabled
|
||||
>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -189,7 +178,6 @@
|
||||
<select
|
||||
v-model="product.typeProductId"
|
||||
class="select select-bordered select-xs"
|
||||
:disabled="isProductLocked(index)"
|
||||
@change="handleProductTypeSelect(product)"
|
||||
>
|
||||
<option value="">
|
||||
@@ -205,22 +193,13 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="!isProductLocked(index)" type="button" class="btn btn-error btn-xs btn-square" @click="removeProduct(index)">
|
||||
<button type="button" class="btn btn-error btn-xs btn-square" @click="removeProduct(index)">
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
<div v-else class="tooltip tooltip-left" data-tip="Ce produit ne peut pas être supprimé car des éléments utilisent cette catégorie">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-ghost btn-xs btn-square opacity-30 cursor-not-allowed"
|
||||
disabled
|
||||
>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="!restrictedMode" type="button" class="btn btn-outline btn-xs" @click="addProduct">
|
||||
<button type="button" class="btn btn-outline btn-xs" @click="addProduct">
|
||||
<IconLucidePlus class="w-3 h-3 mr-2" aria-hidden="true" />
|
||||
Ajouter
|
||||
</button>
|
||||
@@ -261,7 +240,6 @@
|
||||
<select
|
||||
v-model="piece.typePieceId"
|
||||
class="select select-bordered select-xs"
|
||||
:disabled="isPieceLocked(index)"
|
||||
@change="handlePieceTypeSelect(piece)"
|
||||
>
|
||||
<option value="">
|
||||
@@ -293,18 +271,13 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="!isPieceLocked(index)" type="button" class="btn btn-error btn-xs btn-square" @click="removePiece(index)">
|
||||
<button type="button" class="btn btn-error btn-xs btn-square" @click="removePiece(index)">
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
<div v-else class="tooltip tooltip-left" data-tip="Cette pièce ne peut pas être supprimée">
|
||||
<button type="button" class="btn btn-ghost btn-xs btn-square opacity-30 cursor-not-allowed" disabled>
|
||||
<IconLucideTrash class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="!restrictedMode" type="button" class="btn btn-outline btn-xs" @click="addPiece">
|
||||
<button type="button" class="btn btn-outline btn-xs" @click="addPiece">
|
||||
<IconLucidePlus class="w-3 h-3 mr-2" aria-hidden="true" />
|
||||
Ajouter
|
||||
</button>
|
||||
@@ -346,14 +319,12 @@
|
||||
:product-types="productTypes"
|
||||
:allow-subcomponents="childAllowSubcomponents"
|
||||
:max-subcomponent-depth="maxSubcomponentDepth"
|
||||
:restricted-mode="restrictedMode"
|
||||
:is-locked="isSubcomponentLocked(index)"
|
||||
@remove="removeSubComponent(index)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-if="canManageSubcomponents && !restrictedMode"
|
||||
v-if="canManageSubcomponents"
|
||||
type="button"
|
||||
class="btn btn-outline btn-xs"
|
||||
@click="addSubComponent"
|
||||
@@ -386,7 +357,6 @@ const props = withDefaults(defineProps<{
|
||||
lockedTypeLabel?: string
|
||||
allowSubcomponents?: boolean
|
||||
maxSubcomponentDepth?: number
|
||||
restrictedMode?: boolean
|
||||
isLocked?: boolean
|
||||
}>(), {
|
||||
depth: 0,
|
||||
@@ -398,19 +368,13 @@ const props = withDefaults(defineProps<{
|
||||
lockedTypeLabel: '',
|
||||
allowSubcomponents: true,
|
||||
maxSubcomponentDepth: Infinity,
|
||||
restrictedMode: false,
|
||||
isLocked: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits(['remove'])
|
||||
|
||||
const {
|
||||
isCustomFieldLocked,
|
||||
isPieceLocked,
|
||||
isProductLocked,
|
||||
isSubcomponentLocked,
|
||||
isLocked,
|
||||
restrictedMode,
|
||||
componentTypes,
|
||||
pieceTypes,
|
||||
productTypes,
|
||||
|
||||
112
app/components/SyncConfirmationModal.vue
Normal file
112
app/components/SyncConfirmationModal.vue
Normal file
@@ -0,0 +1,112 @@
|
||||
<script setup lang="ts">
|
||||
import type { SyncPreviewResult } from '~/services/modelTypes';
|
||||
|
||||
const props = defineProps<{
|
||||
preview: SyncPreviewResult | null;
|
||||
open: boolean;
|
||||
loading: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [];
|
||||
cancel: [];
|
||||
}>();
|
||||
|
||||
const dialogRef = ref<HTMLDialogElement>();
|
||||
|
||||
watch(() => props.open, (isOpen) => {
|
||||
if (isOpen) {
|
||||
dialogRef.value?.showModal();
|
||||
}
|
||||
else {
|
||||
dialogRef.value?.close();
|
||||
}
|
||||
});
|
||||
|
||||
const hasDeletions = computed(() => {
|
||||
if (!props.preview) return false;
|
||||
return Object.values(props.preview.deletions).some(v => v > 0);
|
||||
});
|
||||
|
||||
const hasModifications = computed(() => {
|
||||
if (!props.preview) return false;
|
||||
return Object.values(props.preview.modifications).some(v => v > 0);
|
||||
});
|
||||
|
||||
const totalAdditions = computed(() => {
|
||||
if (!props.preview) return 0;
|
||||
return Object.values(props.preview.additions).reduce((sum, v) => sum + v, 0);
|
||||
});
|
||||
|
||||
const totalDeletions = computed(() => {
|
||||
if (!props.preview) return 0;
|
||||
return Object.values(props.preview.deletions).reduce((sum, v) => sum + v, 0);
|
||||
});
|
||||
|
||||
const totalModifications = computed(() => {
|
||||
if (!props.preview) return 0;
|
||||
return Object.values(props.preview.modifications).reduce((sum, v) => sum + v, 0);
|
||||
});
|
||||
|
||||
function handleCancel() {
|
||||
emit('cancel');
|
||||
}
|
||||
|
||||
function handleConfirm() {
|
||||
emit('confirm');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<dialog ref="dialogRef" class="modal" @close="handleCancel">
|
||||
<div class="modal-box">
|
||||
<h3 class="text-lg font-bold">
|
||||
Synchronisation des éléments liés
|
||||
</h3>
|
||||
|
||||
<div v-if="preview" class="py-4 space-y-3">
|
||||
<p>
|
||||
Cette modification impactera
|
||||
<strong>{{ preview.itemCount }}</strong>
|
||||
élément(s) lié(s).
|
||||
</p>
|
||||
|
||||
<ul class="list-disc list-inside space-y-1">
|
||||
<li v-if="totalAdditions > 0" class="text-success">
|
||||
{{ totalAdditions }} ajout(s)
|
||||
</li>
|
||||
<li v-if="totalDeletions > 0" class="text-error">
|
||||
{{ totalDeletions }} suppression(s)
|
||||
</li>
|
||||
<li v-if="totalModifications > 0" class="text-warning">
|
||||
{{ totalModifications }} modification(s)
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-if="hasDeletions" role="alert" class="alert alert-warning">
|
||||
<span>Des éléments seront supprimés. Cette action est irréversible.</span>
|
||||
</div>
|
||||
|
||||
<div v-if="hasModifications" role="alert" class="alert alert-info">
|
||||
<span>Des valeurs de champs personnalisés seront réinitialisées.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-action">
|
||||
<button class="btn btn-ghost" :disabled="loading" @click="handleCancel">
|
||||
Annuler
|
||||
</button>
|
||||
<button class="btn btn-primary" :disabled="loading" @click="handleConfirm">
|
||||
<span v-if="loading" class="loading loading-spinner loading-sm" />
|
||||
Confirmer la synchronisation
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form method="dialog" class="modal-backdrop">
|
||||
<button @click="handleCancel">
|
||||
close
|
||||
</button>
|
||||
</form>
|
||||
</dialog>
|
||||
</template>
|
||||
@@ -15,8 +15,7 @@
|
||||
minlength="2"
|
||||
maxlength="120"
|
||||
required
|
||||
:disabled="restrictedMode"
|
||||
/>
|
||||
/>
|
||||
<p v-if="errors.name" class="mt-1 text-sm text-error">{{ errors.name }}</p>
|
||||
</div>
|
||||
<div>
|
||||
@@ -48,7 +47,6 @@
|
||||
rows="4"
|
||||
name="notes"
|
||||
maxlength="2000"
|
||||
:disabled="restrictedMode"
|
||||
></textarea>
|
||||
<p class="mt-1 text-xs text-base-content/70">Saisissez des informations complémentaires (facultatif).</p>
|
||||
</div>
|
||||
@@ -83,7 +81,6 @@
|
||||
v-model="componentStructure"
|
||||
:allow-subcomponents="allowComponentSubcomponents"
|
||||
:max-subcomponent-depth="componentSubcomponentMaxDepth"
|
||||
:restricted-mode="restrictedMode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -95,7 +92,7 @@
|
||||
Aperçu :
|
||||
<span class="font-medium text-base-content">{{ pieceStructurePreview }}</span>
|
||||
</p>
|
||||
<PieceModelStructureEditor v-model="pieceStructure" :restricted-mode="restrictedMode" />
|
||||
<PieceModelStructureEditor v-model="pieceStructure" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -106,30 +103,11 @@
|
||||
Aperçu :
|
||||
<span class="font-medium text-base-content">{{ productStructurePreview }}</span>
|
||||
</p>
|
||||
<PieceModelStructureEditor v-model="productStructure" :restricted-mode="restrictedMode" />
|
||||
<PieceModelStructureEditor v-model="productStructure" />
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="restrictedMode && restrictedModeMessage"
|
||||
class="alert alert-info"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current shrink-0 w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
|
||||
<span>{{ restrictedModeMessage }}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="disableSubmit"
|
||||
class="alert alert-warning"
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
>
|
||||
<span>{{ disableSubmitMessage }}</span>
|
||||
</div>
|
||||
|
||||
<footer class="flex flex-col gap-3 border-t border-base-300 pt-4 sm:flex-row sm:justify-end">
|
||||
<button type="button" class="btn btn-ghost" :disabled="saving" @click="emit('cancel')">
|
||||
Annuler
|
||||
@@ -172,10 +150,6 @@ const props = withDefaults(defineProps<{
|
||||
structureLoading?: boolean
|
||||
allowComponentSubcomponents?: boolean
|
||||
componentSubcomponentMaxDepth?: number
|
||||
disableSubmit?: boolean
|
||||
disableSubmitMessage?: string
|
||||
restrictedMode?: boolean
|
||||
restrictedModeMessage?: string
|
||||
readonly?: boolean
|
||||
}>(), {
|
||||
initialData: null,
|
||||
@@ -184,10 +158,6 @@ const props = withDefaults(defineProps<{
|
||||
structureLoading: false,
|
||||
allowComponentSubcomponents: true,
|
||||
componentSubcomponentMaxDepth: 1,
|
||||
disableSubmit: false,
|
||||
disableSubmitMessage: '',
|
||||
restrictedMode: false,
|
||||
restrictedModeMessage: '',
|
||||
readonly: false,
|
||||
})
|
||||
|
||||
@@ -205,19 +175,7 @@ const componentSubcomponentMaxDepth = computed(() =>
|
||||
? props.componentSubcomponentMaxDepth
|
||||
: 1,
|
||||
)
|
||||
const disableSubmit = computed(() => props.disableSubmit === true)
|
||||
const disableSubmitMessage = computed(() =>
|
||||
(props.disableSubmitMessage && props.disableSubmitMessage.trim())
|
||||
? props.disableSubmitMessage
|
||||
: 'Cette catégorie ne peut pas être modifiée car des éléments y sont déjà liés.',
|
||||
)
|
||||
const isReadonly = computed(() => props.readonly === true)
|
||||
const restrictedMode = computed(() => props.restrictedMode === true || isReadonly.value)
|
||||
const restrictedModeMessage = computed(() =>
|
||||
(props.restrictedModeMessage && props.restrictedModeMessage.trim())
|
||||
? props.restrictedModeMessage
|
||||
: '',
|
||||
)
|
||||
|
||||
const form = reactive<ModelTypePayload>({
|
||||
name: '',
|
||||
@@ -294,7 +252,7 @@ const resetForm = () => {
|
||||
}
|
||||
|
||||
const submitLabel = computed(() => (props.mode === 'edit' ? 'Enregistrer' : 'Créer'))
|
||||
const isSubmitDisabled = computed(() => saving.value || structureLoading.value || disableSubmit.value || isReadonly.value)
|
||||
const isSubmitDisabled = computed(() => saving.value || structureLoading.value || isReadonly.value)
|
||||
|
||||
const validate = () => {
|
||||
errors.name = undefined
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { useApi } from '~/composables/useApi'
|
||||
import { useToast } from '~/composables/useToast'
|
||||
|
||||
type GuardLabels = {
|
||||
singular: string
|
||||
plural: string
|
||||
verifying: string
|
||||
}
|
||||
|
||||
type GuardConfig = {
|
||||
endpoint: string
|
||||
filterKey: string
|
||||
labels: GuardLabels
|
||||
}
|
||||
|
||||
const extractTotal = (payload: any, fallbackLength: number) => {
|
||||
if (typeof payload?.totalItems === 'number') {
|
||||
return payload.totalItems
|
||||
}
|
||||
if (typeof payload?.['hydra:totalItems'] === 'number') {
|
||||
return payload['hydra:totalItems']
|
||||
}
|
||||
if (Array.isArray(payload?.member)) {
|
||||
return payload.member.length
|
||||
}
|
||||
if (Array.isArray(payload?.['hydra:member'])) {
|
||||
return payload['hydra:member'].length
|
||||
}
|
||||
return fallbackLength
|
||||
}
|
||||
|
||||
export function useCategoryEditGuard (config: GuardConfig) {
|
||||
const { get } = useApi()
|
||||
const { showInfo } = useToast()
|
||||
|
||||
const linkedCount = ref(0)
|
||||
const linkedLoading = ref(false)
|
||||
|
||||
const loadLinkedCount = async (modelTypeId: string) => {
|
||||
linkedLoading.value = true
|
||||
try {
|
||||
const params = new URLSearchParams()
|
||||
params.set('itemsPerPage', '1')
|
||||
params.set(config.filterKey, `/api/model_types/${modelTypeId}`)
|
||||
|
||||
const result = await get(`${config.endpoint}?${params.toString()}`)
|
||||
if (!result.success) {
|
||||
linkedCount.value = 0
|
||||
return
|
||||
}
|
||||
|
||||
const fallbackLength = Array.isArray(result.data?.member)
|
||||
? result.data.member.length
|
||||
: Array.isArray(result.data?.['hydra:member'])
|
||||
? result.data['hydra:member'].length
|
||||
: 0
|
||||
|
||||
linkedCount.value = extractTotal(result.data, fallbackLength)
|
||||
} catch (_error) {
|
||||
linkedCount.value = 0
|
||||
} finally {
|
||||
linkedLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const isRestrictedMode = computed(
|
||||
() => !linkedLoading.value && linkedCount.value > 0,
|
||||
)
|
||||
|
||||
const isSubmitBlocked = computed(
|
||||
() => linkedLoading.value,
|
||||
)
|
||||
|
||||
const restrictedModeMessage = computed(() => {
|
||||
if (linkedLoading.value) {
|
||||
return config.labels.verifying
|
||||
}
|
||||
if (linkedCount.value <= 0) {
|
||||
return ''
|
||||
}
|
||||
if (linkedCount.value === 1) {
|
||||
return `Mode restreint : 1 ${config.labels.singular} est déjà lié à cette catégorie. Vous pouvez ajouter de nouveaux champs personnalisés et renommer les existants, mais pas modifier leur type ou les supprimer.`
|
||||
}
|
||||
return `Mode restreint : ${linkedCount.value} ${config.labels.plural} sont déjà liés à cette catégorie. Vous pouvez ajouter de nouveaux champs personnalisés et renommer les existants, mais pas modifier leur type ou les supprimer.`
|
||||
})
|
||||
|
||||
const submitBlockMessage = computed(() => {
|
||||
if (linkedLoading.value) {
|
||||
return config.labels.verifying
|
||||
}
|
||||
return ''
|
||||
})
|
||||
|
||||
const guardSubmitOrNotify = () => {
|
||||
if (!isSubmitBlocked.value) {
|
||||
return false
|
||||
}
|
||||
showInfo(submitBlockMessage.value || 'Veuillez patienter...')
|
||||
return true
|
||||
}
|
||||
|
||||
return {
|
||||
linkedCount,
|
||||
linkedLoading,
|
||||
isRestrictedMode,
|
||||
isSubmitBlocked,
|
||||
restrictedModeMessage,
|
||||
submitBlockMessage,
|
||||
loadLinkedCount,
|
||||
guardSubmitOrNotify,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ export type EditorProduct = {
|
||||
interface Deps {
|
||||
props: {
|
||||
modelValue?: PieceModelStructure | null
|
||||
restrictedMode?: boolean
|
||||
}
|
||||
emit: (event: 'update:modelValue', value: PieceModelStructure) => void
|
||||
}
|
||||
@@ -202,8 +201,6 @@ export function usePieceStructureEditorLogic(deps: Deps) {
|
||||
const products = ref<EditorProduct[]>(hydrateProducts(props.modelValue))
|
||||
const restState = ref<Record<string, unknown>>(extractRest(props.modelValue))
|
||||
|
||||
const initialFieldUids = ref<Set<string>>(new Set(fields.value.map(f => f.uid)))
|
||||
const initialProductUids = ref<Set<string>>(new Set(products.value.map(p => p.uid)))
|
||||
|
||||
// --- Product types ---
|
||||
|
||||
@@ -250,18 +247,6 @@ export function usePieceStructureEditorLogic(deps: Deps) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Locked state ---
|
||||
|
||||
const isFieldLocked = (field: EditorField): boolean => {
|
||||
return props.restrictedMode === true && initialFieldUids.value.has(field.uid)
|
||||
}
|
||||
|
||||
const isProductLocked = (product: EditorProduct): boolean => {
|
||||
return props.restrictedMode === true && initialProductUids.value.has(product.uid)
|
||||
}
|
||||
|
||||
const restrictedMode = computed(() => props.restrictedMode === true)
|
||||
|
||||
// --- CRUD ---
|
||||
|
||||
const createEmptyProduct = (): EditorProduct => ({
|
||||
@@ -407,8 +392,6 @@ export function usePieceStructureEditorLogic(deps: Deps) {
|
||||
products.value = hydrateProducts(value)
|
||||
products.value.forEach(product => updateProductTypeMetadata(product))
|
||||
lastEmitted = incomingSerialized
|
||||
initialFieldUids.value = new Set(fields.value.map(f => f.uid))
|
||||
initialProductUids.value = new Set(products.value.map(p => p.uid))
|
||||
},
|
||||
{ deep: true },
|
||||
)
|
||||
@@ -426,9 +409,6 @@ export function usePieceStructureEditorLogic(deps: Deps) {
|
||||
fields,
|
||||
products,
|
||||
productTypeOptions,
|
||||
restrictedMode,
|
||||
isFieldLocked,
|
||||
isProductLocked,
|
||||
formatProductTypeOption,
|
||||
handleProductTypeSelect,
|
||||
addProduct,
|
||||
|
||||
@@ -1,51 +1,11 @@
|
||||
import { ref } from 'vue'
|
||||
import type { EditableStructureNode } from '~/composables/useStructureNodeLogic'
|
||||
|
||||
export interface StructureNodeCrudDeps {
|
||||
node: EditableStructureNode
|
||||
restrictedMode: boolean
|
||||
canManageSubcomponents: () => boolean
|
||||
}
|
||||
|
||||
export function useStructureNodeCrud(props: StructureNodeCrudDeps) {
|
||||
// --- Lock state ---
|
||||
const initialCustomFieldIndices = ref<Set<number>>(new Set())
|
||||
const initialPieceIndices = ref<Set<number>>(new Set())
|
||||
const initialProductIndices = ref<Set<number>>(new Set())
|
||||
const initialSubcomponentIndices = ref<Set<number>>(new Set())
|
||||
|
||||
const initializeLockedIndices = () => {
|
||||
if (props.restrictedMode) {
|
||||
const customFieldsLength = Array.isArray(props.node.customFields) ? props.node.customFields.length : 0
|
||||
const piecesLength = Array.isArray(props.node.pieces) ? props.node.pieces.length : 0
|
||||
const productsLength = Array.isArray(props.node.products) ? props.node.products.length : 0
|
||||
const subcomponentsLength = Array.isArray(props.node.subcomponents) ? props.node.subcomponents.length : 0
|
||||
|
||||
initialCustomFieldIndices.value = new Set(Array.from({ length: customFieldsLength }, (_, i) => i))
|
||||
initialPieceIndices.value = new Set(Array.from({ length: piecesLength }, (_, i) => i))
|
||||
initialProductIndices.value = new Set(Array.from({ length: productsLength }, (_, i) => i))
|
||||
initialSubcomponentIndices.value = new Set(Array.from({ length: subcomponentsLength }, (_, i) => i))
|
||||
}
|
||||
}
|
||||
|
||||
initializeLockedIndices()
|
||||
|
||||
const isCustomFieldLocked = (index: number): boolean => {
|
||||
return props.restrictedMode === true && initialCustomFieldIndices.value.has(index)
|
||||
}
|
||||
|
||||
const isPieceLocked = (index: number): boolean => {
|
||||
return props.restrictedMode === true && initialPieceIndices.value.has(index)
|
||||
}
|
||||
|
||||
const isProductLocked = (index: number): boolean => {
|
||||
return props.restrictedMode === true && initialProductIndices.value.has(index)
|
||||
}
|
||||
|
||||
const isSubcomponentLocked = (index: number): boolean => {
|
||||
return props.restrictedMode === true && initialSubcomponentIndices.value.has(index)
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
const ensureArray = (key: 'customFields' | 'pieces' | 'products' | 'subcomponents') => {
|
||||
if (!Array.isArray((props.node as any)[key])) {
|
||||
@@ -159,11 +119,6 @@ export function useStructureNodeCrud(props: StructureNodeCrudDeps) {
|
||||
}
|
||||
|
||||
return {
|
||||
// Lock checks
|
||||
isCustomFieldLocked,
|
||||
isPieceLocked,
|
||||
isProductLocked,
|
||||
isSubcomponentLocked,
|
||||
// Helpers exposed for watchers
|
||||
reindexCustomFields,
|
||||
// CRUD
|
||||
|
||||
@@ -25,14 +25,12 @@ export interface StructureNodeLogicDeps {
|
||||
lockedTypeLabel: string
|
||||
allowSubcomponents: boolean
|
||||
maxSubcomponentDepth: number
|
||||
restrictedMode: boolean
|
||||
isLocked: boolean
|
||||
}
|
||||
|
||||
export function useStructureNodeLogic(props: StructureNodeLogicDeps) {
|
||||
// --- Computed props ---
|
||||
const isLocked = computed(() => props.isLocked === true)
|
||||
const restrictedMode = computed(() => props.restrictedMode === true)
|
||||
|
||||
const componentTypes = computed(() => props.componentTypes ?? [])
|
||||
const pieceTypes = computed(() => props.pieceTypes ?? [])
|
||||
@@ -310,7 +308,6 @@ export function useStructureNodeLogic(props: StructureNodeLogicDeps) {
|
||||
// --- CRUD & Lock (delegated to useStructureNodeCrud) ---
|
||||
const crud = useStructureNodeCrud({
|
||||
node: props.node,
|
||||
restrictedMode: props.restrictedMode,
|
||||
canManageSubcomponents: () => canManageSubcomponents.value,
|
||||
})
|
||||
|
||||
@@ -395,14 +392,8 @@ export function useStructureNodeLogic(props: StructureNodeLogicDeps) {
|
||||
)
|
||||
|
||||
return {
|
||||
// Lock checks
|
||||
isCustomFieldLocked: crud.isCustomFieldLocked,
|
||||
isPieceLocked: crud.isPieceLocked,
|
||||
isProductLocked: crud.isProductLocked,
|
||||
isSubcomponentLocked: crud.isSubcomponentLocked,
|
||||
// Computed state
|
||||
isLocked,
|
||||
restrictedMode,
|
||||
componentTypes,
|
||||
pieceTypes,
|
||||
productTypes,
|
||||
|
||||
@@ -27,10 +27,6 @@
|
||||
:lock-category="true"
|
||||
:saving="saving"
|
||||
:readonly="!canEdit"
|
||||
:disable-submit="isSubmitBlocked"
|
||||
:disable-submit-message="submitBlockMessage"
|
||||
:restricted-mode="isRestrictedMode"
|
||||
:restricted-mode-message="restrictedModeMessage"
|
||||
@submit="handleSubmit"
|
||||
@cancel="handleCancel"
|
||||
/>
|
||||
@@ -54,7 +50,6 @@ import { useHead, useRoute, useRouter } from '#imports'
|
||||
import ModelTypeForm from '~/components/model-types/ModelTypeForm.vue'
|
||||
import { getModelType, updateModelType, type ModelTypePayload } from '~/services/modelTypes'
|
||||
import type { ComponentModelStructure } from '~/shared/types/inventory'
|
||||
import { useCategoryEditGuard } from '~/composables/useCategoryEditGuard'
|
||||
import { useComponentTypes } from '~/composables/useComponentTypes'
|
||||
import { useToast } from '~/composables/useToast'
|
||||
|
||||
@@ -68,23 +63,6 @@ const loading = ref(true)
|
||||
const saving = ref(false)
|
||||
const initialData = ref<Partial<ModelTypePayload> | null>(null)
|
||||
|
||||
const {
|
||||
isRestrictedMode,
|
||||
isSubmitBlocked,
|
||||
restrictedModeMessage,
|
||||
submitBlockMessage,
|
||||
loadLinkedCount,
|
||||
guardSubmitOrNotify,
|
||||
} = useCategoryEditGuard({
|
||||
endpoint: '/composants',
|
||||
filterKey: 'typeComposant',
|
||||
labels: {
|
||||
singular: 'composant',
|
||||
plural: 'composants',
|
||||
verifying: 'Vérification des composants liés en cours…',
|
||||
},
|
||||
})
|
||||
|
||||
const title = computed(() =>
|
||||
initialData.value?.name
|
||||
? `Modifier « ${initialData.value.name} »`
|
||||
@@ -126,7 +104,6 @@ const loadCategory = async () => {
|
||||
structure: (response.structure as ComponentModelStructure | null) ?? undefined,
|
||||
}
|
||||
|
||||
await loadLinkedCount(id)
|
||||
} catch (error) {
|
||||
showError(normalizeError(error))
|
||||
await navigateBackToList()
|
||||
@@ -141,9 +118,6 @@ const handleCancel = () => {
|
||||
|
||||
const handleSubmit = async (payload: Parameters<typeof updateModelType>[1]) => {
|
||||
if (!canEdit.value) return
|
||||
if (guardSubmitOrNotify()) {
|
||||
return
|
||||
}
|
||||
const id = String(route.params.id)
|
||||
saving.value = true
|
||||
try {
|
||||
|
||||
@@ -27,10 +27,6 @@
|
||||
:lock-category="true"
|
||||
:saving="saving"
|
||||
:readonly="!canEdit"
|
||||
:disable-submit="isSubmitBlocked"
|
||||
:disable-submit-message="submitBlockMessage"
|
||||
:restricted-mode="isRestrictedMode"
|
||||
:restricted-mode-message="restrictedModeMessage"
|
||||
@submit="handleSubmit"
|
||||
@cancel="handleCancel"
|
||||
/>
|
||||
@@ -54,7 +50,6 @@ import { useHead, useRoute, useRouter } from '#imports'
|
||||
import ModelTypeForm from '~/components/model-types/ModelTypeForm.vue'
|
||||
import { getModelType, updateModelType, type ModelTypePayload } from '~/services/modelTypes'
|
||||
import type { PieceModelStructure } from '~/shared/types/inventory'
|
||||
import { useCategoryEditGuard } from '~/composables/useCategoryEditGuard'
|
||||
import { usePieceTypes } from '~/composables/usePieceTypes'
|
||||
import { useToast } from '~/composables/useToast'
|
||||
|
||||
@@ -68,23 +63,6 @@ const loading = ref(true)
|
||||
const saving = ref(false)
|
||||
const initialData = ref<Partial<ModelTypePayload> | null>(null)
|
||||
|
||||
const {
|
||||
isRestrictedMode,
|
||||
isSubmitBlocked,
|
||||
restrictedModeMessage,
|
||||
submitBlockMessage,
|
||||
loadLinkedCount,
|
||||
guardSubmitOrNotify,
|
||||
} = useCategoryEditGuard({
|
||||
endpoint: '/pieces',
|
||||
filterKey: 'typePiece',
|
||||
labels: {
|
||||
singular: 'pièce',
|
||||
plural: 'pièces',
|
||||
verifying: 'Vérification des pièces liées en cours…',
|
||||
},
|
||||
})
|
||||
|
||||
const title = computed(() =>
|
||||
initialData.value?.name ? `Modifier « ${initialData.value.name} »` : 'Modifier une catégorie de pièce',
|
||||
)
|
||||
@@ -124,7 +102,6 @@ const loadCategory = async () => {
|
||||
structure: (response.structure as PieceModelStructure | null) ?? undefined,
|
||||
}
|
||||
|
||||
await loadLinkedCount(id)
|
||||
} catch (error) {
|
||||
showError(normalizeError(error))
|
||||
await navigateBackToList()
|
||||
@@ -139,9 +116,6 @@ const handleCancel = () => {
|
||||
|
||||
const handleSubmit = async (payload: Parameters<typeof updateModelType>[1]) => {
|
||||
if (!canEdit.value) return
|
||||
if (guardSubmitOrNotify()) {
|
||||
return
|
||||
}
|
||||
const id = String(route.params.id)
|
||||
saving.value = true
|
||||
try {
|
||||
|
||||
@@ -27,10 +27,6 @@
|
||||
:lock-category="true"
|
||||
:saving="saving"
|
||||
:readonly="!canEdit"
|
||||
:disable-submit="isSubmitBlocked"
|
||||
:disable-submit-message="submitBlockMessage"
|
||||
:restricted-mode="isRestrictedMode"
|
||||
:restricted-mode-message="restrictedModeMessage"
|
||||
@submit="handleSubmit"
|
||||
@cancel="handleCancel"
|
||||
/>
|
||||
@@ -54,7 +50,6 @@ import { useHead, useRoute, useRouter } from '#imports'
|
||||
import ModelTypeForm from '~/components/model-types/ModelTypeForm.vue'
|
||||
import { getModelType, updateModelType, type ModelTypePayload } from '~/services/modelTypes'
|
||||
import type { ProductModelStructure } from '~/shared/types/inventory'
|
||||
import { useCategoryEditGuard } from '~/composables/useCategoryEditGuard'
|
||||
import { useProductTypes } from '~/composables/useProductTypes'
|
||||
import { useToast } from '~/composables/useToast'
|
||||
|
||||
@@ -68,23 +63,6 @@ const loading = ref(true)
|
||||
const saving = ref(false)
|
||||
const initialData = ref<Partial<ModelTypePayload> | null>(null)
|
||||
|
||||
const {
|
||||
isRestrictedMode,
|
||||
isSubmitBlocked,
|
||||
restrictedModeMessage,
|
||||
submitBlockMessage,
|
||||
loadLinkedCount,
|
||||
guardSubmitOrNotify,
|
||||
} = useCategoryEditGuard({
|
||||
endpoint: '/products',
|
||||
filterKey: 'typeProduct',
|
||||
labels: {
|
||||
singular: 'produit',
|
||||
plural: 'produits',
|
||||
verifying: 'Vérification des produits liés en cours…',
|
||||
},
|
||||
})
|
||||
|
||||
const title = computed(() =>
|
||||
initialData.value?.name ? `Modifier « ${initialData.value.name} »` : 'Modifier une catégorie de produit',
|
||||
)
|
||||
@@ -124,7 +102,6 @@ const loadCategory = async () => {
|
||||
structure: (response.structure as ProductModelStructure | null) ?? undefined,
|
||||
}
|
||||
|
||||
await loadLinkedCount(id)
|
||||
} catch (error) {
|
||||
showError(normalizeError(error))
|
||||
await navigateBackToList()
|
||||
@@ -139,9 +116,6 @@ const handleCancel = () => {
|
||||
|
||||
const handleSubmit = async (payload: Parameters<typeof updateModelType>[1]) => {
|
||||
if (!canEdit.value) return
|
||||
if (guardSubmitOrNotify()) {
|
||||
return
|
||||
}
|
||||
const id = String(route.params.id)
|
||||
saving.value = true
|
||||
try {
|
||||
|
||||
@@ -211,3 +211,45 @@ export function convertCategory(id: string, opts: { signal?: AbortSignal } = {})
|
||||
signal: opts.signal,
|
||||
}));
|
||||
}
|
||||
|
||||
export interface SyncPreviewResult {
|
||||
modelTypeId: string;
|
||||
category: string;
|
||||
itemCount: number;
|
||||
additions: Record<string, number>;
|
||||
deletions: Record<string, number>;
|
||||
modifications: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface SyncExecuteResult {
|
||||
itemsUpdated: number;
|
||||
additions: Record<string, number>;
|
||||
deletions: Record<string, number>;
|
||||
modifications: Record<string, number>;
|
||||
}
|
||||
|
||||
export function syncPreview(id: string, structure: unknown, opts: { signal?: AbortSignal } = {}) {
|
||||
const requestFetch = useRequestFetch();
|
||||
return requestFetch<SyncPreviewResult>(`${ENDPOINT}/${id}/sync-preview`, createOptions({
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: { structure },
|
||||
signal: opts.signal,
|
||||
}));
|
||||
}
|
||||
|
||||
export function syncExecute(id: string, confirmation: { confirmDeletions: boolean; confirmTypeChanges: boolean }, opts: { signal?: AbortSignal } = {}) {
|
||||
const requestFetch = useRequestFetch();
|
||||
return requestFetch<SyncExecuteResult>(`${ENDPOINT}/${id}/sync`, createOptions({
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: confirmation,
|
||||
signal: opts.signal,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -225,56 +225,6 @@ describe('category lock', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Restricted mode
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('restricted mode', () => {
|
||||
it('shows restricted mode message', () => {
|
||||
const wrapper = mountForm({
|
||||
restrictedMode: true,
|
||||
restrictedModeMessage: 'Mode restreint actif',
|
||||
})
|
||||
expect(wrapper.text()).toContain('Mode restreint actif')
|
||||
expect(wrapper.find('.alert-info').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('does not show restricted mode message when not restricted', () => {
|
||||
const wrapper = mountForm({
|
||||
restrictedMode: false,
|
||||
})
|
||||
expect(wrapper.find('.alert-info').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('disables name input in restricted mode', () => {
|
||||
const wrapper = mountForm({ restrictedMode: true })
|
||||
expect((getNameInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Submit disabled
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('submit disabled', () => {
|
||||
it('disables submit button when disableSubmit is true', () => {
|
||||
const wrapper = mountForm({ disableSubmit: true })
|
||||
expect((getSubmitButton(wrapper).element as HTMLButtonElement).disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('shows warning alert when disableSubmit is true', () => {
|
||||
const wrapper = mountForm({
|
||||
disableSubmit: true,
|
||||
disableSubmitMessage: 'Cannot save now',
|
||||
})
|
||||
expect(wrapper.find('.alert-warning').exists()).toBe(true)
|
||||
expect(wrapper.text()).toContain('Cannot save now')
|
||||
})
|
||||
|
||||
it('does not show warning when disableSubmit is false', () => {
|
||||
const wrapper = mountForm({ disableSubmit: false })
|
||||
expect(wrapper.find('.alert-warning').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Saving state
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -227,98 +227,6 @@ describe('required checkbox', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Restricted mode
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('restricted mode', () => {
|
||||
it('allows editing name of pre-existing field', () => {
|
||||
const wrapper = mountEditor({
|
||||
restrictedMode: true,
|
||||
modelValue: {
|
||||
customFields: [{ name: 'Locked Field', type: 'text', required: false, orderIndex: 0 }],
|
||||
products: [],
|
||||
},
|
||||
})
|
||||
|
||||
const nameInput = wrapper.find('input[type="text"]')
|
||||
expect((nameInput.element as HTMLInputElement).disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('disables type select for pre-existing field', () => {
|
||||
const wrapper = mountEditor({
|
||||
restrictedMode: true,
|
||||
modelValue: {
|
||||
customFields: [{ name: 'Locked', type: 'text', required: false, orderIndex: 0 }],
|
||||
products: [],
|
||||
},
|
||||
})
|
||||
|
||||
const selects = wrapper.findAll('select')
|
||||
const typeSelect = selects[selects.length - 1]
|
||||
expect((typeSelect.element as HTMLSelectElement).disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('disables required checkbox for pre-existing field', () => {
|
||||
const wrapper = mountEditor({
|
||||
restrictedMode: true,
|
||||
modelValue: {
|
||||
customFields: [{ name: 'Locked', type: 'text', required: false, orderIndex: 0 }],
|
||||
products: [],
|
||||
},
|
||||
})
|
||||
|
||||
const checkbox = wrapper.find('input[type="checkbox"]')
|
||||
expect((checkbox.element as HTMLInputElement).disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('hides delete button for pre-existing field', () => {
|
||||
const wrapper = mountEditor({
|
||||
restrictedMode: true,
|
||||
modelValue: {
|
||||
customFields: [{ name: 'Locked', type: 'text', required: false, orderIndex: 0 }],
|
||||
products: [],
|
||||
},
|
||||
})
|
||||
|
||||
// btn-error should not exist for locked fields
|
||||
const deleteBtn = wrapper.find('button.btn-error')
|
||||
expect(deleteBtn.exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('allows full editing of newly added field', async () => {
|
||||
const wrapper = mountEditor({
|
||||
restrictedMode: true,
|
||||
modelValue: {
|
||||
customFields: [],
|
||||
products: [],
|
||||
},
|
||||
})
|
||||
|
||||
await getAddFieldButton(wrapper).trigger('click')
|
||||
await nextTick()
|
||||
|
||||
// New field should have an editable type select (not disabled)
|
||||
const selects = wrapper.findAll('select')
|
||||
const typeSelect = selects[selects.length - 1]
|
||||
expect((typeSelect.element as HTMLSelectElement).disabled).toBe(false)
|
||||
|
||||
// Delete button should exist for new field
|
||||
const deleteBtn = wrapper.find('button.btn-error')
|
||||
expect(deleteBtn.exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('hides product add button in restricted mode', () => {
|
||||
const wrapper = mountEditor({
|
||||
restrictedMode: true,
|
||||
modelValue: { customFields: [], products: [] },
|
||||
})
|
||||
|
||||
const addButtons = wrapper.findAll('button').filter(b => b.text().includes('Ajouter'))
|
||||
// Only the "add field" button should be visible, not the product one
|
||||
expect(addButtons.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Add product
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
import { useCategoryEditGuard } from '~/composables/useCategoryEditGuard'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockGet = vi.fn()
|
||||
const mockShowInfo = vi.fn()
|
||||
|
||||
vi.mock('~/composables/useApi', () => ({
|
||||
useApi: () => ({
|
||||
get: mockGet,
|
||||
post: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
apiCall: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('~/composables/useToast', () => ({
|
||||
useToast: () => ({
|
||||
showInfo: mockShowInfo,
|
||||
showSuccess: vi.fn(),
|
||||
showError: vi.fn(),
|
||||
showToast: vi.fn(),
|
||||
toasts: { value: [] },
|
||||
clearAll: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
const GUARD_CONFIG = {
|
||||
endpoint: '/composants',
|
||||
filterKey: 'typeComposant',
|
||||
labels: {
|
||||
singular: 'composant',
|
||||
plural: 'composants',
|
||||
verifying: 'Vérification des composants liés en cours…',
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Initial state
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('initial state', () => {
|
||||
it('has linkedCount 0 and restrictedMode false', () => {
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
expect(guard.linkedCount.value).toBe(0)
|
||||
expect(guard.isRestrictedMode.value).toBe(false)
|
||||
expect(guard.isSubmitBlocked.value).toBe(false)
|
||||
expect(guard.linkedLoading.value).toBe(false)
|
||||
})
|
||||
|
||||
it('has empty messages when no linked items', () => {
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
expect(guard.restrictedModeMessage.value).toBe('')
|
||||
expect(guard.submitBlockMessage.value).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// loadLinkedCount
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('loadLinkedCount', () => {
|
||||
it('sets linkedCount from API totalItems', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { totalItems: 5, member: [] },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedCount.value).toBe(5)
|
||||
expect(guard.isRestrictedMode.value).toBe(true)
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/composants?'),
|
||||
)
|
||||
})
|
||||
|
||||
it('sets linkedCount 0 when API returns 0 items', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { totalItems: 0, member: [] },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedCount.value).toBe(0)
|
||||
expect(guard.isRestrictedMode.value).toBe(false)
|
||||
})
|
||||
|
||||
it('extracts totalItems from hydra:totalItems format', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { 'hydra:totalItems': 3, 'hydra:member': [{}, {}, {}] },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedCount.value).toBe(3)
|
||||
})
|
||||
|
||||
it('falls back to member.length when no totalItems', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { member: [{}, {}] },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedCount.value).toBe(2)
|
||||
})
|
||||
|
||||
it('falls back to hydra:member.length', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { 'hydra:member': [{}] },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedCount.value).toBe(1)
|
||||
})
|
||||
|
||||
it('sets linkedCount 0 on API failure', async () => {
|
||||
mockGet.mockResolvedValue({ success: false })
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedCount.value).toBe(0)
|
||||
expect(guard.isRestrictedMode.value).toBe(false)
|
||||
})
|
||||
|
||||
it('sets linkedCount 0 on exception', async () => {
|
||||
mockGet.mockRejectedValue(new Error('Network error'))
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedCount.value).toBe(0)
|
||||
})
|
||||
|
||||
it('sends correct filter parameters', async () => {
|
||||
mockGet.mockResolvedValue({ success: true, data: { totalItems: 0 } })
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('abc-123')
|
||||
|
||||
const callUrl = mockGet.mock.calls[0][0] as string
|
||||
expect(callUrl).toContain('itemsPerPage=1')
|
||||
expect(callUrl).toContain('typeComposant=%2Fapi%2Fmodel_types%2Fabc-123')
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// restrictedModeMessage
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('restrictedModeMessage', () => {
|
||||
it('shows singular message for 1 linked item', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { totalItems: 1 },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.restrictedModeMessage.value).toContain('1 composant')
|
||||
expect(guard.restrictedModeMessage.value).toContain('Mode restreint')
|
||||
})
|
||||
|
||||
it('shows plural message for multiple linked items', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { totalItems: 5 },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.restrictedModeMessage.value).toContain('5 composants')
|
||||
expect(guard.restrictedModeMessage.value).toContain('renommer les existants')
|
||||
})
|
||||
|
||||
it('uses custom labels from config', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { totalItems: 3 },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard({
|
||||
endpoint: '/pieces',
|
||||
filterKey: 'typePiece',
|
||||
labels: { singular: 'pièce', plural: 'pièces', verifying: 'Vérification...' },
|
||||
})
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.restrictedModeMessage.value).toContain('3 pièces')
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// isSubmitBlocked & submitBlockMessage
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('submit blocking', () => {
|
||||
it('blocks submit during loading', () => {
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
// Simulate loading state by starting a load without awaiting
|
||||
mockGet.mockReturnValue(new Promise(() => {})) // Never resolves
|
||||
guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.linkedLoading.value).toBe(true)
|
||||
expect(guard.isSubmitBlocked.value).toBe(true)
|
||||
expect(guard.submitBlockMessage.value).toBe(GUARD_CONFIG.labels.verifying)
|
||||
})
|
||||
|
||||
it('unblocks submit after loading completes', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { totalItems: 5 },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.isSubmitBlocked.value).toBe(false)
|
||||
expect(guard.submitBlockMessage.value).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// guardSubmitOrNotify
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('guardSubmitOrNotify', () => {
|
||||
it('returns false when not blocked', async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
success: true,
|
||||
data: { totalItems: 0 },
|
||||
})
|
||||
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
await guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.guardSubmitOrNotify()).toBe(false)
|
||||
expect(mockShowInfo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns true and shows info when blocked', () => {
|
||||
const guard = useCategoryEditGuard(GUARD_CONFIG)
|
||||
// Simulate loading
|
||||
mockGet.mockReturnValue(new Promise(() => {}))
|
||||
guard.loadLinkedCount('mt-1')
|
||||
|
||||
expect(guard.guardSubmitOrNotify()).toBe(true)
|
||||
expect(mockShowInfo).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user