from rest_framework.views import APIView from rest_framework.response import Response import pandas as pd from apps.shop.models import Product as ProductModel, ProductCategory as ProductCategoryModel from apps.workspace.models import Workspace as WorkspaceModel, City as CityModel from apps.customer.models import Customer as CustomerModel from apps.customer.models import ResponsibleGroup as ResponsibleGroupModel from django.core.exceptions import ValidationError as DjangoValidationError from django.db import IntegrityError, transaction from rest_framework import exceptions from rest_framework.permissions import IsAuthenticated from utils import custom_permissions from utils.get_user_workspace import get_user_workspace from utils.validations.mobile import normalize_mobile class ImportExcelView(APIView): permission_classes = (IsAuthenticated, custom_permissions.WorkspaceAdminPermission) def get(self, request): # Keep the legacy URL and filename, but use the same validated importer as Admin. from django.core.files import File from apps.shop.product_import import parse_workbook, import_products try: with open('pe.xlsx', 'rb') as source: rows = parse_workbook(File(source, name='pe.xlsx')) for row in rows: row['values'].setdefault('view_only', 'true') result = import_products(get_user_workspace(request), rows, {'mode': 'upsert', 'create_categories': True, 'errors': 'atomic', 'ordering': 'preserve'}) except (OSError, DjangoValidationError) as error: raise exceptions.ValidationError(getattr(error, 'messages', ['فایل اکسل محصولات خوانده نشد.'])) if not result['committed']: raise exceptions.ValidationError(result) return Response(data={'result': 'ok', 'imported': result['created'] + result['updated']}) class ImportExcelCitysView(APIView): def get(self, request): df = pd.read_excel('cities.xlsx') for index, row in df.iterrows(): city_name = row['name'] pv_id = row['province_id'] try: ostan = CityModel.objects.get(pv_id=pv_id, is_ostan=True) except Exception as exp: print(city_name) print(pv_id) city_obj = CityModel() city_obj.name = city_name city_obj.is_ostan = False city_obj.ostan = ostan city_obj.save() return Response(data={"result": 'ok'}) def customer_from_excel(row, workspace): mobile = row['mobile'] if pd.isna(mobile) or pd.isna(row['name']): raise exceptions.ValidationError('نام و شماره موبایل مشتری الزامی است.') if isinstance(mobile, float) and mobile.is_integer(): mobile = int(mobile) city = CityModel.objects.filter(name=row['shar'], ostan__name=row['ostan'], ostan__is_ostan=True).first() city = city or CityModel.objects.filter(pk=1229).first() if not city: raise exceptions.ValidationError('شهر مشتری در فایل پیدا نشد.') group = ResponsibleGroupModel.objects.filter(pk=row['id_mantaghe'], sys_ws=workspace).first() if not group: raise exceptions.ValidationError('گروه مسئول متعلق به این فضای کاری نیست.') customer = CustomerModel(name_family=row['name'], mobile=normalize_mobile(mobile), city=city, responsible_group=group, sys_ws=workspace, phone=None if pd.isna(row['phone']) else row['phone'], address=None if pd.isna(row['address']) else row['address']) customer.full_clean() customer.save() class ImportExcelCustomersView(APIView): permission_classes = (IsAuthenticated, custom_permissions.WorkspaceAdminPermission) @transaction.atomic def get(self, request): workspace = get_user_workspace(request) try: data = pd.read_excel('customersData.xlsx') except (OSError, ValueError): raise exceptions.ValidationError('فایل اکسل مشتریان خوانده نشد.') for index, row in data.iterrows(): try: customer_from_excel(row, workspace) except DjangoValidationError as error: raise exceptions.ValidationError({'row': int(index)+2, 'errors': error.message_dict}) except IntegrityError: raise exceptions.ValidationError({'row': int(index)+2, 'mobile': 'شماره موبایل مشتری تکراری است.'}) except exceptions.ValidationError as error: raise exceptions.ValidationError({'row': int(index)+2, 'errors': error.detail}) except (KeyError, TypeError, ValueError): raise exceptions.ValidationError({'row': int(index)+2, 'error': 'اطلاعات این ردیف معتبر نیست.'}) return Response(data={'result': 'ok', 'imported': len(data)})