Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

feat: lost deal reason

erwanMarmelab469ff28b56aa
diff --git a/src/components/atomic-crm/deals/DealInputs.tsx b/src/components/atomic-crm/deals/DealInputs.tsx
index 82c148fb..128d9d4e 100644
--- a/src/components/atomic-crm/deals/DealInputs.tsx
+++ b/src/components/atomic-crm/deals/DealInputs.tsx
@@ -1,4 +1,5 @@
import { required, useTranslate } from "ra-core";
+import { useWatch } from "react-hook-form";
import { AutocompleteArrayInput } from "@/components/admin/autocomplete-array-input";
import { ReferenceArrayInput } from "@/components/admin/reference-array-input";
import { ReferenceInput } from "@/components/admin/reference-input";
@@ -12,6 +13,7 @@ import { useIsMobile } from "@/hooks/use-mobile";
import { contactOptionText } from "../misc/ContactOption";
import { useConfigurationContext } from "../root/ConfigurationContext";
import { AutocompleteCompanyInput } from "../companies/AutocompleteCompanyInput.tsx";
+import { LOST_DEAL_STAGE } from "./stages";
export const DealInputs = () => {
const isMobile = useIsMobile();
@@ -100,6 +102,21 @@ const DealMiscInputs = () => {
helperText={false}
validate={required()}
/>
+ <LostReasonInput />
</div>
);
};
+
+const LostReasonInput = () => {
+ const stage = useWatch({ name: "stage" });
+ if (stage !== LOST_DEAL_STAGE) return null;
+ return (
+ <TextInput
+ source="lost_reason"
+ multiline
+ rows={3}
+ helperText={false}
+ validate={required()}
+ />
+ );
+};
diff --git a/src/components/atomic-crm/deals/DealListContent.tsx b/src/components/atomic-crm/deals/DealListContent.tsx
index bbbad24a..ed0a7d84 100644
--- a/src/components/atomic-crm/deals/DealListContent.tsx
+++ b/src/components/atomic-crm/deals/DealListContent.tsx
@@ -1,4 +1,8 @@
-import { DragDropContext, type OnDragEndResponder } from "@hello-pangea/dnd";
+import {
+ DragDropContext,
+ type DropResult,
+ type OnDragEndResponder,
+} from "@hello-pangea/dnd";
import isEqual from "lodash/isEqual";
import { useDataProvider, useListContext, type DataProvider } from "ra-core";
import { useEffect, useState } from "react";
@@ -6,8 +10,9 @@ import { useEffect, useState } from "react";
import { useConfigurationContext } from "../root/ConfigurationContext";
import type { Deal } from "../types";
import { DealColumn } from "./DealColumn";
+import { LostReasonDialog } from "./LostReasonDialog";
import type { DealsByStage } from "./stages";
-import { getDealsByStage } from "./stages";
+import { getDealsByStage, LOST_DEAL_STAGE } from "./stages";
export const DealListContent = () => {
const { dealStages } = useConfigurationContext();
@@ -17,6 +22,10 @@ export const DealListContent = () => {
const [dealsByStage, setDealsByStage] = useState<DealsByStage>(
getDealsByStage([], dealStages),
);
+ // a drop into the lost column waits for a reason before being applied
+ const [pendingLostDrop, setPendingLostDrop] = useState<DropResult | null>(
+ null,
+ );
useEffect(() => {
if (unorderedDeals) {
@@ -44,6 +53,21 @@ export const DealListContent = () => {
return;
}
+ if (
+ destination.droppableId === LOST_DEAL_STAGE &&
+ source.droppableId !== LOST_DEAL_STAGE
+ ) {
+ setPendingLostDrop(result);
+ return;
+ }
+
+ moveDeal(result);
+ };
+
+ const moveDeal = (result: DropResult, lostReason?: string) => {
+ const { destination, source } = result;
+ if (!destination) return;
+
const sourceStage = source.droppableId;
const destinationStage = destination.droppableId;
const sourceDeal = dealsByStage[sourceStage][source.index]!;
@@ -65,13 +89,23 @@ export const DealListContent = () => {
);
// persist the changes
- updateDealStage(sourceDeal, destinationDeal, dataProvider).then(() => {
- refetch();
- });
+ updateDealStage(sourceDeal, destinationDeal, dataProvider, lostReason).then(
+ () => {
+ refetch();
+ },
+ );
};
return (
<DragDropContext onDragEnd={onDragEnd}>
+ <LostReasonDialog
+ open={pendingLostDrop != null}
+ onConfirm={(reason) => {
+ if (pendingLostDrop) moveDeal(pendingLostDrop, reason);
+ setPendingLostDrop(null);
+ }}
+ onCancel={() => setPendingLostDrop(null)}
+ />
<div className="flex gap-4">
{dealStages.map((stage) => (
<DealColumn
@@ -128,6 +162,7 @@ const updateDealStage = async (
index?: number; // undefined if dropped after the last item
},
dataProvider: DataProvider,
+ lostReason?: string,
) => {
if (source.stage === destination.stage) {
// moving deal inside the same column
@@ -237,6 +272,7 @@ const updateDealStage = async (
data: {
index: destinationIndex,
stage: destination.stage,
+ ...(lostReason ? { lost_reason: lostReason } : {}),
},
previousData: source,
}),
diff --git a/src/components/atomic-crm/deals/DealShow.tsx b/src/components/atomic-crm/deals/DealShow.tsx
index 8e422c38..c9b7d6a1 100644
--- a/src/components/atomic-crm/deals/DealShow.tsx
+++ b/src/components/atomic-crm/deals/DealShow.tsx
@@ -28,6 +28,7 @@ import { useConfigurationContext } from "../root/ConfigurationContext";
import type { Deal } from "../types";
import { ContactList } from "./ContactList";
import { findDealLabel, formatISODateString } from "./dealUtils";
+import { LOST_DEAL_STAGE } from "./stages";
export const DealShow = ({ open, id }: { open: boolean; id?: string }) => {
const redirect = useRedirect();
@@ -157,6 +158,15 @@ const DealShowContent = () => {
</div>
)}
+ {record.stage === LOST_DEAL_STAGE && record.lost_reason && (
+ <div className="m-4 whitespace-pre-line">
+ <span className="text-xs text-muted-foreground tracking-wide">
+ {translate("resources.deals.fields.lost_reason")}
+ </span>
+ <p className="text-sm leading-6">{record.lost_reason}</p>
+ </div>
+ )}
+
{record.description && (
<div className="m-4 whitespace-pre-line">
<span className="text-xs text-muted-foreground tracking-wide">
diff --git a/src/components/atomic-crm/deals/LostReasonDialog.test.tsx b/src/components/atomic-crm/deals/LostReasonDialog.test.tsx
new file mode 100644
index 00000000..10e4d095
--- /dev/null
+++ b/src/components/atomic-crm/deals/LostReasonDialog.test.tsx
@@ -0,0 +1,55 @@
+import { I18nContextProvider } from "ra-core";
+import { render } from "vitest-browser-react";
+import { page, userEvent } from "vitest/browser";
+
+import { i18nProvider } from "../providers/commons/i18nProvider";
+import { LostReasonDialog } from "./LostReasonDialog";
+
+// the dialog renders in a portal, so query the whole page
+const renderDialog = async () => {
+ const onConfirm = vi.fn();
+ const onCancel = vi.fn();
+ await i18nProvider.changeLocale("en");
+ await render(
+ <I18nContextProvider value={i18nProvider}>
+ <LostReasonDialog open onConfirm={onConfirm} onCancel={onCancel} />
+ </I18nContextProvider>,
+ );
+ return { onConfirm, onCancel };
+};
+
+describe("LostReasonDialog", () => {
+ it("blocks marking the deal as lost until a reason is given", async () => {
+ const { onConfirm } = await renderDialog();
+ const confirm = page.getByRole("button", { name: "Mark as lost" });
+
+ await expect.element(confirm).toBeDisabled();
+ await userEvent.type(
+ page.getByRole("textbox", { name: "Why was this deal lost?" }),
+ " ",
+ );
+ await expect.element(confirm).toBeDisabled();
+ expect(onConfirm).not.toHaveBeenCalled();
+ });
+
+ it("submits the trimmed reason", async () => {
+ const { onConfirm } = await renderDialog();
+
+ await userEvent.type(
+ page.getByRole("textbox", { name: "Why was this deal lost?" }),
+ " Budget cut ",
+ );
+ await page.getByRole("button", { name: "Mark as lost" }).click();
+
+ expect(onConfirm).toHaveBeenCalledWith("Budget cut");
+ });
+
+ it("cancels without a reason", async () => {
+ const { onConfirm, onCancel } = await renderDialog();
+
+ await page.getByRole("button", { name: "Cancel" }).click();
+
+ expect(onCancel).toHaveBeenCalled();
+ expect(onConfirm).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/components/atomic-crm/deals/LostReasonDialog.tsx b/src/components/atomic-crm/deals/LostReasonDialog.tsx
new file mode 100644
index 00000000..73926d29
--- /dev/null
+++ b/src/components/atomic-crm/deals/LostReasonDialog.tsx
@@ -0,0 +1,71 @@
+import { useTranslate } from "ra-core";
+import { useState, type FormEvent } from "react";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Textarea } from "@/components/ui/textarea";
+
+export const LostReasonDialog = ({
+ open,
+ onConfirm,
+ onCancel,
+}: {
+ open: boolean;
+ onConfirm: (reason: string) => void;
+ onCancel: () => void;
+}) => {
+ const translate = useTranslate();
+ const [reason, setReason] = useState("");
+ const trimmedReason = reason.trim();
+
+ const handleSubmit = (event: FormEvent) => {
+ event.preventDefault();
+ if (!trimmedReason) return;
+ onConfirm(trimmedReason);
+ setReason("");
+ };
+
+ const handleCancel = () => {
+ setReason("");
+ onCancel();
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(isOpen) => !isOpen && handleCancel()}>
+ <DialogContent>
+ <form onSubmit={handleSubmit} className="flex flex-col gap-4">
+ <DialogHeader>
+ <DialogTitle>
+ {translate("resources.deals.lost_reason_dialog.title")}
+ </DialogTitle>
+ <DialogDescription>
+ {translate("resources.deals.lost_reason_dialog.description")}
+ </DialogDescription>
+ </DialogHeader>
+ <Textarea
+ aria-label={translate("resources.deals.fields.lost_reason")}
+ value={reason}
+ onChange={(event) => setReason(event.target.value)}
+ rows={4}
+ required
+ autoFocus
+ />
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={handleCancel}>
+ {translate("ra.action.cancel")}
+ </Button>
+ <Button type="submit" disabled={!trimmedReason}>
+ {translate("resources.deals.lost_reason_dialog.confirm")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/src/components/atomic-crm/deals/stages.ts b/src/components/atomic-crm/deals/stages.ts
index 944353e6..72bed71b 100644
--- a/src/components/atomic-crm/deals/stages.ts
+++ b/src/components/atomic-crm/deals/stages.ts
@@ -1,6 +1,8 @@
import type { ConfigurationContextValue } from "../root/ConfigurationContext";
import type { Deal } from "../types";
+export const LOST_DEAL_STAGE = "lost";
+
export type DealsByStage = Record<Deal["stage"], Deal[]>;
export const getDealsByStage = (
diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index 15a8eabe..e5cbcbb6 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -186,6 +186,13 @@ export const englishCrmMessages = {
amount: "Budget",
expected_closing_date: "Expected closing date",
stage: "Stage",
+ lost_reason: "Why was this deal lost?",
+ },
+ lost_reason_dialog: {
+ title: "Why was this deal lost?",
+ description:
+ "Give a reason so managers can understand what went wrong.",
+ confirm: "Mark as lost",
},
action: {
back_to_deal: "Back to deal",
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index 20448cc8..fac003ca 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -190,6 +190,13 @@ export const frenchCrmMessages = {
amount: "Budget",
expected_closing_date: "Date de clôture prévue",
stage: "Étape",
+ lost_reason: "Pourquoi cette affaire a-t-elle été perdue ?",
+ },
+ lost_reason_dialog: {
+ title: "Pourquoi cette affaire a-t-elle été perdue ?",
+ description:
+ "Indiquez une raison pour que les managers comprennent ce qui n'a pas fonctionné.",
+ confirm: "Marquer comme perdue",
},
action: {
back_to_deal: "Retour à l'affaire",
diff --git a/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.ts b/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.ts
index 440592c6..2a2dd722 100644
--- a/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.ts
@@ -27,13 +27,15 @@ export const generateDeals = (db: Db): Deal[] => {
.toISOString()
.split("T")[0];
+ const stage = random.arrayElement(defaultDealStages).value;
return {
id,
name: lowercaseName[0].toUpperCase() + lowercaseName.slice(1),
company_id: company.id,
contact_ids: contacts.map((contact) => contact.id),
category: random.arrayElement(defaultDealCategories).value,
- stage: random.arrayElement(defaultDealStages).value,
+ stage,
+ lost_reason: stage === "lost" ? lorem.sentence() : null,
description: lorem.paragraphs(datatype.number({ min: 1, max: 4 })),
amount: datatype.number(1000) * 100,
created_at,
diff --git a/src/components/atomic-crm/types.ts b/src/components/atomic-crm/types.ts
index 8c8c70d5..f026a087 100644
--- a/src/components/atomic-crm/types.ts
+++ b/src/components/atomic-crm/types.ts
@@ -128,6 +128,7 @@ export type Deal = {
expected_closing_date: string;
sales_id: Identifier;
index: number;
+ lost_reason?: string | null;
} & Pick<RaRecord, "id">;
export type DealNote = {
diff --git a/supabase/migrations/20260924120000_deals_lost_reason.sql b/supabase/migrations/20260924120000_deals_lost_reason.sql
new file mode 100644
index 00000000..f8698505
--- /dev/null
+++ b/supabase/migrations/20260924120000_deals_lost_reason.sql
@@ -0,0 +1 @@
+alter table "public"."deals" add column "lost_reason" text;
diff --git a/supabase/schemas/01_tables.sql b/supabase/schemas/01_tables.sql
index bdb383c4..8237f607 100644
--- a/supabase/schemas/01_tables.sql
+++ b/supabase/schemas/01_tables.sql
@@ -76,7 +76,8 @@ create table public.deals (
archived_at timestamp with time zone,
expected_closing_date date,
sales_id bigint,
- index smallint
+ index smallint,
+ lost_reason text
);
create table public.deal_notes (