Skip to content
Open
Show file tree
Hide file tree
Changes from 6 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
109 changes: 109 additions & 0 deletions backend/market/management/commands/seed_offers.py
Comment thread
LautaroJBeck marked this conversation as resolved.
Outdated
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
from decimal import Decimal
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This file is a script to artificially add offers to one listing

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Ok maybe make a comment in the file. Also not sure seed_offer is the best name


from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.utils import timezone

from market.models import Category, Item, Listing, Offer


User = get_user_model()


class Command(BaseCommand):
help = "Seed a listing with two pending offers for testing"

def add_arguments(self, parser):
parser.add_argument(
"--listing-id",
type=int,
default=None,
help="Add offers to an existing listing by ID instead of creating a new one",
)

def handle(self, *args, **options):
alice, _ = User.objects.get_or_create(
username="alice",
defaults={
"email": "alice@example.com",
"first_name": "Alice",
"last_name": "Johnson",
"phone_number": "+12155551234",
"phone_verified": True,
},
)
alice.set_password("testpassword123")
alice.save()

bob, _ = User.objects.get_or_create(
username="bob",
defaults={
"email": "bob@example.com",
"first_name": "Bob",
"last_name": "Williams",
"phone_number": "+12155555678",
"phone_verified": True,
},
)
bob.set_password("testpassword123")
bob.save()

self.stdout.write(self.style.SUCCESS("Buyers ready: Alice Johnson, Bob Williams"))

listing_id = options["listing_id"]
if listing_id:
try:
listing = Listing.objects.get(pk=listing_id)
except Listing.DoesNotExist:
self.stdout.write(self.style.ERROR(f"Listing with id={listing_id} not found"))
return
self.stdout.write(self.style.SUCCESS(f"Using existing listing: {listing.title} (id={listing.id})"))
else:
seller, _ = User.objects.get_or_create(
username="lautaro",
defaults={
"email": "lautaro@example.com",
"first_name": "Lautaro",
"last_name": "Beck",
},
)
seller.set_password("testpassword123")
seller.save()
self.stdout.write(self.style.SUCCESS(f"Seller ready: {seller.get_full_name()}"))

category, _ = Category.objects.get_or_create(name="Furniture")
listing = Item.objects.create(
seller=seller,
title="New offer",
description="ASDFASFAFS",
price=Decimal("12312.00"),
negotiable=True,
expires_at=timezone.now() + timezone.timedelta(days=60),
condition=Item.Condition.GOOD,
category=category,
)
self.stdout.write(self.style.SUCCESS(f"Created listing: {listing.title}"))

_, created_alice = Offer.objects.get_or_create(
user=alice,
listing=listing,
defaults={
"offered_price": Decimal("40.00"),
"message": "Would you take $40? I can pick up today.",
},
)

_, created_bob = Offer.objects.get_or_create(
user=bob,
listing=listing,
defaults={
"offered_price": Decimal("45.00"),
"message": "Interested! Is the price negotiable?",
},
)

new_count = sum([created_alice, created_bob])
skipped = 2 - new_count

self.stdout.write(self.style.SUCCESS(f"Created {new_count} offers, skipped {skipped} (already existed)"))
self.stdout.write(self.style.SUCCESS(f"\nDone! Offers added to listing id={listing.id}"))
26 changes: 26 additions & 0 deletions backend/market/migrations/0005_offer_status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Generated by Django 5.0.2 on 2026-03-27 21:34

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("market", "0004_rename_address_sublet_street_address_and_more"),
]

operations = [
migrations.AddField(
model_name="offer",
name="status",
field=models.CharField(
choices=[
("pending", "Pending"),
("accepted", "Accepted"),
("rejected", "Rejected"),
],
default="pending",
max_length=10,
),
),
]
8 changes: 8 additions & 0 deletions backend/market/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ class User(AbstractUser):


class Offer(models.Model):
class Status(models.TextChoices):
PENDING = "pending", "Pending"
ACCEPTED = "accepted", "Accepted"
REJECTED = "rejected", "Rejected"

