feat: improve machine component hierarchy handling

This commit is contained in:
Matthieu
2025-10-13 09:01:19 +02:00
parent 95c2a82689
commit 06ae0ca7aa
9 changed files with 1184 additions and 408 deletions

View File

@@ -156,6 +156,45 @@
</details>
</div>
<div
v-if="structureHasRequirements"
class="space-y-4 rounded-lg border border-primary/30 bg-primary/5 p-4"
>
<div class="flex items-start justify-between gap-4">
<div>
<h2 class="font-semibold text-base-content">
Sélection des éléments du squelette
</h2>
<p class="text-xs text-base-content/70">
Affectez les pièces et sous-composants concrets correspondant à la catégorie choisie.
</p>
</div>
<span
class="badge"
:class="structureSelectionsComplete ? 'badge-success' : structureDataLoading ? 'badge-info' : 'badge-warning'"
>
{{ structureSelectionsComplete ? 'Complet' : structureDataLoading ? 'Chargement…' : 'Incomplet' }}
</span>
</div>
<div
v-if="structureDataLoading"
class="flex items-center gap-3 rounded-md border border-base-200 bg-base-100 p-3 text-sm text-base-content/70"
>
<span class="loading loading-spinner loading-sm" aria-hidden="true"></span>
Chargement du catalogue de pièces et de composants
</div>
<ComponentStructureAssignmentNode
v-else-if="structureAssignments"
:assignment="structureAssignments"
:pieces="availablePieces"
:components="availableComponents"
/>
<p v-else class="text-xs text-error">
Impossible de générer les emplacements définis par le squelette.
</p>
</div>
<div v-if="customFieldInputs.length" class="space-y-4 rounded-lg border border-base-200 bg-base-200/40 p-4">
<header class="space-y-1">
<h2 class="font-semibold text-base-content">Champs personnalisés</h2>
@@ -255,12 +294,20 @@
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from '#imports'
import ConstructeurSelect from '~/components/ConstructeurSelect.vue'
import ComponentStructureAssignmentNode, {
type StructureAssignmentNode,
} from '~/components/ComponentStructureAssignmentNode.vue'
import { useComponentTypes } from '~/composables/useComponentTypes'
import { useComposants } from '~/composables/useComposants'
import { usePieces } from '~/composables/usePieces'
import { useToast } from '~/composables/useToast'
import { useCustomFields } from '~/composables/useCustomFields'
import { formatStructurePreview } from '~/shared/modelUtils'
import type { ComponentModelStructure } from '~/shared/types/inventory'
import type {
ComponentModelPiece,
ComponentModelStructure,
ComponentModelStructureNode,
} from '~/shared/types/inventory'
import type { ModelType } from '~/services/modelTypes'
interface ComponentCatalogType extends ModelType {
@@ -272,7 +319,17 @@ const route = useRoute()
const router = useRouter()
const { componentTypes, loadComponentTypes, loadingComponentTypes } = useComponentTypes()
const { createComposant } = useComposants()
const {
createComposant,
composants: componentCatalogRef,
loadComposants,
loading: componentsLoading,
} = useComposants()
const {
pieces: pieceCatalogRef,
loadPieces,
loading: piecesLoading,
} = usePieces()
const toast = useToast()
const { upsertCustomFieldValue, updateCustomFieldValue } = useCustomFields()
@@ -287,6 +344,13 @@ const creationForm = reactive({
})
const lastSuggestedName = ref('')
const customFieldInputs = ref<CustomFieldInput[]>([])
const structureAssignments = ref<StructureAssignmentNode | null>(null)
const availablePieces = computed(() => pieceCatalogRef.value ?? [])
const availableComponents = computed(() => componentCatalogRef.value ?? [])
const structureDataLoading = computed(
() => piecesLoading.value || componentsLoading.value,
)
watch(
() => route.query.typeId,
@@ -328,6 +392,7 @@ watch(selectedType, (type) => {
if (!type) {
clearCreationForm()
customFieldInputs.value = []
structureAssignments.value = null
return
}
if (!creationForm.name || creationForm.name === lastSuggestedName.value) {
@@ -335,8 +400,195 @@ watch(selectedType, (type) => {
}
lastSuggestedName.value = creationForm.name
customFieldInputs.value = normalizeCustomFieldInputs(type.structure)
structureAssignments.value = initializeStructureAssignments(type.structure)
})
const extractSubcomponents = (
definition: ComponentModelStructure | ComponentModelStructureNode | null | undefined,
): ComponentModelStructureNode[] => {
if (!definition || typeof definition !== 'object') {
return []
}
const raw = Array.isArray((definition as any).subcomponents)
? (definition as any).subcomponents
: Array.isArray((definition as any).subComponents)
? (definition as any).subComponents
: []
return raw.filter(
(item: unknown): item is ComponentModelStructureNode =>
!!item && typeof item === 'object',
)
}
const extractPiecesFromNode = (
definition: ComponentModelStructure | ComponentModelStructureNode | null | undefined,
): ComponentModelPiece[] => {
if (!definition || typeof definition !== 'object') {
return []
}
const raw = Array.isArray((definition as any).pieces)
? (definition as any).pieces
: []
return raw.filter(
(item: unknown): item is ComponentModelPiece =>
!!item && typeof item === 'object',
)
}
const buildAssignmentNode = (
definition: ComponentModelStructureNode | ComponentModelStructure,
path: string,
): StructureAssignmentNode => {
const pieces = extractPiecesFromNode(definition).map((piece, index) => ({
path: `${path}:piece-${index}`,
definition: piece,
selectedPieceId: '',
}))
const subcomponents = extractSubcomponents(definition).map(
(child, index) => buildAssignmentNode(child, `${path}:sub-${index}`),
)
return {
path,
definition,
selectedComponentId: '',
pieces,
subcomponents,
}
}
const initializeStructureAssignments = (
structure: ComponentModelStructure | null,
): StructureAssignmentNode | null => {
if (!structure || typeof structure !== 'object') {
return null
}
return buildAssignmentNode(structure, 'root')
}
const hasAssignments = (node: StructureAssignmentNode | null): boolean => {
if (!node) {
return false
}
if (node.pieces.length > 0 || node.subcomponents.length > 0) {
return true
}
return node.subcomponents.some((child) => hasAssignments(child))
}
const structureHasRequirements = computed(() =>
hasAssignments(structureAssignments.value),
)
const isAssignmentNodeComplete = (
node: StructureAssignmentNode,
isRootNode = false,
): boolean => {
const piecesComplete = node.pieces.every(
(piece) => !!piece.selectedPieceId && piece.selectedPieceId.length > 0,
)
const subcomponentsComplete = node.subcomponents.every(
(child) =>
!!child.selectedComponentId &&
child.selectedComponentId.length > 0 &&
isAssignmentNodeComplete(child, false),
)
return piecesComplete && subcomponentsComplete && (isRootNode || !!node.selectedComponentId)
}
const structureSelectionsComplete = computed(() => {
if (!structureHasRequirements.value) {
return true
}
if (structureDataLoading.value) {
return false
}
if (!structureAssignments.value) {
return false
}
return isAssignmentNodeComplete(structureAssignments.value, true)
})
const stripNullish = (input: Record<string, any>) =>
Object.fromEntries(
Object.entries(input).filter(
([, value]) => value !== null && value !== undefined && value !== '',
),
)
const sanitizeStructureDefinition = (
definition: ComponentModelStructureNode,
) =>
stripNullish({
alias: definition.alias ?? null,
typeComposantId: definition.typeComposantId ?? null,
typeComposantLabel: definition.typeComposantLabel ?? null,
modelId: definition.modelId ?? null,
familyCode: (definition as any).familyCode ?? null,
})
const sanitizePieceDefinition = (definition: ComponentModelPiece) =>
stripNullish({
role: (definition as any).role ?? null,
typePieceId: definition.typePieceId ?? null,
typePieceLabel: definition.typePieceLabel ?? null,
reference: definition.reference ?? null,
})
const serializeStructureAssignments = (
root: StructureAssignmentNode | null,
) => {
if (!root) {
return null
}
const serializeNode = (
assignment: StructureAssignmentNode,
isRootNode = false,
): Record<string, any> => {
const serializedPieces = assignment.pieces
.filter((piece) => !!piece.selectedPieceId)
.map((piece) =>
stripNullish({
path: piece.path,
definition: sanitizePieceDefinition(piece.definition),
selectedPieceId: piece.selectedPieceId,
}),
)
const serializedSubcomponents = assignment.subcomponents
.map((child) => serializeNode(child, false))
.filter((child) => Object.keys(child).length > 0)
const base: Record<string, any> = {
path: assignment.path,
definition: sanitizeStructureDefinition(assignment.definition),
}
if (!isRootNode) {
base.selectedComponentId = assignment.selectedComponentId
}
if (serializedPieces.length) {
base.pieces = serializedPieces
}
if (serializedSubcomponents.length) {
base.subcomponents = serializedSubcomponents
}
return stripNullish(base)
}
const serializedRoot = serializeNode(root, true)
if (
(!serializedRoot.pieces || serializedRoot.pieces.length === 0) &&
(!serializedRoot.subcomponents || serializedRoot.subcomponents.length === 0)
) {
return null
}
return serializedRoot
}
const requiredCustomFieldsFilled = computed(() =>
customFieldInputs.value.every((field) => {
if (!field.required) {
@@ -353,6 +605,7 @@ const canSubmit = computed(() => Boolean(
selectedType.value &&
creationForm.name &&
requiredCustomFieldsFilled.value &&
structureSelectionsComplete.value &&
!submitting.value,
))
@@ -421,6 +674,7 @@ const clearCreationForm = () => {
creationForm.constructeurId = null
creationForm.prix = ''
lastSuggestedName.value = ''
structureAssignments.value = null
}
const submitCreation = async () => {
@@ -455,6 +709,19 @@ const submitCreation = async () => {
}
}
if (structureHasRequirements.value && !structureSelectionsComplete.value) {
toast.showError('Complétez la sélection des pièces et sous-composants.')
return
}
const serializedStructure = structureHasRequirements.value
? serializeStructureAssignments(structureAssignments.value)
: null
if (serializedStructure) {
payload.structure = serializedStructure
}
submitting.value = true
try {
const result = await createComposant(payload)
@@ -473,7 +740,11 @@ const submitCreation = async () => {
}
onMounted(async () => {
await loadComponentTypes()
await Promise.allSettled([
loadComponentTypes(),
loadPieces(),
loadComposants(),
])
})
interface CustomFieldInput {