@contractspec/example.crm-pipeline 3.7.19 → 3.7.22

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.
Files changed (42) hide show
  1. package/.turbo/turbo-build.log +32 -32
  2. package/CHANGELOG.md +62 -0
  3. package/dist/browser/crm-pipeline.feature.js +1 -1
  4. package/dist/browser/example.js +1 -1
  5. package/dist/browser/index.js +5 -5
  6. package/dist/browser/ui/CrmDashboard.js +1 -1
  7. package/dist/browser/ui/hooks/index.js +1 -1
  8. package/dist/browser/ui/hooks/useDealList.js +1 -1
  9. package/dist/browser/ui/index.js +4 -4
  10. package/dist/browser/ui/renderers/index.js +3 -3
  11. package/dist/browser/ui/renderers/pipeline.renderer.js +1 -1
  12. package/dist/browser/ui/tables/DealListTab.js +1 -1
  13. package/dist/crm-pipeline.feature.js +1 -1
  14. package/dist/example.d.ts +3 -2
  15. package/dist/example.js +1 -1
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.js +5 -5
  18. package/dist/node/crm-pipeline.feature.js +1 -1
  19. package/dist/node/example.js +1 -1
  20. package/dist/node/index.js +5 -5
  21. package/dist/node/ui/CrmDashboard.js +1 -1
  22. package/dist/node/ui/hooks/index.js +1 -1
  23. package/dist/node/ui/hooks/useDealList.js +1 -1
  24. package/dist/node/ui/index.js +4 -4
  25. package/dist/node/ui/renderers/index.js +3 -3
  26. package/dist/node/ui/renderers/pipeline.renderer.js +1 -1
  27. package/dist/node/ui/tables/DealListTab.js +1 -1
  28. package/dist/ui/CrmDashboard.js +1 -1
  29. package/dist/ui/hooks/index.js +1 -1
  30. package/dist/ui/hooks/useDealList.js +1 -1
  31. package/dist/ui/index.js +4 -4
  32. package/dist/ui/renderers/index.js +3 -3
  33. package/dist/ui/renderers/pipeline.renderer.js +1 -1
  34. package/dist/ui/tables/DealListTab.d.ts +5 -1
  35. package/dist/ui/tables/DealListTab.js +1 -1
  36. package/package.json +11 -11
  37. package/src/crm-pipeline.feature.ts +1 -1
  38. package/src/example.ts +15 -26
  39. package/src/index.ts +1 -0
  40. package/src/ui/hooks/useDealList.ts +1 -1
  41. package/src/ui/tables/DealListTab.smoke.test.tsx +70 -5
  42. package/src/ui/tables/DealListTab.tsx +96 -8
