@contractspec/example.crm-pipeline 3.7.24 → 3.7.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{jsx as d,jsxs as ZJ}from"react/jsx-runtime";function AJ(J,K){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function $J({deal:J,onClick:K}){let W=J.expectedCloseDate?Math.ceil((J.expectedCloseDate.getTime()-Date.now())/86400000):null;return ZJ("div",{onClick:K,className:"cursor-pointer rounded-lg border border-border bg-card p-3 shadow-sm transition-shadow hover:shadow-md",role:"button",tabIndex:0,onKeyDown:(_)=>{if(_.key==="Enter"||_.key===" ")K?.()},children:[d("h4",{className:"font-medium leading-snug",children:J.name}),d("div",{className:"mt-2 font-semibold text-lg text-primary",children:AJ(J.value,J.currency)}),ZJ("div",{className:"mt-3 flex items-center justify-between text-muted-foreground text-xs",children:[W!==null&&d("span",{className:W<0?"text-red-500":W<=7?"text-yellow-600 dark:text-yellow-500":"",children:W<0?`${Math.abs(W)}d overdue`:W===0?"Due today":`${W}d left`}),d("span",{className:`rounded px-1.5 py-0.5 font-medium text-xs ${J.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":J.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:J.status})]})]})}import{useState as NJ}from"react";import{jsx as D,jsxs as C}from"react/jsx-runtime";function UJ(J){if(J>=1e6)return`$${(J/1e6).toFixed(1)}M`;if(J>=1000)return`$${(J/1000).toFixed(0)}K`;return`$${J}`}function GJ({dealsByStage:J,stages:K,onDealClick:W,onDealMove:_}){let[Q,O]=NJ(null),f=[...K].sort((N,z)=>N.position-z.position),A=(N,z)=>{_?.(N,z),O(null)};return D("div",{className:"flex gap-4 overflow-x-auto pb-4",children:f.map((N)=>{let z=J[N.id]??[],R=z.reduce((Z,F)=>Z+F.value,0);return C("div",{className:"flex w-72 flex-shrink-0 flex-col rounded-lg bg-muted/30",children:[C("div",{className:"flex items-center justify-between border-border border-b px-3 py-2",children:[C("div",{children:[D("h3",{className:"font-medium",children:N.name}),C("p",{className:"text-muted-foreground text-xs",children:[z.length," deals · ",UJ(R)]})]}),D("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",children:z.length})]}),D("div",{className:"flex flex-1 flex-col gap-2 p-2",children:z.length===0?D("div",{className:"flex h-24 items-center justify-center rounded-md border-2 border-muted-foreground/20 border-dashed text-muted-foreground text-xs",children:"No deals"}):z.map((Z)=>C("div",{className:"group relative",children:[D($J,{deal:Z,onClick:()=>W?.(Z.id)}),Z.status==="OPEN"&&_&&C("div",{className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100",children:[D("button",{type:"button",onClick:(F)=>{F.stopPropagation(),O(Q===Z.id?null:Z.id)},className:"flex h-6 w-6 items-center justify-center rounded border border-border bg-background text-xs shadow-sm hover:bg-muted",title:"Quick move",children:"➡️"}),Q===Z.id&&C("div",{className:"absolute top-7 right-0 z-20 min-w-[140px] rounded-lg border border-border bg-card py-1 shadow-lg",children:[D("p",{className:"px-3 py-1 font-medium text-muted-foreground text-xs",children:"Move to:"}),f.filter((F)=>F.id!==Z.stageId).map((F)=>D("button",{type:"button",onClick:(U)=>{U.stopPropagation(),A(Z.id,F.id)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-muted",children:F.name},F.id))]})]})]},Z.id))})]},N.id)})})}import{useTemplateRuntime as WJ}from"@contractspec/lib.example-shared-ui";import{useCallback as wJ,useEffect as PJ,useMemo as VJ,useState as S}from"react";function i(J={}){let{handlers:K,projectId:W}=WJ(),{crm:_}=K,[Q,O]=S(null),[f,A]=S({}),[N,z]=S([]),[R,Z]=S(!0),[F,U]=S(null),[Y,B]=S(0),q=J.pipelineId??"pipeline-1",$=J.pageIndex??Y,X=J.pageSize??J.limit??50,[E]=J.sorting??[],y=E?.id==="deal"?"name":E?.id,v=E?E.desc?"desc":"asc":void 0,c=wJ(async()=>{Z(!0),U(null);try{let[M,H,t]=await Promise.all([_.listDeals({projectId:W,pipelineId:q,stageId:J.stageId,status:J.status==="all"?void 0:J.status,search:J.search,limit:X,offset:$*X,sortBy:y==="name"||y==="value"||y==="status"||y==="expectedCloseDate"||y==="updatedAt"?y:void 0,sortDirection:v}),_.getDealsByStage({projectId:W,pipelineId:q}),_.getPipelineStages({pipelineId:q})]);O(M),A(H),z(t)}catch(M){U(M instanceof Error?M:Error("Unknown error"))}finally{Z(!1)}},[_,W,q,J.stageId,J.status,J.search,$,X,y,v]);PJ(()=>{c()},[c]);let a=VJ(()=>{if(!Q)return null;let M=Q.deals.filter((h)=>h.status==="OPEN"),H=Q.deals.filter((h)=>h.status==="WON"),t=Q.deals.filter((h)=>h.status==="LOST");return{total:Q.total,totalValue:Q.totalValue,openCount:M.length,openValue:M.reduce((h,s)=>h+s.value,0),wonCount:H.length,wonValue:H.reduce((h,s)=>h+s.value,0),lostCount:t.length}},[Q]);return{data:Q,dealsByStage:f,stages:N,loading:R,error:F,stats:a,page:$+1,pageIndex:$,pageSize:X,refetch:c,nextPage:J.pageIndex===void 0?()=>B((M)=>M+1):void 0,prevPage:J.pageIndex===void 0?()=>$>0&&B((M)=>M-1):void 0}}import{useTemplateRuntime as OJ}from"@contractspec/lib.example-shared-ui";import{useCallback as l,useState as r}from"react";function _J(J={}){let{handlers:K,projectId:W}=OJ(),{crm:_}=K,[Q,O]=r({loading:!1,error:null,data:null}),[f,A]=r({loading:!1,error:null,data:null}),[N,z]=r({loading:!1,error:null,data:null}),[R,Z]=r({loading:!1,error:null,data:null}),F=l(async(q)=>{O({loading:!0,error:null,data:null});try{let $=await _.createDeal(q,{projectId:W,ownerId:"user-1"});return O({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to create deal");return O({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,W,J]),U=l(async(q)=>{A({loading:!0,error:null,data:null});try{let $=await _.moveDeal(q);return A({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to move deal");return A({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,J]),Y=l(async(q)=>{z({loading:!0,error:null,data:null});try{let $=await _.winDeal(q);return z({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to mark deal as won");return z({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,J]),B=l(async(q)=>{Z({loading:!0,error:null,data:null});try{let $=await _.loseDeal(q);return Z({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to mark deal as lost");return Z({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,J]);return{createDeal:F,moveDeal:U,winDeal:Y,loseDeal:B,createState:Q,moveState:f,winState:N,loseState:R,isLoading:Q.loading||f.loading||N.loading||R.loading}}import{Button as qJ,Input as e}from"@contractspec/lib.design-system";import{useState as p}from"react";import{jsx as T,jsxs as I}from"react/jsx-runtime";var RJ=["USD","EUR","GBP","CAD"],fJ="pipeline-1";function QJ({isOpen:J,onClose:K,onSubmit:W,stages:_,isLoading:Q=!1}){let[O,f]=p(""),[A,N]=p(""),[z,R]=p("USD"),[Z,F]=p(_[0]?.id??""),[U,Y]=p(""),[B,q]=p(null),$=async(X)=>{if(X.preventDefault(),q(null),!O.trim()){q("Deal name is required");return}let E=parseFloat(A);if(isNaN(E)||E<=0){q("Value must be a positive number");return}if(!Z){q("Please select a pipeline stage");return}try{await W({name:O.trim(),value:E,currency:z,pipelineId:fJ,stageId:Z,expectedCloseDate:U?new Date(U):void 0}),f(""),N(""),R("USD"),F(_[0]?.id??""),Y(""),K()}catch(y){q(y instanceof Error?y.message:"Failed to create deal")}};if(!J)return null;return I("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[T("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:K,role:"button",tabIndex:0,onKeyDown:(X)=>{if(X.key==="Enter"||X.key===" ")K()},"aria-label":"Close modal"}),I("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[T("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Deal"}),I("form",{onSubmit:$,className:"space-y-4",children:[I("div",{children:[T("label",{htmlFor:"deal-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Deal Name *"}),T(e,{id:"deal-name",value:O,onChange:(X)=>f(X.target.value),placeholder:"e.g., Enterprise License - Acme Corp",disabled:Q})]}),I("div",{className:"flex gap-3",children:[I("div",{className:"flex-1",children:[T("label",{htmlFor:"deal-value",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Value *"}),T(e,{id:"deal-value",type:"number",min:"0",step:"0.01",value:A,onChange:(X)=>N(X.target.value),placeholder:"50000",disabled:Q})]}),I("div",{className:"w-24",children:[T("label",{htmlFor:"deal-currency",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Currency"}),T("select",{id:"deal-currency",value:z,onChange:(X)=>R(X.target.value),disabled:Q,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:RJ.map((X)=>T("option",{value:X,children:X},X))})]})]}),I("div",{children:[T("label",{htmlFor:"deal-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Pipeline Stage *"}),T("select",{id:"deal-stage",value:Z,onChange:(X)=>F(X.target.value),disabled:Q,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:_.map((X)=>T("option",{value:X.id,children:X.name},X.id))})]}),I("div",{children:[T("label",{htmlFor:"deal-close-date",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Expected Close Date"}),T(e,{id:"deal-close-date",type:"date",value:U,onChange:(X)=>Y(X.target.value),disabled:Q})]}),B&&T("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:B}),I("div",{className:"flex justify-end gap-3 pt-2",children:[T(qJ,{type:"button",variant:"ghost",onPress:K,disabled:Q,children:"Cancel"}),T(qJ,{type:"submit",disabled:Q,children:Q?"Creating...":"Create Deal"})]})]})]})]})}import{Button as L}from"@contractspec/lib.design-system";import{useState as g}from"react";import{jsx as G,jsxs as P,Fragment as TJ}from"react/jsx-runtime";function EJ(J,K){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function zJ({isOpen:J,deal:K,stages:W,onClose:_,onWin:Q,onLose:O,onMove:f,isLoading:A=!1}){let[N,z]=g("menu"),[R,Z]=g(""),[F,U]=g(""),[Y,B]=g(""),[q,$]=g(""),[X,E]=g(null),y=()=>{z("menu"),Z(""),U(""),B(""),$(""),E(null)},v=()=>{y(),_()},c=async()=>{if(!K)return;E(null);try{await Q({dealId:K.id,wonSource:R.trim()||void 0,notes:Y.trim()||void 0}),v()}catch(H){E(H instanceof Error?H.message:"Failed to mark deal as won")}},a=async()=>{if(!K)return;if(E(null),!F.trim()){E("Please provide a reason for losing the deal");return}try{await O({dealId:K.id,lostReason:F.trim(),notes:Y.trim()||void 0}),v()}catch(H){E(H instanceof Error?H.message:"Failed to mark deal as lost")}},M=async()=>{if(!K)return;if(E(null),!q){E("Please select a stage");return}if(q===K.stageId){E("Deal is already in this stage");return}try{await f({dealId:K.id,stageId:q}),v()}catch(H){E(H instanceof Error?H.message:"Failed to move deal")}};if(!J||!K)return null;return P("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[G("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:v,role:"button",tabIndex:0,onKeyDown:(H)=>{if(H.key==="Enter"||H.key===" ")v()},"aria-label":"Close modal"}),P("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[P("div",{className:"mb-4 border-border border-b pb-4",children:[G("h2",{className:"font-semibold text-xl",children:K.name}),G("p",{className:"font-medium text-lg text-primary",children:EJ(K.value,K.currency)}),G("span",{className:`mt-2 inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${K.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":K.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:K.status})]}),N==="menu"&&P("div",{className:"space-y-3",children:[K.status==="OPEN"&&P(TJ,{children:[P(L,{className:"w-full justify-start",variant:"ghost",onPress:()=>z("win"),children:[G("span",{className:"mr-2",children:"\uD83C\uDFC6"})," Mark as Won"]}),P(L,{className:"w-full justify-start",variant:"ghost",onPress:()=>z("lose"),children:[G("span",{className:"mr-2",children:"❌"})," Mark as Lost"]}),P(L,{className:"w-full justify-start",variant:"ghost",onPress:()=>{$(K.stageId),z("move")},children:[G("span",{className:"mr-2",children:"➡️"})," Move to Stage"]})]}),K.status!=="OPEN"&&P("p",{className:"py-4 text-center text-muted-foreground",children:["This deal is already ",K.status.toLowerCase(),". No actions available."]}),G("div",{className:"border-border border-t pt-3",children:G(L,{className:"w-full",variant:"outline",onPress:v,children:"Close"})})]}),N==="win"&&P("div",{className:"space-y-4",children:[P("div",{children:[G("label",{htmlFor:"won-source",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"How did you win this deal?"}),P("select",{id:"won-source",value:R,onChange:(H)=>Z(H.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[G("option",{value:"",children:"Select a source..."}),G("option",{value:"referral",children:"Referral"}),G("option",{value:"cold_outreach",children:"Cold Outreach"}),G("option",{value:"inbound",children:"Inbound Lead"}),G("option",{value:"upsell",children:"Upsell"}),G("option",{value:"other",children:"Other"})]})]}),P("div",{children:[G("label",{htmlFor:"win-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),G("textarea",{id:"win-notes",value:Y,onChange:(H)=>B(H.target.value),placeholder:"Any additional notes about the win...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),X&&G("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),P("div",{className:"flex justify-end gap-3 pt-2",children:[G(L,{variant:"ghost",onPress:()=>z("menu"),disabled:A,children:"Back"}),G(L,{onPress:c,disabled:A,children:A?"Processing...":"\uD83C\uDFC6 Confirm Win"})]})]}),N==="lose"&&P("div",{className:"space-y-4",children:[P("div",{children:[G("label",{htmlFor:"lost-reason",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Why was this deal lost? *"}),P("select",{id:"lost-reason",value:F,onChange:(H)=>U(H.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[G("option",{value:"",children:"Select a reason..."}),G("option",{value:"price",children:"Price too high"}),G("option",{value:"competitor",children:"Lost to competitor"}),G("option",{value:"no_budget",children:"No budget"}),G("option",{value:"no_decision",children:"No decision made"}),G("option",{value:"timing",children:"Bad timing"}),G("option",{value:"product_fit",children:"Product not a fit"}),G("option",{value:"other",children:"Other"})]})]}),P("div",{children:[G("label",{htmlFor:"lose-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),G("textarea",{id:"lose-notes",value:Y,onChange:(H)=>B(H.target.value),placeholder:"Any additional details...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),X&&G("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),P("div",{className:"flex justify-end gap-3 pt-2",children:[G(L,{variant:"ghost",onPress:()=>z("menu"),disabled:A,children:"Back"}),G(L,{variant:"destructive",onPress:a,disabled:A,children:A?"Processing...":"❌ Confirm Loss"})]})]}),N==="move"&&P("div",{className:"space-y-4",children:[P("div",{children:[G("label",{htmlFor:"move-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Move to Stage"}),G("select",{id:"move-stage",value:q,onChange:(H)=>$(H.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:W.map((H)=>P("option",{value:H.id,children:[H.name,H.id===K.stageId?" (current)":""]},H.id))})]}),X&&G("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),P("div",{className:"flex justify-end gap-3 pt-2",children:[G(L,{variant:"ghost",onPress:()=>z("menu"),disabled:A,children:"Back"}),G(L,{onPress:M,disabled:A,children:A?"Moving...":"➡️ Move Deal"})]})]})]})]})}import{Button as j,DataTable as bJ,DataTableToolbar as BJ,LoaderBlock as MJ}from"@contractspec/lib.design-system";import{useContractTable as kJ}from"@contractspec/lib.presentation-runtime-react";import{Badge as yJ}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as x,VStack as JJ}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as k}from"@contractspec/lib.ui-kit-web/ui/text";import*as u from"react";import{jsx as V,jsxs as m}from"react/jsx-runtime";function IJ(J,K="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function LJ(J){switch(J){case"WON":return"default";case"LOST":return"destructive";case"STALE":return"outline";default:return"secondary"}}function vJ({value:J,onChange:K}){return m(x,{gap:"sm",className:"flex-wrap",children:[V(j,{variant:J==="all"?"secondary":"outline",size:"sm",onPress:()=>K("all"),children:"All Deals"}),V(j,{variant:J==="OPEN"?"secondary":"outline",size:"sm",onPress:()=>K("OPEN"),children:"Open Only"}),V(j,{variant:J==="WON"?"secondary":"outline",size:"sm",onPress:()=>K("WON"),children:"Won Only"}),V(j,{variant:J==="LOST"?"secondary":"outline",size:"sm",onPress:()=>K("LOST"),children:"Lost Only"})]})}function hJ({deals:J,totalItems:K,pageIndex:W,pageSize:_,sorting:Q,search:O,status:f,loading:A,onSortingChange:N,onPaginationChange:z,onSearchChange:R,onStatusChange:Z,onDealClick:F}){let U=kJ({data:J,columns:[{id:"deal",header:"Deal",label:"Deal",accessor:(Y)=>Y.name,cell:({item:Y})=>m(JJ,{gap:"xs",children:[V(k,{className:"font-medium text-sm",children:Y.name}),V(k,{className:"text-muted-foreground text-xs",children:Y.companyId??"Unassigned company"})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"value",header:"Value",label:"Value",accessorKey:"value",cell:({item:Y})=>IJ(Y.value,Y.currency),align:"right",size:140,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:Y})=>V(yJ,{variant:LJ(Y),children:String(Y)}),size:130,canSort:!0,canHide:!0,canPin:!0,canResize:!0},{id:"expectedCloseDate",header:"Expected Close",label:"Expected Close",accessor:(Y)=>Y.expectedCloseDate?.toISOString()??"",cell:({item:Y})=>Y.expectedCloseDate?.toLocaleDateString()??"Not scheduled",size:170,canSort:!0,canHide:!0,canResize:!0},{id:"updatedAt",header:"Updated",label:"Updated",accessor:(Y)=>Y.updatedAt.toISOString(),cell:({item:Y})=>Y.updatedAt.toLocaleDateString(),size:140,canSort:!0,canHide:!0,canResize:!0},{id:"actions",header:"Actions",label:"Actions",accessor:(Y)=>Y.id,cell:({item:Y})=>V(j,{variant:"ghost",size:"sm",onPress:()=>F?.(Y.id),children:"Actions"}),size:120,canSort:!1,canHide:!1,canPin:!1,canResize:!1}],executionMode:"server",selectionMode:"multiple",totalItems:K,state:{sorting:Q,pagination:{pageIndex:W,pageSize:_}},onSortingChange:N,onPaginationChange:z,initialState:{columnVisibility:{updatedAt:!1},columnPinning:{left:["deal","status"],right:[]}},renderExpandedContent:(Y)=>m(JJ,{gap:"sm",className:"py-2",children:[m(x,{justify:"between",children:[V(k,{className:"font-medium text-sm",children:"Owner"}),V(k,{className:"text-muted-foreground text-sm",children:Y.ownerId})]}),m(x,{justify:"between",children:[V(k,{className:"font-medium text-sm",children:"Contact"}),V(k,{className:"text-muted-foreground text-sm",children:Y.contactId??"No linked contact"})]}),Y.wonSource?m(x,{justify:"between",children:[V(k,{className:"font-medium text-sm",children:"Won Source"}),V(k,{className:"text-muted-foreground text-sm",children:Y.wonSource})]}):null,Y.lostReason?m(x,{justify:"between",children:[V(k,{className:"font-medium text-sm",children:"Lost Reason"}),V(k,{className:"text-muted-foreground text-sm",children:Y.lostReason})]}):null,Y.notes?m(JJ,{gap:"xs",children:[V(k,{className:"font-medium text-sm",children:"Notes"}),V(k,{className:"text-muted-foreground text-sm",children:Y.notes})]}):null]}),getCanExpand:()=>!0});return V(bJ,{controller:U,title:"All Deals",description:"Server-mode table using the shared ContractSpec controller.",loading:A,toolbar:V(BJ,{controller:U,searchPlaceholder:"Search deals, companies, contacts, or notes",searchValue:O,onSearchChange:R,activeChips:f==="all"?[]:[{key:"status",label:`Status: ${f}`,onRemove:()=>Z("all")}],onClearAll:()=>{R(""),Z("all")},actionsStart:vJ({value:f,onChange:Z}),actionsEnd:m(k,{className:"text-muted-foreground text-sm",children:[K," total deals"]})}),footer:`Page ${U.pageIndex+1} of ${U.pageCount}`,emptyState:V("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No deals found"})})}function FJ({onDealClick:J}){let[K,W]=u.useState([{id:"value",desc:!0}]),[_,Q]=u.useState({pageIndex:0,pageSize:3}),[O,f]=u.useState(""),[A,N]=u.useState("all"),{data:z,loading:R}=i({pageIndex:_.pageIndex,pageSize:_.pageSize,search:O,status:A,sorting:K});if(R&&!z)return V(MJ,{label:"Loading deals..."});return V(hJ,{deals:z?.deals??[],totalItems:z?.total??0,pageIndex:_.pageIndex,pageSize:_.pageSize,sorting:K,search:O,status:A,loading:R,onSortingChange:(Z)=>{W(Z),Q((F)=>({...F,pageIndex:0}))},onPaginationChange:Q,onSearchChange:(Z)=>{f(Z),Q((F)=>({...F,pageIndex:0}))},onStatusChange:(Z)=>{N(Z),Q((F)=>({...F,pageIndex:0}))},onDealClick:J})}import{Button as DJ,ErrorState as mJ,LoaderBlock as CJ,StatCard as n,StatCardGroup as SJ}from"@contractspec/lib.design-system";import{Tabs as pJ,TabsContent as KJ,TabsList as gJ,TabsTrigger as XJ}from"@contractspec/lib.ui-kit-web/ui/tabs";import{useCallback as HJ,useState as YJ}from"react";import{jsx as w,jsxs as b}from"react/jsx-runtime";function o(J,K="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function TK(){let[J,K]=YJ(!1),[W,_]=YJ(null),[Q,O]=YJ(!1),{data:f,dealsByStage:A,stages:N,loading:z,error:R,stats:Z,refetch:F}=i(),U=_J({onSuccess:()=>{F()}}),Y=HJ((q)=>{let $=A?Object.values(A).flat().find((X)=>X.id===q):null;if($)_($),O(!0)},[A]),B=HJ(async(q,$)=>{await U.moveDeal({dealId:q,stageId:$})},[U]);if(z&&!f)return w(CJ,{label:"Loading CRM..."});if(R)return w(mJ,{title:"Failed to load CRM",description:R.message,onRetry:F,retryLabel:"Retry"});return b("div",{className:"space-y-6",children:[b("div",{className:"flex items-center justify-between",children:[w("h2",{className:"font-bold text-2xl",children:"CRM Pipeline"}),b(DJ,{onClick:()=>K(!0),children:[w("span",{className:"mr-2",children:"+"})," Create Deal"]})]}),Z&&b(SJ,{children:[w(n,{label:"Total Pipeline",value:o(Z.totalValue),hint:`${Z.total} deals`}),w(n,{label:"Open Deals",value:o(Z.openValue),hint:`${Z.openCount} active`}),w(n,{label:"Won",value:o(Z.wonValue),hint:`${Z.wonCount} closed`}),w(n,{label:"Lost",value:Z.lostCount,hint:"deals lost"})]}),b(pJ,{defaultValue:"pipeline",className:"w-full",children:[b(gJ,{children:[b(XJ,{value:"pipeline",children:[w("span",{className:"mr-2",children:"\uD83D\uDCCA"}),"Pipeline"]}),b(XJ,{value:"list",children:[w("span",{className:"mr-2",children:"\uD83D\uDCCB"}),"All Deals"]}),b(XJ,{value:"metrics",children:[w("span",{className:"mr-2",children:"\uD83D\uDCC8"}),"Metrics"]})]}),w(KJ,{value:"pipeline",className:"min-h-[400px]",children:w(GJ,{dealsByStage:A,stages:N,onDealClick:Y,onDealMove:B})}),w(KJ,{value:"list",className:"min-h-[400px]",children:w(FJ,{onDealClick:Y})}),w(KJ,{value:"metrics",className:"min-h-[400px]",children:w(cJ,{stats:Z})})]}),w(QJ,{isOpen:J,onClose:()=>K(!1),onSubmit:async(q)=>{await U.createDeal(q)},stages:N,isLoading:U.createState.loading}),w(zJ,{isOpen:Q,deal:W,stages:N,onClose:()=>{O(!1),_(null)},onWin:async(q)=>{await U.winDeal(q)},onLose:async(q)=>{await U.loseDeal(q)},onMove:async(q)=>{await U.moveDeal(q),F()},isLoading:U.isLoading})]})}function cJ({stats:J}){if(!J)return null;return w("div",{className:"space-y-6",children:b("div",{className:"rounded-xl border border-border bg-card p-6",children:[w("h3",{className:"mb-4 font-semibold text-lg",children:"Pipeline Overview"}),b("dl",{className:"grid gap-4 sm:grid-cols-3",children:[b("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Win Rate"}),b("dd",{className:"font-semibold text-2xl",children:[J.total>0?(J.wonCount/J.total*100).toFixed(0):0,"%"]})]}),b("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Avg Deal Size"}),w("dd",{className:"font-semibold text-2xl",children:o(J.total>0?J.totalValue/J.total:0)})]}),b("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Conversion"}),b("dd",{className:"font-semibold text-2xl",children:[J.wonCount," / ",J.total]})]})]})]})})}export{TK as CrmDashboard};
1
+ import{jsx as d,jsxs as ZJ}from"react/jsx-runtime";function AJ(J,K){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function $J({deal:J,onClick:K}){let W=J.expectedCloseDate?Math.ceil((J.expectedCloseDate.getTime()-Date.now())/86400000):null;return ZJ("div",{onClick:K,className:"cursor-pointer rounded-lg border border-border bg-card p-3 shadow-sm transition-shadow hover:shadow-md",role:"button",tabIndex:0,onKeyDown:(_)=>{if(_.key==="Enter"||_.key===" ")K?.()},children:[d("h4",{className:"font-medium leading-snug",children:J.name}),d("div",{className:"mt-2 font-semibold text-lg text-primary",children:AJ(J.value,J.currency)}),ZJ("div",{className:"mt-3 flex items-center justify-between text-muted-foreground text-xs",children:[W!==null&&d("span",{className:W<0?"text-red-500":W<=7?"text-yellow-600 dark:text-yellow-500":"",children:W<0?`${Math.abs(W)}d overdue`:W===0?"Due today":`${W}d left`}),d("span",{className:`rounded px-1.5 py-0.5 font-medium text-xs ${J.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":J.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:J.status})]})]})}import{useState as NJ}from"react";import{jsx as D,jsxs as C}from"react/jsx-runtime";function UJ(J){if(J>=1e6)return`$${(J/1e6).toFixed(1)}M`;if(J>=1000)return`$${(J/1000).toFixed(0)}K`;return`$${J}`}function GJ({dealsByStage:J,stages:K,onDealClick:W,onDealMove:_}){let[Q,O]=NJ(null),f=[...K].sort((N,z)=>N.position-z.position),A=(N,z)=>{_?.(N,z),O(null)};return D("div",{className:"flex gap-4 overflow-x-auto pb-4",children:f.map((N)=>{let z=J[N.id]??[],R=z.reduce((Z,F)=>Z+F.value,0);return C("div",{className:"flex w-72 flex-shrink-0 flex-col rounded-lg bg-muted/30",children:[C("div",{className:"flex items-center justify-between border-border border-b px-3 py-2",children:[C("div",{children:[D("h3",{className:"font-medium",children:N.name}),C("p",{className:"text-muted-foreground text-xs",children:[z.length," deals · ",UJ(R)]})]}),D("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",children:z.length})]}),D("div",{className:"flex flex-1 flex-col gap-2 p-2",children:z.length===0?D("div",{className:"flex h-24 items-center justify-center rounded-md border-2 border-muted-foreground/20 border-dashed text-muted-foreground text-xs",children:"No deals"}):z.map((Z)=>C("div",{className:"group relative",children:[D($J,{deal:Z,onClick:()=>W?.(Z.id)}),Z.status==="OPEN"&&_&&C("div",{className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100",children:[D("button",{type:"button",onClick:(F)=>{F.stopPropagation(),O(Q===Z.id?null:Z.id)},className:"flex h-6 w-6 items-center justify-center rounded border border-border bg-background text-xs shadow-sm hover:bg-muted",title:"Quick move",children:"➡️"}),Q===Z.id&&C("div",{className:"absolute top-7 right-0 z-20 min-w-[140px] rounded-lg border border-border bg-card py-1 shadow-lg",children:[D("p",{className:"px-3 py-1 font-medium text-muted-foreground text-xs",children:"Move to:"}),f.filter((F)=>F.id!==Z.stageId).map((F)=>D("button",{type:"button",onClick:(U)=>{U.stopPropagation(),A(Z.id,F.id)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-muted",children:F.name},F.id))]})]})]},Z.id))})]},N.id)})})}import{useTemplateRuntime as WJ}from"@contractspec/lib.example-shared-ui";import{useCallback as wJ,useEffect as PJ,useMemo as VJ,useState as S}from"react";function i(J={}){let{handlers:K,projectId:W}=WJ(),{crm:_}=K,[Q,O]=S(null),[f,A]=S({}),[N,z]=S([]),[R,Z]=S(!0),[F,U]=S(null),[Y,B]=S(0),q=J.pipelineId??"pipeline-1",$=J.pageIndex??Y,X=J.pageSize??J.limit??50,[E]=J.sorting??[],y=E?.id==="deal"?"name":E?.id,v=E?E.desc?"desc":"asc":void 0,c=wJ(async()=>{Z(!0),U(null);try{let[k,H,t]=await Promise.all([_.listDeals({projectId:W,pipelineId:q,stageId:J.stageId,status:J.status==="all"?void 0:J.status,search:J.search,limit:X,offset:$*X,sortBy:y==="name"||y==="value"||y==="status"||y==="expectedCloseDate"||y==="updatedAt"?y:void 0,sortDirection:v}),_.getDealsByStage({projectId:W,pipelineId:q}),_.getPipelineStages({pipelineId:q})]);O(k),A(H),z(t)}catch(k){U(k instanceof Error?k:Error("Unknown error"))}finally{Z(!1)}},[_,W,q,J.stageId,J.status,J.search,$,X,y,v]);PJ(()=>{c()},[c]);let a=VJ(()=>{if(!Q)return null;let k=Q.deals.filter((h)=>h.status==="OPEN"),H=Q.deals.filter((h)=>h.status==="WON"),t=Q.deals.filter((h)=>h.status==="LOST");return{total:Q.total,totalValue:Q.totalValue,openCount:k.length,openValue:k.reduce((h,s)=>h+s.value,0),wonCount:H.length,wonValue:H.reduce((h,s)=>h+s.value,0),lostCount:t.length}},[Q]);return{data:Q,dealsByStage:f,stages:N,loading:R,error:F,stats:a,page:$+1,pageIndex:$,pageSize:X,refetch:c,nextPage:J.pageIndex===void 0?()=>B((k)=>k+1):void 0,prevPage:J.pageIndex===void 0?()=>$>0&&B((k)=>k-1):void 0}}import{useTemplateRuntime as OJ}from"@contractspec/lib.example-shared-ui";import{useCallback as r,useState as l}from"react";function _J(J={}){let{handlers:K,projectId:W}=OJ(),{crm:_}=K,[Q,O]=l({loading:!1,error:null,data:null}),[f,A]=l({loading:!1,error:null,data:null}),[N,z]=l({loading:!1,error:null,data:null}),[R,Z]=l({loading:!1,error:null,data:null}),F=r(async(q)=>{O({loading:!0,error:null,data:null});try{let $=await _.createDeal(q,{projectId:W,ownerId:"user-1"});return O({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to create deal");return O({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,W,J]),U=r(async(q)=>{A({loading:!0,error:null,data:null});try{let $=await _.moveDeal(q);return A({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to move deal");return A({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,J]),Y=r(async(q)=>{z({loading:!0,error:null,data:null});try{let $=await _.winDeal(q);return z({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to mark deal as won");return z({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,J]),B=r(async(q)=>{Z({loading:!0,error:null,data:null});try{let $=await _.loseDeal(q);return Z({loading:!1,error:null,data:$}),J.onSuccess?.(),$}catch($){let X=$ instanceof Error?$:Error("Failed to mark deal as lost");return Z({loading:!1,error:X,data:null}),J.onError?.(X),null}},[_,J]);return{createDeal:F,moveDeal:U,winDeal:Y,loseDeal:B,createState:Q,moveState:f,winState:N,loseState:R,isLoading:Q.loading||f.loading||N.loading||R.loading}}import{Button as qJ,Input as e}from"@contractspec/lib.design-system";import{useState as p}from"react";import{jsx as T,jsxs as I}from"react/jsx-runtime";var RJ=["USD","EUR","GBP","CAD"],fJ="pipeline-1";function QJ({isOpen:J,onClose:K,onSubmit:W,stages:_,isLoading:Q=!1}){let[O,f]=p(""),[A,N]=p(""),[z,R]=p("USD"),[Z,F]=p(_[0]?.id??""),[U,Y]=p(""),[B,q]=p(null),$=async(X)=>{if(X.preventDefault(),q(null),!O.trim()){q("Deal name is required");return}let E=parseFloat(A);if(isNaN(E)||E<=0){q("Value must be a positive number");return}if(!Z){q("Please select a pipeline stage");return}try{await W({name:O.trim(),value:E,currency:z,pipelineId:fJ,stageId:Z,expectedCloseDate:U?new Date(U):void 0}),f(""),N(""),R("USD"),F(_[0]?.id??""),Y(""),K()}catch(y){q(y instanceof Error?y.message:"Failed to create deal")}};if(!J)return null;return I("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[T("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:K,role:"button",tabIndex:0,onKeyDown:(X)=>{if(X.key==="Enter"||X.key===" ")K()},"aria-label":"Close modal"}),I("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[T("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Deal"}),I("form",{onSubmit:$,className:"space-y-4",children:[I("div",{children:[T("label",{htmlFor:"deal-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Deal Name *"}),T(e,{id:"deal-name",value:O,onChange:(X)=>f(X.target.value),placeholder:"e.g., Enterprise License - Acme Corp",disabled:Q})]}),I("div",{className:"flex gap-3",children:[I("div",{className:"flex-1",children:[T("label",{htmlFor:"deal-value",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Value *"}),T(e,{id:"deal-value",type:"number",min:"0",step:"0.01",value:A,onChange:(X)=>N(X.target.value),placeholder:"50000",disabled:Q})]}),I("div",{className:"w-24",children:[T("label",{htmlFor:"deal-currency",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Currency"}),T("select",{id:"deal-currency",value:z,onChange:(X)=>R(X.target.value),disabled:Q,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:RJ.map((X)=>T("option",{value:X,children:X},X))})]})]}),I("div",{children:[T("label",{htmlFor:"deal-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Pipeline Stage *"}),T("select",{id:"deal-stage",value:Z,onChange:(X)=>F(X.target.value),disabled:Q,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:_.map((X)=>T("option",{value:X.id,children:X.name},X.id))})]}),I("div",{children:[T("label",{htmlFor:"deal-close-date",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Expected Close Date"}),T(e,{id:"deal-close-date",type:"date",value:U,onChange:(X)=>Y(X.target.value),disabled:Q})]}),B&&T("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:B}),I("div",{className:"flex justify-end gap-3 pt-2",children:[T(qJ,{type:"button",variant:"ghost",onPress:K,disabled:Q,children:"Cancel"}),T(qJ,{type:"submit",disabled:Q,children:Q?"Creating...":"Create Deal"})]})]})]})]})}import{Button as L}from"@contractspec/lib.design-system";import{useState as g}from"react";import{jsx as G,jsxs as P,Fragment as TJ}from"react/jsx-runtime";function EJ(J,K){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function zJ({isOpen:J,deal:K,stages:W,onClose:_,onWin:Q,onLose:O,onMove:f,isLoading:A=!1}){let[N,z]=g("menu"),[R,Z]=g(""),[F,U]=g(""),[Y,B]=g(""),[q,$]=g(""),[X,E]=g(null),y=()=>{z("menu"),Z(""),U(""),B(""),$(""),E(null)},v=()=>{y(),_()},c=async()=>{if(!K)return;E(null);try{await Q({dealId:K.id,wonSource:R.trim()||void 0,notes:Y.trim()||void 0}),v()}catch(H){E(H instanceof Error?H.message:"Failed to mark deal as won")}},a=async()=>{if(!K)return;if(E(null),!F.trim()){E("Please provide a reason for losing the deal");return}try{await O({dealId:K.id,lostReason:F.trim(),notes:Y.trim()||void 0}),v()}catch(H){E(H instanceof Error?H.message:"Failed to mark deal as lost")}},k=async()=>{if(!K)return;if(E(null),!q){E("Please select a stage");return}if(q===K.stageId){E("Deal is already in this stage");return}try{await f({dealId:K.id,stageId:q}),v()}catch(H){E(H instanceof Error?H.message:"Failed to move deal")}};if(!J||!K)return null;return P("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[G("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:v,role:"button",tabIndex:0,onKeyDown:(H)=>{if(H.key==="Enter"||H.key===" ")v()},"aria-label":"Close modal"}),P("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[P("div",{className:"mb-4 border-border border-b pb-4",children:[G("h2",{className:"font-semibold text-xl",children:K.name}),G("p",{className:"font-medium text-lg text-primary",children:EJ(K.value,K.currency)}),G("span",{className:`mt-2 inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${K.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":K.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:K.status})]}),N==="menu"&&P("div",{className:"space-y-3",children:[K.status==="OPEN"&&P(TJ,{children:[P(L,{className:"w-full justify-start",variant:"ghost",onPress:()=>z("win"),children:[G("span",{className:"mr-2",children:"\uD83C\uDFC6"})," Mark as Won"]}),P(L,{className:"w-full justify-start",variant:"ghost",onPress:()=>z("lose"),children:[G("span",{className:"mr-2",children:"❌"})," Mark as Lost"]}),P(L,{className:"w-full justify-start",variant:"ghost",onPress:()=>{$(K.stageId),z("move")},children:[G("span",{className:"mr-2",children:"➡️"})," Move to Stage"]})]}),K.status!=="OPEN"&&P("p",{className:"py-4 text-center text-muted-foreground",children:["This deal is already ",K.status.toLowerCase(),". No actions available."]}),G("div",{className:"border-border border-t pt-3",children:G(L,{className:"w-full",variant:"outline",onPress:v,children:"Close"})})]}),N==="win"&&P("div",{className:"space-y-4",children:[P("div",{children:[G("label",{htmlFor:"won-source",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"How did you win this deal?"}),P("select",{id:"won-source",value:R,onChange:(H)=>Z(H.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[G("option",{value:"",children:"Select a source..."}),G("option",{value:"referral",children:"Referral"}),G("option",{value:"cold_outreach",children:"Cold Outreach"}),G("option",{value:"inbound",children:"Inbound Lead"}),G("option",{value:"upsell",children:"Upsell"}),G("option",{value:"other",children:"Other"})]})]}),P("div",{children:[G("label",{htmlFor:"win-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),G("textarea",{id:"win-notes",value:Y,onChange:(H)=>B(H.target.value),placeholder:"Any additional notes about the win...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),X&&G("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),P("div",{className:"flex justify-end gap-3 pt-2",children:[G(L,{variant:"ghost",onPress:()=>z("menu"),disabled:A,children:"Back"}),G(L,{onPress:c,disabled:A,children:A?"Processing...":"\uD83C\uDFC6 Confirm Win"})]})]}),N==="lose"&&P("div",{className:"space-y-4",children:[P("div",{children:[G("label",{htmlFor:"lost-reason",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Why was this deal lost? *"}),P("select",{id:"lost-reason",value:F,onChange:(H)=>U(H.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[G("option",{value:"",children:"Select a reason..."}),G("option",{value:"price",children:"Price too high"}),G("option",{value:"competitor",children:"Lost to competitor"}),G("option",{value:"no_budget",children:"No budget"}),G("option",{value:"no_decision",children:"No decision made"}),G("option",{value:"timing",children:"Bad timing"}),G("option",{value:"product_fit",children:"Product not a fit"}),G("option",{value:"other",children:"Other"})]})]}),P("div",{children:[G("label",{htmlFor:"lose-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),G("textarea",{id:"lose-notes",value:Y,onChange:(H)=>B(H.target.value),placeholder:"Any additional details...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),X&&G("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),P("div",{className:"flex justify-end gap-3 pt-2",children:[G(L,{variant:"ghost",onPress:()=>z("menu"),disabled:A,children:"Back"}),G(L,{variant:"destructive",onPress:a,disabled:A,children:A?"Processing...":"❌ Confirm Loss"})]})]}),N==="move"&&P("div",{className:"space-y-4",children:[P("div",{children:[G("label",{htmlFor:"move-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Move to Stage"}),G("select",{id:"move-stage",value:q,onChange:(H)=>$(H.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:W.map((H)=>P("option",{value:H.id,children:[H.name,H.id===K.stageId?" (current)":""]},H.id))})]}),X&&G("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),P("div",{className:"flex justify-end gap-3 pt-2",children:[G(L,{variant:"ghost",onPress:()=>z("menu"),disabled:A,children:"Back"}),G(L,{onPress:k,disabled:A,children:A?"Moving...":"➡️ Move Deal"})]})]})]})]})}import{Button as j,DataTable as bJ,DataTableToolbar as BJ,LoaderBlock as kJ}from"@contractspec/lib.design-system";import{useContractTable as MJ}from"@contractspec/lib.presentation-runtime-react";import{Badge as yJ}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as x,VStack as JJ}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as M}from"@contractspec/lib.ui-kit-web/ui/text";import*as u from"react";import{jsx as V,jsxs as m}from"react/jsx-runtime";function IJ(J,K="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function LJ(J){switch(J){case"WON":return"default";case"LOST":return"destructive";case"STALE":return"outline";default:return"secondary"}}function vJ({value:J,onChange:K}){return m(x,{gap:"sm",className:"flex-wrap",children:[V(j,{variant:J==="all"?"secondary":"outline",size:"sm",onPress:()=>K("all"),children:"All Deals"}),V(j,{variant:J==="OPEN"?"secondary":"outline",size:"sm",onPress:()=>K("OPEN"),children:"Open Only"}),V(j,{variant:J==="WON"?"secondary":"outline",size:"sm",onPress:()=>K("WON"),children:"Won Only"}),V(j,{variant:J==="LOST"?"secondary":"outline",size:"sm",onPress:()=>K("LOST"),children:"Lost Only"})]})}function hJ({deals:J,totalItems:K,pageIndex:W,pageSize:_,sorting:Q,search:O,status:f,loading:A,onSortingChange:N,onPaginationChange:z,onSearchChange:R,onStatusChange:Z,onDealClick:F}){let U=MJ({data:J,columns:[{id:"deal",header:"Deal",label:"Deal",accessor:(Y)=>Y.name,cell:({item:Y})=>m(JJ,{gap:"xs",children:[V(M,{className:"font-medium text-sm",children:Y.name}),V(M,{className:"text-muted-foreground text-xs",children:Y.companyId??"Unassigned company"})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"value",header:"Value",label:"Value",accessorKey:"value",cell:({item:Y})=>IJ(Y.value,Y.currency),align:"right",size:140,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:Y})=>V(yJ,{variant:LJ(Y),children:String(Y)}),size:130,canSort:!0,canHide:!0,canPin:!0,canResize:!0},{id:"expectedCloseDate",header:"Expected Close",label:"Expected Close",accessor:(Y)=>Y.expectedCloseDate?.toISOString()??"",cell:({item:Y})=>Y.expectedCloseDate?.toLocaleDateString()??"Not scheduled",size:170,canSort:!0,canHide:!0,canResize:!0},{id:"updatedAt",header:"Updated",label:"Updated",accessor:(Y)=>Y.updatedAt.toISOString(),cell:({item:Y})=>Y.updatedAt.toLocaleDateString(),size:140,canSort:!0,canHide:!0,canResize:!0},{id:"actions",header:"Actions",label:"Actions",accessor:(Y)=>Y.id,cell:({item:Y})=>V(j,{variant:"ghost",size:"sm",onPress:()=>F?.(Y.id),children:"Actions"}),size:120,canSort:!1,canHide:!1,canPin:!1,canResize:!1}],executionMode:"server",selectionMode:"multiple",totalItems:K,state:{sorting:Q,pagination:{pageIndex:W,pageSize:_}},onSortingChange:N,onPaginationChange:z,initialState:{columnVisibility:{updatedAt:!1},columnPinning:{left:["deal","status"],right:[]}},renderExpandedContent:(Y)=>m(JJ,{gap:"sm",className:"py-2",children:[m(x,{justify:"between",children:[V(M,{className:"font-medium text-sm",children:"Owner"}),V(M,{className:"text-muted-foreground text-sm",children:Y.ownerId})]}),m(x,{justify:"between",children:[V(M,{className:"font-medium text-sm",children:"Contact"}),V(M,{className:"text-muted-foreground text-sm",children:Y.contactId??"No linked contact"})]}),Y.wonSource?m(x,{justify:"between",children:[V(M,{className:"font-medium text-sm",children:"Won Source"}),V(M,{className:"text-muted-foreground text-sm",children:Y.wonSource})]}):null,Y.lostReason?m(x,{justify:"between",children:[V(M,{className:"font-medium text-sm",children:"Lost Reason"}),V(M,{className:"text-muted-foreground text-sm",children:Y.lostReason})]}):null,Y.notes?m(JJ,{gap:"xs",children:[V(M,{className:"font-medium text-sm",children:"Notes"}),V(M,{className:"text-muted-foreground text-sm",children:Y.notes})]}):null]}),getCanExpand:()=>!0});return V(bJ,{controller:U,title:"All Deals",description:"Server-mode table using the shared ContractSpec controller.",loading:A,toolbar:V(BJ,{controller:U,searchPlaceholder:"Search deals, companies, contacts, or notes",searchValue:O,onSearchChange:R,activeChips:f==="all"?[]:[{key:"status",label:`Status: ${f}`,onRemove:()=>Z("all")}],onClearAll:()=>{R(""),Z("all")},actionsStart:vJ({value:f,onChange:Z}),actionsEnd:m(M,{className:"text-muted-foreground text-sm",children:[K," total deals"]})}),footer:`Page ${U.pageIndex+1} of ${U.pageCount}`,emptyState:V("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No deals found"})})}function FJ({onDealClick:J}){let[K,W]=u.useState([{id:"value",desc:!0}]),[_,Q]=u.useState({pageIndex:0,pageSize:3}),[O,f]=u.useState(""),[A,N]=u.useState("all"),{data:z,loading:R}=i({pageIndex:_.pageIndex,pageSize:_.pageSize,search:O,status:A,sorting:K});if(R&&!z)return V(kJ,{label:"Loading deals..."});return V(hJ,{deals:z?.deals??[],totalItems:z?.total??0,pageIndex:_.pageIndex,pageSize:_.pageSize,sorting:K,search:O,status:A,loading:R,onSortingChange:(Z)=>{W(Z),Q((F)=>({...F,pageIndex:0}))},onPaginationChange:Q,onSearchChange:(Z)=>{f(Z),Q((F)=>({...F,pageIndex:0}))},onStatusChange:(Z)=>{N(Z),Q((F)=>({...F,pageIndex:0}))},onDealClick:J})}import{Button as DJ,ErrorState as mJ,LoaderBlock as CJ,StatCard as n,StatCardGroup as SJ,Tabs as pJ,TabsContent as KJ,TabsList as gJ,TabsTrigger as XJ}from"@contractspec/lib.design-system";import{useCallback as HJ,useState as YJ}from"react";import{jsx as w,jsxs as b}from"react/jsx-runtime";function o(J,K="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function EK(){let[J,K]=YJ(!1),[W,_]=YJ(null),[Q,O]=YJ(!1),{data:f,dealsByStage:A,stages:N,loading:z,error:R,stats:Z,refetch:F}=i(),U=_J({onSuccess:()=>{F()}}),Y=HJ((q)=>{let $=A?Object.values(A).flat().find((X)=>X.id===q):null;if($)_($),O(!0)},[A]),B=HJ(async(q,$)=>{await U.moveDeal({dealId:q,stageId:$})},[U]);if(z&&!f)return w(CJ,{label:"Loading CRM..."});if(R)return w(mJ,{title:"Failed to load CRM",description:R.message,onRetry:F,retryLabel:"Retry"});return b("div",{className:"space-y-6",children:[b("div",{className:"flex items-center justify-between",children:[w("h2",{className:"font-bold text-2xl",children:"CRM Pipeline"}),b(DJ,{onClick:()=>K(!0),children:[w("span",{className:"mr-2",children:"+"})," Create Deal"]})]}),Z&&b(SJ,{children:[w(n,{label:"Total Pipeline",value:o(Z.totalValue),hint:`${Z.total} deals`}),w(n,{label:"Open Deals",value:o(Z.openValue),hint:`${Z.openCount} active`}),w(n,{label:"Won",value:o(Z.wonValue),hint:`${Z.wonCount} closed`}),w(n,{label:"Lost",value:Z.lostCount,hint:"deals lost"})]}),b(pJ,{defaultValue:"pipeline",className:"w-full",children:[b(gJ,{children:[b(XJ,{value:"pipeline",children:[w("span",{className:"mr-2",children:"\uD83D\uDCCA"}),"Pipeline"]}),b(XJ,{value:"list",children:[w("span",{className:"mr-2",children:"\uD83D\uDCCB"}),"All Deals"]}),b(XJ,{value:"metrics",children:[w("span",{className:"mr-2",children:"\uD83D\uDCC8"}),"Metrics"]})]}),w(KJ,{value:"pipeline",className:"min-h-[400px]",children:w(GJ,{dealsByStage:A,stages:N,onDealClick:Y,onDealMove:B})}),w(KJ,{value:"list",className:"min-h-[400px]",children:w(FJ,{onDealClick:Y})}),w(KJ,{value:"metrics",className:"min-h-[400px]",children:w(cJ,{stats:Z})})]}),w(QJ,{isOpen:J,onClose:()=>K(!1),onSubmit:async(q)=>{await U.createDeal(q)},stages:N,isLoading:U.createState.loading}),w(zJ,{isOpen:Q,deal:W,stages:N,onClose:()=>{O(!1),_(null)},onWin:async(q)=>{await U.winDeal(q)},onLose:async(q)=>{await U.loseDeal(q)},onMove:async(q)=>{await U.moveDeal(q),F()},isLoading:U.isLoading})]})}function cJ({stats:J}){if(!J)return null;return w("div",{className:"space-y-6",children:b("div",{className:"rounded-xl border border-border bg-card p-6",children:[w("h3",{className:"mb-4 font-semibold text-lg",children:"Pipeline Overview"}),b("dl",{className:"grid gap-4 sm:grid-cols-3",children:[b("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Win Rate"}),b("dd",{className:"font-semibold text-2xl",children:[J.total>0?(J.wonCount/J.total*100).toFixed(0):0,"%"]})]}),b("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Avg Deal Size"}),w("dd",{className:"font-semibold text-2xl",children:o(J.total>0?J.totalValue/J.total:0)})]}),b("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Conversion"}),b("dd",{className:"font-semibold text-2xl",children:[J.wonCount," / ",J.total]})]})]})]})})}export{EK as CrmDashboard};
@@ -1,4 +1,4 @@
1
- import{web as fJ}from"@contractspec/lib.runtime-sandbox";var{generateId:kJ}=fJ;function c(J){return{id:J.id,projectId:J.projectId,name:J.name,value:J.value,currency:J.currency,pipelineId:J.pipelineId,stageId:J.stageId,status:J.status,contactId:J.contactId??void 0,companyId:J.companyId??void 0,ownerId:J.ownerId,expectedCloseDate:J.expectedCloseDate?new Date(J.expectedCloseDate):void 0,wonSource:J.wonSource??void 0,lostReason:J.lostReason??void 0,notes:J.notes??void 0,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)}}var PJ={name:"name",value:"value",status:"status",expectedCloseDate:"expectedCloseDate",updatedAt:"updatedAt"};function zX(J){async function Y(X){let{projectId:G,pipelineId:W,stageId:q,status:Z,ownerId:N,search:$,limit:f=20,offset:P=0,sortBy:U="value",sortDirection:F="desc"}=X,O="WHERE projectId = ?",B=[G];if(W)O+=" AND pipelineId = ?",B.push(W);if(q)O+=" AND stageId = ?",B.push(q);if(Z&&Z!=="all")O+=" AND status = ?",B.push(Z);if(N)O+=" AND ownerId = ?",B.push(N);if($)O+=" AND name LIKE ?",B.push(`%${$}%`);let j=(await J.query(`SELECT COUNT(*) as count FROM crm_deal ${O}`,B)).rows[0]?.count??0,y=(await J.query(`SELECT COALESCE(SUM(value), 0) as total FROM crm_deal ${O}`,B)).rows[0]?.total??0,_=PJ[U]??PJ.value,r=F==="asc"?"ASC":"DESC";return{deals:(await J.query(`SELECT * FROM crm_deal ${O} ORDER BY ${_} ${r} LIMIT ? OFFSET ?`,[...B,f,P])).rows.map(c),total:j,totalValue:y}}async function Q(X,G){let W=kJ("deal"),q=new Date().toISOString();await J.execute(`INSERT INTO crm_deal (id, projectId, pipelineId, stageId, name, value, currency, status, contactId, companyId, ownerId, expectedCloseDate, createdAt, updatedAt)
2
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[W,G.projectId,X.pipelineId,X.stageId,X.name,X.value,X.currency??"USD","OPEN",X.contactId??null,X.companyId??null,G.ownerId,X.expectedCloseDate?.toISOString()??null,q,q]);let Z=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[W])).rows;if(!Z[0])throw Error("Failed to create deal");return c(Z[0])}async function H(X){let G=new Date().toISOString();if(!(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows[0])throw Error("NOT_FOUND");if(!(await J.query("SELECT * FROM crm_stage WHERE id = ?",[X.stageId])).rows[0])throw Error("INVALID_STAGE");await J.execute("UPDATE crm_deal SET stageId = ?, updatedAt = ? WHERE id = ?",[X.stageId,G,X.dealId]);let Z=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return c(Z[0])}async function z(X){let G=new Date().toISOString();if(!(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows[0])throw Error("NOT_FOUND");await J.execute("UPDATE crm_deal SET status = 'WON', wonSource = ?, notes = ?, updatedAt = ? WHERE id = ?",[X.wonSource??null,X.notes??null,G,X.dealId]);let q=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return c(q[0])}async function V(X){let G=new Date().toISOString();if(!(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows[0])throw Error("NOT_FOUND");await J.execute("UPDATE crm_deal SET status = 'LOST', lostReason = ?, notes = ?, updatedAt = ? WHERE id = ?",[X.lostReason,X.notes??null,G,X.dealId]);let q=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return c(q[0])}async function A(X){let G=(await J.query("SELECT * FROM crm_deal WHERE projectId = ? AND pipelineId = ? AND status = 'OPEN' ORDER BY value DESC",[X.projectId,X.pipelineId])).rows,W=(await J.query("SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position",[X.pipelineId])).rows,q={};for(let Z of W)q[Z.id]=G.filter((N)=>N.stageId===Z.id).map(c);return q}async function K(X){return(await J.query("SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position",[X.pipelineId])).rows.map((W)=>({id:W.id,pipelineId:W.pipelineId,name:W.name,position:W.position}))}return{listDeals:Y,createDeal:Q,moveDeal:H,winDeal:z,loseDeal:V,getDealsByStage:A,getPipelineStages:K}}var d=[{id:"stage-1",name:"Lead",position:1,pipelineId:"pipeline-1"},{id:"stage-2",name:"Qualified",position:2,pipelineId:"pipeline-1"},{id:"stage-3",name:"Proposal",position:3,pipelineId:"pipeline-1"},{id:"stage-4",name:"Negotiation",position:4,pipelineId:"pipeline-1"},{id:"stage-5",name:"Closed",position:5,pipelineId:"pipeline-1"}],L=[{id:"deal-1",name:"Enterprise License - Acme Corp",value:75000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-3",status:"OPEN",contactId:"contact-1",companyId:"company-1",ownerId:"user-1",expectedCloseDate:new Date("2024-05-15T00:00:00Z"),createdAt:new Date("2024-02-01T10:00:00Z"),updatedAt:new Date("2024-04-10T14:30:00Z")},{id:"deal-2",name:"Startup Plan - TechStart Inc",value:12000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-2",status:"OPEN",contactId:"contact-2",companyId:"company-2",ownerId:"user-2",expectedCloseDate:new Date("2024-04-30T00:00:00Z"),createdAt:new Date("2024-03-15T09:00:00Z"),updatedAt:new Date("2024-04-08T11:15:00Z")},{id:"deal-3",name:"Professional Services - Global Ltd",value:45000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-4",status:"OPEN",contactId:"contact-3",companyId:"company-3",ownerId:"user-1",expectedCloseDate:new Date("2024-04-20T00:00:00Z"),createdAt:new Date("2024-01-20T08:00:00Z"),updatedAt:new Date("2024-04-12T16:45:00Z")},{id:"deal-4",name:"Annual Contract - SmallBiz Co",value:8500,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-1",status:"OPEN",contactId:"contact-4",companyId:"company-4",ownerId:"user-3",createdAt:new Date("2024-04-05T12:00:00Z"),updatedAt:new Date("2024-04-05T12:00:00Z")},{id:"deal-5",name:"Custom Integration - MegaCorp",value:125000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-5",status:"WON",contactId:"contact-5",companyId:"company-5",ownerId:"user-1",expectedCloseDate:new Date("2024-03-31T00:00:00Z"),createdAt:new Date("2023-11-10T10:00:00Z"),updatedAt:new Date("2024-03-28T09:00:00Z")},{id:"deal-6",name:"Pilot Project - NewCo",value:5000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-2",status:"LOST",contactId:"contact-6",companyId:"company-6",ownerId:"user-2",createdAt:new Date("2024-01-15T14:00:00Z"),updatedAt:new Date("2024-02-28T10:30:00Z")}],WX=[{id:"company-1",name:"Acme Corporation",domain:"acme.com",industry:"Technology",size:"1000-5000",website:"https://acme.com",createdAt:new Date("2024-01-01T00:00:00Z")},{id:"company-2",name:"TechStart Inc",domain:"techstart.io",industry:"Software",size:"10-50",website:"https://techstart.io",createdAt:new Date("2024-02-15T00:00:00Z")},{id:"company-3",name:"Global Ltd",domain:"global.com",industry:"Consulting",size:"500-1000",website:"https://global.com",createdAt:new Date("2023-12-01T00:00:00Z")}],UX=[{id:"contact-1",firstName:"John",lastName:"Smith",email:"john.smith@acme.com",phone:"+1-555-0101",title:"VP of Engineering",companyId:"company-1",createdAt:new Date("2024-01-05T00:00:00Z")},{id:"contact-2",firstName:"Sarah",lastName:"Johnson",email:"sarah@techstart.io",phone:"+1-555-0102",title:"CEO",companyId:"company-2",createdAt:new Date("2024-02-20T00:00:00Z")},{id:"contact-3",firstName:"Michael",lastName:"Brown",email:"michael.brown@global.com",phone:"+1-555-0103",title:"CTO",companyId:"company-3",createdAt:new Date("2023-12-10T00:00:00Z")}];async function t(J){let{pipelineId:Y,stageId:Q,status:H,ownerId:z,search:V,limit:A=20,offset:K=0}=J,X=[...L];if(Y)X=X.filter((Z)=>Z.pipelineId===Y);if(Q)X=X.filter((Z)=>Z.stageId===Q);if(H&&H!=="all")X=X.filter((Z)=>Z.status===H);if(z)X=X.filter((Z)=>Z.ownerId===z);if(V){let Z=V.toLowerCase();X=X.filter((N)=>N.name.toLowerCase().includes(Z))}X.sort((Z,N)=>N.value-Z.value);let G=X.length,W=X.reduce((Z,N)=>Z+N.value,0);return{deals:X.slice(K,K+A),total:G,totalValue:W}}async function EJ(J,Y){let Q=new Date,H={id:`deal-${Date.now()}`,name:J.name,value:J.value,currency:J.currency??"USD",pipelineId:J.pipelineId,stageId:J.stageId,status:"OPEN",contactId:J.contactId,companyId:J.companyId,ownerId:Y.ownerId,expectedCloseDate:J.expectedCloseDate,createdAt:Q,updatedAt:Q};return L.push(H),H}async function TJ(J){let Y=L.findIndex((V)=>V.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let Q=L[Y];if(!Q)throw Error("NOT_FOUND");if(!d.find((V)=>V.id===J.stageId))throw Error("INVALID_STAGE");let z={...Q,stageId:J.stageId,updatedAt:new Date};return L[Y]=z,z}async function BJ(J){let Y=L.findIndex((z)=>z.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let Q=L[Y];if(!Q)throw Error("NOT_FOUND");let H={...Q,status:"WON",updatedAt:new Date};return L[Y]=H,H}async function MJ(J){let Y=L.findIndex((z)=>z.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let Q=L[Y];if(!Q)throw Error("NOT_FOUND");let H={...Q,status:"LOST",updatedAt:new Date};return L[Y]=H,H}async function vJ(J){let Y=L.filter((H)=>H.pipelineId===J.pipelineId&&H.status==="OPEN"),Q={};for(let H of d)Q[H.id]=Y.filter((z)=>z.stageId===H.id);return Q}async function s(J){return d.filter((Y)=>Y.pipelineId===J.pipelineId)}import{jsx as e,jsxs as KJ}from"react/jsx-runtime";function yJ(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function RJ({deal:J,onClick:Y}){let Q=J.expectedCloseDate?Math.ceil((J.expectedCloseDate.getTime()-Date.now())/86400000):null;return KJ("div",{onClick:Y,className:"cursor-pointer rounded-lg border border-border bg-card p-3 shadow-sm transition-shadow hover:shadow-md",role:"button",tabIndex:0,onKeyDown:(H)=>{if(H.key==="Enter"||H.key===" ")Y?.()},children:[e("h4",{className:"font-medium leading-snug",children:J.name}),e("div",{className:"mt-2 font-semibold text-lg text-primary",children:yJ(J.value,J.currency)}),KJ("div",{className:"mt-3 flex items-center justify-between text-muted-foreground text-xs",children:[Q!==null&&e("span",{className:Q<0?"text-red-500":Q<=7?"text-yellow-600 dark:text-yellow-500":"",children:Q<0?`${Math.abs(Q)}d overdue`:Q===0?"Due today":`${Q}d left`}),e("span",{className:`rounded px-1.5 py-0.5 font-medium text-xs ${J.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":J.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:J.status})]})]})}import{useState as LJ}from"react";import{jsx as m,jsxs as x}from"react/jsx-runtime";function hJ(J){if(J>=1e6)return`$${(J/1e6).toFixed(1)}M`;if(J>=1000)return`$${(J/1000).toFixed(0)}K`;return`$${J}`}function JJ({dealsByStage:J,stages:Y,onDealClick:Q,onDealMove:H}){let[z,V]=LJ(null),A=[...Y].sort((X,G)=>X.position-G.position),K=(X,G)=>{H?.(X,G),V(null)};return m("div",{className:"flex gap-4 overflow-x-auto pb-4",children:A.map((X)=>{let G=J[X.id]??[],W=G.reduce((q,Z)=>q+Z.value,0);return x("div",{className:"flex w-72 flex-shrink-0 flex-col rounded-lg bg-muted/30",children:[x("div",{className:"flex items-center justify-between border-border border-b px-3 py-2",children:[x("div",{children:[m("h3",{className:"font-medium",children:X.name}),x("p",{className:"text-muted-foreground text-xs",children:[G.length," deals · ",hJ(W)]})]}),m("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",children:G.length})]}),m("div",{className:"flex flex-1 flex-col gap-2 p-2",children:G.length===0?m("div",{className:"flex h-24 items-center justify-center rounded-md border-2 border-muted-foreground/20 border-dashed text-muted-foreground text-xs",children:"No deals"}):G.map((q)=>x("div",{className:"group relative",children:[m(RJ,{deal:q,onClick:()=>Q?.(q.id)}),q.status==="OPEN"&&H&&x("div",{className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100",children:[m("button",{type:"button",onClick:(Z)=>{Z.stopPropagation(),V(z===q.id?null:q.id)},className:"flex h-6 w-6 items-center justify-center rounded border border-border bg-background text-xs shadow-sm hover:bg-muted",title:"Quick move",children:"➡️"}),z===q.id&&x("div",{className:"absolute top-7 right-0 z-20 min-w-[140px] rounded-lg border border-border bg-card py-1 shadow-lg",children:[m("p",{className:"px-3 py-1 font-medium text-muted-foreground text-xs",children:"Move to:"}),A.filter((Z)=>Z.id!==q.stageId).map((Z)=>m("button",{type:"button",onClick:(N)=>{N.stopPropagation(),K(q.id,Z.id)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-muted",children:Z.name},Z.id))]})]})]},q.id))})]},X.id)})})}import{useTemplateRuntime as IJ}from"@contractspec/lib.example-shared-ui";import{useCallback as bJ,useEffect as wJ,useMemo as DJ,useState as p}from"react";function g(J={}){let{handlers:Y,projectId:Q}=IJ(),{crm:H}=Y,[z,V]=p(null),[A,K]=p({}),[X,G]=p([]),[W,q]=p(!0),[Z,N]=p(null),[$,f]=p(0),P=J.pipelineId??"pipeline-1",U=J.pageIndex??$,F=J.pageSize??J.limit??50,[O]=J.sorting??[],B=O?.id==="deal"?"name":O?.id,I=O?O.desc?"desc":"asc":void 0,j=bJ(async()=>{q(!0),N(null);try{let[y,_,r]=await Promise.all([H.listDeals({projectId:Q,pipelineId:P,stageId:J.stageId,status:J.status==="all"?void 0:J.status,search:J.search,limit:F,offset:U*F,sortBy:B==="name"||B==="value"||B==="status"||B==="expectedCloseDate"||B==="updatedAt"?B:void 0,sortDirection:I}),H.getDealsByStage({projectId:Q,pipelineId:P}),H.getPipelineStages({pipelineId:P})]);V(y),K(_),G(r)}catch(y){N(y instanceof Error?y:Error("Unknown error"))}finally{q(!1)}},[H,Q,P,J.stageId,J.status,J.search,U,F,B,I]);wJ(()=>{j()},[j]);let a=DJ(()=>{if(!z)return null;let y=z.deals.filter((b)=>b.status==="OPEN"),_=z.deals.filter((b)=>b.status==="WON"),r=z.deals.filter((b)=>b.status==="LOST");return{total:z.total,totalValue:z.totalValue,openCount:y.length,openValue:y.reduce((b,qJ)=>b+qJ.value,0),wonCount:_.length,wonValue:_.reduce((b,qJ)=>b+qJ.value,0),lostCount:r.length}},[z]);return{data:z,dealsByStage:A,stages:X,loading:W,error:Z,stats:a,page:U+1,pageIndex:U,pageSize:F,refetch:j,nextPage:J.pageIndex===void 0?()=>f((y)=>y+1):void 0,prevPage:J.pageIndex===void 0?()=>U>0&&f((y)=>y-1):void 0}}import{useTemplateRuntime as mJ}from"@contractspec/lib.example-shared-ui";import{useCallback as XJ,useState as YJ}from"react";function HJ(J={}){let{handlers:Y,projectId:Q}=mJ(),{crm:H}=Y,[z,V]=YJ({loading:!1,error:null,data:null}),[A,K]=YJ({loading:!1,error:null,data:null}),[X,G]=YJ({loading:!1,error:null,data:null}),[W,q]=YJ({loading:!1,error:null,data:null}),Z=XJ(async(P)=>{V({loading:!0,error:null,data:null});try{let U=await H.createDeal(P,{projectId:Q,ownerId:"user-1"});return V({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to create deal");return V({loading:!1,error:F,data:null}),J.onError?.(F),null}},[H,Q,J]),N=XJ(async(P)=>{K({loading:!0,error:null,data:null});try{let U=await H.moveDeal(P);return K({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to move deal");return K({loading:!1,error:F,data:null}),J.onError?.(F),null}},[H,J]),$=XJ(async(P)=>{G({loading:!0,error:null,data:null});try{let U=await H.winDeal(P);return G({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to mark deal as won");return G({loading:!1,error:F,data:null}),J.onError?.(F),null}},[H,J]),f=XJ(async(P)=>{q({loading:!0,error:null,data:null});try{let U=await H.loseDeal(P);return q({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to mark deal as lost");return q({loading:!1,error:F,data:null}),J.onError?.(F),null}},[H,J]);return{createDeal:Z,moveDeal:N,winDeal:$,loseDeal:f,createState:z,moveState:A,winState:X,loseState:W,isLoading:z.loading||A.loading||X.loading||W.loading}}import{Button as VJ,Input as GJ}from"@contractspec/lib.design-system";import{useState as u}from"react";import{jsx as M,jsxs as w}from"react/jsx-runtime";var CJ=["USD","EUR","GBP","CAD"],SJ="pipeline-1";function QJ({isOpen:J,onClose:Y,onSubmit:Q,stages:H,isLoading:z=!1}){let[V,A]=u(""),[K,X]=u(""),[G,W]=u("USD"),[q,Z]=u(H[0]?.id??""),[N,$]=u(""),[f,P]=u(null),U=async(F)=>{if(F.preventDefault(),P(null),!V.trim()){P("Deal name is required");return}let O=parseFloat(K);if(isNaN(O)||O<=0){P("Value must be a positive number");return}if(!q){P("Please select a pipeline stage");return}try{await Q({name:V.trim(),value:O,currency:G,pipelineId:SJ,stageId:q,expectedCloseDate:N?new Date(N):void 0}),A(""),X(""),W("USD"),Z(H[0]?.id??""),$(""),Y()}catch(B){P(B instanceof Error?B.message:"Failed to create deal")}};if(!J)return null;return w("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[M("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:Y,role:"button",tabIndex:0,onKeyDown:(F)=>{if(F.key==="Enter"||F.key===" ")Y()},"aria-label":"Close modal"}),w("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[M("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Deal"}),w("form",{onSubmit:U,className:"space-y-4",children:[w("div",{children:[M("label",{htmlFor:"deal-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Deal Name *"}),M(GJ,{id:"deal-name",value:V,onChange:(F)=>A(F.target.value),placeholder:"e.g., Enterprise License - Acme Corp",disabled:z})]}),w("div",{className:"flex gap-3",children:[w("div",{className:"flex-1",children:[M("label",{htmlFor:"deal-value",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Value *"}),M(GJ,{id:"deal-value",type:"number",min:"0",step:"0.01",value:K,onChange:(F)=>X(F.target.value),placeholder:"50000",disabled:z})]}),w("div",{className:"w-24",children:[M("label",{htmlFor:"deal-currency",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Currency"}),M("select",{id:"deal-currency",value:G,onChange:(F)=>W(F.target.value),disabled:z,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:CJ.map((F)=>M("option",{value:F,children:F},F))})]})]}),w("div",{children:[M("label",{htmlFor:"deal-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Pipeline Stage *"}),M("select",{id:"deal-stage",value:q,onChange:(F)=>Z(F.target.value),disabled:z,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:H.map((F)=>M("option",{value:F.id,children:F.name},F.id))})]}),w("div",{children:[M("label",{htmlFor:"deal-close-date",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Expected Close Date"}),M(GJ,{id:"deal-close-date",type:"date",value:N,onChange:(F)=>$(F.target.value),disabled:z})]}),f&&M("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:f}),w("div",{className:"flex justify-end gap-3 pt-2",children:[M(VJ,{type:"button",variant:"ghost",onPress:Y,disabled:z,children:"Cancel"}),M(VJ,{type:"submit",disabled:z,children:z?"Creating...":"Create Deal"})]})]})]})]})}import{Button as D}from"@contractspec/lib.design-system";import{useState as i}from"react";import{jsx as R,jsxs as E,Fragment as xJ}from"react/jsx-runtime";function jJ(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function zJ({isOpen:J,deal:Y,stages:Q,onClose:H,onWin:z,onLose:V,onMove:A,isLoading:K=!1}){let[X,G]=i("menu"),[W,q]=i(""),[Z,N]=i(""),[$,f]=i(""),[P,U]=i(""),[F,O]=i(null),B=()=>{G("menu"),q(""),N(""),f(""),U(""),O(null)},I=()=>{B(),H()},j=async()=>{if(!Y)return;O(null);try{await z({dealId:Y.id,wonSource:W.trim()||void 0,notes:$.trim()||void 0}),I()}catch(_){O(_ instanceof Error?_.message:"Failed to mark deal as won")}},a=async()=>{if(!Y)return;if(O(null),!Z.trim()){O("Please provide a reason for losing the deal");return}try{await V({dealId:Y.id,lostReason:Z.trim(),notes:$.trim()||void 0}),I()}catch(_){O(_ instanceof Error?_.message:"Failed to mark deal as lost")}},y=async()=>{if(!Y)return;if(O(null),!P){O("Please select a stage");return}if(P===Y.stageId){O("Deal is already in this stage");return}try{await A({dealId:Y.id,stageId:P}),I()}catch(_){O(_ instanceof Error?_.message:"Failed to move deal")}};if(!J||!Y)return null;return E("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[R("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:I,role:"button",tabIndex:0,onKeyDown:(_)=>{if(_.key==="Enter"||_.key===" ")I()},"aria-label":"Close modal"}),E("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[E("div",{className:"mb-4 border-border border-b pb-4",children:[R("h2",{className:"font-semibold text-xl",children:Y.name}),R("p",{className:"font-medium text-lg text-primary",children:jJ(Y.value,Y.currency)}),R("span",{className:`mt-2 inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${Y.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":Y.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:Y.status})]}),X==="menu"&&E("div",{className:"space-y-3",children:[Y.status==="OPEN"&&E(xJ,{children:[E(D,{className:"w-full justify-start",variant:"ghost",onPress:()=>G("win"),children:[R("span",{className:"mr-2",children:"\uD83C\uDFC6"})," Mark as Won"]}),E(D,{className:"w-full justify-start",variant:"ghost",onPress:()=>G("lose"),children:[R("span",{className:"mr-2",children:"❌"})," Mark as Lost"]}),E(D,{className:"w-full justify-start",variant:"ghost",onPress:()=>{U(Y.stageId),G("move")},children:[R("span",{className:"mr-2",children:"➡️"})," Move to Stage"]})]}),Y.status!=="OPEN"&&E("p",{className:"py-4 text-center text-muted-foreground",children:["This deal is already ",Y.status.toLowerCase(),". No actions available."]}),R("div",{className:"border-border border-t pt-3",children:R(D,{className:"w-full",variant:"outline",onPress:I,children:"Close"})})]}),X==="win"&&E("div",{className:"space-y-4",children:[E("div",{children:[R("label",{htmlFor:"won-source",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"How did you win this deal?"}),E("select",{id:"won-source",value:W,onChange:(_)=>q(_.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[R("option",{value:"",children:"Select a source..."}),R("option",{value:"referral",children:"Referral"}),R("option",{value:"cold_outreach",children:"Cold Outreach"}),R("option",{value:"inbound",children:"Inbound Lead"}),R("option",{value:"upsell",children:"Upsell"}),R("option",{value:"other",children:"Other"})]})]}),E("div",{children:[R("label",{htmlFor:"win-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),R("textarea",{id:"win-notes",value:$,onChange:(_)=>f(_.target.value),placeholder:"Any additional notes about the win...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),F&&R("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:F}),E("div",{className:"flex justify-end gap-3 pt-2",children:[R(D,{variant:"ghost",onPress:()=>G("menu"),disabled:K,children:"Back"}),R(D,{onPress:j,disabled:K,children:K?"Processing...":"\uD83C\uDFC6 Confirm Win"})]})]}),X==="lose"&&E("div",{className:"space-y-4",children:[E("div",{children:[R("label",{htmlFor:"lost-reason",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Why was this deal lost? *"}),E("select",{id:"lost-reason",value:Z,onChange:(_)=>N(_.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[R("option",{value:"",children:"Select a reason..."}),R("option",{value:"price",children:"Price too high"}),R("option",{value:"competitor",children:"Lost to competitor"}),R("option",{value:"no_budget",children:"No budget"}),R("option",{value:"no_decision",children:"No decision made"}),R("option",{value:"timing",children:"Bad timing"}),R("option",{value:"product_fit",children:"Product not a fit"}),R("option",{value:"other",children:"Other"})]})]}),E("div",{children:[R("label",{htmlFor:"lose-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),R("textarea",{id:"lose-notes",value:$,onChange:(_)=>f(_.target.value),placeholder:"Any additional details...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),F&&R("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:F}),E("div",{className:"flex justify-end gap-3 pt-2",children:[R(D,{variant:"ghost",onPress:()=>G("menu"),disabled:K,children:"Back"}),R(D,{variant:"destructive",onPress:a,disabled:K,children:K?"Processing...":"❌ Confirm Loss"})]})]}),X==="move"&&E("div",{className:"space-y-4",children:[E("div",{children:[R("label",{htmlFor:"move-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Move to Stage"}),R("select",{id:"move-stage",value:P,onChange:(_)=>U(_.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:Q.map((_)=>E("option",{value:_.id,children:[_.name,_.id===Y.stageId?" (current)":""]},_.id))})]}),F&&R("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:F}),E("div",{className:"flex justify-end gap-3 pt-2",children:[R(D,{variant:"ghost",onPress:()=>G("menu"),disabled:K,children:"Back"}),R(D,{onPress:y,disabled:K,children:K?"Moving...":"➡️ Move Deal"})]})]})]})]})}import{Button as l,DataTable as gJ,DataTableToolbar as cJ,LoaderBlock as pJ}from"@contractspec/lib.design-system";import{useContractTable as uJ}from"@contractspec/lib.presentation-runtime-react";import{Badge as iJ}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as n,VStack as FJ}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as h}from"@contractspec/lib.ui-kit-web/ui/text";import*as o from"react";import{jsx as T,jsxs as C}from"react/jsx-runtime";function rJ(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function dJ(J){switch(J){case"WON":return"default";case"LOST":return"destructive";case"STALE":return"outline";default:return"secondary"}}function lJ({value:J,onChange:Y}){return C(n,{gap:"sm",className:"flex-wrap",children:[T(l,{variant:J==="all"?"secondary":"outline",size:"sm",onPress:()=>Y("all"),children:"All Deals"}),T(l,{variant:J==="OPEN"?"secondary":"outline",size:"sm",onPress:()=>Y("OPEN"),children:"Open Only"}),T(l,{variant:J==="WON"?"secondary":"outline",size:"sm",onPress:()=>Y("WON"),children:"Won Only"}),T(l,{variant:J==="LOST"?"secondary":"outline",size:"sm",onPress:()=>Y("LOST"),children:"Lost Only"})]})}function nJ({deals:J,totalItems:Y,pageIndex:Q,pageSize:H,sorting:z,search:V,status:A,loading:K,onSortingChange:X,onPaginationChange:G,onSearchChange:W,onStatusChange:q,onDealClick:Z}){let N=uJ({data:J,columns:[{id:"deal",header:"Deal",label:"Deal",accessor:($)=>$.name,cell:({item:$})=>C(FJ,{gap:"xs",children:[T(h,{className:"font-medium text-sm",children:$.name}),T(h,{className:"text-muted-foreground text-xs",children:$.companyId??"Unassigned company"})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"value",header:"Value",label:"Value",accessorKey:"value",cell:({item:$})=>rJ($.value,$.currency),align:"right",size:140,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:$})=>T(iJ,{variant:dJ($),children:String($)}),size:130,canSort:!0,canHide:!0,canPin:!0,canResize:!0},{id:"expectedCloseDate",header:"Expected Close",label:"Expected Close",accessor:($)=>$.expectedCloseDate?.toISOString()??"",cell:({item:$})=>$.expectedCloseDate?.toLocaleDateString()??"Not scheduled",size:170,canSort:!0,canHide:!0,canResize:!0},{id:"updatedAt",header:"Updated",label:"Updated",accessor:($)=>$.updatedAt.toISOString(),cell:({item:$})=>$.updatedAt.toLocaleDateString(),size:140,canSort:!0,canHide:!0,canResize:!0},{id:"actions",header:"Actions",label:"Actions",accessor:($)=>$.id,cell:({item:$})=>T(l,{variant:"ghost",size:"sm",onPress:()=>Z?.($.id),children:"Actions"}),size:120,canSort:!1,canHide:!1,canPin:!1,canResize:!1}],executionMode:"server",selectionMode:"multiple",totalItems:Y,state:{sorting:z,pagination:{pageIndex:Q,pageSize:H}},onSortingChange:X,onPaginationChange:G,initialState:{columnVisibility:{updatedAt:!1},columnPinning:{left:["deal","status"],right:[]}},renderExpandedContent:($)=>C(FJ,{gap:"sm",className:"py-2",children:[C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Owner"}),T(h,{className:"text-muted-foreground text-sm",children:$.ownerId})]}),C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Contact"}),T(h,{className:"text-muted-foreground text-sm",children:$.contactId??"No linked contact"})]}),$.wonSource?C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Won Source"}),T(h,{className:"text-muted-foreground text-sm",children:$.wonSource})]}):null,$.lostReason?C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Lost Reason"}),T(h,{className:"text-muted-foreground text-sm",children:$.lostReason})]}):null,$.notes?C(FJ,{gap:"xs",children:[T(h,{className:"font-medium text-sm",children:"Notes"}),T(h,{className:"text-muted-foreground text-sm",children:$.notes})]}):null]}),getCanExpand:()=>!0});return T(gJ,{controller:N,title:"All Deals",description:"Server-mode table using the shared ContractSpec controller.",loading:K,toolbar:T(cJ,{controller:N,searchPlaceholder:"Search deals, companies, contacts, or notes",searchValue:V,onSearchChange:W,activeChips:A==="all"?[]:[{key:"status",label:`Status: ${A}`,onRemove:()=>q("all")}],onClearAll:()=>{W(""),q("all")},actionsStart:lJ({value:A,onChange:q}),actionsEnd:C(h,{className:"text-muted-foreground text-sm",children:[Y," total deals"]})}),footer:`Page ${N.pageIndex+1} of ${N.pageCount}`,emptyState:T("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No deals found"})})}function _J({onDealClick:J}){let[Y,Q]=o.useState([{id:"value",desc:!0}]),[H,z]=o.useState({pageIndex:0,pageSize:3}),[V,A]=o.useState(""),[K,X]=o.useState("all"),{data:G,loading:W}=g({pageIndex:H.pageIndex,pageSize:H.pageSize,search:V,status:K,sorting:Y});if(W&&!G)return T(pJ,{label:"Loading deals..."});return T(nJ,{deals:G?.deals??[],totalItems:G?.total??0,pageIndex:H.pageIndex,pageSize:H.pageSize,sorting:Y,search:V,status:K,loading:W,onSortingChange:(q)=>{Q(q),z((Z)=>({...Z,pageIndex:0}))},onPaginationChange:z,onSearchChange:(q)=>{A(q),z((Z)=>({...Z,pageIndex:0}))},onStatusChange:(q)=>{X(q),z((Z)=>({...Z,pageIndex:0}))},onDealClick:J})}import{Button as oJ,ErrorState as aJ,LoaderBlock as tJ,StatCard as ZJ,StatCardGroup as sJ}from"@contractspec/lib.design-system";import{Tabs as eJ,TabsContent as WJ,TabsList as JX,TabsTrigger as UJ}from"@contractspec/lib.ui-kit-web/ui/tabs";import{useCallback as AJ,useState as NJ}from"react";import{jsx as k,jsxs as v}from"react/jsx-runtime";function $J(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function ZY(){let[J,Y]=NJ(!1),[Q,H]=NJ(null),[z,V]=NJ(!1),{data:A,dealsByStage:K,stages:X,loading:G,error:W,stats:q,refetch:Z}=g(),N=HJ({onSuccess:()=>{Z()}}),$=AJ((P)=>{let U=K?Object.values(K).flat().find((F)=>F.id===P):null;if(U)H(U),V(!0)},[K]),f=AJ(async(P,U)=>{await N.moveDeal({dealId:P,stageId:U})},[N]);if(G&&!A)return k(tJ,{label:"Loading CRM..."});if(W)return k(aJ,{title:"Failed to load CRM",description:W.message,onRetry:Z,retryLabel:"Retry"});return v("div",{className:"space-y-6",children:[v("div",{className:"flex items-center justify-between",children:[k("h2",{className:"font-bold text-2xl",children:"CRM Pipeline"}),v(oJ,{onClick:()=>Y(!0),children:[k("span",{className:"mr-2",children:"+"})," Create Deal"]})]}),q&&v(sJ,{children:[k(ZJ,{label:"Total Pipeline",value:$J(q.totalValue),hint:`${q.total} deals`}),k(ZJ,{label:"Open Deals",value:$J(q.openValue),hint:`${q.openCount} active`}),k(ZJ,{label:"Won",value:$J(q.wonValue),hint:`${q.wonCount} closed`}),k(ZJ,{label:"Lost",value:q.lostCount,hint:"deals lost"})]}),v(eJ,{defaultValue:"pipeline",className:"w-full",children:[v(JX,{children:[v(UJ,{value:"pipeline",children:[k("span",{className:"mr-2",children:"\uD83D\uDCCA"}),"Pipeline"]}),v(UJ,{value:"list",children:[k("span",{className:"mr-2",children:"\uD83D\uDCCB"}),"All Deals"]}),v(UJ,{value:"metrics",children:[k("span",{className:"mr-2",children:"\uD83D\uDCC8"}),"Metrics"]})]}),k(WJ,{value:"pipeline",className:"min-h-[400px]",children:k(JJ,{dealsByStage:K,stages:X,onDealClick:$,onDealMove:f})}),k(WJ,{value:"list",className:"min-h-[400px]",children:k(_J,{onDealClick:$})}),k(WJ,{value:"metrics",className:"min-h-[400px]",children:k(XX,{stats:q})})]}),k(QJ,{isOpen:J,onClose:()=>Y(!1),onSubmit:async(P)=>{await N.createDeal(P)},stages:X,isLoading:N.createState.loading}),k(zJ,{isOpen:z,deal:Q,stages:X,onClose:()=>{V(!1),H(null)},onWin:async(P)=>{await N.winDeal(P)},onLose:async(P)=>{await N.loseDeal(P)},onMove:async(P)=>{await N.moveDeal(P),Z()},isLoading:N.isLoading})]})}function XX({stats:J}){if(!J)return null;return k("div",{className:"space-y-6",children:v("div",{className:"rounded-xl border border-border bg-card p-6",children:[k("h3",{className:"mb-4 font-semibold text-lg",children:"Pipeline Overview"}),v("dl",{className:"grid gap-4 sm:grid-cols-3",children:[v("div",{children:[k("dt",{className:"text-muted-foreground text-sm",children:"Win Rate"}),v("dd",{className:"font-semibold text-2xl",children:[J.total>0?(J.wonCount/J.total*100).toFixed(0):0,"%"]})]}),v("div",{children:[k("dt",{className:"text-muted-foreground text-sm",children:"Avg Deal Size"}),k("dd",{className:"font-semibold text-2xl",children:$J(J.total>0?J.totalValue/J.total:0)})]}),v("div",{children:[k("dt",{className:"text-muted-foreground text-sm",children:"Conversion"}),v("dd",{className:"font-semibold text-2xl",children:[J.wonCount," / ",J.total]})]})]})]})})}var YX={overlayId:"crm-pipeline.demo-user",version:"1.0.0",description:"Demo mode with sample data",appliesTo:{feature:"crm-pipeline",role:"demo"},modifications:[{type:"hideField",field:"importButton",reason:"Not available in demo"},{type:"hideField",field:"exportButton",reason:"Not available in demo"},{type:"addBadge",position:"header",label:"Demo Mode",variant:"warning"}]},ZX={overlayId:"crm-pipeline.sales-rep",version:"1.0.0",description:"Sales rep focused view",appliesTo:{feature:"crm-pipeline",role:"sales-rep"},modifications:[{type:"hideField",field:"teamMetrics",reason:"Team metrics for managers only"},{type:"hideField",field:"pipelineSettings",reason:"Admin only"},{type:"renameLabel",field:"deals",newLabel:"My Deals"}]},UY=[YX,ZX];function S(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0}).format(J)}var $X={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="PipelineKanbanView")throw Error("crmPipelineMarkdownRenderer: not PipelineKanbanView");let Q="pipeline-1",[H,z]=await Promise.all([t({pipelineId:Q,limit:50}),s({pipelineId:Q})]),V=H.deals,A=z,K={};for(let G of A)K[G.id]=V.filter((W)=>W.stageId===G.id&&W.status==="OPEN");let X=["# CRM Pipeline","",`**Total Value**: ${S(H.totalValue)}`,`**Total Deals**: ${H.total}`,""];for(let G of A.sort((W,q)=>W.position-q.position)){let W=K[G.id]??[],q=W.reduce((Z,N)=>Z+N.value,0);if(X.push(`## ${G.name}`),X.push(`_${W.length} deals · ${S(q)}_`),X.push(""),W.length===0)X.push("_No deals_");else for(let Z of W)X.push(`- **${Z.name}** - ${S(Z.value,Z.currency)}`);X.push("")}return{mimeType:"text/markdown",body:X.join(`
3
- `)}}},qX={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="CrmDashboard")throw Error("crmDashboardMarkdownRenderer: not CrmDashboard");let Q="pipeline-1",[H,z]=await Promise.all([t({pipelineId:Q,limit:100}),s({pipelineId:Q})]),V=H.deals,A=z,K=V.filter(($)=>$.status==="OPEN"),X=V.filter(($)=>$.status==="WON"),G=V.filter(($)=>$.status==="LOST"),W=K.reduce(($,f)=>$+f.value,0),q=X.reduce(($,f)=>$+f.value,0),Z=["# CRM Dashboard","","> Sales pipeline overview and key metrics","","## Summary","","| Metric | Value |","|--------|-------|",`| Total Deals | ${H.total} |`,`| Pipeline Value | ${S(H.totalValue)} |`,`| Open Deals | ${K.length} (${S(W)}) |`,`| Won Deals | ${X.length} (${S(q)}) |`,`| Lost Deals | ${G.length} |`,"","## Pipeline Stages",""];Z.push("| Stage | Deals | Value |"),Z.push("|-------|-------|-------|");for(let $ of A.sort((f,P)=>f.position-P.position)){let f=K.filter((U)=>U.stageId===$.id),P=f.reduce((U,F)=>U+F.value,0);Z.push(`| ${$.name} | ${f.length} | ${S(P)} |`)}Z.push(""),Z.push("## Recent Deals"),Z.push("");let N=V.slice(0,10);if(N.length===0)Z.push("_No deals yet._");else{Z.push("| Deal | Value | Stage | Status |"),Z.push("|------|-------|-------|--------|");for(let $ of N){let f=A.find((P)=>P.id===$.stageId);Z.push(`| ${$.name} | ${S($.value,$.currency)} | ${f?.name??"-"} | ${$.status} |`)}}return{mimeType:"text/markdown",body:Z.join(`
4
- `)}}};import{jsx as OJ}from"react/jsx-runtime";function HX(){let{dealsByStage:J,stages:Y}=g();return OJ(JJ,{dealsByStage:J,stages:Y})}var GX={target:"react",render:async(J,Y)=>{if(J.source.type!=="component")throw Error("Invalid source type");if(J.source.componentKey!=="CrmPipelineView")throw Error(`Unknown component: ${J.source.componentKey}`);return OJ(HX,{})}};export{HJ as useDealMutations,g as useDealList,ZX as crmSalesRepOverlay,GX as crmPipelineReactRenderer,$X as crmPipelineMarkdownRenderer,UY as crmOverlays,YX as crmDemoOverlay,qX as crmDashboardMarkdownRenderer,zJ as DealActionsModal,JJ as CrmPipelineBoard,RJ as CrmDealCard,ZY as CrmDashboard,QJ as CreateDealModal};
1
+ import{web as fJ}from"@contractspec/lib.runtime-sandbox";var{generateId:kJ}=fJ;function c(J){return{id:J.id,projectId:J.projectId,name:J.name,value:J.value,currency:J.currency,pipelineId:J.pipelineId,stageId:J.stageId,status:J.status,contactId:J.contactId??void 0,companyId:J.companyId??void 0,ownerId:J.ownerId,expectedCloseDate:J.expectedCloseDate?new Date(J.expectedCloseDate):void 0,wonSource:J.wonSource??void 0,lostReason:J.lostReason??void 0,notes:J.notes??void 0,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)}}var PJ={name:"name",value:"value",status:"status",expectedCloseDate:"expectedCloseDate",updatedAt:"updatedAt"};function zX(J){async function Y(X){let{projectId:H,pipelineId:W,stageId:q,status:Z,ownerId:N,search:$,limit:f=20,offset:P=0,sortBy:U="value",sortDirection:F="desc"}=X,O="WHERE projectId = ?",B=[H];if(W)O+=" AND pipelineId = ?",B.push(W);if(q)O+=" AND stageId = ?",B.push(q);if(Z&&Z!=="all")O+=" AND status = ?",B.push(Z);if(N)O+=" AND ownerId = ?",B.push(N);if($)O+=" AND name LIKE ?",B.push(`%${$}%`);let j=(await J.query(`SELECT COUNT(*) as count FROM crm_deal ${O}`,B)).rows[0]?.count??0,y=(await J.query(`SELECT COALESCE(SUM(value), 0) as total FROM crm_deal ${O}`,B)).rows[0]?.total??0,_=PJ[U]??PJ.value,r=F==="asc"?"ASC":"DESC";return{deals:(await J.query(`SELECT * FROM crm_deal ${O} ORDER BY ${_} ${r} LIMIT ? OFFSET ?`,[...B,f,P])).rows.map(c),total:j,totalValue:y}}async function Q(X,H){let W=kJ("deal"),q=new Date().toISOString();await J.execute(`INSERT INTO crm_deal (id, projectId, pipelineId, stageId, name, value, currency, status, contactId, companyId, ownerId, expectedCloseDate, createdAt, updatedAt)
2
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[W,H.projectId,X.pipelineId,X.stageId,X.name,X.value,X.currency??"USD","OPEN",X.contactId??null,X.companyId??null,H.ownerId,X.expectedCloseDate?.toISOString()??null,q,q]);let Z=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[W])).rows;if(!Z[0])throw Error("Failed to create deal");return c(Z[0])}async function G(X){let H=new Date().toISOString();if(!(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows[0])throw Error("NOT_FOUND");if(!(await J.query("SELECT * FROM crm_stage WHERE id = ?",[X.stageId])).rows[0])throw Error("INVALID_STAGE");await J.execute("UPDATE crm_deal SET stageId = ?, updatedAt = ? WHERE id = ?",[X.stageId,H,X.dealId]);let Z=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return c(Z[0])}async function z(X){let H=new Date().toISOString();if(!(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows[0])throw Error("NOT_FOUND");await J.execute("UPDATE crm_deal SET status = 'WON', wonSource = ?, notes = ?, updatedAt = ? WHERE id = ?",[X.wonSource??null,X.notes??null,H,X.dealId]);let q=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return c(q[0])}async function V(X){let H=new Date().toISOString();if(!(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows[0])throw Error("NOT_FOUND");await J.execute("UPDATE crm_deal SET status = 'LOST', lostReason = ?, notes = ?, updatedAt = ? WHERE id = ?",[X.lostReason,X.notes??null,H,X.dealId]);let q=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return c(q[0])}async function A(X){let H=(await J.query("SELECT * FROM crm_deal WHERE projectId = ? AND pipelineId = ? AND status = 'OPEN' ORDER BY value DESC",[X.projectId,X.pipelineId])).rows,W=(await J.query("SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position",[X.pipelineId])).rows,q={};for(let Z of W)q[Z.id]=H.filter((N)=>N.stageId===Z.id).map(c);return q}async function K(X){return(await J.query("SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position",[X.pipelineId])).rows.map((W)=>({id:W.id,pipelineId:W.pipelineId,name:W.name,position:W.position}))}return{listDeals:Y,createDeal:Q,moveDeal:G,winDeal:z,loseDeal:V,getDealsByStage:A,getPipelineStages:K}}var d=[{id:"stage-1",name:"Lead",position:1,pipelineId:"pipeline-1"},{id:"stage-2",name:"Qualified",position:2,pipelineId:"pipeline-1"},{id:"stage-3",name:"Proposal",position:3,pipelineId:"pipeline-1"},{id:"stage-4",name:"Negotiation",position:4,pipelineId:"pipeline-1"},{id:"stage-5",name:"Closed",position:5,pipelineId:"pipeline-1"}],L=[{id:"deal-1",name:"Enterprise License - Acme Corp",value:75000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-3",status:"OPEN",contactId:"contact-1",companyId:"company-1",ownerId:"user-1",expectedCloseDate:new Date("2024-05-15T00:00:00Z"),createdAt:new Date("2024-02-01T10:00:00Z"),updatedAt:new Date("2024-04-10T14:30:00Z")},{id:"deal-2",name:"Startup Plan - TechStart Inc",value:12000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-2",status:"OPEN",contactId:"contact-2",companyId:"company-2",ownerId:"user-2",expectedCloseDate:new Date("2024-04-30T00:00:00Z"),createdAt:new Date("2024-03-15T09:00:00Z"),updatedAt:new Date("2024-04-08T11:15:00Z")},{id:"deal-3",name:"Professional Services - Global Ltd",value:45000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-4",status:"OPEN",contactId:"contact-3",companyId:"company-3",ownerId:"user-1",expectedCloseDate:new Date("2024-04-20T00:00:00Z"),createdAt:new Date("2024-01-20T08:00:00Z"),updatedAt:new Date("2024-04-12T16:45:00Z")},{id:"deal-4",name:"Annual Contract - SmallBiz Co",value:8500,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-1",status:"OPEN",contactId:"contact-4",companyId:"company-4",ownerId:"user-3",createdAt:new Date("2024-04-05T12:00:00Z"),updatedAt:new Date("2024-04-05T12:00:00Z")},{id:"deal-5",name:"Custom Integration - MegaCorp",value:125000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-5",status:"WON",contactId:"contact-5",companyId:"company-5",ownerId:"user-1",expectedCloseDate:new Date("2024-03-31T00:00:00Z"),createdAt:new Date("2023-11-10T10:00:00Z"),updatedAt:new Date("2024-03-28T09:00:00Z")},{id:"deal-6",name:"Pilot Project - NewCo",value:5000,currency:"USD",pipelineId:"pipeline-1",stageId:"stage-2",status:"LOST",contactId:"contact-6",companyId:"company-6",ownerId:"user-2",createdAt:new Date("2024-01-15T14:00:00Z"),updatedAt:new Date("2024-02-28T10:30:00Z")}],WX=[{id:"company-1",name:"Acme Corporation",domain:"acme.com",industry:"Technology",size:"1000-5000",website:"https://acme.com",createdAt:new Date("2024-01-01T00:00:00Z")},{id:"company-2",name:"TechStart Inc",domain:"techstart.io",industry:"Software",size:"10-50",website:"https://techstart.io",createdAt:new Date("2024-02-15T00:00:00Z")},{id:"company-3",name:"Global Ltd",domain:"global.com",industry:"Consulting",size:"500-1000",website:"https://global.com",createdAt:new Date("2023-12-01T00:00:00Z")}],UX=[{id:"contact-1",firstName:"John",lastName:"Smith",email:"john.smith@acme.com",phone:"+1-555-0101",title:"VP of Engineering",companyId:"company-1",createdAt:new Date("2024-01-05T00:00:00Z")},{id:"contact-2",firstName:"Sarah",lastName:"Johnson",email:"sarah@techstart.io",phone:"+1-555-0102",title:"CEO",companyId:"company-2",createdAt:new Date("2024-02-20T00:00:00Z")},{id:"contact-3",firstName:"Michael",lastName:"Brown",email:"michael.brown@global.com",phone:"+1-555-0103",title:"CTO",companyId:"company-3",createdAt:new Date("2023-12-10T00:00:00Z")}];async function t(J){let{pipelineId:Y,stageId:Q,status:G,ownerId:z,search:V,limit:A=20,offset:K=0}=J,X=[...L];if(Y)X=X.filter((Z)=>Z.pipelineId===Y);if(Q)X=X.filter((Z)=>Z.stageId===Q);if(G&&G!=="all")X=X.filter((Z)=>Z.status===G);if(z)X=X.filter((Z)=>Z.ownerId===z);if(V){let Z=V.toLowerCase();X=X.filter((N)=>N.name.toLowerCase().includes(Z))}X.sort((Z,N)=>N.value-Z.value);let H=X.length,W=X.reduce((Z,N)=>Z+N.value,0);return{deals:X.slice(K,K+A),total:H,totalValue:W}}async function EJ(J,Y){let Q=new Date,G={id:`deal-${Date.now()}`,name:J.name,value:J.value,currency:J.currency??"USD",pipelineId:J.pipelineId,stageId:J.stageId,status:"OPEN",contactId:J.contactId,companyId:J.companyId,ownerId:Y.ownerId,expectedCloseDate:J.expectedCloseDate,createdAt:Q,updatedAt:Q};return L.push(G),G}async function TJ(J){let Y=L.findIndex((V)=>V.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let Q=L[Y];if(!Q)throw Error("NOT_FOUND");if(!d.find((V)=>V.id===J.stageId))throw Error("INVALID_STAGE");let z={...Q,stageId:J.stageId,updatedAt:new Date};return L[Y]=z,z}async function BJ(J){let Y=L.findIndex((z)=>z.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let Q=L[Y];if(!Q)throw Error("NOT_FOUND");let G={...Q,status:"WON",updatedAt:new Date};return L[Y]=G,G}async function MJ(J){let Y=L.findIndex((z)=>z.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let Q=L[Y];if(!Q)throw Error("NOT_FOUND");let G={...Q,status:"LOST",updatedAt:new Date};return L[Y]=G,G}async function vJ(J){let Y=L.filter((G)=>G.pipelineId===J.pipelineId&&G.status==="OPEN"),Q={};for(let G of d)Q[G.id]=Y.filter((z)=>z.stageId===G.id);return Q}async function s(J){return d.filter((Y)=>Y.pipelineId===J.pipelineId)}import{jsx as e,jsxs as KJ}from"react/jsx-runtime";function yJ(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function RJ({deal:J,onClick:Y}){let Q=J.expectedCloseDate?Math.ceil((J.expectedCloseDate.getTime()-Date.now())/86400000):null;return KJ("div",{onClick:Y,className:"cursor-pointer rounded-lg border border-border bg-card p-3 shadow-sm transition-shadow hover:shadow-md",role:"button",tabIndex:0,onKeyDown:(G)=>{if(G.key==="Enter"||G.key===" ")Y?.()},children:[e("h4",{className:"font-medium leading-snug",children:J.name}),e("div",{className:"mt-2 font-semibold text-lg text-primary",children:yJ(J.value,J.currency)}),KJ("div",{className:"mt-3 flex items-center justify-between text-muted-foreground text-xs",children:[Q!==null&&e("span",{className:Q<0?"text-red-500":Q<=7?"text-yellow-600 dark:text-yellow-500":"",children:Q<0?`${Math.abs(Q)}d overdue`:Q===0?"Due today":`${Q}d left`}),e("span",{className:`rounded px-1.5 py-0.5 font-medium text-xs ${J.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":J.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:J.status})]})]})}import{useState as LJ}from"react";import{jsx as m,jsxs as x}from"react/jsx-runtime";function hJ(J){if(J>=1e6)return`$${(J/1e6).toFixed(1)}M`;if(J>=1000)return`$${(J/1000).toFixed(0)}K`;return`$${J}`}function JJ({dealsByStage:J,stages:Y,onDealClick:Q,onDealMove:G}){let[z,V]=LJ(null),A=[...Y].sort((X,H)=>X.position-H.position),K=(X,H)=>{G?.(X,H),V(null)};return m("div",{className:"flex gap-4 overflow-x-auto pb-4",children:A.map((X)=>{let H=J[X.id]??[],W=H.reduce((q,Z)=>q+Z.value,0);return x("div",{className:"flex w-72 flex-shrink-0 flex-col rounded-lg bg-muted/30",children:[x("div",{className:"flex items-center justify-between border-border border-b px-3 py-2",children:[x("div",{children:[m("h3",{className:"font-medium",children:X.name}),x("p",{className:"text-muted-foreground text-xs",children:[H.length," deals · ",hJ(W)]})]}),m("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",children:H.length})]}),m("div",{className:"flex flex-1 flex-col gap-2 p-2",children:H.length===0?m("div",{className:"flex h-24 items-center justify-center rounded-md border-2 border-muted-foreground/20 border-dashed text-muted-foreground text-xs",children:"No deals"}):H.map((q)=>x("div",{className:"group relative",children:[m(RJ,{deal:q,onClick:()=>Q?.(q.id)}),q.status==="OPEN"&&G&&x("div",{className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100",children:[m("button",{type:"button",onClick:(Z)=>{Z.stopPropagation(),V(z===q.id?null:q.id)},className:"flex h-6 w-6 items-center justify-center rounded border border-border bg-background text-xs shadow-sm hover:bg-muted",title:"Quick move",children:"➡️"}),z===q.id&&x("div",{className:"absolute top-7 right-0 z-20 min-w-[140px] rounded-lg border border-border bg-card py-1 shadow-lg",children:[m("p",{className:"px-3 py-1 font-medium text-muted-foreground text-xs",children:"Move to:"}),A.filter((Z)=>Z.id!==q.stageId).map((Z)=>m("button",{type:"button",onClick:(N)=>{N.stopPropagation(),K(q.id,Z.id)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-muted",children:Z.name},Z.id))]})]})]},q.id))})]},X.id)})})}import{useTemplateRuntime as IJ}from"@contractspec/lib.example-shared-ui";import{useCallback as bJ,useEffect as wJ,useMemo as DJ,useState as p}from"react";function g(J={}){let{handlers:Y,projectId:Q}=IJ(),{crm:G}=Y,[z,V]=p(null),[A,K]=p({}),[X,H]=p([]),[W,q]=p(!0),[Z,N]=p(null),[$,f]=p(0),P=J.pipelineId??"pipeline-1",U=J.pageIndex??$,F=J.pageSize??J.limit??50,[O]=J.sorting??[],B=O?.id==="deal"?"name":O?.id,I=O?O.desc?"desc":"asc":void 0,j=bJ(async()=>{q(!0),N(null);try{let[y,_,r]=await Promise.all([G.listDeals({projectId:Q,pipelineId:P,stageId:J.stageId,status:J.status==="all"?void 0:J.status,search:J.search,limit:F,offset:U*F,sortBy:B==="name"||B==="value"||B==="status"||B==="expectedCloseDate"||B==="updatedAt"?B:void 0,sortDirection:I}),G.getDealsByStage({projectId:Q,pipelineId:P}),G.getPipelineStages({pipelineId:P})]);V(y),K(_),H(r)}catch(y){N(y instanceof Error?y:Error("Unknown error"))}finally{q(!1)}},[G,Q,P,J.stageId,J.status,J.search,U,F,B,I]);wJ(()=>{j()},[j]);let a=DJ(()=>{if(!z)return null;let y=z.deals.filter((b)=>b.status==="OPEN"),_=z.deals.filter((b)=>b.status==="WON"),r=z.deals.filter((b)=>b.status==="LOST");return{total:z.total,totalValue:z.totalValue,openCount:y.length,openValue:y.reduce((b,qJ)=>b+qJ.value,0),wonCount:_.length,wonValue:_.reduce((b,qJ)=>b+qJ.value,0),lostCount:r.length}},[z]);return{data:z,dealsByStage:A,stages:X,loading:W,error:Z,stats:a,page:U+1,pageIndex:U,pageSize:F,refetch:j,nextPage:J.pageIndex===void 0?()=>f((y)=>y+1):void 0,prevPage:J.pageIndex===void 0?()=>U>0&&f((y)=>y-1):void 0}}import{useTemplateRuntime as mJ}from"@contractspec/lib.example-shared-ui";import{useCallback as XJ,useState as YJ}from"react";function GJ(J={}){let{handlers:Y,projectId:Q}=mJ(),{crm:G}=Y,[z,V]=YJ({loading:!1,error:null,data:null}),[A,K]=YJ({loading:!1,error:null,data:null}),[X,H]=YJ({loading:!1,error:null,data:null}),[W,q]=YJ({loading:!1,error:null,data:null}),Z=XJ(async(P)=>{V({loading:!0,error:null,data:null});try{let U=await G.createDeal(P,{projectId:Q,ownerId:"user-1"});return V({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to create deal");return V({loading:!1,error:F,data:null}),J.onError?.(F),null}},[G,Q,J]),N=XJ(async(P)=>{K({loading:!0,error:null,data:null});try{let U=await G.moveDeal(P);return K({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to move deal");return K({loading:!1,error:F,data:null}),J.onError?.(F),null}},[G,J]),$=XJ(async(P)=>{H({loading:!0,error:null,data:null});try{let U=await G.winDeal(P);return H({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to mark deal as won");return H({loading:!1,error:F,data:null}),J.onError?.(F),null}},[G,J]),f=XJ(async(P)=>{q({loading:!0,error:null,data:null});try{let U=await G.loseDeal(P);return q({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let F=U instanceof Error?U:Error("Failed to mark deal as lost");return q({loading:!1,error:F,data:null}),J.onError?.(F),null}},[G,J]);return{createDeal:Z,moveDeal:N,winDeal:$,loseDeal:f,createState:z,moveState:A,winState:X,loseState:W,isLoading:z.loading||A.loading||X.loading||W.loading}}import{Button as VJ,Input as HJ}from"@contractspec/lib.design-system";import{useState as u}from"react";import{jsx as M,jsxs as w}from"react/jsx-runtime";var CJ=["USD","EUR","GBP","CAD"],SJ="pipeline-1";function QJ({isOpen:J,onClose:Y,onSubmit:Q,stages:G,isLoading:z=!1}){let[V,A]=u(""),[K,X]=u(""),[H,W]=u("USD"),[q,Z]=u(G[0]?.id??""),[N,$]=u(""),[f,P]=u(null),U=async(F)=>{if(F.preventDefault(),P(null),!V.trim()){P("Deal name is required");return}let O=parseFloat(K);if(isNaN(O)||O<=0){P("Value must be a positive number");return}if(!q){P("Please select a pipeline stage");return}try{await Q({name:V.trim(),value:O,currency:H,pipelineId:SJ,stageId:q,expectedCloseDate:N?new Date(N):void 0}),A(""),X(""),W("USD"),Z(G[0]?.id??""),$(""),Y()}catch(B){P(B instanceof Error?B.message:"Failed to create deal")}};if(!J)return null;return w("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[M("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:Y,role:"button",tabIndex:0,onKeyDown:(F)=>{if(F.key==="Enter"||F.key===" ")Y()},"aria-label":"Close modal"}),w("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[M("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Deal"}),w("form",{onSubmit:U,className:"space-y-4",children:[w("div",{children:[M("label",{htmlFor:"deal-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Deal Name *"}),M(HJ,{id:"deal-name",value:V,onChange:(F)=>A(F.target.value),placeholder:"e.g., Enterprise License - Acme Corp",disabled:z})]}),w("div",{className:"flex gap-3",children:[w("div",{className:"flex-1",children:[M("label",{htmlFor:"deal-value",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Value *"}),M(HJ,{id:"deal-value",type:"number",min:"0",step:"0.01",value:K,onChange:(F)=>X(F.target.value),placeholder:"50000",disabled:z})]}),w("div",{className:"w-24",children:[M("label",{htmlFor:"deal-currency",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Currency"}),M("select",{id:"deal-currency",value:H,onChange:(F)=>W(F.target.value),disabled:z,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:CJ.map((F)=>M("option",{value:F,children:F},F))})]})]}),w("div",{children:[M("label",{htmlFor:"deal-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Pipeline Stage *"}),M("select",{id:"deal-stage",value:q,onChange:(F)=>Z(F.target.value),disabled:z,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:G.map((F)=>M("option",{value:F.id,children:F.name},F.id))})]}),w("div",{children:[M("label",{htmlFor:"deal-close-date",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Expected Close Date"}),M(HJ,{id:"deal-close-date",type:"date",value:N,onChange:(F)=>$(F.target.value),disabled:z})]}),f&&M("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:f}),w("div",{className:"flex justify-end gap-3 pt-2",children:[M(VJ,{type:"button",variant:"ghost",onPress:Y,disabled:z,children:"Cancel"}),M(VJ,{type:"submit",disabled:z,children:z?"Creating...":"Create Deal"})]})]})]})]})}import{Button as D}from"@contractspec/lib.design-system";import{useState as i}from"react";import{jsx as R,jsxs as E,Fragment as xJ}from"react/jsx-runtime";function jJ(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function zJ({isOpen:J,deal:Y,stages:Q,onClose:G,onWin:z,onLose:V,onMove:A,isLoading:K=!1}){let[X,H]=i("menu"),[W,q]=i(""),[Z,N]=i(""),[$,f]=i(""),[P,U]=i(""),[F,O]=i(null),B=()=>{H("menu"),q(""),N(""),f(""),U(""),O(null)},I=()=>{B(),G()},j=async()=>{if(!Y)return;O(null);try{await z({dealId:Y.id,wonSource:W.trim()||void 0,notes:$.trim()||void 0}),I()}catch(_){O(_ instanceof Error?_.message:"Failed to mark deal as won")}},a=async()=>{if(!Y)return;if(O(null),!Z.trim()){O("Please provide a reason for losing the deal");return}try{await V({dealId:Y.id,lostReason:Z.trim(),notes:$.trim()||void 0}),I()}catch(_){O(_ instanceof Error?_.message:"Failed to mark deal as lost")}},y=async()=>{if(!Y)return;if(O(null),!P){O("Please select a stage");return}if(P===Y.stageId){O("Deal is already in this stage");return}try{await A({dealId:Y.id,stageId:P}),I()}catch(_){O(_ instanceof Error?_.message:"Failed to move deal")}};if(!J||!Y)return null;return E("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[R("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:I,role:"button",tabIndex:0,onKeyDown:(_)=>{if(_.key==="Enter"||_.key===" ")I()},"aria-label":"Close modal"}),E("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[E("div",{className:"mb-4 border-border border-b pb-4",children:[R("h2",{className:"font-semibold text-xl",children:Y.name}),R("p",{className:"font-medium text-lg text-primary",children:jJ(Y.value,Y.currency)}),R("span",{className:`mt-2 inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${Y.status==="WON"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":Y.status==="LOST"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:Y.status})]}),X==="menu"&&E("div",{className:"space-y-3",children:[Y.status==="OPEN"&&E(xJ,{children:[E(D,{className:"w-full justify-start",variant:"ghost",onPress:()=>H("win"),children:[R("span",{className:"mr-2",children:"\uD83C\uDFC6"})," Mark as Won"]}),E(D,{className:"w-full justify-start",variant:"ghost",onPress:()=>H("lose"),children:[R("span",{className:"mr-2",children:"❌"})," Mark as Lost"]}),E(D,{className:"w-full justify-start",variant:"ghost",onPress:()=>{U(Y.stageId),H("move")},children:[R("span",{className:"mr-2",children:"➡️"})," Move to Stage"]})]}),Y.status!=="OPEN"&&E("p",{className:"py-4 text-center text-muted-foreground",children:["This deal is already ",Y.status.toLowerCase(),". No actions available."]}),R("div",{className:"border-border border-t pt-3",children:R(D,{className:"w-full",variant:"outline",onPress:I,children:"Close"})})]}),X==="win"&&E("div",{className:"space-y-4",children:[E("div",{children:[R("label",{htmlFor:"won-source",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"How did you win this deal?"}),E("select",{id:"won-source",value:W,onChange:(_)=>q(_.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[R("option",{value:"",children:"Select a source..."}),R("option",{value:"referral",children:"Referral"}),R("option",{value:"cold_outreach",children:"Cold Outreach"}),R("option",{value:"inbound",children:"Inbound Lead"}),R("option",{value:"upsell",children:"Upsell"}),R("option",{value:"other",children:"Other"})]})]}),E("div",{children:[R("label",{htmlFor:"win-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),R("textarea",{id:"win-notes",value:$,onChange:(_)=>f(_.target.value),placeholder:"Any additional notes about the win...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),F&&R("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:F}),E("div",{className:"flex justify-end gap-3 pt-2",children:[R(D,{variant:"ghost",onPress:()=>H("menu"),disabled:K,children:"Back"}),R(D,{onPress:j,disabled:K,children:K?"Processing...":"\uD83C\uDFC6 Confirm Win"})]})]}),X==="lose"&&E("div",{className:"space-y-4",children:[E("div",{children:[R("label",{htmlFor:"lost-reason",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Why was this deal lost? *"}),E("select",{id:"lost-reason",value:Z,onChange:(_)=>N(_.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:[R("option",{value:"",children:"Select a reason..."}),R("option",{value:"price",children:"Price too high"}),R("option",{value:"competitor",children:"Lost to competitor"}),R("option",{value:"no_budget",children:"No budget"}),R("option",{value:"no_decision",children:"No decision made"}),R("option",{value:"timing",children:"Bad timing"}),R("option",{value:"product_fit",children:"Product not a fit"}),R("option",{value:"other",children:"Other"})]})]}),E("div",{children:[R("label",{htmlFor:"lose-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),R("textarea",{id:"lose-notes",value:$,onChange:(_)=>f(_.target.value),placeholder:"Any additional details...",rows:3,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"})]}),F&&R("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:F}),E("div",{className:"flex justify-end gap-3 pt-2",children:[R(D,{variant:"ghost",onPress:()=>H("menu"),disabled:K,children:"Back"}),R(D,{variant:"destructive",onPress:a,disabled:K,children:K?"Processing...":"❌ Confirm Loss"})]})]}),X==="move"&&E("div",{className:"space-y-4",children:[E("div",{children:[R("label",{htmlFor:"move-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Move to Stage"}),R("select",{id:"move-stage",value:P,onChange:(_)=>U(_.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",children:Q.map((_)=>E("option",{value:_.id,children:[_.name,_.id===Y.stageId?" (current)":""]},_.id))})]}),F&&R("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:F}),E("div",{className:"flex justify-end gap-3 pt-2",children:[R(D,{variant:"ghost",onPress:()=>H("menu"),disabled:K,children:"Back"}),R(D,{onPress:y,disabled:K,children:K?"Moving...":"➡️ Move Deal"})]})]})]})]})}import{Button as l,DataTable as gJ,DataTableToolbar as cJ,LoaderBlock as pJ}from"@contractspec/lib.design-system";import{useContractTable as uJ}from"@contractspec/lib.presentation-runtime-react";import{Badge as iJ}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as n,VStack as FJ}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as h}from"@contractspec/lib.ui-kit-web/ui/text";import*as o from"react";import{jsx as T,jsxs as C}from"react/jsx-runtime";function rJ(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function dJ(J){switch(J){case"WON":return"default";case"LOST":return"destructive";case"STALE":return"outline";default:return"secondary"}}function lJ({value:J,onChange:Y}){return C(n,{gap:"sm",className:"flex-wrap",children:[T(l,{variant:J==="all"?"secondary":"outline",size:"sm",onPress:()=>Y("all"),children:"All Deals"}),T(l,{variant:J==="OPEN"?"secondary":"outline",size:"sm",onPress:()=>Y("OPEN"),children:"Open Only"}),T(l,{variant:J==="WON"?"secondary":"outline",size:"sm",onPress:()=>Y("WON"),children:"Won Only"}),T(l,{variant:J==="LOST"?"secondary":"outline",size:"sm",onPress:()=>Y("LOST"),children:"Lost Only"})]})}function nJ({deals:J,totalItems:Y,pageIndex:Q,pageSize:G,sorting:z,search:V,status:A,loading:K,onSortingChange:X,onPaginationChange:H,onSearchChange:W,onStatusChange:q,onDealClick:Z}){let N=uJ({data:J,columns:[{id:"deal",header:"Deal",label:"Deal",accessor:($)=>$.name,cell:({item:$})=>C(FJ,{gap:"xs",children:[T(h,{className:"font-medium text-sm",children:$.name}),T(h,{className:"text-muted-foreground text-xs",children:$.companyId??"Unassigned company"})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"value",header:"Value",label:"Value",accessorKey:"value",cell:({item:$})=>rJ($.value,$.currency),align:"right",size:140,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:$})=>T(iJ,{variant:dJ($),children:String($)}),size:130,canSort:!0,canHide:!0,canPin:!0,canResize:!0},{id:"expectedCloseDate",header:"Expected Close",label:"Expected Close",accessor:($)=>$.expectedCloseDate?.toISOString()??"",cell:({item:$})=>$.expectedCloseDate?.toLocaleDateString()??"Not scheduled",size:170,canSort:!0,canHide:!0,canResize:!0},{id:"updatedAt",header:"Updated",label:"Updated",accessor:($)=>$.updatedAt.toISOString(),cell:({item:$})=>$.updatedAt.toLocaleDateString(),size:140,canSort:!0,canHide:!0,canResize:!0},{id:"actions",header:"Actions",label:"Actions",accessor:($)=>$.id,cell:({item:$})=>T(l,{variant:"ghost",size:"sm",onPress:()=>Z?.($.id),children:"Actions"}),size:120,canSort:!1,canHide:!1,canPin:!1,canResize:!1}],executionMode:"server",selectionMode:"multiple",totalItems:Y,state:{sorting:z,pagination:{pageIndex:Q,pageSize:G}},onSortingChange:X,onPaginationChange:H,initialState:{columnVisibility:{updatedAt:!1},columnPinning:{left:["deal","status"],right:[]}},renderExpandedContent:($)=>C(FJ,{gap:"sm",className:"py-2",children:[C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Owner"}),T(h,{className:"text-muted-foreground text-sm",children:$.ownerId})]}),C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Contact"}),T(h,{className:"text-muted-foreground text-sm",children:$.contactId??"No linked contact"})]}),$.wonSource?C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Won Source"}),T(h,{className:"text-muted-foreground text-sm",children:$.wonSource})]}):null,$.lostReason?C(n,{justify:"between",children:[T(h,{className:"font-medium text-sm",children:"Lost Reason"}),T(h,{className:"text-muted-foreground text-sm",children:$.lostReason})]}):null,$.notes?C(FJ,{gap:"xs",children:[T(h,{className:"font-medium text-sm",children:"Notes"}),T(h,{className:"text-muted-foreground text-sm",children:$.notes})]}):null]}),getCanExpand:()=>!0});return T(gJ,{controller:N,title:"All Deals",description:"Server-mode table using the shared ContractSpec controller.",loading:K,toolbar:T(cJ,{controller:N,searchPlaceholder:"Search deals, companies, contacts, or notes",searchValue:V,onSearchChange:W,activeChips:A==="all"?[]:[{key:"status",label:`Status: ${A}`,onRemove:()=>q("all")}],onClearAll:()=>{W(""),q("all")},actionsStart:lJ({value:A,onChange:q}),actionsEnd:C(h,{className:"text-muted-foreground text-sm",children:[Y," total deals"]})}),footer:`Page ${N.pageIndex+1} of ${N.pageCount}`,emptyState:T("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No deals found"})})}function _J({onDealClick:J}){let[Y,Q]=o.useState([{id:"value",desc:!0}]),[G,z]=o.useState({pageIndex:0,pageSize:3}),[V,A]=o.useState(""),[K,X]=o.useState("all"),{data:H,loading:W}=g({pageIndex:G.pageIndex,pageSize:G.pageSize,search:V,status:K,sorting:Y});if(W&&!H)return T(pJ,{label:"Loading deals..."});return T(nJ,{deals:H?.deals??[],totalItems:H?.total??0,pageIndex:G.pageIndex,pageSize:G.pageSize,sorting:Y,search:V,status:K,loading:W,onSortingChange:(q)=>{Q(q),z((Z)=>({...Z,pageIndex:0}))},onPaginationChange:z,onSearchChange:(q)=>{A(q),z((Z)=>({...Z,pageIndex:0}))},onStatusChange:(q)=>{X(q),z((Z)=>({...Z,pageIndex:0}))},onDealClick:J})}import{Button as oJ,ErrorState as aJ,LoaderBlock as tJ,StatCard as ZJ,StatCardGroup as sJ,Tabs as eJ,TabsContent as WJ,TabsList as JX,TabsTrigger as UJ}from"@contractspec/lib.design-system";import{useCallback as AJ,useState as NJ}from"react";import{jsx as k,jsxs as v}from"react/jsx-runtime";function $J(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function YY(){let[J,Y]=NJ(!1),[Q,G]=NJ(null),[z,V]=NJ(!1),{data:A,dealsByStage:K,stages:X,loading:H,error:W,stats:q,refetch:Z}=g(),N=GJ({onSuccess:()=>{Z()}}),$=AJ((P)=>{let U=K?Object.values(K).flat().find((F)=>F.id===P):null;if(U)G(U),V(!0)},[K]),f=AJ(async(P,U)=>{await N.moveDeal({dealId:P,stageId:U})},[N]);if(H&&!A)return k(tJ,{label:"Loading CRM..."});if(W)return k(aJ,{title:"Failed to load CRM",description:W.message,onRetry:Z,retryLabel:"Retry"});return v("div",{className:"space-y-6",children:[v("div",{className:"flex items-center justify-between",children:[k("h2",{className:"font-bold text-2xl",children:"CRM Pipeline"}),v(oJ,{onClick:()=>Y(!0),children:[k("span",{className:"mr-2",children:"+"})," Create Deal"]})]}),q&&v(sJ,{children:[k(ZJ,{label:"Total Pipeline",value:$J(q.totalValue),hint:`${q.total} deals`}),k(ZJ,{label:"Open Deals",value:$J(q.openValue),hint:`${q.openCount} active`}),k(ZJ,{label:"Won",value:$J(q.wonValue),hint:`${q.wonCount} closed`}),k(ZJ,{label:"Lost",value:q.lostCount,hint:"deals lost"})]}),v(eJ,{defaultValue:"pipeline",className:"w-full",children:[v(JX,{children:[v(UJ,{value:"pipeline",children:[k("span",{className:"mr-2",children:"\uD83D\uDCCA"}),"Pipeline"]}),v(UJ,{value:"list",children:[k("span",{className:"mr-2",children:"\uD83D\uDCCB"}),"All Deals"]}),v(UJ,{value:"metrics",children:[k("span",{className:"mr-2",children:"\uD83D\uDCC8"}),"Metrics"]})]}),k(WJ,{value:"pipeline",className:"min-h-[400px]",children:k(JJ,{dealsByStage:K,stages:X,onDealClick:$,onDealMove:f})}),k(WJ,{value:"list",className:"min-h-[400px]",children:k(_J,{onDealClick:$})}),k(WJ,{value:"metrics",className:"min-h-[400px]",children:k(XX,{stats:q})})]}),k(QJ,{isOpen:J,onClose:()=>Y(!1),onSubmit:async(P)=>{await N.createDeal(P)},stages:X,isLoading:N.createState.loading}),k(zJ,{isOpen:z,deal:Q,stages:X,onClose:()=>{V(!1),G(null)},onWin:async(P)=>{await N.winDeal(P)},onLose:async(P)=>{await N.loseDeal(P)},onMove:async(P)=>{await N.moveDeal(P),Z()},isLoading:N.isLoading})]})}function XX({stats:J}){if(!J)return null;return k("div",{className:"space-y-6",children:v("div",{className:"rounded-xl border border-border bg-card p-6",children:[k("h3",{className:"mb-4 font-semibold text-lg",children:"Pipeline Overview"}),v("dl",{className:"grid gap-4 sm:grid-cols-3",children:[v("div",{children:[k("dt",{className:"text-muted-foreground text-sm",children:"Win Rate"}),v("dd",{className:"font-semibold text-2xl",children:[J.total>0?(J.wonCount/J.total*100).toFixed(0):0,"%"]})]}),v("div",{children:[k("dt",{className:"text-muted-foreground text-sm",children:"Avg Deal Size"}),k("dd",{className:"font-semibold text-2xl",children:$J(J.total>0?J.totalValue/J.total:0)})]}),v("div",{children:[k("dt",{className:"text-muted-foreground text-sm",children:"Conversion"}),v("dd",{className:"font-semibold text-2xl",children:[J.wonCount," / ",J.total]})]})]})]})})}var YX={overlayId:"crm-pipeline.demo-user",version:"1.0.0",description:"Demo mode with sample data",appliesTo:{feature:"crm-pipeline",role:"demo"},modifications:[{type:"hideField",field:"importButton",reason:"Not available in demo"},{type:"hideField",field:"exportButton",reason:"Not available in demo"},{type:"addBadge",position:"header",label:"Demo Mode",variant:"warning"}]},ZX={overlayId:"crm-pipeline.sales-rep",version:"1.0.0",description:"Sales rep focused view",appliesTo:{feature:"crm-pipeline",role:"sales-rep"},modifications:[{type:"hideField",field:"teamMetrics",reason:"Team metrics for managers only"},{type:"hideField",field:"pipelineSettings",reason:"Admin only"},{type:"renameLabel",field:"deals",newLabel:"My Deals"}]},WY=[YX,ZX];function S(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0}).format(J)}var $X={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="PipelineKanbanView")throw Error("crmPipelineMarkdownRenderer: not PipelineKanbanView");let Q="pipeline-1",[G,z]=await Promise.all([t({pipelineId:Q,limit:50}),s({pipelineId:Q})]),V=G.deals,A=z,K={};for(let H of A)K[H.id]=V.filter((W)=>W.stageId===H.id&&W.status==="OPEN");let X=["# CRM Pipeline","",`**Total Value**: ${S(G.totalValue)}`,`**Total Deals**: ${G.total}`,""];for(let H of A.sort((W,q)=>W.position-q.position)){let W=K[H.id]??[],q=W.reduce((Z,N)=>Z+N.value,0);if(X.push(`## ${H.name}`),X.push(`_${W.length} deals · ${S(q)}_`),X.push(""),W.length===0)X.push("_No deals_");else for(let Z of W)X.push(`- **${Z.name}** - ${S(Z.value,Z.currency)}`);X.push("")}return{mimeType:"text/markdown",body:X.join(`
3
+ `)}}},qX={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="CrmDashboard")throw Error("crmDashboardMarkdownRenderer: not CrmDashboard");let Q="pipeline-1",[G,z]=await Promise.all([t({pipelineId:Q,limit:100}),s({pipelineId:Q})]),V=G.deals,A=z,K=V.filter(($)=>$.status==="OPEN"),X=V.filter(($)=>$.status==="WON"),H=V.filter(($)=>$.status==="LOST"),W=K.reduce(($,f)=>$+f.value,0),q=X.reduce(($,f)=>$+f.value,0),Z=["# CRM Dashboard","","> Sales pipeline overview and key metrics","","## Summary","","| Metric | Value |","|--------|-------|",`| Total Deals | ${G.total} |`,`| Pipeline Value | ${S(G.totalValue)} |`,`| Open Deals | ${K.length} (${S(W)}) |`,`| Won Deals | ${X.length} (${S(q)}) |`,`| Lost Deals | ${H.length} |`,"","## Pipeline Stages",""];Z.push("| Stage | Deals | Value |"),Z.push("|-------|-------|-------|");for(let $ of A.sort((f,P)=>f.position-P.position)){let f=K.filter((U)=>U.stageId===$.id),P=f.reduce((U,F)=>U+F.value,0);Z.push(`| ${$.name} | ${f.length} | ${S(P)} |`)}Z.push(""),Z.push("## Recent Deals"),Z.push("");let N=V.slice(0,10);if(N.length===0)Z.push("_No deals yet._");else{Z.push("| Deal | Value | Stage | Status |"),Z.push("|------|-------|-------|--------|");for(let $ of N){let f=A.find((P)=>P.id===$.stageId);Z.push(`| ${$.name} | ${S($.value,$.currency)} | ${f?.name??"-"} | ${$.status} |`)}}return{mimeType:"text/markdown",body:Z.join(`
4
+ `)}}};import{jsx as OJ}from"react/jsx-runtime";function GX(){let{dealsByStage:J,stages:Y}=g();return OJ(JJ,{dealsByStage:J,stages:Y})}var HX={target:"react",render:async(J,Y)=>{if(J.source.type!=="component")throw Error("Invalid source type");if(J.source.componentKey!=="CrmPipelineView")throw Error(`Unknown component: ${J.source.componentKey}`);return OJ(GX,{})}};export{GJ as useDealMutations,g as useDealList,ZX as crmSalesRepOverlay,HX as crmPipelineReactRenderer,$X as crmPipelineMarkdownRenderer,WY as crmOverlays,YX as crmDemoOverlay,qX as crmDashboardMarkdownRenderer,zJ as DealActionsModal,JJ as CrmPipelineBoard,RJ as CrmDealCard,YY as CrmDashboard,QJ as CreateDealModal};