From a1998d7966bae9a65fbb8a45850dd4f0d5136cdb Mon Sep 17 00:00:00 2001 From: matthieu Date: Sun, 8 Mar 2026 17:24:50 +0100 Subject: [PATCH] refactor(frontend) : extract component create page logic into composable Co-Authored-By: Claude Opus 4.6 --- app/composables/useComponentCreate.ts | 417 ++++++++++++ app/pages/component/create.vue | 593 +----------------- .../utils/structureAssignmentHelpers.ts | 257 ++++++++ 3 files changed, 706 insertions(+), 561 deletions(-) create mode 100644 app/composables/useComponentCreate.ts create mode 100644 app/shared/utils/structureAssignmentHelpers.ts diff --git a/app/composables/useComponentCreate.ts b/app/composables/useComponentCreate.ts new file mode 100644 index 0000000..2865f3e --- /dev/null +++ b/app/composables/useComponentCreate.ts @@ -0,0 +1,417 @@ +/** + * Component creation page – orchestration composable. + * + * Pure structure-assignment helpers live in + * `~/shared/utils/structureAssignmentHelpers.ts`. + */ + +import { computed, onMounted, reactive, ref, watch } from 'vue' +import { useRoute, useRouter } from '#imports' +import type { StructureAssignmentNode } from '~/components/ComponentStructureAssignmentNode.vue' +import { useComponentTypes } from '~/composables/useComponentTypes' +import { useComposants } from '~/composables/useComposants' +import { usePieces } from '~/composables/usePieces' +import { usePieceTypes } from '~/composables/usePieceTypes' +import { useProducts } from '~/composables/useProducts' +import { useProductTypes } from '~/composables/useProductTypes' +import { useApi } from '~/composables/useApi' +import { useToast } from '~/composables/useToast' +import { humanizeError } from '~/shared/utils/errorMessages' +import { useCustomFields } from '~/composables/useCustomFields' +import { useDocuments } from '~/composables/useDocuments' +import { formatStructurePreview, normalizeStructureForEditor } from '~/shared/modelUtils' +import { + type CustomFieldInput, + normalizeCustomFieldInputs, + requiredCustomFieldsFilled as _requiredCustomFieldsFilled, + saveCustomFieldValues as _saveCustomFieldValues, +} from '~/shared/utils/customFieldFormUtils' +import { uniqueConstructeurIds } from '~/shared/constructeurUtils' +import { + getStructurePieces, + resolvePieceLabel as _resolvePieceLabel, + resolveProductLabel as _resolveProductLabel, + resolveSubcomponentLabel, + fetchModelTypeNames, + buildTypeLabelMap, +} from '~/shared/utils/structureDisplayUtils' +import { + hasAssignments, + initializeStructureAssignments, + isAssignmentNodeComplete, + serializeStructureAssignments, +} from '~/shared/utils/structureAssignmentHelpers' +import type { ComponentModelStructure } from '~/shared/types/inventory' +import type { ModelType } from '~/services/modelTypes' + +interface ComponentCatalogType extends ModelType { + structure: ComponentModelStructure | null + customFields?: Array> +} + +// --------------------------------------------------------------------------- +// Main composable +// --------------------------------------------------------------------------- + +export function useComponentCreate() { + const route = useRoute() + const router = useRouter() + const { get } = useApi() + + const { componentTypes, loadComponentTypes, loadingComponentTypes: loadingTypes } = useComponentTypes() + const { pieceTypes, loadPieceTypes } = usePieceTypes() + const { productTypes, loadProductTypes } = useProductTypes() + const { + createComposant, + composants: componentCatalogRef, + loading: componentsLoading, + } = useComposants() + const { + pieces: pieceCatalogRef, + loading: piecesLoading, + } = usePieces() + const { + products: productCatalogRef, + loading: productsLoading, + } = useProducts() + const toast = useToast() + const { upsertCustomFieldValue, updateCustomFieldValue } = useCustomFields() + const { uploadDocuments } = useDocuments() + const { canEdit } = usePermissions() + + // ------------------------------------------------------------------------- + // Local state + // ------------------------------------------------------------------------- + + const selectedTypeId = ref(typeof route.query.typeId === 'string' ? route.query.typeId : '') + const submitting = ref(false) + const creationForm = reactive({ + name: '' as string, + description: '' as string, + reference: '' as string, + constructeurIds: [] as string[], + prix: '' as string, + }) + const lastSuggestedName = ref('') + const customFieldInputs = ref([]) + const structureAssignments = ref(null) + const selectedDocuments = ref([]) + const uploadingDocuments = ref(false) + + // ------------------------------------------------------------------------- + // Computed + // ------------------------------------------------------------------------- + + const availablePieces = computed(() => pieceCatalogRef.value ?? []) + const availableProducts = computed(() => productCatalogRef.value ?? []) + const availableComponents = computed(() => componentCatalogRef.value ?? []) + const structureDataLoading = computed( + () => piecesLoading.value || componentsLoading.value || productsLoading.value, + ) + + const fetchedPieceTypeMap = ref>({}) + const pieceTypeLabelMap = computed(() => + buildTypeLabelMap(pieceTypes.value, fetchedPieceTypeMap.value), + ) + const productTypeLabelMap = computed(() => + buildTypeLabelMap(productTypes.value), + ) + const componentTypeLabelMap = computed(() => + buildTypeLabelMap(componentTypes.value), + ) + + const componentTypeList = computed(() => + (componentTypes.value || []) + .filter((item: any) => item?.category === 'COMPONENT') as ComponentCatalogType[], + ) + + const typeOptionLabel = (type?: ComponentCatalogType) => + type?.name || 'Catégorie' + + const typeOptionDescription = (type?: ComponentCatalogType) => + type?.description ? String(type.description) : '' + + const selectedType = computed(() => { + if (!selectedTypeId.value) { + return null + } + return componentTypeList.value.find((type) => type.id === selectedTypeId.value) ?? null + }) + + const selectedTypeStructure = computed(() => { + const structure = selectedType.value?.structure ?? null + return structure ? normalizeStructureForEditor(structure) : null + }) + + const structureHasRequirements = computed(() => + hasAssignments(structureAssignments.value), + ) + + const structureSelectionsComplete = computed(() => { + if (!structureHasRequirements.value) { + return true + } + if (structureDataLoading.value) { + return false + } + if (!structureAssignments.value) { + return false + } + return isAssignmentNodeComplete(structureAssignments.value, true) + }) + + const requiredCustomFieldsFilled = computed(() => + _requiredCustomFieldsFilled(customFieldInputs.value), + ) + + const canSubmit = computed(() => Boolean( + canEdit.value + && selectedType.value + && creationForm.name + && requiredCustomFieldsFilled.value + && structureSelectionsComplete.value + && !submitting.value, + )) + + const resolvePieceLabel = (piece: Record) => + _resolvePieceLabel(piece, pieceTypeLabelMap.value) + + const resolveProductLabel = (product: Record) => + _resolveProductLabel(product, productTypeLabelMap.value) + + // ------------------------------------------------------------------------- + // Watchers + // ------------------------------------------------------------------------- + + watch( + () => route.query.typeId, + (value) => { + if (typeof value === 'string') { + selectedTypeId.value = value + } + }, + ) + + watch(selectedTypeId, (id) => { + const current = typeof route.query.typeId === 'string' ? route.query.typeId : '' + if ((id || '') === current) { + return + } + const nextQuery = { ...route.query } + if (id) { + nextQuery.typeId = id + } + else { + delete nextQuery.typeId + } + router.replace({ path: route.path, query: nextQuery }).catch(() => {}) + }) + + const clearCreationForm = () => { + creationForm.name = '' + creationForm.description = '' + creationForm.reference = '' + creationForm.constructeurIds = [] + creationForm.prix = '' + lastSuggestedName.value = '' + structureAssignments.value = null + } + + watch(selectedType, (type) => { + if (!type) { + clearCreationForm() + customFieldInputs.value = [] + structureAssignments.value = null + return + } + if (!creationForm.name || creationForm.name === lastSuggestedName.value) { + creationForm.name = type.name + } + lastSuggestedName.value = creationForm.name + customFieldInputs.value = normalizeCustomFieldInputs(selectedTypeStructure.value) + structureAssignments.value = initializeStructureAssignments(selectedTypeStructure.value) + }) + + watch( + selectedTypeStructure, + (structure) => { + const ids = getStructurePieces(structure) + .map((piece: any) => piece?.typePieceId) + .filter((id: any): id is string => typeof id === 'string' && id.trim().length > 0) + if (!ids.length) { + return + } + fetchModelTypeNames(Array.from(new Set(ids)), pieceTypeLabelMap.value, get) + .then((additions) => { + if (Object.keys(additions).length) { + fetchedPieceTypeMap.value = { ...fetchedPieceTypeMap.value, ...additions } + } + }) + .catch(() => {}) + }, + { immediate: true }, + ) + + // ------------------------------------------------------------------------- + // Submission + // ------------------------------------------------------------------------- + + const submitCreation = async () => { + if (!selectedType.value) { + toast.showError('Sélectionnez une catégorie de composant.') + return + } + const payload: Record = { + name: creationForm.name.trim(), + typeComposantId: selectedType.value.id, + } + + const description = creationForm.description.trim() + if (description) { + payload.description = description + } + + const reference = creationForm.reference.trim() + if (reference) { + payload.reference = reference + } + + if (creationForm.constructeurIds.length) { + payload.constructeurIds = uniqueConstructeurIds(creationForm.constructeurIds) + } + + const rawPrice = typeof creationForm.prix === 'string' + ? creationForm.prix.trim() + : creationForm.prix === null || creationForm.prix === undefined + ? '' + : String(creationForm.prix).trim() + + if (rawPrice) { + const parsed = Number(rawPrice) + if (!Number.isNaN(parsed)) { + payload.prix = String(parsed) + } + } + + const rootProductSelection + = structureAssignments.value?.products?.find( + (product) => typeof product.selectedProductId === 'string' && product.selectedProductId.trim().length > 0, + ) ?? null + + if (rootProductSelection?.selectedProductId) { + payload.productId = rootProductSelection.selectedProductId.trim() + } + + if (structureHasRequirements.value && !structureSelectionsComplete.value) { + toast.showError('Complétez la sélection des pièces, produits 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) + if (result.success) { + const createdComponent = result.data as Record + await _saveCustomFieldValues( + 'composant', + createdComponent.id, + [createdComponent?.typeComposant?.customFields], + { customFieldInputs, upsertCustomFieldValue, updateCustomFieldValue, toast }, + ) + if (selectedDocuments.value.length && result.data?.id) { + uploadingDocuments.value = true + const uploadResult = await uploadDocuments( + { + files: selectedDocuments.value, + context: { composantId: result.data.id }, + }, + { updateStore: false }, + ) + if (!uploadResult.success) { + const message = uploadResult.error + ? `Documents non ajoutés : ${uploadResult.error}` + : 'Documents non ajoutés : une erreur est survenue.' + toast.showError(message) + } + selectedDocuments.value = [] + } + toast.showSuccess('Composant créé avec succès') + await router.push('/component-catalog') + } + else if (result.error) { + toast.showError(result.error) + } + } + catch (error: any) { + toast.showError(humanizeError(error?.message) || 'Impossible de créer le composant') + } + finally { + submitting.value = false + uploadingDocuments.value = false + } + } + + // ------------------------------------------------------------------------- + // Initialization + // ------------------------------------------------------------------------- + + onMounted(async () => { + await Promise.allSettled([ + loadComponentTypes(), + loadPieceTypes(), + loadProductTypes(), + ]) + }) + + // ------------------------------------------------------------------------- + // Public API + // ------------------------------------------------------------------------- + + return { + // State + selectedTypeId, + submitting, + creationForm, + customFieldInputs, + structureAssignments, + selectedDocuments, + uploadingDocuments, + + // Computed + loadingTypes, + componentTypeList, + selectedType, + selectedTypeStructure, + availablePieces, + availableProducts, + availableComponents, + piecesLoading, + productsLoading, + componentsLoading, + structureDataLoading, + pieceTypeLabelMap, + productTypeLabelMap, + componentTypeLabelMap, + structureHasRequirements, + structureSelectionsComplete, + canEdit, + canSubmit, + + // Functions + typeOptionLabel, + typeOptionDescription, + formatStructurePreview, + resolvePieceLabel, + resolveProductLabel, + resolveSubcomponentLabel, + submitCreation, + } +} diff --git a/app/pages/component/create.vue b/app/pages/component/create.vue index 8850bf0..dbc1b21 100644 --- a/app/pages/component/create.vue +++ b/app/pages/component/create.vue @@ -215,567 +215,38 @@ diff --git a/app/shared/utils/structureAssignmentHelpers.ts b/app/shared/utils/structureAssignmentHelpers.ts new file mode 100644 index 0000000..c285044 --- /dev/null +++ b/app/shared/utils/structureAssignmentHelpers.ts @@ -0,0 +1,257 @@ +/** + * Pure helper functions for building, validating and serializing + * component structure assignment trees. + * + * Extracted from useComponentCreate composable to keep file sizes manageable. + */ + +import type { StructureAssignmentNode } from '~/components/ComponentStructureAssignmentNode.vue' +import type { + ComponentModelPiece, + ComponentModelProduct, + ComponentModelStructure, + ComponentModelStructureNode, +} from '~/shared/types/inventory' + +// --------------------------------------------------------------------------- +// Extraction helpers +// --------------------------------------------------------------------------- + +export function 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', + ) +} + +export function 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', + ) +} + +export function extractProductsFromNode( + definition: ComponentModelStructure | ComponentModelStructureNode | null | undefined, +): ComponentModelProduct[] { + if (!definition || typeof definition !== 'object') { + return [] + } + const raw = Array.isArray((definition as any).products) + ? (definition as any).products + : [] + return raw.filter( + (item: unknown): item is ComponentModelProduct => + !!item && typeof item === 'object', + ) +} + +// --------------------------------------------------------------------------- +// Assignment tree building +// --------------------------------------------------------------------------- + +export function buildAssignmentNode( + definition: ComponentModelStructureNode | ComponentModelStructure, + path: string, +): StructureAssignmentNode { + const pieces = extractPiecesFromNode(definition).map((piece, index) => ({ + path: `${path}:piece-${index}`, + definition: piece, + selectedPieceId: '', + })) + + const products = extractProductsFromNode(definition).map((product, index) => ({ + path: `${path}:product-${index}`, + definition: product, + selectedProductId: '', + })) + + const subcomponents = extractSubcomponents(definition).map( + (child, index) => buildAssignmentNode(child, `${path}:sub-${index}`), + ) + + return { + path, + definition, + selectedComponentId: '', + pieces, + products, + subcomponents, + } +} + +export function initializeStructureAssignments( + structure: ComponentModelStructure | null, +): StructureAssignmentNode | null { + if (!structure || typeof structure !== 'object') { + return null + } + return buildAssignmentNode(structure, 'root') +} + +// --------------------------------------------------------------------------- +// Validation +// --------------------------------------------------------------------------- + +export function hasAssignments(node: StructureAssignmentNode | null): boolean { + if (!node) { + return false + } + if (node.pieces.length > 0 || node.products.length > 0 || node.subcomponents.length > 0) { + return true + } + return node.subcomponents.some((child) => hasAssignments(child)) +} + +export function isAssignmentNodeComplete( + node: StructureAssignmentNode, + isRootNode = false, +): boolean { + const piecesComplete = node.pieces.every( + (piece) => !!piece.selectedPieceId && piece.selectedPieceId.length > 0, + ) + const productsComplete = node.products.every( + (product) => !!product.selectedProductId && product.selectedProductId.length > 0, + ) + const subcomponentsComplete = node.subcomponents.every( + (child) => + !!child.selectedComponentId + && child.selectedComponentId.length > 0 + && isAssignmentNodeComplete(child, false), + ) + return ( + piecesComplete + && productsComplete + && subcomponentsComplete + && (isRootNode || !!node.selectedComponentId) + ) +} + +// --------------------------------------------------------------------------- +// Serialization +// --------------------------------------------------------------------------- + +export function stripNullish(input: Record) { + return Object.fromEntries( + Object.entries(input).filter( + ([, value]) => value !== null && value !== undefined && value !== '', + ), + ) +} + +export function sanitizeStructureDefinition( + definition: ComponentModelStructureNode, +) { + return stripNullish({ + alias: definition.alias ?? null, + typeComposantId: definition.typeComposantId ?? null, + typeComposantLabel: definition.typeComposantLabel ?? null, + modelId: definition.modelId ?? null, + familyCode: (definition as any).familyCode ?? null, + }) +} + +export function sanitizePieceDefinition(definition: ComponentModelPiece) { + return stripNullish({ + role: (definition as any).role ?? null, + typePieceId: definition.typePieceId ?? null, + typePieceLabel: definition.typePieceLabel ?? null, + reference: definition.reference ?? null, + familyCode: (definition as any).familyCode ?? null, + }) +} + +export function sanitizeProductDefinition(definition: ComponentModelProduct) { + return stripNullish({ + role: (definition as any).role ?? null, + typeProductId: definition.typeProductId ?? null, + typeProductLabel: (definition as any).typeProductLabel ?? null, + reference: (definition as any).reference ?? null, + familyCode: (definition as any).familyCode ?? null, + }) +} + +export function serializeStructureAssignments( + root: StructureAssignmentNode | null, +) { + if (!root) { + return null + } + + const serializeNode = ( + assignment: StructureAssignmentNode, + isRootNode = false, + ): Record => { + const serializedPieces = assignment.pieces + .filter((piece) => !!piece.selectedPieceId) + .map((piece) => + stripNullish({ + path: piece.path, + definition: sanitizePieceDefinition(piece.definition), + selectedPieceId: piece.selectedPieceId, + }), + ) + + const serializedProducts = assignment.products + .filter((product) => !!product.selectedProductId) + .map((product) => + stripNullish({ + path: product.path, + definition: sanitizeProductDefinition(product.definition), + selectedProductId: product.selectedProductId, + }), + ) + + const serializedSubcomponents = assignment.subcomponents + .map((child) => serializeNode(child, false)) + .filter((child) => Object.keys(child).length > 0) + + const base: Record = { + path: assignment.path, + definition: sanitizeStructureDefinition(assignment.definition), + } + + if (!isRootNode) { + base.selectedComponentId = assignment.selectedComponentId + } + if (serializedPieces.length) { + base.pieces = serializedPieces + } + if (serializedProducts.length) { + base.products = serializedProducts + } + if (serializedSubcomponents.length) { + base.subcomponents = serializedSubcomponents + } + + return stripNullish(base) + } + + const serializedRoot = serializeNode(root, true) + if ( + (!serializedRoot.pieces || serializedRoot.pieces.length === 0) + && (!serializedRoot.products || serializedRoot.products.length === 0) + && (!serializedRoot.subcomponents || serializedRoot.subcomponents.length === 0) + ) { + return null + } + return serializedRoot +}