def delete(self, request, pk=None): """FolderClientAPIView delete Description: delete folder Args: :param name: (str) folder name """ req_inf = RequestInfo() name = request.query_params.get('name', None) if name is not None: try: folder = FolderClient.objects.get(slug=name) documents = Document.objects.filter(folder=folder) last_id = folder.id last_name = folder.name for doc in documents: doc.document.delete() doc.delete() folder.delete() log = Log.objects.create( action=Log.NOTIFICATION_TYPE.get_value('update_client'), user=request.user, description='Modificacion de cliente {} - {}'.format( last_id, last_name)) log.save() return req_inf.status_200() except Exception as e: return req_inf.status_400(e.args[0]) else: return req_inf.status_400('Nombre de folder requerido')
def delete(self, request, pk=None): """DocumentDetailAPIView delete Description: Delete Documents Args: :param name: (str) the name of the document """ req_inf = RequestInfo() name = request.query_params.get('name', None) if name is not None: try: document = Document.objects.get(slug=name) document.document.delete() last_id = document.id last_name = document.name document.delete() log = Log.objects.create( action=Log.NOTIFICATION_TYPE.get_value('delete_document'), user=request.user, description='Eliminacion de documento {}- {}'.format( las_id, last_name)) log.save() return req_inf.status_200() except Exception as e: return req_inf.status_400(e.args[0]) else: return req_inf.status_400('Nombre de documento requerido')
def put(self, request, pk): """DocumentDetailAPIView put Description: update document information """ req_inf = RequestInfo() document_cls = self.get_object(pk) if isinstance(document_cls, Document): serializer = DocumentInfoSerializer(document_cls, data=request.data) if serializer.is_valid(): try: serializer.save() log = Log.objects.create( action=Log.NOTIFICATION_TYPE.get_value( 'update_document'), user=request.user, description='Modificacion de documento {} - {}'.format( serializer.instance.id, serializer.instance.name)) log.save() return req_inf.status_200() except Exception as e: return req_inf.status_400(e.args[0]) return req_inf.status_400(serializer.errors) else: return req_inf.status_404(document_cls)
def put(self, request): """Update user account data :param email: str :param first_name: str :param last_name: str :param username: str :param password: str :param phone: str :param genre: str :param birthdate: date :param profile_photo: file :return token: jwt_token """ user = request.user request_info = RequestInfo() serializer = UserSerializer(user, data=request.data) if user is not None and serializer.is_valid(): serializer.save() return request_info.return_status({ 'status': status.HTTP_200_OK, 'token': generate_jwt(user), 'detail': 'user updated' }) else: raise AuthenticationFailed()
def put(self, request, pk): """UserClientDetailAPIView put Description: update client information """ import pudb pudb.set_trace() req_inf = RequestInfo() user_client = self.get_object(pk) if isinstance(user_client, UserClient): serializer = ClientSerializer(user_client, data=request.data) if serializer.is_valid(): try: serializer.save() log = Log.objects.create( action=Log.NOTIFICATION_TYPE.get_value( 'update_client'), user=request.user, description='Modificacion de cliente {} - {}'.format( serializer.instance.id, serializer.instance.name)) log.save() return req_inf.status_200() except Exception as e: return req_inf.status_400(e.args[0]) return req_inf.status_400(serializer.errors) else: return req_inf.status_404(user_client)
def post(self, request): """DocumentAPIView post Description: Create Documents Args: :param name: (str) the name of the document :param document: (file) document file :param folder: (id) folder id """ req_inf = RequestInfo() serializer = DocumentInfoSerializer(data=request.data) if serializer.is_valid(): try: serializer.save() log = Log.objects.create( action=Log.NOTIFICATION_TYPE.get_value('create_document'), user=request.user, description='Creacion de Documento {} - {}'.format( serializer.instance.id, serializer.instance.name)) log.save() return req_inf.status_200() except Exception as e: return req_inf.status_400(e.args[0]) else: return req_inf.status_400(serializer.errors)
def get(self, request): """Address API GET Description: return all directions associated to user """ user = get_jwt_user(request) req_inf = RequestInfo() try: if user is not None: try: serializer = AddressSerializer( client.addresses.all(), many=True ) return Response(serializer.data) except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0]) else: return req_inf.status_401('token invalido') except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0])
def create_simple_user(request): """create simple user fiscal info :basic_info: (dict) :param email: (str) :param first_name: (str) :param last_name: (str) :param fiscal: (dict) :param rfc: (str) :param business_name: (str) :param physical_person: (bool) :param address: (dict) :param street: (str) :param street_number: (str) :param zip_code: (str) :param neighborhood: (str) :param city: (str) :param state: (str) """ import random import re req_inf = RequestInfo() try: try: username = request.data['basic_info']['username'] except KeyError: request.data['basic_info']['username'] = re.sub( "[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", request.data['basic_info']['email'][:(request.data['basic_info']['email'].find('@'))] ) request.data['basic_info']['username'] = '******'.format( request.data['basic_info']['username'], random.randrange(10**8) ) except Exception: pass user_serializer = BasicUserSerializer(data=request.data.get('basic_info')) if user_serializer.is_valid(): user_serializer.save() request.data['fiscal']['user'] = user_serializer.instance.id fiscal_serializer = FiscalSerializer( Fiscal.objects.get(user_id=user_serializer.instance.id), data=request.data.get('fiscal') ) if fiscal_serializer.is_valid(): fiscal_serializer.save() request.data['address']['fiscal'] = fiscal_serializer.instance.id address_serializer = AddreesSerializer( Address.objects.get(fiscal_id=fiscal_serializer.instance.id), data=request.data.get('address')) if address_serializer.is_valid(): address_serializer.save() return req_inf.status() except Exception as e: return req_inf.status(e.args[0], status.HTTP_400_BAD_REQUEST)
def get(self, request): """Get user data :param Authorization: token :return UserSerializer: json user data """ request_info = RequestInfo() if request.user is not None: serializer = UserSerializer(request.user) return Response(serializer.data) else: raise AuthenticationFailed()
def get_object(self, pk): """get_object Description: Get Document object or None Args: :param pk: (int) Document's pk """ req_inf = RequestInfo() try: return Document.objects.get(pk=pk) except Document.DoesNotExist as e: return e.args[0]
def bills(request): """get list of disponible bills """ req_inf = RequestInfo() data = { "emisor_bill": FacturaSerializer(Factura.objects.filter(emisor=request.user), many=True).data, "receiver_bill": FacturaSerializer(Factura.objects.filter(receiver=request.user), many=True).data } return Response(data)
def get(self, request): """Get fiscal information from user """ req_inf = RequestInfo() rfc = request.GET.get('rfc', None) user = request.user try: if rfc is not None: user = Fiscal.objects.get(rfc=rfc).user return Response(UserInfoSerializer(user).data) except ObjectDoesNotExist as e: return req_inf.status(e.args[0], status.HTTP_404_NOT_FOUND) except Exception as e: return req_inf.status(e.args[0], status.HTTP_400_BAD_REQUEST)
def get(self, request): """UserClientAPIView get Description: Get client id Args: :param name: (str) client slug name """ req_inf = RequestInfo() name = request.GET.get('name', None) try: serializer = ClientSimpleSerializer( UserClient.objects.get(slug=name)) return Response(serializer.data) except Exception as e: return req_inf.status_400(e.args[0])
def create_bill(request): """create bill :param basic_information: (dict) :param emisor_rfc: (str) :param receiver_rfc: (str) :param date_expedition: (date) :param coin: (str) :param folio: (str) :param way_to_pay: (str) :param concepts: (list of dicts) :param product_key: (str) :param quantity: (str) :param description: (str) :param amount: (str) """ req_inf = RequestInfo() errors = [] concepts = [] try: request.data['basic_information']['emisor'] = Fiscal.objects.get( rfc=request.data['basic_information']['emisor_rfc']).user.id request.data['basic_information']['receiver'] = Fiscal.objects.get( rfc=request.data['basic_information']['receiver_rfc']).user.id request.data['basic_information'].pop('emisor_rfc') request.data['basic_information'].pop('receiver_rfc') for data in request.data.get('concepts'): concept_serializer = ConceptSerializer(data=data) if concept_serializer.is_valid(): concept_serializer.save() concepts.append(concept_serializer.instance) else: errors.append(concept_serializer.errors) if len(errors) == 0: bill_serializer = SimpleFacturaSerializer( data=request.data.get('basic_information')) if bill_serializer.is_valid(): bill_serializer.save() for con in concepts: bill_serializer.instance.concepts.add(con) bill_serializer.save() return req_inf.status() else: return req_inf.status(bill_serializer.errors, status.HTTP_400_BAD_REQUEST) else: return req_inf.return_status(errors) except Exception as e: return req_inf.status(e.args[0], status.HTTP_400_BAD_REQUEST)
def put(self, request): """modification of tax data :param fiscal: (dic): :param rfc: (str) :param business_name: (str) :param physical_person: (bool) :param address: (dict) :param street: (str) :param street_number: (str) :param zip_code: (str) :param neighborhood: (str) :param city: (str) :param state: (str) """ req_inf = RequestInfo() errors = [] rfc = request.data.get('rfc', None) user = request.user if rfc is not None: user = Fiscal.objects.get(rfc=rfc).user try: fiscal_serializer = FiscalSerializer( Fiscal.objects.get(user=user), data=request.data.get('fiscal') ) address_serializer = AddreesSerializer( Address.objects.get(fiscal_id=fiscal_serializer.instance.id), data=request.data.get('address') ) if fiscal_serializer.is_valid() and address_serializer.is_valid(): fiscal_serializer.save() address_serializer.save() return req_inf.status() else: try: errors.append(fiscal_serializer.errors) except Exception: pass try: errors.append(address_serializer.errors) except Exception: pass return req_inf.status(errors, status.HTTP_400_BAD_REQUEST) except ObjectDoesNotExist as e: return req_inf.status(e.args[0], status.HTTP_404_NOT_FOUND) except Exception as e: return req_inf.status(e.args[0], status.HTTP_400_BAD_REQUEST)
def get(self, request): """User API GET Description: returns user info """ user = get_jwt_user(request) req_inf = RequestInfo() if user is not None: try: serializer = ClientSerializer(user.client) return Response(serializer.data) except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0]) else: return req_inf.status_401('token invalido')
def patch(self, request): """Address API PATCH Args: country: (str) region: (str) town: (str) neighborhood: (str) zip_code: (str) street: (str) street_number: (str) suite_number: (str) address_id: (int) Description: update directions """ user = get_jwt_user(request) data = request.data req_inf = RequestInfo() try: if user is not None: client = Client.objects.get(user=user) address = Address.objects.get(id=data.get('address_id')) if 'country' in data: address.country = data.get('country') if 'region' in data: address.region = data.get('region') if 'town' in data: address.town = data.get('town') if 'neighborhood' in data: address.neighborhood = data.get('neighborhood') if 'zip_code' in data: address.zip_code = data.get('zip_code') if 'street' in data: address.street = data.get('street') if 'street_number' in data: address.street_number = data.get('street_number') if 'suite_number' in data: address.suite_number = data.get('suite_number') address.save() return req_inf.status_200('address updated') else: return req_inf.status_401('token invalido') except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0])
def patch(self, request): """User API PATCH Args: username: (str) first_name: (str) last_name: (str) email: (str) password: (str) phone: (str) Description: update user info view """ user = get_jwt_user(request) data = request.data req_inf = RequestInfo() try: if user is not None: user_cls = Client.objects.get(user=user) if 'username' in data: if self.validate_data(data.get('username'), user.username): user.username = data.get('username') if 'email' in data: if self.validate_data(data.get('email'), user_cls.user.email): user.email = data.get('email') if 'password' in data: user.set_password(data.get('password')) if 'phone' in data: user_cls.phone = data.get('phone') if 'first_name' in data: user.first_name = data.get('first_name') if 'last_name' in data: user.last_name = data.get('last_name') user.save() user_cls.save() data_err = { 'status': status.HTTP_200_OK, 'token': generate_jwt(user, request), 'detail': 'user updated' } return req_inf.return_status(data_err) else: return req_inf.status_401('token invalido') except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0])
def get(self, request): """FolderAPIView get Description: Get folder id Args: :param name: (str) folder slug name """ req_inf = RequestInfo() name = request.GET.get('name', None) if name is not None: try: serializer = FolderSimpleSerializer( FolderClient.objects.get(slug=name)) return Response(serializer.data) except Exception as e: return req_inf.status_400(e.args[0]) else: return req_inf.status_400('nombre de folder requerido')
def get_bill(request): """download bill """ req_inf = RequestInfo() try: bill = Factura.objects.get(_id=request.GET.get('bill')) name = 'bill-{}{}.xml'.format(request.user.username, bill.id) with open(name, 'wb') as f: f.write( dicttoxml(FacturaDetailSerializer(bill).data, attr_type=False)) bill_file = open('{}/{}'.format(settings.BASE_DIR, name), 'rb') response = HttpResponse(FileWrapper(bill_file), content_type='application/xml') response['Content-Disposition'] = 'attachment; filename="{}"'.format( name) os.remove('{}/{}'.format(settings.BASE_DIR, name)) return response except ObjectDoesNotExist as e: return req_inf.status(e.args[0], status.HTTP_404_NOT_FOUND) except Exception as e: return req_inf.status(e.args[0], status.HTTP_400_BAD_REQUEST)
def put(self, request, pk=None): """FolderClientAPIView put Description: update client information """ req_inf = RequestInfo() folder_client = self.get_object(pk) if isinstance(folder_client, FolderClient): serializer = FolderSerializer(folder_client, data=request.data) if serializer.is_valid(): serializer.save() log = Log.objects.create( action=Log.NOTIFICATION_TYPE.get_value('update_folder'), user=request.user, description='Modificacion de folder {} - {}'.format( serializer.instance.id, serializer.instance.name)) log.save() return req_inf.status_200() return req_inf.status_400(serializer.errors) else: return req_inf.status_404(folder_client)
def post(self, request): """Creates user accounts :param email: str :param first_name: str :param last_name: str :param password: str :return token: jwt_token """ import re req_inf = RequestInfo() try: username = request.data['basic_info']['username'] except KeyError: request.data['username'] = re.sub( "[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", request.data['email'][:(request.data['email'].find('@'))] ) request.data['username'] = '******'.format( request.data['username'], random.randrange(10**8) ) except Exception: pass try: serializer = CreateUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({ 'token': generate_jwt(serializer.instance) }) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) except ObjectDoesNotExist as e: return req_inf.status(e.args[0], status.HTTP_404_NOT_FOUND) except Exception as e: return req_inf.status(e.args[0], status.HTTP_400_BAD_REQUEST)
def post(self, request): """User API POST Args: username: (str) first_name: (str) last_name: (str) email: (str) password: (str) Description: create user view """ data = request.data username = data.get('username') first_name = data.get('first_name', None) last_name = data.get('last_name', None) email = data.get('email') password = data.get('password') req_inf = RequestInfo() user = None try: user = User.objects.get(email=email) except ObjectDoesNotExist as e: pass if user is not None: return req_inf.status_400('email already exists') try: user_cls = Client.create( username, first_name, last_name, email, None, password ) user_cls.save() return req_inf.status_200() except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0])
def delete(self, request): """Address API PATCH Args: address_id: (int) Description: delete directions """ user = get_jwt_user(request) data = request.data req_inf = RequestInfo() try: if user is not None: client = Client.objects.get(user=user) address = Address.objects.get(id=data.get('address_id')) address.delete() return req_inf.status_200('address deleted') else: return req_inf.status_401('token invalido') except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0])
def post(self, request): """Address API GET Args: country: (str) region: (str) town: (str) neighborhood: (str) zip_code: (str) street: (str) street_number: (str) suite_number: (str) Description: create directions """ user = get_jwt_user(request) data = request.data req_inf = RequestInfo() try: if user is not None: client = Client.objects.get(user=user) address = Address.create( data.get('country'), data.get('region'), data.get('town'), data.get('neighborhood'), data.get('zip_code'), data.get('street'), data.get('street_number'), data.get('suite_number') ) client.addresses.add(address) client.save() return req_inf.status_200('address created') else: return req_inf.status_401('token invalido') except ObjectDoesNotExist as e: return req_inf.status_404(e.args[0]) except Exception as e: return req_inf.status_400(e.args[0])
def post(self, request): """UserClientAPIView post Description: Create clients Args: :param name: (str) the name of the client """ req_inf = RequestInfo() serializer = ClientSerializer(data=request.data) if serializer.is_valid(): try: serializer.save() log = Log.objects.create( action=Log.NOTIFICATION_TYPE.get_value('create_client'), user=request.user, description='Creacion de cliente {} - {}'.format( serializer.instance.id, serializer.instance.name)) log.save() return req_inf.status_200() except Exception as e: return req_inf.status(e.args[0]) else: return req_inf.status_400(serializer.errors)
def login(request): """Login API View Args: username (str): user email password (str): user password """ username = request.data.get('username', None) password = request.data.get('password', None) req_info = RequestInfo() if '@' in username: try: u = User.objects.get(email=username) except User.DoesNotExist: pass else: username = u.username try: user = authenticate(username=username, password=password) except ObjectDoesNotExist: user = None if user is not None: return Response({'token': generate_jwt(user, request)}) else: return req_info.status_400('email o password incorrectos')