File size: 51,890 Bytes
47b08cd
 
4088a7c
 
 
 
 
 
 
 
 
47b08cd
4088a7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47b08cd
4088a7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47b08cd
4088a7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47b08cd
4088a7c
47b08cd
4088a7c
 
 
47b08cd
 
 
4088a7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47b08cd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
ο»Ώ---
title: PRISM Marketing Intelligence
emoji: πŸ“Š
colorFrom: blue
colorTo: green
sdk: docker
app_port: 7860
pinned: false
license: mit
---

# PRISM Marketing Intelligence β€” MMM Dashboard

## Table of Contents

1. [Project Overview](#project-overview)
2. [Tech Stack](#tech-stack)
3. [Project Structure](#project-structure)
4. [Data Harmonization & Pipeline](#data-harmonization--pipeline)
   - [Architecture Overview](#architecture-overview)
   - [Medallion Pipeline Layers](#medallion-pipeline-layers)
   - [Raw Data Sources](#raw-data-sources)
   - [Data Quality Issues (Simulated)](#data-quality-issues-simulated)
   - [Pipeline Operations](#pipeline-operations)
     - [Step 1: Load Raw](#step-1-load-raw)
     - [Step 2: Data Profiling](#step-2-data-profiling)
     - [Step 3: Auto Column Mapping](#step-3-auto-column-mapping)
     - [Step 4: Apply Mapping (Raw β†’ Bronze)](#step-4-apply-mapping-raw--bronze)
     - [Step 5: Date Standardization (Bronze β†’ Silver)](#step-5-date-standardization-bronze--silver)
     - [Step 6: Missing Value Imputation](#step-6-missing-value-imputation)
     - [Step 7: Outlier Detection & Handling](#step-7-outlier-detection--handling)
     - [Step 8: Merge to Gold (Silver β†’ Gold)](#step-8-merge-to-gold-silver--gold)
     - [Step 9: Activate Gold Layer](#step-9-activate-gold-layer)
   - [AIRA Agent Cards](#aira-agent-cards)
   - [Column Alias Dictionary](#column-alias-dictionary)
   - [Standard Value Normalization](#standard-value-normalization)
   - [Schema Definitions](#schema-definitions)
   - [API Endpoints](#api-endpoints)
   - [Frontend Pipeline UI](#frontend-pipeline-ui)

---

## Project Overview

An end-to-end **Marketing Mix Modelling (MMM)** solution covering Media, Consumer Promo, and Trade Promo analysis with interactive dashboards, modelling capabilities, **NOVA** (Next-gen Optimization & Value Advisor), and an **Intelligent Alert & Simulation framework**.

The system ingests raw, messy data files (simulating real client exports), transforms them through a multi-layer pipeline, and feeds clean, standardized data into 13 analytical dashboards.

---

## Tech Stack

| Layer | Technology |
|-------|-----------|
| Backend | Python 3, Flask |
| Frontend | HTML5, JavaScript (vanilla), CSS3 |
| Charts | Plotly.js |
| Data Processing | Pandas, NumPy |
| Fuzzy Matching | `difflib.SequenceMatcher` (Python stdlib) |
| File Formats | Excel (.xlsx) input, CSV output |

---

## Project Structure

```
Marketing Effectivness/
β”œβ”€β”€ app_pkg/                         # Flask application package
β”‚   β”œβ”€β”€ __init__.py                  # App factory, DataService initialization
β”‚   β”œβ”€β”€ blueprints/
β”‚   β”‚   β”œβ”€β”€ data_mgmt.py            # Data Harmonization routes + Pipeline API
β”‚   β”‚   β”œβ”€β”€ main.py                 # Executive Summary routes
β”‚   β”‚   └── media.py                # Media Analysis routes
β”‚   └── services/
β”‚       β”œβ”€β”€ data_service.py          # DataService - loads data for all dashboards
β”‚       β”œβ”€β”€ pipeline_service.py      # PipelineService - medallion pipeline engine
β”‚       └── upload_service.py        # Upload validation service
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ raw/                         # Raw messy Excel files (input)
β”‚   β”œβ”€β”€ bronze/                      # (in-memory only, not persisted to disk)
β”‚   β”œβ”€β”€ silver/                      # (in-memory only, not persisted to disk)
β”‚   β”œβ”€β”€ gold/                        # Final clean CSVs (output, used by dashboards)
β”‚   └── synthetic/                   # Original clean synthetic data (fallback)
β”œβ”€β”€ static/
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   β”œβ”€β”€ style.css                # Global styles, themes (dark/light)
β”‚   β”‚   └── components.css           # Component styles including pipeline UI
β”‚   └── js/
β”‚       β”œβ”€β”€ pipeline.js              # Pipeline interaction logic
β”‚       β”œβ”€β”€ charts.js                # Chart rendering utilities
β”‚       └── theme.js                 # Theme toggle (dark/light mode)
β”œβ”€β”€ templates/
β”‚   β”œβ”€β”€ base.html                    # Base template with sidebar, NOVA, filters
β”‚   β”œβ”€β”€ data_mgmt.html              # Data Harmonization page
β”‚   β”œβ”€β”€ index.html                   # Executive Summary / Home
β”‚   └── media.html                   # Media Analysis page
β”œβ”€β”€ config.py                        # Flask configuration (paths, secrets)
β”œβ”€β”€ generate_raw_data.py             # Script to generate messy raw Excel files
β”œβ”€β”€ generate_data.py                 # Script to generate clean synthetic CSVs
β”œβ”€β”€ run.py                           # Flask entry point
β”œβ”€β”€ CLAUDE.md                        # Full project specification
└── README.md                        # This file
```

---

## Data Harmonization & Pipeline

### Architecture Overview

The Data Harmonization system implements a **Medallion Architecture** β€” a multi-layer data pipeline pattern used in data engineering to progressively improve data quality:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    DATA PIPELINE FLOW                                β”‚
β”‚                                                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”‚
β”‚  β”‚  RAW    │───▸│  BRONZE  │───▸│  SILVER  │───▸│  GOLD   β”‚       β”‚
β”‚  β”‚ (Excel) β”‚    β”‚ (Mapped) β”‚    β”‚(Cleaned) β”‚    β”‚ (Final) β”‚       β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚
β”‚       β”‚              β”‚               β”‚               β”‚             β”‚
β”‚   Load raw      Column mapping   Transforms     Dedup +           β”‚
β”‚   Excel files   via aliases +    (dates,        normalize +       β”‚
β”‚                 fuzzy match      missing,        save CSVs         β”‚
β”‚                                  outliers)                         β”‚
β”‚                                                                     β”‚
β”‚  5 source files  ──────────────────────────────▸  5 gold CSVs     β”‚
β”‚                                                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”‚
β”‚  β”‚           DataService (Hot-Reload)                       β”‚       β”‚
β”‚  β”‚  Dashboards use Gold if available, else Synthetic CSVs   β”‚       β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**Why Medallion Architecture?**
- **Traceability**: Each layer preserves the state of data at that stage, enabling debugging and auditability
- **Separation of Concerns**: Each transformation step is isolated and independently testable
- **Incremental Processing**: Sources can be processed independently and at different times
- **Rollback**: If a transformation produces unexpected results, you can re-run from a previous layer

---

### Medallion Pipeline Layers

| Layer | Description | Storage | Contents |
|-------|-------------|---------|----------|
| **Raw** | Original client data exactly as received | `data/raw/*.xlsx` | Excel files with messy column names, mixed formats, errors |
| **Bronze** | Schema-aligned data | In-memory (DataFrame) | Columns renamed to standard names, junk columns dropped |
| **Silver** | Cleaned and transformed data | In-memory (DataFrame) | Dates standardized, missing values imputed, outliers handled |
| **Gold** | Production-ready analytical data | `data/gold/*.csv` | Deduplicated, string-normalized, sorted, final CSVs |

---

### Raw Data Sources

Five raw Excel files simulate the kind of messy data a marketing analytics team would receive from various internal teams, agencies, and third-party vendors:

| # | File Name | Source Type | Simulates | Rows (approx.) |
|---|-----------|-------------|-----------|-----------------|
| 1 | `Media_Spend_Report_2024-25.xlsx` | `media` | Agency media spend export | ~1,870 |
| 2 | `Sales_Extract_All_Regions.xlsx` | `sales` | ERP/sales system extract | ~1,475 |
| 3 | `Consumer_Promotions_Master.xlsx` | `consumer_promo` | Marketing promo tracker | ~750 |
| 4 | `Trade_Promo_Events_Log.xlsx` | `trade_promo` | Trade marketing event log | ~735 |
| 5 | `Weather_Economic_Data.xlsx` | `external_factors` | External data vendor feed | ~740 |

**To regenerate raw files:**
```bash
python generate_raw_data.py
```
This reads the clean synthetic CSVs from `data/synthetic/` and introduces controlled data quality issues.

---

### Data Quality Issues (Simulated)

Each raw file has specific, realistic data quality problems that the pipeline is designed to handle:

#### Media Data (`Media_Spend_Report_2024-25.xlsx`)

| Issue | Details | Why It Happens in Real Life |
|-------|---------|----------------------------|
| **Renamed columns** | `channel` β†’ `Media Channel`, `spend` β†’ `Spend_USD`, `impressions` β†’ `Imp`, `brand` β†’ `Brand Name` | Different agencies and platforms use different naming conventions |
| **Mixed date formats** | `MM/DD/YYYY`, `DD-Mon-YYYY`, `YYYY/MM/DD` mixed in the same column | Data combined from multiple exports across different locales |
| **Inconsistent channel casing** | `tv`, `TV`, `Tv`, `TV ` (with trailing space) for the same channel | Manual data entry, copy-paste from different sources |
| **Missing clicks** | ~8% of click values are `NaN` | Not all media platforms report clicks (e.g., TV, Radio) |
| **Missing regions** | ~5% of region values are `NaN` | Some campaigns are national (no region tagged) |
| **Missing leads** | ~6% of lead values are `NaN` | Lead tracking not set up for all campaigns |
| **Spend outliers** | ~2% of spend values multiplied by 10x | Fat-finger errors, currency unit mistakes (e.g., entering cents instead of dollars) |
| **Duplicate rows** | ~3% duplicate records | Re-runs of export queries, overlapping report pulls |

#### Sales Data (`Sales_Extract_All_Regions.xlsx`)

| Issue | Details | Why It Happens in Real Life |
|-------|---------|----------------------------|
| **Renamed columns** | `product` β†’ `Product Name`, `revenue` β†’ `Sales_Revenue`, `price` β†’ `Unit Price`, `units_sold` β†’ `Units` | ERP systems have their own column naming conventions |
| **DD/MM/YYYY dates** | 40% `DD/MM/YYYY`, 30% `MM-DD-YYYY`, 30% `YYYY-MM-DD` | International teams using different locale settings |
| **Negative revenues** | ~1% of revenue values are negative | Returns/refunds mixed into the sales data |
| **Junk column** | `Unnamed: 0` column with sequential integers | Excel auto-generated index column from a prior save |
| **Missing new_customers** | ~6% null values | Customer tracking not available for all channels |
| **Missing prices** | ~3% null values | Promotional pricing not recorded properly |
| **Duplicate rows** | ~2% duplicates | Overlapping regional exports |

#### Consumer Promo Data (`Consumer_Promotions_Master.xlsx`)

| Issue | Details | Why It Happens in Real Life |
|-------|---------|----------------------------|
| **Renamed columns** | `promo_id` β†’ `Promo ID`, `promo_type` β†’ `Type`, `promo_spend` β†’ `Spend`, `start_date` β†’ `Start`, `end_date` β†’ `End` | Marketing teams use informal spreadsheet naming |
| **Inconsistent promo type casing** | `coupon`, `COUPON`, `Coupon`, `coupon ` for the same type; `BOGO`, `bogo`, `Buy One Get One` | Multiple team members entering data manually |
| **Mixed date formats** | Start/End dates in `YYYY-MM-DD`, `Mon DD, YYYY`, `MM/DD/YYYY` | Promo dates copied from different calendar systems |
| **Missing units_redeemed** | ~10% null values | Redemption tracking delayed, especially for in-store promos |
| **Missing promo_depth** | ~7% null values | Some promos have variable/dynamic discounts |
| **Spend outliers** | ~3% of spend values multiplied by 5-15x | Budget approvals recorded instead of actual spend |
| **Duplicate rows** | ~4% duplicates | Promo events spanning multiple periods double-counted |

#### Trade Promo Data (`Trade_Promo_Events_Log.xlsx`)

| Issue | Details | Why It Happens in Real Life |
|-------|---------|----------------------------|
| **Renamed columns** | `event_id` β†’ `Event ID`, `retailer` β†’ `Retailer Name`, `planned_spend` β†’ `Plan_Spend`, `actual_spend` β†’ `Act_Spend` | Trade marketing systems export with custom labels |
| **Compliance status typos** | `Complient`, `Partial`, `NC`, `COMPLIANT`, `Part. Compliant` | Field reps entering compliance status manually on mobile devices |
| **Mixed date formats** | ~5% of dates in `DD-Mon-YY` format, rest in original format | Some events entered from handwritten notes |
| **Missing baseline_volume** | ~12% null values | Baseline calculation requires historical data not always available |
| **Missing compliance_status** | ~5% null values | Compliance audits not completed for all events |
| **Actual spend outliers** | ~2% of actual_spend multiplied by 100x | Units error (entering in minor currency units vs. major) |
| **Duplicate rows** | ~2% duplicates | Same events reported by both brand team and retailer |

#### External Factors Data (`Weather_Economic_Data.xlsx`)

| Issue | Details | Why It Happens in Real Life |
|-------|---------|----------------------------|
| **Renamed columns** | `temperature` β†’ `temp_f`, `precipitation` β†’ `rain_inches`, `holiday_flag` β†’ `is_holiday`, `economic_index` β†’ `econ_idx` | Vendor APIs return abbreviated field names |
| **Boolean as Yes/No strings** | `holiday_flag` contains `Yes`/`No` instead of `True`/`False`; `event_flag` contains `Y`/`N` | CSV/Excel export from legacy systems that don't support boolean types |
| **Sensor error values** | ~1% of temperature readings are `-999.0` | Weather station sensor failures recorded as sentinel values |
| **Missing temperature** | ~3% null values | Weather station outages |
| **Missing economic_index** | ~2% null values | Economic data published with a lag, some periods missing |
| **Duplicate rows** | ~1% duplicates | Overlapping API pulls |

---

### Pipeline Operations

Each operation is a discrete, traceable step. Here's what each one does, why it's needed, and how it works internally:

---

#### Step 1: Load Raw

**What it does:** Reads a raw Excel file (`.xlsx`) from the `data/raw/` directory into an in-memory Pandas DataFrame.

**Why it's required:** The pipeline needs the data in memory to perform analysis and transformations. Loading also validates that the file exists and is readable.

**How it works:**
```
1. Look up the raw file name for the given source_type (e.g., 'media' β†’ 'Media_Spend_Report_2024-25.xlsx')
2. Read with pd.read_excel(filepath)
3. Store the DataFrame in pipeline state as raw_df
4. Set the source's layer to 'raw'
5. Reset any previous bronze/silver/gold state for this source
6. Log: "Loaded {N} rows, {M} columns from {filename}"
```

**API:** `POST /api/pipeline/load-raw` with `{"source_type": "media"}`

**Output:** Row count, column count, column names

---

#### Step 2: Data Profiling

**What it does:** Computes comprehensive statistics for every column in the raw data β€” data types, null percentages, distributions, outliers, date format detection, mixed casing detection.

**Why it's required:** Before you can clean data, you need to understand what's wrong with it. Profiling surfaces all quality issues systematically rather than discovering them one-by-one during analysis. It answers questions like:
- How many values are missing per column?
- Are there outliers? How extreme?
- What date formats are present?
- Are there sentinel values (like `-999`)?
- Are string values inconsistently cased?

**How it works per column:**

```
For each column in the DataFrame:
  1. Basic stats: total count, null count, null %, unique count

  2. TYPE INFERENCE β€” try to classify the column:
     a. NUMERIC: If >50% of non-null values can be parsed as numbers:
        - Compute: min, max, mean, median, std deviation
        - IQR-based outlier detection: values outside [Q1 - 1.5*IQR, Q3 + 1.5*IQR]
        - Sentinel detection: count of values < -900 (e.g., -999)
        - Negative value count (flags potential errors in spend/revenue columns)

     b. DATE: If >50% of non-null values can be parsed as dates:
        - Date range: earliest to latest
        - Format detection: tests each value against 8 known date patterns:
          YYYY-MM-DD, MM/DD/YYYY, DD/MM/YYYY, DD-Mon-YYYY, DD-Mon-YY,
          Mon DD YYYY, MM-DD-YYYY, YYYY/MM/DD
        - Parse failure count: values that couldn't be interpreted as dates

     c. STRING: Everything else:
        - Top 5 most frequent values with counts
        - Mixed casing detection: compares unique values vs unique values
          after lowercasing β€” if different, casing is inconsistent
        - Reports the number of "casing variants" (e.g., 'TV', 'tv', 'Tv' = 2 variants)
```

**Dataset-level stats:**
- Total duplicate rows (full row matches)
- Quality score: `(1 - missing_cells / total_cells) Γ— 100`
- Total missing cells across all columns

**API:** `POST /api/pipeline/profile` with `{"source_type": "media"}`

**Output example:**
```json
{
  "rows": 1872,
  "columns_count": 14,
  "duplicates": 54,
  "quality_score": 96.8,
  "missing_total": 385,
  "column_profiles": [
    {
      "name": "Media Channel",
      "dtype": "object",
      "inferred_type": "string",
      "nulls": 0,
      "null_pct": 0.0,
      "unique": 9,
      "mixed_casing": true,
      "casing_variants": 3,
      "top_values": [{"value": "tv", "count": 210}, ...]
    },
    {
      "name": "Spend_USD",
      "dtype": "float64",
      "inferred_type": "numeric",
      "nulls": 0,
      "min": 120.50,
      "max": 95420.00,
      "mean": 4520.30,
      "outliers": 38,
      "negatives": 0
    }
  ]
}
```

---

#### Step 3: Auto Column Mapping

**What it does:** Automatically figures out which raw column corresponds to which schema column. For example, it determines that `Spend_USD` in the raw file should map to the standard `spend` column.

**Why it's required:** Every data source uses different column names. Media agencies call it "Spend_USD", finance teams call it "Cost", analytics platforms call it "Amount Spent". The system needs a single, consistent schema to work with. Manual mapping of dozens of columns across 5 data sources is tedious and error-prone β€” auto-mapping handles this intelligently.

**How it works β€” Three-Tier Matching:**

```
For each raw column name, try matching in this priority order:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TIER 1: EXACT MATCH (Confidence: 100%)                  β”‚
β”‚                                                         β”‚
β”‚ Normalize the raw column: lowercase, strip whitespace,  β”‚
β”‚ replace spaces and hyphens with underscores.            β”‚
β”‚                                                         β”‚
β”‚ Example: "clicks" β†’ "clicks" = exact match              β”‚
β”‚ Example: "date" β†’ "date" = exact match                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚ No match? Try next tier
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TIER 2: ALIAS DICTIONARY LOOKUP (Confidence: 92%)       β”‚
β”‚                                                         β”‚
β”‚ Check against a curated dictionary of ~60 known column  β”‚
β”‚ name aliases. Each standard column has a list of known  β”‚
β”‚ alternative names from common platforms and systems.     β”‚
β”‚                                                         β”‚
β”‚ Example: "Spend_USD" β†’ alias "spend_usd" β†’ maps to     β”‚
β”‚          "spend" (92% confidence)                       β”‚
β”‚ Example: "Imp" β†’ alias "imp" β†’ maps to                 β”‚
β”‚          "impressions" (92% confidence)                 β”‚
β”‚ Example: "Brand Name" β†’ alias "brand_name" β†’ maps to   β”‚
β”‚          "brand" (92% confidence)                       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚ No match? Try next tier
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TIER 3: FUZZY MATCHING (Confidence: varies, min 60%)    β”‚
β”‚                                                         β”‚
β”‚ Uses Python's difflib.SequenceMatcher to compute string β”‚
β”‚ similarity ratio between the raw column name and all    β”‚
β”‚ remaining unmapped schema columns.                      β”‚
β”‚                                                         β”‚
β”‚ Picks the best match above 60% similarity threshold.    β”‚
β”‚ Confidence score = similarity ratio Γ— 100.              β”‚
β”‚                                                         β”‚
β”‚ Example: "campaign" β†’ 78% similar to "campaign_name"    β”‚
β”‚          β†’ maps with 78% confidence                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚ No match above 60%?
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SPECIAL CASES                                           β”‚
β”‚                                                         β”‚
β”‚ β€’ Junk columns (starting with "Unnamed") β†’ marked as    β”‚
β”‚   "__drop__" (100% confidence, method: "drop")          β”‚
β”‚ β€’ No match found β†’ marked as "__unmapped__"             β”‚
β”‚   (0% confidence, method: "unmapped")                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**Collision prevention:** Once a target column is matched, it's removed from the candidate pool. This prevents two raw columns from mapping to the same target.

**API:** `POST /api/pipeline/auto-map` with `{"source_type": "media"}`

**Output example:**
```json
{
  "mappings": {
    "Media Channel": {"mapped_to": "channel", "confidence": 92, "method": "alias"},
    "Spend_USD": {"mapped_to": "spend", "confidence": 92, "method": "alias"},
    "Imp": {"mapped_to": "impressions", "confidence": 92, "method": "alias"},
    "clicks": {"mapped_to": "clicks", "confidence": 100, "method": "exact"},
    "Unnamed: 0": {"mapped_to": "__drop__", "confidence": 100, "method": "drop"}
  },
  "target_columns": ["date", "channel", "spend", "impressions", "brand", ...]
}
```

---

#### Step 4: Apply Mapping (Raw β†’ Bronze)

**What it does:** Takes the column mappings (from Step 3) and physically renames the columns, drops junk/unmapped columns, and creates the Bronze DataFrame.

**Why it's required:** This is the structural transformation β€” the data now conforms to the expected schema column names. Without this, downstream transformations wouldn't know which column is "spend" vs "Spend_USD" vs "cost". It also cleans up garbage columns that would pollute analysis.

**How it works:**
```
1. Build a rename dictionary from confirmed mappings
   Example: {"Media Channel" β†’ "channel", "Spend_USD" β†’ "spend", ...}

2. Build a drop list from mappings marked as __drop__ or __unmapped__
   Example: ["Unnamed: 0"]

3. Drop junk columns from DataFrame

4. Rename remaining columns to standard names

5. Clean string columns:
   - Strip leading/trailing whitespace from all string values
   - Convert literal "nan" strings back to actual NaN

6. Remove fully empty rows (rows where every cell is NaN)

7. Store result as bronze_df
8. Also copy to silver_df (silver starts as a copy of bronze,
   then transforms are applied incrementally)
9. Set layer to 'bronze'
```

**API:** `POST /api/pipeline/apply-mapping` with `{"source_type": "media"}`

---

#### Step 5: Date Standardization (Bronze β†’ Silver)

**What it does:** Converts all date columns to a consistent `YYYY-MM-DD` format, regardless of what format they were originally in.

**Why it's required:** A single dataset might contain dates in 3-4 different formats (`01/15/2024`, `15-Jan-2024`, `2024/01/15`) because data was compiled from multiple sources or regions. Date sorting, filtering, time series analysis, and joins between tables all require consistent date formatting. Ambiguous dates like `01/02/2024` (is that Jan 2 or Feb 1?) must be resolved.

**How it works:**
```
1. Identify all date columns from the schema definition
   (e.g., 'date', 'start_date', 'end_date')

2. For each date column:
   a. Count nulls BEFORE transformation

   b. Parse with pd.to_datetime(format='mixed', dayfirst=False)
      - 'mixed' format allows pandas to try multiple date patterns
      - dayfirst=False resolves ambiguous dates as MM/DD (US convention)

   c. Count nulls AFTER transformation (new nulls = unparseable values)

   d. Detect which formats were present in the original data
      by testing a 50-row sample against 8 known format patterns

   e. Convert all successfully parsed dates to 'YYYY-MM-DD' string format

   f. Values that couldn't be parsed remain as NaN

3. Log: "Standardized {N} date columns. Fixed {M} values."
```

**Date format patterns detected:**

| Pattern | Format Code | Example |
|---------|------------|---------|
| `YYYY-MM-DD` | `%Y-%m-%d` | `2024-01-15` |
| `MM/DD/YYYY` | `%m/%d/%Y` | `01/15/2024` |
| `DD/MM/YYYY` | `%d/%m/%Y` | `15/01/2024` |
| `DD-Mon-YYYY` | `%d-%b-%Y` | `15-Jan-2024` |
| `DD-Mon-YY` | `%d-%b-%y` | `15-Jan-24` |
| `Mon DD, YYYY` | `%b %d, %Y` | `Jan 15, 2024` |
| `MM-DD-YYYY` | `%m-%d-%Y` | `01-15-2024` |
| `YYYY/MM/DD` | `%Y/%m/%d` | `2024/01/15` |

**API:** `POST /api/pipeline/transform/dates` with `{"source_type": "media"}`

**Output example:**
```json
{
  "results": [
    {
      "column": "date",
      "formats_found": ["MM/DD/YYYY", "DD-Mon-YYYY", "YYYY/MM/DD"],
      "converted": 1872,
      "failed": 0
    }
  ],
  "total_fixed": 1872
}
```

---

#### Step 6: Missing Value Imputation

**What it does:** Fills in missing (`NaN`) values using statistically appropriate methods based on the column's data type and business context.

**Why it's required:** Missing values cause multiple problems:
- Many statistical models and chart libraries can't handle NaN values
- Missing data biases aggregations (averages, totals, etc.)
- Downstream joins may fail or produce incorrect results
- A 10% missing rate in clicks means CTR calculations are wrong for those periods

The imputation strategy must be appropriate for each column type β€” you can't fill missing dates with a median, and you shouldn't fill missing IDs.

**How it works β€” Strategy per column type:**

```
For each column with missing values:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ STRATEGY SELECTION BY COLUMN TYPE                   β”‚
β”‚                                                     β”‚
β”‚ ID Columns (promo_id, event_id, ad_id):            β”‚
β”‚   β†’ SKIP: IDs are unique identifiers, imputing     β”‚
β”‚     them would create fake records                  β”‚
β”‚                                                     β”‚
β”‚ Date Columns (date, start_date, end_date):         β”‚
β”‚   β†’ FORWARD FILL: Use the previous row's date      β”‚
β”‚     Rationale: time series data is sequential,      β”‚
β”‚     a missing date likely falls between neighbors   β”‚
β”‚                                                     β”‚
β”‚ Float Columns (spend, revenue, price, etc.):       β”‚
β”‚   β†’ MEDIAN: Use the column's median value           β”‚
β”‚     Rationale: median is robust to outliers          β”‚
β”‚     (unlike mean, which gets skewed by extremes)    β”‚
β”‚                                                     β”‚
β”‚ Integer Columns (clicks, conversions, units):      β”‚
β”‚   β†’ MEDIAN + ROUND: Median, then round to integer   β”‚
β”‚     Rationale: same as float, but maintain int type β”‚
β”‚     Uses nullable Int64 dtype (supports NaN)        β”‚
β”‚                                                     β”‚
β”‚ Boolean Columns (holiday_flag, event_flag):         β”‚
β”‚   β†’ FILL FALSE: Assume no holiday/event             β”‚
β”‚     Rationale: holidays are rare; missing usually   β”‚
β”‚     means "no event" rather than unknown event      β”‚
β”‚                                                     β”‚
β”‚ String/Categorical (channel, brand, region):        β”‚
β”‚   β†’ MODE: Use the most frequent value               β”‚
β”‚     Rationale: categorical data should match the    β”‚
β”‚     most common category (conservative approach)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**API:** `POST /api/pipeline/transform/missing` with `{"source_type": "media"}`

**Output example:**
```json
{
  "results": [
    {"column": "clicks", "missing_before": 150, "missing_after": 0, "method": "median (245.0)", "imputed": 150},
    {"column": "region", "missing_before": 94, "missing_after": 0, "method": "mode (\"North\")", "imputed": 94},
    {"column": "leads", "missing_before": 112, "missing_after": 0, "method": "median (18.0)", "imputed": 112}
  ],
  "total_imputed": 356
}
```

---

#### Step 7: Outlier Detection & Handling

**What it does:** Identifies values that are statistically extreme or represent data entry errors, then caps them at reasonable bounds (winsorization) rather than deleting the entire row.

**Why it's required:** Outliers distort every statistical analysis:
- A single `$95,000` spend entry (should be `$9,500`) inflates average spend by 5-10%
- Outlier revenue values skew ROAS calculations
- Sentinel values like `-999` (sensor errors) get treated as real negatives
- Fat-finger errors propagate through all downstream charts and models

**Why winsorization (capping) instead of deletion:**
- Deleting rows loses all the other valid columns in that row
- The row represents a real marketing event; only the specific value is wrong
- Capping to the statistical boundary preserves the directional information

**How it works:**

```
For each numeric column defined in the schema:

1. CONVERT TO FLOAT64
   Why: Previous missing value imputation may have set columns to
   Int64 (nullable integer) dtype. Float64 is required for
   statistical operations and clip().

2. SENTINEL VALUE DETECTION
   Check for values < -900 (common sensor error codes: -999, -998, etc.)
   If found: Replace -999, -998, -997 with NaN
   These are not real data β€” they're error codes masquerading as numbers.

3. IQR-BASED OUTLIER DETECTION
   Q1 = 25th percentile
   Q3 = 75th percentile
   IQR = Q3 - Q1 (interquartile range)

   Lower bound = Q1 - 1.5 Γ— IQR
   Upper bound = Q3 + 1.5 Γ— IQR

   Values outside [lower, upper] are classified as outliers.

   This is the standard Tukey's fence method used in box plots.

4. POSITIVE-ONLY CONSTRAINT
   For columns that can never be negative in business context:
   (spend, revenue, impressions, clicks, conversions, units_sold,
    price, promo_spend, planned_spend, actual_spend, temperature,
    precipitation, etc.)

   β†’ Set lower bound to max(0, calculated_lower)
   β†’ Also count and fix any negative values

   Why: You can't have -$500 in media spend or -100 impressions.

5. WINSORIZATION (Capping)
   All outlier values are clipped to [lower_bound, upper_bound]:
   - Values below lower bound β†’ set to lower bound
   - Values above upper bound β†’ set to upper bound

   Example: If spend bounds are [$200, $12,000]:
   - A value of $95,420 (fat-finger) β†’ capped to $12,000
   - A value of -$500 (error) β†’ capped to $0
```

**Minimum data requirement:** Skips columns with fewer than 10 non-null values (not enough data for meaningful statistical bounds).

**API:** `POST /api/pipeline/transform/outliers` with `{"source_type": "media"}`

**Output example:**
```json
{
  "results": [
    {"column": "spend", "outliers_found": 38, "sentinel_values": 0, "negatives_fixed": 0, "bounds": [120.50, 12000.00], "action": "capped"},
    {"column": "impressions", "outliers_found": 12, "sentinel_values": 0, "negatives_fixed": 0, "bounds": [1000, 500000], "action": "capped"},
    {"column": "clicks", "outliers_found": 5, "sentinel_values": 0, "negatives_fixed": 0, "bounds": [0, 8500], "action": "capped"}
  ],
  "total_outliers": 55
}
```

---

#### Step 8: Merge to Gold (Silver β†’ Gold)

**What it does:** Takes all 5 Silver DataFrames, performs final cleaning and normalization, and saves them as individual CSV files in the `data/gold/` directory.

**Why it's required:** The Gold layer is the single source of truth for all downstream dashboards. This step ensures:
- No duplicate records inflate metrics
- All string values are consistently formatted (no `tv` vs `TV` vs `Tv`)
- Boolean values are actual booleans (not `Yes`/`No` strings)
- Data is chronologically sorted for time series analysis
- Files are in CSV format for fast loading by DataService

**How it works:**

```
For each of the 5 source types:

1. DEDUPLICATION
   - Remove exact duplicate rows (every column matches)
   - Track count of duplicates removed
   - Why: Prevents double-counting in aggregations

2. STRING VALUE NORMALIZATION
   Standardize common string values using a lookup dictionary:

   Channel:     'tv' β†’ 'TV', 'digital display' β†’ 'Digital Display', etc.
   Brand:       'alpha' β†’ 'Alpha', 'beta' β†’ 'Beta', etc.
   Region:      'north' β†’ 'North', 'south' β†’ 'South', etc.
   Compliance:  'complient' β†’ 'Compliant', 'nc' β†’ 'Non-compliant', etc.
   Promo Type:  'bogo' β†’ 'BOGO', 'cash back' β†’ 'Cashback', etc.

   Process: lowercase the value β†’ look up in normalization map β†’ replace
   Values not in the map are left unchanged.

3. BOOLEAN CONVERSION
   holiday_flag: 'Yes'/'No'/'Y'/'N'/'True'/'False'/'1'/'0' β†’ True/False
   event_flag:   Same conversion
   Unrecognized values β†’ default to False

4. CHRONOLOGICAL SORTING
   Parse 'date' column as datetime, sort ascending, reset index
   Convert back to 'YYYY-MM-DD' string for CSV storage

5. SAVE TO CSV
   Save as: data/gold/{source_type}_data.csv
   Files: media_data.csv, sales_data.csv, consumer_promo_data.csv,
          trade_promo_data.csv, external_factors_data.csv
   No index column (index=False)

6. Update pipeline state to 'gold' for all sources
```

**API:** `POST /api/pipeline/to-gold`

**Output example:**
```json
{
  "success": true,
  "stats": {
    "media": {"rows": 1818, "columns": 14, "duplicates_removed": 54},
    "sales": {"rows": 1446, "columns": 9, "duplicates_removed": 29},
    "consumer_promo": {"rows": 700, "columns": 14, "duplicates_removed": 50},
    "trade_promo": {"rows": 718, "columns": 14, "duplicates_removed": 17},
    "external_factors": {"rows": 725, "columns": 9, "duplicates_removed": 8}
  },
  "gold_dir": "data/gold"
}
```

---

#### Step 9: Activate Gold Layer

**What it does:** Hot-reloads the application's DataService to use Gold layer CSVs instead of the original synthetic data, without restarting the server.

**Why it's required:** The DataService is initialized at app startup and loads data into memory. After the pipeline creates Gold CSVs, the running app would still be using the old synthetic data. This step swaps the data source live, so all dashboards immediately reflect the cleaned, pipeline-processed data.

**How it works:**
```
1. Check that gold directory exists
2. Call data_service.reload_from_gold(gold_dir)
3. DataService re-reads all CSVs from data/gold/
4. All dashboard routes now serve cleaned data
5. DataService._source changes from 'synthetic' to 'gold'
```

**Effect on dashboards:**
- Revenue numbers may change slightly (outliers removed, duplicates cleaned)
- Channel names are consistent (no more `tv` vs `TV`)
- Date-based filtering works reliably
- Missing value gaps in charts are filled

**API:** `POST /api/pipeline/activate-gold`

---

### NOVA Pipeline Agents

The UI presents three "NOVA Pipeline Agent" cards that orchestrate the pipeline operations in logical groups:

| Agent Card | Operations Performed | Description |
|------------|---------------------|-------------|
| **Data Profiler (NOVA)** | Load Raw β†’ Profile (for all 5 sources) | Loads all raw Excel files and runs comprehensive profiling. Shows column-level statistics, quality scores, and detected issues in a tabular results panel. |
| **Auto Column Mapper (NOVA)** | Auto-Map β†’ Apply Mapping (for all 5 sources) | Runs three-tier column matching, displays mapping results with confidence badges (green β‰₯90%, yellow β‰₯70%, red <70%), then applies confirmed mappings to create Bronze DataFrames. |
| **Apply All Transforms (NOVA)** | Date Transform β†’ Missing β†’ Outliers β†’ Merge to Gold (for all 5 sources) | Sequentially runs all three Silver transformations across all sources, then merges to Gold. Shows individual transform results with statistics. |

Each agent card also has individual transform buttons for running steps one at a time:

| Transform Card | What it Runs |
|----------------|-------------|
| Date Standardization | `transform_dates` on all sources |
| Missing Value Handler | `transform_missing` on all sources |
| Outlier Detection | `transform_outliers` on all sources |
| Merge to Gold | `merge_to_gold` |

---

### Column Alias Dictionary

The auto-mapper uses a curated dictionary of ~60 known column name aliases. This is the complete mapping:

| Standard Column | Known Aliases |
|----------------|---------------|
| `date` | date, dt, week, period |
| `channel` | media_channel, media channel, platform, channel_name |
| `sub_channel` | sub_channel, sub channel, subchannel, sub_platform |
| `campaign_name` | campaign, campaign_name, camp_name, campaign_id |
| `campaign_objective` | objective, campaign_objective, obj, goal |
| `ad_id` | ad_id, ad id, creative_id, ad_identifier |
| `ad_format` | format, ad_format, creative_format, ad_type |
| `spend` | spend_usd, spend, cost, media_spend, amount_spent, budget, investment |
| `impressions` | imp, imps, impressions, total_impressions, views |
| `clicks` | clicks, click, total_clicks |
| `conversions` | conversions, conv, conversion, total_conversions |
| `leads` | leads, lead, total_leads |
| `region` | region, geo, geography, area, territory |
| `brand` | brand_name, brand, product_brand, brand_id |
| `media_type` | type, media_type, paid_organic |
| `product` | product_name, product, item, sku_name, sku |
| `units_sold` | units, units_sold, quantity, qty, volume, unit_sold |
| `revenue` | sales_revenue, revenue, total_revenue, sales, rev, gross_revenue |
| `price` | unit_price, price, selling_price, avg_price, unit price |
| `new_customers` | new_customers, new_cust, acquired, new_customer |
| `promo_id` | promo_id, promo id, promotion_id, promo_code |
| `promo_name` | promo_name, promo name, promotion_name, name |
| `promo_type` | type, promo_type, promotion_type, promo_category |
| `promo_mechanic` | mechanic, promo_mechanic, delivery_mechanism, mechanism |
| `promo_spend` | spend, promo_spend, promo_cost, promotion_spend, cost |
| `promo_depth` | depth_%, depth, promo_depth, discount_depth, discount_%, discount_pct |
| `units_redeemed` | redeemed, units_redeemed, redemptions, redeemed_units |
| `total_units_distributed` | distributed, total_units_distributed, total_distributed, units_distributed |
| `start_date` | start, start_date, promo_start, begin_date, start date |
| `end_date` | end, end_date, promo_end, finish_date, end date |
| `event_id` | event_id, event id, event_code, trade_event_id |
| `retailer` | retailer_name, retailer, account, customer_name, store |
| `planned_spend` | plan_spend, planned_spend, budget_planned, planned_cost |
| `actual_spend` | act_spend, actual_spend, actual_cost, real_spend |
| `baseline_volume` | base_vol, baseline_volume, base_volume, baseline_vol |
| `actual_volume` | act_vol, actual_volume, actual_vol, real_volume |
| `compliance_status` | compliance, compliance_status, comp_status, execution_status |
| `temperature` | temp_f, temp_c, temperature, avg_temp, avg_temperature |
| `precipitation` | rain_inches, rainfall, precipitation, precip, rain |
| `holiday_flag` | is_holiday, holiday_flag, holiday, holiday_indicator |
| `holiday_name` | holiday_name, holiday_desc, holiday_description |
| `economic_index` | econ_idx, economic_index, econ_index, consumer_confidence |
| `competitor_price_index` | comp_price_idx, competitor_price_index, comp_idx, competitor_index |
| `event_flag` | event_flag, event_indicator, special_event |
| `event_name` | event_name, event_desc, event_description |

---

### Standard Value Normalization

The Gold layer normalizes string values to a single canonical form. Here's the complete normalization map:

#### Channels
| Input Variants | Normalized To |
|---------------|---------------|
| `tv`, `television` | `TV` |
| `digital display`, `display` | `Digital Display` |
| `paid search`, `search` | `Paid Search` |
| `social media`, `social` | `Social Media` |
| `radio` | `Radio` |
| `print` | `Print` |

#### Brands
| Input Variants | Normalized To |
|---------------|---------------|
| `alpha` | `Alpha` |
| `beta` | `Beta` |
| `gamma` | `Gamma` |

#### Regions
| Input Variants | Normalized To |
|---------------|---------------|
| `north` | `North` |
| `south` | `South` |
| `east` | `East` |
| `west` | `West` |

#### Compliance Status
| Input Variants | Normalized To |
|---------------|---------------|
| `compliant`, `complient` | `Compliant` |
| `partially compliant`, `partial`, `part. compliant` | `Partially Compliant` |
| `non-compliant`, `noncompliant`, `nc` | `Non-compliant` |

#### Promo Types
| Input Variants | Normalized To |
|---------------|---------------|
| `coupon` | `Coupon` |
| `discount %`, `discount%` | `Discount %` |
| `bogo`, `buy one get one` | `BOGO` |
| `cashback`, `cash back` | `Cashback` |
| `free sample`, `freesample` | `Free Sample` |
| `bundle deal`, `bundle` | `Bundle Deal` |
| `off-invoice discount` | `Off-invoice discount` |
| `bill-back` | `Bill-back` |
| `scan-down` | `Scan-down` |
| `display allowance` | `Display allowance` |
| `slotting fee` | `Slotting fee` |
| `co-op advertising` | `Co-op advertising` |
| `volume rebate` | `Volume rebate` |

---

### Schema Definitions

Each data source has a defined schema with required and optional fields:

#### Media Schema
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `date` | date | Yes | Activity date |
| `channel` | string | Yes | Media channel (TV, Digital, etc.) |
| `spend` | float | Yes | Spend amount ($) |
| `impressions` | int | Yes | Number of impressions |
| `brand` | string | Yes | Brand name |
| `sub_channel` | string | No | Sub-channel (Facebook, Google, etc.) |
| `campaign_name` | string | No | Campaign identifier |
| `campaign_objective` | string | No | Campaign goal |
| `ad_id` | string | No | Individual ad identifier |
| `ad_format` | string | No | Creative format |
| `clicks` | int | No | Number of clicks |
| `conversions` | int | No | Number of conversions |
| `leads` | int | No | Number of leads |
| `region` | string | No | Geographic region |
| `media_type` | string | No | Paid/Owned/Earned |

#### Sales Schema
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `date` | date | Yes | Sales date |
| `product` | string | Yes | Product name/SKU |
| `brand` | string | Yes | Brand name |
| `units_sold` | int | Yes | Units sold |
| `revenue` | float | Yes | Revenue ($) |
| `price` | float | Yes | Selling price |
| `region` | string | No | Geographic region |
| `channel` | string | No | Sales channel |
| `new_customers` | int | No | New customer count |

#### Consumer Promo Schema
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `date` | date | Yes | Activity date |
| `promo_id` | string | Yes | Promo identifier |
| `promo_name` | string | Yes | Promo name |
| `promo_type` | string | Yes | Coupon/Discount/BOGO etc. |
| `product` | string | Yes | Target product |
| `promo_spend` | float | Yes | Promo cost ($) |
| `start_date` | date | Yes | Promo start |
| `end_date` | date | Yes | Promo end |
| `brand` | string | Yes | Brand name |
| `promo_mechanic` | string | No | Delivery mechanism |
| `promo_depth` | float | No | Discount depth (%) |
| `units_redeemed` | int | No | Units redeemed |
| `total_units_distributed` | int | No | Total distributed |
| `region` | string | No | Geographic region |

#### Trade Promo Schema
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `date` | date | Yes | Activity date |
| `event_id` | string | Yes | Event identifier |
| `promo_type` | string | Yes | Trade promo type |
| `retailer` | string | Yes | Retailer/account name |
| `product` | string | Yes | Target product/SKU |
| `planned_spend` | float | Yes | Planned spend ($) |
| `actual_spend` | float | Yes | Actual spend ($) |
| `actual_volume` | float | Yes | During-promo volume |
| `start_date` | date | Yes | Event start |
| `end_date` | date | Yes | Event end |
| `brand` | string | Yes | Brand name |
| `baseline_volume` | float | No | Pre-promo baseline |
| `compliance_status` | string | No | Execution compliance |
| `region` | string | No | Geographic region |

#### External Factors Schema
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `date` | date | Yes | Date |
| `temperature` | float | No | Average temperature |
| `precipitation` | float | No | Rainfall amount |
| `holiday_flag` | boolean | No | Holiday indicator |
| `holiday_name` | string | No | Holiday name |
| `economic_index` | float | No | Consumer confidence index |
| `competitor_price_index` | float | No | Competitor pricing index |
| `event_flag` | boolean | No | Special event indicator |
| `event_name` | string | No | Event name |

---

### API Endpoints

All pipeline endpoints are prefixed under the Data Management blueprint:

| Method | Endpoint | Description | Request Body |
|--------|----------|-------------|-------------|
| `GET` | `/api/pipeline/status` | Get pipeline status for all sources | β€” |
| `POST` | `/api/pipeline/load-raw` | Load a raw Excel file | `{"source_type": "media"}` |
| `POST` | `/api/pipeline/profile` | Profile a loaded source | `{"source_type": "media"}` |
| `POST` | `/api/pipeline/auto-map` | Auto-detect column mappings | `{"source_type": "media"}` |
| `POST` | `/api/pipeline/apply-mapping` | Apply mappings to create Bronze | `{"source_type": "media", "mappings": {...}}` |
| `POST` | `/api/pipeline/transform/dates` | Standardize date columns | `{"source_type": "media"}` |
| `POST` | `/api/pipeline/transform/missing` | Impute missing values | `{"source_type": "media"}` |
| `POST` | `/api/pipeline/transform/outliers` | Detect and handle outliers | `{"source_type": "media"}` |
| `POST` | `/api/pipeline/to-gold` | Merge all Silver sources to Gold | β€” |
| `POST` | `/api/pipeline/activate-gold` | Hot-reload DataService with Gold data | β€” |
| `GET` | `/api/pipeline/preview?source_type=media&layer=silver` | Preview data at any layer | Query params |
| `GET` | `/api/pipeline/log` | Get transformation log | β€” |

---

### Frontend Pipeline UI

The Data Harmonization page (`templates/data_mgmt.html`) provides a visual interface for the pipeline:

#### Pipeline Progress Tracker
A horizontal stepper showing all 4 layers: **Raw β†’ Bronze β†’ Silver β†’ Gold**
- Each step shows a count (e.g., `3/5`) of how many sources have reached that layer
- Steps turn green when all 5 sources are at that layer or beyond
- Connectors between steps animate when transitions are happening

#### Source Cards Grid
Five cards (one per data source) showing:
- Current layer badge (color-coded: gray=none, copper=raw, bronze=bronze, green=silver, gold=gold)
- File name and size
- Row Γ— column dimensions
- Action buttons contextual to current layer

#### Results Panel
Tabbed panel showing operation results:
- **Profile Tab**: Column statistics table with type, nulls, outliers, distributions
- **Mapping Tab**: Column mapping results with confidence badges and match methods
- **Preview Tab**: Data preview at any layer (raw/bronze/silver/gold)
- **Log Tab**: Chronological transformation log with timestamps

#### Gold Banner
Appears after Gold layer is created, with an "Activate Gold Layer" button that hot-reloads all dashboards with cleaned data.

---

## Running the Application

```bash
# 1. Install dependencies
pip install flask pandas numpy openpyxl

# 2. Generate synthetic data (if not present)
python generate_data.py

# 3. Generate messy raw files (if not present)
python generate_raw_data.py

# 4. Start the Flask server
python run.py

# 5. Open in browser
# http://localhost:5000
```

**Pipeline workflow in the UI:**
1. Navigate to "Data Harmonization" (first item in sidebar)
2. Click "Data Profiler" agent card β†’ loads and profiles all 5 sources
3. Click "Auto Column Mapper" agent card β†’ maps columns and creates Bronze
4. Click "Apply All Transforms" agent card β†’ runs all transforms and creates Gold
5. Click "Activate Gold Layer" β†’ dashboards now use cleaned data

---

## Known Limitations

1. **In-memory state**: Pipeline state is held in the Flask process memory. Restarting the server (or Flask's debug reloader triggering) resets the pipeline state. Gold CSVs persist on disk and are auto-loaded on next startup.

2. **Date ambiguity**: Dates like `01/02/2024` are interpreted as MM/DD/YYYY (US convention) due to `dayfirst=False`. This may be incorrect for European data sources where it would mean Feb 1st, not Jan 2nd.

3. **Fuzzy matching threshold**: The 60% similarity threshold for fuzzy column matching may produce false positives on short column names (e.g., a 3-letter column matching a 4-letter target at 62% similarity).

4. **Single-process design**: The PipelineService singleton assumes a single Flask worker process. Multiple workers (e.g., gunicorn with multiple workers) would each have independent pipeline states.

---

*Last updated: May 2026 β€” PRISM Marketing Intelligence powered by NOVA*