@@ -1,4 +1,4 @@
1
- import{defineFeature as kX}from"@contractspec/lib.contracts-spec";var jY=kX({meta:{key:"crm-pipeline",title:"CRM Pipeline",description:"CRM and sales pipeline management with deals, contacts, and companies",domain:"crm",owners:["@crm-team"],tags:["crm","sales","pipeline","deals"],stability:"experimental",version:"1.0.0"},operations:[{key:"crm.deal.create",version:"1.0.0"},{key:"crm.deal.move",version:"1.0.0"},{key:"crm.deal.win",version:"1.0.0"},{key:"crm.deal.lose",version:"1.0.0"},{key:"crm.deal.list",version:"1.0.0"}],events:[{key:"deal.created",version:"1.0.0"},{key:"deal.moved",version:"1.0.0"},{key:"deal.won",version:"1.0.0"},{key:"deal.lost",version:"1.0.0"},{key:"contact.created",version:"1.0.0"},{key:"task.completed",version:"1.0.0"}],presentations:[{key:"crm.dashboard",version:"1.0.0"},{key:"crm.pipeline.kanban",version:"1.0.0"},{key:"crm.deal.viewList",version:"1.0.0"},{key:"crm.deal.detail",version:"1.0.0"},{key:"crm.deal.card",version:"1.0.0"},{key:"crm.pipeline.metrics",version:"1.0.0"}],opToPresentation:[{op:{key:"crm.deal.list",version:"1.0.0"},pres:{key:"crm.pipeline.kanban",version:"1.0.0"}},{op:{key:"crm.deal.move",version:"1.0.0"},pres:{key:"crm.pipeline.kanban",version:"1.0.0"}}],presentationsTargets:[{key:"crm.dashboard",version:"1.0.0",targets:["react","markdown"]},{key:"crm.pipeline.kanban",version:"1.0.0",targets:["react","markdown"]},{key:"crm.deal.viewList",version:"1.0.0",targets:["react","markdown","application/json"]},{key:"crm.pipeline.metrics",version:"1.0.0",targets:["react","markdown"]}],capabilities:{requires:[{key:"identity",version:"1.0.0"},{key:"audit-trail",version:"1.0.0"},{key:"notifications",version:"1.0.0"}]},telemetry:[{key:"crm-pipeline.telemetry",version:"1.0.0"}],docs:["docs.examples.crm-pipeline.goal","docs.examples.crm-pipeline.usage","docs.examples.crm-pipeline.reference","docs.examples.crm-pipeline.constraints"]});import{defineEnum as tJ}from"@contractspec/lib.schema";var EJ=tJ("DealStatus",["OPEN","WON","LOST","STALE"]),FJ=tJ("DealStatusFilter",["OPEN","WON","LOST","all"]);import{defineSchemaModel as m,ScalarTypeEnum as K}from"@contractspec/lib.schema";var g=m({name:"Deal",description:"A deal in the CRM pipeline",fields:{id:{type:K.String_unsecure(),isOptional:!1},name:{type:K.String_unsecure(),isOptional:!1},value:{type:K.Float_unsecure(),isOptional:!1},currency:{type:K.String_unsecure(),isOptional:!1},pipelineId:{type:K.String_unsecure(),isOptional:!1},stageId:{type:K.String_unsecure(),isOptional:!1},status:{type:EJ,isOptional:!1},contactId:{type:K.String_unsecure(),isOptional:!0},companyId:{type:K.String_unsecure(),isOptional:!0},ownerId:{type:K.String_unsecure(),isOptional:!1},expectedCloseDate:{type:K.DateTime(),isOptional:!0},createdAt:{type:K.DateTime(),isOptional:!1},updatedAt:{type:K.DateTime(),isOptional:!1}}}),QJ=m({name:"CreateDealInput",description:"Input for creating a deal",fields:{name:{type:K.NonEmptyString(),isOptional:!1},value:{type:K.Float_unsecure(),isOptional:!1},currency:{type:K.String_unsecure(),isOptional:!0},pipelineId:{type:K.String_unsecure(),isOptional:!1},stageId:{type:K.String_unsecure(),isOptional:!1},contactId:{type:K.String_unsecure(),isOptional:!0},companyId:{type:K.String_unsecure(),isOptional:!0},expectedCloseDate:{type:K.DateTime(),isOptional:!0}}}),zJ=m({name:"MoveDealInput",description:"Input for moving a deal to another stage",fields:{dealId:{type:K.String_unsecure(),isOptional:!1},stageId:{type:K.String_unsecure(),isOptional:!1},position:{type:K.Int_unsecure(),isOptional:!0}}}),WJ=m({name:"DealMovedPayload",fields:{dealId:{type:K.String_unsecure(),isOptional:!1},fromStage:{type:K.String_unsecure(),isOptional:!1},toStage:{type:K.String_unsecure(),isOptional:!1}}}),UJ=m({name:"WinDealInput",description:"Input for marking a deal as won",fields:{dealId:{type:K.String_unsecure(),isOptional:!1},wonSource:{type:K.String_unsecure(),isOptional:!0},notes:{type:K.String_unsecure(),isOptional:!0}}}),KJ=m({name:"DealWonPayload",fields:{dealId:{type:K.String_unsecure(),isOptional:!1},value:{type:K.Float_unsecure(),isOptional:!1}}}),NJ=m({name:"LoseDealInput",description:"Input for marking a deal as lost",fields:{dealId:{type:K.String_unsecure(),isOptional:!1},lostReason:{type:K.String_unsecure(),isOptional:!1},notes:{type:K.String_unsecure(),isOptional:!0}}}),VJ=m({name:"DealLostPayload",fields:{dealId:{type:K.String_unsecure(),isOptional:!1},reason:{type:K.String_unsecure(),isOptional:!1}}}),_J=m({name:"ListDealsInput",description:"Input for listing deals",fields:{pipelineId:{type:K.String_unsecure(),isOptional:!0},stageId:{type:K.String_unsecure(),isOptional:!0},status:{type:FJ,isOptional:!0},ownerId:{type:K.String_unsecure(),isOptional:!0},search:{type:K.String_unsecure(),isOptional:!0},limit:{type:K.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:K.Int_unsecure(),isOptional:!0,defaultValue:0}}}),PJ=m({name:"ListDealsOutput",description:"Output for listing deals",fields:{deals:{type:g,isArray:!0,isOptional:!1},total:{type:K.Int_unsecure(),isOptional:!1},totalValue:{type:K.Float_unsecure(),isOptional:!1}}});import{defineCommand as RJ,defineQuery as vX}from"@contractspec/lib.contracts-spec/operations";var XJ=["@example.crm-pipeline"],aJ=RJ({meta:{key:"crm.deal.create",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","create"],description:"Create a new deal in the pipeline.",goal:"Allow sales reps to create new opportunities.",context:"Deal creation UI, quick add."},io:{input:QJ,output:g},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.created",version:"1.0.0",when:"Deal is created",payload:g}],audit:["deal.created"]},acceptance:{scenarios:[{key:"create-deal-happy-path",given:["User is authenticated"],when:["User creates a deal with valid data"],then:["Deal is created","DealCreated event is emitted"]}],examples:[{key:"create-basic-deal",input:{title:"Big Corp Q3 License",stageId:"stage-lead",value:50000,companyId:"comp-123"},output:{id:"deal-789",title:"Big Corp Q3 License",status:"open"}}]}}),eJ=RJ({meta:{key:"crm.deal.move",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","move","kanban"],description:"Move a deal to a different stage.",goal:"Allow drag-and-drop stage movement in Kanban.",context:"Pipeline Kanban view."},io:{input:zJ,output:g},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.moved",version:"1.0.0",when:"Deal stage changed",payload:WJ}],audit:["deal.moved"]},acceptance:{scenarios:[{key:"move-deal-happy-path",given:["Deal exists in stage A"],when:["User moves deal to stage B"],then:["Deal stage is updated","DealMoved event is emitted"]}],examples:[{key:"move-to-negotiation",input:{dealId:"deal-789",targetStageId:"stage-negotiation"},output:{id:"deal-789",stageId:"stage-negotiation",movedAt:"2025-01-15T10:00:00Z"}}]}}),JX=RJ({meta:{key:"crm.deal.win",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","won"],description:"Mark a deal as won.",goal:"Close a deal as successful.",context:"Deal closing flow."},io:{input:UJ,output:g},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.won",version:"1.0.0",when:"Deal is won",payload:KJ}],audit:["deal.won"]},acceptance:{scenarios:[{key:"win-deal-happy-path",given:["Deal is open"],when:["User marks deal as won"],then:["Deal status becomes WON","DealWon event is emitted"]}],examples:[{key:"mark-won",input:{dealId:"deal-789",actualValue:52000,note:"Signed contract attached"},output:{id:"deal-789",status:"won",closedAt:"2025-01-20T14:30:00Z"}}]}}),XX=RJ({meta:{key:"crm.deal.lose",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","lost"],description:"Mark a deal as lost.",goal:"Close a deal as unsuccessful.",context:"Deal closing flow."},io:{input:NJ,output:g},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.lost",version:"1.0.0",when:"Deal is lost",payload:VJ}],audit:["deal.lost"]},acceptance:{scenarios:[{key:"lose-deal-happy-path",given:["Deal is open"],when:["User marks deal as lost"],then:["Deal status becomes LOST","DealLost event is emitted"]}],examples:[{key:"mark-lost",input:{dealId:"deal-789",reason:"competitor",note:"Went with cheaper option"},output:{id:"deal-789",status:"lost",closedAt:"2025-01-21T09:00:00Z"}}]}}),YX=vX({meta:{key:"crm.deal.list",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","list"],description:"List deals with filters.",goal:"Show pipeline, deal lists, dashboards.",context:"Pipeline view, deal list."},io:{input:_J,output:PJ},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-deals-happy-path",given:["User has access to deals"],when:["User lists deals"],then:["List of deals is returned"]}],examples:[{key:"list-filter-stage",input:{stageId:"stage-lead",limit:20},output:{items:[],total:5,hasMore:!1}}]}});import{registerDocBlocks as MX}from"@contractspec/lib.contracts-spec/docs";var LX=[{id:"docs.examples.crm-pipeline.goal",title:"CRM Pipeline — Goal",summary:"Deals, stages, contacts, companies, and tasks with auditable stage movement.",kind:"goal",visibility:"public",route:"/docs/examples/crm-pipeline/goal",tags:["crm","goal"],body:`## Why it matters
1
+ import{defineFeature as MX}from"@contractspec/lib.contracts-spec/features";var fY=MX({meta:{key:"crm-pipeline",title:"CRM Pipeline",description:"CRM and sales pipeline management with deals, contacts, and companies",domain:"crm",owners:["@crm-team"],tags:["crm","sales","pipeline","deals"],stability:"experimental",version:"1.0.0"},operations:[{key:"crm.deal.create",version:"1.0.0"},{key:"crm.deal.move",version:"1.0.0"},{key:"crm.deal.win",version:"1.0.0"},{key:"crm.deal.lose",version:"1.0.0"},{key:"crm.deal.list",version:"1.0.0"}],events:[{key:"deal.created",version:"1.0.0"},{key:"deal.moved",version:"1.0.0"},{key:"deal.won",version:"1.0.0"},{key:"deal.lost",version:"1.0.0"},{key:"contact.created",version:"1.0.0"},{key:"task.completed",version:"1.0.0"}],presentations:[{key:"crm.dashboard",version:"1.0.0"},{key:"crm.pipeline.kanban",version:"1.0.0"},{key:"crm.deal.viewList",version:"1.0.0"},{key:"crm.deal.detail",version:"1.0.0"},{key:"crm.deal.card",version:"1.0.0"},{key:"crm.pipeline.metrics",version:"1.0.0"}],opToPresentation:[{op:{key:"crm.deal.list",version:"1.0.0"},pres:{key:"crm.pipeline.kanban",version:"1.0.0"}},{op:{key:"crm.deal.move",version:"1.0.0"},pres:{key:"crm.pipeline.kanban",version:"1.0.0"}}],presentationsTargets:[{key:"crm.dashboard",version:"1.0.0",targets:["react","markdown"]},{key:"crm.pipeline.kanban",version:"1.0.0",targets:["react","markdown"]},{key:"crm.deal.viewList",version:"1.0.0",targets:["react","markdown","application/json"]},{key:"crm.pipeline.metrics",version:"1.0.0",targets:["react","markdown"]}],capabilities:{requires:[{key:"identity",version:"1.0.0"},{key:"audit-trail",version:"1.0.0"},{key:"notifications",version:"1.0.0"}]},telemetry:[{key:"crm-pipeline.telemetry",version:"1.0.0"}],docs:["docs.examples.crm-pipeline.goal","docs.examples.crm-pipeline.usage","docs.examples.crm-pipeline.reference","docs.examples.crm-pipeline.constraints"]});import{defineEnum as aJ}from"@contractspec/lib.schema";var yJ=aJ("DealStatus",["OPEN","WON","LOST","STALE"]),zJ=aJ("DealStatusFilter",["OPEN","WON","LOST","all"]);import{defineSchemaModel as m,ScalarTypeEnum as N}from"@contractspec/lib.schema";var y=m({name:"Deal",description:"A deal in the CRM pipeline",fields:{id:{type:N.String_unsecure(),isOptional:!1},name:{type:N.String_unsecure(),isOptional:!1},value:{type:N.Float_unsecure(),isOptional:!1},currency:{type:N.String_unsecure(),isOptional:!1},pipelineId:{type:N.String_unsecure(),isOptional:!1},stageId:{type:N.String_unsecure(),isOptional:!1},status:{type:yJ,isOptional:!1},contactId:{type:N.String_unsecure(),isOptional:!0},companyId:{type:N.String_unsecure(),isOptional:!0},ownerId:{type:N.String_unsecure(),isOptional:!1},expectedCloseDate:{type:N.DateTime(),isOptional:!0},createdAt:{type:N.DateTime(),isOptional:!1},updatedAt:{type:N.DateTime(),isOptional:!1}}}),WJ=m({name:"CreateDealInput",description:"Input for creating a deal",fields:{name:{type:N.NonEmptyString(),isOptional:!1},value:{type:N.Float_unsecure(),isOptional:!1},currency:{type:N.String_unsecure(),isOptional:!0},pipelineId:{type:N.String_unsecure(),isOptional:!1},stageId:{type:N.String_unsecure(),isOptional:!1},contactId:{type:N.String_unsecure(),isOptional:!0},companyId:{type:N.String_unsecure(),isOptional:!0},expectedCloseDate:{type:N.DateTime(),isOptional:!0}}}),UJ=m({name:"MoveDealInput",description:"Input for moving a deal to another stage",fields:{dealId:{type:N.String_unsecure(),isOptional:!1},stageId:{type:N.String_unsecure(),isOptional:!1},position:{type:N.Int_unsecure(),isOptional:!0}}}),KJ=m({name:"DealMovedPayload",fields:{dealId:{type:N.String_unsecure(),isOptional:!1},fromStage:{type:N.String_unsecure(),isOptional:!1},toStage:{type:N.String_unsecure(),isOptional:!1}}}),NJ=m({name:"WinDealInput",description:"Input for marking a deal as won",fields:{dealId:{type:N.String_unsecure(),isOptional:!1},wonSource:{type:N.String_unsecure(),isOptional:!0},notes:{type:N.String_unsecure(),isOptional:!0}}}),VJ=m({name:"DealWonPayload",fields:{dealId:{type:N.String_unsecure(),isOptional:!1},value:{type:N.Float_unsecure(),isOptional:!1}}}),_J=m({name:"LoseDealInput",description:"Input for marking a deal as lost",fields:{dealId:{type:N.String_unsecure(),isOptional:!1},lostReason:{type:N.String_unsecure(),isOptional:!1},notes:{type:N.String_unsecure(),isOptional:!0}}}),RJ=m({name:"DealLostPayload",fields:{dealId:{type:N.String_unsecure(),isOptional:!1},reason:{type:N.String_unsecure(),isOptional:!1}}}),AJ=m({name:"ListDealsInput",description:"Input for listing deals",fields:{pipelineId:{type:N.String_unsecure(),isOptional:!0},stageId:{type:N.String_unsecure(),isOptional:!0},status:{type:zJ,isOptional:!0},ownerId:{type:N.String_unsecure(),isOptional:!0},search:{type:N.String_unsecure(),isOptional:!0},limit:{type:N.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:N.Int_unsecure(),isOptional:!0,defaultValue:0}}}),PJ=m({name:"ListDealsOutput",description:"Output for listing deals",fields:{deals:{type:y,isArray:!0,isOptional:!1},total:{type:N.Int_unsecure(),isOptional:!1},totalValue:{type:N.Float_unsecure(),isOptional:!1}}});import{defineCommand as OJ,defineQuery as vX}from"@contractspec/lib.contracts-spec/operations";var XJ=["@example.crm-pipeline"],eJ=OJ({meta:{key:"crm.deal.create",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","create"],description:"Create a new deal in the pipeline.",goal:"Allow sales reps to create new opportunities.",context:"Deal creation UI, quick add."},io:{input:WJ,output:y},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.created",version:"1.0.0",when:"Deal is created",payload:y}],audit:["deal.created"]},acceptance:{scenarios:[{key:"create-deal-happy-path",given:["User is authenticated"],when:["User creates a deal with valid data"],then:["Deal is created","DealCreated event is emitted"]}],examples:[{key:"create-basic-deal",input:{title:"Big Corp Q3 License",stageId:"stage-lead",value:50000,companyId:"comp-123"},output:{id:"deal-789",title:"Big Corp Q3 License",status:"open"}}]}}),JX=OJ({meta:{key:"crm.deal.move",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","move","kanban"],description:"Move a deal to a different stage.",goal:"Allow drag-and-drop stage movement in Kanban.",context:"Pipeline Kanban view."},io:{input:UJ,output:y},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.moved",version:"1.0.0",when:"Deal stage changed",payload:KJ}],audit:["deal.moved"]},acceptance:{scenarios:[{key:"move-deal-happy-path",given:["Deal exists in stage A"],when:["User moves deal to stage B"],then:["Deal stage is updated","DealMoved event is emitted"]}],examples:[{key:"move-to-negotiation",input:{dealId:"deal-789",targetStageId:"stage-negotiation"},output:{id:"deal-789",stageId:"stage-negotiation",movedAt:"2025-01-15T10:00:00Z"}}]}}),XX=OJ({meta:{key:"crm.deal.win",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","won"],description:"Mark a deal as won.",goal:"Close a deal as successful.",context:"Deal closing flow."},io:{input:NJ,output:y},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.won",version:"1.0.0",when:"Deal is won",payload:VJ}],audit:["deal.won"]},acceptance:{scenarios:[{key:"win-deal-happy-path",given:["Deal is open"],when:["User marks deal as won"],then:["Deal status becomes WON","DealWon event is emitted"]}],examples:[{key:"mark-won",input:{dealId:"deal-789",actualValue:52000,note:"Signed contract attached"},output:{id:"deal-789",status:"won",closedAt:"2025-01-20T14:30:00Z"}}]}}),YX=OJ({meta:{key:"crm.deal.lose",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","lost"],description:"Mark a deal as lost.",goal:"Close a deal as unsuccessful.",context:"Deal closing flow."},io:{input:_J,output:y},policy:{auth:"user"},sideEffects:{emits:[{key:"deal.lost",version:"1.0.0",when:"Deal is lost",payload:RJ}],audit:["deal.lost"]},acceptance:{scenarios:[{key:"lose-deal-happy-path",given:["Deal is open"],when:["User marks deal as lost"],then:["Deal status becomes LOST","DealLost event is emitted"]}],examples:[{key:"mark-lost",input:{dealId:"deal-789",reason:"competitor",note:"Went with cheaper option"},output:{id:"deal-789",status:"lost",closedAt:"2025-01-21T09:00:00Z"}}]}}),ZX=vX({meta:{key:"crm.deal.list",version:"1.0.0",stability:"stable",owners:[...XJ],tags:["crm","deal","list"],description:"List deals with filters.",goal:"Show pipeline, deal lists, dashboards.",context:"Pipeline view, deal list."},io:{input:AJ,output:PJ},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-deals-happy-path",given:["User has access to deals"],when:["User lists deals"],then:["List of deals is returned"]}],examples:[{key:"list-filter-stage",input:{stageId:"stage-lead",limit:20},output:{items:[],total:5,hasMore:!1}}]}});import{registerDocBlocks as LX}from"@contractspec/lib.contracts-spec/docs";var IX=[{id:"docs.examples.crm-pipeline.goal",title:"CRM Pipeline — Goal",summary:"Deals, stages, contacts, companies, and tasks with auditable stage movement.",kind:"goal",visibility:"public",route:"/docs/examples/crm-pipeline/goal",tags:["crm","goal"],body:`## Why it matters
2
2
  - Regenerable CRM flow for deals/stages without code drift.
3
3
  - Ensures stage movement, tasks, and contacts stay aligned across surfaces.
4
4
 
@@ -66,7 +66,7 @@ import{defineFeature as kX}from"@contractspec/lib.contracts-spec";var jY=kX({met
66
66
  ## Verification
67
67
  - Add fixtures for stage move rules and SLA/task changes.
68
68
  - Ensure Audit/Notifications remain wired for stage and task events.
69
- - Use Feature Flags for experimental stages/SLAs; default safe/off.`}];MX(LX);import{defineEntity as IX,defineEntityEnum as hX,field as I,index as ZX}from"@contractspec/lib.schema";var jJ=hX({name:"CompanySize",values:["STARTUP","SMALL","MEDIUM","LARGE","ENTERPRISE"],schema:"crm",description:"Size category of a company."}),$X=IX({name:"Company",description:"A company/organization in the CRM.",schema:"crm",map:"company",fields:{id:I.id({description:"Unique company ID"}),name:I.string({description:"Company name"}),domain:I.string({isOptional:!0,description:"Website domain"}),website:I.url({isOptional:!0}),industry:I.string({isOptional:!0}),size:I.enum("CompanySize",{isOptional:!0}),employeeCount:I.int({isOptional:!0}),annualRevenue:I.decimal({isOptional:!0}),organizationId:I.foreignKey(),ownerId:I.foreignKey({description:"Account owner"}),phone:I.string({isOptional:!0}),email:I.email({isOptional:!0}),address:I.string({isOptional:!0}),city:I.string({isOptional:!0}),state:I.string({isOptional:!0}),country:I.string({isOptional:!0}),postalCode:I.string({isOptional:!0}),linkedInUrl:I.url({isOptional:!0}),description:I.string({isOptional:!0}),tags:I.string({isArray:!0}),customFields:I.json({isOptional:!0}),createdAt:I.createdAt(),updatedAt:I.updatedAt(),contacts:I.hasMany("Contact"),deals:I.hasMany("Deal")},indexes:[ZX.on(["organizationId","ownerId"]),ZX.on(["domain"])],enums:[jJ]});import{defineEntity as wX,defineEntityEnum as DX,field as v,index as AJ}from"@contractspec/lib.schema";var yJ=DX({name:"ContactStatus",values:["LEAD","PROSPECT","CUSTOMER","CHURNED","ARCHIVED"],schema:"crm",description:"Status of a contact in the sales funnel."}),qX=wX({name:"Contact",description:"An individual person in the CRM.",schema:"crm",map:"contact",fields:{id:v.id({description:"Unique contact ID"}),firstName:v.string({description:"First name"}),lastName:v.string({description:"Last name"}),email:v.email({isOptional:!0,isUnique:!0}),phone:v.string({isOptional:!0}),companyId:v.string({isOptional:!0,description:"Associated company"}),jobTitle:v.string({isOptional:!0}),status:v.enum("ContactStatus",{default:"LEAD"}),organizationId:v.foreignKey(),ownerId:v.foreignKey({description:"Sales rep who owns this contact"}),source:v.string({isOptional:!0,description:"Lead source"}),linkedInUrl:v.url({isOptional:!0}),twitterHandle:v.string({isOptional:!0}),address:v.string({isOptional:!0}),city:v.string({isOptional:!0}),state:v.string({isOptional:!0}),country:v.string({isOptional:!0}),postalCode:v.string({isOptional:!0}),notes:v.string({isOptional:!0}),tags:v.string({isArray:!0}),customFields:v.json({isOptional:!0}),lastContactedAt:v.dateTime({isOptional:!0}),nextFollowUpAt:v.dateTime({isOptional:!0}),createdAt:v.createdAt(),updatedAt:v.updatedAt(),company:v.belongsTo("Company",["companyId"],["id"]),deals:v.hasMany("Deal"),tasks:v.hasMany("Task"),activities:v.hasMany("Activity")},indexes:[AJ.on(["organizationId","status"]),AJ.on(["organizationId","ownerId"]),AJ.on(["organizationId","companyId"]),AJ.on(["email"])],enums:[yJ]});import{defineEntity as gJ,defineEntityEnum as bX,field as W,index as YJ}from"@contractspec/lib.schema";var fJ=bX({name:"DealStatus",values:["OPEN","WON","LOST","STALE"],schema:"crm",description:"Status of a deal."}),HX=gJ({name:"Pipeline",description:"A sales pipeline with stages.",schema:"crm",map:"pipeline",fields:{id:W.id(),name:W.string({description:"Pipeline name"}),description:W.string({isOptional:!0}),organizationId:W.foreignKey(),isDefault:W.boolean({default:!1}),createdAt:W.createdAt(),updatedAt:W.updatedAt(),stages:W.hasMany("Stage"),deals:W.hasMany("Deal")}}),GX=gJ({name:"Stage",description:"A stage within a sales pipeline.",schema:"crm",map:"stage",fields:{id:W.id(),name:W.string({description:"Stage name"}),pipelineId:W.foreignKey(),position:W.int({description:"Order in pipeline"}),probability:W.int({default:0,description:"Win probability (0-100)"}),isWonStage:W.boolean({default:!1}),isLostStage:W.boolean({default:!1}),color:W.string({isOptional:!0,description:"Stage color for UI"}),createdAt:W.createdAt(),updatedAt:W.updatedAt(),pipeline:W.belongsTo("Pipeline",["pipelineId"],["id"],{onDelete:"Cascade"}),deals:W.hasMany("Deal")},indexes:[YJ.on(["pipelineId","position"])]}),FX=gJ({name:"Deal",description:"A sales opportunity/deal.",schema:"crm",map:"deal",fields:{id:W.id({description:"Unique deal ID"}),name:W.string({description:"Deal name"}),value:W.decimal({description:"Deal value"}),currency:W.string({default:'"USD"'}),pipelineId:W.foreignKey(),stageId:W.foreignKey(),status:W.enum("DealStatus",{default:"OPEN"}),contactId:W.string({isOptional:!0}),companyId:W.string({isOptional:!0}),organizationId:W.foreignKey(),ownerId:W.foreignKey({description:"Deal owner"}),expectedCloseDate:W.dateTime({isOptional:!0}),closedAt:W.dateTime({isOptional:!0}),lostReason:W.string({isOptional:!0}),wonSource:W.string({isOptional:!0}),notes:W.string({isOptional:!0}),tags:W.string({isArray:!0}),customFields:W.json({isOptional:!0}),stagePosition:W.int({default:0}),createdAt:W.createdAt(),updatedAt:W.updatedAt(),pipeline:W.belongsTo("Pipeline",["pipelineId"],["id"]),stage:W.belongsTo("Stage",["stageId"],["id"]),contact:W.belongsTo("Contact",["contactId"],["id"]),company:W.belongsTo("Company",["companyId"],["id"]),tasks:W.hasMany("Task"),activities:W.hasMany("Activity")},indexes:[YJ.on(["organizationId","status"]),YJ.on(["pipelineId","stageId","stagePosition"]),YJ.on(["ownerId","status"]),YJ.on(["expectedCloseDate"])],enums:[fJ]});import{defineEntity as QX,defineEntityEnum as xJ,field as A,index as n}from"@contractspec/lib.schema";var SJ=xJ({name:"TaskType",values:["CALL","EMAIL","MEETING","TODO","FOLLOW_UP","OTHER"],schema:"crm",description:"Type of CRM task."}),mJ=xJ({name:"TaskPriority",values:["LOW","NORMAL","HIGH","URGENT"],schema:"crm",description:"Priority of a task."}),pJ=xJ({name:"TaskStatus",values:["PENDING","IN_PROGRESS","COMPLETED","CANCELLED"],schema:"crm",description:"Status of a task."}),zX=QX({name:"Task",description:"A task or follow-up activity.",schema:"crm",map:"task",fields:{id:A.id(),title:A.string({description:"Task title"}),description:A.string({isOptional:!0}),type:A.enum("TaskType",{default:"TODO"}),priority:A.enum("TaskPriority",{default:"NORMAL"}),status:A.enum("TaskStatus",{default:"PENDING"}),dueDate:A.dateTime({isOptional:!0}),reminderAt:A.dateTime({isOptional:!0}),contactId:A.string({isOptional:!0}),dealId:A.string({isOptional:!0}),companyId:A.string({isOptional:!0}),organizationId:A.foreignKey(),assignedTo:A.foreignKey({description:"User assigned to this task"}),createdBy:A.foreignKey(),completedAt:A.dateTime({isOptional:!0}),completedBy:A.string({isOptional:!0}),createdAt:A.createdAt(),updatedAt:A.updatedAt(),contact:A.belongsTo("Contact",["contactId"],["id"]),deal:A.belongsTo("Deal",["dealId"],["id"]),company:A.belongsTo("Company",["companyId"],["id"])},indexes:[n.on(["organizationId","assignedTo","status"]),n.on(["dueDate","status"]),n.on(["contactId"]),n.on(["dealId"])],enums:[SJ,mJ,pJ]}),WX=QX({name:"Activity",description:"An activity/interaction logged in the CRM.",schema:"crm",map:"activity",fields:{id:A.id(),type:A.enum("TaskType"),subject:A.string(),description:A.string({isOptional:!0}),contactId:A.string({isOptional:!0}),dealId:A.string({isOptional:!0}),companyId:A.string({isOptional:!0}),organizationId:A.foreignKey(),performedBy:A.foreignKey(),outcome:A.string({isOptional:!0}),occurredAt:A.dateTime(),duration:A.int({isOptional:!0,description:"Duration in minutes"}),createdAt:A.createdAt(),contact:A.belongsTo("Contact",["contactId"],["id"]),deal:A.belongsTo("Deal",["dealId"],["id"]),company:A.belongsTo("Company",["companyId"],["id"])},indexes:[n.on(["contactId","occurredAt"]),n.on(["dealId","occurredAt"])]});var UX={moduleId:"@contractspec/example.crm-pipeline",entities:[$X,qX,FX,HX,GX,zX,WX],enums:[jJ,yJ,fJ,SJ,mJ,pJ]};import{defineEvent as TX}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as CX,ScalarTypeEnum as ZJ}from"@contractspec/lib.schema";var EX=CX({name:"ContactCreatedPayload",description:"Payload when a contact is created",fields:{contactId:{type:ZJ.String_unsecure(),isOptional:!1},email:{type:ZJ.EmailAddress(),isOptional:!0},organizationId:{type:ZJ.String_unsecure(),isOptional:!1},ownerId:{type:ZJ.String_unsecure(),isOptional:!1},createdAt:{type:ZJ.DateTime(),isOptional:!1}}}),VZ=TX({meta:{key:"contact.created",version:"1.0.0",description:"A new contact has been created.",stability:"stable",owners:["@crm-team"],tags:["contact","created"]},payload:EX});import{defineEvent as OJ}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as BJ,ScalarTypeEnum as w}from"@contractspec/lib.schema";var jX=BJ({name:"DealCreatedPayload",description:"Payload when a deal is created",fields:{dealId:{type:w.String_unsecure(),isOptional:!1},name:{type:w.String_unsecure(),isOptional:!1},value:{type:w.Float_unsecure(),isOptional:!1},pipelineId:{type:w.String_unsecure(),isOptional:!1},stageId:{type:w.String_unsecure(),isOptional:!1},ownerId:{type:w.String_unsecure(),isOptional:!1},createdAt:{type:w.DateTime(),isOptional:!1}}}),yX=BJ({name:"DealMovedEventPayload",description:"Payload when a deal is moved to another stage",fields:{dealId:{type:w.String_unsecure(),isOptional:!1},fromStageId:{type:w.String_unsecure(),isOptional:!1},toStageId:{type:w.String_unsecure(),isOptional:!1},movedBy:{type:w.String_unsecure(),isOptional:!1},movedAt:{type:w.DateTime(),isOptional:!1}}}),gX=BJ({name:"DealWonEventPayload",description:"Payload when a deal is won",fields:{dealId:{type:w.String_unsecure(),isOptional:!1},value:{type:w.Float_unsecure(),isOptional:!1},currency:{type:w.String_unsecure(),isOptional:!1},contactId:{type:w.String_unsecure(),isOptional:!0},companyId:{type:w.String_unsecure(),isOptional:!0},ownerId:{type:w.String_unsecure(),isOptional:!1},wonAt:{type:w.DateTime(),isOptional:!1}}}),fX=BJ({name:"DealLostEventPayload",description:"Payload when a deal is lost",fields:{dealId:{type:w.String_unsecure(),isOptional:!1},value:{type:w.Float_unsecure(),isOptional:!1},reason:{type:w.String_unsecure(),isOptional:!1},ownerId:{type:w.String_unsecure(),isOptional:!1},lostAt:{type:w.DateTime(),isOptional:!1}}}),AZ=OJ({meta:{key:"deal.created",version:"1.0.0",description:"A new deal has been created.",stability:"stable",owners:["@crm-team"],tags:["deal","created"]},payload:jX}),OZ=OJ({meta:{key:"deal.moved",version:"1.0.0",description:"A deal has been moved to a different stage.",stability:"stable",owners:["@crm-team"],tags:["deal","moved"]},payload:yX}),BZ=OJ({meta:{key:"deal.won",version:"1.0.0",description:"A deal has been won.",stability:"stable",owners:["@crm-team"],tags:["deal","won"]},payload:gX}),kZ=OJ({meta:{key:"deal.lost",version:"1.0.0",description:"A deal has been lost.",stability:"stable",owners:["@crm-team"],tags:["deal","lost"]},payload:fX});import{defineEvent as xX}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as SX,ScalarTypeEnum as $J}from"@contractspec/lib.schema";var mX=SX({name:"TaskCompletedPayload",description:"Payload when a task is completed",fields:{taskId:{type:$J.String_unsecure(),isOptional:!1},type:{type:$J.String_unsecure(),isOptional:!1},assignedTo:{type:$J.String_unsecure(),isOptional:!1},completedBy:{type:$J.String_unsecure(),isOptional:!1},completedAt:{type:$J.DateTime(),isOptional:!1}}}),IZ=xX({meta:{key:"task.completed",version:"1.0.0",description:"A task has been completed.",stability:"stable",owners:["@crm-team"],tags:["task","lifecycle"]},payload:mX});import{defineExample as pX}from"@contractspec/lib.contracts-spec";var cX=pX({meta:{key:"crm-pipeline",version:"1.0.0",title:"CRM Pipeline",description:"Sales CRM with contacts, companies, deals, pipelines, and tasks.",kind:"template",visibility:"public",stability:"experimental",owners:["@platform.core"],tags:["crm","sales","pipeline","deals"]},docs:{rootDocId:"docs.examples.crm-pipeline"},entrypoints:{packageName:"@contractspec/example.crm-pipeline",feature:"./feature",contracts:"./contracts",presentations:"./presentations",handlers:"./handlers",docs:"./docs"},surfaces:{templates:!0,sandbox:{enabled:!0,modes:["playground","specs","builder","markdown","evolution"]},studio:{enabled:!0,installable:!0},mcp:{enabled:!0}}}),uX=cX;import{web as rX}from"@contractspec/lib.runtime-sandbox";var{generateId:oX}=rX;function s(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 KX={name:"name",value:"value",status:"status",expectedCloseDate:"expectedCloseDate",updatedAt:"updatedAt"};function yZ(J){async function Y(X){let{projectId:H,pipelineId:Z,stageId:G,status:$,ownerId:R,search:O,limit:L=20,offset:N=0,sortBy:U="value",sortDirection:Q="desc"}=X,M="WHERE projectId = ?",b=[H];if(Z)M+=" AND pipelineId = ?",b.push(Z);if(G)M+=" AND stageId = ?",b.push(G);if($&&$!=="all")M+=" AND status = ?",b.push($);if(R)M+=" AND ownerId = ?",b.push(R);if(O)M+=" AND name LIKE ?",b.push(`%${O}%`);let d=(await J.query(`SELECT COUNT(*) as count FROM crm_deal ${M}`,b)).rows[0]?.count??0,j=(await J.query(`SELECT COALESCE(SUM(value), 0) as total FROM crm_deal ${M}`,b)).rows[0]?.total??0,B=KX[U]??KX.value,JJ=Q==="asc"?"ASC":"DESC";return{deals:(await J.query(`SELECT * FROM crm_deal ${M} ORDER BY ${B} ${JJ} LIMIT ? OFFSET ?`,[...b,L,N])).rows.map(s),total:d,totalValue:j}}async function F(X,H){let Z=oX("deal"),G=new Date().toISOString();await J.execute(`INSERT INTO crm_deal (id, projectId, pipelineId, stageId, name, value, currency, status, contactId, companyId, ownerId, expectedCloseDate, createdAt, updatedAt)
70
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[Z,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,G,G]);let $=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[Z])).rows;if(!$[0])throw Error("Failed to create deal");return s($[0])}async function q(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 $=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return s($[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 G=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return s(G[0])}async function P(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 G=(await J.query("SELECT * FROM crm_deal WHERE id = ?",[X.dealId])).rows;return s(G[0])}async function k(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,Z=(await J.query("SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position",[X.pipelineId])).rows,G={};for(let $ of Z)G[$.id]=H.filter((R)=>R.stageId===$.id).map(s);return G}async function V(X){return(await J.query("SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position",[X.pipelineId])).rows.map((Z)=>({id:Z.id,pipelineId:Z.pipelineId,name:Z.name,position:Z.position}))}return{listDeals:Y,createDeal:F,moveDeal:q,winDeal:z,loseDeal:P,getDealsByStage:k,getPipelineStages:V}}var qJ=[{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"}],f=[{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")}],fZ=[{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")}],xZ=[{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 kJ(J){let{pipelineId:Y,stageId:F,status:q,ownerId:z,search:P,limit:k=20,offset:V=0}=J,X=[...f];if(Y)X=X.filter(($)=>$.pipelineId===Y);if(F)X=X.filter(($)=>$.stageId===F);if(q&&q!=="all")X=X.filter(($)=>$.status===q);if(z)X=X.filter(($)=>$.ownerId===z);if(P){let $=P.toLowerCase();X=X.filter((R)=>R.name.toLowerCase().includes($))}X.sort(($,R)=>R.value-$.value);let H=X.length,Z=X.reduce(($,R)=>$+R.value,0);return{deals:X.slice(V,V+k),total:H,totalValue:Z}}async function dX(J,Y){let F=new Date,q={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:F,updatedAt:F};return f.push(q),q}async function lX(J){let Y=f.findIndex((P)=>P.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let F=f[Y];if(!F)throw Error("NOT_FOUND");if(!qJ.find((P)=>P.id===J.stageId))throw Error("INVALID_STAGE");let z={...F,stageId:J.stageId,updatedAt:new Date};return f[Y]=z,z}async function iX(J){let Y=f.findIndex((z)=>z.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let F=f[Y];if(!F)throw Error("NOT_FOUND");let q={...F,status:"WON",updatedAt:new Date};return f[Y]=q,q}async function nX(J){let Y=f.findIndex((z)=>z.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let F=f[Y];if(!F)throw Error("NOT_FOUND");let q={...F,status:"LOST",updatedAt:new Date};return f[Y]=q,q}async function sX(J){let Y=f.filter((q)=>q.pipelineId===J.pipelineId&&q.status==="OPEN"),F={};for(let q of qJ)F[q.id]=Y.filter((z)=>z.stageId===q.id);return F}async function vJ(J){return qJ.filter((Y)=>Y.pipelineId===J.pipelineId)}import{definePresentation as NX,StabilityEnum as VX}from"@contractspec/lib.contracts-spec";var nZ=NX({meta:{key:"crm.dashboard",version:"1.0.0",title:"CRM Dashboard",description:"Main CRM dashboard with pipeline overview, deal stats, and activities",domain:"crm-pipeline",owners:["@crm-team"],tags:["dashboard","overview"],stability:VX.Experimental,goal:"Provide a high-level overview of CRM performance and active deals.",context:"The landing page for CRM users."},source:{type:"component",framework:"react",componentKey:"CrmDashboard"},targets:["react","markdown"],policy:{flags:["crm.enabled"]}}),sZ=NX({meta:{key:"crm.pipeline.metrics",version:"1.0.0",title:"Pipeline Metrics",description:"Pipeline metrics and forecasting view",domain:"crm-pipeline",owners:["@crm-team"],tags:["pipeline","metrics","forecast"],stability:VX.Experimental,goal:"Track pipeline health and sales forecasts.",context:"Data-intensive widget for sales managers."},source:{type:"component",framework:"react",componentKey:"PipelineMetricsView"},targets:["react","markdown"],policy:{flags:["crm.metrics.enabled"]}});import{definePresentation as MJ,StabilityEnum as LJ}from"@contractspec/lib.contracts-spec";var J0=MJ({meta:{key:"crm.pipeline.kanban",version:"1.0.0",title:"Pipeline Kanban",description:"Kanban board view of deals organized by stage",domain:"crm-pipeline",owners:["@crm-team"],tags:["pipeline","kanban","deals"],stability:LJ.Experimental,goal:"Visualize the sales pipeline status and deal distribution across stages.",context:"Used in the sales dashboard and management reports."},source:{type:"component",framework:"react",componentKey:"PipelineKanbanView",props:g},targets:["react","markdown"],policy:{flags:["crm.pipeline.enabled"]}}),X0=MJ({meta:{key:"crm.deal.viewList",version:"1.0.0",title:"Deal List",description:"List view of deals with value, status, and owner info",domain:"crm-pipeline",owners:["@crm-team"],tags:["deal","list"],stability:LJ.Experimental,goal:"Search, filter, and review deal lists.",context:"Standard view for deal management and bulk actions."},source:{type:"component",framework:"react",componentKey:"DealListView",props:g},targets:["react","markdown","application/json"],policy:{flags:["crm.deals.enabled"]}}),Y0=MJ({meta:{key:"crm.deal.detail",version:"1.0.0",title:"Deal Details",description:"Detailed view of a deal with activities, contacts, and history",domain:"crm-pipeline",owners:["@crm-team"],tags:["deal","detail"],stability:LJ.Experimental,goal:"Deep dive into deal details and historical activities.",context:"The main workspace for managing a single deal execution."},source:{type:"component",framework:"react",componentKey:"DealDetailView"},targets:["react","markdown"],policy:{flags:["crm.deals.enabled"]}}),Z0=MJ({meta:{key:"crm.deal.card",version:"1.0.0",title:"Deal Card",description:"Compact deal card for kanban board display",domain:"crm-pipeline",owners:["@crm-team"],tags:["deal","card","kanban"],stability:LJ.Experimental,goal:"Provide a quick overview of deal status in the pipeline view.",context:"Condensed representation used within the Pipeline Kanban board."},source:{type:"component",framework:"react",componentKey:"DealCard",props:g},targets:["react"],policy:{flags:["crm.deals.enabled"]}});import{jsx as IJ,jsxs as _X}from"react/jsx-runtime";function tX(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function PX({deal:J,onClick:Y}){let F=J.expectedCloseDate?Math.ceil((J.expectedCloseDate.getTime()-Date.now())/86400000):null;return _X("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:(q)=>{if(q.key==="Enter"||q.key===" ")Y?.()},children:[IJ("h4",{className:"font-medium leading-snug",children:J.name}),IJ("div",{className:"mt-2 font-semibold text-lg text-primary",children:tX(J.value,J.currency)}),_X("div",{className:"mt-3 flex items-center justify-between text-muted-foreground text-xs",children:[F!==null&&IJ("span",{className:F<0?"text-red-500":F<=7?"text-yellow-600 dark:text-yellow-500":"",children:F<0?`${Math.abs(F)}d overdue`:F===0?"Due today":`${F}d left`}),IJ("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 aX}from"react";import{jsx as r,jsxs as l}from"react/jsx-runtime";function eX(J){if(J>=1e6)return`$${(J/1e6).toFixed(1)}M`;if(J>=1000)return`$${(J/1000).toFixed(0)}K`;return`$${J}`}function hJ({dealsByStage:J,stages:Y,onDealClick:F,onDealMove:q}){let[z,P]=aX(null),k=[...Y].sort((X,H)=>X.position-H.position),V=(X,H)=>{q?.(X,H),P(null)};return r("div",{className:"flex gap-4 overflow-x-auto pb-4",children:k.map((X)=>{let H=J[X.id]??[],Z=H.reduce((G,$)=>G+$.value,0);return l("div",{className:"flex w-72 flex-shrink-0 flex-col rounded-lg bg-muted/30",children:[l("div",{className:"flex items-center justify-between border-border border-b px-3 py-2",children:[l("div",{children:[r("h3",{className:"font-medium",children:X.name}),l("p",{className:"text-muted-foreground text-xs",children:[H.length," deals · ",eX(Z)]})]}),r("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",children:H.length})]}),r("div",{className:"flex flex-1 flex-col gap-2 p-2",children:H.length===0?r("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((G)=>l("div",{className:"group relative",children:[r(PX,{deal:G,onClick:()=>F?.(G.id)}),G.status==="OPEN"&&q&&l("div",{className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100",children:[r("button",{type:"button",onClick:($)=>{$.stopPropagation(),P(z===G.id?null:G.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===G.id&&l("div",{className:"absolute top-7 right-0 z-20 min-w-[140px] rounded-lg border border-border bg-card py-1 shadow-lg",children:[r("p",{className:"px-3 py-1 font-medium text-muted-foreground text-xs",children:"Move to:"}),k.filter(($)=>$.id!==G.stageId).map(($)=>r("button",{type:"button",onClick:(R)=>{R.stopPropagation(),V(G.id,$.id)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-muted",children:$.name},$.id))]})]})]},G.id))})]},X.id)})})}import{useTemplateRuntime as JY}from"@contractspec/lib.example-shared-ui";import{useCallback as XY,useEffect as YY,useMemo as ZY,useState as t}from"react";function i(J={}){let{handlers:Y,projectId:F}=JY(),{crm:q}=Y,[z,P]=t(null),[k,V]=t({}),[X,H]=t([]),[Z,G]=t(!0),[$,R]=t(null),[O,L]=t(0),N=J.pipelineId??"pipeline-1",U=J.pageIndex??O,Q=J.pageSize??J.limit??50,[M]=J.sorting??[],b=M?.id,x=M?M.desc?"desc":"asc":void 0,d=XY(async()=>{G(!0),R(null);try{let[j,B,JJ]=await Promise.all([q.listDeals({projectId:F,pipelineId:N,stageId:J.stageId,status:J.status==="all"?void 0:J.status,search:J.search,limit:Q,offset:U*Q,sortBy:b==="name"||b==="value"||b==="status"||b==="expectedCloseDate"||b==="updatedAt"?b:void 0,sortDirection:x}),q.getDealsByStage({projectId:F,pipelineId:N}),q.getPipelineStages({pipelineId:N})]);P(j),V(B),H(JJ)}catch(j){R(j instanceof Error?j:Error("Unknown error"))}finally{G(!1)}},[q,F,N,J.stageId,J.status,J.search,U,Q,b,x]);YY(()=>{d()},[d]);let GJ=ZY(()=>{if(!z)return null;let j=z.deals.filter((S)=>S.status==="OPEN"),B=z.deals.filter((S)=>S.status==="WON"),JJ=z.deals.filter((S)=>S.status==="LOST");return{total:z.total,totalValue:z.totalValue,openCount:j.length,openValue:j.reduce((S,CJ)=>S+CJ.value,0),wonCount:B.length,wonValue:B.reduce((S,CJ)=>S+CJ.value,0),lostCount:JJ.length}},[z]);return{data:z,dealsByStage:k,stages:X,loading:Z,error:$,stats:GJ,page:U+1,pageIndex:U,pageSize:Q,refetch:d,nextPage:J.pageIndex===void 0?()=>L((j)=>j+1):void 0,prevPage:J.pageIndex===void 0?()=>U>0&&L((j)=>j-1):void 0}}import{useTemplateRuntime as $Y}from"@contractspec/lib.example-shared-ui";import{useCallback as wJ,useState as DJ}from"react";function cJ(J={}){let{handlers:Y,projectId:F}=$Y(),{crm:q}=Y,[z,P]=DJ({loading:!1,error:null,data:null}),[k,V]=DJ({loading:!1,error:null,data:null}),[X,H]=DJ({loading:!1,error:null,data:null}),[Z,G]=DJ({loading:!1,error:null,data:null}),$=wJ(async(N)=>{P({loading:!0,error:null,data:null});try{let U=await q.createDeal(N,{projectId:F,ownerId:"user-1"});return P({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let Q=U instanceof Error?U:Error("Failed to create deal");return P({loading:!1,error:Q,data:null}),J.onError?.(Q),null}},[q,F,J]),R=wJ(async(N)=>{V({loading:!0,error:null,data:null});try{let U=await q.moveDeal(N);return V({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let Q=U instanceof Error?U:Error("Failed to move deal");return V({loading:!1,error:Q,data:null}),J.onError?.(Q),null}},[q,J]),O=wJ(async(N)=>{H({loading:!0,error:null,data:null});try{let U=await q.winDeal(N);return H({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let Q=U instanceof Error?U:Error("Failed to mark deal as won");return H({loading:!1,error:Q,data:null}),J.onError?.(Q),null}},[q,J]),L=wJ(async(N)=>{G({loading:!0,error:null,data:null});try{let U=await q.loseDeal(N);return G({loading:!1,error:null,data:U}),J.onSuccess?.(),U}catch(U){let Q=U instanceof Error?U:Error("Failed to mark deal as lost");return G({loading:!1,error:Q,data:null}),J.onError?.(Q),null}},[q,J]);return{createDeal:$,moveDeal:R,winDeal:O,loseDeal:L,createState:z,moveState:k,winState:X,loseState:Z,isLoading:z.loading||k.loading||X.loading||Z.loading}}import{Button as RX,Input as uJ}from"@contractspec/lib.design-system";import{useState as a}from"react";import{jsx as C,jsxs as p}from"react/jsx-runtime";var qY=["USD","EUR","GBP","CAD"],HY="pipeline-1";function rJ({isOpen:J,onClose:Y,onSubmit:F,stages:q,isLoading:z=!1}){let[P,k]=a(""),[V,X]=a(""),[H,Z]=a("USD"),[G,$]=a(q[0]?.id??""),[R,O]=a(""),[L,N]=a(null),U=async(Q)=>{if(Q.preventDefault(),N(null),!P.trim()){N("Deal name is required");return}let M=parseFloat(V);if(isNaN(M)||M<=0){N("Value must be a positive number");return}if(!G){N("Please select a pipeline stage");return}try{await F({name:P.trim(),value:M,currency:H,pipelineId:HY,stageId:G,expectedCloseDate:R?new Date(R):void 0}),k(""),X(""),Z("USD"),$(q[0]?.id??""),O(""),Y()}catch(b){N(b instanceof Error?b.message:"Failed to create deal")}};if(!J)return null;return p("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[C("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:Y,role:"button",tabIndex:0,onKeyDown:(Q)=>{if(Q.key==="Enter"||Q.key===" ")Y()},"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:[C("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Deal"}),p("form",{onSubmit:U,className:"space-y-4",children:[p("div",{children:[C("label",{htmlFor:"deal-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Deal Name *"}),C(uJ,{id:"deal-name",value:P,onChange:(Q)=>k(Q.target.value),placeholder:"e.g., Enterprise License - Acme Corp",disabled:z})]}),p("div",{className:"flex gap-3",children:[p("div",{className:"flex-1",children:[C("label",{htmlFor:"deal-value",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Value *"}),C(uJ,{id:"deal-value",type:"number",min:"0",step:"0.01",value:V,onChange:(Q)=>X(Q.target.value),placeholder:"50000",disabled:z})]}),p("div",{className:"w-24",children:[C("label",{htmlFor:"deal-currency",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Currency"}),C("select",{id:"deal-currency",value:H,onChange:(Q)=>Z(Q.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:qY.map((Q)=>C("option",{value:Q,children:Q},Q))})]})]}),p("div",{children:[C("label",{htmlFor:"deal-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Pipeline Stage *"}),C("select",{id:"deal-stage",value:G,onChange:(Q)=>$(Q.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:q.map((Q)=>C("option",{value:Q.id,children:Q.name},Q.id))})]}),p("div",{children:[C("label",{htmlFor:"deal-close-date",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Expected Close Date"}),C(uJ,{id:"deal-close-date",type:"date",value:R,onChange:(Q)=>O(Q.target.value),disabled:z})]}),L&&C("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:L}),p("div",{className:"flex justify-end gap-3 pt-2",children:[C(RX,{type:"button",variant:"ghost",onPress:Y,disabled:z,children:"Cancel"}),C(RX,{type:"submit",disabled:z,children:z?"Creating...":"Create Deal"})]})]})]})]})}import{Button as c}from"@contractspec/lib.design-system";import{useState as e}from"react";import{jsx as _,jsxs as D,Fragment as FY}from"react/jsx-runtime";function GY(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function oJ({isOpen:J,deal:Y,stages:F,onClose:q,onWin:z,onLose:P,onMove:k,isLoading:V=!1}){let[X,H]=e("menu"),[Z,G]=e(""),[$,R]=e(""),[O,L]=e(""),[N,U]=e(""),[Q,M]=e(null),b=()=>{H("menu"),G(""),R(""),L(""),U(""),M(null)},x=()=>{b(),q()},d=async()=>{if(!Y)return;M(null);try{await z({dealId:Y.id,wonSource:Z.trim()||void 0,notes:O.trim()||void 0}),x()}catch(B){M(B instanceof Error?B.message:"Failed to mark deal as won")}},GJ=async()=>{if(!Y)return;if(M(null),!$.trim()){M("Please provide a reason for losing the deal");return}try{await P({dealId:Y.id,lostReason:$.trim(),notes:O.trim()||void 0}),x()}catch(B){M(B instanceof Error?B.message:"Failed to mark deal as lost")}},j=async()=>{if(!Y)return;if(M(null),!N){M("Please select a stage");return}if(N===Y.stageId){M("Deal is already in this stage");return}try{await k({dealId:Y.id,stageId:N}),x()}catch(B){M(B instanceof Error?B.message:"Failed to move deal")}};if(!J||!Y)return null;return D("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[_("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:x,role:"button",tabIndex:0,onKeyDown:(B)=>{if(B.key==="Enter"||B.key===" ")x()},"aria-label":"Close modal"}),D("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[D("div",{className:"mb-4 border-border border-b pb-4",children:[_("h2",{className:"font-semibold text-xl",children:Y.name}),_("p",{className:"font-medium text-lg text-primary",children:GY(Y.value,Y.currency)}),_("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"&&D("div",{className:"space-y-3",children:[Y.status==="OPEN"&&D(FY,{children:[D(c,{className:"w-full justify-start",variant:"ghost",onPress:()=>H("win"),children:[_("span",{className:"mr-2",children:"\uD83C\uDFC6"})," Mark as Won"]}),D(c,{className:"w-full justify-start",variant:"ghost",onPress:()=>H("lose"),children:[_("span",{className:"mr-2",children:"❌"})," Mark as Lost"]}),D(c,{className:"w-full justify-start",variant:"ghost",onPress:()=>{U(Y.stageId),H("move")},children:[_("span",{className:"mr-2",children:"➡️"})," Move to Stage"]})]}),Y.status!=="OPEN"&&D("p",{className:"py-4 text-center text-muted-foreground",children:["This deal is already ",Y.status.toLowerCase(),". No actions available."]}),_("div",{className:"border-border border-t pt-3",children:_(c,{className:"w-full",variant:"outline",onPress:x,children:"Close"})})]}),X==="win"&&D("div",{className:"space-y-4",children:[D("div",{children:[_("label",{htmlFor:"won-source",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"How did you win this deal?"}),D("select",{id:"won-source",value:Z,onChange:(B)=>G(B.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:[_("option",{value:"",children:"Select a source..."}),_("option",{value:"referral",children:"Referral"}),_("option",{value:"cold_outreach",children:"Cold Outreach"}),_("option",{value:"inbound",children:"Inbound Lead"}),_("option",{value:"upsell",children:"Upsell"}),_("option",{value:"other",children:"Other"})]})]}),D("div",{children:[_("label",{htmlFor:"win-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),_("textarea",{id:"win-notes",value:O,onChange:(B)=>L(B.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"})]}),Q&&_("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:Q}),D("div",{className:"flex justify-end gap-3 pt-2",children:[_(c,{variant:"ghost",onPress:()=>H("menu"),disabled:V,children:"Back"}),_(c,{onPress:d,disabled:V,children:V?"Processing...":"\uD83C\uDFC6 Confirm Win"})]})]}),X==="lose"&&D("div",{className:"space-y-4",children:[D("div",{children:[_("label",{htmlFor:"lost-reason",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Why was this deal lost? *"}),D("select",{id:"lost-reason",value:$,onChange:(B)=>R(B.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:[_("option",{value:"",children:"Select a reason..."}),_("option",{value:"price",children:"Price too high"}),_("option",{value:"competitor",children:"Lost to competitor"}),_("option",{value:"no_budget",children:"No budget"}),_("option",{value:"no_decision",children:"No decision made"}),_("option",{value:"timing",children:"Bad timing"}),_("option",{value:"product_fit",children:"Product not a fit"}),_("option",{value:"other",children:"Other"})]})]}),D("div",{children:[_("label",{htmlFor:"lose-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),_("textarea",{id:"lose-notes",value:O,onChange:(B)=>L(B.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"})]}),Q&&_("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:Q}),D("div",{className:"flex justify-end gap-3 pt-2",children:[_(c,{variant:"ghost",onPress:()=>H("menu"),disabled:V,children:"Back"}),_(c,{variant:"destructive",onPress:GJ,disabled:V,children:V?"Processing...":"❌ Confirm Loss"})]})]}),X==="move"&&D("div",{className:"space-y-4",children:[D("div",{children:[_("label",{htmlFor:"move-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Move to Stage"}),_("select",{id:"move-stage",value:N,onChange:(B)=>U(B.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:F.map((B)=>D("option",{value:B.id,children:[B.name,B.id===Y.stageId?" (current)":""]},B.id))})]}),Q&&_("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:Q}),D("div",{className:"flex justify-end gap-3 pt-2",children:[_(c,{variant:"ghost",onPress:()=>H("menu"),disabled:V,children:"Back"}),_(c,{onPress:j,disabled:V,children:V?"Moving...":"➡️ Move Deal"})]})]})]})]})}import{Button as QY,DataTable as zY,LoaderBlock as WY}from"@contractspec/lib.design-system";import{useContractTable as UY}from"@contractspec/lib.presentation-runtime-react";import{Badge as KY}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as HJ,VStack as dJ}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as y}from"@contractspec/lib.ui-kit-web/ui/text";import*as lJ from"react";import{jsx as T,jsxs as u}from"react/jsx-runtime";function NY(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function VY(J){switch(J){case"WON":return"default";case"LOST":return"destructive";case"STALE":return"outline";default:return"secondary"}}function _Y({deals:J,totalItems:Y,pageIndex:F,pageSize:q,sorting:z,loading:P,onSortingChange:k,onPaginationChange:V,onDealClick:X}){let H=UY({data:J,columns:[{id:"deal",header:"Deal",label:"Deal",accessor:(Z)=>Z.name,cell:({item:Z})=>u(dJ,{gap:"xs",children:[T(y,{className:"font-medium text-sm",children:Z.name}),T(y,{className:"text-muted-foreground text-xs",children:Z.companyId??"Unassigned company"})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"value",header:"Value",label:"Value",accessorKey:"value",cell:({item:Z})=>NY(Z.value,Z.currency),align:"right",size:140,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:Z})=>T(KY,{variant:VY(Z),children:String(Z)}),size:130,canSort:!0,canHide:!0,canPin:!0,canResize:!0},{id:"expectedCloseDate",header:"Expected Close",label:"Expected Close",accessor:(Z)=>Z.expectedCloseDate?.toISOString()??"",cell:({item:Z})=>Z.expectedCloseDate?.toLocaleDateString()??"Not scheduled",size:170,canSort:!0,canHide:!0,canResize:!0},{id:"updatedAt",header:"Updated",label:"Updated",accessor:(Z)=>Z.updatedAt.toISOString(),cell:({item:Z})=>Z.updatedAt.toLocaleDateString(),size:140,canSort:!0,canHide:!0,canResize:!0},{id:"actions",header:"Actions",label:"Actions",accessor:(Z)=>Z.id,cell:({item:Z})=>T(QY,{variant:"ghost",size:"sm",onPress:()=>X?.(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:F,pageSize:q}},onSortingChange:k,onPaginationChange:V,initialState:{columnVisibility:{updatedAt:!1},columnPinning:{left:["deal","status"],right:[]}},renderExpandedContent:(Z)=>u(dJ,{gap:"sm",className:"py-2",children:[u(HJ,{justify:"between",children:[T(y,{className:"font-medium text-sm",children:"Owner"}),T(y,{className:"text-muted-foreground text-sm",children:Z.ownerId})]}),u(HJ,{justify:"between",children:[T(y,{className:"font-medium text-sm",children:"Contact"}),T(y,{className:"text-muted-foreground text-sm",children:Z.contactId??"No linked contact"})]}),Z.wonSource?u(HJ,{justify:"between",children:[T(y,{className:"font-medium text-sm",children:"Won Source"}),T(y,{className:"text-muted-foreground text-sm",children:Z.wonSource})]}):null,Z.lostReason?u(HJ,{justify:"between",children:[T(y,{className:"font-medium text-sm",children:"Lost Reason"}),T(y,{className:"text-muted-foreground text-sm",children:Z.lostReason})]}):null,Z.notes?u(dJ,{gap:"xs",children:[T(y,{className:"font-medium text-sm",children:"Notes"}),T(y,{className:"text-muted-foreground text-sm",children:Z.notes})]}):null]}),getCanExpand:()=>!0});return T(zY,{controller:H,title:"All Deals",description:"Server-mode table using the shared ContractSpec controller.",loading:P,toolbar:u(HJ,{gap:"sm",className:"flex-wrap",children:[u(y,{className:"text-muted-foreground text-sm",children:["Selected ",H.selectedRowIds.length]}),u(y,{className:"text-muted-foreground text-sm",children:[Y," total deals"]})]}),footer:`Page ${H.pageIndex+1} of ${H.pageCount}`,emptyState:T("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No deals found"})})}function AX({onDealClick:J}){let[Y,F]=lJ.useState([{id:"value",desc:!0}]),[q,z]=lJ.useState({pageIndex:0,pageSize:3}),{data:P,loading:k}=i({pageIndex:q.pageIndex,pageSize:q.pageSize,sorting:Y});if(k&&!P)return T(WY,{label:"Loading deals..."});return T(_Y,{deals:P?.deals??[],totalItems:P?.total??0,pageIndex:q.pageIndex,pageSize:q.pageSize,sorting:Y,loading:k,onSortingChange:(V)=>{F(V),z((X)=>({...X,pageIndex:0}))},onPaginationChange:z,onDealClick:J})}import{Button as PY,ErrorState as RY,LoaderBlock as AY,StatCard as bJ,StatCardGroup as OY}from"@contractspec/lib.design-system";import{Tabs as BY,TabsContent as iJ,TabsList as kY,TabsTrigger as nJ}from"@contractspec/lib.ui-kit-web/ui/tabs";import{useCallback as OX,useState as sJ}from"react";import{jsx as h,jsxs as E}from"react/jsx-runtime";function TJ(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function o0(){let[J,Y]=sJ(!1),[F,q]=sJ(null),[z,P]=sJ(!1),{data:k,dealsByStage:V,stages:X,loading:H,error:Z,stats:G,refetch:$}=i(),R=cJ({onSuccess:()=>{$()}}),O=OX((N)=>{let U=V?Object.values(V).flat().find((Q)=>Q.id===N):null;if(U)q(U),P(!0)},[V]),L=OX(async(N,U)=>{await R.moveDeal({dealId:N,stageId:U})},[R]);if(H&&!k)return h(AY,{label:"Loading CRM..."});if(Z)return h(RY,{title:"Failed to load CRM",description:Z.message,onRetry:$,retryLabel:"Retry"});return E("div",{className:"space-y-6",children:[E("div",{className:"flex items-center justify-between",children:[h("h2",{className:"font-bold text-2xl",children:"CRM Pipeline"}),E(PY,{onClick:()=>Y(!0),children:[h("span",{className:"mr-2",children:"+"})," Create Deal"]})]}),G&&E(OY,{children:[h(bJ,{label:"Total Pipeline",value:TJ(G.totalValue),hint:`${G.total} deals`}),h(bJ,{label:"Open Deals",value:TJ(G.openValue),hint:`${G.openCount} active`}),h(bJ,{label:"Won",value:TJ(G.wonValue),hint:`${G.wonCount} closed`}),h(bJ,{label:"Lost",value:G.lostCount,hint:"deals lost"})]}),E(BY,{defaultValue:"pipeline",className:"w-full",children:[E(kY,{children:[E(nJ,{value:"pipeline",children:[h("span",{className:"mr-2",children:"\uD83D\uDCCA"}),"Pipeline"]}),E(nJ,{value:"list",children:[h("span",{className:"mr-2",children:"\uD83D\uDCCB"}),"All Deals"]}),E(nJ,{value:"metrics",children:[h("span",{className:"mr-2",children:"\uD83D\uDCC8"}),"Metrics"]})]}),h(iJ,{value:"pipeline",className:"min-h-[400px]",children:h(hJ,{dealsByStage:V,stages:X,onDealClick:O,onDealMove:L})}),h(iJ,{value:"list",className:"min-h-[400px]",children:h(AX,{onDealClick:O})}),h(iJ,{value:"metrics",className:"min-h-[400px]",children:h(vY,{stats:G})})]}),h(rJ,{isOpen:J,onClose:()=>Y(!1),onSubmit:async(N)=>{await R.createDeal(N)},stages:X,isLoading:R.createState.loading}),h(oJ,{isOpen:z,deal:F,stages:X,onClose:()=>{P(!1),q(null)},onWin:async(N)=>{await R.winDeal(N)},onLose:async(N)=>{await R.loseDeal(N)},onMove:async(N)=>{await R.moveDeal(N),$()},isLoading:R.isLoading})]})}function vY({stats:J}){if(!J)return null;return h("div",{className:"space-y-6",children:E("div",{className:"rounded-xl border border-border bg-card p-6",children:[h("h3",{className:"mb-4 font-semibold text-lg",children:"Pipeline Overview"}),E("dl",{className:"grid gap-4 sm:grid-cols-3",children:[E("div",{children:[h("dt",{className:"text-muted-foreground text-sm",children:"Win Rate"}),E("dd",{className:"font-semibold text-2xl",children:[J.total>0?(J.wonCount/J.total*100).toFixed(0):0,"%"]})]}),E("div",{children:[h("dt",{className:"text-muted-foreground text-sm",children:"Avg Deal Size"}),h("dd",{className:"font-semibold text-2xl",children:TJ(J.total>0?J.totalValue/J.total:0)})]}),E("div",{children:[h("dt",{className:"text-muted-foreground text-sm",children:"Conversion"}),E("dd",{className:"font-semibold text-2xl",children:[J.wonCount," / ",J.total]})]})]})]})})}var MY={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"}]},LY={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"}]},J3=[MY,LY];function o(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0}).format(J)}var IY={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="PipelineKanbanView")throw Error("crmPipelineMarkdownRenderer: not PipelineKanbanView");let F="pipeline-1",[q,z]=await Promise.all([kJ({pipelineId:F,limit:50}),vJ({pipelineId:F})]),P=q.deals,k=z,V={};for(let H of k)V[H.id]=P.filter((Z)=>Z.stageId===H.id&&Z.status==="OPEN");let X=["# CRM Pipeline","",`**Total Value**: ${o(q.totalValue)}`,`**Total Deals**: ${q.total}`,""];for(let H of k.sort((Z,G)=>Z.position-G.position)){let Z=V[H.id]??[],G=Z.reduce(($,R)=>$+R.value,0);if(X.push(`## ${H.name}`),X.push(`_${Z.length} deals · ${o(G)}_`),X.push(""),Z.length===0)X.push("_No deals_");else for(let $ of Z)X.push(`- **${$.name}** - ${o($.value,$.currency)}`);X.push("")}return{mimeType:"text/markdown",body:X.join(`
71
- `)}}},hY={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="CrmDashboard")throw Error("crmDashboardMarkdownRenderer: not CrmDashboard");let F="pipeline-1",[q,z]=await Promise.all([kJ({pipelineId:F,limit:100}),vJ({pipelineId:F})]),P=q.deals,k=z,V=P.filter((O)=>O.status==="OPEN"),X=P.filter((O)=>O.status==="WON"),H=P.filter((O)=>O.status==="LOST"),Z=V.reduce((O,L)=>O+L.value,0),G=X.reduce((O,L)=>O+L.value,0),$=["# CRM Dashboard","","> Sales pipeline overview and key metrics","","## Summary","","| Metric | Value |","|--------|-------|",`| Total Deals | ${q.total} |`,`| Pipeline Value | ${o(q.totalValue)} |`,`| Open Deals | ${V.length} (${o(Z)}) |`,`| Won Deals | ${X.length} (${o(G)}) |`,`| Lost Deals | ${H.length} |`,"","## Pipeline Stages",""];$.push("| Stage | Deals | Value |"),$.push("|-------|-------|-------|");for(let O of k.sort((L,N)=>L.position-N.position)){let L=V.filter((U)=>U.stageId===O.id),N=L.reduce((U,Q)=>U+Q.value,0);$.push(`| ${O.name} | ${L.length} | ${o(N)} |`)}$.push(""),$.push("## Recent Deals"),$.push("");let R=P.slice(0,10);if(R.length===0)$.push("_No deals yet._");else{$.push("| Deal | Value | Stage | Status |"),$.push("|------|-------|-------|--------|");for(let O of R){let L=k.find((N)=>N.id===O.stageId);$.push(`| ${O.name} | ${o(O.value,O.currency)} | ${L?.name??"-"} | ${O.status} |`)}}return{mimeType:"text/markdown",body:$.join(`
72
- `)}}};import{jsx as BX}from"react/jsx-runtime";function wY(){let{dealsByStage:J,stages:Y}=i();return BX(hJ,{dealsByStage:J,stages:Y})}var DY={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 BX(wY,{})}};import{identityRbacSchemaContribution as bY}from"@contractspec/lib.identity-rbac";import{auditTrailSchemaContribution as TY}from"@contractspec/module.audit-trail";import{notificationsSchemaContribution as CY}from"@contractspec/module.notifications";var I3={modules:[bY,TY,CY,UX],provider:"postgresql",outputPath:"./prisma/schema/generated.prisma"};export{cJ as useDealMutations,i as useDealList,I3 as schemaComposition,iX as mockWinDealHandler,lX as mockMoveDealHandler,nX as mockLoseDealHandler,kJ as mockListDealsHandler,vJ as mockGetPipelineStagesHandler,sX as mockGetDealsByStageHandler,dX as mockCreateDealHandler,uX as example,LY as crmSalesRepOverlay,UX as crmPipelineSchemaContribution,DY as crmPipelineReactRenderer,IY as crmPipelineMarkdownRenderer,J3 as crmOverlays,MY as crmDemoOverlay,hY as crmDashboardMarkdownRenderer,yZ as createCrmHandlers,UJ as WinDealInputModel,JX as WinDealContract,SJ as TaskTypeEnum,pJ as TaskStatusEnum,mJ as TaskPriorityEnum,zX as TaskEntity,IZ as TaskCompletedEvent,GX as StageEntity,sZ as PipelineMetricsPresentation,J0 as PipelineKanbanPresentation,HX as PipelineEntity,zJ as MoveDealInputModel,eJ as MoveDealContract,qJ as MOCK_STAGES,f as MOCK_DEALS,xZ as MOCK_CONTACTS,fZ as MOCK_COMPANIES,NJ as LoseDealInputModel,XX as LoseDealContract,PJ as ListDealsOutputModel,_J as ListDealsInputModel,YX as ListDealsContract,KJ as DealWonPayloadModel,BZ as DealWonEvent,FJ as DealStatusFilterEnum,fJ as DealStatusEnum,WJ as DealMovedPayloadModel,OZ as DealMovedEvent,g as DealModel,VJ as DealLostPayloadModel,kZ as DealLostEvent,X0 as DealListPresentation,FX as DealEntity,Y0 as DealDetailPresentation,AZ as DealCreatedEvent,Z0 as DealCardPresentation,oJ as DealActionsModal,jY as CrmPipelineFeature,hJ as CrmPipelineBoard,PX as CrmDealCard,nZ as CrmDashboardPresentation,o0 as CrmDashboard,rJ as CreateDealModal,QJ as CreateDealInputModel,aJ as CreateDealContract,yJ as ContactStatusEnum,qX as ContactEntity,VZ as ContactCreatedEvent,jJ as CompanySizeEnum,$X as CompanyEntity,WX as ActivityEntity};
69
+ - Use Feature Flags for experimental stages/SLAs; default safe/off.`}];LX(IX);import{defineEntity as wX,defineEntityEnum as DX,field as I,index as $X}from"@contractspec/lib.schema";var fJ=DX({name:"CompanySize",values:["STARTUP","SMALL","MEDIUM","LARGE","ENTERPRISE"],schema:"crm",description:"Size category of a company."}),qX=wX({name:"Company",description:"A company/organization in the CRM.",schema:"crm",map:"company",fields:{id:I.id({description:"Unique company ID"}),name:I.string({description:"Company name"}),domain:I.string({isOptional:!0,description:"Website domain"}),website:I.url({isOptional:!0}),industry:I.string({isOptional:!0}),size:I.enum("CompanySize",{isOptional:!0}),employeeCount:I.int({isOptional:!0}),annualRevenue:I.decimal({isOptional:!0}),organizationId:I.foreignKey(),ownerId:I.foreignKey({description:"Account owner"}),phone:I.string({isOptional:!0}),email:I.email({isOptional:!0}),address:I.string({isOptional:!0}),city:I.string({isOptional:!0}),state:I.string({isOptional:!0}),country:I.string({isOptional:!0}),postalCode:I.string({isOptional:!0}),linkedInUrl:I.url({isOptional:!0}),description:I.string({isOptional:!0}),tags:I.string({isArray:!0}),customFields:I.json({isOptional:!0}),createdAt:I.createdAt(),updatedAt:I.updatedAt(),contacts:I.hasMany("Contact"),deals:I.hasMany("Deal")},indexes:[$X.on(["organizationId","ownerId"]),$X.on(["domain"])],enums:[fJ]});import{defineEntity as hX,defineEntityEnum as bX,field as M,index as kJ}from"@contractspec/lib.schema";var gJ=bX({name:"ContactStatus",values:["LEAD","PROSPECT","CUSTOMER","CHURNED","ARCHIVED"],schema:"crm",description:"Status of a contact in the sales funnel."}),HX=hX({name:"Contact",description:"An individual person in the CRM.",schema:"crm",map:"contact",fields:{id:M.id({description:"Unique contact ID"}),firstName:M.string({description:"First name"}),lastName:M.string({description:"Last name"}),email:M.email({isOptional:!0,isUnique:!0}),phone:M.string({isOptional:!0}),companyId:M.string({isOptional:!0,description:"Associated company"}),jobTitle:M.string({isOptional:!0}),status:M.enum("ContactStatus",{default:"LEAD"}),organizationId:M.foreignKey(),ownerId:M.foreignKey({description:"Sales rep who owns this contact"}),source:M.string({isOptional:!0,description:"Lead source"}),linkedInUrl:M.url({isOptional:!0}),twitterHandle:M.string({isOptional:!0}),address:M.string({isOptional:!0}),city:M.string({isOptional:!0}),state:M.string({isOptional:!0}),country:M.string({isOptional:!0}),postalCode:M.string({isOptional:!0}),notes:M.string({isOptional:!0}),tags:M.string({isArray:!0}),customFields:M.json({isOptional:!0}),lastContactedAt:M.dateTime({isOptional:!0}),nextFollowUpAt:M.dateTime({isOptional:!0}),createdAt:M.createdAt(),updatedAt:M.updatedAt(),company:M.belongsTo("Company",["companyId"],["id"]),deals:M.hasMany("Deal"),tasks:M.hasMany("Task"),activities:M.hasMany("Activity")},indexes:[kJ.on(["organizationId","status"]),kJ.on(["organizationId","ownerId"]),kJ.on(["organizationId","companyId"]),kJ.on(["email"])],enums:[gJ]});import{defineEntity as xJ,defineEntityEnum as TX,field as U,index as YJ}from"@contractspec/lib.schema";var SJ=TX({name:"DealStatus",values:["OPEN","WON","LOST","STALE"],schema:"crm",description:"Status of a deal."}),GX=xJ({name:"Pipeline",description:"A sales pipeline with stages.",schema:"crm",map:"pipeline",fields:{id:U.id(),name:U.string({description:"Pipeline name"}),description:U.string({isOptional:!0}),organizationId:U.foreignKey(),isDefault:U.boolean({default:!1}),createdAt:U.createdAt(),updatedAt:U.updatedAt(),stages:U.hasMany("Stage"),deals:U.hasMany("Deal")}}),FX=xJ({name:"Stage",description:"A stage within a sales pipeline.",schema:"crm",map:"stage",fields:{id:U.id(),name:U.string({description:"Stage name"}),pipelineId:U.foreignKey(),position:U.int({description:"Order in pipeline"}),probability:U.int({default:0,description:"Win probability (0-100)"}),isWonStage:U.boolean({default:!1}),isLostStage:U.boolean({default:!1}),color:U.string({isOptional:!0,description:"Stage color for UI"}),createdAt:U.createdAt(),updatedAt:U.updatedAt(),pipeline:U.belongsTo("Pipeline",["pipelineId"],["id"],{onDelete:"Cascade"}),deals:U.hasMany("Deal")},indexes:[YJ.on(["pipelineId","position"])]}),QX=xJ({name:"Deal",description:"A sales opportunity/deal.",schema:"crm",map:"deal",fields:{id:U.id({description:"Unique deal ID"}),name:U.string({description:"Deal name"}),value:U.decimal({description:"Deal value"}),currency:U.string({default:'"USD"'}),pipelineId:U.foreignKey(),stageId:U.foreignKey(),status:U.enum("DealStatus",{default:"OPEN"}),contactId:U.string({isOptional:!0}),companyId:U.string({isOptional:!0}),organizationId:U.foreignKey(),ownerId:U.foreignKey({description:"Deal owner"}),expectedCloseDate:U.dateTime({isOptional:!0}),closedAt:U.dateTime({isOptional:!0}),lostReason:U.string({isOptional:!0}),wonSource:U.string({isOptional:!0}),notes:U.string({isOptional:!0}),tags:U.string({isArray:!0}),customFields:U.json({isOptional:!0}),stagePosition:U.int({default:0}),createdAt:U.createdAt(),updatedAt:U.updatedAt(),pipeline:U.belongsTo("Pipeline",["pipelineId"],["id"]),stage:U.belongsTo("Stage",["stageId"],["id"]),contact:U.belongsTo("Contact",["contactId"],["id"]),company:U.belongsTo("Company",["companyId"],["id"]),tasks:U.hasMany("Task"),activities:U.hasMany("Activity")},indexes:[YJ.on(["organizationId","status"]),YJ.on(["pipelineId","stageId","stagePosition"]),YJ.on(["ownerId","status"]),YJ.on(["expectedCloseDate"])],enums:[SJ]});import{defineEntity as zX,defineEntityEnum as mJ,field as O,index as n}from"@contractspec/lib.schema";var pJ=mJ({name:"TaskType",values:["CALL","EMAIL","MEETING","TODO","FOLLOW_UP","OTHER"],schema:"crm",description:"Type of CRM task."}),cJ=mJ({name:"TaskPriority",values:["LOW","NORMAL","HIGH","URGENT"],schema:"crm",description:"Priority of a task."}),uJ=mJ({name:"TaskStatus",values:["PENDING","IN_PROGRESS","COMPLETED","CANCELLED"],schema:"crm",description:"Status of a task."}),WX=zX({name:"Task",description:"A task or follow-up activity.",schema:"crm",map:"task",fields:{id:O.id(),title:O.string({description:"Task title"}),description:O.string({isOptional:!0}),type:O.enum("TaskType",{default:"TODO"}),priority:O.enum("TaskPriority",{default:"NORMAL"}),status:O.enum("TaskStatus",{default:"PENDING"}),dueDate:O.dateTime({isOptional:!0}),reminderAt:O.dateTime({isOptional:!0}),contactId:O.string({isOptional:!0}),dealId:O.string({isOptional:!0}),companyId:O.string({isOptional:!0}),organizationId:O.foreignKey(),assignedTo:O.foreignKey({description:"User assigned to this task"}),createdBy:O.foreignKey(),completedAt:O.dateTime({isOptional:!0}),completedBy:O.string({isOptional:!0}),createdAt:O.createdAt(),updatedAt:O.updatedAt(),contact:O.belongsTo("Contact",["contactId"],["id"]),deal:O.belongsTo("Deal",["dealId"],["id"]),company:O.belongsTo("Company",["companyId"],["id"])},indexes:[n.on(["organizationId","assignedTo","status"]),n.on(["dueDate","status"]),n.on(["contactId"]),n.on(["dealId"])],enums:[pJ,cJ,uJ]}),UX=zX({name:"Activity",description:"An activity/interaction logged in the CRM.",schema:"crm",map:"activity",fields:{id:O.id(),type:O.enum("TaskType"),subject:O.string(),description:O.string({isOptional:!0}),contactId:O.string({isOptional:!0}),dealId:O.string({isOptional:!0}),companyId:O.string({isOptional:!0}),organizationId:O.foreignKey(),performedBy:O.foreignKey(),outcome:O.string({isOptional:!0}),occurredAt:O.dateTime(),duration:O.int({isOptional:!0,description:"Duration in minutes"}),createdAt:O.createdAt(),contact:O.belongsTo("Contact",["contactId"],["id"]),deal:O.belongsTo("Deal",["dealId"],["id"]),company:O.belongsTo("Company",["companyId"],["id"])},indexes:[n.on(["contactId","occurredAt"]),n.on(["dealId","occurredAt"])]});var KX={moduleId:"@contractspec/example.crm-pipeline",entities:[qX,HX,QX,GX,FX,WX,UX],enums:[fJ,gJ,SJ,pJ,cJ,uJ]};import{defineEvent as CX}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as EX,ScalarTypeEnum as ZJ}from"@contractspec/lib.schema";var jX=EX({name:"ContactCreatedPayload",description:"Payload when a contact is created",fields:{contactId:{type:ZJ.String_unsecure(),isOptional:!1},email:{type:ZJ.EmailAddress(),isOptional:!0},organizationId:{type:ZJ.String_unsecure(),isOptional:!1},ownerId:{type:ZJ.String_unsecure(),isOptional:!1},createdAt:{type:ZJ.DateTime(),isOptional:!1}}}),RZ=CX({meta:{key:"contact.created",version:"1.0.0",description:"A new contact has been created.",stability:"stable",owners:["@crm-team"],tags:["contact","created"]},payload:jX});import{defineEvent as BJ}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as MJ,ScalarTypeEnum as D}from"@contractspec/lib.schema";var yX=MJ({name:"DealCreatedPayload",description:"Payload when a deal is created",fields:{dealId:{type:D.String_unsecure(),isOptional:!1},name:{type:D.String_unsecure(),isOptional:!1},value:{type:D.Float_unsecure(),isOptional:!1},pipelineId:{type:D.String_unsecure(),isOptional:!1},stageId:{type:D.String_unsecure(),isOptional:!1},ownerId:{type:D.String_unsecure(),isOptional:!1},createdAt:{type:D.DateTime(),isOptional:!1}}}),fX=MJ({name:"DealMovedEventPayload",description:"Payload when a deal is moved to another stage",fields:{dealId:{type:D.String_unsecure(),isOptional:!1},fromStageId:{type:D.String_unsecure(),isOptional:!1},toStageId:{type:D.String_unsecure(),isOptional:!1},movedBy:{type:D.String_unsecure(),isOptional:!1},movedAt:{type:D.DateTime(),isOptional:!1}}}),gX=MJ({name:"DealWonEventPayload",description:"Payload when a deal is won",fields:{dealId:{type:D.String_unsecure(),isOptional:!1},value:{type:D.Float_unsecure(),isOptional:!1},currency:{type:D.String_unsecure(),isOptional:!1},contactId:{type:D.String_unsecure(),isOptional:!0},companyId:{type:D.String_unsecure(),isOptional:!0},ownerId:{type:D.String_unsecure(),isOptional:!1},wonAt:{type:D.DateTime(),isOptional:!1}}}),xX=MJ({name:"DealLostEventPayload",description:"Payload when a deal is lost",fields:{dealId:{type:D.String_unsecure(),isOptional:!1},value:{type:D.Float_unsecure(),isOptional:!1},reason:{type:D.String_unsecure(),isOptional:!1},ownerId:{type:D.String_unsecure(),isOptional:!1},lostAt:{type:D.DateTime(),isOptional:!1}}}),kZ=BJ({meta:{key:"deal.created",version:"1.0.0",description:"A new deal has been created.",stability:"stable",owners:["@crm-team"],tags:["deal","created"]},payload:yX}),BZ=BJ({meta:{key:"deal.moved",version:"1.0.0",description:"A deal has been moved to a different stage.",stability:"stable",owners:["@crm-team"],tags:["deal","moved"]},payload:fX}),MZ=BJ({meta:{key:"deal.won",version:"1.0.0",description:"A deal has been won.",stability:"stable",owners:["@crm-team"],tags:["deal","won"]},payload:gX}),vZ=BJ({meta:{key:"deal.lost",version:"1.0.0",description:"A deal has been lost.",stability:"stable",owners:["@crm-team"],tags:["deal","lost"]},payload:xX});import{defineEvent as SX}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as mX,ScalarTypeEnum as $J}from"@contractspec/lib.schema";var pX=mX({name:"TaskCompletedPayload",description:"Payload when a task is completed",fields:{taskId:{type:$J.String_unsecure(),isOptional:!1},type:{type:$J.String_unsecure(),isOptional:!1},assignedTo:{type:$J.String_unsecure(),isOptional:!1},completedBy:{type:$J.String_unsecure(),isOptional:!1},completedAt:{type:$J.DateTime(),isOptional:!1}}}),DZ=SX({meta:{key:"task.completed",version:"1.0.0",description:"A task has been completed.",stability:"stable",owners:["@crm-team"],tags:["task","lifecycle"]},payload:pX});import{defineExample as cX}from"@contractspec/lib.contracts-spec/examples";var uX=cX({meta:{key:"examples.crm-pipeline",version:"1.0.0",title:"Crm Pipeline",description:"CRM Pipeline - Contacts, Companies, Deals, Tasks",kind:"template",visibility:"experimental",stability:"experimental",owners:["@contractspec-core"],tags:["package","examples","crm-pipeline"]},surfaces:{templates:!0,sandbox:{enabled:!0,modes:["playground","specs"]},studio:{enabled:!1,installable:!1},mcp:{enabled:!1}},entrypoints:{packageName:"@contractspec/example.crm-pipeline"}}),rX=uX;import{web as oX}from"@contractspec/lib.runtime-sandbox";var{generateId:dX}=oX;function s(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 NX={name:"name",value:"value",status:"status",expectedCloseDate:"expectedCloseDate",updatedAt:"updatedAt"};function gZ(J){async function Y(X){let{projectId:G,pipelineId:W,stageId:q,status:Z,ownerId:V,search:$,limit:L=20,offset:_=0,sortBy:K="value",sortDirection:z="desc"}=X,v="WHERE projectId = ?",T=[G];if(W)v+=" AND pipelineId = ?",T.push(W);if(q)v+=" AND stageId = ?",T.push(q);if(Z&&Z!=="all")v+=" AND status = ?",T.push(Z);if(V)v+=" AND ownerId = ?",T.push(V);if($)v+=" AND name LIKE ?",T.push(`%${$}%`);let d=(await J.query(`SELECT COUNT(*) as count FROM crm_deal ${v}`,T)).rows[0]?.count??0,j=(await J.query(`SELECT COALESCE(SUM(value), 0) as total FROM crm_deal ${v}`,T)).rows[0]?.total??0,k=NX[K]??NX.value,JJ=z==="asc"?"ASC":"DESC";return{deals:(await J.query(`SELECT * FROM crm_deal ${v} ORDER BY ${k} ${JJ} LIMIT ? OFFSET ?`,[...T,L,_])).rows.map(s),total:d,totalValue:j}}async function F(X,G){let W=dX("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)
70
+ 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 s(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 s(Z[0])}async function Q(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 s(q[0])}async function P(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 s(q[0])}async function B(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((V)=>V.stageId===Z.id).map(s);return q}async function R(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:F,moveDeal:H,winDeal:Q,loseDeal:P,getDealsByStage:B,getPipelineStages:R}}var qJ=[{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"}],f=[{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")}],SZ=[{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")}],mZ=[{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 vJ(J){let{pipelineId:Y,stageId:F,status:H,ownerId:Q,search:P,limit:B=20,offset:R=0}=J,X=[...f];if(Y)X=X.filter((Z)=>Z.pipelineId===Y);if(F)X=X.filter((Z)=>Z.stageId===F);if(H&&H!=="all")X=X.filter((Z)=>Z.status===H);if(Q)X=X.filter((Z)=>Z.ownerId===Q);if(P){let Z=P.toLowerCase();X=X.filter((V)=>V.name.toLowerCase().includes(Z))}X.sort((Z,V)=>V.value-Z.value);let G=X.length,W=X.reduce((Z,V)=>Z+V.value,0);return{deals:X.slice(R,R+B),total:G,totalValue:W}}async function lX(J,Y){let F=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:F,updatedAt:F};return f.push(H),H}async function iX(J){let Y=f.findIndex((P)=>P.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let F=f[Y];if(!F)throw Error("NOT_FOUND");if(!qJ.find((P)=>P.id===J.stageId))throw Error("INVALID_STAGE");let Q={...F,stageId:J.stageId,updatedAt:new Date};return f[Y]=Q,Q}async function nX(J){let Y=f.findIndex((Q)=>Q.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let F=f[Y];if(!F)throw Error("NOT_FOUND");let H={...F,status:"WON",updatedAt:new Date};return f[Y]=H,H}async function sX(J){let Y=f.findIndex((Q)=>Q.id===J.dealId);if(Y===-1)throw Error("NOT_FOUND");let F=f[Y];if(!F)throw Error("NOT_FOUND");let H={...F,status:"LOST",updatedAt:new Date};return f[Y]=H,H}async function tX(J){let Y=f.filter((H)=>H.pipelineId===J.pipelineId&&H.status==="OPEN"),F={};for(let H of qJ)F[H.id]=Y.filter((Q)=>Q.stageId===H.id);return F}async function LJ(J){return qJ.filter((Y)=>Y.pipelineId===J.pipelineId)}import{definePresentation as VX,StabilityEnum as _X}from"@contractspec/lib.contracts-spec";var tZ=VX({meta:{key:"crm.dashboard",version:"1.0.0",title:"CRM Dashboard",description:"Main CRM dashboard with pipeline overview, deal stats, and activities",domain:"crm-pipeline",owners:["@crm-team"],tags:["dashboard","overview"],stability:_X.Experimental,goal:"Provide a high-level overview of CRM performance and active deals.",context:"The landing page for CRM users."},source:{type:"component",framework:"react",componentKey:"CrmDashboard"},targets:["react","markdown"],policy:{flags:["crm.enabled"]}}),aZ=VX({meta:{key:"crm.pipeline.metrics",version:"1.0.0",title:"Pipeline Metrics",description:"Pipeline metrics and forecasting view",domain:"crm-pipeline",owners:["@crm-team"],tags:["pipeline","metrics","forecast"],stability:_X.Experimental,goal:"Track pipeline health and sales forecasts.",context:"Data-intensive widget for sales managers."},source:{type:"component",framework:"react",componentKey:"PipelineMetricsView"},targets:["react","markdown"],policy:{flags:["crm.metrics.enabled"]}});import{definePresentation as IJ,StabilityEnum as wJ}from"@contractspec/lib.contracts-spec";var Y0=IJ({meta:{key:"crm.pipeline.kanban",version:"1.0.0",title:"Pipeline Kanban",description:"Kanban board view of deals organized by stage",domain:"crm-pipeline",owners:["@crm-team"],tags:["pipeline","kanban","deals"],stability:wJ.Experimental,goal:"Visualize the sales pipeline status and deal distribution across stages.",context:"Used in the sales dashboard and management reports."},source:{type:"component",framework:"react",componentKey:"PipelineKanbanView",props:y},targets:["react","markdown"],policy:{flags:["crm.pipeline.enabled"]}}),Z0=IJ({meta:{key:"crm.deal.viewList",version:"1.0.0",title:"Deal List",description:"List view of deals with value, status, and owner info",domain:"crm-pipeline",owners:["@crm-team"],tags:["deal","list"],stability:wJ.Experimental,goal:"Search, filter, and review deal lists.",context:"Standard view for deal management and bulk actions."},source:{type:"component",framework:"react",componentKey:"DealListView",props:y},targets:["react","markdown","application/json"],policy:{flags:["crm.deals.enabled"]}}),$0=IJ({meta:{key:"crm.deal.detail",version:"1.0.0",title:"Deal Details",description:"Detailed view of a deal with activities, contacts, and history",domain:"crm-pipeline",owners:["@crm-team"],tags:["deal","detail"],stability:wJ.Experimental,goal:"Deep dive into deal details and historical activities.",context:"The main workspace for managing a single deal execution."},source:{type:"component",framework:"react",componentKey:"DealDetailView"},targets:["react","markdown"],policy:{flags:["crm.deals.enabled"]}}),q0=IJ({meta:{key:"crm.deal.card",version:"1.0.0",title:"Deal Card",description:"Compact deal card for kanban board display",domain:"crm-pipeline",owners:["@crm-team"],tags:["deal","card","kanban"],stability:wJ.Experimental,goal:"Provide a quick overview of deal status in the pipeline view.",context:"Condensed representation used within the Pipeline Kanban board."},source:{type:"component",framework:"react",componentKey:"DealCard",props:y},targets:["react"],policy:{flags:["crm.deals.enabled"]}});import{jsx as DJ,jsxs as RX}from"react/jsx-runtime";function aX(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function AX({deal:J,onClick:Y}){let F=J.expectedCloseDate?Math.ceil((J.expectedCloseDate.getTime()-Date.now())/86400000):null;return RX("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:[DJ("h4",{className:"font-medium leading-snug",children:J.name}),DJ("div",{className:"mt-2 font-semibold text-lg text-primary",children:aX(J.value,J.currency)}),RX("div",{className:"mt-3 flex items-center justify-between text-muted-foreground text-xs",children:[F!==null&&DJ("span",{className:F<0?"text-red-500":F<=7?"text-yellow-600 dark:text-yellow-500":"",children:F<0?`${Math.abs(F)}d overdue`:F===0?"Due today":`${F}d left`}),DJ("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 eX}from"react";import{jsx as u,jsxs as l}from"react/jsx-runtime";function JY(J){if(J>=1e6)return`$${(J/1e6).toFixed(1)}M`;if(J>=1000)return`$${(J/1000).toFixed(0)}K`;return`$${J}`}function hJ({dealsByStage:J,stages:Y,onDealClick:F,onDealMove:H}){let[Q,P]=eX(null),B=[...Y].sort((X,G)=>X.position-G.position),R=(X,G)=>{H?.(X,G),P(null)};return u("div",{className:"flex gap-4 overflow-x-auto pb-4",children:B.map((X)=>{let G=J[X.id]??[],W=G.reduce((q,Z)=>q+Z.value,0);return l("div",{className:"flex w-72 flex-shrink-0 flex-col rounded-lg bg-muted/30",children:[l("div",{className:"flex items-center justify-between border-border border-b px-3 py-2",children:[l("div",{children:[u("h3",{className:"font-medium",children:X.name}),l("p",{className:"text-muted-foreground text-xs",children:[G.length," deals · ",JY(W)]})]}),u("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",children:G.length})]}),u("div",{className:"flex flex-1 flex-col gap-2 p-2",children:G.length===0?u("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)=>l("div",{className:"group relative",children:[u(AX,{deal:q,onClick:()=>F?.(q.id)}),q.status==="OPEN"&&H&&l("div",{className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100",children:[u("button",{type:"button",onClick:(Z)=>{Z.stopPropagation(),P(Q===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:"➡️"}),Q===q.id&&l("div",{className:"absolute top-7 right-0 z-20 min-w-[140px] rounded-lg border border-border bg-card py-1 shadow-lg",children:[u("p",{className:"px-3 py-1 font-medium text-muted-foreground text-xs",children:"Move to:"}),B.filter((Z)=>Z.id!==q.stageId).map((Z)=>u("button",{type:"button",onClick:(V)=>{V.stopPropagation(),R(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 XY}from"@contractspec/lib.example-shared-ui";import{useCallback as YY,useEffect as ZY,useMemo as $Y,useState as t}from"react";function i(J={}){let{handlers:Y,projectId:F}=XY(),{crm:H}=Y,[Q,P]=t(null),[B,R]=t({}),[X,G]=t([]),[W,q]=t(!0),[Z,V]=t(null),[$,L]=t(0),_=J.pipelineId??"pipeline-1",K=J.pageIndex??$,z=J.pageSize??J.limit??50,[v]=J.sorting??[],T=v?.id==="deal"?"name":v?.id,x=v?v.desc?"desc":"asc":void 0,d=YY(async()=>{q(!0),V(null);try{let[j,k,JJ]=await Promise.all([H.listDeals({projectId:F,pipelineId:_,stageId:J.stageId,status:J.status==="all"?void 0:J.status,search:J.search,limit:z,offset:K*z,sortBy:T==="name"||T==="value"||T==="status"||T==="expectedCloseDate"||T==="updatedAt"?T:void 0,sortDirection:x}),H.getDealsByStage({projectId:F,pipelineId:_}),H.getPipelineStages({pipelineId:_})]);P(j),R(k),G(JJ)}catch(j){V(j instanceof Error?j:Error("Unknown error"))}finally{q(!1)}},[H,F,_,J.stageId,J.status,J.search,K,z,T,x]);ZY(()=>{d()},[d]);let QJ=$Y(()=>{if(!Q)return null;let j=Q.deals.filter((S)=>S.status==="OPEN"),k=Q.deals.filter((S)=>S.status==="WON"),JJ=Q.deals.filter((S)=>S.status==="LOST");return{total:Q.total,totalValue:Q.totalValue,openCount:j.length,openValue:j.reduce((S,jJ)=>S+jJ.value,0),wonCount:k.length,wonValue:k.reduce((S,jJ)=>S+jJ.value,0),lostCount:JJ.length}},[Q]);return{data:Q,dealsByStage:B,stages:X,loading:W,error:Z,stats:QJ,page:K+1,pageIndex:K,pageSize:z,refetch:d,nextPage:J.pageIndex===void 0?()=>L((j)=>j+1):void 0,prevPage:J.pageIndex===void 0?()=>K>0&&L((j)=>j-1):void 0}}import{useTemplateRuntime as qY}from"@contractspec/lib.example-shared-ui";import{useCallback as bJ,useState as TJ}from"react";function rJ(J={}){let{handlers:Y,projectId:F}=qY(),{crm:H}=Y,[Q,P]=TJ({loading:!1,error:null,data:null}),[B,R]=TJ({loading:!1,error:null,data:null}),[X,G]=TJ({loading:!1,error:null,data:null}),[W,q]=TJ({loading:!1,error:null,data:null}),Z=bJ(async(_)=>{P({loading:!0,error:null,data:null});try{let K=await H.createDeal(_,{projectId:F,ownerId:"user-1"});return P({loading:!1,error:null,data:K}),J.onSuccess?.(),K}catch(K){let z=K instanceof Error?K:Error("Failed to create deal");return P({loading:!1,error:z,data:null}),J.onError?.(z),null}},[H,F,J]),V=bJ(async(_)=>{R({loading:!0,error:null,data:null});try{let K=await H.moveDeal(_);return R({loading:!1,error:null,data:K}),J.onSuccess?.(),K}catch(K){let z=K instanceof Error?K:Error("Failed to move deal");return R({loading:!1,error:z,data:null}),J.onError?.(z),null}},[H,J]),$=bJ(async(_)=>{G({loading:!0,error:null,data:null});try{let K=await H.winDeal(_);return G({loading:!1,error:null,data:K}),J.onSuccess?.(),K}catch(K){let z=K instanceof Error?K:Error("Failed to mark deal as won");return G({loading:!1,error:z,data:null}),J.onError?.(z),null}},[H,J]),L=bJ(async(_)=>{q({loading:!0,error:null,data:null});try{let K=await H.loseDeal(_);return q({loading:!1,error:null,data:K}),J.onSuccess?.(),K}catch(K){let z=K instanceof Error?K:Error("Failed to mark deal as lost");return q({loading:!1,error:z,data:null}),J.onError?.(z),null}},[H,J]);return{createDeal:Z,moveDeal:V,winDeal:$,loseDeal:L,createState:Q,moveState:B,winState:X,loseState:W,isLoading:Q.loading||B.loading||X.loading||W.loading}}import{Button as PX,Input as oJ}from"@contractspec/lib.design-system";import{useState as a}from"react";import{jsx as C,jsxs as p}from"react/jsx-runtime";var HY=["USD","EUR","GBP","CAD"],GY="pipeline-1";function dJ({isOpen:J,onClose:Y,onSubmit:F,stages:H,isLoading:Q=!1}){let[P,B]=a(""),[R,X]=a(""),[G,W]=a("USD"),[q,Z]=a(H[0]?.id??""),[V,$]=a(""),[L,_]=a(null),K=async(z)=>{if(z.preventDefault(),_(null),!P.trim()){_("Deal name is required");return}let v=parseFloat(R);if(isNaN(v)||v<=0){_("Value must be a positive number");return}if(!q){_("Please select a pipeline stage");return}try{await F({name:P.trim(),value:v,currency:G,pipelineId:GY,stageId:q,expectedCloseDate:V?new Date(V):void 0}),B(""),X(""),W("USD"),Z(H[0]?.id??""),$(""),Y()}catch(T){_(T instanceof Error?T.message:"Failed to create deal")}};if(!J)return null;return p("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[C("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:Y,role:"button",tabIndex:0,onKeyDown:(z)=>{if(z.key==="Enter"||z.key===" ")Y()},"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:[C("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Deal"}),p("form",{onSubmit:K,className:"space-y-4",children:[p("div",{children:[C("label",{htmlFor:"deal-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Deal Name *"}),C(oJ,{id:"deal-name",value:P,onChange:(z)=>B(z.target.value),placeholder:"e.g., Enterprise License - Acme Corp",disabled:Q})]}),p("div",{className:"flex gap-3",children:[p("div",{className:"flex-1",children:[C("label",{htmlFor:"deal-value",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Value *"}),C(oJ,{id:"deal-value",type:"number",min:"0",step:"0.01",value:R,onChange:(z)=>X(z.target.value),placeholder:"50000",disabled:Q})]}),p("div",{className:"w-24",children:[C("label",{htmlFor:"deal-currency",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Currency"}),C("select",{id:"deal-currency",value:G,onChange:(z)=>W(z.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:HY.map((z)=>C("option",{value:z,children:z},z))})]})]}),p("div",{children:[C("label",{htmlFor:"deal-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Pipeline Stage *"}),C("select",{id:"deal-stage",value:q,onChange:(z)=>Z(z.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:H.map((z)=>C("option",{value:z.id,children:z.name},z.id))})]}),p("div",{children:[C("label",{htmlFor:"deal-close-date",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Expected Close Date"}),C(oJ,{id:"deal-close-date",type:"date",value:V,onChange:(z)=>$(z.target.value),disabled:Q})]}),L&&C("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:L}),p("div",{className:"flex justify-end gap-3 pt-2",children:[C(PX,{type:"button",variant:"ghost",onPress:Y,disabled:Q,children:"Cancel"}),C(PX,{type:"submit",disabled:Q,children:Q?"Creating...":"Create Deal"})]})]})]})]})}import{Button as c}from"@contractspec/lib.design-system";import{useState as e}from"react";import{jsx as A,jsxs as h,Fragment as QY}from"react/jsx-runtime";function FY(J,Y){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function lJ({isOpen:J,deal:Y,stages:F,onClose:H,onWin:Q,onLose:P,onMove:B,isLoading:R=!1}){let[X,G]=e("menu"),[W,q]=e(""),[Z,V]=e(""),[$,L]=e(""),[_,K]=e(""),[z,v]=e(null),T=()=>{G("menu"),q(""),V(""),L(""),K(""),v(null)},x=()=>{T(),H()},d=async()=>{if(!Y)return;v(null);try{await Q({dealId:Y.id,wonSource:W.trim()||void 0,notes:$.trim()||void 0}),x()}catch(k){v(k instanceof Error?k.message:"Failed to mark deal as won")}},QJ=async()=>{if(!Y)return;if(v(null),!Z.trim()){v("Please provide a reason for losing the deal");return}try{await P({dealId:Y.id,lostReason:Z.trim(),notes:$.trim()||void 0}),x()}catch(k){v(k instanceof Error?k.message:"Failed to mark deal as lost")}},j=async()=>{if(!Y)return;if(v(null),!_){v("Please select a stage");return}if(_===Y.stageId){v("Deal is already in this stage");return}try{await B({dealId:Y.id,stageId:_}),x()}catch(k){v(k instanceof Error?k.message:"Failed to move deal")}};if(!J||!Y)return null;return h("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[A("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:x,role:"button",tabIndex:0,onKeyDown:(k)=>{if(k.key==="Enter"||k.key===" ")x()},"aria-label":"Close modal"}),h("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[h("div",{className:"mb-4 border-border border-b pb-4",children:[A("h2",{className:"font-semibold text-xl",children:Y.name}),A("p",{className:"font-medium text-lg text-primary",children:FY(Y.value,Y.currency)}),A("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"&&h("div",{className:"space-y-3",children:[Y.status==="OPEN"&&h(QY,{children:[h(c,{className:"w-full justify-start",variant:"ghost",onPress:()=>G("win"),children:[A("span",{className:"mr-2",children:"\uD83C\uDFC6"})," Mark as Won"]}),h(c,{className:"w-full justify-start",variant:"ghost",onPress:()=>G("lose"),children:[A("span",{className:"mr-2",children:"❌"})," Mark as Lost"]}),h(c,{className:"w-full justify-start",variant:"ghost",onPress:()=>{K(Y.stageId),G("move")},children:[A("span",{className:"mr-2",children:"➡️"})," Move to Stage"]})]}),Y.status!=="OPEN"&&h("p",{className:"py-4 text-center text-muted-foreground",children:["This deal is already ",Y.status.toLowerCase(),". No actions available."]}),A("div",{className:"border-border border-t pt-3",children:A(c,{className:"w-full",variant:"outline",onPress:x,children:"Close"})})]}),X==="win"&&h("div",{className:"space-y-4",children:[h("div",{children:[A("label",{htmlFor:"won-source",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"How did you win this deal?"}),h("select",{id:"won-source",value:W,onChange:(k)=>q(k.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:[A("option",{value:"",children:"Select a source..."}),A("option",{value:"referral",children:"Referral"}),A("option",{value:"cold_outreach",children:"Cold Outreach"}),A("option",{value:"inbound",children:"Inbound Lead"}),A("option",{value:"upsell",children:"Upsell"}),A("option",{value:"other",children:"Other"})]})]}),h("div",{children:[A("label",{htmlFor:"win-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),A("textarea",{id:"win-notes",value:$,onChange:(k)=>L(k.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"})]}),z&&A("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:z}),h("div",{className:"flex justify-end gap-3 pt-2",children:[A(c,{variant:"ghost",onPress:()=>G("menu"),disabled:R,children:"Back"}),A(c,{onPress:d,disabled:R,children:R?"Processing...":"\uD83C\uDFC6 Confirm Win"})]})]}),X==="lose"&&h("div",{className:"space-y-4",children:[h("div",{children:[A("label",{htmlFor:"lost-reason",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Why was this deal lost? *"}),h("select",{id:"lost-reason",value:Z,onChange:(k)=>V(k.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:[A("option",{value:"",children:"Select a reason..."}),A("option",{value:"price",children:"Price too high"}),A("option",{value:"competitor",children:"Lost to competitor"}),A("option",{value:"no_budget",children:"No budget"}),A("option",{value:"no_decision",children:"No decision made"}),A("option",{value:"timing",children:"Bad timing"}),A("option",{value:"product_fit",children:"Product not a fit"}),A("option",{value:"other",children:"Other"})]})]}),h("div",{children:[A("label",{htmlFor:"lose-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),A("textarea",{id:"lose-notes",value:$,onChange:(k)=>L(k.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"})]}),z&&A("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:z}),h("div",{className:"flex justify-end gap-3 pt-2",children:[A(c,{variant:"ghost",onPress:()=>G("menu"),disabled:R,children:"Back"}),A(c,{variant:"destructive",onPress:QJ,disabled:R,children:R?"Processing...":"❌ Confirm Loss"})]})]}),X==="move"&&h("div",{className:"space-y-4",children:[h("div",{children:[A("label",{htmlFor:"move-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Move to Stage"}),A("select",{id:"move-stage",value:_,onChange:(k)=>K(k.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:F.map((k)=>h("option",{value:k.id,children:[k.name,k.id===Y.stageId?" (current)":""]},k.id))})]}),z&&A("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:z}),h("div",{className:"flex justify-end gap-3 pt-2",children:[A(c,{variant:"ghost",onPress:()=>G("menu"),disabled:R,children:"Back"}),A(c,{onPress:j,disabled:R,children:R?"Moving...":"➡️ Move Deal"})]})]})]})]})}import{Button as HJ,DataTable as zY,DataTableToolbar as WY,LoaderBlock as UY}from"@contractspec/lib.design-system";import{useContractTable as KY}from"@contractspec/lib.presentation-runtime-react";import{Badge as NY}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as GJ,VStack as iJ}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as g}from"@contractspec/lib.ui-kit-web/ui/text";import*as FJ from"react";import{jsx as b,jsxs as r}from"react/jsx-runtime";function VY(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function _Y(J){switch(J){case"WON":return"default";case"LOST":return"destructive";case"STALE":return"outline";default:return"secondary"}}function RY({value:J,onChange:Y}){return r(GJ,{gap:"sm",className:"flex-wrap",children:[b(HJ,{variant:J==="all"?"secondary":"outline",size:"sm",onPress:()=>Y("all"),children:"All Deals"}),b(HJ,{variant:J==="OPEN"?"secondary":"outline",size:"sm",onPress:()=>Y("OPEN"),children:"Open Only"}),b(HJ,{variant:J==="WON"?"secondary":"outline",size:"sm",onPress:()=>Y("WON"),children:"Won Only"}),b(HJ,{variant:J==="LOST"?"secondary":"outline",size:"sm",onPress:()=>Y("LOST"),children:"Lost Only"})]})}function AY({deals:J,totalItems:Y,pageIndex:F,pageSize:H,sorting:Q,search:P,status:B,loading:R,onSortingChange:X,onPaginationChange:G,onSearchChange:W,onStatusChange:q,onDealClick:Z}){let V=KY({data:J,columns:[{id:"deal",header:"Deal",label:"Deal",accessor:($)=>$.name,cell:({item:$})=>r(iJ,{gap:"xs",children:[b(g,{className:"font-medium text-sm",children:$.name}),b(g,{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:$})=>VY($.value,$.currency),align:"right",size:140,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:$})=>b(NY,{variant:_Y($),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:$})=>b(HJ,{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:Q,pagination:{pageIndex:F,pageSize:H}},onSortingChange:X,onPaginationChange:G,initialState:{columnVisibility:{updatedAt:!1},columnPinning:{left:["deal","status"],right:[]}},renderExpandedContent:($)=>r(iJ,{gap:"sm",className:"py-2",children:[r(GJ,{justify:"between",children:[b(g,{className:"font-medium text-sm",children:"Owner"}),b(g,{className:"text-muted-foreground text-sm",children:$.ownerId})]}),r(GJ,{justify:"between",children:[b(g,{className:"font-medium text-sm",children:"Contact"}),b(g,{className:"text-muted-foreground text-sm",children:$.contactId??"No linked contact"})]}),$.wonSource?r(GJ,{justify:"between",children:[b(g,{className:"font-medium text-sm",children:"Won Source"}),b(g,{className:"text-muted-foreground text-sm",children:$.wonSource})]}):null,$.lostReason?r(GJ,{justify:"between",children:[b(g,{className:"font-medium text-sm",children:"Lost Reason"}),b(g,{className:"text-muted-foreground text-sm",children:$.lostReason})]}):null,$.notes?r(iJ,{gap:"xs",children:[b(g,{className:"font-medium text-sm",children:"Notes"}),b(g,{className:"text-muted-foreground text-sm",children:$.notes})]}):null]}),getCanExpand:()=>!0});return b(zY,{controller:V,title:"All Deals",description:"Server-mode table using the shared ContractSpec controller.",loading:R,toolbar:b(WY,{controller:V,searchPlaceholder:"Search deals, companies, contacts, or notes",searchValue:P,onSearchChange:W,activeChips:B==="all"?[]:[{key:"status",label:`Status: ${B}`,onRemove:()=>q("all")}],onClearAll:()=>{W(""),q("all")},actionsStart:RY({value:B,onChange:q}),actionsEnd:r(g,{className:"text-muted-foreground text-sm",children:[Y," total deals"]})}),footer:`Page ${V.pageIndex+1} of ${V.pageCount}`,emptyState:b("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No deals found"})})}function OX({onDealClick:J}){let[Y,F]=FJ.useState([{id:"value",desc:!0}]),[H,Q]=FJ.useState({pageIndex:0,pageSize:3}),[P,B]=FJ.useState(""),[R,X]=FJ.useState("all"),{data:G,loading:W}=i({pageIndex:H.pageIndex,pageSize:H.pageSize,search:P,status:R,sorting:Y});if(W&&!G)return b(UY,{label:"Loading deals..."});return b(AY,{deals:G?.deals??[],totalItems:G?.total??0,pageIndex:H.pageIndex,pageSize:H.pageSize,sorting:Y,search:P,status:R,loading:W,onSortingChange:(q)=>{F(q),Q((Z)=>({...Z,pageIndex:0}))},onPaginationChange:Q,onSearchChange:(q)=>{B(q),Q((Z)=>({...Z,pageIndex:0}))},onStatusChange:(q)=>{X(q),Q((Z)=>({...Z,pageIndex:0}))},onDealClick:J})}import{Button as PY,ErrorState as OY,LoaderBlock as kY,StatCard as CJ,StatCardGroup as BY}from"@contractspec/lib.design-system";import{Tabs as MY,TabsContent as nJ,TabsList as vY,TabsTrigger as sJ}from"@contractspec/lib.ui-kit-web/ui/tabs";import{useCallback as kX,useState as tJ}from"react";import{jsx as w,jsxs as E}from"react/jsx-runtime";function EJ(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function l0(){let[J,Y]=tJ(!1),[F,H]=tJ(null),[Q,P]=tJ(!1),{data:B,dealsByStage:R,stages:X,loading:G,error:W,stats:q,refetch:Z}=i(),V=rJ({onSuccess:()=>{Z()}}),$=kX((_)=>{let K=R?Object.values(R).flat().find((z)=>z.id===_):null;if(K)H(K),P(!0)},[R]),L=kX(async(_,K)=>{await V.moveDeal({dealId:_,stageId:K})},[V]);if(G&&!B)return w(kY,{label:"Loading CRM..."});if(W)return w(OY,{title:"Failed to load CRM",description:W.message,onRetry:Z,retryLabel:"Retry"});return E("div",{className:"space-y-6",children:[E("div",{className:"flex items-center justify-between",children:[w("h2",{className:"font-bold text-2xl",children:"CRM Pipeline"}),E(PY,{onClick:()=>Y(!0),children:[w("span",{className:"mr-2",children:"+"})," Create Deal"]})]}),q&&E(BY,{children:[w(CJ,{label:"Total Pipeline",value:EJ(q.totalValue),hint:`${q.total} deals`}),w(CJ,{label:"Open Deals",value:EJ(q.openValue),hint:`${q.openCount} active`}),w(CJ,{label:"Won",value:EJ(q.wonValue),hint:`${q.wonCount} closed`}),w(CJ,{label:"Lost",value:q.lostCount,hint:"deals lost"})]}),E(MY,{defaultValue:"pipeline",className:"w-full",children:[E(vY,{children:[E(sJ,{value:"pipeline",children:[w("span",{className:"mr-2",children:"\uD83D\uDCCA"}),"Pipeline"]}),E(sJ,{value:"list",children:[w("span",{className:"mr-2",children:"\uD83D\uDCCB"}),"All Deals"]}),E(sJ,{value:"metrics",children:[w("span",{className:"mr-2",children:"\uD83D\uDCC8"}),"Metrics"]})]}),w(nJ,{value:"pipeline",className:"min-h-[400px]",children:w(hJ,{dealsByStage:R,stages:X,onDealClick:$,onDealMove:L})}),w(nJ,{value:"list",className:"min-h-[400px]",children:w(OX,{onDealClick:$})}),w(nJ,{value:"metrics",className:"min-h-[400px]",children:w(LY,{stats:q})})]}),w(dJ,{isOpen:J,onClose:()=>Y(!1),onSubmit:async(_)=>{await V.createDeal(_)},stages:X,isLoading:V.createState.loading}),w(lJ,{isOpen:Q,deal:F,stages:X,onClose:()=>{P(!1),H(null)},onWin:async(_)=>{await V.winDeal(_)},onLose:async(_)=>{await V.loseDeal(_)},onMove:async(_)=>{await V.moveDeal(_),Z()},isLoading:V.isLoading})]})}function LY({stats:J}){if(!J)return null;return w("div",{className:"space-y-6",children:E("div",{className:"rounded-xl border border-border bg-card p-6",children:[w("h3",{className:"mb-4 font-semibold text-lg",children:"Pipeline Overview"}),E("dl",{className:"grid gap-4 sm:grid-cols-3",children:[E("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Win Rate"}),E("dd",{className:"font-semibold text-2xl",children:[J.total>0?(J.wonCount/J.total*100).toFixed(0):0,"%"]})]}),E("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Avg Deal Size"}),w("dd",{className:"font-semibold text-2xl",children:EJ(J.total>0?J.totalValue/J.total:0)})]}),E("div",{children:[w("dt",{className:"text-muted-foreground text-sm",children:"Conversion"}),E("dd",{className:"font-semibold text-2xl",children:[J.wonCount," / ",J.total]})]})]})]})})}var IY={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"}]},wY={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"}]},Y3=[IY,wY];function o(J,Y="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:Y,minimumFractionDigits:0}).format(J)}var DY={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="PipelineKanbanView")throw Error("crmPipelineMarkdownRenderer: not PipelineKanbanView");let F="pipeline-1",[H,Q]=await Promise.all([vJ({pipelineId:F,limit:50}),LJ({pipelineId:F})]),P=H.deals,B=Q,R={};for(let G of B)R[G.id]=P.filter((W)=>W.stageId===G.id&&W.status==="OPEN");let X=["# CRM Pipeline","",`**Total Value**: ${o(H.totalValue)}`,`**Total Deals**: ${H.total}`,""];for(let G of B.sort((W,q)=>W.position-q.position)){let W=R[G.id]??[],q=W.reduce((Z,V)=>Z+V.value,0);if(X.push(`## ${G.name}`),X.push(`_${W.length} deals · ${o(q)}_`),X.push(""),W.length===0)X.push("_No deals_");else for(let Z of W)X.push(`- **${Z.name}** - ${o(Z.value,Z.currency)}`);X.push("")}return{mimeType:"text/markdown",body:X.join(`
71
+ `)}}},hY={target:"markdown",render:async(J,Y)=>{if(J.source.type!=="component"||J.source.componentKey!=="CrmDashboard")throw Error("crmDashboardMarkdownRenderer: not CrmDashboard");let F="pipeline-1",[H,Q]=await Promise.all([vJ({pipelineId:F,limit:100}),LJ({pipelineId:F})]),P=H.deals,B=Q,R=P.filter(($)=>$.status==="OPEN"),X=P.filter(($)=>$.status==="WON"),G=P.filter(($)=>$.status==="LOST"),W=R.reduce(($,L)=>$+L.value,0),q=X.reduce(($,L)=>$+L.value,0),Z=["# CRM Dashboard","","> Sales pipeline overview and key metrics","","## Summary","","| Metric | Value |","|--------|-------|",`| Total Deals | ${H.total} |`,`| Pipeline Value | ${o(H.totalValue)} |`,`| Open Deals | ${R.length} (${o(W)}) |`,`| Won Deals | ${X.length} (${o(q)}) |`,`| Lost Deals | ${G.length} |`,"","## Pipeline Stages",""];Z.push("| Stage | Deals | Value |"),Z.push("|-------|-------|-------|");for(let $ of B.sort((L,_)=>L.position-_.position)){let L=R.filter((K)=>K.stageId===$.id),_=L.reduce((K,z)=>K+z.value,0);Z.push(`| ${$.name} | ${L.length} | ${o(_)} |`)}Z.push(""),Z.push("## Recent Deals"),Z.push("");let V=P.slice(0,10);if(V.length===0)Z.push("_No deals yet._");else{Z.push("| Deal | Value | Stage | Status |"),Z.push("|------|-------|-------|--------|");for(let $ of V){let L=B.find((_)=>_.id===$.stageId);Z.push(`| ${$.name} | ${o($.value,$.currency)} | ${L?.name??"-"} | ${$.status} |`)}}return{mimeType:"text/markdown",body:Z.join(`
72
+ `)}}};import{jsx as BX}from"react/jsx-runtime";function bY(){let{dealsByStage:J,stages:Y}=i();return BX(hJ,{dealsByStage:J,stages:Y})}var TY={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 BX(bY,{})}};import{identityRbacSchemaContribution as CY}from"@contractspec/lib.identity-rbac";import{auditTrailSchemaContribution as EY}from"@contractspec/module.audit-trail";import{notificationsSchemaContribution as jY}from"@contractspec/module.notifications";var D3={modules:[CY,EY,jY,KX],provider:"postgresql",outputPath:"./prisma/schema/generated.prisma"};export{rJ as useDealMutations,i as useDealList,D3 as schemaComposition,nX as mockWinDealHandler,iX as mockMoveDealHandler,sX as mockLoseDealHandler,vJ as mockListDealsHandler,LJ as mockGetPipelineStagesHandler,tX as mockGetDealsByStageHandler,lX as mockCreateDealHandler,rX as example,wY as crmSalesRepOverlay,KX as crmPipelineSchemaContribution,TY as crmPipelineReactRenderer,DY as crmPipelineMarkdownRenderer,Y3 as crmOverlays,IY as crmDemoOverlay,hY as crmDashboardMarkdownRenderer,gZ as createCrmHandlers,NJ as WinDealInputModel,XX as WinDealContract,pJ as TaskTypeEnum,uJ as TaskStatusEnum,cJ as TaskPriorityEnum,WX as TaskEntity,DZ as TaskCompletedEvent,FX as StageEntity,aZ as PipelineMetricsPresentation,Y0 as PipelineKanbanPresentation,GX as PipelineEntity,UJ as MoveDealInputModel,JX as MoveDealContract,qJ as MOCK_STAGES,f as MOCK_DEALS,mZ as MOCK_CONTACTS,SZ as MOCK_COMPANIES,_J as LoseDealInputModel,YX as LoseDealContract,PJ as ListDealsOutputModel,AJ as ListDealsInputModel,ZX as ListDealsContract,uX as ExamplesCrmPipelineExample,VJ as DealWonPayloadModel,MZ as DealWonEvent,zJ as DealStatusFilterEnum,SJ as DealStatusEnum,KJ as DealMovedPayloadModel,BZ as DealMovedEvent,y as DealModel,RJ as DealLostPayloadModel,vZ as DealLostEvent,Z0 as DealListPresentation,QX as DealEntity,$0 as DealDetailPresentation,kZ as DealCreatedEvent,q0 as DealCardPresentation,lJ as DealActionsModal,fY as CrmPipelineFeature,hJ as CrmPipelineBoard,AX as CrmDealCard,tZ as CrmDashboardPresentation,l0 as CrmDashboard,dJ as CreateDealModal,WJ as CreateDealInputModel,eJ as CreateDealContract,gJ as ContactStatusEnum,HX as ContactEntity,RZ as ContactCreatedEvent,fJ as CompanySizeEnum,qX as CompanyEntity,UX as ActivityEntity};
@@ -1 +1 @@
1
- import{jsx as u,jsxs as YJ}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 ZJ({deal:J,onClick:K}){let N=J.expectedCloseDate?Math.ceil((J.expectedCloseDate.getTime()-Date.now())/86400000):null;return YJ("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:(G)=>{if(G.key==="Enter"||G.key===" ")K?.()},children:[u("h4",{className:"font-medium leading-snug",children:J.name}),u("div",{className:"mt-2 font-semibold text-lg text-primary",children:AJ(J.value,J.currency)}),YJ("div",{className:"mt-3 flex items-center justify-between text-muted-foreground text-xs",children:[N!==null&&u("span",{className:N<0?"text-red-500":N<=7?"text-yellow-600 dark:text-yellow-500":"",children:N<0?`${Math.abs(N)}d overdue`:N===0?"Due today":`${N}d left`}),u("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 HJ}from"react";import{jsx as C,jsxs as m}from"react/jsx-runtime";function NJ(J){if(J>=1e6)return`$${(J/1e6).toFixed(1)}M`;if(J>=1000)return`$${(J/1000).toFixed(0)}K`;return`$${J}`}function $J({dealsByStage:J,stages:K,onDealClick:N,onDealMove:G}){let[z,P]=HJ(null),O=[...K].sort((H,Q)=>H.position-Q.position),A=(H,Q)=>{G?.(H,Q),P(null)};return C("div",{className:"flex gap-4 overflow-x-auto pb-4",children:O.map((H)=>{let Q=J[H.id]??[],Y=Q.reduce((_,W)=>_+W.value,0);return m("div",{className:"flex w-72 flex-shrink-0 flex-col rounded-lg bg-muted/30",children:[m("div",{className:"flex items-center justify-between border-border border-b px-3 py-2",children:[m("div",{children:[C("h3",{className:"font-medium",children:H.name}),m("p",{className:"text-muted-foreground text-xs",children:[Q.length," deals · ",NJ(Y)]})]}),C("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",children:Q.length})]}),C("div",{className:"flex flex-1 flex-col gap-2 p-2",children:Q.length===0?C("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"}):Q.map((_)=>m("div",{className:"group relative",children:[C(ZJ,{deal:_,onClick:()=>N?.(_.id)}),_.status==="OPEN"&&G&&m("div",{className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100",children:[C("button",{type:"button",onClick:(W)=>{W.stopPropagation(),P(z===_.id?null:_.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===_.id&&m("div",{className:"absolute top-7 right-0 z-20 min-w-[140px] rounded-lg border border-border bg-card py-1 shadow-lg",children:[C("p",{className:"px-3 py-1 font-medium text-muted-foreground text-xs",children:"Move to:"}),O.filter((W)=>W.id!==_.stageId).map((W)=>C("button",{type:"button",onClick:(V)=>{V.stopPropagation(),A(_.id,W.id)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-muted",children:W.name},W.id))]})]})]},_.id))})]},H.id)})})}import{useTemplateRuntime as UJ}from"@contractspec/lib.example-shared-ui";import{useCallback as WJ,useEffect as PJ,useMemo as wJ,useState as S}from"react";function x(J={}){let{handlers:K,projectId:N}=UJ(),{crm:G}=K,[z,P]=S(null),[O,A]=S({}),[H,Q]=S([]),[Y,_]=S(!0),[W,V]=S(null),[T,b]=S(0),q=J.pipelineId??"pipeline-1",Z=J.pageIndex??T,X=J.pageSize??J.limit??50,[R]=J.sorting??[],k=R?.id,L=R?R.desc?"desc":"asc":void 0,c=WJ(async()=>{_(!0),V(null);try{let[M,F,o]=await Promise.all([G.listDeals({projectId:N,pipelineId:q,stageId:J.stageId,status:J.status==="all"?void 0:J.status,search:J.search,limit:X,offset:Z*X,sortBy:k==="name"||k==="value"||k==="status"||k==="expectedCloseDate"||k==="updatedAt"?k:void 0,sortDirection:L}),G.getDealsByStage({projectId:N,pipelineId:q}),G.getPipelineStages({pipelineId:q})]);P(M),A(F),Q(o)}catch(M){V(M instanceof Error?M:Error("Unknown error"))}finally{_(!1)}},[G,N,q,J.stageId,J.status,J.search,Z,X,k,L]);PJ(()=>{c()},[c]);let n=wJ(()=>{if(!z)return null;let M=z.deals.filter((D)=>D.status==="OPEN"),F=z.deals.filter((D)=>D.status==="WON"),o=z.deals.filter((D)=>D.status==="LOST");return{total:z.total,totalValue:z.totalValue,openCount:M.length,openValue:M.reduce((D,a)=>D+a.value,0),wonCount:F.length,wonValue:F.reduce((D,a)=>D+a.value,0),lostCount:o.length}},[z]);return{data:z,dealsByStage:O,stages:H,loading:Y,error:W,stats:n,page:Z+1,pageIndex:Z,pageSize:X,refetch:c,nextPage:J.pageIndex===void 0?()=>b((M)=>M+1):void 0,prevPage:J.pageIndex===void 0?()=>Z>0&&b((M)=>M-1):void 0}}import{useTemplateRuntime as VJ}from"@contractspec/lib.example-shared-ui";import{useCallback as i,useState as d}from"react";function GJ(J={}){let{handlers:K,projectId:N}=VJ(),{crm:G}=K,[z,P]=d({loading:!1,error:null,data:null}),[O,A]=d({loading:!1,error:null,data:null}),[H,Q]=d({loading:!1,error:null,data:null}),[Y,_]=d({loading:!1,error:null,data:null}),W=i(async(q)=>{P({loading:!0,error:null,data:null});try{let Z=await G.createDeal(q,{projectId:N,ownerId:"user-1"});return P({loading:!1,error:null,data:Z}),J.onSuccess?.(),Z}catch(Z){let X=Z instanceof Error?Z:Error("Failed to create deal");return P({loading:!1,error:X,data:null}),J.onError?.(X),null}},[G,N,J]),V=i(async(q)=>{A({loading:!0,error:null,data:null});try{let Z=await G.moveDeal(q);return A({loading:!1,error:null,data:Z}),J.onSuccess?.(),Z}catch(Z){let X=Z instanceof Error?Z:Error("Failed to move deal");return A({loading:!1,error:X,data:null}),J.onError?.(X),null}},[G,J]),T=i(async(q)=>{Q({loading:!0,error:null,data:null});try{let Z=await G.winDeal(q);return Q({loading:!1,error:null,data:Z}),J.onSuccess?.(),Z}catch(Z){let X=Z instanceof Error?Z:Error("Failed to mark deal as won");return Q({loading:!1,error:X,data:null}),J.onError?.(X),null}},[G,J]),b=i(async(q)=>{_({loading:!0,error:null,data:null});try{let Z=await G.loseDeal(q);return _({loading:!1,error:null,data:Z}),J.onSuccess?.(),Z}catch(Z){let X=Z instanceof Error?Z:Error("Failed to mark deal as lost");return _({loading:!1,error:X,data:null}),J.onError?.(X),null}},[G,J]);return{createDeal:W,moveDeal:V,winDeal:T,loseDeal:b,createState:z,moveState:O,winState:H,loseState:Y,isLoading:z.loading||O.loading||H.loading||Y.loading}}import{Button as _J,Input as t}from"@contractspec/lib.design-system";import{useState as p}from"react";import{jsx as E,jsxs as v}from"react/jsx-runtime";var OJ=["USD","EUR","GBP","CAD"],RJ="pipeline-1";function qJ({isOpen:J,onClose:K,onSubmit:N,stages:G,isLoading:z=!1}){let[P,O]=p(""),[A,H]=p(""),[Q,Y]=p("USD"),[_,W]=p(G[0]?.id??""),[V,T]=p(""),[b,q]=p(null),Z=async(X)=>{if(X.preventDefault(),q(null),!P.trim()){q("Deal name is required");return}let R=parseFloat(A);if(isNaN(R)||R<=0){q("Value must be a positive number");return}if(!_){q("Please select a pipeline stage");return}try{await N({name:P.trim(),value:R,currency:Q,pipelineId:RJ,stageId:_,expectedCloseDate:V?new Date(V):void 0}),O(""),H(""),Y("USD"),W(G[0]?.id??""),T(""),K()}catch(k){q(k instanceof Error?k.message:"Failed to create deal")}};if(!J)return null;return v("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[E("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"}),v("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[E("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Deal"}),v("form",{onSubmit:Z,className:"space-y-4",children:[v("div",{children:[E("label",{htmlFor:"deal-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Deal Name *"}),E(t,{id:"deal-name",value:P,onChange:(X)=>O(X.target.value),placeholder:"e.g., Enterprise License - Acme Corp",disabled:z})]}),v("div",{className:"flex gap-3",children:[v("div",{className:"flex-1",children:[E("label",{htmlFor:"deal-value",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Value *"}),E(t,{id:"deal-value",type:"number",min:"0",step:"0.01",value:A,onChange:(X)=>H(X.target.value),placeholder:"50000",disabled:z})]}),v("div",{className:"w-24",children:[E("label",{htmlFor:"deal-currency",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Currency"}),E("select",{id:"deal-currency",value:Q,onChange:(X)=>Y(X.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:OJ.map((X)=>E("option",{value:X,children:X},X))})]})]}),v("div",{children:[E("label",{htmlFor:"deal-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Pipeline Stage *"}),E("select",{id:"deal-stage",value:_,onChange:(X)=>W(X.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((X)=>E("option",{value:X.id,children:X.name},X.id))})]}),v("div",{children:[E("label",{htmlFor:"deal-close-date",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Expected Close Date"}),E(t,{id:"deal-close-date",type:"date",value:V,onChange:(X)=>T(X.target.value),disabled:z})]}),b&&E("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:b}),v("div",{className:"flex justify-end gap-3 pt-2",children:[E(_J,{type:"button",variant:"ghost",onPress:K,disabled:z,children:"Cancel"}),E(_J,{type:"submit",disabled:z,children:z?"Creating...":"Create Deal"})]})]})]})]})}import{Button as y}from"@contractspec/lib.design-system";import{useState as g}from"react";import{jsx as $,jsxs as w,Fragment as EJ}from"react/jsx-runtime";function fJ(J,K){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function QJ({isOpen:J,deal:K,stages:N,onClose:G,onWin:z,onLose:P,onMove:O,isLoading:A=!1}){let[H,Q]=g("menu"),[Y,_]=g(""),[W,V]=g(""),[T,b]=g(""),[q,Z]=g(""),[X,R]=g(null),k=()=>{Q("menu"),_(""),V(""),b(""),Z(""),R(null)},L=()=>{k(),G()},c=async()=>{if(!K)return;R(null);try{await z({dealId:K.id,wonSource:Y.trim()||void 0,notes:T.trim()||void 0}),L()}catch(F){R(F instanceof Error?F.message:"Failed to mark deal as won")}},n=async()=>{if(!K)return;if(R(null),!W.trim()){R("Please provide a reason for losing the deal");return}try{await P({dealId:K.id,lostReason:W.trim(),notes:T.trim()||void 0}),L()}catch(F){R(F instanceof Error?F.message:"Failed to mark deal as lost")}},M=async()=>{if(!K)return;if(R(null),!q){R("Please select a stage");return}if(q===K.stageId){R("Deal is already in this stage");return}try{await O({dealId:K.id,stageId:q}),L()}catch(F){R(F instanceof Error?F.message:"Failed to move deal")}};if(!J||!K)return null;return w("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[$("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:L,role:"button",tabIndex:0,onKeyDown:(F)=>{if(F.key==="Enter"||F.key===" ")L()},"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:[w("div",{className:"mb-4 border-border border-b pb-4",children:[$("h2",{className:"font-semibold text-xl",children:K.name}),$("p",{className:"font-medium text-lg text-primary",children:fJ(K.value,K.currency)}),$("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})]}),H==="menu"&&w("div",{className:"space-y-3",children:[K.status==="OPEN"&&w(EJ,{children:[w(y,{className:"w-full justify-start",variant:"ghost",onPress:()=>Q("win"),children:[$("span",{className:"mr-2",children:"\uD83C\uDFC6"})," Mark as Won"]}),w(y,{className:"w-full justify-start",variant:"ghost",onPress:()=>Q("lose"),children:[$("span",{className:"mr-2",children:"❌"})," Mark as Lost"]}),w(y,{className:"w-full justify-start",variant:"ghost",onPress:()=>{Z(K.stageId),Q("move")},children:[$("span",{className:"mr-2",children:"➡️"})," Move to Stage"]})]}),K.status!=="OPEN"&&w("p",{className:"py-4 text-center text-muted-foreground",children:["This deal is already ",K.status.toLowerCase(),". No actions available."]}),$("div",{className:"border-border border-t pt-3",children:$(y,{className:"w-full",variant:"outline",onPress:L,children:"Close"})})]}),H==="win"&&w("div",{className:"space-y-4",children:[w("div",{children:[$("label",{htmlFor:"won-source",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"How did you win this deal?"}),w("select",{id:"won-source",value:Y,onChange:(F)=>_(F.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:[$("option",{value:"",children:"Select a source..."}),$("option",{value:"referral",children:"Referral"}),$("option",{value:"cold_outreach",children:"Cold Outreach"}),$("option",{value:"inbound",children:"Inbound Lead"}),$("option",{value:"upsell",children:"Upsell"}),$("option",{value:"other",children:"Other"})]})]}),w("div",{children:[$("label",{htmlFor:"win-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),$("textarea",{id:"win-notes",value:T,onChange:(F)=>b(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"})]}),X&&$("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),w("div",{className:"flex justify-end gap-3 pt-2",children:[$(y,{variant:"ghost",onPress:()=>Q("menu"),disabled:A,children:"Back"}),$(y,{onPress:c,disabled:A,children:A?"Processing...":"\uD83C\uDFC6 Confirm Win"})]})]}),H==="lose"&&w("div",{className:"space-y-4",children:[w("div",{children:[$("label",{htmlFor:"lost-reason",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Why was this deal lost? *"}),w("select",{id:"lost-reason",value:W,onChange:(F)=>V(F.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:[$("option",{value:"",children:"Select a reason..."}),$("option",{value:"price",children:"Price too high"}),$("option",{value:"competitor",children:"Lost to competitor"}),$("option",{value:"no_budget",children:"No budget"}),$("option",{value:"no_decision",children:"No decision made"}),$("option",{value:"timing",children:"Bad timing"}),$("option",{value:"product_fit",children:"Product not a fit"}),$("option",{value:"other",children:"Other"})]})]}),w("div",{children:[$("label",{htmlFor:"lose-notes",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Notes (optional)"}),$("textarea",{id:"lose-notes",value:T,onChange:(F)=>b(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"})]}),X&&$("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),w("div",{className:"flex justify-end gap-3 pt-2",children:[$(y,{variant:"ghost",onPress:()=>Q("menu"),disabled:A,children:"Back"}),$(y,{variant:"destructive",onPress:n,disabled:A,children:A?"Processing...":"❌ Confirm Loss"})]})]}),H==="move"&&w("div",{className:"space-y-4",children:[w("div",{children:[$("label",{htmlFor:"move-stage",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Move to Stage"}),$("select",{id:"move-stage",value:q,onChange:(F)=>Z(F.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:N.map((F)=>w("option",{value:F.id,children:[F.name,F.id===K.stageId?" (current)":""]},F.id))})]}),X&&$("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:X}),w("div",{className:"flex justify-end gap-3 pt-2",children:[$(y,{variant:"ghost",onPress:()=>Q("menu"),disabled:A,children:"Back"}),$(y,{onPress:M,disabled:A,children:A?"Moving...":"➡️ Move Deal"})]})]})]})]})}import{Button as hJ,DataTable as TJ,LoaderBlock as BJ}from"@contractspec/lib.design-system";import{useContractTable as bJ}from"@contractspec/lib.presentation-runtime-react";import{Badge as MJ}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as j,VStack as s}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as B}from"@contractspec/lib.ui-kit-web/ui/text";import*as e from"react";import{jsx as f,jsxs as I}from"react/jsx-runtime";function kJ(J,K="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function vJ(J){switch(J){case"WON":return"default";case"LOST":return"destructive";case"STALE":return"outline";default:return"secondary"}}function yJ({deals:J,totalItems:K,pageIndex:N,pageSize:G,sorting:z,loading:P,onSortingChange:O,onPaginationChange:A,onDealClick:H}){let Q=bJ({data:J,columns:[{id:"deal",header:"Deal",label:"Deal",accessor:(Y)=>Y.name,cell:({item:Y})=>I(s,{gap:"xs",children:[f(B,{className:"font-medium text-sm",children:Y.name}),f(B,{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})=>kJ(Y.value,Y.currency),align:"right",size:140,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:Y})=>f(MJ,{variant:vJ(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})=>f(hJ,{variant:"ghost",size:"sm",onPress:()=>H?.(Y.id),children:"Actions"}),size:120,canSort:!1,canHide:!1,canPin:!1,canResize:!1}],executionMode:"server",selectionMode:"multiple",totalItems:K,state:{sorting:z,pagination:{pageIndex:N,pageSize:G}},onSortingChange:O,onPaginationChange:A,initialState:{columnVisibility:{updatedAt:!1},columnPinning:{left:["deal","status"],right:[]}},renderExpandedContent:(Y)=>I(s,{gap:"sm",className:"py-2",children:[I(j,{justify:"between",children:[f(B,{className:"font-medium text-sm",children:"Owner"}),f(B,{className:"text-muted-foreground text-sm",children:Y.ownerId})]}),I(j,{justify:"between",children:[f(B,{className:"font-medium text-sm",children:"Contact"}),f(B,{className:"text-muted-foreground text-sm",children:Y.contactId??"No linked contact"})]}),Y.wonSource?I(j,{justify:"between",children:[f(B,{className:"font-medium text-sm",children:"Won Source"}),f(B,{className:"text-muted-foreground text-sm",children:Y.wonSource})]}):null,Y.lostReason?I(j,{justify:"between",children:[f(B,{className:"font-medium text-sm",children:"Lost Reason"}),f(B,{className:"text-muted-foreground text-sm",children:Y.lostReason})]}):null,Y.notes?I(s,{gap:"xs",children:[f(B,{className:"font-medium text-sm",children:"Notes"}),f(B,{className:"text-muted-foreground text-sm",children:Y.notes})]}):null]}),getCanExpand:()=>!0});return f(TJ,{controller:Q,title:"All Deals",description:"Server-mode table using the shared ContractSpec controller.",loading:P,toolbar:I(j,{gap:"sm",className:"flex-wrap",children:[I(B,{className:"text-muted-foreground text-sm",children:["Selected ",Q.selectedRowIds.length]}),I(B,{className:"text-muted-foreground text-sm",children:[K," total deals"]})]}),footer:`Page ${Q.pageIndex+1} of ${Q.pageCount}`,emptyState:f("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No deals found"})})}function zJ({onDealClick:J}){let[K,N]=e.useState([{id:"value",desc:!0}]),[G,z]=e.useState({pageIndex:0,pageSize:3}),{data:P,loading:O}=x({pageIndex:G.pageIndex,pageSize:G.pageSize,sorting:K});if(O&&!P)return f(BJ,{label:"Loading deals..."});return f(yJ,{deals:P?.deals??[],totalItems:P?.total??0,pageIndex:G.pageIndex,pageSize:G.pageSize,sorting:K,loading:O,onSortingChange:(A)=>{N(A),z((H)=>({...H,pageIndex:0}))},onPaginationChange:z,onDealClick:J})}import{Button as IJ,ErrorState as LJ,LoaderBlock as DJ,StatCard as r,StatCardGroup as CJ}from"@contractspec/lib.design-system";import{Tabs as mJ,TabsContent as JJ,TabsList as SJ,TabsTrigger as KJ}from"@contractspec/lib.ui-kit-web/ui/tabs";import{useCallback as FJ,useState as XJ}from"react";import{jsx as U,jsxs as h}from"react/jsx-runtime";function l(J,K="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:K,minimumFractionDigits:0,maximumFractionDigits:0}).format(J)}function fK(){let[J,K]=XJ(!1),[N,G]=XJ(null),[z,P]=XJ(!1),{data:O,dealsByStage:A,stages:H,loading:Q,error:Y,stats:_,refetch:W}=x(),V=GJ({onSuccess:()=>{W()}}),T=FJ((q)=>{let Z=A?Object.values(A).flat().find((X)=>X.id===q):null;if(Z)G(Z),P(!0)},[A]),b=FJ(async(q,Z)=>{await V.moveDeal({dealId:q,stageId:Z})},[V]);if(Q&&!O)return U(DJ,{label:"Loading CRM..."});if(Y)return U(LJ,{title:"Failed to load CRM",description:Y.message,onRetry:W,retryLabel:"Retry"});return h("div",{className:"space-y-6",children:[h("div",{className:"flex items-center justify-between",children:[U("h2",{className:"font-bold text-2xl",children:"CRM Pipeline"}),h(IJ,{onClick:()=>K(!0),children:[U("span",{className:"mr-2",children:"+"})," Create Deal"]})]}),_&&h(CJ,{children:[U(r,{label:"Total Pipeline",value:l(_.totalValue),hint:`${_.total} deals`}),U(r,{label:"Open Deals",value:l(_.openValue),hint:`${_.openCount} active`}),U(r,{label:"Won",value:l(_.wonValue),hint:`${_.wonCount} closed`}),U(r,{label:"Lost",value:_.lostCount,hint:"deals lost"})]}),h(mJ,{defaultValue:"pipeline",className:"w-full",children:[h(SJ,{children:[h(KJ,{value:"pipeline",children:[U("span",{className:"mr-2",children:"\uD83D\uDCCA"}),"Pipeline"]}),h(KJ,{value:"list",children:[U("span",{className:"mr-2",children:"\uD83D\uDCCB"}),"All Deals"]}),h(KJ,{value:"metrics",children:[U("span",{className:"mr-2",children:"\uD83D\uDCC8"}),"Metrics"]})]}),U(JJ,{value:"pipeline",className:"min-h-[400px]",children:U($J,{dealsByStage:A,stages:H,onDealClick:T,onDealMove:b})}),U(JJ,{value:"list",className:"min-h-[400px]",children:U(zJ,{onDealClick:T})}),U(JJ,{value:"metrics",className:"min-h-[400px]",children:U(pJ,{stats:_})})]}),U(qJ,{isOpen:J,onClose:()=>K(!1),onSubmit:async(q)=>{await V.createDeal(q)},stages:H,isLoading:V.createState.loading}),U(QJ,{isOpen:z,deal:N,stages:H,onClose:()=>{P(!1),G(null)},onWin:async(q)=>{await V.winDeal(q)},onLose:async(q)=>{await V.loseDeal(q)},onMove:async(q)=>{await V.moveDeal(q),W()},isLoading:V.isLoading})]})}function pJ({stats:J}){if(!J)return null;return U("div",{className:"space-y-6",children:h("div",{className:"rounded-xl border border-border bg-card p-6",children:[U("h3",{className:"mb-4 font-semibold text-lg",children:"Pipeline Overview"}),h("dl",{className:"grid gap-4 sm:grid-cols-3",children:[h("div",{children:[U("dt",{className:"text-muted-foreground text-sm",children:"Win Rate"}),h("dd",{className:"font-semibold text-2xl",children:[J.total>0?(J.wonCount/J.total*100).toFixed(0):0,"%"]})]}),h("div",{children:[U("dt",{className:"text-muted-foreground text-sm",children:"Avg Deal Size"}),U("dd",{className:"font-semibold text-2xl",children:l(J.total>0?J.totalValue/J.total:0)})]}),h("div",{children:[U("dt",{className:"text-muted-foreground text-sm",children:"Conversion"}),h("dd",{className:"font-semibold text-2xl",children:[J.wonCount," / ",J.total]})]})]})]})})}export{fK 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[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 +1 @@
1
- import{useTemplateRuntime as x}from"@contractspec/lib.example-shared-ui";import{useCallback as B,useEffect as C,useMemo as y,useState as V}from"react";function D(A={}){let{handlers:k,projectId:Q}=x(),{crm:G}=k,[J,X]=V(null),[_,Y]=V({}),[$,Z]=V([]),[T,U]=V(!0),[w,E]=V(null),[M,P]=V(0),H=A.pipelineId??"pipeline-1",q=A.pageIndex??M,F=A.pageSize??A.limit??50,[R]=A.sorting??[],O=R?.id,b=R?R.desc?"desc":"asc":void 0,f=B(async()=>{U(!0),E(null);try{let[K,W,v]=await Promise.all([G.listDeals({projectId:Q,pipelineId:H,stageId:A.stageId,status:A.status==="all"?void 0:A.status,search:A.search,limit:F,offset:q*F,sortBy:O==="name"||O==="value"||O==="status"||O==="expectedCloseDate"||O==="updatedAt"?O:void 0,sortDirection:b}),G.getDealsByStage({projectId:Q,pipelineId:H}),G.getPipelineStages({pipelineId:H})]);X(K),Y(W),Z(v)}catch(K){E(K instanceof Error?K:Error("Unknown error"))}finally{U(!1)}},[G,Q,H,A.stageId,A.status,A.search,q,F,O,b]);C(()=>{f()},[f]);let h=y(()=>{if(!J)return null;let K=J.deals.filter((N)=>N.status==="OPEN"),W=J.deals.filter((N)=>N.status==="WON"),v=J.deals.filter((N)=>N.status==="LOST");return{total:J.total,totalValue:J.totalValue,openCount:K.length,openValue:K.reduce((N,L)=>N+L.value,0),wonCount:W.length,wonValue:W.reduce((N,L)=>N+L.value,0),lostCount:v.length}},[J]);return{data:J,dealsByStage:_,stages:$,loading:T,error:w,stats:h,page:q+1,pageIndex:q,pageSize:F,refetch:f,nextPage:A.pageIndex===void 0?()=>P((K)=>K+1):void 0,prevPage:A.pageIndex===void 0?()=>q>0&&P((K)=>K-1):void 0}}import{useTemplateRuntime as I}from"@contractspec/lib.example-shared-ui";import{useCallback as z,useState as j}from"react";function g(A={}){let{handlers:k,projectId:Q}=I(),{crm:G}=k,[J,X]=j({loading:!1,error:null,data:null}),[_,Y]=j({loading:!1,error:null,data:null}),[$,Z]=j({loading:!1,error:null,data:null}),[T,U]=j({loading:!1,error:null,data:null}),w=z(async(H)=>{X({loading:!0,error:null,data:null});try{let q=await G.createDeal(H,{projectId:Q,ownerId:"user-1"});return X({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to create deal");return X({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,Q,A]),E=z(async(H)=>{Y({loading:!0,error:null,data:null});try{let q=await G.moveDeal(H);return Y({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to move deal");return Y({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,A]),M=z(async(H)=>{Z({loading:!0,error:null,data:null});try{let q=await G.winDeal(H);return Z({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to mark deal as won");return Z({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,A]),P=z(async(H)=>{U({loading:!0,error:null,data:null});try{let q=await G.loseDeal(H);return U({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to mark deal as lost");return U({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,A]);return{createDeal:w,moveDeal:E,winDeal:M,loseDeal:P,createState:J,moveState:_,winState:$,loseState:T,isLoading:J.loading||_.loading||$.loading||T.loading}}export{g as useDealMutations,D as useDealList};
1
+ import{useTemplateRuntime as x}from"@contractspec/lib.example-shared-ui";import{useCallback as B,useEffect as C,useMemo as y,useState as V}from"react";function D(A={}){let{handlers:w,projectId:Q}=x(),{crm:G}=w,[J,X]=V(null),[_,Y]=V({}),[$,Z]=V([]),[T,U]=V(!0),[M,E]=V(null),[R,P]=V(0),H=A.pipelineId??"pipeline-1",q=A.pageIndex??R,F=A.pageSize??A.limit??50,[W]=A.sorting??[],O=W?.id==="deal"?"name":W?.id,b=W?W.desc?"desc":"asc":void 0,f=B(async()=>{U(!0),E(null);try{let[K,z,v]=await Promise.all([G.listDeals({projectId:Q,pipelineId:H,stageId:A.stageId,status:A.status==="all"?void 0:A.status,search:A.search,limit:F,offset:q*F,sortBy:O==="name"||O==="value"||O==="status"||O==="expectedCloseDate"||O==="updatedAt"?O:void 0,sortDirection:b}),G.getDealsByStage({projectId:Q,pipelineId:H}),G.getPipelineStages({pipelineId:H})]);X(K),Y(z),Z(v)}catch(K){E(K instanceof Error?K:Error("Unknown error"))}finally{U(!1)}},[G,Q,H,A.stageId,A.status,A.search,q,F,O,b]);C(()=>{f()},[f]);let h=y(()=>{if(!J)return null;let K=J.deals.filter((N)=>N.status==="OPEN"),z=J.deals.filter((N)=>N.status==="WON"),v=J.deals.filter((N)=>N.status==="LOST");return{total:J.total,totalValue:J.totalValue,openCount:K.length,openValue:K.reduce((N,L)=>N+L.value,0),wonCount:z.length,wonValue:z.reduce((N,L)=>N+L.value,0),lostCount:v.length}},[J]);return{data:J,dealsByStage:_,stages:$,loading:T,error:M,stats:h,page:q+1,pageIndex:q,pageSize:F,refetch:f,nextPage:A.pageIndex===void 0?()=>P((K)=>K+1):void 0,prevPage:A.pageIndex===void 0?()=>q>0&&P((K)=>K-1):void 0}}import{useTemplateRuntime as I}from"@contractspec/lib.example-shared-ui";import{useCallback as j,useState as k}from"react";function g(A={}){let{handlers:w,projectId:Q}=I(),{crm:G}=w,[J,X]=k({loading:!1,error:null,data:null}),[_,Y]=k({loading:!1,error:null,data:null}),[$,Z]=k({loading:!1,error:null,data:null}),[T,U]=k({loading:!1,error:null,data:null}),M=j(async(H)=>{X({loading:!0,error:null,data:null});try{let q=await G.createDeal(H,{projectId:Q,ownerId:"user-1"});return X({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to create deal");return X({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,Q,A]),E=j(async(H)=>{Y({loading:!0,error:null,data:null});try{let q=await G.moveDeal(H);return Y({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to move deal");return Y({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,A]),R=j(async(H)=>{Z({loading:!0,error:null,data:null});try{let q=await G.winDeal(H);return Z({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to mark deal as won");return Z({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,A]),P=j(async(H)=>{U({loading:!0,error:null,data:null});try{let q=await G.loseDeal(H);return U({loading:!1,error:null,data:q}),A.onSuccess?.(),q}catch(q){let F=q instanceof Error?q:Error("Failed to mark deal as lost");return U({loading:!1,error:F,data:null}),A.onError?.(F),null}},[G,A]);return{createDeal:M,moveDeal:E,winDeal:R,loseDeal:P,createState:J,moveState:_,winState:$,loseState:T,isLoading:J.loading||_.loading||$.loading||T.loading}}export{g as useDealMutations,D as useDealList};
@@ -1 +1 @@
1
- import{useTemplateRuntime as R}from"@contractspec/lib.example-shared-ui";import{useCallback as f,useEffect as h,useMemo as x,useState as H}from"react";function B(q={}){let{handlers:C,projectId:U}=R(),{crm:K}=C,[F,M]=H(null),[T,b]=H({}),[w,L]=H([]),[j,Z]=H(!0),[E,_]=H(null),[P,$]=H(0),N=q.pipelineId??"pipeline-1",J=q.pageIndex??P,O=q.pageSize??q.limit??50,[V]=q.sorting??[],G=V?.id,k=V?V.desc?"desc":"asc":void 0,W=f(async()=>{Z(!0),_(null);try{let[v,Q,X]=await Promise.all([K.listDeals({projectId:U,pipelineId:N,stageId:q.stageId,status:q.status==="all"?void 0:q.status,search:q.search,limit:O,offset:J*O,sortBy:G==="name"||G==="value"||G==="status"||G==="expectedCloseDate"||G==="updatedAt"?G:void 0,sortDirection:k}),K.getDealsByStage({projectId:U,pipelineId:N}),K.getPipelineStages({pipelineId:N})]);M(v),b(Q),L(X)}catch(v){_(v instanceof Error?v:Error("Unknown error"))}finally{Z(!1)}},[K,U,N,q.stageId,q.status,q.search,J,O,G,k]);h(()=>{W()},[W]);let z=x(()=>{if(!F)return null;let v=F.deals.filter((A)=>A.status==="OPEN"),Q=F.deals.filter((A)=>A.status==="WON"),X=F.deals.filter((A)=>A.status==="LOST");return{total:F.total,totalValue:F.totalValue,openCount:v.length,openValue:v.reduce((A,Y)=>A+Y.value,0),wonCount:Q.length,wonValue:Q.reduce((A,Y)=>A+Y.value,0),lostCount:X.length}},[F]);return{data:F,dealsByStage:T,stages:w,loading:j,error:E,stats:z,page:J+1,pageIndex:J,pageSize:O,refetch:W,nextPage:q.pageIndex===void 0?()=>$((v)=>v+1):void 0,prevPage:q.pageIndex===void 0?()=>J>0&&$((v)=>v-1):void 0}}export{B as useDealList};
1
+ import{useTemplateRuntime as R}from"@contractspec/lib.example-shared-ui";import{useCallback as f,useEffect as h,useMemo as x,useState as H}from"react";function B(q={}){let{handlers:C,projectId:V}=R(),{crm:K}=C,[F,M]=H(null),[T,b]=H({}),[w,L]=H([]),[j,Z]=H(!0),[E,_]=H(null),[P,$]=H(0),N=q.pipelineId??"pipeline-1",J=q.pageIndex??P,O=q.pageSize??q.limit??50,[Q]=q.sorting??[],G=Q?.id==="deal"?"name":Q?.id,k=Q?Q.desc?"desc":"asc":void 0,W=f(async()=>{Z(!0),_(null);try{let[v,U,X]=await Promise.all([K.listDeals({projectId:V,pipelineId:N,stageId:q.stageId,status:q.status==="all"?void 0:q.status,search:q.search,limit:O,offset:J*O,sortBy:G==="name"||G==="value"||G==="status"||G==="expectedCloseDate"||G==="updatedAt"?G:void 0,sortDirection:k}),K.getDealsByStage({projectId:V,pipelineId:N}),K.getPipelineStages({pipelineId:N})]);M(v),b(U),L(X)}catch(v){_(v instanceof Error?v:Error("Unknown error"))}finally{Z(!1)}},[K,V,N,q.stageId,q.status,q.search,J,O,G,k]);h(()=>{W()},[W]);let z=x(()=>{if(!F)return null;let v=F.deals.filter((A)=>A.status==="OPEN"),U=F.deals.filter((A)=>A.status==="WON"),X=F.deals.filter((A)=>A.status==="LOST");return{total:F.total,totalValue:F.totalValue,openCount:v.length,openValue:v.reduce((A,Y)=>A+Y.value,0),wonCount:U.length,wonValue:U.reduce((A,Y)=>A+Y.value,0),lostCount:X.length}},[F]);return{data:F,dealsByStage:T,stages:w,loading:j,error:E,stats:z,page:J+1,pageIndex:J,pageSize:O,refetch:W,nextPage:q.pageIndex===void 0?()=>$((v)=>v+1):void 0,prevPage:q.pageIndex===void 0?()=>J>0&&$((v)=>v-1):void 0}}export{B as useDealList};