|
| 1 | +""" |
| 2 | +Script to import data from magento_products.csv into the orders table. |
| 3 | +""" |
| 4 | +import csv |
| 5 | +from datetime import datetime |
| 6 | +from app.utils.db import get_db_connection_direct |
| 7 | + |
| 8 | +CSV_PATH = "app/static/csv/magento_products.csv" |
| 9 | + |
| 10 | +# List of columns in the orders table (must match the table definition) |
| 11 | +ORDERS_COLUMNS = [ |
| 12 | + "sku","store_view_code","attribute_set_code","product_type","categories","product_websites","name","description","short_description","weight","product_online","tax_class_name","visibility","price","special_price","special_price_from_date","special_price_to_date","url_key","meta_title","meta_keywords","meta_description","base_image","base_image_label","small_image","small_image_label","thumbnail_image","thumbnail_image_label","swatch_image","swatch_image_label","created_at","updated_at","new_from_date","new_to_date","display_product_options_in","map_price","msrp_price","map_enabled","gift_message_available","custom_design","custom_design_from","custom_design_to","custom_layout_update","page_layout","product_options_container","msrp_display_actual_price_type","country_of_manufacture","additional_attributes","qty","out_of_stock_qty","use_config_min_qty","is_qty_decimal","allow_backorders","use_config_backorders","min_cart_qty","use_config_min_sale_qty","max_cart_qty","use_config_max_sale_qty","is_in_stock","notify_on_stock_below","use_config_notify_stock_qty","manage_stock","use_config_manage_stock","use_config_qty_increments","qty_increments","use_config_enable_qty_inc","enable_qty_increments","is_decimal_divided","website_id","related_skus","related_position","crosssell_skus","crosssell_position","upsell_skus","upsell_position","additional_images","additional_image_labels","hide_from_product_page","custom_options","bundle_price_type","bundle_sku_type","bundle_price_view","bundle_weight_type","bundle_values","bundle_shipment_type","associated_skus","downloadable_links","downloadable_samples","configurable_variations","configurable_variation_labels","hide","flag" |
| 13 | +] |
| 14 | + |
| 15 | + |
| 16 | +def import_csv_to_orders(): |
| 17 | + conn = get_db_connection_direct() |
| 18 | + inserted = 0 |
| 19 | + total = 0 |
| 20 | + with conn: |
| 21 | + with conn.cursor() as cur: |
| 22 | + with open(CSV_PATH, newline='', encoding='utf-8') as csvfile: |
| 23 | + reader = csv.DictReader(csvfile) |
| 24 | + for idx, row in enumerate(reader): |
| 25 | + total += 1 |
| 26 | + # Add hide and flag fields if not present |
| 27 | + row.setdefault("hide", False) |
| 28 | + row.setdefault("flag", False) |
| 29 | + # Convert empty strings to None |
| 30 | + values = [row.get(col) if row.get(col) != '' else None for col in ORDERS_COLUMNS] |
| 31 | + # Print first row and values for debug |
| 32 | + if idx == 0: |
| 33 | + print("First CSV row:", row) |
| 34 | + print("First values list:", values) |
| 35 | + # Convert booleans and numerics as needed |
| 36 | + for i, col in enumerate(ORDERS_COLUMNS): |
| 37 | + if col in ["hide", "flag", "product_online", "use_config_min_qty", "is_qty_decimal", "allow_backorders", "use_config_backorders", "use_config_min_sale_qty", "use_config_max_sale_qty", "is_in_stock", "notify_on_stock_below", "use_config_notify_stock_qty", "manage_stock", "use_config_manage_stock", "use_config_qty_increments", "use_config_enable_qty_inc", "enable_qty_increments", "is_decimal_divided"]: |
| 38 | + if values[i] is not None: |
| 39 | + values[i] = str(values[i]).lower() in ("1", "true", "t", "yes") |
| 40 | + elif col in ["weight", "price", "special_price", "map_price", "msrp_price", "qty", "out_of_stock_qty", "min_cart_qty", "max_cart_qty", "qty_increments"]: |
| 41 | + if values[i] is not None: |
| 42 | + try: |
| 43 | + values[i] = float(values[i]) |
| 44 | + except ValueError: |
| 45 | + values[i] = None |
| 46 | + elif col.endswith("_date") or col.endswith("_at") or col in ["custom_design_from", "custom_design_to"]: |
| 47 | + if values[i] is not None: |
| 48 | + try: |
| 49 | + # Try parsing as date or datetime |
| 50 | + values[i] = datetime.strptime(values[i], "%m/%d/%y") |
| 51 | + except Exception: |
| 52 | + try: |
| 53 | + values[i] = datetime.strptime(values[i], "%Y-%m-%d") |
| 54 | + except Exception: |
| 55 | + values[i] = None |
| 56 | + placeholders = ','.join(['%s'] * len(ORDERS_COLUMNS)) |
| 57 | + sql = f"INSERT INTO orders ({', '.join(ORDERS_COLUMNS)}) VALUES ({placeholders}) ON CONFLICT (sku) DO NOTHING" |
| 58 | + try: |
| 59 | + cur.execute(sql, values) |
| 60 | + inserted += 1 |
| 61 | + except Exception as e: |
| 62 | + print(f"Error inserting row {idx+1} (sku={row.get('sku')}): {e}") |
| 63 | + try: |
| 64 | + conn.commit() |
| 65 | + print("Database commit successful.") |
| 66 | + except Exception as e: |
| 67 | + print(f"Error during commit: {e}") |
| 68 | + print(f"Total rows processed: {total}") |
| 69 | + print(f"Total rows attempted to insert: {inserted}") |
| 70 | + if inserted == 0: |
| 71 | + print("No rows were inserted. Please check for errors above or review the data and schema alignment.") |
| 72 | + print("Data import attempt complete.") |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + import_csv_to_orders() |
0 commit comments