Skip to content
Merged
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
3 changes: 2 additions & 1 deletion src/etools/applications/last_mile/admin_panel/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ class LocationsFilter(filters.FilterSet):
country = filters.CharFilter(method='filter_country', label='Country')
partner_organization = filters.CharFilter(method='filter_partner_organization', label='Partner Organization Name/Number')
primary_type = filters.CharFilter(field_name="poi_type__name", lookup_expr="icontains")
secondary_type = filters.CharFilter(field_name="secondary_type__name", lookup_expr="icontains")
is_active = filters.BooleanFilter(field_name="is_active")
latitude = filters.CharFilter(method='filter_latitude', label='Latitude')
longitude = filters.CharFilter(method='filter_longitude', label='Longitude')
Expand Down Expand Up @@ -125,7 +126,7 @@ def filter_longitude(self, queryset, name, value):

class Meta:
model = PointOfInterest
fields = ('name', 'p_code', 'primary_type', 'is_active')
fields = ('name', 'p_code', 'primary_type', 'is_active', 'secondary_type')


class UserLocationsFilter(filters.FilterSet):
Expand Down
23 changes: 15 additions & 8 deletions src/etools/applications/last_mile/admin_panel/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,16 +298,21 @@ def to_representation(self, instance):


class PointOfInterestCustomSerializer(serializers.ModelSerializer):
parent = serializers.PrimaryKeyRelatedField(
queryset=Location.objects.all(),
)
partner_organizations = serializers.PrimaryKeyRelatedField(
queryset=PartnerOrganization.objects.all(),
many=True,
)
poi_type = serializers.PrimaryKeyRelatedField(
queryset=models.PointOfInterestType.objects.all(),
)

secondary_type = serializers.PrimaryKeyRelatedField(
queryset=models.PointOfInterestType.objects.all(),
required=False,
allow_empty=True,
allow_null=True
)

point = GeometryField(required=False)

created_by = serializers.HiddenField(
Expand All @@ -320,7 +325,7 @@ class PointOfInterestCustomSerializer(serializers.ModelSerializer):

class Meta:
model = models.PointOfInterest
fields = ('name', 'parent', 'p_code', 'partner_organizations', 'poi_type', 'point', 'created_by', 'is_active')
fields = ('name', 'partner_organizations', 'poi_type', 'secondary_type', 'point', 'created_by', 'is_active')


class SimplePartnerOrganizationSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -349,6 +354,7 @@ def to_representation(self, instance):
class PointOfInterestAdminSerializer(serializers.ModelSerializer):
partner_organizations = SimplePartnerOrganizationSerializer(many=True, read_only=True)
poi_type = PointOfInterestTypeSerializer(read_only=True)
secondary_type = PointOfInterestTypeSerializer(read_only=True)
country = serializers.CharField(read_only=True)
region = serializers.CharField(read_only=True)
district = serializers.CharField(read_only=True)
Expand Down Expand Up @@ -693,7 +699,7 @@ def get_description(self, obj):

class Meta:
model = models.Item
fields = ('id', 'material', 'quantity', 'modified', 'uom', 'batch_id', 'description', "transfer_name", "base_uom", "base_quantity")
fields = ('id', 'material', 'quantity', 'modified', 'uom', 'batch_id', 'description', "transfer_name", "base_uom", "base_quantity", "expiry_date")


class TransferItemSerializer(serializers.ModelSerializer):
Expand All @@ -715,6 +721,7 @@ class TransferItemDetailSerializer(serializers.Serializer):
)
quantity = serializers.IntegerField(required=True)
uom = serializers.CharField(required=True)
expiry_date = serializers.DateField(allow_null=True, required=False)


class TransferItemCreateSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -890,9 +897,9 @@ def to_representation(self, instance):
if instance.parent.FIRST_ADMIN_LEVEL in parent_locations:
data['country'] = LocationWithBordersSerializer(parent_locations[instance.parent.FIRST_ADMIN_LEVEL]).data
if instance.parent.SECOND_ADMIN_LEVEL in parent_locations:
data['region'] = LocationWithBordersSerializer(parent_locations[instance.parent.FIRST_ADMIN_LEVEL]).data
data['region'] = LocationWithBordersSerializer(parent_locations[instance.parent.SECOND_ADMIN_LEVEL]).data
if instance.parent.THIRD_ADMIN_LEVEL in parent_locations:
data['district'] = LocationWithBordersSerializer(parent_locations[instance.parent.FIRST_ADMIN_LEVEL]).data
data['district'] = LocationWithBordersSerializer(parent_locations[instance.parent.THIRD_ADMIN_LEVEL]).data
return data

