Merge branch 'feat/toggle-negative-usage' into 'development'

fix: missing useRef

See merge request mbugroup/lti-web-client!445
This commit is contained in:
Adnan Zahir
2026-04-29 12:18:21 +07:00
@@ -1,6 +1,6 @@
'use client';
import { useMemo, useState, useEffect, useCallback } from 'react';
import { useMemo, useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
@@ -1277,10 +1277,10 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
};
}
// In migration mode (edit), the form field `product_warehouse_id` must hold
// the master product ID (what the dropdown options use as `value`), not the
// PW entity ID returned by the API. The API response has the product ID
// nested at stock.product_warehouse.product_id.
// In migration mode (edit), the dropdown options use product.id as their value,
// but the API returns product_warehouse_id (PW entity ID). Remap so the dropdown
// can match the correct option. The product ID is available on the nested
// product_warehouse object returned by the API.
if (isMigrationMode && type === 'edit' && initialValues?.stocks?.length) {
baseValues.stocks = initialValues.stocks.map((stock) => ({
product_warehouse_id:
@@ -1421,19 +1421,30 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
},
});
// When migration mode activates after formik has initialized (SWR timing race),
// push the corrected stock values (product_id, not PW entity id) into the form.
// SWR timing fix: formik initializes before system-settings load, so isMigrationMode
// starts false. When it flips true, formikInitialValues recomputes but enableReinitialize
// is false, so formik won't pick it up. Push the corrected stock values once, and only
// once — the ref prevents re-firing if something causes isMigrationMode to re-evaluate.
const migrationEditMappingApplied = useRef(false);
useEffect(() => {
if (type !== 'edit' || !isMigrationMode || !initialValues?.stocks?.length)
if (
type !== 'edit' ||
!isMigrationMode ||
!initialValues?.stocks?.length ||
migrationEditMappingApplied.current
)
return;
const migrationStocks = initialValues.stocks.map((stock) => ({
product_warehouse_id:
stock.product_warehouse?.product_id ?? stock.product_warehouse_id,
qty: stock.usage_amount ?? '',
}));
formik.setFieldValue('stocks', migrationStocks);
migrationEditMappingApplied.current = true;
formik.setFieldValue(
'stocks',
initialValues.stocks.map((stock) => ({
product_warehouse_id:
stock.product_warehouse?.product_id ?? stock.product_warehouse_id,
qty: stock.usage_amount ?? '',
}))
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isMigrationMode]); // intentionally shallow — only run when migration mode flips
}, [isMigrationMode]);
// ===== HELPER FUNCTIONS =====
const { setFieldValue } = formik;