class Meta:
constraints = [
models.UniqueConstraint(
Expand All @@ -37,6 +42,9 @@ class Meta:
max_digits=10, decimal_places=2, validators=[MinValueValidator(0)]
)
message = models.TextField(max_length=500, blank=True)
status = models.CharField(
max_length=10, choices=Status.choices, default=Status.PENDING
)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
Expand Down
9 changes: 7 additions & 2 deletions backend/market/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,19 @@ def has_object_permission(self, request, view, obj):

class OfferOwnerPermission(permissions.BasePermission):
"""
Custom permission to allow owner of an offer to delete it.
- GET: offer owner can view offers on their listing
- DELETE: offer owner can delete their own offer
- PATCH: offer owner can update offer status
"""

def has_permission(self, request, view):
return request.user.is_authenticated

def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS: # GET
if request.method in permissions.SAFE_METHODS:
return obj.listing.seller == request.user

if request.method in ("PATCH", "PUT"):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

you can prob combine these 2 conditions since they are doing the same thing

return obj.listing.seller == request.user

return obj.user == request.user
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
if request.method in permissions.SAFE_METHODS:
return obj.listing.seller == request.user
if request.method in ("PATCH", "PUT"):
return obj.listing.seller == request.user
return obj.user == request.user
return obj.listing.seller == request.user

27 changes: 25 additions & 2 deletions backend/market/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,37 @@ class OfferSerializer(ModelSerializer):

class Meta:
model = Offer
fields = ["id", "user", "listing", "offered_price", "message", "created_at"]
read_only_fields = ["id", "created_at", "user"]
fields = [
"id",
"user",
"listing",
"offered_price",
"message",
"status",
"created_at",
]
read_only_fields = ["id", "created_at", "user", "status"]

def create(self, validated_data):
validated_data["user"] = self.context["request"].user
return super().create(validated_data)


class OfferStatusSerializer(ModelSerializer):
class Meta:
model = Offer
fields = ["id", "status"]
read_only_fields = ["id"]

def validate_status(self, value):
valid_statuses = [choice[0] for choice in Offer.Status.choices]
if value not in valid_statuses:
raise ValidationError(
f"Invalid status. Must be one of: {', '.join(valid_statuses)}"
)
return value


# Create/Update Image Serializer
class ListingImageSerializer(ModelSerializer):
image = ImageField(write_only=True, required=False, allow_null=True)
Expand Down
5 changes: 4 additions & 1 deletion backend/market/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
OffersReceived,
Tags,
UserFavorites,
change_offer_status,
get_current_user,
get_phone_status,
send_verification_code,
Expand Down Expand Up @@ -46,9 +47,11 @@
# post: create an offer for an listing
# delete: delete an offer for an listing
path(
"listings/<listing_id>/offers/",
"listings/<int:listing_id>/offers/",
Offers.as_view({"get": "list", "post": "create", "delete": "destroy"}),
),
# Update offer status (PATCH)
path("offers/<int:offer_id>/", change_offer_status, name="offer-status"),
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Make it clear that this is for modifying status by adding /status at the end (like how you did for details)

# Image Creation
path("listings/<listing_id>/images/", CreateImages.as_view()),
# Image Deletion
Expand Down
28 changes: 27 additions & 1 deletion backend/market/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
ListingSerializerList,
ListingSerializerPublic,
OfferSerializer,
OfferStatusSerializer,
TagSerializer,
UserSerializer,
)
Expand Down Expand Up @@ -192,6 +193,11 @@ def retrieve(self, request, *args, **kwargs):
serializer = serializer_class(instance)
return Response(serializer.data)

def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return Response({"deleted": True}, status=status.HTTP_200_OK)


# TODO: This doesn't use CreateAPIView's functionality
# since we overrode the create method.
Expand Down Expand Up @@ -300,6 +306,11 @@ class Offers(viewsets.ModelViewSet):
serializer_class = OfferSerializer
pagination_class = PageSizeOffsetPagination

def get_serializer_class(self):
if self.action in ["partial_update", "update"]:
return OfferStatusSerializer
return OfferSerializer

def get_queryset(self):
if Listing.objects.filter(pk=int(self.kwargs["listing_id"])).exists():
return Offer.objects.filter(
Expand Down Expand Up @@ -332,7 +343,7 @@ def destroy(self, request, *args, **kwargs):
obj = get_object_or_404(queryset, **filter)
self.check_object_permissions(self.request, obj)
self.perform_destroy(obj)
return Response(status=status.HTTP_204_NO_CONTENT)
return Response({"deleted": True}, status=status.HTTP_204)

def list(self, request, *args, **kwargs):
if not Listing.objects.filter(pk=int(self.kwargs["listing_id"])).exists():
Expand All @@ -342,6 +353,21 @@ def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)


