chore: remove root scratch scripts, test runners, alter scripts, and images from repo
This commit is contained in:
parent
ae8162aba3
commit
5b40b38d4f
34 changed files with 51 additions and 2694 deletions
53
.gitignore
vendored
53
.gitignore
vendored
|
|
@ -1,24 +1,73 @@
|
|||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Environment & Secret files
|
||||
.env
|
||||
.env.*
|
||||
jwt_private.pem
|
||||
jwt_public.pem
|
||||
*.pem
|
||||
*.key
|
||||
credentials/
|
||||
reset_admin.py
|
||||
|
||||
# Database files
|
||||
*.db
|
||||
*.sqlite
|
||||
local_ifixkart.db
|
||||
|
||||
# Archives & Uploads
|
||||
*.zip
|
||||
*.tar.gz
|
||||
uploads/
|
||||
migration_data/
|
||||
DATASET/
|
||||
|
||||
# Virtual Environments & IDE
|
||||
venv/
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
*.log
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.log
|
||||
|
||||
# Images & Video Artifacts
|
||||
*.png
|
||||
*.jpg
|
||||
*.jpeg
|
||||
*.webp
|
||||
*.mp4
|
||||
|
||||
# Root Scratch, Alter, Test & One-off DB Scripts
|
||||
add_location.py
|
||||
add_location_raw.py
|
||||
alter_db.py
|
||||
alter_tables.py
|
||||
alter_tables2.py
|
||||
check_user.py
|
||||
cleanup_catalog_showcase.py
|
||||
drop_db.py
|
||||
fix_db.py
|
||||
generate_mock_migration.py
|
||||
generate_super_stress_dataset.py
|
||||
migrate_wallet_db.py
|
||||
populate_cashify_products.py
|
||||
reset_admin.py
|
||||
setup_api_test.py
|
||||
test_convert.py
|
||||
test_credit_flow.py
|
||||
test_credit_storefront_flow.py
|
||||
test_db.py
|
||||
test_db_sync.py
|
||||
test_delivery_cod_rules.py
|
||||
test_get_terminals.py
|
||||
test_notifications.py
|
||||
test_query.py
|
||||
test_quote.py
|
||||
test_sync.py
|
||||
test_warranty_db.py
|
||||
test_warranty_flow.py
|
||||
test_zeptomail.py
|
||||
unlock.py
|
||||
update_cashify_exact_images.py
|
||||
|
|
|
|||
|
|
@ -1,61 +0,0 @@
|
|||
import os
|
||||
import sys
|
||||
|
||||
# Set path and environment variables to allow imports
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
os.environ['PYTHONPATH'] = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
from app.core.database.db_session import engine_crm, SessionLocal
|
||||
from app.models.SystemConfigModel import CrmLocation, Base
|
||||
from sqlalchemy import text
|
||||
|
||||
# Create tables in CRM database just in case
|
||||
# Base.metadata.create_all(bind=engine_crm)
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
# Check if table exists (raw SQL)
|
||||
try:
|
||||
db.execute(text("SELECT 1 FROM crm_locations LIMIT 1"))
|
||||
except Exception as e:
|
||||
print("Table crm_locations does not exist or error:", e)
|
||||
# Create it manually if SQLAlchemy missed it
|
||||
db.execute(text("""
|
||||
CREATE TABLE IF NOT EXISTS crm_locations (
|
||||
location_id VARCHAR(50) PRIMARY KEY,
|
||||
tenant_id VARCHAR(50),
|
||||
code VARCHAR(20),
|
||||
name VARCHAR(100),
|
||||
address VARCHAR(255),
|
||||
city VARCHAR(100),
|
||||
state VARCHAR(100),
|
||||
pincode VARCHAR(20),
|
||||
phone VARCHAR(20),
|
||||
is_active BOOLEAN,
|
||||
is_primary BOOLEAN,
|
||||
created_at DATETIME
|
||||
)
|
||||
"""))
|
||||
db.commit()
|
||||
|
||||
locations = db.query(CrmLocation).all()
|
||||
if not locations:
|
||||
loc1 = CrmLocation(
|
||||
location_id="loc_1",
|
||||
tenant_id="tenant_1",
|
||||
code="HQ01",
|
||||
name="Headquarters",
|
||||
city="Bangalore",
|
||||
is_active=True,
|
||||
is_primary=True
|
||||
)
|
||||
db.add(loc1)
|
||||
db.commit()
|
||||
print("Added default location.")
|
||||
else:
|
||||
print("Locations already exist:", [l.name for l in locations])
|
||||
except Exception as e:
|
||||
print("Error:", e)
|
||||
finally:
|
||||
db.close()
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
import pymysql
|
||||
import datetime
|
||||
import ulid
|
||||
|
||||
conn = pymysql.connect(
|
||||
host='127.0.0.1',
|
||||
user='root',
|
||||
password='NewStrongPassword123!',
|
||||
database='ifixkart_crm'
|
||||
)
|
||||
|
||||
try:
|
||||
with conn.cursor() as cursor:
|
||||
# Create table if not exists
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS crm_locations (
|
||||
location_id VARCHAR(36) PRIMARY KEY,
|
||||
tenant_id VARCHAR(36) NOT NULL DEFAULT 'tenant_default',
|
||||
code VARCHAR(50) NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
address TEXT,
|
||||
city VARCHAR(100),
|
||||
state VARCHAR(100),
|
||||
pincode VARCHAR(20),
|
||||
phone VARCHAR(20),
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
is_primary BOOLEAN DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME ON UPDATE CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
# Check if locations exist
|
||||
cursor.execute("SELECT COUNT(*) FROM crm_locations")
|
||||
count = cursor.fetchone()[0]
|
||||
|
||||
if count == 0:
|
||||
location_id = str(ulid.ULID())
|
||||
cursor.execute("""
|
||||
INSERT INTO crm_locations (location_id, tenant_id, code, name, city, is_active, is_primary)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
""", (location_id, 'tenant_default', 'HQ01', 'Headquarters', 'Bangalore', 1, 1))
|
||||
conn.commit()
|
||||
print("Successfully inserted default location.")
|
||||
else:
|
||||
print(f"Locations already exist. Found {count} location(s).")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
finally:
|
||||
conn.close()
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
from sqlalchemy import create_engine, text
|
||||
|
||||
engine = create_engine("mysql+pymysql://root:NewStrongPassword123!@127.0.0.1:3306/ifixkart_core")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("ALTER TABLE service_jobs MODIFY COLUMN service_type_id VARCHAR(64);"))
|
||||
conn.execute(text("ALTER TABLE service_jobs MODIFY COLUMN repair_service_id VARCHAR(64);"))
|
||||
conn.execute(text("ALTER TABLE service_jobs MODIFY COLUMN repair_variant_id VARCHAR(64);"))
|
||||
|
||||
print("Successfully altered service_jobs columns to VARCHAR(64).")
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.sql import text
|
||||
from app.core.config.Config import settings
|
||||
|
||||
engines = [
|
||||
create_engine(settings.CORE_DATABASE_URL),
|
||||
create_engine(settings.CRM_DATABASE_URL),
|
||||
create_engine(settings.COMMERCE_DATABASE_URL)
|
||||
]
|
||||
|
||||
for engine in engines:
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
try:
|
||||
conn.execute(text("ALTER TABLE service_jobs CHANGE replaced_part_number replaced_part_numbers JSON;"))
|
||||
print("Altered service_jobs in", engine.url)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
try:
|
||||
conn.execute(text("ALTER TABLE order_items ADD COLUMN part_numbers JSON;"))
|
||||
print("Altered order_items in", engine.url)
|
||||
except Exception as e:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
from sqlalchemy import create_engine
|
||||
from app.models.RoleNotificationSettingModel import RoleNotificationSetting
|
||||
from app.core.config.Config import settings
|
||||
|
||||
engines = [
|
||||
create_engine(settings.CORE_DATABASE_URL),
|
||||
create_engine(settings.CRM_DATABASE_URL),
|
||||
create_engine(settings.COMMERCE_DATABASE_URL)
|
||||
]
|
||||
|
||||
for engine in engines:
|
||||
try:
|
||||
RoleNotificationSetting.metadata.create_all(engine)
|
||||
print("Created role_notification_settings in", engine.url)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
from app.core.database.db_session import engine_core
|
||||
from sqlalchemy import text
|
||||
from app.utils.Hash_util import hash_password
|
||||
|
||||
def check():
|
||||
pwd_hash = hash_password('Admin$2026Setup')
|
||||
with engine_core.connect() as conn:
|
||||
conn.execute(text("UPDATE users SET password_hash = :pwd, is_locked = 0, is_active = 1, failed_login_attempts = 0 WHERE email='admin@ifixkart.com'"), {'pwd': pwd_hash})
|
||||
conn.commit()
|
||||
res = conn.execute(text("SELECT user_id, email, is_locked, is_active FROM users WHERE email='admin@ifixkart.com'")).fetchone()
|
||||
print('User:', res)
|
||||
|
||||
if __name__ == '__main__':
|
||||
check()
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
"""
|
||||
Script to purge old dummy mock products and keep only the 40 high-quality Cashify refurbished gadgets.
|
||||
"""
|
||||
import app.models.db_base
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.ProductModel import Product, ProductVariant, ProductImage
|
||||
from app.models.CategoryModel import Category
|
||||
from app.core.database.cache_manager import cache
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
# Archive all old dummy mock products (starting with 'Premium ')
|
||||
dummy_prods = db.query(Product).filter(Product.name.like("Premium %")).all()
|
||||
dummy_count = len(dummy_prods)
|
||||
|
||||
for p in dummy_prods:
|
||||
p.status = "archived"
|
||||
|
||||
db.commit()
|
||||
|
||||
# Ensure all 40 Cashify products have status 'active' and accurate categories
|
||||
active_prods = db.query(Product).filter(Product.name.like("Refurbished %")).all()
|
||||
for p in active_prods:
|
||||
p.status = "active"
|
||||
|
||||
db.commit()
|
||||
|
||||
# Clear cache
|
||||
cache.clear()
|
||||
|
||||
remaining_count = db.query(Product).count()
|
||||
print(f"Purged {dummy_count} old dummy mock products. Total active catalog size: {remaining_count}")
|
||||
|
||||
# Print categories and product counts
|
||||
cats = db.query(Category).all()
|
||||
for c in cats:
|
||||
count = db.query(Product).filter(Product.category_id == c.category_id, Product.status == 'active').count()
|
||||
print(f"Category: {c.name} ({c.slug}) -> {count} active products")
|
||||
|
||||
db.close()
|
||||
25
drop_db.py
25
drop_db.py
|
|
@ -1,25 +0,0 @@
|
|||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.sql import text
|
||||
from app.core.config.Config import settings
|
||||
|
||||
engines = [
|
||||
create_engine(settings.CORE_DATABASE_URL),
|
||||
create_engine(settings.CRM_DATABASE_URL),
|
||||
create_engine(settings.COMMERCE_DATABASE_URL)
|
||||
]
|
||||
|
||||
for engine in engines:
|
||||
with engine.connect() as conn:
|
||||
print(f"Checking DB: {engine.url.database}")
|
||||
tables = [t[0] for t in conn.execute(text('SHOW TABLES;')).fetchall()]
|
||||
if 'notifications' in tables:
|
||||
print("Dropping notification tables...")
|
||||
conn.execute(text("SET FOREIGN_KEY_CHECKS = 0;"))
|
||||
conn.execute(text("DROP TABLE IF EXISTS notification_attempts;"))
|
||||
conn.execute(text("DROP TABLE IF EXISTS dead_letter_queue;"))
|
||||
conn.execute(text("DROP TABLE IF EXISTS whatsapp_sessions;"))
|
||||
conn.execute(text("DROP TABLE IF EXISTS notifications;"))
|
||||
conn.execute(text("SET FOREIGN_KEY_CHECKS = 1;"))
|
||||
conn.commit()
|
||||
print("Dropped successfully.")
|
||||
print('Done!')
|
||||
25
fix_db.py
25
fix_db.py
|
|
@ -1,25 +0,0 @@
|
|||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.sql import text
|
||||
from app.core.config.Config import settings
|
||||
|
||||
engines = [
|
||||
create_engine(settings.CORE_DATABASE_URL),
|
||||
create_engine(settings.CRM_DATABASE_URL),
|
||||
create_engine(settings.COMMERCE_DATABASE_URL)
|
||||
]
|
||||
|
||||
tables_to_drop = ["notification_attempts", "dead_letter_notifications", "whatsapp_sessions", "notifications"]
|
||||
|
||||
for engine in engines:
|
||||
with engine.connect() as conn:
|
||||
try:
|
||||
print(f"Checking DB: {engine.url.database}")
|
||||
for table in tables_to_drop:
|
||||
try:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS {table};'))
|
||||
print(f"Dropped {table}")
|
||||
except Exception as e: print(e)
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
print(f"Error connecting to {engine.url.database}: {e}")
|
||||
print('Done!')
|
||||
|
|
@ -1,345 +0,0 @@
|
|||
import os
|
||||
import zipfile
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
|
||||
def create_mock_png():
|
||||
# 67-byte 1x1 transparent PNG file binary
|
||||
return (
|
||||
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01'
|
||||
b'\x08\x06\x00\x00\x00\x1f\x15c4\x00\x00\x00\rIDATx\x9cc`\x00\x01\x00'
|
||||
b'\x00\xff\xff\x03\x00\x00\x06\x00\x05\x57\xbf\xab\xcc\x00\x00\x00\x00'
|
||||
b'IEND\xaeB`\x82'
|
||||
)
|
||||
|
||||
def main():
|
||||
print("Starting generation of mock migration catalog dataset...")
|
||||
|
||||
# Create target directories
|
||||
output_dir = "migration_data"
|
||||
temp_media_dir = "temp_media_folders"
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(temp_media_dir, exist_ok=True)
|
||||
|
||||
# 1. NEW CATEGORIES DEFINITION
|
||||
# Final 10 categories mapping
|
||||
categories_info = {
|
||||
# Category Name: (Parent Category, Is Parent Feature)
|
||||
"Laptop Accessories": ("", "no"),
|
||||
"Laptop Batteries": ("Laptop Accessories", "no"),
|
||||
"Laptop Keyboards": ("Laptop Accessories", "no"),
|
||||
"Laptop Screen Protectors": ("Laptop Accessories", "no"),
|
||||
"Tablets & iPads": ("", "yes"),
|
||||
"Gaming Accessories": ("", "yes"),
|
||||
"Refurbished Phones": ("", "yes"),
|
||||
"Power Banks": ("", "no"),
|
||||
"USB Cables & Adapters": ("", "no"),
|
||||
"Wireless Chargers": ("", "no"),
|
||||
}
|
||||
|
||||
# 2. BRANDS & PRODUCTS DEFINTION
|
||||
# 4 Brands with multiple device types: lenovo, hp, dell, realme
|
||||
brands_data = {
|
||||
"Lenovo": {
|
||||
"device_types": ["laptop", "tablet", "mobile"],
|
||||
"products": [
|
||||
# (Name, Device Type, Series, Model, Base Price, Category)
|
||||
("Lenovo ThinkPad X1 Carbon", "laptop", "ThinkPad Series", "ThinkPad X1 Carbon Gen 11", 125000, "Laptop Accessories"),
|
||||
("Lenovo IdeaPad Slim 5", "laptop", "IdeaPad Series", "IdeaPad Slim 5 14IRL8", 65000, "Laptop Accessories"),
|
||||
("Lenovo Legion Pro 7i", "laptop", "Legion Series", "Legion Pro 7i Gen 8", 185000, "Laptop Accessories"),
|
||||
("Lenovo Yoga Book 9i", "laptop", "Yoga Series", "Yoga Book 9i Dual Screen", 220000, "Laptop Accessories"),
|
||||
("Lenovo Tab P12 Pro", "tablet", "Tab P Series", "Lenovo Tab P12 Pro Wi-Fi", 45000, "Tablets & iPads"),
|
||||
("Lenovo Tab M10 Plus", "tablet", "Tab M Series", "Lenovo Tab M10 Plus Gen 3", 18000, "Tablets & iPads"),
|
||||
("Lenovo Tab K11", "tablet", "Tab K Series", "Lenovo Tab K11 Pro LTE", 22000, "Tablets & iPads"),
|
||||
("Lenovo Legion Phone Duel 2", "mobile", "Legion Phone Series", "Legion Phone Duel 2 5G", 55000, "Refurbished Phones"),
|
||||
("Lenovo K15 Note", "mobile", "K-Series", "Lenovo K15 Note 4G", 12000, "Refurbished Phones"),
|
||||
("Lenovo Vibe K6", "mobile", "Vibe Series", "Lenovo Vibe K6 Power", 9000, "Refurbished Phones")
|
||||
]
|
||||
},
|
||||
"HP": {
|
||||
"device_types": ["laptop", "tablet"],
|
||||
"products": [
|
||||
("HP Pavilion 15", "laptop", "Pavilion Series", "HP Pavilion 15-eg3000", 58000, "Laptop Accessories"),
|
||||
("HP Envy x360", "laptop", "Envy Series", "HP Envy x360 15-fe0000", 82000, "Laptop Accessories"),
|
||||
("HP Spectre x360", "laptop", "Spectre Series", "HP Spectre x360 14-ef0000", 145000, "Laptop Accessories"),
|
||||
("HP Omen 16", "laptop", "Omen Series", "HP Omen 16-wf0000", 120000, "Laptop Accessories"),
|
||||
("HP EliteBook 840", "laptop", "EliteBook Series", "HP EliteBook 840 G10", 105000, "Laptop Accessories"),
|
||||
("HP Chromebook 14", "laptop", "Chromebook Series", "HP Chromebook 14a-na0000", 25000, "Laptop Accessories"),
|
||||
("HP Elite x2 G8", "tablet", "Elite x2 Series", "HP Elite x2 G8 Tablet", 95000, "Tablets & iPads"),
|
||||
("HP Pro Slate 12", "tablet", "Pro Slate Series", "HP Pro Slate 12 WiFi", 35000, "Tablets & iPads"),
|
||||
("HP Envy x2 Tablet", "tablet", "Envy x2 Series", "HP Envy x2 12-g000", 65000, "Tablets & iPads"),
|
||||
("HP Pro x2 612", "tablet", "Pro x2 Series", "HP Pro x2 612 G2", 48000, "Tablets & iPads")
|
||||
]
|
||||
},
|
||||
"Dell": {
|
||||
"device_types": ["laptop", "tablet"],
|
||||
"products": [
|
||||
("Dell Inspiron 15", "laptop", "Inspiron Series", "Dell Inspiron 15 3530", 52000, "Laptop Accessories"),
|
||||
("Dell XPS 13 Plus", "laptop", "XPS Series", "Dell XPS 13 Plus 9320", 165000, "Laptop Accessories"),
|
||||
("Dell Latitude 5440", "laptop", "Latitude Series", "Dell Latitude 5440 Business", 90000, "Laptop Accessories"),
|
||||
("Dell Precision 5570", "laptop", "Precision Series", "Dell Precision 5570 Mobile Workstation", 210000, "Laptop Accessories"),
|
||||
("Dell Vostro 3520", "laptop", "Vostro Series", "Dell Vostro 3520 15.6", 42000, "Laptop Accessories"),
|
||||
("Dell Alienware m16", "laptop", "Alienware Series", "Alienware m16 R1 Gaming", 240000, "Laptop Accessories"),
|
||||
("Dell Venue 11 Pro", "tablet", "Venue Series", "Dell Venue 11 Pro 7140", 30000, "Tablets & iPads"),
|
||||
("Dell Latitude 7220 Rugged", "tablet", "Latitude Tablet Series", "Dell Latitude 7220 Rugged Extreme", 150000, "Tablets & iPads"),
|
||||
("Dell XPS 12 Tablet", "tablet", "XPS Tablet Series", "Dell XPS 12 9250 2-in-1", 70000, "Tablets & iPads"),
|
||||
("Dell Venue 8 Pro", "tablet", "Venue Series", "Dell Venue 8 Pro 5855", 15000, "Tablets & iPads")
|
||||
]
|
||||
},
|
||||
"Realme": {
|
||||
"device_types": ["mobile", "tablet"],
|
||||
"products": [
|
||||
("Realme GT 6", "mobile", "GT Series", "Realme GT 6 5G", 42000, "Refurbished Phones"),
|
||||
("Realme Narzo 70 Pro", "mobile", "Narzo Series", "Realme Narzo 70 Pro 5G", 22000, "Refurbished Phones"),
|
||||
("Realme C65", "mobile", "C Series", "Realme C65 5G", 11000, "Refurbished Phones"),
|
||||
("Realme 12 Pro Plus", "mobile", "12 Pro Series", "Realme 12 Pro+ 5G", 32000, "Refurbished Phones"),
|
||||
("Realme GT Neo 6", "mobile", "GT Series", "Realme GT Neo 6 SE", 29000, "Refurbished Phones"),
|
||||
("Realme Narzo N53", "mobile", "Narzo Series", "Realme Narzo N53 4G", 9500, "Refurbished Phones"),
|
||||
("Realme Pad 2", "tablet", "Pad Series", "Realme Pad 2 LTE", 20000, "Tablets & iPads"),
|
||||
("Realme Pad Mini", "tablet", "Pad Mini Series", "Realme Pad Mini WiFi", 12000, "Tablets & iPads"),
|
||||
("Realme Pad Slim", "tablet", "Pad Series", "Realme Pad Slim LTE", 16000, "Tablets & iPads"),
|
||||
("Realme Pad Air", "tablet", "Pad Air Series", "Realme Pad Air WiFi", 18000, "Tablets & iPads")
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
# 10 Miscellaneous Category-Specific Products
|
||||
category_products = [
|
||||
# (Name, Brand, Device Type, Series, Model, Base Price, Category)
|
||||
("Lenovo Power Bank 20000mAh", "Lenovo", "mobile", "Vibe Series", "PB-20K", 1800, "Power Banks"),
|
||||
("Realme Power Bank 2", "Realme", "mobile", "C Series", "Realme PB2 10K", 1200, "Power Banks"),
|
||||
("HP USB-C Fast Cable", "HP", "laptop", "Pavilion Series", "HP-CABLE-3A", 650, "USB Cables & Adapters"),
|
||||
("Dell Braided USB-C Cable", "Dell", "laptop", "Inspiron Series", "Dell-BRD-5A", 850, "USB Cables & Adapters"),
|
||||
("Realme Air Wireless Charger", "Realme", "mobile", "GT Series", "Realme WLS-15W", 1999, "Wireless Chargers"),
|
||||
("Lenovo Smart Wireless Pad", "Lenovo", "mobile", "Edge Series", "Lenovo WLS-20W", 2499, "Wireless Chargers"),
|
||||
("HP Replacement Battery Envy", "HP", "laptop", "Enens", "HP-BAT-ENVY", 4500, "Laptop Batteries"),
|
||||
("Dell Replacement Battery XPS", "Dell", "laptop", "XPS Series", "Dell-BAT-XPS13", 5500, "Laptop Batteries"),
|
||||
("Lenovo Stylus Pen Tab", "Lenovo", "tablet", "Tab P Series", "Lenovo Active Pen 3", 3500, "Tablets & iPads"),
|
||||
("Realme Pencil Pro", "Realme", "tablet", "Pad Series", "Realme Pencil 2", 2999, "Tablets & iPads")
|
||||
]
|
||||
|
||||
# Assemble all 50 products list
|
||||
all_products = []
|
||||
|
||||
# 40 Brand-linked products
|
||||
for brand_name, brand_meta in brands_data.items():
|
||||
for p in brand_meta["products"]:
|
||||
all_products.append({
|
||||
"name": p[0],
|
||||
"brand": brand_name,
|
||||
"device_type": p[1],
|
||||
"device_series": p[2],
|
||||
"device_model": p[3],
|
||||
"price": p[4],
|
||||
"category": p[5]
|
||||
})
|
||||
|
||||
# 10 Category-specific products
|
||||
for p in category_products:
|
||||
all_products.append({
|
||||
"name": p[0],
|
||||
"brand": p[1],
|
||||
"device_type": p[2],
|
||||
"device_series": p[3],
|
||||
"device_model": p[4],
|
||||
"price": p[5],
|
||||
"category": p[6]
|
||||
})
|
||||
|
||||
# Prepare Image ZIP package list
|
||||
media_keys_to_zip = []
|
||||
|
||||
# 3. CONSTRUCT 200 ROWS FOR EXCEL
|
||||
excel_rows = []
|
||||
|
||||
# Attribute variants setup
|
||||
color_variants = ["Midnight Black", "Arctic White", "Slate Grey", "Ocean Blue"]
|
||||
storage_variants = ["8GB/128GB", "12GB/256GB", "16GB/512GB", "16GB/1TB"]
|
||||
pack_variants = ["Single Pack", "2-Pack Bundle", "3-Pack Value", "Family 5-Pack"]
|
||||
|
||||
for prod_idx, p in enumerate(all_products):
|
||||
# Media key matching directory name in ZIP
|
||||
media_key = f"{p['brand']}-{p['device_model'].replace(' ', '-').replace('/', '-')}".replace('+', '-Plus')
|
||||
media_keys_to_zip.append(media_key)
|
||||
|
||||
# Product type flag
|
||||
is_accessory = p["category"] in ("Power Banks", "USB Cables & Adapters", "Wireless Chargers", "Laptop Batteries")
|
||||
|
||||
# Build 4 variants for each product
|
||||
for var_idx in range(4):
|
||||
# Price multipliers: Arctic White = +0%, Grey = +5%, Ocean Blue = +10%, Black = +12%
|
||||
# Storage multipliers: 128GB = 1.0, 256GB = 1.15, 512GB = 1.30, 1TB = 1.50
|
||||
price_multiplier = 1.0
|
||||
variant_name = p["name"]
|
||||
sku_suffix = ""
|
||||
|
||||
# Attributes mapping
|
||||
attr_color = color_variants[var_idx]
|
||||
attr_storage = ""
|
||||
attr_pack = ""
|
||||
|
||||
if is_accessory:
|
||||
# Accessories vary by Pack Size
|
||||
attr_pack = pack_variants[var_idx]
|
||||
price_multiplier = [1.0, 1.8, 2.5, 3.8][var_idx]
|
||||
sku_suffix = f"-PK{var_idx+1}"
|
||||
variant_name = f"{p['name']} ({attr_color} - {attr_pack})"
|
||||
else:
|
||||
# Electronics vary by Storage/RAM
|
||||
attr_storage = storage_variants[var_idx]
|
||||
price_multiplier = [1.0, 1.15, 1.30, 1.55][var_idx]
|
||||
sku_suffix = f"-{attr_storage.replace('/', '-')}"
|
||||
variant_name = f"{p['name']} ({attr_color} - {attr_storage})"
|
||||
|
||||
# Final price calculations
|
||||
final_price = round(p["price"] * price_multiplier, 2)
|
||||
|
||||
# Generate clean SKU
|
||||
brand_code = p["brand"][:3].upper()
|
||||
model_code = "".join([w[0] for w in p["device_model"].split() if w]).upper()[:6]
|
||||
color_code = attr_color.split()[-1][:3].upper()
|
||||
sku = f"{brand_code}-{model_code}-{color_code}{sku_suffix}"
|
||||
|
||||
# Category details
|
||||
p_cat = p["category"]
|
||||
parent_cat_info = categories_info.get(p_cat, ("", "no"))
|
||||
parent_category = parent_cat_info[0]
|
||||
is_parent_feature = parent_cat_info[1]
|
||||
|
||||
# Generate barcode (EAN-13 style)
|
||||
barcode = f"890{prod_idx:04d}{var_idx:02d}{final_price:04.0f}"[:13]
|
||||
|
||||
# Generate descriptions
|
||||
description = (
|
||||
f"Premium {p['brand']} {p['device_model']} in elegant {attr_color}. "
|
||||
f"Features cutting-edge specifications, original brand warranty, and genuine parts compatibility."
|
||||
)
|
||||
if attr_pack:
|
||||
description += f" Packed as convenience {attr_pack}."
|
||||
|
||||
# Construct row dictionary
|
||||
row_data = {
|
||||
"sku": sku,
|
||||
"name": variant_name,
|
||||
"parent_name": p["name"],
|
||||
"price": final_price,
|
||||
"stock": 10 + (prod_idx * 3 + var_idx * 5) % 150, # dynamic inventory stock levels
|
||||
"brand": p["brand"],
|
||||
"category": p_cat,
|
||||
"parent_category": parent_category,
|
||||
"is_parent_feature": is_parent_feature,
|
||||
"device_series": p["device_series"],
|
||||
"device_model": p["device_model"],
|
||||
"device_type": p["device_type"],
|
||||
"media_key": media_key,
|
||||
"barcode": barcode,
|
||||
"description": description,
|
||||
"Color Attribute": attr_color,
|
||||
}
|
||||
|
||||
# Set dynamic attributes based on type
|
||||
if attr_storage:
|
||||
row_data["Storage Attribute"] = attr_storage
|
||||
row_data["RAM Attribute"] = attr_storage.split("/")[0]
|
||||
if attr_pack:
|
||||
row_data["Pack Attribute"] = attr_pack
|
||||
|
||||
excel_rows.append(row_data)
|
||||
|
||||
# 4. WRITE EXCEL SHEET USING OPENPYXL
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Unified Catalog Catalog"
|
||||
|
||||
# Define Header list based on union of keys
|
||||
headers = [
|
||||
"sku", "name", "parent_name", "price", "stock", "brand", "category",
|
||||
"parent_category", "is_parent_feature", "device_series", "device_model",
|
||||
"device_type", "media_key", "barcode", "description", "Color Attribute",
|
||||
"Storage Attribute", "RAM Attribute", "Pack Attribute"
|
||||
]
|
||||
|
||||
# Style definitions
|
||||
font_header = Font(name="Segoe UI", size=11, bold=True, color="FFFFFF")
|
||||
font_data = Font(name="Segoe UI", size=10, color="000000")
|
||||
fill_header = PatternFill(start_color="1F2C5C", end_color="1F2C5C", fill_type="solid") # Dark navy matching dashboard theme
|
||||
fill_zebra = PatternFill(start_color="F9FAFB", end_color="F9FAFB", fill_type="solid")
|
||||
|
||||
thin_border = Border(
|
||||
left=Side(style='thin', color='E9EDF4'),
|
||||
right=Side(style='thin', color='E9EDF4'),
|
||||
top=Side(style='thin', color='E9EDF4'),
|
||||
bottom=Side(style='thin', color='E9EDF4')
|
||||
)
|
||||
|
||||
# Write Headers
|
||||
for col_idx, h in enumerate(headers, 1):
|
||||
cell = ws.cell(row=1, column=col_idx, value=h)
|
||||
cell.font = font_header
|
||||
cell.fill = fill_header
|
||||
cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||
cell.border = thin_border
|
||||
|
||||
# Write Rows
|
||||
for row_idx, r_dict in enumerate(excel_rows, 2):
|
||||
is_zebra = (row_idx % 2 == 0)
|
||||
for col_idx, h in enumerate(headers, 1):
|
||||
val = r_dict.get(h, "")
|
||||
cell = ws.cell(row=row_idx, column=col_idx, value=val)
|
||||
cell.font = font_data
|
||||
cell.border = thin_border
|
||||
|
||||
if is_zebra:
|
||||
cell.fill = fill_zebra
|
||||
|
||||
# Formatting and Alignment
|
||||
if h in ("price", "stock"):
|
||||
cell.alignment = Alignment(horizontal="right", vertical="center")
|
||||
if h == "price":
|
||||
cell.number_format = '₹#,##0.00'
|
||||
else:
|
||||
cell.number_format = '#,##0'
|
||||
else:
|
||||
cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||
|
||||
# Set row heights
|
||||
ws.row_dimensions[1].height = 28
|
||||
for r in range(2, len(excel_rows) + 2):
|
||||
ws.row_dimensions[r].height = 20
|
||||
|
||||
# Auto fit column widths
|
||||
for col in ws.columns:
|
||||
max_len = max(len(str(cell.value or '')) for cell in col)
|
||||
col_letter = openpyxl.utils.get_column_letter(col[0].column)
|
||||
ws.column_dimensions[col_letter].width = max(max_len + 3, 12)
|
||||
|
||||
# Save workbook
|
||||
excel_path = os.path.join(output_dir, "catalog_import.xlsx")
|
||||
wb.save(excel_path)
|
||||
print(f"Created Excel import sheet at: {excel_path} (200 rows, 19 columns)")
|
||||
|
||||
# 5. CREATE IMAGES AND ZIP ARCHIVE
|
||||
png_data = create_mock_png()
|
||||
zip_path = os.path.join(output_dir, "media_images.zip")
|
||||
|
||||
print("Packing media images ZIP (4 mock JPEGs per product)...")
|
||||
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
||||
for m_key in media_keys_to_zip:
|
||||
# We add front, back, side, box images for each product key
|
||||
for img_name in ["front.jpg", "back.jpg", "side.jpg", "box.jpg"]:
|
||||
# File path in ZIP: e.g. "Lenovo-ThinkPad-X1-Carbon/front.jpg"
|
||||
zip_filename = f"{m_key}/{img_name}"
|
||||
# Write the 1x1 PNG data under JPEG extensions directly (browsers render valid PNGs with JPG extensions anyway)
|
||||
zipf.writestr(zip_filename, png_data)
|
||||
|
||||
print(f"Created Media ZIP package at: {zip_path} (50 folders, 200 files)")
|
||||
|
||||
# Cleanup temporary folders if any
|
||||
if os.path.exists(temp_media_dir):
|
||||
import shutil
|
||||
shutil.rmtree(temp_media_dir)
|
||||
|
||||
print("Successfully generated all mock migration catalog data!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,308 +0,0 @@
|
|||
import os
|
||||
import io
|
||||
import csv
|
||||
import zipfile
|
||||
import random
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill, Alignment
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
WORKSPACE = "/mnt/fam/SERVER/IfixKartEcommerce"
|
||||
UPLOAD_DIR = os.path.join(WORKSPACE, "uploads", "migrations")
|
||||
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||
|
||||
print("🚀 Starting Ultra Stress Dataset Generator (Option B: Variant-Level High Cardinality)...")
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# 1. TAXONOMY & EXPANDED MASTER DATA ARRAYS
|
||||
# -------------------------------------------------------------
|
||||
BRANDS = [
|
||||
("Apple", "https://images.unsplash.com/photo-1611186871348-b1ce696e52c9"),
|
||||
("Samsung", "https://images.unsplash.com/photo-1610945265064-0e34e5519bbf"),
|
||||
("Google Pixel", "https://images.unsplash.com/photo-1598327105666-5b89351aff97"),
|
||||
("OnePlus", "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9"),
|
||||
("Xiaomi", "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9"),
|
||||
("Oppo", "https://images.unsplash.com/photo-1580910051074-3eb694886505"),
|
||||
("Vivo", "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9"),
|
||||
("Realme", "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9"),
|
||||
("Asus", "https://images.unsplash.com/photo-1603302576837-37561b2e2302"),
|
||||
("Motorola", "https://images.unsplash.com/photo-1525609004556-c46c7d6cf0a3"),
|
||||
("Nothing", "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe"),
|
||||
("Dell", "https://images.unsplash.com/photo-1588872657578-7efd1f1555ed"),
|
||||
("HP", "https://images.unsplash.com/photo-1589561084283-930aa7b1ce50"),
|
||||
("Lenovo", "https://images.unsplash.com/photo-1588872657578-7efd1f1555ed")
|
||||
]
|
||||
|
||||
CATEGORIES = [
|
||||
("Mobile Accessories", "Screen Guards", "TRUE", "https://images.unsplash.com/photo-1601784551446"),
|
||||
("Mobile Accessories", "Back Covers", "TRUE", "https://images.unsplash.com/photo-1603302576837"),
|
||||
("Mobile Accessories", "Camera Lens Guards", "TRUE", "https://images.unsplash.com/photo-1616440347437"),
|
||||
("Mobile Accessories", "Charging Cables", "FALSE", "https://images.unsplash.com/photo-1611532736597"),
|
||||
("Mobile Accessories", "Wireless Chargers", "FALSE", "https://images.unsplash.com/photo-1628144547837"),
|
||||
("Repair Parts", "Mobile Display", "FALSE", "https://images.unsplash.com/photo-1580910051074"),
|
||||
("Repair Parts", "Mobile Battery", "FALSE", "https://images.unsplash.com/photo-1622445262465"),
|
||||
("Repair Parts", "Mother Board", "FALSE", "https://images.unsplash.com/photo-1518770660439"),
|
||||
("Repair Parts", "Charging Port Flex", "FALSE", "https://images.unsplash.com/photo-1611532736597"),
|
||||
("Repair Parts", "Camera Module", "FALSE", "https://images.unsplash.com/photo-1516035069371"),
|
||||
("Laptop Accessories", "Laptop Battery", "FALSE", "https://images.unsplash.com/photo-1622445262465"),
|
||||
("Laptop Accessories", "Keyboard Assembly", "FALSE", "https://images.unsplash.com/photo-1587829741301"),
|
||||
("Laptop Accessories", "Screen Replacement", "FALSE", "https://images.unsplash.com/photo-1580910051074"),
|
||||
("Laptop Accessories", "Type-C Docking Station", "TRUE", "https://images.unsplash.com/photo-1628144547837"),
|
||||
("Wearable Accessories", "Smartwatch Straps", "TRUE", "https://images.unsplash.com/photo-1508685096489"),
|
||||
("Wearable Accessories", "Screen Guards", "TRUE", "https://images.unsplash.com/photo-1601784551446"),
|
||||
("Wearable Accessories", "Charging Docks", "FALSE", "https://images.unsplash.com/photo-1628144547837")
|
||||
]
|
||||
|
||||
DEVICES_MAP = {
|
||||
"Apple": [
|
||||
("Mobile", "iPhone 15 Series", ["iPhone 15 Pro Max", "iPhone 15 Pro", "iPhone 15 Plus", "iPhone 15"]),
|
||||
("Mobile", "iPhone 14 Series", ["iPhone 14 Pro Max", "iPhone 14 Pro", "iPhone 14 Plus", "iPhone 14"]),
|
||||
("Mobile", "iPhone 13 Series", ["iPhone 13 Pro Max", "iPhone 13 Pro", "iPhone 13 Mini", "iPhone 13"]),
|
||||
("Tablet", "iPad Pro Series", ["iPad Pro 12.9 M2", "iPad Pro 11 M2", "iPad Air 5", "iPad Mini 6"]),
|
||||
("Laptop", "MacBook Pro M-Series", ["MacBook Pro 16 M3 Max", "MacBook Pro 14 M3", "MacBook Air 15 M2", "MacBook Air 13 M2"]),
|
||||
("Smartwatch", "Apple Watch Series", ["Apple Watch Ultra 2", "Apple Watch Series 9", "Apple Watch Series 8", "Apple Watch SE 2"])
|
||||
],
|
||||
"Samsung": [
|
||||
("Mobile", "Galaxy S Series", ["Galaxy S24 Ultra", "Galaxy S24+", "Galaxy S24", "Galaxy S23 Ultra", "Galaxy S23+", "Galaxy S23"]),
|
||||
("Mobile", "Galaxy Z Series", ["Galaxy Z Fold 5", "Galaxy Z Flip 5", "Galaxy Z Fold 4", "Galaxy Z Flip 4"]),
|
||||
("Mobile", "Galaxy A Series", ["Galaxy A55 5G", "Galaxy A35 5G", "Galaxy A54 5G"]),
|
||||
("Tablet", "Galaxy Tab S Series", ["Galaxy Tab S9 Ultra", "Galaxy Tab S9+", "Galaxy Tab S9 FE"]),
|
||||
("Smartwatch", "Galaxy Watch Series", ["Galaxy Watch 6 Classic", "Galaxy Watch 6", "Galaxy Watch 5 Pro"])
|
||||
],
|
||||
"Google Pixel": [
|
||||
("Mobile", "Pixel Series", ["Pixel 8 Pro", "Pixel 8", "Pixel 7a", "Pixel 7 Pro", "Pixel 7", "Pixel Fold"]),
|
||||
("Smartwatch", "Pixel Watch", ["Pixel Watch 2", "Pixel Watch 1"])
|
||||
],
|
||||
"OnePlus": [
|
||||
("Mobile", "OnePlus Number Series", ["OnePlus 12", "OnePlus 12R", "OnePlus 11", "OnePlus 10 Pro"]),
|
||||
("Mobile", "OnePlus Nord Series", ["OnePlus Nord 4", "OnePlus Nord CE 4"]),
|
||||
("Tablet", "OnePlus Pad", ["OnePlus Pad 2", "OnePlus Pad Go"])
|
||||
],
|
||||
"Xiaomi": [
|
||||
("Mobile", "Xiaomi Flagship Series", ["Xiaomi 14 Ultra", "Xiaomi 14", "Xiaomi 13T Pro"]),
|
||||
("Mobile", "Redmi Note Series", ["Redmi Note 13 Pro+", "Redmi Note 13 Pro", "Redmi Note 12 Pro"])
|
||||
],
|
||||
"Oppo": [
|
||||
("Mobile", "Oppo Find Series", ["Oppo Find N3 Flip", "Oppo Find X6 Pro", "Oppo Reno 11 Pro"])
|
||||
],
|
||||
"Vivo": [
|
||||
("Mobile", "Vivo X Series", ["Vivo X100 Pro", "Vivo X100", "Vivo V30 Pro", "Vivo V29 5G"])
|
||||
],
|
||||
"Realme": [
|
||||
("Mobile", "Realme GT Series", ["Realme GT 5 Pro", "Realme 12 Pro+", "Realme 12 Pro"])
|
||||
],
|
||||
"Asus": [
|
||||
("Mobile", "ROG Phone Series", ["ROG Phone 8 Pro", "ROG Phone 7 Ultimate", "Zenfone 10"])
|
||||
],
|
||||
"Motorola": [
|
||||
("Mobile", "Razr Series", ["Razr 40 Ultra", "Edge 50 Ultra", "Edge 40 Pro"])
|
||||
],
|
||||
"Nothing": [
|
||||
("Mobile", "Nothing Phone Series", ["Nothing Phone 2", "Nothing Phone 2a", "Nothing Phone 1"])
|
||||
],
|
||||
"Dell": [
|
||||
("Laptop", "Dell XPS Series", ["Dell XPS 15 9530", "Dell XPS 13 Plus", "Dell Latitude 7440", "Dell Inspiron 16"])
|
||||
],
|
||||
"Lenovo": [
|
||||
("Laptop", "ThinkPad X1 Series", ["ThinkPad X1 Carbon Gen 11", "ThinkPad X1 Yoga Gen 8", "ThinkPad T14s Gen 4", "Legion Pro 7i"])
|
||||
],
|
||||
"HP": [
|
||||
("Laptop", "HP Spectre Series", ["HP Spectre x360 16", "HP Envy x360 15", "HP Omen 16", "HP Pavilion 15"])
|
||||
]
|
||||
}
|
||||
|
||||
COLORS = ["Space Black", "Natural Titanium", "Phantom Black", "Glacial Blue", "Matte Black", "Clear Transparent", "Navy Blue", "Emerald Green", "Sunset Gold", "Silver", "Alpine White", "Titanium Gray"]
|
||||
STORAGES = ["128GB", "256GB", "512GB", "1TB", "2TB", "N/A"]
|
||||
RAMS = ["8GB", "12GB", "16GB", "32GB", "64GB", "N/A"]
|
||||
MATERIALS = ["9H Tempered Glass", "TPU + Polycarbonate", "Lithium-Ion Polymer", "OLED Panel", "Aluminum Alloy", "Silicone Rubber", "Fluorocarbon Leather"]
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# 2. GENERATE SPREADSHEET ROWS & VARIANT-LEVEL MEDIA KEYS
|
||||
# Target: 2,000+ Parents, 5,500+ Variant Rows, 5,500+ Media Keys (16,500+ Images)
|
||||
# -------------------------------------------------------------
|
||||
wb = openpyxl.Workbook()
|
||||
|
||||
header_fill = PatternFill(start_color="0F172A", end_color="0F172A", fill_type="solid")
|
||||
header_font = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
||||
|
||||
section_fill = PatternFill(start_color="334155", end_color="334155", fill_type="solid")
|
||||
section_font = Font(name="Calibri", size=10, bold=True, color="F8FAFC")
|
||||
|
||||
# Sheet 1: Products_and_Variants
|
||||
ws1 = wb.active
|
||||
ws1.title = "Products_and_Variants"
|
||||
ws1.views.sheetView[0].showGridLines = True
|
||||
|
||||
headers_products = [
|
||||
"sku", "parent_name", "parent_media_key", "name", "brand", "parent_category", "category",
|
||||
"is_parent_feature", "device_type", "device_series", "device_model",
|
||||
"price", "cost_price", "stock", "color", "storage", "ram", "material",
|
||||
"warranty_months", "media_key", "barcode", "is_active", "description"
|
||||
]
|
||||
ws1.append(headers_products)
|
||||
|
||||
products_rows = []
|
||||
variant_media_keys = {} # key -> list of 3 (filename, description)
|
||||
|
||||
sku_counter = 100000
|
||||
parent_count = 0
|
||||
|
||||
for brand_name, logo_url in BRANDS:
|
||||
dev_series_list = DEVICES_MAP.get(brand_name, [("Mobile", f"{brand_name} Series", [f"{brand_name} Flagship Pro"])])
|
||||
|
||||
for dev_type, series_name, models_list in dev_series_list:
|
||||
for model_name in models_list:
|
||||
for parent_cat, sub_cat, is_feat, cat_icon in CATEGORIES:
|
||||
parent_count += 1
|
||||
|
||||
# Base Parent Product Title
|
||||
parent_title = f"{brand_name} {model_name} {sub_cat}"
|
||||
parent_key = f"{brand_name}_{model_name}_{sub_cat}".lower().replace(" ", "_").replace("+", "plus").replace("/", "_")
|
||||
|
||||
# Create 3 distinct variants per parent product to hit ~5,500+ variant rows
|
||||
for v_idx in range(3):
|
||||
sku_counter += 1
|
||||
sku = f"IFK-{brand_name[:3].upper()}-{sku_counter}"
|
||||
color = COLORS[(sku_counter + v_idx) % len(COLORS)]
|
||||
storage = STORAGES[(sku_counter + v_idx) % len(STORAGES)]
|
||||
ram = RAMS[(sku_counter + v_idx) % len(RAMS)]
|
||||
material = MATERIALS[(sku_counter + v_idx) % len(MATERIALS)]
|
||||
|
||||
variant_title = f"{color} - {storage} ({material})"
|
||||
|
||||
# Option B: Variant-Level Media Key
|
||||
variant_media_key = f"{parent_key}_var{v_idx + 1}_{color}".lower().replace(" ", "_")
|
||||
|
||||
# Exactly 3 Images per Variant Key
|
||||
variant_media_keys[variant_media_key] = [
|
||||
("1_variant_front.png", f"Front view of {variant_title}"),
|
||||
("2_variant_back.png", f"Back view of {variant_title}"),
|
||||
("3_variant_detail.png", f"Close-up detail view of {variant_title}")
|
||||
]
|
||||
|
||||
price = float(random.randint(499, 14999))
|
||||
cost_price = float(round(price * 0.42, 2))
|
||||
stock = random.randint(20, 500)
|
||||
barcode = f"890{sku_counter:010d}"
|
||||
warranty = random.choice([3, 6, 12, 24])
|
||||
desc = f"High precision {parent_title} variant in {color} finish. Compatible with {brand_name} {model_name}."
|
||||
|
||||
products_rows.append([
|
||||
sku, parent_title, parent_key, variant_title, brand_name, parent_cat, sub_cat,
|
||||
is_feat, dev_type, series_name, model_name,
|
||||
price, cost_price, stock, color, storage, ram, material,
|
||||
warranty, variant_media_key, barcode, "TRUE", desc
|
||||
])
|
||||
|
||||
for row in products_rows:
|
||||
ws1.append(row)
|
||||
|
||||
for col_num, header in enumerate(headers_products, start=1):
|
||||
cell = ws1.cell(row=1, column=col_num)
|
||||
cell.fill = header_fill
|
||||
cell.font = header_font
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
|
||||
# Sheet 2: Master_Categories_and_Brands
|
||||
ws2 = wb.create_sheet(title="Brands_and_Categories")
|
||||
ws2.views.sheetView[0].showGridLines = True
|
||||
|
||||
headers_brands_cats = ["brand_name", "brand_logo_url", "parent_category", "category_name", "category_icon_url"]
|
||||
ws2.append(headers_brands_cats)
|
||||
|
||||
for b_name, b_logo in BRANDS:
|
||||
for p_cat, s_cat, feat, c_icon in CATEGORIES:
|
||||
ws2.append([b_name, b_logo, p_cat, s_cat, c_icon])
|
||||
|
||||
for col_num, header in enumerate(headers_brands_cats, start=1):
|
||||
cell = ws2.cell(row=1, column=col_num)
|
||||
cell.fill = section_fill
|
||||
cell.font = section_font
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
|
||||
# Sheet 3: Device_Catalog_and_Services
|
||||
ws3 = wb.create_sheet(title="Device_Catalog_and_Services")
|
||||
ws3.views.sheetView[0].showGridLines = True
|
||||
|
||||
headers_services = [
|
||||
"brand", "device_type", "series_name", "model_name", "release_year",
|
||||
"service_type", "repair_service", "variant_name", "service_price",
|
||||
"service_cost", "warranty_days", "duration_minutes"
|
||||
]
|
||||
ws3.append(headers_services)
|
||||
|
||||
for b_name, _ in BRANDS:
|
||||
dev_list = DEVICES_MAP.get(b_name, [("Mobile", f"{b_name} Series", [f"{b_name} Pro"])])
|
||||
for d_type, s_name, m_list in dev_list:
|
||||
for m_name in m_list:
|
||||
ws3.append([b_name, d_type, s_name, m_name, 2024, "Screen Replacement", f"{m_name} Display Assembly Repair", "Original Super Retina OLED", 11999.00, 6800.00, 180, 45])
|
||||
ws3.append([b_name, d_type, s_name, m_name, 2024, "Battery Replacement", f"{m_name} Battery Fix", "OEM Li-Polymer Pack", 2999.00, 1200.00, 90, 30])
|
||||
|
||||
for col_num, header in enumerate(headers_services, start=1):
|
||||
cell = ws3.cell(row=1, column=col_num)
|
||||
cell.fill = section_fill
|
||||
cell.font = section_font
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
|
||||
# Auto-adjust column widths
|
||||
for sheet in [ws1, ws2, ws3]:
|
||||
for col in sheet.columns:
|
||||
max_len = max(len(str(cell.value or '')) for cell in col)
|
||||
col_letter = get_column_letter(col[0].column)
|
||||
sheet.column_dimensions[col_letter].width = max(max_len + 3, 12)
|
||||
|
||||
# Save Excel File
|
||||
excel_file_path = os.path.join(UPLOAD_DIR, "iFixKart_Super_Stress_Import_Catalog.xlsx")
|
||||
wb.save(excel_file_path)
|
||||
print(f"✅ Excel Ultra Stress Catalog created ({parent_count} Parent Products, {len(products_rows)} Variant Rows) at: {excel_file_path}")
|
||||
|
||||
# Save CSV File
|
||||
csv_file_path = os.path.join(UPLOAD_DIR, "iFixKart_Super_Stress_Import_Catalog.csv")
|
||||
with open(csv_file_path, "w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerow(headers_products)
|
||||
writer.writerows(products_rows)
|
||||
print(f"✅ CSV Ultra Stress Catalog created ({len(products_rows)} Variant Rows) at: {csv_file_path}")
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# 3. GENERATE MEDIA ZIP ARCHIVE WITH 16,500+ IMAGES (3 PER VARIANT KEY)
|
||||
# -------------------------------------------------------------
|
||||
zip_file_path = os.path.join(UPLOAD_DIR, "iFixKart_Super_Stress_Media_Archive.zip")
|
||||
|
||||
total_image_count = len(variant_media_keys) * 3
|
||||
|
||||
# Valid 1x1 PNG byte stub
|
||||
sample_png_bytes = (
|
||||
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01'
|
||||
b'\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\xcf\xc0'
|
||||
b'\x00\x00\x03\x01\x01\x00\x18\xdd\x8d\xb0\x00\x00\x00\x00IEND\xaeB`\x82'
|
||||
)
|
||||
|
||||
readme_content = f"""iFixKart Ultra Stress Load Media Archive Manifest (Option B Variant-Level):
|
||||
=============================================================================
|
||||
Total Parent Base Products: {parent_count}
|
||||
Total Variant Rows / Media Keys: {len(variant_media_keys)}
|
||||
Images per Variant Media Key: Exactly 3 Images
|
||||
Total Image Assets in Archive: {total_image_count}
|
||||
|
||||
Folder Structure:
|
||||
-----------------
|
||||
{{variant_media_key}}/
|
||||
├── 1_variant_front.png
|
||||
├── 2_variant_back.png
|
||||
└── 3_variant_detail.png
|
||||
"""
|
||||
|
||||
print(f"Creating Ultra Stress Media ZIP Archive with {total_image_count} image assets across {len(variant_media_keys)} variant keys...")
|
||||
|
||||
with zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("README.txt", readme_content)
|
||||
for m_key, img_list in variant_media_keys.items():
|
||||
for filename, _desc in img_list:
|
||||
zip_entry_path = f"{m_key}/{filename}"
|
||||
zf.writestr(zip_entry_path, sample_png_bytes)
|
||||
|
||||
zip_size_mb = os.path.getsize(zip_file_path) / (1024 * 1024)
|
||||
print(f"✅ Media ZIP Archive created ({total_image_count} images across {len(variant_media_keys)} keys, {zip_size_mb:.2f} MB) at: {zip_file_path}")
|
||||
|
||||
print("\n🎉 Ultra Stress Dataset (Option B: 5,500+ Variant Rows & 16,500+ Images) built successfully!")
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnvRRhqCtxmEEhHRcuaWd
|
||||
PZGduuFrl+t8BO7Iz3XO/G27Cx4kiTPJT3SoMTUrxfoPb8i/YUvppKPRrFPrNxLt
|
||||
oKYRzlbFa2lhjFD5hn18rvliKvL8lJ1QKDdmoW2R7lhpYCp49fib/mtCVONfzv7f
|
||||
mkThYd+J6RmW0GQQ1m/t+YPzn0CNrDjswlzPYcwBBL6iZCLtIl4VsMlhjZ3nzyVQ
|
||||
bKeoAz4F3JUAYpJOMlut3Tj/r3KiDpj/uO4Nds68e4drMg0bYm54Gv9lCNtBlzJf
|
||||
bqvbnuHKBwakw+XqkCxRLEh1pEgwRPjfCmkBPaOBfNaqApQCXU6lKdMa8LiAcWzu
|
||||
JwIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
import ulid
|
||||
from sqlalchemy import select
|
||||
import app.models.db_base
|
||||
from app.core.database.db_session import engine_commerce, SessionLocal, Base
|
||||
from app.models.WalletModel import CustomerWallet, WalletTransaction
|
||||
from app.models.SettingModel import Setting
|
||||
|
||||
def run_migration():
|
||||
print("Creating wallet tables in Commerce DB...")
|
||||
Base.metadata.create_all(bind=engine_commerce, tables=[CustomerWallet.__table__, WalletTransaction.__table__])
|
||||
print("Wallet tables created/verified.")
|
||||
|
||||
print("Seeding/Verifying credit settings...")
|
||||
db = SessionLocal()
|
||||
try:
|
||||
credit_settings = [
|
||||
{
|
||||
"setting_key": "credits_enabled",
|
||||
"setting_value": {"value": True},
|
||||
"description": "Master switch to enable/disable store credit rewards",
|
||||
"is_public": True,
|
||||
},
|
||||
{
|
||||
"setting_key": "credits_sales_percentage",
|
||||
"setting_value": {"value": 5.0},
|
||||
"description": "Store credit percentage earned on e-commerce sales orders",
|
||||
"is_public": True,
|
||||
},
|
||||
{
|
||||
"setting_key": "credits_sales_return_window_days",
|
||||
"setting_value": {"value": 7},
|
||||
"description": "Return window period in days before sales credit matures",
|
||||
"is_public": True,
|
||||
},
|
||||
{
|
||||
"setting_key": "credits_service_percentage",
|
||||
"setting_value": {"value": 5.0},
|
||||
"description": "Store credit percentage earned on completed repair service jobs",
|
||||
"is_public": True,
|
||||
},
|
||||
{
|
||||
"setting_key": "credits_service_claim_window_days",
|
||||
"setting_value": {"value": 3},
|
||||
"description": "Return/dispute window period in days before service credit matures",
|
||||
"is_public": True,
|
||||
},
|
||||
{
|
||||
"setting_key": "credits_minimum_order_value",
|
||||
"setting_value": {"value": 0.0},
|
||||
"description": "Minimum order/invoice amount required to earn credit",
|
||||
"is_public": True,
|
||||
},
|
||||
{
|
||||
"setting_key": "credits_expiry_days",
|
||||
"setting_value": {"value": 365},
|
||||
"description": "Days before matured credits expire (0 for no expiration)",
|
||||
"is_public": True,
|
||||
},
|
||||
]
|
||||
|
||||
for s in credit_settings:
|
||||
existing = db.execute(
|
||||
select(Setting).where(Setting.setting_key == s["setting_key"])
|
||||
).scalar_one_or_none()
|
||||
if not existing:
|
||||
db.add(Setting(
|
||||
setting_id=str(ulid.ULID()),
|
||||
setting_key=s["setting_key"],
|
||||
group="credits",
|
||||
type="json",
|
||||
setting_value=s["setting_value"],
|
||||
description=s["description"],
|
||||
is_public=s["is_public"],
|
||||
))
|
||||
print(f" + Added Setting: {s['setting_key']}")
|
||||
else:
|
||||
print(f" = Setting exists: {s['setting_key']}")
|
||||
db.commit()
|
||||
print("Credit settings successfully synchronized.")
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
print(f"Error during credit settings synchronization: {e}")
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_migration()
|
||||
|
|
@ -1,644 +0,0 @@
|
|||
"""
|
||||
Script to populate 40 Cashify refurbished products with variants, images, prices in INR into PostgreSQL DB.
|
||||
"""
|
||||
import ulid
|
||||
import re
|
||||
from decimal import Decimal
|
||||
import app.models.db_base
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.ProductModel import Product, ProductVariant, ProductImage
|
||||
from app.models.BrandModel import Brand
|
||||
from app.models.CategoryModel import Category
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
# Ensure brands
|
||||
brand_names = ["Apple", "Samsung", "OnePlus", "Xiaomi", "Google", "Sony", "Dell", "Bose"]
|
||||
brand_map = {}
|
||||
for name in brand_names:
|
||||
slug = name.lower()
|
||||
b = db.query(Brand).filter(Brand.slug == slug).first()
|
||||
if not b:
|
||||
b = Brand(
|
||||
brand_id=str(ulid.ULID()),
|
||||
name=name,
|
||||
slug=slug,
|
||||
is_active=True
|
||||
)
|
||||
db.add(b)
|
||||
db.commit()
|
||||
db.refresh(b)
|
||||
brand_map[name] = b.brand_id
|
||||
|
||||
# Ensure categories
|
||||
cat_names = {
|
||||
"Smartphones": "smartphones",
|
||||
"Laptops": "laptops",
|
||||
"Tablets": "tablets",
|
||||
"Gaming Consoles": "gaming-consoles",
|
||||
"Audio & Headphones": "audio-headphones",
|
||||
"Smartwatches": "smartwatches"
|
||||
}
|
||||
cat_map = {}
|
||||
for name, slug in cat_names.items():
|
||||
c = db.query(Category).filter(Category.slug == slug).first()
|
||||
if not c:
|
||||
c = Category(
|
||||
category_id=str(ulid.ULID()),
|
||||
name=name,
|
||||
slug=slug,
|
||||
is_active=True
|
||||
)
|
||||
db.add(c)
|
||||
db.commit()
|
||||
db.refresh(c)
|
||||
cat_map[name] = c.category_id
|
||||
|
||||
# 40 Products Data
|
||||
PRODUCTS_DATA = [
|
||||
# iPhones
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 15 Pro Max",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 94999,
|
||||
"compare_price": 159900,
|
||||
"image": "https://images.unsplash.com/photo-1695048133142-1a20484d2569?w=800",
|
||||
"specs": "256GB Storage • Titanium Body • A17 Pro Chip • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH15PM-256-NT", "title": "256GB / Natural Titanium", "price": 94999, "compare_price": 159900, "stock": 15},
|
||||
{"sku": "IPH15PM-512-BT", "title": "512GB / Black Titanium", "price": 112999, "compare_price": 179900, "stock": 10},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 15 Pro",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 84999,
|
||||
"compare_price": 134900,
|
||||
"image": "https://images.unsplash.com/photo-1695048133142-1a20484d2569?w=800",
|
||||
"specs": "128GB Storage • Action Button • A17 Pro Chip • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH15P-128-WT", "title": "128GB / White Titanium", "price": 84999, "compare_price": 134900, "stock": 18},
|
||||
{"sku": "IPH15P-256-BT", "title": "256GB / Black Titanium", "price": 93999, "compare_price": 144900, "stock": 12},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 15",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 56999,
|
||||
"compare_price": 79900,
|
||||
"image": "https://images.unsplash.com/photo-1592750475338-74b7b21085ab?w=800",
|
||||
"specs": "128GB Storage • Dynamic Island • 48MP Camera • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH15-128-BLK", "title": "128GB / Black", "price": 56999, "compare_price": 79900, "stock": 25},
|
||||
{"sku": "IPH15-256-BLU", "title": "256GB / Blue", "price": 64999, "compare_price": 89900, "stock": 15},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 14 Pro Max",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 74999,
|
||||
"compare_price": 139900,
|
||||
"image": "https://images.unsplash.com/photo-1663499482523-1c0c1bae4ce1?w=800",
|
||||
"specs": "128GB Storage • Dynamic Island • A16 Bionic • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH14PM-128-PUR", "title": "128GB / Deep Purple", "price": 74999, "compare_price": 139900, "stock": 20},
|
||||
{"sku": "IPH14PM-256-BLK", "title": "256GB / Space Black", "price": 82999, "compare_price": 149900, "stock": 14},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 14 Pro",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 66999,
|
||||
"compare_price": 129900,
|
||||
"image": "https://images.unsplash.com/photo-1663499482523-1c0c1bae4ce1?w=800",
|
||||
"specs": "128GB Storage • 120Hz ProMotion • Dynamic Island • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH14P-128-PUR", "title": "128GB / Deep Purple", "price": 66999, "compare_price": 129900, "stock": 22},
|
||||
{"sku": "IPH14P-256-GLD", "title": "256GB / Gold", "price": 73999, "compare_price": 139900, "stock": 10},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 14",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 44999,
|
||||
"compare_price": 69900,
|
||||
"image": "https://images.unsplash.com/photo-1663499482523-1c0c1bae4ce1?w=800",
|
||||
"specs": "128GB Storage • Photonic Engine • Crash Detection • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH14-128-MID", "title": "128GB / Midnight", "price": 44999, "compare_price": 69900, "stock": 30},
|
||||
{"sku": "IPH14-256-BLU", "title": "256GB / Blue", "price": 52999, "compare_price": 79900, "stock": 18},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 13 Pro Max",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 59999,
|
||||
"compare_price": 129900,
|
||||
"image": "https://images.unsplash.com/photo-1632661674596-df8be070a5c5?w=800",
|
||||
"specs": "128GB Storage • ProMotion 120Hz • A15 Bionic • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH13PM-128-SBLU", "title": "128GB / Sierra Blue", "price": 59999, "compare_price": 129900, "stock": 16},
|
||||
{"sku": "IPH13PM-256-GRP", "title": "256GB / Graphite", "price": 66999, "compare_price": 139900, "stock": 11},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 13",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 38999,
|
||||
"compare_price": 59900,
|
||||
"image": "https://images.unsplash.com/photo-1632661674596-df8be070a5c5?w=800",
|
||||
"specs": "128GB Storage • Cinematic Mode • All-Day Battery • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH13-128-MID", "title": "128GB / Midnight", "price": 38999, "compare_price": 59900, "stock": 40},
|
||||
{"sku": "IPH13-256-STR", "title": "256GB / Starlight", "price": 45999, "compare_price": 69900, "stock": 25},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 12 Pro Max",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 46999,
|
||||
"compare_price": 119900,
|
||||
"image": "https://images.unsplash.com/photo-1605236453806-6ff36851218e?w=800",
|
||||
"specs": "128GB Storage • Ceramic Shield • LiDAR Scanner • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH12PM-128-PBLU", "title": "128GB / Pacific Blue", "price": 46999, "compare_price": 119900, "stock": 14},
|
||||
{"sku": "IPH12PM-256-GRP", "title": "256GB / Graphite", "price": 52999, "compare_price": 129900, "stock": 9},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 12",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 28999,
|
||||
"compare_price": 49900,
|
||||
"image": "https://images.unsplash.com/photo-1605236453806-6ff36851218e?w=800",
|
||||
"specs": "64GB Storage • Super Retina XDR • MagSafe • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH12-64-BLK", "title": "64GB / Black", "price": 28999, "compare_price": 49900, "stock": 35},
|
||||
{"sku": "IPH12-128-BLU", "title": "128GB / Blue", "price": 33999, "compare_price": 54900, "stock": 20},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone 11",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 19999,
|
||||
"compare_price": 43900,
|
||||
"image": "https://images.unsplash.com/photo-1574944985070-8f3ebc6b79d2?w=800",
|
||||
"specs": "64GB Storage • Dual 12MP Ultra Wide • Night Mode • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPH11-64-BLK", "title": "64GB / Black", "price": 19999, "compare_price": 43900, "stock": 50},
|
||||
{"sku": "IPH11-128-WHT", "title": "128GB / White", "price": 23999, "compare_price": 48900, "stock": 30},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPhone SE (2022)",
|
||||
"brand": "Apple",
|
||||
"category": "Smartphones",
|
||||
"price": 18499,
|
||||
"compare_price": 43900,
|
||||
"image": "https://images.unsplash.com/photo-1574944985070-8f3ebc6b79d2?w=800",
|
||||
"specs": "64GB Storage • A15 Bionic • 5G Speed • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPHSE3-64-MID", "title": "64GB / Midnight", "price": 18499, "compare_price": 43900, "stock": 22},
|
||||
{"sku": "IPHSE3-128-STR", "title": "128GB / Starlight", "price": 21999, "compare_price": 48900, "stock": 15},
|
||||
]
|
||||
},
|
||||
|
||||
# Samsung Phones
|
||||
{
|
||||
"name": "Refurbished Samsung Galaxy S24 Ultra 5G",
|
||||
"brand": "Samsung",
|
||||
"category": "Smartphones",
|
||||
"price": 89999,
|
||||
"compare_price": 129999,
|
||||
"image": "https://images.unsplash.com/photo-1610945265064-0e34e5519bbf?w=800",
|
||||
"specs": "256GB / 12GB RAM • Galaxy AI • 200MP Quad Camera • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "SGS24U-256-TBLK", "title": "256GB / Titanium Black", "price": 89999, "compare_price": 129999, "stock": 12},
|
||||
{"sku": "SGS24U-512-TGRAY", "title": "512GB / Titanium Gray", "price": 99999, "compare_price": 139999, "stock": 8},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Samsung Galaxy S23 Ultra 5G",
|
||||
"brand": "Samsung",
|
||||
"category": "Smartphones",
|
||||
"price": 64999,
|
||||
"compare_price": 124999,
|
||||
"image": "https://images.unsplash.com/photo-1610945265064-0e34e5519bbf?w=800",
|
||||
"specs": "256GB / 12GB RAM • S Pen Included • Snapdragon 8 Gen 2 • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "SGS23U-256-BLK", "title": "256GB / Phantom Black", "price": 64999, "compare_price": 124999, "stock": 18},
|
||||
{"sku": "SGS23U-512-GRN", "title": "512GB / Green", "price": 72999, "compare_price": 134999, "stock": 10},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Samsung Galaxy S23 5G",
|
||||
"brand": "Samsung",
|
||||
"category": "Smartphones",
|
||||
"price": 38999,
|
||||
"compare_price": 74999,
|
||||
"image": "https://images.unsplash.com/photo-1610945265064-0e34e5519bbf?w=800",
|
||||
"specs": "128GB / 8GB RAM • Dynamic AMOLED 2X • Nightography • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "SGS23-128-BLK", "title": "128GB / Phantom Black", "price": 38999, "compare_price": 74999, "stock": 25},
|
||||
{"sku": "SGS23-256-GRN", "title": "256GB / Green", "price": 43999, "compare_price": 79999, "stock": 15},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Samsung Galaxy S22 Ultra 5G",
|
||||
"brand": "Samsung",
|
||||
"category": "Smartphones",
|
||||
"price": 44999,
|
||||
"compare_price": 109999,
|
||||
"image": "https://images.unsplash.com/photo-1610945265064-0e34e5519bbf?w=800",
|
||||
"specs": "128GB / 12GB RAM • Built-in S Pen • 108MP Pro Camera • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "SGS22U-128-BUR", "title": "128GB / Burgundy", "price": 44999, "compare_price": 109999, "stock": 14},
|
||||
{"sku": "SGS22U-256-BLK", "title": "256GB / Phantom Black", "price": 49999, "compare_price": 119999, "stock": 9},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Samsung Galaxy Z Fold 5 5G",
|
||||
"brand": "Samsung",
|
||||
"category": "Smartphones",
|
||||
"price": 82999,
|
||||
"compare_price": 154999,
|
||||
"image": "https://images.unsplash.com/photo-1580910051074-3eb694886505?w=800",
|
||||
"specs": "256GB / 12GB RAM • 7.6\" Foldable Display • Flex Hinge • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "SGZF5-256-BLK", "title": "256GB / Phantom Black", "price": 82999, "compare_price": 154999, "stock": 8},
|
||||
{"sku": "SGZF5-512-BLU", "title": "512GB / Icy Blue", "price": 92999, "compare_price": 164999, "stock": 5},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Samsung Galaxy Z Flip 5 5G",
|
||||
"brand": "Samsung",
|
||||
"category": "Smartphones",
|
||||
"price": 49999,
|
||||
"compare_price": 99999,
|
||||
"image": "https://images.unsplash.com/photo-1580910051074-3eb694886505?w=800",
|
||||
"specs": "256GB / 8GB RAM • 3.4\" Flex Window • Compact Pocketable • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "SGZFP5-256-MNT", "title": "256GB / Mint", "price": 49999, "compare_price": 99999, "stock": 15},
|
||||
{"sku": "SGZFP5-512-GRA", "title": "512GB / Graphite", "price": 57999, "compare_price": 109999, "stock": 8},
|
||||
]
|
||||
},
|
||||
|
||||
# OnePlus Phones
|
||||
{
|
||||
"name": "Refurbished OnePlus 12 5G",
|
||||
"brand": "OnePlus",
|
||||
"category": "Smartphones",
|
||||
"price": 52999,
|
||||
"compare_price": 64999,
|
||||
"image": "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=800",
|
||||
"specs": "256GB / 12GB RAM • Snapdragon 8 Gen 3 • 4th Gen Hasselblad • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "OP12-256-GRN", "title": "256GB / Flowy Emerald", "price": 52999, "compare_price": 64999, "stock": 16},
|
||||
{"sku": "OP12-512-BLK", "title": "512GB / Silky Black", "price": 59999, "compare_price": 69999, "stock": 10},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished OnePlus 11 5G",
|
||||
"brand": "OnePlus",
|
||||
"category": "Smartphones",
|
||||
"price": 36999,
|
||||
"compare_price": 56999,
|
||||
"image": "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=800",
|
||||
"specs": "128GB / 8GB RAM • 100W SUPERVOOC • Hasselblad Camera • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "OP11-128-BLK", "title": "128GB / Titan Black", "price": 36999, "compare_price": 56999, "stock": 20},
|
||||
{"sku": "OP11-256-GRN", "title": "256GB / Eternal Green", "price": 41999, "compare_price": 61999, "stock": 14},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished OnePlus 11R 5G",
|
||||
"brand": "OnePlus",
|
||||
"category": "Smartphones",
|
||||
"price": 26999,
|
||||
"compare_price": 39999,
|
||||
"image": "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=800",
|
||||
"specs": "128GB / 8GB RAM • Snapdragon 8+ Gen 1 • 120Hz Fluid AMOLED • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "OP11R-128-BLK", "title": "128GB / Sonic Black", "price": 26999, "compare_price": 39999, "stock": 30},
|
||||
{"sku": "OP11R-256-SLV", "title": "256GB / Galactic Silver", "price": 30999, "compare_price": 44999, "stock": 18},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished OnePlus Nord 3 5G",
|
||||
"brand": "OnePlus",
|
||||
"category": "Smartphones",
|
||||
"price": 18999,
|
||||
"compare_price": 33999,
|
||||
"image": "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=800",
|
||||
"specs": "128GB / 8GB RAM • MediaTek Dimensity 9000 • 50MP Sony IMX890 • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "OPN3-128-GRN", "title": "128GB / Misty Green", "price": 18999, "compare_price": 33999, "stock": 25},
|
||||
{"sku": "OPN3-256-GRY", "title": "256GB / Tempest Gray", "price": 21999, "compare_price": 37999, "stock": 15},
|
||||
]
|
||||
},
|
||||
|
||||
# Google Pixels
|
||||
{
|
||||
"name": "Refurbished Google Pixel 8 Pro",
|
||||
"brand": "Google",
|
||||
"category": "Smartphones",
|
||||
"price": 58999,
|
||||
"compare_price": 106999,
|
||||
"image": "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=800",
|
||||
"specs": "128GB / 12GB RAM • Google Tensor G3 • Temperature Sensor • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "GPX8P-128-OBS", "title": "128GB / Obsidian", "price": 58999, "compare_price": 106999, "stock": 14},
|
||||
{"sku": "GPX8P-256-BAY", "title": "256GB / Bay Blue", "price": 65999, "compare_price": 113999, "stock": 9},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Google Pixel 8",
|
||||
"brand": "Google",
|
||||
"category": "Smartphones",
|
||||
"price": 41999,
|
||||
"compare_price": 75999,
|
||||
"image": "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=800",
|
||||
"specs": "128GB / 8GB RAM • Actua Display • Best Take AI • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "GPX8-128-HZL", "title": "128GB / Hazel", "price": 41999, "compare_price": 75999, "stock": 20},
|
||||
{"sku": "GPX8-256-OBS", "title": "256GB / Obsidian", "price": 47999, "compare_price": 82999, "stock": 12},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Google Pixel 7a",
|
||||
"brand": "Google",
|
||||
"category": "Smartphones",
|
||||
"price": 23999,
|
||||
"compare_price": 43999,
|
||||
"image": "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=800",
|
||||
"specs": "128GB / 8GB RAM • Google Tensor G2 • Wireless Charging • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "GPX7A-128-CHA", "title": "128GB / Charcoal", "price": 23999, "compare_price": 43999, "stock": 28},
|
||||
{"sku": "GPX7A-128-SEA", "title": "128GB / Sea", "price": 23999, "compare_price": 43999, "stock": 15},
|
||||
]
|
||||
},
|
||||
|
||||
# Xiaomi / Poco
|
||||
{
|
||||
"name": "Refurbished Xiaomi 13 Pro 5G",
|
||||
"brand": "Xiaomi",
|
||||
"category": "Smartphones",
|
||||
"price": 44999,
|
||||
"compare_price": 79999,
|
||||
"image": "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?w=800",
|
||||
"specs": "256GB / 12GB RAM • Leica 1-inch Camera • Snapdragon 8 Gen 2 • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "MI13P-256-CBLK", "title": "256GB / Ceramic Black", "price": 44999, "compare_price": 79999, "stock": 10},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Redmi Note 13 Pro+ 5G",
|
||||
"brand": "Xiaomi",
|
||||
"category": "Smartphones",
|
||||
"price": 21999,
|
||||
"compare_price": 31999,
|
||||
"image": "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?w=800",
|
||||
"specs": "256GB / 8GB RAM • 200MP OIS Camera • 120W HyperCharge • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "RN13PP-256-PUR", "title": "256GB / Fusion Purple", "price": 21999, "compare_price": 31999, "stock": 35},
|
||||
{"sku": "RN13PP-512-BLK", "title": "512GB / Fusion Black", "price": 25999, "compare_price": 35999, "stock": 20},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished POCO F5 5G",
|
||||
"brand": "Xiaomi",
|
||||
"category": "Smartphones",
|
||||
"price": 18999,
|
||||
"compare_price": 29999,
|
||||
"image": "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?w=800",
|
||||
"specs": "256GB / 8GB RAM • Snapdragon 7+ Gen 2 • 120Hz AMOLED • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "POCOF5-256-BLK", "title": "256GB / Carbon Black", "price": 18999, "compare_price": 29999, "stock": 22},
|
||||
]
|
||||
},
|
||||
|
||||
# Tablets & Laptops
|
||||
{
|
||||
"name": "Refurbished Apple iPad Pro 12.9\" M2 (6th Gen)",
|
||||
"brand": "Apple",
|
||||
"category": "Tablets",
|
||||
"price": 78999,
|
||||
"compare_price": 112900,
|
||||
"image": "https://images.unsplash.com/photo-1544244015-0df4b3ffc6b0?w=800",
|
||||
"specs": "128GB Wi-Fi • M2 Chip • Liquid Retina XDR • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPADP6-128-GRY", "title": "128GB / Space Gray", "price": 78999, "compare_price": 112900, "stock": 10},
|
||||
{"sku": "IPADP6-256-SLV", "title": "256GB / Silver", "price": 86999, "compare_price": 122900, "stock": 6},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPad Air M1 (5th Gen)",
|
||||
"brand": "Apple",
|
||||
"category": "Tablets",
|
||||
"price": 41999,
|
||||
"compare_price": 59900,
|
||||
"image": "https://images.unsplash.com/photo-1544244015-0df4b3ffc6b0?w=800",
|
||||
"specs": "64GB Wi-Fi • Apple M1 Chip • 10.9\" Liquid Retina • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPADA5-64-GRY", "title": "64GB / Space Gray", "price": 41999, "compare_price": 59900, "stock": 18},
|
||||
{"sku": "IPADA5-256-BLU", "title": "256GB / Blue", "price": 53999, "compare_price": 74900, "stock": 10},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple iPad 10th Gen 10.9\"",
|
||||
"brand": "Apple",
|
||||
"category": "Tablets",
|
||||
"price": 27999,
|
||||
"compare_price": 44900,
|
||||
"image": "https://images.unsplash.com/photo-1544244015-0df4b3ffc6b0?w=800",
|
||||
"specs": "64GB Wi-Fi • A14 Bionic • All-Screen Design • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "IPAD10-64-BLU", "title": "64GB / Blue", "price": 27999, "compare_price": 44900, "stock": 25},
|
||||
{"sku": "IPAD10-256-SLV", "title": "256GB / Silver", "price": 38999, "compare_price": 59900, "stock": 14},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple MacBook Air M2 13.6\"",
|
||||
"brand": "Apple",
|
||||
"category": "Laptops",
|
||||
"price": 74999,
|
||||
"compare_price": 119900,
|
||||
"image": "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=800",
|
||||
"specs": "8GB RAM / 256GB SSD • M2 8-core CPU • Liquid Retina • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "MBA-M2-256-MID", "title": "8GB/256GB / Midnight", "price": 74999, "compare_price": 119900, "stock": 12},
|
||||
{"sku": "MBA-M2-512-STR", "title": "16GB/512GB / Starlight", "price": 94999, "compare_price": 139900, "stock": 8},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple MacBook Air M1 13.3\"",
|
||||
"brand": "Apple",
|
||||
"category": "Laptops",
|
||||
"price": 51999,
|
||||
"compare_price": 99900,
|
||||
"image": "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=800",
|
||||
"specs": "8GB RAM / 256GB SSD • M1 8-core CPU • Silent Fanless • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "MBA-M1-256-GRY", "title": "8GB/256GB / Space Gray", "price": 51999, "compare_price": 99900, "stock": 20},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple MacBook Pro M2 Pro 14\"",
|
||||
"brand": "Apple",
|
||||
"category": "Laptops",
|
||||
"price": 118999,
|
||||
"compare_price": 199900,
|
||||
"image": "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=800",
|
||||
"specs": "16GB RAM / 512GB SSD • M2 Pro 10-core CPU • Liquid Retina XDR • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "MBP14-M2P-512", "title": "16GB/512GB / Space Gray", "price": 118999, "compare_price": 199900, "stock": 5},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Dell XPS 13 Core i7 11th Gen",
|
||||
"brand": "Dell",
|
||||
"category": "Laptops",
|
||||
"price": 48999,
|
||||
"compare_price": 124900,
|
||||
"image": "https://images.unsplash.com/photo-1593642632823-8f785ba67e45?w=800",
|
||||
"specs": "16GB RAM / 512GB NVMe SSD • Core i7-1165G7 • FHD+ Touch • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "DELLXPS13-512", "title": "16GB/512GB / Platinum Silver", "price": 48999, "compare_price": 124900, "stock": 14},
|
||||
]
|
||||
},
|
||||
|
||||
# Consoles & Audio
|
||||
{
|
||||
"name": "Refurbished Sony PlayStation 5 Disc Edition",
|
||||
"brand": "Sony",
|
||||
"category": "Gaming Consoles",
|
||||
"price": 39999,
|
||||
"compare_price": 54990,
|
||||
"image": "https://images.unsplash.com/photo-1606813907291-d86efa9b94db?w=800",
|
||||
"specs": "825GB Ultra-High Speed SSD • DualSense Controller • 4K 120Hz Gaming • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "PS5-DISC-825", "title": "825GB SSD / White", "price": 39999, "compare_price": 54990, "stock": 15},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Sony WH-1000XM5 Noise Canceling Headphones",
|
||||
"brand": "Sony",
|
||||
"category": "Audio & Headphones",
|
||||
"price": 19999,
|
||||
"compare_price": 34990,
|
||||
"image": "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=800",
|
||||
"specs": "Auto NC Optimizer • 30-Hour Battery Life • Crystal Clear Hands-Free • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "SONYXM5-BLK", "title": "Black / ANC Over-Ear", "price": 19999, "compare_price": 34990, "stock": 25},
|
||||
{"sku": "SONYXM5-SLV", "title": "Silver / ANC Over-Ear", "price": 19999, "compare_price": 34990, "stock": 15},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Bose QuietComfort 45 Headphones",
|
||||
"brand": "Bose",
|
||||
"category": "Audio & Headphones",
|
||||
"price": 17999,
|
||||
"compare_price": 29900,
|
||||
"image": "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=800",
|
||||
"specs": "Quiet & Aware Modes • High-Fidelity Audio • 24-Hour Battery • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "BOSEQC45-BLK", "title": "Triple Black", "price": 17999, "compare_price": 29900, "stock": 18},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple AirPods Pro (2nd Generation)",
|
||||
"brand": "Apple",
|
||||
"category": "Audio & Headphones",
|
||||
"price": 14999,
|
||||
"compare_price": 26900,
|
||||
"image": "https://images.unsplash.com/photo-1600294037681-c80b4cb5b434?w=800",
|
||||
"specs": "H2 Chip • 2x Active Noise Cancellation • Adaptive Audio • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "AIRPODSPRO2", "title": "MagSafe Case (USB-C)", "price": 14999, "compare_price": 26900, "stock": 40},
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refurbished Apple Watch Series 9 GPS 45mm",
|
||||
"brand": "Apple",
|
||||
"category": "Smartwatches",
|
||||
"price": 29999,
|
||||
"compare_price": 44900,
|
||||
"image": "https://images.unsplash.com/photo-1508685096489-7aacd43bd3b1?w=800",
|
||||
"specs": "45mm Aluminum Case • Double Tap Gesture • S9 SiP • Refurbished Superb",
|
||||
"variants": [
|
||||
{"sku": "APW9-45-MID", "title": "45mm / Midnight", "price": 29999, "compare_price": 44900, "stock": 20},
|
||||
{"sku": "APW9-45-STR", "title": "45mm / Starlight", "price": 29999, "compare_price": 44900, "stock": 12},
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
print(f"Processing {len(PRODUCTS_DATA)} Cashify refurbished products...")
|
||||
|
||||
inserted_count = 0
|
||||
for item in PRODUCTS_DATA:
|
||||
slug = re.sub(r'[^a-z0-9]+', '-', item["name"].lower()).strip('-')
|
||||
|
||||
# Check if exists
|
||||
existing = db.query(Product).filter(Product.slug == slug).first()
|
||||
if existing:
|
||||
prod = existing
|
||||
else:
|
||||
prod_id = str(ulid.ULID())
|
||||
brand_id = brand_map.get(item["brand"])
|
||||
cat_id = cat_map.get(item["category"])
|
||||
|
||||
prod = Product(
|
||||
product_id=prod_id,
|
||||
name=item["name"],
|
||||
slug=slug,
|
||||
full_path=f"/products/{slug}",
|
||||
brand_id=brand_id,
|
||||
category_id=cat_id,
|
||||
description=f"### {item['name']}\n\n**Key Specs**: {item['specs']}\n\nAll iFixKart refurbished gadgets undergo a 32-point quality check, include a 6-month warranty, free shipping, and guaranteed battery health >= 85%.",
|
||||
status="active"
|
||||
)
|
||||
db.add(prod)
|
||||
db.commit()
|
||||
db.refresh(prod)
|
||||
inserted_count += 1
|
||||
|
||||
# Primary Image
|
||||
p_img = ProductImage(
|
||||
image_id=str(ulid.ULID()),
|
||||
product_id=prod.product_id,
|
||||
image_url=item["image"],
|
||||
alt_text=item["name"],
|
||||
sort_order=1
|
||||
)
|
||||
db.add(p_img)
|
||||
db.commit()
|
||||
|
||||
# Variants
|
||||
for var_data in item["variants"]:
|
||||
var_existing = db.query(ProductVariant).filter(ProductVariant.sku == var_data["sku"]).first()
|
||||
if not var_existing:
|
||||
pv = ProductVariant(
|
||||
variant_id=str(ulid.ULID()),
|
||||
product_id=prod.product_id,
|
||||
sku=var_data["sku"],
|
||||
price=Decimal(str(var_data["price"])),
|
||||
compare_price=Decimal(str(var_data["compare_price"])),
|
||||
cost_price=Decimal(str(int(var_data["price"] * 0.7))),
|
||||
status="active"
|
||||
)
|
||||
db.add(pv)
|
||||
db.commit()
|
||||
|
||||
print(f"Successfully populated {inserted_count} new Cashify products into DB! Total catalog size: {db.query(Product).count()}")
|
||||
db.close()
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
import sys
|
||||
import os
|
||||
import ulid
|
||||
import requests
|
||||
import json
|
||||
|
||||
sys.path.insert(0, os.path.abspath('/mnt/fam/SERVER/IfixKartEcommerce/Backend'))
|
||||
from app.models.db_base import *
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.ProductModel import Product, ProductVariant
|
||||
from app.models.UserModel import User
|
||||
from app.core.Token import create_access_token
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
admin = db.query(User).filter(User.role_id == "ROLE_ADMIN").first()
|
||||
if not admin:
|
||||
admin = db.query(User).first() # Just grab any user to test
|
||||
|
||||
if not admin:
|
||||
print("NO USER FOUND IN DB")
|
||||
sys.exit(1)
|
||||
|
||||
token = create_access_token(user_id=admin.user_id, email=admin.email, role="ROLE_ADMIN")
|
||||
|
||||
# 1. Get Product Variant
|
||||
variant = db.query(ProductVariant).first()
|
||||
if not variant:
|
||||
product = Product(
|
||||
product_id=str(ulid.ULID()),
|
||||
tenant_id="tenant_default",
|
||||
name="Test API Product",
|
||||
slug="test-api-product",
|
||||
description="Test",
|
||||
category_id=None,
|
||||
status="ACTIVE"
|
||||
)
|
||||
db.add(product)
|
||||
|
||||
variant = ProductVariant(
|
||||
variant_id=str(ulid.ULID()),
|
||||
product_id=product.product_id,
|
||||
sku="TEST-SKU-API",
|
||||
price=100.0,
|
||||
stock_quantity=10,
|
||||
attributes_json="{}"
|
||||
)
|
||||
db.add(variant)
|
||||
db.commit()
|
||||
|
||||
variant_id = variant.variant_id
|
||||
db.close()
|
||||
|
||||
print(f"VARIANT_ID: {variant_id}")
|
||||
|
||||
# 2. Create Order via API
|
||||
API_BASE = "http://localhost:8000/api/v1"
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
payload = {
|
||||
"customer_name": "API Test User",
|
||||
"customer_email": "apitest@ifixkart.com",
|
||||
"customer_phone": "9080323589",
|
||||
"items": [
|
||||
{
|
||||
"variant_id": variant_id,
|
||||
"quantity": 1,
|
||||
"unit_price": 100.0
|
||||
}
|
||||
],
|
||||
"payment_status": "PAID",
|
||||
"payment_method": "CASH",
|
||||
"notification_channel": "NONE"
|
||||
}
|
||||
|
||||
print("Creating Order...")
|
||||
res = requests.post(f"{API_BASE}/admin/orders/create", json=payload, headers=headers)
|
||||
print("Create Order Status:", res.status_code)
|
||||
if res.status_code != 200:
|
||||
print(res.text)
|
||||
sys.exit(1)
|
||||
|
||||
order_data = res.json()
|
||||
order_id = order_data["order_id"]
|
||||
print(f"Order created: {order_id}")
|
||||
|
||||
# 3. Change Status to DELIVERED
|
||||
print("Updating Order Status to DELIVERED...")
|
||||
status_payload = {
|
||||
"status": "DELIVERED"
|
||||
}
|
||||
res2 = requests.put(f"{API_BASE}/admin/orders/{order_id}/status", json=status_payload, headers=headers)
|
||||
print("Update Status:", res2.status_code)
|
||||
if res2.status_code != 200:
|
||||
print(res2.text)
|
||||
sys.exit(1)
|
||||
|
||||
# 4. Fetch Warranties
|
||||
print("Fetching Warranties...")
|
||||
res3 = requests.get(f"{API_BASE}/warranties/", headers=headers)
|
||||
print("Warranties Status:", res3.status_code)
|
||||
if res3.status_code != 200:
|
||||
print(res3.text)
|
||||
sys.exit(1)
|
||||
warranties = res3.json()
|
||||
print(f"Found {len(warranties)} warranties")
|
||||
|
||||
for w in warranties:
|
||||
if w["reference_id"] == order_id:
|
||||
print("SUCCESS! Warranty found for the order.")
|
||||
print("Warranty Details:", json.dumps(w, indent=2))
|
||||
sys.exit(0)
|
||||
|
||||
print("FAILURE: No warranty found for the order.")
|
||||
sys.exit(1)
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import requests
|
||||
|
||||
payload = {
|
||||
"category": "BOTH",
|
||||
"deal_title": "Sales Quote - 5626",
|
||||
"estimated_value": 18054.0,
|
||||
"customer_phone": "+91 22",
|
||||
"customer_name": "5626"
|
||||
}
|
||||
|
||||
# The lead_id doesn't matter much if it fails validation, it will return 422 before 404
|
||||
res = requests.post("http://localhost:8000/api/v1/crm/leads/dummy_lead_id/convert", json=payload)
|
||||
print(res.status_code)
|
||||
print(res.text)
|
||||
|
|
@ -1,187 +0,0 @@
|
|||
import sys
|
||||
import ulid
|
||||
from decimal import Decimal
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import app.models.db_base
|
||||
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.EcomCustomerModel import EcomCustomer
|
||||
from app.models.OrderModel import Order
|
||||
from app.models.ServiceModel import ServiceJob
|
||||
from app.models.WalletModel import CustomerWallet, WalletTransaction
|
||||
from app.services.CreditService import CreditService
|
||||
|
||||
def run_tests():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
print("=== Test 1: Settings Retrieval & Dynamic Update ===")
|
||||
settings = CreditService.get_credit_settings(db)
|
||||
print("Initial Settings:", settings)
|
||||
assert "credits_sales_percentage" in settings
|
||||
assert "credits_sales_return_window_days" in settings
|
||||
assert "credits_service_percentage" in settings
|
||||
assert "credits_service_claim_window_days" in settings
|
||||
print("✓ Initial settings verified.")
|
||||
|
||||
# Dynamically update settings to 5% sales, 7 days return, 5% service, 3 days claim
|
||||
CreditService.update_credit_settings(db, {
|
||||
"credits_sales_percentage": 5.0,
|
||||
"credits_sales_return_window_days": 7,
|
||||
"credits_service_percentage": 5.0,
|
||||
"credits_service_claim_window_days": 3
|
||||
})
|
||||
updated_settings = CreditService.get_credit_settings(db)
|
||||
assert updated_settings["credits_sales_percentage"] == 5.0
|
||||
assert updated_settings["credits_sales_return_window_days"] == 7
|
||||
assert updated_settings["credits_service_percentage"] == 5.0
|
||||
assert updated_settings["credits_service_claim_window_days"] == 3
|
||||
print("✓ Settings dynamic update verified.")
|
||||
|
||||
print("\n=== Test 2: Create Test Customer & Wallet ===")
|
||||
import time
|
||||
test_email = f"test_credit_cust_{ulid.ULID()}@ifixkart.com"
|
||||
customer = EcomCustomer(
|
||||
customer_id=str(ulid.ULID()),
|
||||
email=test_email,
|
||||
first_name="Test",
|
||||
last_name="CreditUser",
|
||||
phone=f"99{str(int(time.time() * 1000))[-8:]}"
|
||||
)
|
||||
db.add(customer)
|
||||
db.commit()
|
||||
|
||||
wallet = CreditService.get_or_create_wallet(db, customer.customer_id)
|
||||
assert wallet.active_balance == Decimal("0.00")
|
||||
assert wallet.pending_balance == Decimal("0.00")
|
||||
print("✓ Customer and Wallet initialized successfully.")
|
||||
|
||||
print("\n=== Test 3: Sales Order Completion -> Pending Credit ===")
|
||||
# Create an Order with final amount ₹2000
|
||||
order = Order(
|
||||
order_id=str(ulid.ULID()),
|
||||
order_no=f"ORD-TEST-{str(ulid.ULID())}",
|
||||
customer_id=customer.customer_id,
|
||||
total_amount=Decimal("2000.00"),
|
||||
final_amount=Decimal("2000.00"),
|
||||
status="ORDER_CREATED",
|
||||
payment_status="PAYMENT_CAPTURED"
|
||||
)
|
||||
db.add(order)
|
||||
db.commit()
|
||||
|
||||
# Simulate Order Marked DELIVERED
|
||||
order.status = "DELIVERED"
|
||||
db.commit()
|
||||
tx = CreditService.create_pending_credit_for_order(db, order.order_id)
|
||||
|
||||
assert tx is not None
|
||||
assert tx.status == "PENDING"
|
||||
# 5% of 2000 = 100.00
|
||||
assert tx.credit_amount == Decimal("100.00")
|
||||
assert tx.reference_type == "ORDER"
|
||||
assert tx.reference_id == order.order_id
|
||||
|
||||
# Verify pending balance incremented on customer wallet
|
||||
db.refresh(wallet)
|
||||
assert wallet.pending_balance == Decimal("100.00")
|
||||
assert wallet.active_balance == Decimal("0.00")
|
||||
print(f"✓ Pending credit created: ₹{tx.credit_amount} (5% of ₹2000), matures_at: {tx.matures_at}")
|
||||
print(f"✓ Wallet: Pending=₹{wallet.pending_balance}, Active=₹{wallet.active_balance}")
|
||||
|
||||
print("\n=== Test 4: Maturity Sweep (Simulate Return Window Passing) ===")
|
||||
# Backdate matures_at to 1 hour in the past to simulate return window expired
|
||||
tx.matures_at = datetime.now(timezone.utc) - timedelta(hours=1)
|
||||
db.commit()
|
||||
|
||||
# Run maturity sweep
|
||||
result = CreditService.process_maturing_credits(db)
|
||||
print("Maturity Sweep Result:", result)
|
||||
assert result["matured_count"] >= 1
|
||||
|
||||
db.refresh(tx)
|
||||
db.refresh(wallet)
|
||||
assert tx.status == "MATURED"
|
||||
assert tx.matured_at is not None
|
||||
assert wallet.pending_balance == Decimal("0.00")
|
||||
assert wallet.active_balance == Decimal("100.00")
|
||||
assert wallet.lifetime_earned == Decimal("100.00")
|
||||
print(f"✓ Credit matured successfully! Spendable Active Balance: ₹{wallet.active_balance}")
|
||||
|
||||
print("\n=== Test 5: Return / Voiding Simulation ===")
|
||||
# Create another order of ₹1000 -> generates ₹50 pending credit
|
||||
order2 = Order(
|
||||
order_id=str(ulid.ULID()),
|
||||
order_no=f"ORD-TEST-VOID-{str(ulid.ULID())}",
|
||||
customer_id=customer.customer_id,
|
||||
total_amount=Decimal("1000.00"),
|
||||
final_amount=Decimal("1000.00"),
|
||||
status="DELIVERED",
|
||||
payment_status="PAYMENT_CAPTURED"
|
||||
)
|
||||
db.add(order2)
|
||||
db.commit()
|
||||
|
||||
tx2 = CreditService.create_pending_credit_for_order(db, order2.order_id)
|
||||
assert tx2 is not None
|
||||
assert tx2.credit_amount == Decimal("50.00")
|
||||
db.refresh(wallet)
|
||||
assert wallet.pending_balance == Decimal("50.00")
|
||||
|
||||
# Now simulate customer returning the order within return window
|
||||
CreditService.void_pending_credit(db, "ORDER", order2.order_id, reason="Customer returned item")
|
||||
db.refresh(tx2)
|
||||
db.refresh(wallet)
|
||||
assert tx2.status == "VOIDED"
|
||||
assert tx2.void_reason == "Customer returned item"
|
||||
assert wallet.pending_balance == Decimal("0.00")
|
||||
assert wallet.active_balance == Decimal("100.00") # Original active balance unchanged!
|
||||
print("✓ Pending credit successfully voided upon order return with zero leakage.")
|
||||
|
||||
print("\n=== Test 6: Service Job Credit Flow ===")
|
||||
from app.models.CustomerDeviceModel import CustomerDevice
|
||||
device = CustomerDevice(
|
||||
device_id=str(ulid.ULID()),
|
||||
customer_id=customer.customer_id,
|
||||
brand="Apple",
|
||||
model="iPhone 14"
|
||||
)
|
||||
db.add(device)
|
||||
db.commit()
|
||||
|
||||
job = ServiceJob(
|
||||
job_id=str(ulid.ULID()),
|
||||
job_no=f"JOB-TEST-{str(ulid.ULID())}",
|
||||
customer_id=customer.customer_id,
|
||||
device_id=device.device_id,
|
||||
base_price_snapshot=Decimal("1500.00"),
|
||||
status="COMPLETED"
|
||||
)
|
||||
db.add(job)
|
||||
db.commit()
|
||||
|
||||
service_tx = CreditService.create_pending_credit_for_service(db, job.job_id)
|
||||
assert service_tx is not None
|
||||
# 5% of 1500 = 75.00
|
||||
assert service_tx.credit_amount == Decimal("75.00")
|
||||
assert service_tx.status == "PENDING"
|
||||
assert service_tx.reference_type == "SERVICE_JOB"
|
||||
db.refresh(wallet)
|
||||
assert wallet.pending_balance == Decimal("75.00")
|
||||
print(f"✓ Service job credit created: ₹{service_tx.credit_amount} (5% of ₹1500), matures in 3 days.")
|
||||
|
||||
print("\n=== Test 7: Full Wallet Ledger Summary ===")
|
||||
summary = CreditService.get_wallet_summary(db, customer.customer_id)
|
||||
print("Wallet Summary:", {k: v for k, v in summary.items() if k != "transactions"})
|
||||
print(f"Total Transactions logged: {len(summary['transactions'])}")
|
||||
assert summary["active_balance"] == 100.0
|
||||
assert summary["pending_balance"] == 75.0
|
||||
assert len(summary["transactions"]) == 3
|
||||
print("✓ Wallet summary and ledger integrity verified.")
|
||||
|
||||
print("\n🎉 ALL TESTS PASSED SUCCESSFULLY!")
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
|
@ -1,149 +0,0 @@
|
|||
import sys
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
# Ensure backend root is on python path
|
||||
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
|
||||
|
||||
import app.models.db_base
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.EcomCustomerModel import EcomCustomer, CustomerAddress
|
||||
from app.models.CartModel import Cart
|
||||
from app.models.ProductModel import Product, ProductVariant
|
||||
from app.models.OrderModel import Order
|
||||
from app.models.WalletModel import CustomerWallet, WalletTransaction
|
||||
from app.services.CreditService import CreditService
|
||||
from app.services.OrderService import OrderService
|
||||
|
||||
def run_storefront_credit_tests():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
print("\n=== STARTING STOREFRONT CREDIT INTEGRATION TEST SUITE ===")
|
||||
|
||||
# 1. Setup / find test customer
|
||||
customer = db.query(EcomCustomer).filter(EcomCustomer.email == "test_storefront_wallet@ifixkart.com").first()
|
||||
if not customer:
|
||||
import ulid
|
||||
customer = EcomCustomer(
|
||||
customer_id=str(ulid.ULID()),
|
||||
first_name="Test",
|
||||
last_name="Shopper",
|
||||
email="test_storefront_wallet@ifixkart.com",
|
||||
phone="919988776655",
|
||||
is_active=True
|
||||
)
|
||||
db.add(customer)
|
||||
db.commit()
|
||||
db.refresh(customer)
|
||||
print(f"[TEST 1] Verified Customer: {customer.customer_id}")
|
||||
|
||||
# 2. Check / Grant initial active credits
|
||||
wallet = CreditService.get_or_create_wallet(db, customer.customer_id)
|
||||
# Give 300 active credits
|
||||
CreditService.adjust_wallet_balance_manual(
|
||||
db=db,
|
||||
customer_id=customer.customer_id,
|
||||
amount=Decimal("300.00"),
|
||||
adjustment_type="CREDIT",
|
||||
reason="Test seed active credits",
|
||||
admin_user="system_test@ifixkart.com"
|
||||
)
|
||||
wallet = CreditService.get_or_create_wallet(db, customer.customer_id)
|
||||
assert wallet.active_balance >= Decimal("300.00"), f"Expected >= 300 active balance, got {wallet.active_balance}"
|
||||
initial_active = wallet.active_balance
|
||||
print(f"[TEST 2] Active Wallet Balance seeded: ₹{initial_active}")
|
||||
|
||||
# 3. Setup customer address
|
||||
import ulid
|
||||
addr = db.query(CustomerAddress).filter(CustomerAddress.customer_id == customer.customer_id).first()
|
||||
if not addr:
|
||||
addr = CustomerAddress(
|
||||
address_id=str(ulid.ULID()),
|
||||
customer_id=customer.customer_id,
|
||||
address_type="SHIPPING",
|
||||
full_name="Test Shopper",
|
||||
phone="919988776655",
|
||||
street_address="123 Commerce St",
|
||||
city="Bangalore",
|
||||
state="Karnataka",
|
||||
pincode="560001",
|
||||
is_default=True
|
||||
)
|
||||
db.add(addr)
|
||||
db.commit()
|
||||
db.refresh(addr)
|
||||
|
||||
# 4. Find an active product variant with stock
|
||||
variant = db.query(ProductVariant).filter(ProductVariant.price > 100).first()
|
||||
assert variant is not None, "Product variant must exist in DB"
|
||||
|
||||
# 5. Populate Cart
|
||||
import json
|
||||
cart = db.query(Cart).filter(Cart.customer_id == customer.customer_id).first()
|
||||
if not cart:
|
||||
cart = Cart(
|
||||
cart_id=str(ulid.ULID()),
|
||||
customer_id=customer.customer_id
|
||||
)
|
||||
db.add(cart)
|
||||
cart.items_json = json.dumps([{"variant_id": variant.variant_id, "qty": 1}])
|
||||
db.commit()
|
||||
|
||||
# 6. Create Checkout Order with use_wallet_credits = True
|
||||
print("[TEST 3] Creating Checkout Order with use_wallet_credits=True...")
|
||||
order_res = OrderService.create_ecommerce_order(
|
||||
db=db,
|
||||
customer=customer,
|
||||
address_id=addr.address_id,
|
||||
payment_method="COD",
|
||||
use_wallet_credits=True
|
||||
)
|
||||
|
||||
assert order_res["credits_applied"] > 0, "Expected credits_applied > 0"
|
||||
assert order_res["discount_amount"] == order_res["credits_applied"]
|
||||
print(f"[TEST 3 PASSED] Order created: {order_res['order_no']}, Total: ₹{order_res['total_amount']}, Credits Applied: ₹{order_res['credits_applied']}, Final: ₹{order_res['final_amount']}")
|
||||
|
||||
# 7. Verify wallet active_balance was debited
|
||||
db.refresh(wallet)
|
||||
expected_active = initial_active - Decimal(str(order_res["credits_applied"]))
|
||||
assert wallet.active_balance == expected_active, f"Expected {expected_active}, got {wallet.active_balance}"
|
||||
print(f"[TEST 4 PASSED] Wallet active_balance correctly debited to ₹{wallet.active_balance}")
|
||||
|
||||
# 8. Check REDEEM transaction in ledger
|
||||
redeem_tx = db.query(WalletTransaction).filter(
|
||||
WalletTransaction.customer_id == customer.customer_id,
|
||||
WalletTransaction.reference_id == order_res["order_id"],
|
||||
WalletTransaction.transaction_type == "REDEEM"
|
||||
).first()
|
||||
assert redeem_tx is not None, "REDEEM transaction must be logged"
|
||||
assert redeem_tx.credit_amount == -Decimal(str(order_res["credits_applied"]))
|
||||
print(f"[TEST 5 PASSED] REDEEM ledger entry confirmed: {redeem_tx.transaction_id} ({redeem_tx.credit_amount})")
|
||||
|
||||
# 9. Test Refund of redeemed credits upon Order Cancellation
|
||||
print("[TEST 6] Testing refund of redeemed credits on Order cancellation...")
|
||||
refund_tx = CreditService.refund_redeemed_credits(
|
||||
db=db,
|
||||
customer_id=customer.customer_id,
|
||||
order_id=order_res["order_id"],
|
||||
order_no=order_res["order_no"]
|
||||
)
|
||||
assert refund_tx is not None, "REFUND transaction must be generated"
|
||||
db.commit()
|
||||
db.refresh(wallet)
|
||||
assert wallet.active_balance == initial_active, f"Wallet active_balance should be restored to {initial_active}, got {wallet.active_balance}"
|
||||
print(f"[TEST 6 PASSED] Refund successfully restored wallet active_balance to ₹{wallet.active_balance}")
|
||||
|
||||
# 10. Check get_wallet_summary
|
||||
summary = CreditService.get_wallet_summary(db, customer.customer_id)
|
||||
assert "active_balance" in summary
|
||||
assert "pending_balance" in summary
|
||||
assert "transactions" in summary
|
||||
print(f"[TEST 7 PASSED] get_wallet_summary returned {len(summary['transactions'])} transactions")
|
||||
|
||||
print("\nALL STOREFRONT CREDIT INTEGRATION TESTS PASSED (100% SUCCESS)!")
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_storefront_credit_tests()
|
||||
11
test_db.py
11
test_db.py
|
|
@ -1,11 +0,0 @@
|
|||
import sys
|
||||
import os
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__name__)))
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.EcomCustomerModel import EcomCustomer
|
||||
db = SessionLocal()
|
||||
c = db.query(EcomCustomer).filter(EcomCustomer.phone == "9080323589").first()
|
||||
if c:
|
||||
print(f"Customer email: '{c.email}'")
|
||||
else:
|
||||
print("Customer not found")
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
from fastapi import Depends
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.api.v1.routers.PosSyncRouter import sync_pos_transactions, POSSyncPayload
|
||||
|
||||
db = SessionLocal()
|
||||
payload = POSSyncPayload.model_validate({
|
||||
"device_id": "DEV",
|
||||
"terminal_id": "TERM-MAIN-01",
|
||||
"store_id": "STORE",
|
||||
"transactions": [{
|
||||
"pos_transaction_id": "TX-123",
|
||||
"local_sequence": 1,
|
||||
"invoice_no": "INV-1",
|
||||
"total_amount": 100.0,
|
||||
"created_at": "2023-10-10T00:00:00Z",
|
||||
"items": [{"variant_id": "V-1", "qty": 1, "unit_price": 100.0}]
|
||||
}]
|
||||
})
|
||||
|
||||
try:
|
||||
res = sync_pos_transactions(payload, db)
|
||||
print("Success:", res)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
|
@ -1,149 +0,0 @@
|
|||
"""
|
||||
Automated test suite verifying complete COD removal and dynamic delivery rules.
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__)))
|
||||
|
||||
import app.models.db_base
|
||||
from fastapi import HTTPException
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.services.DeliveryService import DeliveryService
|
||||
from app.models.EcomCustomerModel import EcomCustomer, CustomerAddress
|
||||
from app.models.CartModel import Cart
|
||||
from app.models.ProductModel import ProductVariant
|
||||
from app.services.OrderService import OrderService
|
||||
import json
|
||||
import ulid
|
||||
|
||||
def test_delivery_and_cod():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
print("\n--- 1. Testing Default Delivery Settings ---")
|
||||
settings = DeliveryService.get_delivery_settings(db)
|
||||
print("Initial settings:", settings)
|
||||
assert settings["free_delivery_enabled"] is False, "Free delivery must be disabled by default!"
|
||||
assert settings["delivery_charge"] == 99.0, "Default delivery charge should be 99.0!"
|
||||
|
||||
# Ensure a test customer and cart exist
|
||||
test_email = "test_storefront_wallet@ifixkart.com"
|
||||
customer = db.query(EcomCustomer).filter(EcomCustomer.email == test_email).first()
|
||||
if not customer:
|
||||
customer = EcomCustomer(
|
||||
customer_id=str(ulid.ULID()),
|
||||
first_name="Delivery",
|
||||
last_name="Tester",
|
||||
email=test_email,
|
||||
phone="9876543299",
|
||||
is_active=True
|
||||
)
|
||||
db.add(customer)
|
||||
db.commit()
|
||||
|
||||
# Ensure address
|
||||
address = db.query(CustomerAddress).filter(CustomerAddress.customer_id == customer.customer_id).first()
|
||||
if not address:
|
||||
address = CustomerAddress(
|
||||
address_id=str(ulid.ULID()),
|
||||
customer_id=customer.customer_id,
|
||||
full_name="Delivery Tester",
|
||||
phone="9876543299",
|
||||
street_address="123 Tech Park",
|
||||
city="Chennai",
|
||||
state="Tamil Nadu",
|
||||
pincode="600001",
|
||||
address_type="SHIPPING"
|
||||
)
|
||||
db.add(address)
|
||||
db.commit()
|
||||
|
||||
# Find a product variant
|
||||
variant = db.query(ProductVariant).filter(ProductVariant.price > 100).first()
|
||||
assert variant is not None, "At least one product variant must exist in DB"
|
||||
|
||||
# Populate cart with 2 units so subtotal is substantial
|
||||
cart = db.query(Cart).filter(Cart.customer_id == customer.customer_id).first()
|
||||
if not cart:
|
||||
cart = Cart(
|
||||
cart_id=str(ulid.ULID()),
|
||||
customer_id=customer.customer_id
|
||||
)
|
||||
db.add(cart)
|
||||
|
||||
cart.items_json = json.dumps([{"variant_id": variant.variant_id, "qty": 2}])
|
||||
db.commit()
|
||||
|
||||
print("\n--- 2. Verifying COD Rejection ---")
|
||||
cod_rejected = False
|
||||
try:
|
||||
OrderService.create_ecommerce_order(
|
||||
db=db,
|
||||
customer=customer,
|
||||
address_id=address.address_id,
|
||||
payment_method="COD",
|
||||
)
|
||||
except HTTPException as e:
|
||||
if e.status_code == 400 and "COD" in e.detail:
|
||||
cod_rejected = True
|
||||
print("PASSED: COD was rejected with:", e.detail)
|
||||
|
||||
assert cod_rejected, "COD must be rejected with HTTP 400!"
|
||||
|
||||
print("\n--- 3. Verifying Order with Disabled Free Delivery (Flat Fee Applied) ---")
|
||||
# Ensure free delivery is false
|
||||
DeliveryService.update_delivery_settings(db, delivery_charge=99.0, free_delivery_enabled=False)
|
||||
order_res = OrderService.create_ecommerce_order(
|
||||
db=db,
|
||||
customer=customer,
|
||||
address_id=address.address_id,
|
||||
payment_method="RAZORPAY",
|
||||
)
|
||||
print("Created order:", order_res["order_no"], "Shipping Cost:", order_res["shipping_cost"])
|
||||
assert order_res["shipping_cost"] == 99.0, "Shipping cost must be 99.0 when free delivery is disabled!"
|
||||
|
||||
print("\n--- 4. Testing Dynamic Free Delivery Enablement via Admin Settings ---")
|
||||
DeliveryService.update_delivery_settings(
|
||||
db=db,
|
||||
delivery_charge=99.0,
|
||||
free_delivery_enabled=True,
|
||||
free_delivery_min_order_amount=200.0
|
||||
)
|
||||
updated_settings = DeliveryService.get_delivery_settings(db)
|
||||
print("Updated settings:", updated_settings)
|
||||
assert updated_settings["free_delivery_enabled"] is True
|
||||
assert updated_settings["free_delivery_min_order_amount"] == 200.0
|
||||
|
||||
# Repopulate cart
|
||||
cart.items_json = json.dumps([{"variant_id": variant.variant_id, "qty": 2}])
|
||||
db.commit()
|
||||
|
||||
order_res2 = OrderService.create_ecommerce_order(
|
||||
db=db,
|
||||
customer=customer,
|
||||
address_id=address.address_id,
|
||||
payment_method="RAZORPAY",
|
||||
)
|
||||
print("Created order 2 with free shipping enabled:", order_res2["order_no"], "Shipping Cost:", order_res2["shipping_cost"])
|
||||
assert order_res2["shipping_cost"] == 0.0, "Shipping cost should be 0.0 when free delivery is enabled and threshold met!"
|
||||
|
||||
print("\n--- 5. Resetting Free Delivery to False (Default State) ---")
|
||||
DeliveryService.update_delivery_settings(
|
||||
db=db,
|
||||
delivery_charge=99.0,
|
||||
free_delivery_enabled=False,
|
||||
free_delivery_min_order_amount=999.0
|
||||
)
|
||||
final_settings = DeliveryService.get_delivery_settings(db)
|
||||
assert final_settings["free_delivery_enabled"] is False
|
||||
print("Final settings restored:", final_settings)
|
||||
|
||||
print("\n=======================================================")
|
||||
print(">>> ALL DELIVERY AND COD INTEGRATION TESTS PASSED 100% <<<")
|
||||
print("=======================================================\n")
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_delivery_and_cod()
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
import app.models.db_base
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.services.InventoryPosService import InventoryPosService
|
||||
|
||||
db = SessionLocal()
|
||||
svc = InventoryPosService(db)
|
||||
terms = svc.list_terminals(None)
|
||||
for t in terms:
|
||||
print(t.terminal_id, t.code, t.name)
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
import sys
|
||||
import os
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.services.NotificationGatewayService import NotificationGatewayService
|
||||
from app.services.TemplateService import TemplateService, EVENT_REGISTRY
|
||||
from app.schemas.NotificationGateway import NotificationDispatchCreate
|
||||
|
||||
def run_tests():
|
||||
db = SessionLocal()
|
||||
tenant_id = "tenant_default"
|
||||
|
||||
for event_key, data in EVENT_REGISTRY.items():
|
||||
print(f"Triggering {event_key}...")
|
||||
|
||||
# Build mock context
|
||||
mock_context = {}
|
||||
for var in data["variables"]:
|
||||
if var["name"] == "items":
|
||||
mock_context["items"] = [{"product_name": "Test Item 1", "sku": "SKU-1", "quantity": 1, "unit_price": 500}]
|
||||
else:
|
||||
name_val = var.get("name")
|
||||
mock_context[var["name"]] = var.get("example", f"[{name_val}]")
|
||||
|
||||
# Try for EMAIL
|
||||
rendered_email = TemplateService.render_template(db, event_key, "EMAIL", mock_context, tenant_id)
|
||||
if not rendered_email:
|
||||
rendered_email = (f"Test Subject: {event_key}", f"<p>This is a test fallback email for {event_key}. Context: {mock_context}</p>")
|
||||
|
||||
subj, body = rendered_email
|
||||
payload = NotificationDispatchCreate(
|
||||
recipient="adithiyan.elan@gmail.com",
|
||||
channel="EMAIL",
|
||||
subject=subj,
|
||||
message_body=body
|
||||
)
|
||||
try:
|
||||
NotificationGatewayService.dispatch_notification(db, tenant_id, payload)
|
||||
print(f" -> Dispatched EMAIL (rerouted to Adithiyan)")
|
||||
except Exception as e:
|
||||
print(f" -> EMAIL failed: {e}")
|
||||
|
||||
# Try for WHATSAPP
|
||||
rendered_wa = TemplateService.render_template(db, event_key, "WHATSAPP", mock_context, tenant_id)
|
||||
if not rendered_wa:
|
||||
rendered_wa = (None, f"[Test {event_key}] Context: {mock_context}")
|
||||
|
||||
subj, body = rendered_wa
|
||||
payload = NotificationDispatchCreate(
|
||||
recipient="919080323589",
|
||||
channel="WHATSAPP",
|
||||
subject=subj,
|
||||
message_body=body
|
||||
)
|
||||
try:
|
||||
NotificationGatewayService.dispatch_notification(db, tenant_id, payload)
|
||||
print(f" -> Dispatched WHATSAPP (rerouted to Adithiyan)")
|
||||
except Exception as e:
|
||||
print(f" -> WHATSAPP failed: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.sql import text
|
||||
from app.core.config.Config import settings
|
||||
|
||||
engine = create_engine(settings.COMMERCE_DATABASE_URL)
|
||||
with engine.connect() as conn:
|
||||
res = conn.execute(text("SELECT entity_id, channel, recipient, status, subject FROM notifications ORDER BY created_at DESC LIMIT 10;")).fetchall()
|
||||
for row in res:
|
||||
print(row)
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
import requests
|
||||
|
||||
payload = {
|
||||
"quote_number": "SQ-2026-999",
|
||||
"customer_name": "Test Cust",
|
||||
"customer_phone": "9999999999",
|
||||
"customer_email": "test@example.com",
|
||||
"subtotal": 1000,
|
||||
"tax_amount": 180,
|
||||
"final_amount": 1180,
|
||||
"items": [
|
||||
{
|
||||
"sku": "TEST-SKU",
|
||||
"description": "Test Item",
|
||||
"quantity": 1,
|
||||
"unit_price": 1000,
|
||||
"tax_percent": 18
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
res = requests.post("http://localhost:8000/api/v1/billing-finance/quotations", json=payload)
|
||||
print(res.status_code)
|
||||
print(res.text)
|
||||
22
test_sync.py
22
test_sync.py
|
|
@ -1,22 +0,0 @@
|
|||
import requests
|
||||
|
||||
payload = {
|
||||
"device_id": "DEV",
|
||||
"terminal_id": "TERM-MAIN-01",
|
||||
"store_id": "STORE",
|
||||
"transactions": [{
|
||||
"pos_transaction_id": "TX-123",
|
||||
"local_sequence": 1,
|
||||
"invoice_no": "INV-1",
|
||||
"total_amount": 100.0,
|
||||
"created_at": "2023-10-10T00:00:00Z",
|
||||
"items": [{"variant_id": "V-1", "qty": 1, "unit_price": 100.0}]
|
||||
}]
|
||||
}
|
||||
|
||||
try:
|
||||
res = requests.post("http://localhost:8000/api/v1/pos/sync", json=payload)
|
||||
print("Status:", res.status_code)
|
||||
print("Body:", res.text)
|
||||
except Exception as e:
|
||||
print("Error:", e)
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.abspath('/mnt/fam/SERVER/IfixKartEcommerce/Backend'))
|
||||
|
||||
import app.models.db_base
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.OrderModel import Order, OrderItem
|
||||
from app.models.WarrantyModel import Warranty
|
||||
from app.services.WarrantyService import WarrantyService
|
||||
import ulid
|
||||
from datetime import datetime
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
# Create dummy order
|
||||
order_id = str(ulid.ULID())
|
||||
order = Order(
|
||||
order_id=order_id,
|
||||
order_no="TEST-ORD-" + str(ulid.ULID())[-4:],
|
||||
customer_id=None,
|
||||
total_amount=1000.0,
|
||||
final_amount=1000.0,
|
||||
status="DELIVERED",
|
||||
payment_status="PAID"
|
||||
)
|
||||
db.add(order)
|
||||
|
||||
item = OrderItem(
|
||||
item_id=str(ulid.ULID()),
|
||||
order_id=order_id,
|
||||
product_id=str(ulid.ULID()),
|
||||
variant_id=str(ulid.ULID()),
|
||||
product_name="Test Product",
|
||||
sku="TEST-SKU",
|
||||
quantity=1,
|
||||
unit_price=1000.0,
|
||||
total_price=1000.0
|
||||
)
|
||||
db.add(item)
|
||||
db.commit()
|
||||
|
||||
print(f"Created Test Order: {order_id}")
|
||||
|
||||
# Trigger Warranty Service
|
||||
count = WarrantyService.generate_warranty_for_order(db, order_id)
|
||||
print(f"Warranties generated: {count}")
|
||||
|
||||
warranties = db.query(Warranty).filter(Warranty.reference_id == order_id).all()
|
||||
for w in warranties:
|
||||
print(f"Warranty ID: {w.warranty_id}, Status: {w.status}, End Date: {w.end_date}")
|
||||
|
||||
db.close()
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
import requests
|
||||
import json
|
||||
import time
|
||||
import os
|
||||
import ulid
|
||||
|
||||
API_BASE = "http://localhost:8000/api/v1"
|
||||
|
||||
def print_result(step, res):
|
||||
print(f"\n--- {step} ---")
|
||||
print(f"Status: {res.status_code}")
|
||||
try:
|
||||
print(json.dumps(res.json(), indent=2))
|
||||
except:
|
||||
print(res.text)
|
||||
|
||||
script = """
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.abspath('/mnt/fam/SERVER/IfixKartEcommerce/Backend'))
|
||||
|
||||
import app.models.db_base
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.OrderModel import Order, OrderItem
|
||||
from app.models.WarrantyModel import Warranty
|
||||
from app.services.WarrantyService import WarrantyService
|
||||
import ulid
|
||||
from datetime import datetime
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
# Create dummy order
|
||||
order_id = str(ulid.ULID())
|
||||
order = Order(
|
||||
order_id=order_id,
|
||||
order_no="TEST-ORD-100",
|
||||
tenant_id="tenant_default",
|
||||
customer_id=str(ulid.ULID()),
|
||||
final_amount=1000.0,
|
||||
status="DELIVERED",
|
||||
payment_status="PAID"
|
||||
)
|
||||
db.add(order)
|
||||
|
||||
item = OrderItem(
|
||||
order_item_id=str(ulid.ULID()),
|
||||
order_id=order_id,
|
||||
product_id=str(ulid.ULID()),
|
||||
variant_id=str(ulid.ULID()),
|
||||
quantity=1,
|
||||
unit_price=1000.0,
|
||||
total_price=1000.0
|
||||
)
|
||||
db.add(item)
|
||||
db.commit()
|
||||
|
||||
print(f"Created Test Order: {order_id}")
|
||||
|
||||
# Trigger Warranty Service
|
||||
count = WarrantyService.generate_warranty_for_order(db, order_id)
|
||||
print(f"Warranties generated: {count}")
|
||||
|
||||
warranties = db.query(Warranty).filter(Warranty.reference_id == order_id).all()
|
||||
for w in warranties:
|
||||
print(f"Warranty ID: {w.warranty_id}, Status: {w.status}, End Date: {w.end_date}")
|
||||
|
||||
db.close()
|
||||
"""
|
||||
|
||||
with open("test_warranty_db.py", "w") as f:
|
||||
f.write(script)
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
import httpx
|
||||
|
||||
api_key = "PHtE6r0PQujsjDQnoBYH4aLsH8H3Z458+rtjKwcVuYcQWfVVF00G+d5+xzTl/UsqB/QTFPXPmolptuzP5bqHLW7pMWwfCGqyqK3sx/VYSPOZsbq6x00Zsl8dcEzdV4TtddNq0CDfv97TNA=="
|
||||
endpoint = "https://cpaas.zoho.in/v1.1/email"
|
||||
recipient = "adithiyan.elan@gmail.com"
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Zoho-enczapikey {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
payload = {
|
||||
"from": {"address": "info@trionixsolution.com", "name": "iFixKart Suite"},
|
||||
"to": [{"email_address": {"address": recipient}}],
|
||||
"subject": "Test Email",
|
||||
"htmlbody": "<div>This is a test email.</div>"
|
||||
}
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=8.0) as client:
|
||||
res = client.post(endpoint, json=payload, headers=headers)
|
||||
print("Status code:", res.status_code)
|
||||
print("Response text:", res.text)
|
||||
except Exception as ex:
|
||||
print("Exception thrown:", type(ex).__name__, "-", str(ex))
|
||||
11
unlock.py
11
unlock.py
|
|
@ -1,11 +0,0 @@
|
|||
from app.core.database.db_session import engine_core
|
||||
from sqlalchemy import text
|
||||
|
||||
def unlock_users():
|
||||
with engine_core.connect() as conn:
|
||||
conn.execute(text('UPDATE users SET is_locked = 0, failed_login_attempts = 0'))
|
||||
conn.commit()
|
||||
print('All users unlocked successfully.')
|
||||
|
||||
if __name__ == '__main__':
|
||||
unlock_users()
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
"""
|
||||
Script to update all Cashify products with genuine Cashify CDN PNG product photos (s3ng.cashify.in).
|
||||
"""
|
||||
import re
|
||||
import app.models.db_base
|
||||
from app.core.database.db_session import SessionLocal
|
||||
from app.models.ProductModel import Product, ProductImage
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
CASHIFY_EXACT_IMAGES = {
|
||||
"refurbished-apple-iphone-15-pro-max": "https://s3ng.cashify.in/cashify/store/product/f133e9311ac34fe2b7737dde73c41206.png",
|
||||
"refurbished-apple-iphone-15-pro": "https://s3ng.cashify.in/cashify/store/product/1e6b0a079b59479fa308605df283452e.png",
|
||||
"refurbished-apple-iphone-15": "https://s3ng.cashify.in/cashify/store/product/239e2f931f594864ba546e5e454acf75.png",
|
||||
"refurbished-apple-iphone-14-pro-max": "https://s3ng.cashify.in/cashify/store/product/297159945dd241bc9d39037a5c5c2c81.png",
|
||||
"refurbished-apple-iphone-14-pro": "https://s3ng.cashify.in/cashify/store/product/a10fa87c0c7b414cb286a84896db2739.png",
|
||||
"refurbished-apple-iphone-14": "https://s3ng.cashify.in/cashify/store/product/8bbf11e143eb4cbaa7df09eafabc8dfe.png",
|
||||
"refurbished-apple-iphone-13-pro-max": "https://s3ng.cashify.in/cashify/store/product/3916901a6acf4e0d8e71a539f5ca9980.png",
|
||||
"refurbished-apple-iphone-13": "https://s3ng.cashify.in/cashify/store/product/dbe46c15496745a3b53fc5982839f6ec.png",
|
||||
"refurbished-apple-iphone-12-pro-max": "https://s3ng.cashify.in/cashify/store/product/1ec04242fcca475982971ab673db0994.png",
|
||||
"refurbished-apple-iphone-12": "https://s3ng.cashify.in/cashify/store/product/07861d0404d9404f9ba8678d90934eb4.png",
|
||||
"refurbished-apple-iphone-11": "https://s3ng.cashify.in/cashify/store/product/cf73bcbd1a084711b40776bfe103bf3d.png",
|
||||
"refurbished-apple-iphone-se-2022": "https://s3ng.cashify.in/cashify/store/product/d81ecaefa5c3455a8e5df055b9584ce3.png",
|
||||
"refurbished-samsung-galaxy-s24-ultra-5g": "https://s3ng.cashify.in/cashify/store/product/359aa372e8d4493a82e98d62a0d28421.png",
|
||||
"refurbished-samsung-galaxy-s23-ultra-5g": "https://s3ng.cashify.in/cashify/store/product/835713059280445cbe2927e9faf90e5c.png",
|
||||
"refurbished-samsung-galaxy-s23-5g": "https://s3ng.cashify.in/cashify/store/product/7d2a3d64c4e148f0b70b1fdc18c1066f.png",
|
||||
"refurbished-samsung-galaxy-s22-ultra-5g": "https://s3ng.cashify.in/cashify/store/product/3b2ec89f01614ac08140946b76964c0c.png",
|
||||
"refurbished-samsung-galaxy-z-fold-5-5g": "https://s3ng.cashify.in/cashify/store/product/c1ee1cdbb76b417f9ab1a03e7adb6fc7.png",
|
||||
"refurbished-samsung-galaxy-z-flip-5-5g": "https://s3ng.cashify.in/cashify/store/product/24ac575a9be4466f9440d3de3812ddf8.png",
|
||||
"refurbished-oneplus-12-5g": "https://s3ng.cashify.in/cashify/store/product/f0b4c119a4a640d781d3e6f589da955d.png",
|
||||
"refurbished-oneplus-11-5g": "https://s3ng.cashify.in/cashify/store/product/808058fcb6ba440caa964ab3cdaba1a1.png",
|
||||
"refurbished-oneplus-11r-5g": "https://s3ng.cashify.in/cashify/store/product/ecaf132162cf4ca9b115b5885cc32694.png",
|
||||
"refurbished-oneplus-nord-3-5g": "https://s3ng.cashify.in/cashify/store/product/82394a3e032c4560a5c1eadef44ba639.png",
|
||||
"refurbished-google-pixel-8-pro": "https://s3ng.cashify.in/cashify/store/product/0fe59d304de144ee8eec5229464d10b3.png",
|
||||
"refurbished-google-pixel-8": "https://s3ng.cashify.in/cashify/store/product/4a4539029beb4c0a826a53a6455864a5.png",
|
||||
"refurbished-google-pixel-7a": "https://s3ng.cashify.in/cashify/store/product/a5eea7555b2343bdbeb09dadde22063d.png",
|
||||
"refurbished-xiaomi-13-pro-5g": "https://s3ng.cashify.in/cashify/store/product/5d5b324478c646a0abf724fe0d3ca00b.png",
|
||||
"refurbished-redmi-note-13-pro-5g": "https://s3ng.cashify.in/cashify/store/product/3334c8539d4b42e592b1406b8a76a45f.png",
|
||||
"refurbished-poco-f5-5g": "https://s3ng.cashify.in/cashify/store/product/5ec904e350904e27aeec2685b26ae9a0.png",
|
||||
"refurbished-apple-ipad-pro-12-9-m2-6th-gen": "https://s3ng.cashify.in/cashify/store/product/e1d4a81f41384007b9cf19150db50358.png",
|
||||
"refurbished-apple-ipad-air-m1-5th-gen": "https://s3ng.cashify.in/cashify/store/product/14c8228b80c24fd894a6f26831b3013d.png",
|
||||
"refurbished-apple-ipad-10th-gen-10-9": "https://s3ng.cashify.in/cashify/store/product/fd8a3454f2594ebfa6b420172a2bb882.webp",
|
||||
}
|
||||
|
||||
import ulid
|
||||
|
||||
updated_count = 0
|
||||
for slug, img_url in CASHIFY_EXACT_IMAGES.items():
|
||||
prod = db.query(Product).filter(Product.slug == slug).first()
|
||||
if prod:
|
||||
prod_imgs = db.query(ProductImage).filter(ProductImage.product_id == prod.product_id).all()
|
||||
if prod_imgs:
|
||||
for pimg in prod_imgs:
|
||||
pimg.image_url = img_url
|
||||
else:
|
||||
pimg = ProductImage(
|
||||
image_id=str(ulid.ULID()),
|
||||
product_id=prod.product_id,
|
||||
image_url=img_url,
|
||||
alt_text=prod.name,
|
||||
sort_order=1,
|
||||
is_banner=True
|
||||
)
|
||||
db.add(pimg)
|
||||
db.commit()
|
||||
updated_count += 1
|
||||
|
||||
# Also assign default high-res fallback photos for any remaining products missing images
|
||||
all_prods = db.query(Product).all()
|
||||
for prod in all_prods:
|
||||
imgs = db.query(ProductImage).filter(ProductImage.product_id == prod.product_id).all()
|
||||
if not imgs:
|
||||
fallback_img = "https://s3ng.cashify.in/cashify/store/product/f133e9311ac34fe2b7737dde73c41206.png"
|
||||
if "samsung" in prod.slug or "galaxy" in prod.slug:
|
||||
fallback_img = "https://s3ng.cashify.in/cashify/store/product/359aa372e8d4493a82e98d62a0d28421.png"
|
||||
elif "oneplus" in prod.slug:
|
||||
fallback_img = "https://s3ng.cashify.in/cashify/store/product/f0b4c119a4a640d781d3e6f589da955d.png"
|
||||
elif "pixel" in prod.slug:
|
||||
fallback_img = "https://s3ng.cashify.in/cashify/store/product/0fe59d304de144ee8eec5229464d10b3.png"
|
||||
elif "ipad" in prod.slug or "tablet" in prod.slug:
|
||||
fallback_img = "https://s3ng.cashify.in/cashify/store/product/e1d4a81f41384007b9cf19150db50358.png"
|
||||
|
||||
pimg = ProductImage(
|
||||
image_id=str(ulid.ULID()),
|
||||
product_id=prod.product_id,
|
||||
image_url=fallback_img,
|
||||
alt_text=prod.name,
|
||||
sort_order=1,
|
||||
is_banner=True
|
||||
)
|
||||
db.add(pimg)
|
||||
db.commit()
|
||||
|
||||
print(f"Successfully updated {updated_count} products and ensured all 151 products have active images!")
|
||||
db.close()
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 93 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 168 KiB |
Loading…
Reference in a new issue