Ejemplo n.º 1
0
class FacilityUpsertSerializer(serializers.ModelSerializer):
    """
    Use only for listing and upserting - Upsert based on name and district uniqueness
    """

    capacity = serializers.ListSerializer(child=FacilityCapacitySerializer(), source="facilitycapacity_set")
    location = PointField(required=False)
    district = serializers.IntegerField()

    class Meta:
        model = Facility
        fields = [
            "id",
            "name",
            "facility_type",
            "address",
            "district",
            "location",
            "oxygen_capacity",
            "phone_number",
            "capacity",
            "created_by",
        ]

    def validate_name(self, value):
        return str(value).strip().replace("  ", " ")

    def validate_phone_number(self, value):
        return str(value).strip().replace("  ", " ")

    def create(self, validated_data):
        raise NotImplementedError()

    def update(self, instance, validated_data):
        raise NotImplementedError()
Ejemplo n.º 2
0
    def list(self, request, format=None):

        if request.user.user_type < User.TYPE_VALUE_MAP["DistrictLabAdmin"]:
            return Response({}, status=status.HTTP_403_FORBIDDEN)

        possible_filter_params = ["state", "local_body", "district"]
        filter_params = {}
        for filter_query in possible_filter_params:
            if request.GET.get(filter_query, False):
                filter_params["facility__" + filter_query] = int(
                    request.GET[filter_query])

        capacity_objects = FacilityCapacity.objects.filter(
            **filter_params).select_related("facility", "facility__state",
                                            "facility__district",
                                            "facility__local_body")
        capacity_summary = {}
        for capacity_object in capacity_objects:
            facility_id = capacity_object.facility.id
            if facility_id not in capacity_summary:
                capacity_summary[facility_id] = FacilitySerializer(
                    capacity_object.facility).data
                capacity_summary[facility_id]["availability"] = []
            capacity_summary[facility_id]["availability"].append(
                FacilityCapacitySerializer(capacity_object).data)

        return Response(capacity_summary)
Ejemplo n.º 3
0
def FacilityCapacitySummary():
    capacity_objects = FacilityCapacity.objects.all().select_related(
        "facility", "facility__state", "facility__district",
        "facility__local_body")
    capacity_summary = {}
    current_date = localtime(now()).replace(hour=0,
                                            minute=0,
                                            second=0,
                                            microsecond=0)
    for capacity_object in capacity_objects:
        facility_id = capacity_object.facility.id
        if facility_id not in capacity_summary:
            capacity_summary[facility_id] = FacilitySerializer(
                capacity_object.facility).data
            capacity_summary[facility_id]["availability"] = []
        capacity_summary[facility_id]["availability"].append(
            FacilityCapacitySerializer(capacity_object).data)

    for i in list(capacity_summary.keys()):
        facility_summary_obj = None
        if FacilityRelatedSummary.objects.filter(
                s_type="FacilityCapacity",
                facility_id=i,
                created_date__gte=current_date).exists():
            facility_summary_obj = FacilityRelatedSummary.objects.get(
                s_type="FacilityCapacity",
                facility_id=i,
                created_date__gte=current_date)
        else:
            facility_summary_obj = FacilityRelatedSummary(
                s_type="FacilityCapacity", facility_id=i)
        facility_summary_obj.data = capacity_summary[i]
        facility_summary_obj.save()

    return True
Ejemplo n.º 4
0
class FacilityUpsertSerializer(serializers.ModelSerializer):
    """
    Use only for listing and upserting - Upsert based on name and district uniqueness
    """

    capacity = serializers.ListSerializer(child=FacilityCapacitySerializer(),
                                          source="facilitycapacity_set")
    location = PointField(required=False)

    class Meta:
        model = Facility
        fields = [
            "id",
            "name",
            "district",
            "facility_type",
            "address",
            "location",
            "oxygen_capacity",
            "phone_number",
            "capacity",
            "created_by",
        ]

    def validate_name(self, value):
        return str(value).strip().replace("  ", " ")

    def validate_phone_number(self, value):
        return str(value).strip().replace("  ", " ")

    def create(self, validated_data):
        capacities = validated_data.pop("facilitycapacity_set")
        facility = Facility.objects.filter(
            **{
                "name__iexact": validated_data["name"],
                "district": validated_data["district"],
            }).first()

        user = self.context["user"]
        if not facility:
            validated_data["created_by"] = user
            facility = Facility.objects.create(**validated_data)
        else:
            if facility.created_by != user and not user.is_superuser:
                raise PermissionDenied(f"{facility} is owned by another user")
            for k, v in validated_data.items():
                setattr(facility, k, v)
            facility.save()

        for ca in capacities:
            facility.facilitycapacity_set.update_or_create(
                room_type=ca["room_type"], defaults=ca)
        return facility

    def update(self, instance, validated_data):
        raise NotImplementedError()
Ejemplo n.º 5
0
def FacilityCapacitySummary():
    capacity_objects = FacilityCapacity.objects.all().select_related(
        "facility", "facility__state", "facility__district",
        "facility__local_body")
    capacity_summary = {}
    current_date = localtime(now()).replace(hour=0,
                                            minute=0,
                                            second=0,
                                            microsecond=0)

    for facility_obj in Facility.objects.all():
        # Calculate Actual Patients Discharged and Live in this Facility
        patients_in_facility = PatientRegistration.objects.filter(
            facility_id=facility_obj.id).select_related(
                "state", "district", "local_body")
        capacity_summary[facility_obj.id] = FacilitySerializer(
            facility_obj).data
        capacity_summary[facility_obj.id][
            "actual_live_patients"] = patients_in_facility.filter(
                is_active=True).count()
        discharge_patients = patients_in_facility.filter(is_active=False)
        capacity_summary[facility_obj.id][
            "actual_discharged_patients"] = discharge_patients.count()
        capacity_summary[facility_obj.id]["availability"] = []

    for capacity_object in capacity_objects:
        facility_id = capacity_object.facility.id
        if facility_id not in capacity_summary:
            capacity_summary[facility_id] = FacilitySerializer(
                capacity_object.facility).data
        if "availability" not in capacity_summary[facility_id]:
            capacity_summary[facility_id]["availability"] = []
        capacity_summary[facility_id]["availability"].append(
            FacilityCapacitySerializer(capacity_object).data)

    for i in capacity_summary:
        facility_summary_obj = None
        if FacilityRelatedSummary.objects.filter(
                s_type="FacilityCapacity",
                facility_id=i,
                created_date__gte=current_date).exists():
            facility_summary_obj = FacilityRelatedSummary.objects.get(
                s_type="FacilityCapacity",
                facility_id=i,
                created_date__gte=current_date)
        else:
            facility_summary_obj = FacilityRelatedSummary(
                s_type="FacilityCapacity", facility_id=i)
        facility_summary_obj.data = capacity_summary[i]
        facility_summary_obj.save()

    return True
Ejemplo n.º 6
0
class FacilityUpsertSerializer(serializers.ModelSerializer):
    """
    Use only for listing and upserting - Upsert based on name and district uniqueness
    """
    capacity = serializers.ListSerializer(child=FacilityCapacitySerializer(), source='facilitycapacity_set')

    class Meta:
        model = Facility
        fields = [
            "id",
            "name",
            "district",
            "facility_type",
            "address",
            "location",
            "oxygen_capacity",
            "phone_number",
            "capacity",
            "created_by"
        ]

    def validate_name(self, value):
        return str(value).strip().replace("  ", " ")

    def validate_phone_number(self, value):
        return str(value).strip().replace("  ", " ")

    def create(self, validated_data):
        capacities = validated_data.pop('facilitycapacity_set')
        facility = Facility.objects.filter(
            **{"name__iexact": validated_data['name'], "district": validated_data['district']}
        ).first()

        if not facility:
            facility = Facility.objects.create(**validated_data)
        else:
            for k, v in validated_data.items():
                setattr(facility, k, v)
            facility.save()

        for ca in capacities:
            facility.facilitycapacity_set.update_or_create(
                room_type=ca['room_type'],
                defaults=ca
            )
        return facility

    def update(self, instance, validated_data):
        raise NotImplementedError()
Ejemplo n.º 7
0
def FacilityCapacitySummary():
    capacity_objects = FacilityCapacity.objects.all().select_related(
        "facility", "facility__state", "facility__district",
        "facility__local_body")
    capacity_summary = {}
    for capacity_object in capacity_objects:
        facility_id = capacity_object.facility.id
        if facility_id not in capacity_summary:
            capacity_summary[facility_id] = FacilitySerializer(
                capacity_object.facility).data
            capacity_summary[facility_id]["availability"] = []
        capacity_summary[facility_id]["availability"].append(
            FacilityCapacitySerializer(capacity_object).data)

    for i in list(capacity_summary.keys()):
        FacilityRelatedSummary(s_type="FacilityCapacity",
                               facility_id=i,
                               data=capacity_summary[i]).save()

    return True
