|
| 1 | +import json |
| 2 | +from commercetools.platform.models import ( |
| 3 | + ProductDraft, |
| 4 | + ProductVariantDraft, |
| 5 | + ProductTypeResourceIdentifier, |
| 6 | + ProductPriceModeEnum |
| 7 | +) |
| 8 | +from commerce_coordinator.apps.commercetools.management.commands._ct_api_client_command import ( |
| 9 | + CommercetoolsAPIClientCommand, |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +product_json=''' |
| 14 | +
|
| 15 | +
|
| 16 | +
|
| 17 | +''' |
| 18 | + |
| 19 | +class Command(CommercetoolsAPIClientCommand): |
| 20 | + help = "Create a commercetools product from a JSON string or file" |
| 21 | + |
| 22 | + def handle(self, *args, **options): |
| 23 | + if product_json: |
| 24 | + try: |
| 25 | + product_data = json.loads(product_json) |
| 26 | + except json.JSONDecodeError as e: |
| 27 | + self.stderr.write(f"Invalid JSON format: {e}") |
| 28 | + return |
| 29 | + else: |
| 30 | + print("\n\n\n\nNo JSON data provided.\n\n\n\n") |
| 31 | + return |
| 32 | + |
| 33 | + product_type_data = product_data.get("productType") |
| 34 | + if product_type_data: |
| 35 | + product_type = ProductTypeResourceIdentifier(id=product_type_data["id"]) |
| 36 | + else: |
| 37 | + print("\n\n\n\nMissing productType data.\n\n\n\n") |
| 38 | + return |
| 39 | + |
| 40 | + master_variant_data = product_data.get("masterVariant") |
| 41 | + variants_data = product_data.get("variants", []) |
| 42 | + |
| 43 | + master_variant = ProductVariantDraft(**master_variant_data) |
| 44 | + variants = [ProductVariantDraft(**variant) for variant in variants_data] |
| 45 | + |
| 46 | + product_draft_data = { |
| 47 | + "key": product_data.get("key"), |
| 48 | + "name": product_data.get("name"), |
| 49 | + "description": product_data.get("description"), |
| 50 | + "slug": product_data.get("slug"), |
| 51 | + "price_mode": ProductPriceModeEnum.STANDALONE, |
| 52 | + "publish": product_data.get("publish"), |
| 53 | + "tax_category": product_data.get("taxCategory"), |
| 54 | + "master_variant": master_variant, |
| 55 | + "variants": variants, |
| 56 | + "product_type": product_type |
| 57 | + } |
| 58 | + |
| 59 | + try: |
| 60 | + product_draft = ProductDraft(**product_draft_data) |
| 61 | + created_product = self.ct_api_client.base_client.products.create(draft=product_draft) |
| 62 | + print(f"\n\n\n\nSuccessfully created product with ID: {created_product.id}") |
| 63 | + except Exception as e: |
| 64 | + print(f"\n\n\n\nError creating product: {e}") |
| 65 | + |
0 commit comments