Spaces:
Sleeping
Sleeping
File size: 7,181 Bytes
7d3bfe5 90ebf1e 7d3bfe5 90ebf1e 7d3bfe5 90ebf1e 7d3bfe5 90ebf1e 7d3bfe5 618461c 7d3bfe5 618461c 7d3bfe5 618461c 7d3bfe5 618461c 90ebf1e 7d3bfe5 90ebf1e 7d3bfe5 5f97141 7d3bfe5 |
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 |
import pandas as pd
import asyncio
import math
import json
from datetime import datetime, date
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from passlib.context import CryptContext
from src.core.database import async_session
from src.core.models import Users, Teams, Roles, UserTeamsRole, Assets, AssetStatus
# ---------------------------------------------
# PASSWORD HASHER
# ---------------------------------------------
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
# ---------------------------------------------
# CLEAN NaN / EMPTY VALUES
# ---------------------------------------------
def clean(value):
if value is None:
return None
if isinstance(value, float) and math.isnan(value):
return None
if isinstance(value, str) and value.strip() == "":
return None
return value
# ---------------------------------------------
# NORMALIZE ASSET ID (NEW)
# ---------------------------------------------
def normalize_asset_id(value: str) -> str:
"""Convert messy input to clean format YB-73-M or YB-77-MS"""
if not value:
return None
value = value.strip().replace(" ", "")
value = value.upper()
while "--" in value:
value = value.replace("--", "-")
if "-" not in value:
prefix = value[:2]
number = "".join(filter(str.isdigit, value))
suffix = value[len(prefix) + len(number) :]
return f"{prefix}-{number}-{suffix}"
return value
# ---------------------------------------------
# ASSET TYPE MAP (fallback)
# ---------------------------------------------
ASSET_TYPE_MAP = {
"M": "Monitor",
"L": "Laptop",
"H": "Headphone",
"MS": "Mouse",
}
# ---------------------------------------------
# get_or_create
# ---------------------------------------------
async def get_or_create(session: AsyncSession, model, name: str):
result = await session.exec(select(model).where(model.name == name))
row = result.first()
if row:
return row
row = model(name=name)
session.add(row)
await session.commit()
await session.refresh(row)
return row
# ---------------------------------------------
# PARSE ASSETS JSON
# ---------------------------------------------
def parse_assets_from_excel(raw_value):
if raw_value is None:
return []
raw = str(raw_value).strip()
raw = raw.replace('""', '"')
if raw.startswith('"') and raw.endswith('"'):
raw = raw[1:-1]
try:
parsed = json.loads(raw)
if isinstance(parsed, list):
return parsed
return []
except:
return []
# ---------------------------------------------
# FORMAT JOIN DATE (NEW)
# ---------------------------------------------
def format_join_date(value):
"""Always return YYYY-MM-DD string, no time."""
if value is None:
return None
if isinstance(value, datetime):
return value.date().isoformat() # remove time
if isinstance(value, date):
return value.isoformat()
if isinstance(value, str):
value = value.strip()
# Try standard formats
for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%d-%m-%Y", "%m/%d/%Y"):
try:
d = datetime.strptime(value, fmt).date()
return d.isoformat()
except:
continue
# Fallback: return cleaned string
return value
return str(value)
# ---------------------------------------------
# MAIN IMPORT
# ---------------------------------------------
async def seed_from_excel(session: AsyncSession, excel_path="src/data_add/users.xlsx"):
df = pd.read_excel(excel_path)
print("\n📌 Importing users from Excel...\n")
for _, row in df.iterrows():
# --- DOB ---
raw_dob = clean(row["dob"])
dob = None
if isinstance(raw_dob, str):
try:
dob = datetime.strptime(raw_dob, "%d.%m.%Y").date()
except:
dob = None
elif isinstance(raw_dob, datetime):
dob = raw_dob.date()
else:
dob = raw_dob
# --- JOIN DATE (FIXED) ---
raw_join = clean(row["join_date"])
join_date = format_join_date(raw_join)
# --- CREATE USER ---
user = Users(
email_id=row["email"],
password=hash_password(row["password"]),
user_name=row["User_name"],
dob=dob,
address=clean(row["address"]),
join_date=join_date, # <--- NOW ONLY YYYY-MM-DD
is_verified=True,
)
session.add(user)
await session.commit()
await session.refresh(user)
# --- TEAM / ROLE ---
team = await get_or_create(session, Teams, row["team"])
role = await get_or_create(session, Roles, row["role"])
mapping = UserTeamsRole(
user_id=user.id,
team_id=team.id,
role_id=role.id,
)
session.add(mapping)
# --- ASSETS JSON ---
assets_list = parse_assets_from_excel(clean(row["assets"]))
for asset in assets_list:
raw_id = clean(asset.get("id"))
raw_type = clean(asset.get("type"))
if not raw_id:
continue
# Clean & normalize asset id (your YB-12 format)
asset_id = normalize_asset_id(raw_id)
asset_type = raw_type or "Unknown"
# Skip duplicates (because of unique constraint asset_id + type)
existing = await session.exec(
select(Assets).where(
Assets.asset_id == asset_id, Assets.type == asset_type
)
)
if existing.first():
print(f"⚠ Skipping duplicate asset: {asset_id} ({asset_type})")
continue
# Insert new asset
asset_obj = Assets(
user_id=user.id,
asset_id=asset_id,
type=asset_type,
status=AssetStatus.ACTIVE,
)
session.add(asset_obj)
await session.commit()
print("\n🎉 Excel Import Completed Successfully!\n")
# ---------------------------------------------
# RUN SEEDS
# ---------------------------------------------
async def run_all_seeds():
async with async_session() as session:
print("\n🟦 Seeding TEAMS...")
for t in [
"AI/Tech",
"Shared Services",
"Digital Marketing",
"Bevolve",
"Bridge",
"Quilt",
"HR",
]:
await get_or_create(session, Teams, t)
print("\n🟦 Seeding ROLES...")
for r in ["Mentor", "Team Lead", "HR", "Member"]:
await get_or_create(session, Roles, r)
print("\n🟦 Importing USERS from Excel...")
await seed_from_excel(session, "src/data_add/users.xlsx")
print("\n✔ All seeding complete!\n")
if __name__ == "__main__":
asyncio.run(run_all_seeds())
|