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.

feat(batches): pick due dates from a calendar in the batch builder (#1760)

Sidad204fd6605d
diff --git a/apps/erp/app/components/DateSelect.tsx b/apps/erp/app/components/DateSelect.tsx
index 0fd5157d17..fea959e761 100644
--- a/apps/erp/app/components/DateSelect.tsx
+++ b/apps/erp/app/components/DateSelect.tsx
@@ -9,9 +9,10 @@ import {
ToggleGroup,
ToggleGroupItem
} from "@carbon/react";
+import type { CalendarDate } from "@internationalized/date";
import { useLingui } from "@lingui/react/macro";
import type { DateRange } from "@react-types/datepicker";
-import { forwardRef, useMemo } from "react";
+import { forwardRef, useMemo, useState } from "react";
import { LuCalendar } from "react-icons/lu";
type DateSelectOption = {
@@ -26,6 +27,8 @@ interface DateSelectProps {
showCustom?: boolean;
dateRange?: DateRange | null;
onDateRangeChange?: (dateRange: DateRange | null) => void;
+ /** Days to flag with a dot in the custom-range calendar. */
+ isDateMarked?: (date: CalendarDate) => boolean;
className?: string;
}
@@ -38,11 +41,19 @@ const DateSelect = forwardRef<HTMLDivElement, DateSelectProps>(
showCustom = true,
dateRange,
onDateRangeChange,
+ isDateMarked,
className
},
ref
) => {
const { t } = useLingui();
+ // Picking "custom" opens the calendar straight away; a page that merely
+ // loads on "custom" (e.g. from the URL) leaves it closed.
+ const [openCalendar, setOpenCalendar] = useState(false);
+ const onChange = (next: string) => {
+ setOpenCalendar(next === "custom");
+ onValueChange(next);
+ };
const resolvedOptions = useMemo(() => {
if (options) return options;
return [
@@ -64,7 +75,7 @@ const DateSelect = forwardRef<HTMLDivElement, DateSelectProps>(
className={cn("inline-flex items-center gap-2", className)}
>
{/* Compact dropdown for small screens */}
- <Select value={value} onValueChange={onValueChange}>
+ <Select value={value} onValueChange={onChange}>
<SelectTrigger className="md:hidden w-auto h-8 text-xs">
<SelectValue />
</SelectTrigger>
@@ -82,7 +93,7 @@ const DateSelect = forwardRef<HTMLDivElement, DateSelectProps>(
type="single"
value={value}
onValueChange={(v) => {
- if (v) onValueChange(v);
+ if (v) onChange(v);
}}
className="hidden md:inline-flex gap-0 rounded-full border border-border bg-muted p-0.5 shadow-sm"
>
@@ -122,6 +133,8 @@ const DateSelect = forwardRef<HTMLDivElement, DateSelectProps>(
value={dateRange}
onChange={onDateRangeChange}
size="sm"
+ defaultOpen={openCalendar}
+ isDateMarked={isDateMarked}
/>
)}
</div>
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
index 16fca91dc7..1eeaa8bee1 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
@@ -43,9 +43,16 @@ import {
resolveBatchRules,
round
} from "@carbon/utils";
-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
+import {
+ type CalendarDate,
+ getLocalTimeZone,
+ parseDate,
+ toCalendarDate,
+ today
+} from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
+import type { DateRange } from "@react-types/datepicker";
import type { ColumnDef } from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
@@ -64,7 +71,7 @@ import {
LuX
} from "react-icons/lu";
import { useFetcher, useNavigate } from "react-router";
-import { Enumerable, ItemThumbnail, Table } from "~/components";
+import { DateSelect, Enumerable, ItemThumbnail, Table } from "~/components";
import { EnumerableGroup } from "~/components/EnumerableGroup";
import { path } from "~/utils/path";
import type { jobStatus } from "../../production.models";
@@ -86,9 +93,11 @@ import {
computeLockedById,
computeMemberMismatches,
computeSelectionDimSets,
+ type DueFilter,
deriveAddTargets,
deriveFacetDimensions,
dueDateOf,
+ dueDatesOf,
type FacetDimension,
filterAndSortCandidates,
groupingKey,
@@ -330,7 +339,29 @@ export function BatchBuilder({
);
const [search, setSearch] = useState("");
const [facets, setFacets] = useState<Record<string, string[]>>({});
- const [dueWindow, setDueWindow] = useState<number | null>(null);
+ // The due filter as the standard DateSelect holds it: "all", a preset day
+ // count, or "custom" with the calendar's range.
+ const [dueSelect, setDueSelect] = useState("all");
+ const [dueRange, setDueRange] = useState<DateRange | null>(null);
+ const due = useMemo<DueFilter | null>(() => {
+ if (dueSelect === "custom") {
+ return dueRange
+ ? {
+ kind: "range",
+ start: toCalendarDate(dueRange.start),
+ end: toCalendarDate(dueRange.end)
+ }
+ : null;
+ }
+ const days = Number(dueSelect);
+ return Number.isInteger(days) && days > 0 ? { kind: "window", days } : null;
+ }, [dueSelect, dueRange]);
+ // Leaving "custom" drops its range, so coming back to it starts empty
+ // rather than silently re-applying a range picked earlier.
+ const onDueSelectChange = useCallback((value: string) => {
+ setDueSelect(value);
+ if (value !== "custom") setDueRange(null);
+ }, []);
const [workCenterId, setWorkCenterId] = useState<string | null>(null);
const [notes, setNotes] = useState("");
const [outputLots, setOutputLots] =
@@ -398,7 +429,8 @@ export function BatchBuilder({
setSelectedById(new Map());
setSearch("");
setFacets({});
- setDueWindow(null);
+ setDueSelect("all");
+ setDueRange(null);
setWorkCenterId(null);
}, []);
@@ -596,7 +628,7 @@ export function BatchBuilder({
);
// A candidate matches if ANY BOM line satisfies ALL active facets, the search
- // term matches its job/item/op text, and it falls inside the due window.
+ // term matches its job/item/op text, and it falls inside the due filter.
// Sorted most-urgent first (due date asc, undated last).
const filtered = useMemo(
() =>
@@ -604,10 +636,26 @@ export function BatchBuilder({
activeFacetKeys,
facets,
search,
- dueWindow,
+ due,
today: today(getLocalTimeZone())
}),
- [candidates, activeFacetKeys, facets, search, dueWindow]
+ [candidates, activeFacetKeys, facets, search, due]
+ );
+
+ // Days the calendar marks: where the operations matching every OTHER filter
+ // are due, so picking a day never lands on an empty list by surprise.
+ const dueDays = useMemo(
+ () =>
+ dueDatesOf(
+ filterAndSortCandidates(candidates, {
+ activeFacetKeys,
+ facets,
+ search,
+ due: null,
+ today: today(getLocalTimeZone())
+ })
+ ),
+ [candidates, activeFacetKeys, facets, search]
);
const visible = useMemo(() => filtered.slice(0, MAX_VISIBLE), [filtered]);
@@ -908,8 +956,12 @@ export function BatchBuilder({
onSearchChange={setSearch}
facets={facets}
dimensions={facetDimensions}
- dueWindow={dueWindow}
- onDueWindowChange={setDueWindow}
+ dueSelect={dueSelect}
+ onDueSelectChange={onDueSelectChange}
+ dueRange={dueRange}
+ onDueRangeChange={setDueRange}
+ isDueFiltered={due !== null}
+ dueDays={dueDays}
suggestions={suggestions}
onApplySuggestion={selectMany}
visible={visible}
@@ -1542,8 +1594,12 @@ function ComposePanel({
onSearchChange,
facets,
dimensions,
- dueWindow,
- onDueWindowChange,
+ dueSelect,
+ onDueSelectChange,
+ dueRange,
+ onDueRangeChange,
+ isDueFiltered,
+ dueDays,
suggestions,
onApplySuggestion,
visible,
@@ -1565,8 +1621,12 @@ function ComposePanel({
onSearchChange: (v: string) => void;
facets: Record<string, string[]>;
dimensions: FacetDimension[];
- dueWindow: number | null;
- onDueWindowChange: (days: number | null) => void;
+ dueSelect: string;
+ onDueSelectChange: (value: string) => void;
+ dueRange: DateRange | null;
+ onDueRangeChange: (range: DateRange | null) => void;
+ isDueFiltered: boolean;
+ dueDays: Set<string>;
suggestions: Suggestion[];
onApplySuggestion: (members: BatchCandidate[]) => void;
visible: BatchCandidate[];
@@ -1582,14 +1642,28 @@ function ComposePanel({
compat: CompatInfo;
}) {
const { t } = useLingui();
+ const dueOptions = useMemo(
+ () => [
+ { value: "all", label: t`All` },
+ ...DUE_WINDOWS.map((days) => ({
+ value: String(days),
+ label: t`${days}d`
+ }))
+ ],
+ [t]
+ );
+ // Dots in the calendar: days with operations due (every other filter
+ // applied), so a planner sees where work falls before picking a range.
+ const isDueDay = useCallback(
+ (date: CalendarDate) => dueDays.has(date.toString()),
+ [dueDays]
+ );
const activeDimensions = dimensions.filter(
(d) => (facets[d.key]?.length ?? 0) > 0
);
const isFiltered =
- search.trim().length > 0 ||
- dueWindow !== null ||
- activeDimensions.length > 0;
+ search.trim().length > 0 || isDueFiltered || activeDimensions.length > 0;
return (
<VStack spacing={0} className="h-full min-h-0 overflow-hidden bg-card">
@@ -1636,32 +1710,14 @@ function ComposePanel({
className="text-sm"
/>
</InputGroup>
- <HStack
- spacing={0}
- className="items-center gap-0.5 rounded-md border p-0.5"
- title={t`Due within`}
- >
- <LuCalendarClock className="size-3.5 text-muted-foreground mx-1.5 flex-shrink-0" />
- <Button
- size="sm"
- variant={dueWindow === null ? "secondary" : "ghost"}
- className="h-7 px-2"
- onClick={() => onDueWindowChange(null)}
- >
- {t`All`}
- </Button>
- {DUE_WINDOWS.map((days) => (
- <Button
- key={days}
- size="sm"
- variant={dueWindow === days ? "secondary" : "ghost"}
- className="h-7 px-2 tabular-nums"
- onClick={() => onDueWindowChange(days)}
- >
- {t`${days}d`}
- </Button>
- ))}
- </HStack>
+ <DateSelect
+ value={dueSelect}
+ onValueChange={onDueSelectChange}
+ options={dueOptions}
+ dateRange={dueRange}
+ onDateRangeChange={onDueRangeChange}
+ isDateMarked={isDueDay}
+ />
</HStack>
{view === "table" && suggestions.length > 0 && (
<SuggestionsBanner
diff --git a/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts b/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts
index 7e57df9255..eeab47a9a1 100644
--- a/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts
+++ b/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts
@@ -453,23 +453,46 @@ export function deriveFacetDimensions(
return dims;
}
+// The due-date filter: a rolling window ("due within N days", overdue
+// included) or a calendar range picked day to day, both ends inclusive.
+export type DueFilter =
+ | { kind: "window"; days: number }
+ | { kind: "range"; start: CalendarDate; end: CalendarDate };
+
+// Every distinct day (YYYY-MM-DD) the candidates are due on — the calendar
+// marks these days so a planner can see where work falls before picking.
+export function dueDatesOf(candidates: BatchCandidate[]): Set<string> {
+ const days = new Set<string>();
+ for (const c of candidates) {
+ const due = dueDateOf(c);
+ if (due) days.add(due);
+ }
+ return days;
+}
+
// A candidate matches if ANY BOM line satisfies ALL active facets, the search
-// term matches its job/item/op text, and it falls inside the due window. Sorted
-// most-urgent first (due date asc, undated last). `today` is injected so this
-// stays pure and testable.
+// term matches its job/item/op text, and it falls inside the due filter.
+// Sorted most-urgent first (due date asc, undated last). `today` is injected
+// so this stays pure and testable.
export function filterAndSortCandidates(
candidates: BatchCandidate[],
opts: {
activeFacetKeys: string[];
facets: Record<string, string[]>;
search: string;
- dueWindow: number | null;
+ due: DueFilter | null;
today: CalendarDate;
}
): BatchCandidate[] {
- const { activeFacetKeys, facets, search, dueWindow, today } = opts;
+ const { activeFacetKeys, facets, search, due: dueFilter, today } = opts;
const term = search.trim().toLowerCase();
- const dueLimit = dueWindow !== null ? today.add({ days: dueWindow }) : null;
+ const dueStart = dueFilter?.kind === "range" ? dueFilter.start : null;
+ const dueEnd =
+ dueFilter?.kind === "range"
+ ? dueFilter.end
+ : dueFilter?.kind === "window"
+ ? today.add({ days: dueFilter.days })
+ : null;
const matches = candidates.filter((c) => {
if (activeFacetKeys.length > 0) {
const anyLineMatches = (c.materials ?? []).some((m) =>
@@ -477,9 +500,12 @@ export function filterAndSortCandidates(
);
if (!anyLineMatches) return false;
}
- if (dueLimit) {
+ if (dueEnd) {
const due = dueDateOf(c);
- if (!due || parseDate(due).compare(dueLimit) > 0) return false;
+ if (!due) return false;
+ const dueDay = parseDate(due);
+ if (dueDay.compare(dueEnd) > 0) return false;
+ if (dueStart && dueDay.compare(dueStart) < 0) return false;
}
if (term) {
const haystack = [
diff --git a/apps/erp/test/batch-suggestions.test.ts b/apps/erp/test/batch-suggestions.test.ts
index 7757cea99e..9d6f3472c4 100644
--- a/apps/erp/test/batch-suggestions.test.ts
+++ b/apps/erp/test/batch-suggestions.test.ts
@@ -1,4 +1,5 @@
import { resolveBatchRules } from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import { describe, expect, it } from "vitest";
// Import the logic module directly — the ERP barrels drag lingui macros vitest
// does not transform (see batching-migration-guards.test.ts).
@@ -9,6 +10,8 @@ import {
computeLockedById,
computeMemberMismatches,
computeSelectionDimSets,
+ dueDatesOf,
+ filterAndSortCandidates,
groupingKey,
materialSignature,
rankSuggestions,
@@ -720,3 +723,73 @@ describe("computeMemberMismatches", () => {
expect(computeMemberMismatches([entry("solo", "Steel")], DEFAULT_RULES).size).toBe(0);
});
});
+
+describe("filterAndSortCandidates due filter", () => {
+ const today = parseDate("2026-09-29");
+ const candidates = [
+ makeCandidate("overdue", { dueDate: "2026-09-20" }),
+ makeCandidate("today", { dueDate: "2026-09-29" }),
+ makeCandidate("thu", { dueDate: "2026-10-01" }),
+ makeCandidate("next-week", { dueDate: "2026-10-06" }),
+ makeCandidate("job-due", { jobDueDate: "2026-10-01" }),
+ makeCandidate("undated")
+ ];
+ const run = (due: Parameters<typeof filterAndSortCandidates>[1]["due"]) =>
+ filterAndSortCandidates(candidates, {
+ activeFacetKeys: [],
+ facets: {},
+ search: "",
+ due,
+ today
+ }).map((c) => c.id);
+
+ it("keeps everything, undated last, with no due filter", () => {
+ expect(run(null)).toEqual([
+ "overdue",
+ "today",
+ "thu",
+ "job-due",
+ "next-week",
+ "undated"
+ ]);
+ });
+
+ it("a window keeps everything due up to today + N days, overdue included", () => {
+ expect(run({ kind: "window", days: 7 })).toEqual([
+ "overdue",
+ "today",
+ "thu",
+ "job-due",
+ "next-week"
+ ]);
+ });
+
+ it("a range keeps only what is due inside it, both ends inclusive", () => {
+ expect(
+ run({
+ kind: "range",
+ start: parseDate("2026-09-29"),
+ end: parseDate("2026-10-01")
+ })
+ ).toEqual(["today", "thu", "job-due"]);
+ });
+
+ it("a one-day range keeps only that day", () => {
+ const day = parseDate("2026-10-06");
+ expect(run({ kind: "range", start: day, end: day })).toEqual([
+ "next-week"
+ ]);
+ });
+});
+
+describe("dueDatesOf", () => {
+ it("collects each distinct due day, falling back to the job due date", () => {
+ const days = dueDatesOf([
+ makeCandidate("a", { dueDate: "2026-10-01" }),
+ makeCandidate("b", { dueDate: "2026-10-01" }),
+ makeCandidate("c", { jobDueDate: "2026-10-03" }),
+ makeCandidate("d")
+ ]);
+ expect([...days].sort()).toEqual(["2026-10-01", "2026-10-03"]);
+ });
+});
diff --git a/packages/react/src/Date/DateRangePicker.tsx b/packages/react/src/Date/DateRangePicker.tsx
index 0428191db4..ec45d7cd6a 100644
--- a/packages/react/src/Date/DateRangePicker.tsx
+++ b/packages/react/src/Date/DateRangePicker.tsx
@@ -1,3 +1,4 @@
+import type { CalendarDate } from "@internationalized/date";
import { useDateRangePicker } from "@react-aria/datepicker";
import { useDateRangePickerState } from "@react-stately/datepicker";
import type { DateRangePickerProps, DateValue } from "@react-types/datepicker";
@@ -39,9 +40,12 @@ const fieldVariants = cva("flex w-full", {
const DateRangePicker = ({
size = "md",
+ isDateMarked,
...props
}: DateRangePickerProps<DateValue> & {
size?: "sm" | "md" | "lg";
+ /** Days to flag with a dot in the calendar, e.g. days that have work due. */
+ isDateMarked?: (date: CalendarDate) => boolean;
}) => {
const state = useDateRangePickerState({
...props,
@@ -92,7 +96,7 @@ const DateRangePicker = ({
</PopoverTrigger>
</HStack>
<PopoverContent align="end" {...dialogProps}>
- <RangeCalendar {...calendarProps} />
+ <RangeCalendar {...calendarProps} isDateMarked={isDateMarked} />
</PopoverContent>
</div>
</Popover>
diff --git a/packages/react/src/Date/components/CalendarGrid.tsx b/packages/react/src/Date/components/CalendarGrid.tsx
index 59ac6a7918..6ea6fdcf4d 100644
--- a/packages/react/src/Date/components/CalendarGrid.tsx
+++ b/packages/react/src/Date/components/CalendarGrid.tsx
@@ -1,4 +1,4 @@
-import type { DateDuration } from "@internationalized/date";
+import type { CalendarDate, DateDuration } from "@internationalized/date";
import { endOfMonth, getWeeksInMonth } from "@internationalized/date";
import { useCalendarGrid } from "@react-aria/calendar";
import { useLocale } from "@react-aria/i18n";
@@ -12,11 +12,13 @@ import { CalendarRangeCell } from "./CalendarRangeCell";
export const CalendarGrid = ({
state,
offset = {},
- isRangeCalendar = false
+ isRangeCalendar = false,
+ isDateMarked
}: {
state: CalendarState | RangeCalendarState;
offset?: DateDuration;
isRangeCalendar?: boolean;
+ isDateMarked?: (date: CalendarDate) => boolean;
}) => {
const { locale } = useLocale();
const startDate = state.visibleRange.start.add(offset);
@@ -64,6 +66,7 @@ export const CalendarGrid = ({
date={date}
currentMonth={startDate}
locale={locale}
+ isMarked={isDateMarked?.(date) ?? false}
/>
) : (
<CalendarCell
diff --git a/packages/react/src/Date/components/CalendarRangeCell.tsx b/packages/react/src/Date/components/CalendarRangeCell.tsx
index bb3529a7d8..7e1f5439d0 100644
--- a/packages/react/src/Date/components/CalendarRangeCell.tsx
+++ b/packages/react/src/Date/components/CalendarRangeCell.tsx
@@ -16,6 +16,7 @@ export function CalendarRangeCell({
state,
date,
currentMonth,
+ isMarked = false,
...props
}: {
state: RangeCalendarState;
@@ -23,6 +24,7 @@ export function CalendarRangeCell({
currentMonth: CalendarDate;
isRangeCalendar?: boolean;
locale?: string;
+ isMarked?: boolean;
}) {
const ref = useRef<HTMLButtonElement>(null);
const {
@@ -76,16 +78,25 @@ export function CalendarRangeCell({
>
{formattedDate}
</Button>
- {isToday && (
- <span
- className={clsx(
- "absolute w-1 h-1 bottom-1 rounded-full left-1/2 transform -translate-x-1/2",
- {
- "bg-card": isSelected,
- "bg-primary ": !isSelected
- }
+ {(isToday || isMarked) && !isOutsideMonth && (
+ <span className="absolute bottom-1 left-1/2 flex -translate-x-1/2 gap-0.5 pointer-events-none">
+ {isToday && (
+ <span
+ className={clsx("w-1 h-1 rounded-full", {
+ "bg-card": isSelected,
+ "bg-primary": !isSelected
+ })}
+ />
)}
- />
+ {isMarked && (
+ <span
+ className={clsx("w-1 h-1 rounded-full", {
+ "bg-card/70": isSelected,
+ "bg-muted-foreground": !isSelected
+ })}
+ />
+ )}
+ </span>
)}
</td>
);
diff --git a/packages/react/src/Date/components/RangeCalendar.tsx b/packages/react/src/Date/components/RangeCalendar.tsx
index 3bfde174fb..aa35ae090d 100644
--- a/packages/react/src/Date/components/RangeCalendar.tsx
+++ b/packages/react/src/Date/components/RangeCalendar.tsx
@@ -17,11 +17,14 @@ import { CalendarGrid } from "./CalendarGrid";
export function RangeCalendar({
bordered = false,
+ isDateMarked,
...props
}: RangeCalendarProps<DateValue> & {
locale?: string;
bordered?: boolean;
className?: string;
+ /** Days to flag with a dot, e.g. days that have work due. */
+ isDateMarked?: (date: CalendarDate) => boolean;
}) {
const { locale } = useLocale();
const state = useRangeCalendarState({
@@ -100,7 +103,11 @@ export function RangeCalendar({
</div>
</div>
<div className="flex gap-8">
- <CalendarGrid state={state} isRangeCalendar />
+ <CalendarGrid
+ state={state}
+ isRangeCalendar
+ isDateMarked={isDateMarked}
+ />
</div>
</div>
<div
@@ -130,7 +137,12 @@ export function RangeCalendar({
/>
</div>
<div className="flex gap-8">
- <CalendarGrid state={state} offset={{ months: 1 }} isRangeCalendar />
+ <CalendarGrid
+ state={state}
+ offset={{ months: 1 }}
+ isRangeCalendar
+ isDateMarked={isDateMarked}
+ />
</div>
</div>
</div>