Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(mes): allow fractional quantities in the job operation quantity modal

Sidwebworks4fee66fe8ddc
diff --git a/.ai/lessons.md b/.ai/lessons.md
index f1965f081e..2a654f3860 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -583,3 +583,13 @@ Format: `Context → Problem → Rule → Applies to`
- Colored callout on a `Card`: always pair the tint with its `dark:` variant (`bg-emerald-500/5 dark:bg-emerald-500/5`). `cn`/twMerge then drops the base `dark:bg-card`. Verify by checking the rendered class list no longer contains `dark:bg-card`.
**Applies to:** any UI composing `@carbon/react` `Card`/`CardContent`/`CardHeader`; the `Section`/`Panel` primitives in `packages/onboarding/src/ui/primitives/Section.tsx` centralize this composition for the hub.
+
+## react-aria compares `formatOptions` by reference — an inline literal wipes half-typed numbers
+
+**Context:** Any `NumberField` / `Number` / `NumberControlled` field that passes `formatOptions={{ ... }}` at the call site (real case: the MES Log Completed quantity in `apps/mes/app/components/JobOperation/components/QuantityModal.tsx`, where operators could not enter `1.5`).
+
+**Problem:** `useNumberFieldState` (`@react-stately/numberfield`) guards with `formatOptions !== prevFormatOptions` — a **reference** check — and on a change calls `setInputValue(format(numberValue))`, replacing whatever is in the input with the last *committed* number. `react-aria-components`' `NumberField` spreads caller props straight through, so an inline object literal is a new reference every render. Any parent re-render while the user is mid-edit destroys the in-progress text. Commit only happens on blur/Enter/stepper, so a single digit usually survives but a decimal (`1.` → `1.5`, two-plus keystrokes) reliably does not. It reads as "the field doesn't support decimals" even though the format options, the zod validator, and the numeric DB column all allow them.
+
+**Rule:** Never let an unstable `Intl.NumberFormatOptions` reference reach react-aria. `packages/react/src/Number.tsx`'s `NumberField` now stabilizes it via `useStableFormatOptions` / `areNumberFormatOptionsEqual` (shallow value compare — exact, since the options are all primitives), so call sites are free to pass literals. If you build another react-aria wrapper that forwards `formatOptions`, do the same; do not "fix" this class of bug by only adding/adjusting `formatOptions` at the call site — that is what introduced it here. Also note the same trap for any react-aria prop compared by identity.
+
+**Applies to:** `packages/react/src/Number.tsx`; every `formatOptions={{ ... }}` call site in `apps/erp` / `apps/mes` (~144); `packages/form/src/components/{Number,NumberControlled,ArrayNumeric}.tsx`, whose `rest.formatOptions ?? ({ ... })` default also allocates a fresh object each render.
diff --git a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
index 0a645efb2d..94acee1022 100644
--- a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
@@ -37,6 +37,13 @@ import type {
import { path } from "~/utils/path";
import ScrapReason from "./ScrapReason";
+// Fractional quantities for weight/length UoMs, capped at the 2 decimals
+// jobOperation.quantityComplete/Scrapped/Reworked store.
+const QUANTITY_FORMAT_OPTIONS: Intl.NumberFormatOptions = {
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 2
+};
+
export function QuantityModal({
allStepsRecorded = true,
laborProductionEvent,
@@ -93,7 +100,12 @@ export function QuantityModal({
finish: t`Finish ${operation.itemReadableId}`
};
- const isOperationComplete = baseline.complete >= operation.operationQuantity;
+ // operationQuantity is Math.ceil'd upstream (recalculate/get-method), so a 1.5-unit
+ // job reports 2. Matches how x+/complete.tsx decides willBeFinished.
+ const targetQuantity =
+ operation.targetQuantity ?? operation.operationQuantity ?? 0;
+
+ const isOperationComplete = baseline.complete >= targetQuantity;
const descriptionMap = {
scrap: t`Select a scrap quantity and reason`,
@@ -226,7 +238,7 @@ export function QuantityModal({
<AlertDescription>
<Trans>
The completed quantity for this operation is less than the
- required quantity of {operation.operationQuantity}.
+ required quantity of {targetQuantity}.
</Trans>
</AlertDescription>
</Alert>
@@ -254,13 +266,7 @@ export function QuantityModal({
onChange={setQuantity}
isReadOnly={parentIsSerial}
minValue={0}
- // Allow fractional quantities (weight/length UoMs), capped
- // at 2 decimals. Without formatOptions, NumberControlled
- // inherits react-aria's 3-decimal default.
- formatOptions={{
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ formatOptions={QUANTITY_FORMAT_OPTIONS}
size="lg"
/>
</div>
@@ -271,9 +277,7 @@ export function QuantityModal({
className="h-12"
onClick={() =>
setQuantity(
- operation.operationQuantity -
- baseline.complete -
- baseline.reworked
+ targetQuantity - baseline.complete - baseline.reworked
)
}
>
@@ -296,6 +300,7 @@ export function QuantityModal({
<NumberControlled
name="totalQuantity"
label={t`Total Quantity`}
+ formatOptions={QUANTITY_FORMAT_OPTIONS}
size="lg"
value={
quantity +
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index d4718c581c..6bc3d45e6d 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Bediener wechseln"
msgid "Tag"
msgstr "Tag"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "Die abgeschlossene Menge für diesen Arbeitsgang ist geringer als die erforderliche Menge von {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "Die abgeschlossene Menge für diesen Arbeitsgang ist geringer als die erforderliche Menge von {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Das Los wird als Bestanden markiert und {remaining} verbleibende Einheit(en) werden bei diesem Arbeitsgang abgeschlossen."
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index b6147c8b91..fe41796134 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Switch Operator"
msgid "Tag"
msgstr "Tag"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "The completed quantity for this operation is less than the required quantity of {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index a14006bfc5..befdbecb45 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Cambiar operador"
msgid "Tag"
msgstr "Etiqueta"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "La cantidad completada para esta operación es menor que la cantidad requerida de {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "La cantidad completada para esta operación es menor que la cantidad requerida de {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "El lote se marcará como Aprobado y {remaining} unidad(es) restante(s) se completarán en esta operación."
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index fe7cd2b3b4..b94d0ca656 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Changer d'opérateur"
msgid "Tag"
msgstr "Étiquette"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "La quantité produite pour cette opération est inférieure à la quantité requise de {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "La quantité produite pour cette opération est inférieure à la quantité requise de {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Le lot sera marqué comme Réussi et {remaining} unité(s) restante(s) seront complétées à cette opération."
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 1424b3f274..1538a5f9cb 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -1165,9 +1165,8 @@ msgstr "ऑपरेटर स्विच करें"
msgid "Tag"
msgstr "टैग"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "इस ऑपरेशन के लिए पूर्ण मात्रा आवश्यक मात्रा {0} से कम है।"
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "इस ऑपरेशन के लिए पूर्ण मात्रा आवश्यक मात्रा {targetQuantity} से कम है।"
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "लॉट को पास के रूप में चिह्नित किया जाएगा और {remaining} शेष इकाई(यों) को इस ऑपरेशन पर पूरा किया जाएगा।"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index ccee0c5a9f..26c7531faa 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Cambia Operatore"
msgid "Tag"
msgstr "Etichetta"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "La quantità completata per questa operazione è inferiore alla quantità richiesta di {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "La quantità completata per questa operazione è inferiore alla quantità richiesta di {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Il lotto sarà contrassegnato come Superato e {remaining} unità/unità rimanente/i saranno completate in questa operazione."
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 79b34ee121..2af8bff0ce 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -1165,9 +1165,8 @@ msgstr "オペレーターを切替"
msgid "Tag"
msgstr "タグ"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "この工程の完了数量が必要数量 {0} を下回っています。"
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "この工程の完了数量が必要数量 {targetQuantity} を下回っています。"
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "ロットは「合格」とマークされ、{remaining}個の残りユニットがこの工程で完了します。"
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index 2a75042401..680309f5f6 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -1165,9 +1165,8 @@ msgstr "작업자 전환"
msgid "Tag"
msgstr "태그"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "이 공정작업의 완료 수량이 필요 수량 {0}보다 적습니다."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "이 공정작업의 완료 수량이 필요 수량 {targetQuantity}보다 적습니다."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "로트가 합격으로 표시되고 {remaining}개의 남은 단위가 이 작업에서 완료됩니다."
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 2530594677..ad067818ef 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Zmień operatora"
msgid "Tag"
msgstr "Tag"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "Ukończona ilość dla tej operacji jest mniejsza niż wymagana ilość {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "Ukończona ilość dla tej operacji jest mniejsza niż wymagana ilość {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Partia zostanie oznaczona jako Zaakceptowana i {remaining} pozostałych jednostek zostanie ukończonych w tej operacji."
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index 3cd8c80114..48de5d35a5 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Trocar Operador"
msgid "Tag"
msgstr "Etiqueta"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "A quantidade concluída para esta operação é menor que a quantidade requerida de {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "A quantidade concluída para esta operação é menor que a quantidade requerida de {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "O lote será marcado como Aprovado e {remaining} unidade(s) restante(s) será(ão) concluída(s) nesta operação."
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index ae9bbb9f4b..8f62dce452 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Сменить оператора"
msgid "Tag"
msgstr "Тег"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "Количество готовой продукции по этой операции меньше требуемого количества {0}."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "Количество готовой продукции по этой операции меньше требуемого количества {targetQuantity}."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Партия будет отмечена как Пройдена, и {remaining} оставшихся единиц будут завершены в этой операции."
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 322ce24f36..be2a2e455a 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -1165,9 +1165,8 @@ msgstr "Operatörü Değiştir"
msgid "Tag"
msgstr "Etiket"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "Bu işlem için tamamlanan miktar, gerekli miktar olan {0}'dan azdır."
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "Bu işlem için tamamlanan miktar, gerekli miktar olan {targetQuantity}'dan azdır."
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Lot Passed olarak işaretlenecek ve {remaining} kalan birim(ler) bu operasyonda tamamlanacaktır."
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index f22b7bebdb..09d7987ae7 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -1165,9 +1165,8 @@ msgstr "切换操作员"
msgid "Tag"
msgstr "标签"
-#. placeholder {0}: operation.operationQuantity
-msgid "The completed quantity for this operation is less than the required quantity of {0}."
-msgstr "此工序的完成数量小于所需数量 {0}。"
+msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgstr "此工序的完成数量小于所需数量 {targetQuantity}。"
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "该批次将被标记为\"通过\",{remaining} 个剩余单位将在此操作中完成。"
diff --git a/packages/react/src/Number.tsx b/packages/react/src/Number.tsx
index 4f6dc35a3e..529257f008 100644
--- a/packages/react/src/Number.tsx
+++ b/packages/react/src/Number.tsx
@@ -1,5 +1,5 @@
import type React from "react";
-import { forwardRef } from "react";
+import { forwardRef, useRef } from "react";
import * as ReactAria from "react-aria-components";
import type { InputProps } from "./Input";
import { Input } from "./Input";
@@ -7,9 +7,50 @@ import { cn } from "./utils/cn";
export type NumberFieldProps = ReactAria.NumberFieldProps;
-const NumberField = ({ className, ...props }: ReactAria.NumberFieldProps) => {
+/** Shallow compare — exact here, since every option value is a primitive. */
+export function areNumberFormatOptionsEqual(
+ a: Intl.NumberFormatOptions | undefined,
+ b: Intl.NumberFormatOptions | undefined
+): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+
+ const aKeys = Object.keys(a) as (keyof Intl.NumberFormatOptions)[];
+ const bKeys = Object.keys(b);
+ if (aKeys.length !== bKeys.length) return false;
+
+ return aKeys.every(
+ (key) =>
+ Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key])
+ );
+}
+
+/**
+ * react-aria compares `formatOptions` by reference and, on a change, rewrites the
+ * input text with the last committed value. An inline literal at the call site is a
+ * new reference every render, so a parent re-render mid-typing discards what the
+ * operator has typed — decimals never survive.
+ */
+function useStableFormatOptions(formatOptions?: Intl.NumberFormatOptions) {
+ const ref = useRef(formatOptions);
+ if (!areNumberFormatOptionsEqual(ref.current, formatOptions)) {
+ ref.current = formatOptions;
+ }
+ return ref.current;
+}
+
+const NumberField = ({
+ className,
+ formatOptions,
+ ...props
+}: ReactAria.NumberFieldProps) => {
+ const stableFormatOptions = useStableFormatOptions(formatOptions);
return (
- <ReactAria.NumberField className={cn("w-full", className)} {...props} />
+ <ReactAria.NumberField
+ className={cn("w-full", className)}
+ {...props}
+ formatOptions={stableFormatOptions}
+ />
);
};
diff --git a/packages/react/src/__tests__/Number.test.tsx b/packages/react/src/__tests__/Number.test.tsx
index 8402e8d4ae..7d6b8d8ac1 100644
--- a/packages/react/src/__tests__/Number.test.tsx
+++ b/packages/react/src/__tests__/Number.test.tsx
@@ -11,7 +11,7 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
-import { NumberInput } from "../Number";
+import { areNumberFormatOptionsEqual, NumberInput } from "../Number";
/**
* The `onFocus` behavior ([4] focus-select) is an inline closure on the real
@@ -104,3 +104,59 @@ describe("NumberInput", () => {
});
});
});
+
+/**
+ * react-aria compares `formatOptions` by reference and rewrites the in-progress
+ * input text when it changes, so an inline literal at a call site destroys
+ * half-typed decimals on any parent re-render. `NumberField` holds the reference
+ * steady via this predicate — these tests pin the comparison, the snap-back
+ * itself is only observable in a browser.
+ */
+describe("areNumberFormatOptionsEqual", () => {
+ const options = { minimumFractionDigits: 0, maximumFractionDigits: 2 };
+
+ it("treats distinct literals with the same values as equal", () => {
+ expect(areNumberFormatOptionsEqual({ ...options }, { ...options })).toBe(
+ true
+ );
+ });
+
+ it("treats a changed value as not equal", () => {
+ expect(
+ areNumberFormatOptionsEqual(options, {
+ ...options,
+ maximumFractionDigits: 4
+ })
+ ).toBe(false);
+ });
+
+ it("treats an added key as not equal", () => {
+ expect(
+ areNumberFormatOptionsEqual(options, { ...options, style: "decimal" })
+ ).toBe(false);
+ });
+
+ it("treats a removed key as not equal", () => {
+ expect(
+ areNumberFormatOptionsEqual(options, { maximumFractionDigits: 2 })
+ ).toBe(false);
+ });
+
+ it("is insensitive to key order", () => {
+ expect(
+ areNumberFormatOptionsEqual(
+ { style: "currency", currency: "USD" },
+ { currency: "USD", style: "currency" }
+ )
+ ).toBe(true);
+ });
+
+ it("treats both undefined as equal", () => {
+ expect(areNumberFormatOptionsEqual(undefined, undefined)).toBe(true);
+ });
+
+ it("treats one undefined side as not equal", () => {
+ expect(areNumberFormatOptionsEqual(options, undefined)).toBe(false);
+ expect(areNumberFormatOptionsEqual(undefined, options)).toBe(false);
+ });
+});