@api_view(["PATCH"])
@permission_classes([OfferOwnerPermission | IsSuperUser])
def change_offer_status(request, offer_id):
offer = get_object_or_404(Offer, pk=offer_id)
if not any(
perm.has_object_permission(request, None, offer)
for perm in [OfferOwnerPermission(), IsSuperUser()]
):
raise exceptions.PermissionDenied()
serializer = OfferStatusSerializer(offer, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(OfferSerializer(offer).data)

Comment on lines 362 to +365
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

3 things:

  1. Once you address my feedback for the api url, these should no longer exist. Instead, define a single view. Might want to refer to UpdateAPIView (check docs online)
  2. You are modifying the status field on the offer but status doesnt even exist in the offer model. You need to edit models.py to add status field in the Offer class (it might be bneneficial to add Status choices like
class Status(models.TextChoices):
    PENDING = "pending", "Pending"                        
    ACCEPTED = "accepted", "Accepted"                   
    REJECTED = "rejected", "Rejected"     

Remember, once you make model changes you need to make migration files, then commit that to version control
3.

if offer.listing.seller != request.user:
    raise exceptions.PermissionDenied("Only the listing owner can accept offers.")

This technically worksd but it breaks the project's pattern. Every other view delegates authorization to a permission class in permissions.py. Instead, go to permissions.py. As a side note, it's a much better practice to handle authorization logic in one place than being mixed into view logic. Its an application of separation of concern/signle responsibilitry principle where each permission class has one job and views have one job (handling req/resp logic). Refer to other permission classes and how they are used.


@api_view(["POST"])
@permission_classes([IsAuthenticated])
def send_verification_code(request):
Expand Down
17 changes: 14 additions & 3 deletions frontend/app/items/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import { ListingDetail } from "@/components/listings/detail/ListingDetail";
import { getListingOrNotFound } from "@/lib/actions";
import { getCurrentUser, getListingOrNotFound, getOffersForListing } from "@/lib/actions";

export default async function ItemPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const item = await getListingOrNotFound(id);
const [item, currentUser] = await Promise.all([getListingOrNotFound(id), getCurrentUser()]);
const isOwner = currentUser?.id === item.seller.id;
const offersResponse = isOwner ? await getOffersForListing(item.id) : null;
const offers = offersResponse?.results ?? [];

return <ListingDetail listing={item} initialIsFavorited={item.is_favorited ?? false} />;
return (
<ListingDetail
listing={item}
initialIsFavorited={item.is_favorited ?? false}
offers={offers}
offersMode={isOwner ? "received" : "made"}
isOwner={isOwner}
/>
);
}
17 changes: 14 additions & 3 deletions frontend/app/sublets/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import { ListingDetail } from "@/components/listings/detail/ListingDetail";
import { getListingOrNotFound } from "@/lib/actions";
import { getCurrentUser, getListingOrNotFound, getOffersForListing } from "@/lib/actions";

export default async function SubletPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const sublet = await getListingOrNotFound(id);
const [sublet, currentUser] = await Promise.all([getListingOrNotFound(id), getCurrentUser()]);
const isOwner = currentUser?.id === sublet.seller.id;
const offersResponse = isOwner ? await getOffersForListing(sublet.id) : null;
const offers = offersResponse?.results ?? [];

return <ListingDetail listing={sublet} initialIsFavorited={sublet.is_favorited ?? false} />;
return (
<ListingDetail
listing={sublet}
initialIsFavorited={sublet.is_favorited ?? false}
offers={offers}
offersMode={isOwner ? "received" : "made"}
isOwner={isOwner}
/>
);
}
6 changes: 6 additions & 0 deletions frontend/components/listings/detail/ListingActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ interface Props {
listingPrice: number;
listingOwnerLabel: string;
priceLabel?: string;
isOwner?: boolean;
}

type ModalState = "none" | "phone-input" | "verification" | "offer";
Expand All @@ -23,6 +24,7 @@ export const ListingActions = ({
listingPrice,
priceLabel,
listingOwnerLabel,
isOwner = false,
}: Props) => {
const [modalState, setModalState] = useState<ModalState>("none");
const [pendingPhoneNumber, setPendingPhoneNumber] = useState<string>("");
Expand All @@ -35,6 +37,10 @@ export const ListingActions = ({
queryFn: getPhoneStatus,
});

if (isOwner) {
return null;
}

const handleMakeOfferClick = () => {
if (!phoneStatus) return;

Expand Down
Loading
Loading