class StockSerializer(serializers.ModelSerializer): controlled_substance = ControlledSubstancesSerializer( fields=('controlled_substance_pk', 'controlled_substance_id', 'controlled_substance_name', 'units')) location = LocationSerializer(fields=('location_id', 'location_name', 'map_lat', 'map_long')) added_by_user = UserSerializer(fields=('user_id', 'name')) disposed_by_user = UserSerializer(fields=('user_id', 'name')) def to_internal_value(self, data): ret = super(StockSerializer, self).to_internal_value(data) return ret def to_representation(self, instance): ret = super(StockSerializer, self).to_representation(instance) return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(StockSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class Meta: model = Stock
class UserResortListSerializer(serializers.ModelSerializer): user = UserSerializer(fields=('user_id', 'name', 'email')) def to_representation(self, instance): from apps.custom_user.utils import userrole_option ret = super(UserResortListSerializer, self).to_representation(instance) ret['role'] = userrole_option(int(ret['role'])) return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(UserResortListSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class Meta: model = UserResortMap
class AuditLogSerializer(serializers.ModelSerializer): added_by_user = UserSerializer(fields=('user_id', 'name')) def to_internal_value(self, data): ret = super(AuditLogSerializer, self).to_internal_value(data) return ret def to_representation(self, instance): ret = super(AuditLogSerializer, self).to_representation(instance) return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(AuditLogSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class Meta: model = AuditLog exclude = ('controlled_substance_audit_log_pk', 'resort')
def get_user_resort_combo(user_id, resort_required_data, user_required_data=('user_id', 'name', 'phone', 'email', 'user_connected', 'user_controlled_substances', 'user_asset_management')): user_resort = {} actual_user = user.objects.get(pk=user_id) user_data = UserSerializer(actual_user, fields=user_required_data) user_resort = user_data.data resorts_user = UserResortMap.objects.filter(user=actual_user) resorts = [] for resort in resorts_user: resorts.append(resort.resort) resort_data = ResortSerializer(resorts, fields=resort_required_data, many=True) user_resort["resorts"] = resort_data.data user_resort["role_id"] = userrole_option( resorts_user[len(resorts) - 1].role.role_id) if len(resorts) > 0 else "" user_resort["resort_count"] = len(resorts) return user_resort
class StockReportSerializer(serializers.ModelSerializer): controlled_substance = ControlledSubstancesSerializer( fields=('controlled_substance_id', 'controlled_substance_name', 'controlled_substance_pk', 'units')) location = LocationSerializer(fields=('location_id', 'location_name', 'map_lat', 'map_long')) added_by_user = UserSerializer(fields=('user_id', 'name')) disposed_by_user = UserSerializer(fields=('user_id', 'name')) def to_internal_value(self, data): ret = super(StockReportSerializer, self).to_internal_value(data) return ret def to_representation(self, instance): # Add assignment if its found assignment = StockAssignment.objects.filter(controlled_substance_stock=instance) if assignment: assignment_data = StockAssignmentSerializer(assignment[0], fields=('controlled_substance_stock_assignment_id', 'dt_added', 'dt_used', 'user', 'incident_id')).data else: assignment_data = {} ret = super(StockReportSerializer, self).to_representation(instance) ret['assignment'] = assignment_data return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(StockReportSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class Meta: model = Stock
class IncidentListSerializer(serializers.ModelSerializer): resort = ResortSerializer(fields=('resort_id', 'resort_name')) assigned_to = UserSerializer(fields=('user_id', 'name')) class Meta: model = Incident def to_representation(self, instance): config = instance.resort.incident_template incident_json = get_incident_data(instance.incident_pk) ret = super(IncidentListSerializer, self).to_representation(instance) incident_status = ret['incident_status'] ret.update(incident_json) data = get_extra_incident_info(config, incident_json, instance.incident_pk, 'list', self.context['data_key']) ret.update(data) ret.update( get_patient_info(instance.incident_pk, self.context['data_key'])) try: ret['incident_status'] = incident_status_option(incident_status) except: ret['incident_status'] = "" if instance.resort.use_sequential_incident_id == 1 and instance.assigned_to.user_connected == 1: ret['incident_pk'] = instance.incident_sequence else: ret['incident_pk'] = instance.incident_pk notes = IncidentNotes.objects.filter( incident=instance).order_by('-note_date') ret['notes'] = IncidentNotesSerializer(notes, fields=('note_id', 'note_date', 'note', 'user'), many=True).data return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(IncidentListSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name)
class IncidentStatusReportSerializer(serializers.ModelSerializer): assigned_to = UserSerializer(fields=('user_id', 'name')) class Meta: model = Incident def to_representation(self, instance): config = instance.resort.incident_template incident_json = get_incident_data(instance.incident_pk) ret = super(IncidentStatusReportSerializer, self).to_representation(instance) data = get_extra_incident_info_status_report(config, incident_json) ret.update(data) try: ret['incident_status'] = incident_status_option_for_status_report( ret['incident_status']) except: ret['incident_status'] = "" if instance.resort.use_sequential_incident_id == 1 and instance.assigned_to.user_connected == 1: ret['incident_pk'] = instance.incident_sequence else: ret['incident_pk'] = instance.incident_pk return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(IncidentStatusReportSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name)
class StockAssignmentSerializer(serializers.ModelSerializer): user = UserSerializer(fields=('user_id', 'name')) incident_id = serializers.StringRelatedField() def to_internal_value(self, data): ret = super(StockAssignmentSerializer, self).to_internal_value(data) return ret def to_representation(self, instance): ret = super(StockAssignmentSerializer, self).to_representation(instance) controlled_substance_stock_assignment_status = ret.get('controlled_substance_stock_assignment_status') if controlled_substance_stock_assignment_status is not None: try: ret['controlled_substance_stock_assignment_status'] = construct_options(STOCK_ASSIGNMENT_STATUS, controlled_substance_stock_assignment_status) except: pass try: if 'incident_id' in ret: ret['incident_pk'] = instance.incident_id.incident_sequence if instance.incident_id.resort.use_sequential_incident_id else instance.incident_id.incident_pk except: pass return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(StockAssignmentSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class Meta: model = StockAssignment
class StatusHistorySerializer(serializers.ModelSerializer): status = IncidentStatusSerializer(fields=('key', 'incident_status_id')) user = UserSerializer(fields=('user_id', 'name')) class Meta: model = StatusHistory def to_representation(self, instance): ret = super(StatusHistorySerializer, self).to_representation(instance) return replace_null(ret) def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(StatusHistorySerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name)
def post(self, request, format=None): user = None resort = None resort_created = False resort_map = None remote_request = True if settings.RUN_ENV != 'local': domain = Domains.objects.get(domain=request.get_host()) else: domain = Domains.objects.get(pk=1) us_domain = Domains.objects.get(pk=1) au_domain = Domains.objects.get(pk=2) resort_network_key = request.data.get('resort_network_key', '') if resort_network_key: try: resort_map = RoutingCompany.objects.get( resort_token=resort_network_key) except: return Response( {_('detail'): _('Resort with network key does not exist')}, status=400) country = request.data.get('country', '').lower() if resort_map is not None: if resort_map.domain == domain: remote_request = False # If user specified any of the below country then create resort and user in that particular region if country and country in [ "australia", "new zealand" ] and (domain == us_domain) and (settings.RUN_ENV != 'local') and remote_request: pool = urllib3.PoolManager() url = "https://" + au_domain.domain + "/api/v3/auth/register/" data = request.data header = { "Authorization": "Bearer sOMaRH33KEdmrLk2D6bdhaG13MjgY4", "Content-Type": "application/json" } # try creating resort in AU server. Returns error if anything went wild try: response = pool.urlopen('POST', url, headers=header, body=json.dumps(data)) return Response(json.loads(response.data)) except Exception as e: return Response(e.message, status=500) elif country and country not in [ "australia", "new zealand" ] and (domain == au_domain) and (settings.RUN_ENV != 'local') and remote_request: pool = urllib3.PoolManager() url = "https://" + us_domain.domain + "/api/v3/auth/register/" data = request.data header = { "Authorization": "Bearer sOMaRH33KEdmrLk2D6bdhaG13MjgY4", "Content-Type": "application/json" } # try creating resort in AU server. Returns error if anything went wild try: response = pool.urlopen('POST', url, headers=header, body=json.dumps(data)) return Response(json.loads(response.data)) except Exception as e: return Response(e.message, status=500) elif resort_map is not None and resort_map.domain != domain and ( settings.RUN_ENV != 'local') and remote_request: pool = urllib3.PoolManager() url = "https://" + resort_map.domain.domain + "/api/v3/auth/register/" data = request.data header = { "Authorization": "Bearer sOMaRH33KEdmrLk2D6bdhaG13MjgY4", "Content-Type": "application/json" } # try creating resort in AU server. Returns error if anything went wild try: response = pool.urlopen('POST', url, headers=header, body=json.dumps(data)) return Response(json.loads(response.data)) except Exception as e: return Response(e.message, status=500) else: resort_name = request.data.get('resort_name') # First preference is given to the resort_network_key using which user can be connected to resort if resort_network_key is not None and resort_network_key: resort = get_resort_by_network_key(resort_network_key) if resort is None: return Response( { _('detail'): _('Resort with network key does not exist') }, status=400) else: if resort.license_expiry_date is not None: if resort.license_expiry_date < ( timezone.now() + datetime.timedelta(hours=24)): return Response( {_('detail'): _('Resort expiry date past')}, status=400) if resort.licenses is not None: if UserResortMap.objects.filter( resort=resort, user__is_active=True, user__user_connected=1).count( ) >= resort.licenses: return Response( {_('detail'): _('no more licenses')}, status=400) user_connected = 1 # Second preference for connecting user to resort is given to the resort_name # If resort with provided resort_name doesn't exists then new one is created elif resort_name is not None and resort_name: resort = get_resort_by_name(resort_name) if resort is None: resort_data = ResortSerializer(data=request.data) if resort_data.is_valid(): resort = resort_data.save(domain_id=domain) resort_created = True else: return Response(resort_data.errors, status=400) user_connected = 0 else: return Response( { _('detail'): _('resort name and/or resort network key not provided') }, status=400) # Try to get existing user and if it doesn't find then create new user try: user = get_user_model().objects.get( email__iexact=request.data.get('email')) return Response( {_('detail'): _('the email address is already in use')}, status=403) # user_data = UserSerializer(user, data=request.data, partial=True) except: user_data = UserSerializer(data=request.data, fields=('email', 'phone', 'name', 'password')) if user_data.is_valid(): user = user_data.save(user_connected=user_connected, is_active=True) if settings.RUN_ENV == 'master': register_user_mailchimp('c08200b7c1', user.email, resort.resort_name, user.name, "", ['11182343c6']) else: register_user_mailchimp('c08200b7c1', user.email, resort.resort_name, user.name, "", ['0005c6dcdf']) else: return Response(user_data.errors, status=400) # Create user and resort mapping and uses default role of patroller for newly created user user_resort_map, created = UserResortMap.objects.get_or_create( user=user, resort=resort, defaults={'role': UserRoles.objects.get(pk=1)}) if user_connected == 1: inject_patroller(resort, user, 'add') # Creates new device data = request.data data['device_user'] = user.user_pk device_data = DeviceSerializer(data=data) if device_data.is_valid(): device = device_data.save() else: return Response(device_data.errors, status=400) # Gets token of newly created user token = Token.objects.get(user=user) # Updates user discovery table across the cluster try: update_user_discovery(user, resort.domain_id, request) except Exception as e: return Response(e.message, status=500) return Response({ "resort_id": resort.resort_id, "resort_name": resort.resort_name, "user_id": user.user_id, "device_id": device.device_id, "token": token.key, "user_connected": construct_options(UserConnected, user_connected) })
def update(self, request, pk=None): try: user = get_user_model().objects.get(user_id=pk) except: return Response({_("detail"): _("User does not exists")}, status=400) resort = get_resort_for_user(user) if user_has_permission( request.user, resort, 3) or request.user == user or request.user.is_admin: if not user.is_active: return Response({_("detail"): _("User inactive or deleted.")}, status=403) user_data = UserSerializer(user, data=request.data, partial=True) if user_data.is_valid(): routing_user = RoutingUser.objects.filter( email=user_data.validated_data['email']).first() if routing_user is not None: if user_data.validated_data['email'] != user.email: return Response( { _("detail"): _('the email address is already in use') }, status=403) else: # Remove previous user information from discovery table across all region remove_user_discovery(user, resort.domain_id, request) user = user_data.save() if user.user_connected == 1: inject_patroller(resort, user, 'add') else: inject_patroller(resort, user, 'remove') role = request.data.get('role_id') if role is not None and role: user_resort = UserResortMap.objects.filter( user=user, resort=resort).first() if user_resort is not None: role = UserRoles.objects.filter(role_id=role).first() if role is not None: user_resort.role = role user_resort.save() else: return Response( { _("detail"): _("specified role does not exists") }, status=400) if routing_user is None: # Update user email and Name across all the region update_user_discovery(user, resort.domain_id, request) # Update mailchimp with new user if settings.RUN_ENV == 'master': register_user_mailchimp('c08200b7c1', user.email, resort.resort_name, user.name, "", ['11182343c6']) else: register_user_mailchimp('c08200b7c1', user.email, resort.resort_name, user.name, "", ['0005c6dcdf']) else: return Response(user_data.errors, status=400) else: return Response( {_("detail"): _("You don't have permission to update user")}, status=403) response_data = get_user_resort_combo( user.user_pk, ('resort_id', 'resort_name', 'map_kml', 'map_type', 'report_form', 'unit_format', 'timezone', 'map_lat', 'map_lng', 'resort_logo', 'datetime_format', 'resort_controlled_substances', 'resort_asset_management')) return Response(response_data, status=200)
def create(self, request): resort_id = request.data.get('resort_id') resort = get_resort_by_resort_id(resort_id) role_id = request.data.get('role_id') # If role_id not provided (or) empty then use default role_id as 1 (patroller) if (role_id is None) and (not role_id): role_id = 1 elif not (0 < role_id < 4): return Response({_('detail'): _("invalid role_id provided")}, status=400) if resort is not None: if resort.licenses is not None: if UserResortMap.objects.filter( resort=resort, user__is_active=True, user__user_connected=1).count() >= resort.licenses: return Response({_('detail'): _('no more licenses')}, status=400) if user_has_permission(request.user, resort, 3) or request.user.is_admin: try: user = get_user_model().objects.get( email__iexact=request.data.get('email').lower()) return Response( { _('detail'): _('the email address is already in use') }, status=403) # user_data = UserSerializer(user, data=request.data, partial=True) except: user_data = UserSerializer(data=request.data, fields=('email', 'phone', 'name', 'password')) if user_data.is_valid(): user = user_data.save(user_connected=1, is_active=True) if settings.RUN_ENV == 'master': register_user_mailchimp('c08200b7c1', user.email, resort.resort_name, user.name, "", ['11182343c6']) else: register_user_mailchimp('c08200b7c1', user.email, resort.resort_name, user.name, "", ['0005c6dcdf']) else: return Response(user_data.errors, status=400) inject_patroller(resort, user, 'add') else: return Response( { _('detail'): _("You dont have have permission to add user") }, status=403) else: return Response( { _("detail"): _("Resort with provided resort_id does not exists") }, status=400) update_user_discovery(user, resort.domain_id, request) user_resort_map(user, resort, role_id) response_data = get_user_resort_combo( user.user_pk, ('resort_id', 'resort_name', 'map_kml', 'map_type', 'report_form', 'unit_format', 'timezone', 'map_lat', 'map_lng', 'resort_logo', 'datetime_format', 'resort_controlled_substances', 'resort_asset_management')) return Response(response_data, status=200)