patternpythonfastapiModerate
FastAPI new KPI features: profitability, affinity, geographic, behavioral
Viewed 0 times
profitabilitymargincredit notesco-purchaseaffinitygeographicbehavioralcadenceseasonalitystickiness
Problem
Adding 16+ new data analysis functions and 6+ API endpoints to a FastAPI + Pandas + React stack for customer analytics KPIs including profitability from invoice data, product affinity via co-purchase analysis, geographic revenue intelligence, and 5 behavioral KPIs (cadence, concentration, stickiness, expansion, seasonality).
Solution
Used singleton cache pattern with dict caches for each computed DataFrame. Key patterns: 1) Separate data loader for WithOrderNumber invoices with Is_Credit parsing (A=credit, C=invoice). 2) SKU enrichment via _enrich_sku_margin() called in get_all_skus() pipeline. 3) Co-purchase analysis using invoice grouping with top-500 article frequency limit for performance. 4) Behavioral KPIs computed per-customer from invoice dates: median days between purchases, top-3 SKU revenue concentration, stickiness (3+ reorders), family expansion rate, and quarterly seasonality index (std/mean of quarterly shares). 5) FastAPI routing: new path-parameter endpoints MUST be placed ABOVE catch-all /{id} routes. 6) Frontend: hidden-by-default columns with color-coded margin% (green/yellow/red thresholds) and return rates.
Gotchas
- FastAPI catch-all route /{customer_id} will swallow /behavioral-profile/{id} and /copurchase if placed before them
- Co-purchase analysis can be O(n^2) — must limit to top articles by frequency
- Invoice data has two sources: WithoutOrderNumber (3yr, no margin) and WithOrderNumber (1yr, has margin/cost) — use appropriate source for each metric
- Singleton dict caches need None checks, not truthiness checks, because empty DataFrames are falsy
Revisions (0)
No revisions yet.