Ejemplo n.º 8
0
def FacilityCapacitySummary():
    capacity_objects = FacilityCapacity.objects.all().select_related(
        "facility", "facility__state", "facility__district",
        "facility__local_body")
    capacity_summary = {}
    current_date = localtime(now()).replace(hour=0,
                                            minute=0,
                                            second=0,
                                            microsecond=0)

    for facility_obj in Facility.objects.all():
        # Calculate Actual Patients Discharged and Live in this Facility
        patients_in_facility = PatientRegistration.objects.filter(
            facility_id=facility_obj.id).select_related(
                "state", "district", "local_body")
        capacity_summary[facility_obj.id] = FacilitySerializer(
            facility_obj).data
        capacity_summary[facility_obj.id][
            "actual_live_patients"] = patients_in_facility.filter(
                is_active=True).count()
        discharge_patients = patients_in_facility.filter(is_active=False)
        capacity_summary[facility_obj.id][
            "actual_discharged_patients"] = discharge_patients.count()
        capacity_summary[facility_obj.id]["availability"] = []

        temp_inventory_summary_obj = {}
        summary_objs = FacilityInventorySummary.objects.filter(
            facility_id=facility_obj.id)
        for summary_obj in summary_objs:
            burn_rate = FacilityInventoryBurnRate.objects.filter(
                facility_id=facility_obj.id,
                item_id=summary_obj.item.id).first()
            log_query = FacilityInventoryLog.objects.filter(
                facility_id=facility_obj.id,
                item_id=summary_obj.item.id,
                created_date__gte=current_date)
            start_log = log_query.order_by("created_date").first()
            end_log = log_query.order_by("-created_date").first()
            start_stock = summary_obj.quantity
            if start_log:
                start_stock = start_log.current_stock - start_log.quantity_in_default_unit
            end_stock = start_stock
            if end_log:
                end_stock = end_log.current_stock
            total_consumed = 0
            temp1 = log_query.filter(is_incoming=False).aggregate(
                Sum("quantity_in_default_unit"))
            if temp1:
                total_consumed = temp1["quantity_in_default_unit__sum"]
            total_added = 0
            temp2 = log_query.filter(is_incoming=True).aggregate(
                Sum("quantity_in_default_unit"))
            if temp2:
                total_added = temp2["quantity_in_default_unit__sum"]

            if burn_rate:
                burn_rate = burn_rate.burn_rate
            temp_inventory_summary_obj[summary_obj.item.id] = {
                "item_name":
                summary_obj.item.name,
                "stock":
                summary_obj.quantity,
                "unit":
                summary_obj.item.default_unit.name,
                "is_low":
                summary_obj.is_low,
                "burn_rate":
                burn_rate,
                "start_stock":
                start_stock,
                "end_stock":
                end_stock,
                "total_consumed":
                total_consumed,
                "total_added":
                total_added,
                "modified_date":
                summary_obj.modified_date.astimezone().isoformat(),
            }
        capacity_summary[
            facility_obj.id]["inventory"] = temp_inventory_summary_obj

    for capacity_object in capacity_objects:
        facility_id = capacity_object.facility.id
        if facility_id not in capacity_summary:
            capacity_summary[facility_id] = FacilitySerializer(
                capacity_object.facility).data
        if "availability" not in capacity_summary[facility_id]:
            capacity_summary[facility_id]["availability"] = []
        capacity_summary[facility_id]["availability"].append(
            FacilityCapacitySerializer(capacity_object).data)

    for i in capacity_summary:
        facility_summary_obj = None
        if FacilityRelatedSummary.objects.filter(
                s_type="FacilityCapacity",
                facility_id=i,
                created_date__gte=current_date).exists():
            facility_summary_obj = FacilityRelatedSummary.objects.get(
                s_type="FacilityCapacity",
                facility_id=i,
                created_date__gte=current_date)
        else:
            facility_summary_obj = FacilityRelatedSummary(
                s_type="FacilityCapacity", facility_id=i)
        facility_summary_obj.data = capacity_summary[i]
        facility_summary_obj.save()

    return True