Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add list and detail serializer to facility_asset module #1427

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions care/facility/api/serializers/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def update(self, instance, validated_data):


class AssetSerializer(ModelSerializer):
# TODO: Remove when issue #5492 is resolved
id = UUIDField(source="external_id", read_only=True)
status = ChoiceField(choices=Asset.StatusChoices, read_only=True)
asset_type = ChoiceField(choices=Asset.AssetTypeChoices)
Expand Down Expand Up @@ -306,3 +307,160 @@ class DummyAssetOperateResponseSerializer(Serializer):

class Meta:
fields = ("message", "result")


class AssetListSerializer(ModelSerializer):
id = UUIDField(source="external_id", read_only=True)
location_object = AssetLocationSerializer(source="current_location", read_only=True)

class Meta:
model = Asset
fields = ["id", "name", "asset_class", "is_working", "location_object"]
read_only_fields = TIMESTAMP_FIELDS


class AssetDetailSerializer(AssetListSerializer):
id = UUIDField(source="external_id", read_only=True)
status = ChoiceField(choices=Asset.StatusChoices, read_only=True)
asset_type = ChoiceField(choices=Asset.AssetTypeChoices)
location_object = AssetLocationSerializer(source="current_location", read_only=True)
location = UUIDField(write_only=True, required=True)
last_service = AssetServiceSerializer(read_only=True)
last_serviced_on = serializers.DateField(write_only=True, required=False)
note = serializers.CharField(write_only=True, required=False, allow_blank=True)

class Meta:
model = Asset
exclude = ("deleted", "external_id", "current_location")
read_only_fields = TIMESTAMP_FIELDS

def validate_qr_code_id(self, value):
value = value or None # treat empty string as null
UniqueValidator(
queryset=Asset.objects.filter(qr_code_id__isnull=False),
message="QR code already assigned",
)(value, self.fields.get("qr_code_id"))
return value

def validate(self, attrs):
user = self.context["request"].user
if "location" in attrs:
location = get_object_or_404(
AssetLocation.objects.filter(external_id=attrs["location"])
)

facilities = get_facility_queryset(user)
if not facilities.filter(id=location.facility.id).exists():
raise PermissionError()
del attrs["location"]
attrs["current_location"] = location

# validate that warraty date is not in the past
if warranty_amc_end_of_validity := attrs.get("warranty_amc_end_of_validity"):
# pop out warranty date if it is not changed
if (
self.instance
and self.instance.warranty_amc_end_of_validity
== warranty_amc_end_of_validity
):
del attrs["warranty_amc_end_of_validity"]

elif warranty_amc_end_of_validity < datetime.now().date():
raise ValidationError(
"Warranty/AMC end of validity cannot be in the past"
)

# validate that last serviced date is not in the future
if "last_serviced_on" in attrs and attrs["last_serviced_on"]:
if attrs["last_serviced_on"] > datetime.now().date():
raise ValidationError("Last serviced on cannot be in the future")

# only allow setting asset class on creation (or updation if asset class is not set)
if (
attrs.get("asset_class")
and self.instance
and self.instance.asset_class
and self.instance.asset_class != attrs["asset_class"]
):
raise ValidationError({"asset_class": "Cannot change asset class"})

return super().validate(attrs)

def create(self, validated_data):
last_serviced_on = validated_data.pop("last_serviced_on", None)
note = validated_data.pop("note", None)
with transaction.atomic():
asset_instance = super().create(validated_data)
if last_serviced_on or note:
asset_service = AssetService(
asset=asset_instance, serviced_on=last_serviced_on, note=note
)
asset_service.save()
asset_instance.last_service = asset_service
asset_instance.save(update_fields=["last_service"])
return asset_instance

def update(self, instance, validated_data):
user = self.context["request"].user
with transaction.atomic():
if validated_data.get("last_serviced_on") and (
not instance.last_service
or instance.last_service.serviced_on
!= validated_data.get(
"last_serviced_on", instance.last_service.serviced_on
)
or instance.last_service.note
!= validated_data.get("note", instance.last_service.note)
):
asset_service = AssetService(
asset=instance,
serviced_on=validated_data.get("last_serviced_on"),
note=validated_data.get("note"),
)
asset_service_initial_edit = AssetServiceEdit(
asset_service=asset_service,
edited_on=now(),
edited_by=user,
serviced_on=asset_service.serviced_on,
note=asset_service.note,
)
asset_service.save()
asset_service_initial_edit.save()
instance.last_service = asset_service

if (
"current_location" in validated_data
and instance.current_location != validated_data["current_location"]
):
if (
instance.current_location.facility.id
!= validated_data["current_location"].facility.id
):
raise ValidationError(
{"location": "Interfacility transfer is not allowed here"}
)
AssetTransaction(
from_location=instance.current_location,
to_location=validated_data["current_location"],
asset=instance,
performed_by=user,
).save()
updated_instance = super().update(instance, validated_data)
cache.delete(f"asset:{instance.external_id}")
return updated_instance


class PublicAssetDetailSerializer(AssetListSerializer):
id = UUIDField(source="external_id", read_only=True)
location_object = AssetLocationSerializer(source="current_location", read_only=True)

class Meta:
model = Asset
exclude = (
"description",
"asset_class",
"not_working_reason",
"qr_code_id",
"manufacturer",
"warranty_amc_end_of_validity",
)
17 changes: 13 additions & 4 deletions care/facility/api/viewsets/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@

from care.facility.api.serializers.asset import (
AssetAvailabilitySerializer,
AssetDetailSerializer,
AssetListSerializer,
AssetLocationSerializer,
AssetSerializer,
AssetServiceSerializer,
AssetTransactionSerializer,
DummyAssetOperateResponseSerializer,
DummyAssetOperateSerializer,
PublicAssetDetailSerializer,
UserDefaultAssetLocationSerializer,
)
from care.facility.models import (
Expand Down Expand Up @@ -154,8 +156,10 @@ def filter_is_permanent(self, queryset, _, value):


class AssetPublicViewSet(GenericViewSet):
queryset = Asset.objects.all()
serializer_class = AssetSerializer
queryset = Asset.objects.all().select_related(
"current_location", "current_location__facility"
)
serializer_class = PublicAssetDetailSerializer
lookup_field = "external_id"

def retrieve(self, request, *args, **kwargs):
Expand Down Expand Up @@ -195,7 +199,7 @@ class AssetViewSet(
.select_related("current_location", "current_location__facility")
.order_by("-created_date")
)
serializer_class = AssetSerializer
serializer_class = AssetDetailSerializer
lookup_field = "external_id"
filter_backends = (filters.DjangoFilterBackend, drf_filters.SearchFilter)
search_fields = ["name", "serial_number", "qr_code_id"]
Expand All @@ -220,6 +224,11 @@ def get_queryset(self):
)
return queryset

def get_serializer_class(self):
if self.action == "list":
return AssetListSerializer
return self.serializer_class

def destroy(self, request, *args, **kwargs):
user = self.request.user
if user.user_type >= User.TYPE_VALUE_MAP["DistrictAdmin"]:
Expand Down
Loading