class Meta:
Expand Down Expand Up @@ -938,7 +945,7 @@ def update(self, validated_data, approver_user):
class BulkReviewPointOfInterestSerializer(serializers.Serializer):
status = serializers.ChoiceField(choices=PointOfInterestSerializer.Meta.model.ApprovalStatus.choices)
points_of_interest = serializers.PrimaryKeyRelatedField(queryset=models.PointOfInterest.objects.all(), many=True, write_only=True)
review_notes = serializers.CharField(required=False)
review_notes = serializers.CharField(required=False, allow_blank=True, allow_null=True)

def validate_status(self, value):
self.admin_validator = AdminPanelValidator()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def create_stock_management(self, validated_data):
quantity=item.get('quantity'),
uom=item.get('uom'),
batch_id=item.get('item_name'),
expiry_date=item.get('expiration_date'),
expiry_date=item.get('expiration_date') or item.get('expiry_date'),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why two different field names??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because we have 2 separate functions that are using this service. The expirty_date come directly from the UI and expiration_date is from BE

)
)
models.Item.objects.bulk_create(items_to_create)
Expand Down
9 changes: 7 additions & 2 deletions src/etools/applications/last_mile/admin_panel/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ class LocationsViewSet(mixins.ListModelMixin,
queryset = models.PointOfInterest.all_objects.select_related(
"parent",
"poi_type",
"secondary_type",
"parent__parent",
"parent__parent__parent",
"parent__parent__parent__parent"
Expand All @@ -270,6 +271,7 @@ class LocationsViewSet(mixins.ListModelMixin,
ordering_fields = [
'id',
'poi_type',
'secondary_type',
'country',
'p_code',
'description',
Expand Down Expand Up @@ -312,7 +314,10 @@ def list_export_csv(self, request, *args, **kwargs):
LocationsCSVExporter().generate_csv_data(queryset=queryset, serializer_class=self.get_serializer_class(), only_locations=only_locations),
content_type='text/csv'
)
response['Content-Disposition'] = f'attachment; filename="locations_{timezone.now().date()}.csv"'
if only_locations:
response['Content-Disposition'] = f'attachment; filename="locations_{timezone.now()}.csv"'
else:
response['Content-Disposition'] = f'attachment; filename="stock_management_locations_{timezone.now()}.csv"'
return response

@action(detail=False, methods=['post'], url_path='import/xlsx')
Expand Down Expand Up @@ -342,7 +347,7 @@ class PointOfInterestsLightViewSet(mixins.ListModelMixin,
serializer_class = PointOfInterestLightSerializer
pagination_class = DynamicPageNumberPagination

queryset = models.PointOfInterest.objects.select_related("parent", "poi_type").prefetch_related('partner_organizations').all().order_by('id')
queryset = models.PointOfInterest.all_objects.select_related("parent", "poi_type", "parent__parent", "parent__parent__parent", "parent__parent__parent__parent").prefetch_related('partner_organizations').all().order_by('id')


class UserLocationsViewSet(mixins.ListModelMixin,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated by Django 4.2.3 on 2025-10-15 18:39

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('last_mile', '0013_auditconfiguration_itemauditlog_and_more'),
]

operations = [
migrations.AddField(
model_name='pointofinterest',
name='secondary_type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='secondary_points_of_interest', to='last_mile.pointofinteresttype', verbose_name='Secondary Type'),
),
]
27 changes: 27 additions & 0 deletions src/etools/applications/last_mile/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,13 @@ class ApprovalStatus(models.TextChoices):
on_delete=models.SET_NULL,
null=True
)
secondary_type = models.ForeignKey(
PointOfInterestType,
verbose_name=_("Secondary Type"),
related_name='secondary_points_of_interest',
on_delete=models.SET_NULL,
null=True
)
other = models.JSONField(verbose_name=_("Other Details"), null=True, blank=True)
point = PointField(verbose_name=_("Point"), null=True, blank=True)

Expand Down Expand Up @@ -182,7 +189,27 @@ def get_parent_location(point):
def is_warehouse(self):
return self.poi_type.category.lower() == 'warehouse' if self.poi_type else False

def _autogenerate_pcode(self):
tenant_name = connection.schema_name

if tenant_name:
start_p_code = tenant_name[:3]
else:
start_p_code = 'pub'

last_location = PointOfInterest.all_objects.only('p_code').order_by('-created').first()

if last_location and last_location.p_code.startswith(start_p_code):
last_p_code = int(last_location.p_code.split(start_p_code)[-1])
next_p_code = last_p_code + 1
else:
next_p_code = 1

return f"{start_p_code}{str(next_p_code).zfill(9)}"

def save(self, **kwargs):
if not self.p_code:
self.p_code = self._autogenerate_pcode()
if not self.parent_id:
self.parent = self.get_parent_location(self.point)
assert self.parent_id, 'Unable to find location for {}'.format(self.point)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ def test_create_location_success(self):
"p_code": "P001",
"partner_organizations": [self.partner.pk],
"poi_type": self.poi_type.pk,
"secondary_type": self.poi_type.pk,
"point": {"type": "Point", "coordinates": [43.7, 25.6]},
}
response = self.forced_auth_req(
Expand All @@ -287,10 +288,10 @@ def test_create_location_missing_required_field(self):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_create_location_invalid_parent(self):
def test_create_location_without_parent(self):
payload = {
"name": "Invalid Parent",
"parent": 9999, # non-existent parent
"parent": 9999, # non-existent parent -> Parent is set based on the coordinates
"p_code": "P003",
"partner_organizations": [self.partner.pk],
"poi_type": self.poi_type.pk,
Expand All @@ -299,7 +300,7 @@ def test_create_location_invalid_parent(self):
response = self.forced_auth_req(
"post", self.url, data=payload, user=self.partner_staff
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)

def test_create_location_invalid_partner_organizations(self):
payload = {
Expand Down Expand Up @@ -414,7 +415,7 @@ def test_export_csv_success(self):
self.assertEqual(response.status_code, status.HTTP_200_OK)
content_disposition = response.headers.get("Content-Disposition", "")
self.assertTrue(
content_disposition.startswith('attachment; filename="locations_')
content_disposition.startswith('attachment; filename="stock_management_locations_')
)

def test_export_csv(self):
Expand Down Expand Up @@ -828,11 +829,10 @@ def test_create_location_with_extreme_coordinates(self):
f"Failed for coordinates: {coords}",
)

def test_create_location_with_duplicate_pcode(self):
def test_create_locations_with_correct_autogenerated_p_codes(self):
payload1 = {
"name": "First Location",
"parent": self.parent_location.pk,
"p_code": "DUP001",
"partner_organizations": [self.partner.pk],
"poi_type": self.poi_type.pk,
"point": {"type": "Point", "coordinates": [43.7, 25.6]},
Expand All @@ -845,15 +845,19 @@ def test_create_location_with_duplicate_pcode(self):
payload2 = {
"name": "Second Location",
"parent": self.parent_location.pk,
"p_code": "DUP001", # Same p_code
"partner_organizations": [self.partner.pk],
"poi_type": self.poi_type.pk,
"point": {"type": "Point", "coordinates": [44.7, 26.6]},
}
response2 = self.forced_auth_req(
"post", self.url, data=payload2, user=self.partner_staff
)
self.assertEqual(response2.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response2.status_code, status.HTTP_201_CREATED)
last_2_pois = models.PointOfInterest.objects.order_by("-created")[:2]
first_poi = last_2_pois[1]
second_poi = last_2_pois[0]
self.assertEqual(first_poi.p_code, "tes000000001")
self.assertEqual(second_poi.p_code, "tes000000002")

def test_create_location_with_multiple_partner_organizations(self):
payload = {
Expand Down
2 changes: 1 addition & 1 deletion src/etools/applications/last_mile/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class PointOfInterestViewSet(POIQuerysetMixin, ModelViewSet):

def get_queryset(self):
return self.get_poi_queryset(exclude_partner_prefetch=True).only(
'parent__name', 'p_code', 'name', 'is_active', 'description', 'poi_type', 'status', 'created_on', 'approved_on', 'review_notes', 'created_by_id', 'approved_by_id'
'parent__name', 'p_code', 'name', 'is_active', 'description', 'poi_type', 'secondary_type', 'status', 'created_on', 'approved_on', 'review_notes', 'created_by_id', 'approved_by_id'
)

@action(detail=True, methods=['post'], url_path='upload-waybill',
Expand Down