sort.py

2.8 kB · python · 92 lines

1from catalog.helpers import load_product, save_product2from catalog.models import Variant3from typing import Tuple45STANDARD_SIZES = [6    "3XS", "2XS", "XS", "S", "S/M", "M", "M/L", "L", "L/XL", "XL",7    "2XL", "3XL", "4XL", "5XL", "6XL", "7XL"8]910SPECIAL_SIZES = [11    "One size"12]1314KIDS_SIZES = [15    "2T", "3T", "4T", "5T", "6", "6X", "7", "8", "10", "12", "14"16]1718SIZE_CATEGORIES = {19    "standard": set(STANDARD_SIZES),20    "special": set(SPECIAL_SIZES),21    "kids": set(KIDS_SIZES),22}2324def clean_size(size: str) -> str:25    if not size:26        return ""27    size = size.replace("\u2033", "")28    size = size.replace("\u00d7", "x")29    size = size.replace(" ", "")30    return size3132def parse_dimensional_size(size: str) -> Tuple[float, float]:33    if not size:34        return None35    try:36        cleaned = clean_size(size)37        if not cleaned:38            return None39        if "x" in cleaned.lower():40            width, height = cleaned.lower().split("x")41            return (float(width), float(height))42        value = float(cleaned)43        return (value, value)44    except ValueError:45        return None4647def determine_size_type(variants: list[Variant]) -> str:48    variant_sizes = {v.size for v in variants if v.size}49    if not variant_sizes:50        return "unknown"51    if all(parse_dimensional_size(size) for size in variant_sizes):52        return "dimensional"53    for size_type, size_set in SIZE_CATEGORIES.items():54        if variant_sizes.issubset(size_set):55            return size_type56    print(f"No size array contains all sizes: {variant_sizes}")57    return "unknown"5859def get_size_index(size: str, size_type: str) -> Tuple[int, float]:60    if not size:61        return (999, 0)62    match size_type:63        case "standard":64            if size in STANDARD_SIZES:65                return (100, STANDARD_SIZES.index(size))66        case "special":67            if size in SPECIAL_SIZES:68                return (200, SPECIAL_SIZES.index(size))69        case "kids":70            if size in KIDS_SIZES:71                return (300, KIDS_SIZES.index(size))72        case "dimensional":73            dimensional_size = parse_dimensional_size(size)74            if dimensional_size:75                width, height = dimensional_size76                return (400, width * height)77            return (999, 0)78    print(f"Unknown size type for {size}")79    return (999, 0)8081def sort_products(ids: list[int]):82    print(f"Sorting {len(ids)} products")83    for id in ids:84        product = load_product(id)85        size_type = determine_size_type(product.variants)86        product.variants = sorted(87            product.variants,88            key=lambda v: (get_size_index(v.size, size_type))89        )90        print(f"Sorted: {product.desc} - {size_type.upper()}")91        save_product(product)92    print(f"Sorted {len(ids)} products")