importing woocommerce products is working

This commit is contained in:
Sam
2021-02-17 12:26:40 +00:00
parent 4140250174
commit 42097c3102
2 changed files with 48 additions and 19 deletions

View File

@@ -19,6 +19,8 @@ from companies.serializers import CompanySerializer
from utils.tag_filters import CompanyTagFilter
from back_latienda.permissions import IsCreator
from utils import woocommerce
class CompanyViewSet(viewsets.ModelViewSet):
queryset = Company.objects.all()
@@ -120,23 +122,34 @@ class CompanyViewSet(viewsets.ModelViewSet):
except Exception as e:
return Response({"errors":{"details": str(e),}}, status=500)
@action(detail=True, methods=['POST', ])
@action(detail=True, methods=['GET', ])
def import_products(self, request, **kwargs):
instance = self.queryset.filter(pk=kwargs['pk']).first()
# check if it's a shop
if instance.shop is not True:
return Response('This company is not a shop')
# check what platform
platform = instance.platform
if platform is None:
return Response('This company is not registered with any platforms')
return Response({'error': 'This company is not a shop'})
# check required credentials
credentials = instance.credentials
if credentials is None or credentials == {}:
return Response('This company has no registered credentials')
# execute import
return Response()
return Response({'error': 'This company has no registered credentials'})
# check what platform
platform = instance.platform
if platform is None:
message = {'error': 'This company is not registered with any platforms'}
elif platform == 'WOO_COMMERCE':
# recheck credentials
if 'key' in credentials.keys() and 'secret' in credentials.keys():
# execute import
products = woocommerce.migrate_shop_products(
instance.web_link,
credentials['key'],
credentials['secret'])
message = {'details': f'{len(products)} products added for {instance.company_name}'}
else:
message = {"error": 'Credentials have wrong format'}
else:
message = {'error': f'Platform {plaform} not registered'}
return Response(message)
@api_view(['GET',])

View File

@@ -67,24 +67,40 @@ def migrate_shop_products(url, key, secret, version="wc/v3"):
instance_data[key] = product[key]
# remove unwanted fields
instance_data.pop('id')
if instance_data.get('tags') == []:
instance_data.pop('tags')
if instance_data.get('attributes') == []:
instance_data.pop('attributes')
# extract m2m field data
tags = instance_data.pop('tags')
attributes = instance_data.pop('attributes')
# create instance with serializer
'''
serializer = ProductSerializer(data=instance_data)
if serializer.is_valid():
new = serializer.save()
if tags:
new.tags.set(tags)
if attributes:
new.attributes.set(attributes)
new.save()
else:
logging.error(f"{serializer.errors}")
continue
'''
# alternative method
try:
new = Product.objects.create(**instance_data)
except Exception as e:
logging.error(f"Could not create product instance: {str(e)}")
'''
serializer = ProductSerializer(data=instance_data)
if serializer.is_valid():
try:
new = Product.objects.create(**serializer.validated_data)
if tags:
new.tags.set(tags)
if attributes:
new.attributes.set(attributes)
new.save()
except Exception as e:
logging.error(f"Could not create product instance: {str(e)}")
else:
logging.error(f"{serializer.errors}")
continue
products_created.append(new)
counter += 1
logging.info(f"Product {instance_data.get('name')} created")