Repository navigation
Expand file tree
/
Copy pathvalidate_restructured.py
More file actions
209 lines (163 loc) · 8.1 KB
/
Copy pathvalidate_restructured.py
File metadata and controls
209 lines (163 loc) · 8.1 KB
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
"""
Pelcro Import Validation Script
================================
POC — Customers & Addresses checks
Checks performed:
1. customers — invalid email format
2. customers — invalid phone numbers
3. customers — duplicated old_provider_id
4. customers — duplicated email addresses
5. addresses — customer_old_provider_id not found in customers file (orphan addresses)
Usage:
python validate.py --input /path/to/csv/folder
python validate.py --input /path/to/csv/folder --output /path/to/results
"""
import os
import re
import argparse
import pandas as pd
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
EMAIL_REGEX = re.compile(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
PHONE_INVALID_CHARS = re.compile(r"[a-zA-Z\[\]?,]") # letters or clearly wrong chars
PHONE_MAX_LENGTH = 20
def load_csv(path: str) -> pd.DataFrame | None:
"""Load a CSV file; return None if file doesn't exist."""
if not os.path.isfile(path):
return None
df = pd.read_csv(path, encoding="utf-8-sig", low_memory=False)
# Strip BOM from column names
df.columns = df.columns.str.replace(r"^", "", regex=True).str.strip()
return df
def save_result(df: pd.DataFrame, output_dir: str, check_name: str, summary: list[dict]):
"""Save flagged rows to CSV and record summary entry."""
count = len(df)
if count == 0:
summary.append({"check": check_name, "issues_found": 0, "output_file": ""})
return
out_path = os.path.join(output_dir, f"{check_name}.csv")
df.to_csv(out_path, index=False)
summary.append({"check": check_name, "issues_found": count, "output_file": out_path})
print(f" ⚠ {check_name}: {count} issue(s) → {out_path}")
# ---------------------------------------------------------------------------
# Check 1 — Invalid email format
# ---------------------------------------------------------------------------
def check_invalid_emails(customers: pd.DataFrame, output_dir: str, summary: list[dict]):
"""Flag rows where 'email' doesn't match a basic email pattern (nulls excluded)."""
non_null = customers[customers["email"].notna()].copy()
flagged = non_null[~non_null["email"].astype(str).str.match(EMAIL_REGEX)]
save_result(flagged, output_dir, "customers_invalid_email_format", summary)
# ---------------------------------------------------------------------------
# Check 2 — Invalid phone numbers
# ---------------------------------------------------------------------------
def check_invalid_phones(customers: pd.DataFrame, output_dir: str, summary: list[dict]):
"""
Two sub-checks:
a) Phone contains letters or clearly invalid characters.
b) Phone string length exceeds 20 characters.
"""
has_phone = customers[customers["phone"].notna()].copy()
phone_str = has_phone["phone"].astype(str)
# 2a — bad characters
bad_chars = has_phone[phone_str.str.contains(PHONE_INVALID_CHARS)]
save_result(bad_chars, output_dir, "customers_phone_invalid_chars", summary)
# 2b — too long
too_long = has_phone[phone_str.str.len() > PHONE_MAX_LENGTH]
save_result(too_long, output_dir, "customers_phone_too_long", summary)
# ---------------------------------------------------------------------------
# Check 3 — Duplicated old_provider_id
# ---------------------------------------------------------------------------
def check_duplicate_customer_ids(customers: pd.DataFrame, output_dir: str, summary: list[dict]):
"""Flag all rows that share the same old_provider_id (blanks excluded)."""
non_null = customers[customers["old_provider_id"].notna()]
flagged = non_null[non_null["old_provider_id"].duplicated(keep=False)]
save_result(flagged.copy(), output_dir, "customers_duplicate_old_provider_id", summary)
# ---------------------------------------------------------------------------
# Check 4 — Duplicated emails
# ---------------------------------------------------------------------------
def check_duplicate_emails(customers: pd.DataFrame, output_dir: str, summary: list[dict]):
"""Flag all rows where the same email (case-insensitive) appears more than once."""
non_null = customers[customers["email"].notna()].copy()
non_null["_email_lower"] = non_null["email"].str.lower()
flagged = non_null[non_null["_email_lower"].duplicated(keep=False)].drop(columns=["_email_lower"])
save_result(flagged, output_dir, "customers_duplicate_email", summary)
# ---------------------------------------------------------------------------
# Check 5 — Address ↔ Customer relationship
# ---------------------------------------------------------------------------
def check_address_customer_relationship(
addresses: pd.DataFrame,
customers: pd.DataFrame,
output_dir: str,
summary: list[dict],
):
"""Flag addresses whose customer_old_provider_id has no matching customer."""
valid_ids = set(customers["old_provider_id"].dropna().unique())
flagged = addresses[~addresses["customer_old_provider_id"].isin(valid_ids)].copy()
save_result(flagged, output_dir, "addresses_orphan_customer_id", summary)
# ---------------------------------------------------------------------------
# Runner
# ---------------------------------------------------------------------------
def run_validation(input_dir: str, output_dir: str):
os.makedirs(output_dir, exist_ok=True)
summary: list[dict] = []
print(f"\n{'='*60}")
print("Pelcro Validation — POC")
print(f"Input : {input_dir}")
print(f"Output: {output_dir}")
print(f"{'='*60}\n")
# Load files
customers = load_csv(os.path.join(input_dir, "customers.csv"))
addresses = load_csv(os.path.join(input_dir, "addresses.csv"))
if customers is None:
print("ERROR: customers.csv not found — aborting.")
return
print(f"Loaded customers.csv → {len(customers):,} rows")
if addresses is not None:
print(f"Loaded addresses.csv → {len(addresses):,} rows")
print()
# --- Customer checks ---
print("Running customer checks…")
if "email" in customers.columns:
check_invalid_emails(customers, output_dir, summary)
check_duplicate_emails(customers, output_dir, summary)
else:
print(" SKIP: 'email' column not found in customers.csv")
if "phone" in customers.columns:
check_invalid_phones(customers, output_dir, summary)
else:
print(" SKIP: 'phone' column not found in customers.csv")
if "old_provider_id" in customers.columns:
check_duplicate_customer_ids(customers, output_dir, summary)
else:
print(" SKIP: 'old_provider_id' column not found in customers.csv")
# --- Address checks ---
if addresses is not None:
print("\nRunning address checks…")
if "customer_old_provider_id" in addresses.columns and "old_provider_id" in customers.columns:
check_address_customer_relationship(addresses, customers, output_dir, summary)
else:
print(" SKIP: required columns missing for address-customer relationship check")
# --- Summary report ---
print(f"\n{'='*60}")
print("SUMMARY")
print(f"{'='*60}")
summary_df = pd.DataFrame(summary)
print(summary_df.to_string(index=False))
summary_path = os.path.join(output_dir, "validation_summary.csv")
summary_df.to_csv(summary_path, index=False)
print(f"\nSummary saved → {summary_path}\n")
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Pelcro import validation — customers & addresses POC")
parser.add_argument("--input", required=True, help="Directory containing the CSV files")
parser.add_argument(
"--output",
default=None,
help="Directory to write results (default: <input>/validation_results)",
)
args = parser.parse_args()
out = args.output or os.path.join(args.input, "validation_results")
run_validation(args.input, out)