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.

Kanban Progress (#112)

Brad Barbinbd24bb3c34f0
diff --git a/apps/carbon/app/components/RealtimeDataProvider.tsx b/apps/carbon/app/components/RealtimeDataProvider.tsx
index 855bfc7b2f..5247ade9bd 100644
--- a/apps/carbon/app/components/RealtimeDataProvider.tsx
+++ b/apps/carbon/app/components/RealtimeDataProvider.tsx
@@ -1,8 +1,9 @@
"use client";
import { useCarbon } from "@carbon/auth";
+import type { RealtimeChannel } from "@supabase/supabase-js";
import idb from "localforage";
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
import { useUser } from "~/hooks";
import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";
import type { Item } from "~/stores/items";
@@ -95,206 +96,233 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
);
};
+ const channelRef = useRef<RealtimeChannel | null>(null);
+
useEffect(() => {
if (!companyId) return;
hydrate();
- if (!carbon || !accessToken) return;
- carbon.realtime.setAuth(accessToken);
- const channel = carbon
- .channel("realtime:core")
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "item",
- },
- (payload) => {
- if ("companyId" in payload.new && payload.new.companyId !== companyId)
- return;
- switch (payload.eventType) {
- case "INSERT":
- const { new: inserted } = payload;
+ if (!channelRef.current && carbon && accessToken) {
+ carbon.realtime.setAuth(accessToken);
+ channelRef.current = carbon
+ .channel("realtime:core")
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "item",
+ filter: `companyId=eq.${companyId}`,
+ },
+ (payload) => {
+ if (
+ "companyId" in payload.new &&
+ payload.new.companyId !== companyId
+ )
+ return;
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
- setItems((items) =>
- [
- ...items,
- {
- id: inserted.id,
- name: inserted.name,
- readableId: inserted.readableId,
- description: inserted.description,
- replenishmentSystem: inserted.replenishmentSystem,
- type: inserted.type,
- active: inserted.active,
- },
- ].sort((a, b) => a.readableId.localeCompare(b.readableId))
- );
+ setItems((items) =>
+ [
+ ...items,
+ {
+ id: inserted.id,
+ name: inserted.name,
+ readableId: inserted.readableId,
+ description: inserted.description,
+ replenishmentSystem: inserted.replenishmentSystem,
+ type: inserted.type,
+ active: inserted.active,
+ },
+ ].sort((a, b) => a.readableId.localeCompare(b.readableId))
+ );
- break;
- case "UPDATE":
- const { new: updated } = payload;
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
- setItems((items) =>
- items
- .map((i) => {
- if (i.id === updated.id) {
- return {
- ...i,
- readableId: updated.readableId,
- name: updated.name,
- replenishmentSystem: updated.replenishmentSystem,
- type: updated.type,
- active: updated.active,
- };
- }
- return i;
- })
- .sort((a, b) => a.readableId.localeCompare(b.readableId))
- );
- break;
- case "DELETE":
- const { old: deleted } = payload;
- setItems((items) => items.filter((p) => p.id !== deleted.id));
- break;
- default:
- break;
+ setItems((items) =>
+ items
+ .map((i) => {
+ if (i.id === updated.id) {
+ return {
+ ...i,
+ readableId: updated.readableId,
+ name: updated.name,
+ replenishmentSystem: updated.replenishmentSystem,
+ type: updated.type,
+ active: updated.active,
+ };
+ }
+ return i;
+ })
+ .sort((a, b) => a.readableId.localeCompare(b.readableId))
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setItems((items) => items.filter((p) => p.id !== deleted.id));
+ break;
+ default:
+ break;
+ }
}
- }
- )
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "customer",
- },
- (payload) => {
- if ("companyId" in payload.new && payload.new.companyId !== companyId)
- return;
- switch (payload.eventType) {
- case "INSERT":
- const { new: inserted } = payload;
- setCustomers((customers) =>
- [
- ...customers,
- {
- id: inserted.id,
- name: inserted.name,
- },
- ].sort((a, b) => a.name.localeCompare(b.name))
- );
- break;
- case "UPDATE":
- const { new: updated } = payload;
- setCustomers((customers) =>
- customers
- .map((p) => {
- if (p.id === updated.id) {
- return {
- ...p,
- name: updated.name,
- };
- }
- return p;
- })
- .sort((a, b) => a.name.localeCompare(b.name))
- );
- break;
- case "DELETE":
- const { old: deleted } = payload;
- setCustomers((customers) =>
- customers.filter((p) => p.id !== deleted.id)
- );
- break;
- default:
- break;
+ )
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "customer",
+ filter: `companyId=eq.${companyId}`,
+ },
+ (payload) => {
+ if (
+ "companyId" in payload.new &&
+ payload.new.companyId !== companyId
+ )
+ return;
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
+ setCustomers((customers) =>
+ [
+ ...customers,
+ {
+ id: inserted.id,
+ name: inserted.name,
+ },
+ ].sort((a, b) => a.name.localeCompare(b.name))
+ );
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+ setCustomers((customers) =>
+ customers
+ .map((p) => {
+ if (p.id === updated.id) {
+ return {
+ ...p,
+ name: updated.name,
+ };
+ }
+ return p;
+ })
+ .sort((a, b) => a.name.localeCompare(b.name))
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setCustomers((customers) =>
+ customers.filter((p) => p.id !== deleted.id)
+ );
+ break;
+ default:
+ break;
+ }
}
- }
- )
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "supplier",
- },
- (payload) => {
- if ("companyId" in payload.new && payload.new.companyId !== companyId)
- return;
- switch (payload.eventType) {
- case "INSERT":
- const { new: inserted } = payload;
+ )
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "supplier",
+ filter: `companyId=eq.${companyId}`,
+ },
+ (payload) => {
+ if (
+ "companyId" in payload.new &&
+ payload.new.companyId !== companyId
+ )
+ return;
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
- setSuppliers((suppliers) =>
- [
- ...suppliers,
- {
- id: inserted.id,
- name: inserted.name,
- },
- ].sort((a, b) => a.name.localeCompare(b.name))
- );
- break;
- case "UPDATE":
- const { new: updated } = payload;
- setSuppliers((suppliers) =>
- suppliers
- .map((p) => {
- if (p.id === updated.id) {
- return {
- ...p,
- name: updated.name,
- };
- }
- return p;
- })
- .sort((a, b) => a.name.localeCompare(b.name))
- );
- break;
- case "DELETE":
- const { old: deleted } = payload;
- setSuppliers((suppliers) =>
- suppliers.filter((p) => p.id !== deleted.id)
- );
- break;
- default:
- break;
+ setSuppliers((suppliers) =>
+ [
+ ...suppliers,
+ {
+ id: inserted.id,
+ name: inserted.name,
+ },
+ ].sort((a, b) => a.name.localeCompare(b.name))
+ );
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+ setSuppliers((suppliers) =>
+ suppliers
+ .map((p) => {
+ if (p.id === updated.id) {
+ return {
+ ...p,
+ name: updated.name,
+ };
+ }
+ return p;
+ })
+ .sort((a, b) => a.name.localeCompare(b.name))
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setSuppliers((suppliers) =>
+ suppliers.filter((p) => p.id !== deleted.id)
+ );
+ break;
+ default:
+ break;
+ }
}
- }
- )
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "employee",
- },
- async (payload) => {
- if ("companyId" in payload.new && payload.new.companyId !== companyId)
- return;
- // TODO: there's a cleaner way of doing this, but since customers and suppliers
- // are also in the users table, we can't automatically add/update/delete them
- // from our list of employees. So for now we just refetch.
- const { data } = await carbon
- .from("employees")
- .select("id, name, avatarUrl")
- .eq("companyId", companyId)
- .order("name");
- if (data) {
- // @ts-ignore
- setPeople(data);
+ )
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "employee",
+ filter: `companyId=eq.${companyId}`,
+ },
+ async (payload) => {
+ if (
+ "companyId" in payload.new &&
+ payload.new.companyId !== companyId
+ )
+ return;
+ // TODO: there's a cleaner way of doing this, but since customers and suppliers
+ // are also in the users table, we can't automatically add/update/delete them
+ // from our list of employees. So for now we just refetch.
+ const { data } = await carbon
+ .from("employees")
+ .select("id, name, avatarUrl")
+ .eq("companyId", companyId)
+ .order("name");
+ if (data) {
+ // @ts-ignore
+ setPeople(data);
+ }
}
- }
- )
- .subscribe();
+ )
+ .subscribe();
+ }
return () => {
- if (channel) carbon?.removeChannel(channel);
+ if (channelRef.current) {
+ channelRef.current.unsubscribe();
+ channelRef.current = null;
+ }
};
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [carbon, accessToken, companyId]);
+ }, [companyId]);
+
+ useEffect(() => {
+ if (carbon && accessToken) carbon.realtime.setAuth(accessToken);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [accessToken]);
return <>{children}</>;
};
diff --git a/apps/carbon/app/modules/items/ui/Item/index.ts b/apps/carbon/app/modules/items/ui/Item/index.ts
index 7bd96bb483..875caeb144 100644
--- a/apps/carbon/app/modules/items/ui/Item/index.ts
+++ b/apps/carbon/app/modules/items/ui/Item/index.ts
@@ -8,6 +8,7 @@ import { FileBadge } from "./FileBadge";
import ItemCostingForm from "./ItemCostingForm";
import ItemDocuments from "./ItemDocuments";
import ItemForm from "./ItemForm";
+import ItemNotes from "./ItemNotes";
import ItemPlanningForm from "./ItemPlanningForm";
import ItemPurchasingForm from "./ItemPurchasingForm";
import ItemSalePriceForm from "./ItemSalePriceForm";
@@ -24,6 +25,7 @@ export {
ItemCostingForm,
ItemDocuments,
ItemForm,
+ ItemNotes,
ItemPlanningForm,
ItemPurchasingForm,
ItemSalePriceForm,
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index a231a8fce3..8861143be9 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -353,12 +353,10 @@ const JobBillOfProcess = ({
const channelRef = useRef<RealtimeChannel | null>(null);
useEffect(() => {
- if (!carbon || !accessToken || !selectedItemId) return;
- carbon.realtime.setAuth(accessToken);
-
- if (!channelRef.current) {
+ if (!channelRef.current && carbon && accessToken) {
+ carbon.realtime.setAuth(accessToken);
channelRef.current = carbon
- .channel("realtime:core")
+ .channel(`production-events:${selectedItemId}`)
.on(
"postgres_changes",
{
@@ -401,9 +399,18 @@ const JobBillOfProcess = ({
}
return () => {
- if (channelRef.current) carbon?.removeChannel(channelRef.current);
+ if (channelRef.current) {
+ channelRef.current.unsubscribe();
+ channelRef.current = null;
+ }
};
- }, [accessToken, carbon, selectedItemId]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedItemId]);
+
+ useEffect(() => {
+ if (carbon && accessToken) carbon.realtime.setAuth(accessToken);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [accessToken]);
const loadMoreProductionEvents = useCallback(async () => {
if (isLoading || !hasMore || !selectedItemId) return;
@@ -437,6 +444,7 @@ const JobBillOfProcess = ({
onToggleItem,
onRemoveItem,
}: SortableItemRenderProps<ItemWithData>) => {
+ console.log({ item, items, selectedItemId });
const isOpen = item.id === selectedItemId;
const tabs = [
{
diff --git a/apps/carbon/app/modules/production/ui/Schedule/Kanban/Kanban.tsx b/apps/carbon/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
index 218f1ca314..8469f8ed51 100644
--- a/apps/carbon/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
@@ -22,12 +22,13 @@ import { createPortal } from "react-dom";
import { path } from "~/utils/path";
import { BoardContainer, ColumnCard } from "./components/ColumnCard";
import { ItemCard } from "./components/ItemCard";
-import type { Column, DisplaySettings, Item } from "./types";
+import type { Column, DisplaySettings, Item, Progress } from "./types";
import { coordinateGetter, hasDraggableData } from "./utils";
type KanbanProps = {
columns: Column[];
items: Item[];
+ progressByItemId: Record<string, Progress>;
} & DisplaySettings;
const COLUMN_ORDER_KEY = "kanban-column-order";
@@ -35,6 +36,7 @@ const COLUMN_ORDER_KEY = "kanban-column-order";
const Kanban = ({
columns,
items: initialItems,
+ progressByItemId,
...displaySettings
}: KanbanProps) => {
const submit = useSubmit();
@@ -215,6 +217,7 @@ const Kanban = ({
key={col.id}
column={col}
items={items.filter((item) => item.columnId === col.id)}
+ progressByItemId={progressByItemId}
{...displaySettings}
/>
);
@@ -233,11 +236,24 @@ const Kanban = ({
items={items.filter(
(item) => item.columnId === activeColumn.id
)}
+ progressByItemId={progressByItemId}
{...displaySettings}
/>
)}
{activeItem && (
- <ItemCard item={activeItem} isOverlay {...displaySettings} />
+ <ItemCard
+ item={{
+ ...activeItem,
+ status: progressByItemId[activeItem.id]?.active
+ ? "In Progress"
+ : activeItem.status,
+ progress: progressByItemId[activeItem.id]?.progress ?? 0,
+ duration:
+ progressByItemId[activeItem.id]?.totalDuration ?? 0,
+ }}
+ isOverlay
+ {...displaySettings}
+ />
)}
</DragOverlay>,
document.body
diff --git a/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
index ef621d8f30..97cbd22da3 100644
--- a/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
@@ -15,19 +15,27 @@ import { cva } from "class-variance-authority";
import { useMemo } from "react";
import { LuGripVertical } from "react-icons/lu";
import { useUrlParams } from "~/hooks";
-import type { Column, ColumnDragData, DisplaySettings, Item } from "../types";
+import type {
+ Column,
+ ColumnDragData,
+ DisplaySettings,
+ Item,
+ Progress,
+} from "../types";
import { ItemCard } from "./ItemCard";
type ColumnCardProps = {
column: Column;
items: Item[];
isOverlay?: boolean;
+ progressByItemId: Record<string, Progress>;
} & DisplaySettings;
export function ColumnCard({
column,
items,
isOverlay,
+ progressByItemId,
...displaySettings
}: ColumnCardProps) {
const [params] = useUrlParams();
@@ -37,7 +45,10 @@ export function ColumnCard({
}, [items]);
const totalDuration = items.reduce((acc, item) => {
- return acc + Math.max((item.duration ?? 0) - (item.progress ?? 0), 0);
+ const progress = progressByItemId[item.id]?.progress ?? 0;
+ const duration = progressByItemId[item.id]?.totalDuration ?? 0;
+ const effectiveDuration = Math.max(duration - progress, 0);
+ return acc + effectiveDuration;
}, 0);
const {
@@ -76,6 +87,8 @@ export function ColumnCard({
}
);
+ const isActive = items.some((item) => progressByItemId[item.id]?.active);
+
return (
<Card
ref={setNodeRef}
@@ -91,7 +104,7 @@ export function ColumnCard({
>
<CardHeader className="p-4 w-full font-semibold text-left flex flex-row space-between items-center sticky top-0 bg-card z-10 border-b">
<div className="flex flex-grow items-start space-x-2">
- {column.active && <PulsingDot />}
+ {isActive && <PulsingDot />}
<div className="flex flex-col flex-grow">
<span className="mr-auto truncate"> {column.title}</span>
{totalDuration > 0 ? (
@@ -118,7 +131,18 @@ export function ColumnCard({
<CardContent className="flex flex-col gap-2 p-2">
<SortableContext items={itemsIds}>
{items.map((item) => (
- <ItemCard key={item.id} item={item} {...displaySettings} />
+ <ItemCard
+ key={item.id}
+ item={{
+ ...item,
+ status: progressByItemId[item.id]?.active
+ ? "In Progress"
+ : item.status,
+ progress: progressByItemId[item.id]?.progress ?? 0,
+ duration: progressByItemId[item.id]?.totalDuration ?? 0,
+ }}
+ {...displaySettings}
+ />
))}
</SortableContext>
</CardContent>
diff --git a/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
index 7e759cdf05..e64c279e62 100644
--- a/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
@@ -129,6 +129,13 @@ export function ItemCard({
? new Date(item.dueDate) < new Date()
: false;
+ console.log({
+ value:
+ item.progress && item.duration
+ ? (item.progress / item.duration) * 100
+ : 0,
+ });
+
return (
<Card
ref={setNodeRef}
@@ -186,10 +193,17 @@ export function ItemCard({
</div>
{showProgress &&
- ["Paused", "Done", "In Progress"].includes(item.status!) && (
+ Number.isFinite(item?.progress) &&
+ Number.isFinite(item?.duration) &&
+ Number(item?.progress) >= 0 &&
+ Number(item?.duration) >= 0 && (
<Progress
indicatorClassName={
- item.status === "Paused" ? "bg-yellow-500" : ""
+ (item.progress ?? 0) > (item.duration ?? 0)
+ ? "bg-destructive"
+ : item.status === "Paused"
+ ? "bg-yellow-500"
+ : ""
}
numerator={
item.progress ? formatDurationMilliseconds(item.progress) : ""
@@ -197,11 +211,12 @@ export function ItemCard({
denominator={
item.duration ? formatDurationMilliseconds(item.duration) : ""
}
- value={
+ value={Math.min(
item.progress && item.duration
? (item.progress / item.duration) * 100
- : 0
- }
+ : 0,
+ 100
+ )}
/>
)}
</CardHeader>
diff --git a/apps/carbon/app/modules/production/ui/Schedule/Kanban/types.ts b/apps/carbon/app/modules/production/ui/Schedule/Kanban/types.ts
index 6875fa9d46..365f478f6a 100644
--- a/apps/carbon/app/modules/production/ui/Schedule/Kanban/types.ts
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/types.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import type { ProductionEvent } from "~/modules/production";
import { deadlineTypes, jobOperationStatus } from "~/modules/production";
export const columnValidator = z.object({
@@ -28,6 +29,11 @@ export type DisplaySettings = {
export type DraggableData = ColumnDragData | ItemDragData;
+export type Event = Pick<
+ ProductionEvent,
+ "id" | "jobOperationId" | "duration" | "startTime" | "endTime"
+>;
+
const itemValidator = z.object({
id: z.string(),
columnId: z.string(),
@@ -47,6 +53,9 @@ const itemValidator = z.object({
salesOrderReadableId: z.string().optional(),
salesOrderId: z.string().optional(),
salesOrderLineId: z.string().optional(),
+ setupDuration: z.number().optional(),
+ laborDuration: z.number().optional(),
+ machineDuration: z.number().optional(),
});
export type Item = z.infer<typeof itemValidator>;
@@ -56,26 +65,8 @@ export interface ItemDragData {
item: Item;
}
-export enum ItemStatus {
- Canceled = "CANCELED",
- Done = "DONE",
- InProgress = "IN_PROGRESS",
- Paused = "PAUSED",
- Ready = "READY",
- Todo = "TODO",
- Waiting = "WAITING",
-}
-
-export enum ItemDeadline {
- ASAP = "ASAP",
- HardDeadline = "Hard Deadline",
- SoftDeadline = "Soft Deadline",
- NoDeadline = "No Deadline",
-}
-
-export enum ItemPriority {
- ASAP = "ASAP",
- High = "HIGH",
- Average = "AVERAGE",
- Low = "LOW",
-}
+export type Progress = {
+ totalDuration: number;
+ progress: number;
+ active: boolean;
+};
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
index 152990ada6..2c03aedf2d 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
@@ -48,6 +48,8 @@ const SalesRFQHeader = () => {
opportunity: Opportunity;
}>(path.to.salesRfq(rfqId));
+ console.log(routeData?.opportunity);
+
const status = routeData?.rfqSummary?.status ?? "Draft";
const statusFetcher = useFetcher<{}>();
diff --git a/apps/carbon/app/routes/x+/_index.tsx b/apps/carbon/app/routes/x+/_index.tsx
index f7890c3fcc..053872333c 100644
--- a/apps/carbon/app/routes/x+/_index.tsx
+++ b/apps/carbon/app/routes/x+/_index.tsx
@@ -3,11 +3,13 @@ import { getLocalTimeZone } from "@internationalized/date";
import { useLocale } from "@react-aria/i18n";
import { Link } from "@remix-run/react";
import { useMemo, type ComponentProps } from "react";
+import { LuHardHat } from "react-icons/lu";
import { useModules, useUser } from "~/hooks";
import type { Authenticated, NavItem } from "~/types";
export default function AppIndexRoute() {
const user = useUser();
+ // const permissions = usePermissions();
const modules = useModules();
const { locale } = useLocale();
const date = new Date();
@@ -28,9 +30,25 @@ export default function AppIndexRoute() {
<Hr />
<Subheading className="mb-8">Modules</Subheading>
<div className="grid grid-cols-1 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-6">
+ {/* {permissions.can("view", "production") && (
+ <ModuleCard
+ module={{
+ name: "Schedule",
+ to: path.to.schedule,
+ icon: LuCalendarClock,
+ }}
+ />
+ )} */}
{modules.map((module) => (
<ModuleCard key={module.name} module={module} />
))}
+ <ModuleCard
+ module={{
+ name: "MES",
+ to: "https://mes.carbonos.dev",
+ icon: LuHardHat,
+ }}
+ />
</div>
</div>
);
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.details.tsx b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
index 23d658be75..8aa1eefd16 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
import { Spinner, VStack } from "@carbon/react";
import { Await, useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
@@ -12,6 +13,7 @@ import { usePermissions, useRouteData } from "~/hooks";
import type { ItemFile, PartSummary } from "~/modules/items";
import {
ItemDocuments,
+ ItemNotes,
PartForm,
partValidator,
upsertPart,
@@ -86,6 +88,12 @@ export default function PartDetailsRoute() {
key={JSON.stringify(partInitialValues)}
initialValues={partInitialValues}
/>
+ <ItemNotes
+ id={partData.partSummary?.itemId ?? null}
+ title={partData.partSummary?.id ?? ""}
+ subTitle={partData.partSummary?.name ?? ""}
+ notes={partData.partSummary?.notes as JSONContent}
+ />
{permissions.is("employee") && (
<div className="grid grid-cols-1 2xl:grid-cols-2 w-full flex-grow gap-2">
<Suspense
diff --git a/apps/carbon/app/routes/x+/schedule+/index.tsx b/apps/carbon/app/routes/x+/schedule+/index.tsx
index 49a2d25171..00aa27e0ae 100644
--- a/apps/carbon/app/routes/x+/schedule+/index.tsx
+++ b/apps/carbon/app/routes/x+/schedule+/index.tsx
@@ -1,22 +1,38 @@
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
-import { error } from "@carbon/auth";
+import { error, useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { Button, ClientOnly, HStack, Spinner } from "@carbon/react";
+import {
+ Button,
+ ClientOnly,
+ HStack,
+ Spinner,
+ toast,
+ useInterval,
+ useMount,
+} from "@carbon/react";
+import {
+ getLocalTimeZone,
+ now,
+ parseAbsolute,
+ toZoned,
+} from "@internationalized/date";
import { Link, useLoaderData } from "@remix-run/react";
+import type { RealtimeChannel } from "@supabase/supabase-js";
import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";
-import { useMemo } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LuAlertTriangle, LuPlusCircle } from "react-icons/lu";
import { SearchFilter } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ActiveFilters, Filter } from "~/components/Table/components/Filter";
import type { ColumnFilter } from "~/components/Table/components/Filter/types";
import { useFilters } from "~/components/Table/components/Filter/useFilters";
-import { useUrlParams } from "~/hooks";
+import { useUrlParams, useUser } from "~/hooks";
import type { Column, Item } from "~/modules/production";
import { getActiveJobOperationsByLocation, Kanban } from "~/modules/production";
+import type { Event, Progress } from "~/modules/production/ui/Schedule/Kanban";
import {
getLocationsList,
getProcessesList,
@@ -183,15 +199,17 @@ export async function loader({ request }: LoaderFunctionArgs) {
subtitle: op.itemReadableId,
description: op.description,
dueDate: op.jobDueDate,
- duration:
- operation.setupDuration +
- Math.max(operation.laborDuration, operation.machineDuration),
+ duration: 0, // set in the client
+ progress: 0, // set in the client
deadlineType: op.jobDeadlineType,
customerId: op.jobCustomerId,
salesOrderReadableId: op.salesOrderReadableId,
salesOrderId: op.salesOrderId,
salesOrderLineId: op.salesOrderLineId,
status: op.operationStatus,
+ setupDuration: operation.setupDuration,
+ laborDuration: operation.laborDuration,
+ machineDuration: operation.machineDuration,
};
}) ?? []) satisfies Item[],
processes: processes.data ?? [],
@@ -207,9 +225,35 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ScheduleRoute() {
- const { columns, items, processes, salesOrders } =
- useLoaderData<typeof loader>();
+ const {
+ columns,
+ items: initialItems,
+ processes,
+ salesOrders,
+ } = useLoaderData<typeof loader>();
+
+ const [items, setItems] = useState<Item[]>(initialItems);
+
+ useEffect(() => {
+ setItems(initialItems);
+ }, [initialItems]);
+
+ const sortItems = useCallback((items: Item[]) => {
+ return [...items].sort((a, b) => a.priority - b.priority);
+ }, []);
+
+ useEffect(() => {
+ setItems((prevItems) => sortItems(prevItems));
+ }, [sortItems]);
+
+ const progressByOperation = useProgressByOperation(
+ items,
+ setItems,
+ sortItems
+ );
+
const [params] = useUrlParams();
+
const { hasFilters, clearFilters } = useFilters();
const currentFilters = params.getAll("filter").filter(Boolean);
const filters = useMemo<ColumnFilter[]>(() => {
@@ -281,12 +325,13 @@ export default function ScheduleRoute() {
<Kanban
columns={columns}
items={items}
+ progressByItemId={progressByOperation}
showCustomer
showDescription
showDueDate
showDuration
showEmployee
- showProgress={false}
+ showProgress
showStatus
showSalesOrder
/>
@@ -320,3 +365,216 @@ export default function ScheduleRoute() {
</div>
);
}
+
+function useProgressByOperation(
+ items: Item[],
+ setItems: React.Dispatch<React.SetStateAction<Item[]>>,
+ sortItems: (items: Item[]) => Item[]
+) {
+ const {
+ company: { id: companyId },
+ } = useUser();
+ const { carbon, accessToken } = useCarbon();
+
+ const [productionEventsByOperation, setProductionEventsByOperation] =
+ useState<Record<string, Event[]>>({});
+
+ const [progressByOperation, setProgressByOperation] = useState<
+ Record<string, Progress>
+ >({});
+
+ const getProductionEvents = useCallback(
+ async (operationIds: string[]) => {
+ if (!carbon) return;
+
+ const { data, error } = await carbon
+ .from("productionEvent")
+ .select("id, jobOperationId, duration, startTime, endTime, duration")
+ .eq("companyId", companyId)
+ .in("jobOperationId", operationIds);
+
+ if (error) {
+ toast.error(error.message);
+ }
+
+ if (data) {
+ setProductionEventsByOperation(
+ data.reduce<Record<string, Event[]>>((acc, event) => {
+ acc[event.jobOperationId] = [
+ ...(acc[event.jobOperationId] ?? []),
+ event,
+ ];
+ return acc;
+ }, {})
+ );
+ }
+ },
+ [carbon, companyId]
+ );
+
+ useMount(() => {
+ getProductionEvents(items.map((item) => item.id));
+ });
+
+ const getProgress = useCallback(() => {
+ const timeNow = now(getLocalTimeZone());
+ const progress: Record<string, Progress> = {};
+
+ Object.entries(productionEventsByOperation).forEach(
+ ([operationId, events]) => {
+ const operation = items.find((item) => item.id === operationId);
+ const totalDuration =
+ (operation?.setupDuration ?? 0) +
+ (operation?.laborDuration ?? 0) +
+ (operation?.machineDuration ?? 0);
+
+ let currentProgress = 0;
+ let active = false;
+ events.forEach((event) => {
+ if (event.endTime && event.duration) {
+ currentProgress += event.duration * 1000;
+ } else if (event.startTime) {
+ active = true;
+ const startTime = toZoned(
+ parseAbsolute(event.startTime, getLocalTimeZone()),
+ getLocalTimeZone()
+ );
+
+ const difference = timeNow.compare(startTime);
+ if (difference > 0) {
+ currentProgress += difference;
+ }
+ }
+ });
+
+ progress[operationId] = {
+ totalDuration,
+ progress: currentProgress,
+ active,
+ };
+ }
+ );
+
+ return progress;
+ }, [productionEventsByOperation, items]);
+
+ useInterval(() => {
+ setProgressByOperation(getProgress());
+ }, 1000);
+
+ useEffect(() => {
+ if (Object.keys(productionEventsByOperation).length > 0) {
+ setProgressByOperation(getProgress());
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [productionEventsByOperation]);
+
+ const channelRef = useRef<RealtimeChannel | null>(null);
+ useMount(() => {
+ if (!channelRef.current && carbon && accessToken) {
+ carbon.realtime.setAuth(accessToken);
+ channelRef.current = carbon
+ .channel(`kanban-schedule:${companyId}`)
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "jobOperation",
+ filter: `id=in.(${items.map((item) => item.id).join(",")})`,
+ },
+ (payload) => {
+ switch (payload.eventType) {
+ case "UPDATE": {
+ const { new: updated } = payload;
+ setItems((prevItems: Item[]) =>
+ sortItems(
+ prevItems.map((item: Item) => {
+ if (item.id === updated.id) {
+ return {
+ ...item,
+ columnId: updated.workCenterId,
+ priority: updated.priority,
+ };
+ }
+ return item;
+ })
+ )
+ );
+ break;
+ }
+ case "DELETE": {
+ const { old: deleted } = payload;
+ setItems((prevItems: Item[]) =>
+ sortItems(
+ prevItems.filter((item: Item) => item.id !== deleted.id)
+ )
+ );
+ break;
+ }
+ }
+ }
+ )
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "productionEvent",
+ filter: `companyId=eq.${companyId}`,
+ },
+ (payload) => {
+ if (payload.eventType === "INSERT") {
+ const { new: inserted } = payload;
+ if (inserted.jobOperationId) {
+ setProductionEventsByOperation((prevState) => ({
+ ...prevState,
+ [inserted.jobOperationId]: [
+ ...(prevState[inserted.jobOperationId] ?? []),
+ inserted,
+ ],
+ }));
+ }
+ } else if (payload.eventType === "UPDATE") {
+ const { new: updated } = payload;
+ if (updated.jobOperationId) {
+ setProductionEventsByOperation((prevState) => ({
+ ...prevState,
+ [updated.jobOperationId]: (
+ prevState[updated.jobOperationId] ?? []
+ ).map((event) => (event.id === updated.id ? updated : event)),
+ }));
+ }
+ } else if (payload.eventType === "DELETE") {
+ const { old: deleted } = payload;
+ if (deleted.jobOperationId) {
+ setProductionEventsByOperation((prevState) => ({
+ ...prevState,
+ [deleted.jobOperationId]: (
+ prevState[deleted.jobOperationId] ?? []
+ ).filter((event) => event.id !== deleted.id),
+ }));
+ }
+ }
+ }
+ )
+ .subscribe();
+ }
+
+ return () => {
+ if (channelRef.current) {
+ channelRef.current.unsubscribe();
+ carbon?.removeChannel(channelRef.current);
+ channelRef.current = null;
+ }
+ };
+ });
+
+ useEffect(() => {
+ if (carbon && accessToken && channelRef.current)
+ carbon.realtime.setAuth(accessToken);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [accessToken]);
+
+ return progressByOperation;
+}
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 45ed8dc9a0..790fa41e3f 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -369,7 +369,7 @@ export const JobOperation = ({
<Heading
size="h3"
className={cn(
- "truncate",
+ "w-full truncate",
isOverdue ? "text-red-500" : ""
)}
>
diff --git a/apps/mes/app/components/RealtimeDataProvider.tsx b/apps/mes/app/components/RealtimeDataProvider.tsx
index 8312b5a29c..579cc77e9c 100644
--- a/apps/mes/app/components/RealtimeDataProvider.tsx
+++ b/apps/mes/app/components/RealtimeDataProvider.tsx
@@ -83,6 +83,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
event: "*",
schema: "public",
table: "item",
+ filter: `companyId=eq.${companyId}`,
},
(payload) => {
if ("companyId" in payload.new && payload.new.companyId !== companyId)
@@ -144,6 +145,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
event: "*",
schema: "public",
table: "employee",
+ filter: `companyId=eq.${companyId}`,
},
async (payload) => {
if ("companyId" in payload.new && payload.new.companyId !== companyId)
diff --git a/apps/mes/app/hooks/useRealtime.tsx b/apps/mes/app/hooks/useRealtime.tsx
index f0074d2e6f..e7fa0b8299 100644
--- a/apps/mes/app/hooks/useRealtime.tsx
+++ b/apps/mes/app/hooks/useRealtime.tsx
@@ -20,7 +20,7 @@ export function useRealtime(table: string, filter?: string) {
event: "*",
schema: "public",
table: table,
- filter: filter,
+ filter: filter ?? `companyId=eq.${company.id}`,
},
(payload) => {
revalidator.revalidate();
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index fd52fbaa49..5838995b13 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -25911,14 +25911,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -28570,14 +28570,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index fd52fbaa49..5838995b13 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -25911,14 +25911,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -28570,14 +28570,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/form/src/components/InputControlled.tsx b/packages/form/src/components/InputControlled.tsx
index 7d4ac2e59c..61208e9054 100644
--- a/packages/form/src/components/InputControlled.tsx
+++ b/packages/form/src/components/InputControlled.tsx
@@ -15,7 +15,7 @@ import {
} from "@carbon/react";
import type { ChangeEvent, ReactNode } from "react";
import { forwardRef, useEffect, useRef, useState } from "react";
-import { LuPlusCircle, LuSettings2 } from "react-icons/lu";
+import { LuPlus, LuSettings2 } from "react-icons/lu";
import { useControlField, useField } from "../hooks";
type FormInputControlledProps = Omit<InputProps, "value" | "onChange"> & {
@@ -84,7 +84,7 @@ const InputControlled = forwardRef<HTMLInputElement, FormInputControlledProps>(
<span className="flex-grow text-sm line-clamp-1">{value}</span>
)}
<IconButton
- icon={value ? <LuSettings2 /> : <LuPlusCircle />}
+ icon={value ? <LuSettings2 /> : <LuPlus />}
aria-label={value ? "Edit" : "Add"}
size="sm"
variant="secondary"
diff --git a/packages/form/src/components/NumberControlled.tsx b/packages/form/src/components/NumberControlled.tsx
index eb575855b6..28e5da108c 100644
--- a/packages/form/src/components/NumberControlled.tsx
+++ b/packages/form/src/components/NumberControlled.tsx
@@ -21,7 +21,7 @@ import { forwardRef, useEffect, useRef, useState } from "react";
import {
LuChevronDown,
LuChevronUp,
- LuPlusCircle,
+ LuPlus,
LuSettings2,
} from "react-icons/lu";
import { useControlField, useField } from "../hooks";
@@ -83,8 +83,14 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
<span className="flex-grow line-clamp-1">{value}</span>
)}
<IconButton
- icon={value !== undefined ? <LuSettings2 /> : <LuPlusCircle />}
- aria-label={value !== undefined ? "Edit" : "Add"}
+ icon={
+ value !== undefined && !isNaN(value) ? (
+ <LuSettings2 />
+ ) : (
+ <LuPlus />
+ )
+ }
+ aria-label={value !== undefined && !isNaN(value) ? "Edit" : "Add"}
size="sm"
variant="secondary"
isDisabled={isReadOnly}
diff --git a/packages/form/src/components/Select.tsx b/packages/form/src/components/Select.tsx
index 35fdbb1f78..f5b831575b 100644
--- a/packages/form/src/components/Select.tsx
+++ b/packages/form/src/components/Select.tsx
@@ -16,7 +16,7 @@ import {
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef } from "react";
-import { LuPlusCircle, LuSettings2, LuX } from "react-icons/lu";
+import { LuPlus, LuSettings2, LuX } from "react-icons/lu";
import { useControlField, useField } from "../hooks";
export type SelectProps = Omit<SelectBaseProps, "onChange"> & {
@@ -162,7 +162,7 @@ export const SelectBase = forwardRef<HTMLButtonElement, SelectBaseProps>(
size={size ?? "sm"}
variant="secondary"
aria-label={value ? "Edit" : "Add"}
- icon={value ? <LuSettings2 /> : <LuPlusCircle />}
+ icon={value ? <LuSettings2 /> : <LuPlus />}
isDisabled={isReadOnly}
/>
) : (
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 16939b720b..a513204e37 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -1,7 +1,7 @@
import { useVirtualizer } from "@tanstack/react-virtual";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef, useMemo, useRef, useState } from "react";
-import { LuCheck, LuPlusCircle, LuSettings2, LuX } from "react-icons/lu";
+import { LuCheck, LuPlus, LuSettings2, LuX } from "react-icons/lu";
import {
Command,
CommandGroup,
@@ -76,7 +76,7 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(
size={size ?? "sm"}
variant="secondary"
aria-label={value ? "Edit" : "Add"}
- icon={value ? <LuSettings2 /> : <LuPlusCircle />}
+ icon={value ? <LuSettings2 /> : <LuPlus />}
isDisabled={isReadOnly}
ref={ref}
onClick={() => setOpen(true)}
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index 3d64839c5e..8951e5a4d5 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -1,7 +1,7 @@
import { useVirtualizer } from "@tanstack/react-virtual";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef, useMemo, useRef, useState } from "react";
-import { LuCheck, LuPlusCircle, LuSettings2, LuX } from "react-icons/lu";
+import { LuCheck, LuPlus, LuSettings2, LuX } from "react-icons/lu";
import {
Command,
CommandGroup,
@@ -83,7 +83,7 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
size={size ?? "sm"}
variant="secondary"
aria-label={value ? "Edit" : "Add"}
- icon={value ? <LuSettings2 /> : <LuPlusCircle />}
+ icon={value ? <LuSettings2 /> : <LuPlus />}
ref={ref}
isDisabled={isReadOnly}
onClick={() => setOpen(true)}