Application Use Cases¶
The application layer orchestrates domain objects to fulfil business use cases. It has no knowledge of FastAPI, DuckDB, or pickle files — those are injected via the repository and model ports.
Predict Churn¶
src.application.use_cases.predict_churn ¶
PredictChurnUseCase – application layer use case.
Orchestrates domain objects to produce a churn prediction. This layer has no knowledge of FastAPI, DuckDB, or pickle files.
Classes¶
PredictChurnRequest
dataclass
¶
PredictChurnUseCase ¶
Coordinates retrieval, feature engineering, and prediction for one customer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_repo
|
CustomerRepository
|
Repository for fetching Customer entities. |
required |
usage_repo
|
UsageRepository
|
Repository for fetching UsageEvent sequences (retained for future use; feature extraction now happens inside the extractor). |
required |
churn_service
|
ChurnModelService
|
Domain service that runs the churn model. |
required |
risk_service
|
RiskModelService
|
Domain service that computes the composite risk score. |
required |
risk_signals_repo
|
RiskSignalsRepository | None
|
Optional repository for real risk signal data. Falls back to zeroed signals when not provided, which preserves backward compatibility for unit tests. |
None
|
Source code in src/application/use_cases/predict_churn.py
Functions¶
Run the end-to-end churn prediction pipeline for a single customer.
Business Context: Fetches customer state, resolves real risk signals from raw.risk_signals (compliance gaps + vendor flags + usage decay), and delegates to ChurnModelService which queries the dbt feature mart for all ML features. One DB read per layer, < 5ms total.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
PredictChurnRequest
|
Contains customer_id and optional lookback window. |
required |
Returns:
| Type | Description |
|---|---|
PredictionResult
|
PredictionResult with calibrated churn probability, composite risk |
PredictionResult
|
score, top-5 SHAP feature drivers, and a recommended CS action. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the customer is not found or has already churned. |
Source code in src/application/use_cases/predict_churn.py
Compute Risk Score¶
src.application.use_cases.compute_risk_score ¶
ComputeRiskScoreUseCase – application layer use case.
Classes¶
ComputeRiskScoreRequest
dataclass
¶
Input DTO for the ComputeRiskScoreUseCase.
Source code in src/application/use_cases/compute_risk_score.py
ComputeRiskScoreUseCase ¶
Computes a composite risk score from pre-fetched signal values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_service
|
RiskModelService
|
Domain service that applies the weighting formula. |
required |
Source code in src/application/use_cases/compute_risk_score.py
Functions¶
Compute and return a RiskScore for the given signals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
ComputeRiskScoreRequest
|
Pre-fetched signal values for the customer. |
required |
Returns:
| Type | Description |
|---|---|
RiskScore
|
RiskScore value object in [0, 1] with risk tier. |
Source code in src/application/use_cases/compute_risk_score.py
Get Customer 360¶
src.application.use_cases.get_customer_360 ¶
GetCustomer360UseCase – assembles a full Customer 360 profile.
Orchestrates the customer domain, prediction domain, and raw DuckDB queries to produce a single rich response for the Customer 360 API endpoint.
Classes¶
ShapFeatureSummary
dataclass
¶
Application-layer DTO for a single SHAP feature contribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature
|
str
|
Feature name as returned by the model. |
required |
value
|
float
|
Raw feature value. |
required |
shap_impact
|
float
|
Signed SHAP contribution (positive = increases churn risk). |
required |
Source code in src/application/use_cases/get_customer_360.py
Customer360Profile
dataclass
¶
Application-layer DTO returned by GetCustomer360UseCase.
This DTO is mapped to Customer360Response by the delivery layer (FastAPI router). Keeping it here ensures the application layer has no dependency on app/schemas/.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_id
|
str
|
Unique customer identifier. |
required |
plan_tier
|
str
|
Commercial tier (starter / growth / enterprise). |
required |
industry
|
str
|
Vertical segment. |
required |
mrr
|
float
|
Monthly Recurring Revenue in USD. |
required |
tenure_days
|
int
|
Days since signup. |
required |
churn_probability
|
float
|
Calibrated P(churn in 90 days), 0–1. |
required |
risk_tier
|
str
|
LOW | MEDIUM | HIGH | CRITICAL. |
required |
top_shap_features
|
list[ShapFeatureSummary]
|
Top SHAP drivers (sorted by |impact|). |
list()
|
events_last_30d
|
int
|
Product events in the last 30 days. |
0
|
open_ticket_count
|
int
|
Currently open support tickets. |
0
|
gtm_stage
|
str | None
|
Most recent GTM opportunity stage, if any. |
None
|
latest_prediction_at
|
str
|
ISO-8601 UTC timestamp of the prediction. |
''
|
Source code in src/application/use_cases/get_customer_360.py
GetCustomer360Request
dataclass
¶
Input DTO for GetCustomer360UseCase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_id
|
str
|
UUID of the customer to profile. |
required |
Source code in src/application/use_cases/get_customer_360.py
GetCustomer360UseCase ¶
Assembles a Customer 360 profile from multiple domain sources.
Business Context: CS teams spend 10–15 min per customer pulling data from 3+ tools before each call. This use case collapses that into a single <50ms API response — enabling same-day at-risk customer triage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_repo
|
CustomerRepository
|
Reads customer master data. |
required |
predict_use_case
|
PredictChurnUseCase
|
Reuses the existing churn prediction pipeline. |
required |
Source code in src/application/use_cases/get_customer_360.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
Functions¶
Build and return the Customer 360 profile.
Business Context: Single entrypoint for all customer health data — churn score, feature drivers, usage velocity, support load, and GTM pipeline stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
GetCustomer360Request
|
Contains customer_id. |
required |
Returns:
| Type | Description |
|---|---|
Customer360Profile
|
Customer360Profile DTO with all fields populated. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the customer is not found. |
Source code in src/application/use_cases/get_customer_360.py
Functions¶
Generate Expansion Summary¶
src.application.use_cases.generate_expansion_summary ¶
GenerateExpansionSummaryUseCase — orchestrates the expansion narrative pipeline.
Translates a high-propensity ExpansionResult into an AE tactical brief and optional email draft, validated by ExpansionGuardrailsService before returning.
Classes¶
PropensityTooLowError ¶
Bases: ValueError
Raised when propensity is below the API-layer minimum threshold (0.15).
Business Context: Accounts with propensity < 0.15 are not expansion candidates. Calling the LLM for these accounts wastes tokens and produces misleading briefs. The API layer maps this to HTTP 422 so callers know the account is not ready.
Source code in src/application/use_cases/generate_expansion_summary.py
GenerateExpansionSummaryRequest
dataclass
¶
Input DTO for GenerateExpansionSummaryUseCase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_id
|
str
|
UUID of the active customer to generate a brief for. |
required |
audience
|
Literal['account_executive', 'csm']
|
'account_executive' (tactical brief + optional email) or 'csm' (nurture brief only; email_draft forced to None). |
'account_executive'
|
include_email_draft
|
bool
|
If True and audience is 'account_executive', the response will include a 3-sentence email draft. |
False
|
Source code in src/application/use_cases/generate_expansion_summary.py
GenerateExpansionSummaryUseCase ¶
Generates a personalised AE brief grounded in the expansion propensity model.
Business Context: Reduces AE prep time from ~20 minutes to 30 seconds. Personalisation via SHAP signals drives 10–15% conversion lift vs generic outreach. The correlation_id in each result enables the data team to join brief quality (fact_confidence) to close rates in the V2 fine-tuning flywheel.
Pipeline
- Fetch Customer entity (raises ValueError if not found / churned)
- Run PredictExpansionUseCase → ExpansionResult
- Propensity < 0.15 → raise PropensityTooLowError (API → 422)
- Propensity < 0.35 → return "not ready" result without LLM call
- CSM audience override: force include_email_draft=False
- Build expansion prompt via PromptBuilder
- Call LLM via SummaryPort.generate_from_prompt()
- Validate + transform via ExpansionGuardrailsService
- Return ExpansionSummaryResult
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_repo
|
CustomerRepository
|
Repository for fetching Customer entities. |
required |
expansion_use_case
|
PredictExpansionUseCase
|
PredictExpansionUseCase for propensity + SHAP. |
required |
summary_service
|
SummaryPort
|
SummaryPort implementation (Groq or Ollama). |
required |
guardrails
|
ExpansionGuardrailsService
|
ExpansionGuardrailsService for validation + watermark. |
required |
Source code in src/application/use_cases/generate_expansion_summary.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
Functions¶
Run the full expansion narrative pipeline for a single customer.
Business Context: All LLM calls are grounded in verified model outputs (ExpansionResult SHAP features). The guardrail layer ensures hallucinated signals are caught before the brief reaches an AE's CRM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
GenerateExpansionSummaryRequest
|
Contains customer_id, audience, and email draft flag. |
required |
Returns:
| Type | Description |
|---|---|
ExpansionSummaryResult
|
ExpansionSummaryResult with brief, guardrail result, and provenance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the customer is not found or has already churned. |
PropensityTooLowError
|
If propensity < 0.15 (API maps this to 422). |
Source code in src/application/use_cases/generate_expansion_summary.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |