Skip to content

Commit

Permalink
Remove unnecessary comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Winston-Hsiao committed Nov 18, 2024
1 parent cb2586d commit 3153354
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 41 deletions.
1 change: 0 additions & 1 deletion frontend/src/components/pages/SellerOnboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export default function SellerOnboarding() {

if (data?.account_id) {
setConnectedAccountId(data.account_id);
// Refresh user data to get updated stripe connect account id
await auth.fetchCurrentUser();
}
} catch (error) {
Expand Down
12 changes: 1 addition & 11 deletions store/app/crud/orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,26 +88,16 @@ async def update_order(self, order_id: str, update_data: OrderDataUpdate) -> Ord
if not order:
raise ItemNotFoundError("Order not found")

# Create a dict of current order data
current_data = order.model_dump()

# Convert TypedDict to regular dict
update_dict = dict(update_data) # Convert TypedDict to regular dict

# Update with new data
update_dict = dict(update_data)
current_data.update(update_dict)

try:
# Validate the updated data
Order(**current_data)
except ValidationError as e:
# If validation fails, raise an error
raise ValueError(f"Invalid update data: {str(e)}")

# If validation passes, update the order
await self._update_item(order_id, Order, update_dict)

# Fetch and return the updated order
updated_order = await self.get_order(order_id)
if not updated_order:
raise ItemNotFoundError("Updated order not found")
Expand Down
16 changes: 7 additions & 9 deletions store/app/crud/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import logging
import random
import string
import time
import warnings
from typing import Any, Literal, Optional, overload

Expand Down Expand Up @@ -292,23 +293,20 @@ async def generate_unique_username(self, base: str) -> str:
return username

async def update_stripe_connect_status(self, user_id: str, account_id: str, is_completed: bool) -> User:
"""Updates the user's Stripe Connect status."""
user = await self.get_user(user_id, throw_if_missing=True)
user.set_stripe_connect(account_id, is_completed)

stripe_connect = UserStripeConnect(
account_id=account_id,
onboarding_completed=is_completed,
)
updates = {
"stripe_connect": {
"account_id": account_id,
"onboarding_completed": is_completed,
}
"stripe_connect": stripe_connect.model_dump(),
"updated_at": int(time.time()),
}
return await self.update_user(user_id, updates)

async def set_content_manager(self, user_id: str, is_content_manager: bool) -> User:
user = await self.get_user(user_id, throw_if_missing=True)
if user.permissions is None:
user.permissions = set()

if is_content_manager:
user.permissions.add("is_content_manager")
else:
Expand Down
20 changes: 0 additions & 20 deletions store/app/routers/stripe.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,10 @@
f"{settings.site.homepage}/order/final-payment/cancel?session_id={{CHECKOUT_SESSION_ID}}"
)

# Configure logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


# Add a console handler if one doesn't exist
if not logger.handlers:
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
Expand Down Expand Up @@ -82,7 +80,6 @@ async def refund_payment_intent(
else refund_request.cancel_reason.reason
)

# Create a Refund for payment_intent_id with the order amount
refund = stripe.Refund.create(
payment_intent=payment_intent_id,
amount=amount,
Expand All @@ -91,13 +88,11 @@ async def refund_payment_intent(
)
logger.info("Refund created: %s", refund.id)

# Make sure order exists
order = await crud.get_order(order_id)
if order is None or order.user_id != user.id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Order not found")
logger.info("Found order id: %s", order.id)

# Update order status
order_data: OrderDataUpdate = {
"stripe_refund_id": refund.id,
"status": ("refunded" if (refund.status and refund.status) == "succeeded" else order.status),
Expand All @@ -114,7 +109,6 @@ async def refund_payment_intent(

@router.post("/webhook")
async def stripe_webhook(request: Request, crud: Crud = Depends(Crud.get)) -> dict[str, str]:
"""Handle direct account webhooks (non-Connect events)."""
payload = await request.body()
sig_header = request.headers.get("stripe-signature")

Expand All @@ -138,21 +132,18 @@ async def stripe_webhook(request: Request, crud: Crud = Depends(Crud.get)) -> di

@router.post("/connect/webhook")
async def stripe_connect_webhook(request: Request, crud: Crud = Depends(Crud.get)) -> dict[str, str]:
"""Handle Connect account webhooks."""
payload = await request.body()
sig_header = request.headers.get("stripe-signature")

try:
event = stripe.Webhook.construct_event(payload, sig_header, settings.stripe.connect_webhook_secret)
logger.info("Connect webhook event type: %s", event["type"])

# Get the connected account ID
connected_account_id = event.get("account")
if not connected_account_id:
logger.warning("No connected account ID in webhook event")
return {"status": "skipped"}

# Handle Connect-specific events
if event["type"] == "account.updated":
account = event["data"]["object"]
capabilities = account.get("capabilities", {})
Expand All @@ -166,7 +157,6 @@ async def stripe_connect_webhook(request: Request, crud: Crud = Depends(Crud.get

if is_fully_onboarded:
try:
# Get user_id from account metadata
user_id = account.get("metadata", {}).get("user_id")
if user_id:
await crud.update_stripe_connect_status(user_id, account["id"], is_completed=True)
Expand Down Expand Up @@ -304,22 +294,18 @@ async def create_checkout_session(
) -> CreateCheckoutSessionResponse:
async with crud:
try:
# Get the listing
listing = await crud.get_listing(request.listing_id)
if not listing or not listing.price_amount:
logger.error(f"Listing not found or has no price: {request.listing_id}")
raise HTTPException(status_code=404, detail="Listing not found or has no price")

# Get seller details
seller = await crud.get_user(listing.user_id)
if not seller or not seller.stripe_connect or not seller.stripe_connect.onboarding_completed:
raise HTTPException(status_code=400, detail="Seller not found or not connected to Stripe")

# Check if user is trying to buy their own listing
if seller.id == user.id:
raise HTTPException(status_code=400, detail="You cannot purchase your own listing")

# Calculate maximum quantity
max_quantity = 10
if listing.inventory_type == "finite" and listing.inventory_quantity is not None:
max_quantity = min(listing.inventory_quantity, 10)
Expand Down Expand Up @@ -402,22 +388,19 @@ async def create_checkout_session(
else:
# Regular payment mode
if not listing.stripe_price_id and listing.stripe_product_id:
# Create a new price if one doesn't exist
price = stripe.Price.create(
unit_amount=listing.price_amount,
currency=listing.currency or "usd",
product=listing.stripe_product_id,
metadata={"listing_id": listing.id},
stripe_account=seller.stripe_connect.account_id,
)
# Update the listing with the new price ID
await crud.edit_listing(listing_id=listing.id, stripe_price_id=price.id)
listing.stripe_price_id = price.id

if listing.stripe_price_id is None:
raise HTTPException(status_code=400, detail="Price not configured")

# Calculate application fee
application_fee = int(listing.price_amount * 0.02) # 2% fee

checkout_params.update(
Expand Down Expand Up @@ -466,20 +449,17 @@ class ProductResponse(BaseModel):
@router.get("/get-product/{product_id}", response_model=ProductResponse)
async def get_product(product_id: str, crud: Annotated[Crud, Depends(Crud.get)]) -> ProductResponse:
try:
# First get the listing by stripe_product_id
listing = await crud.get_listing_by_stripe_product_id(product_id)
if not listing:
raise HTTPException(status_code=404, detail="Listing not found")

# Get the seller
seller = await crud.get_user(listing.user_id)
if not seller or not seller.stripe_connect:
raise HTTPException(status_code=400, detail="Seller not found or not connected to Stripe")

# Retrieve the product using the seller's connected account
product = stripe.Product.retrieve(product_id, stripe_account=seller.stripe_connect.account_id)

# Convert Stripe Product to our ProductResponse model
return ProductResponse(
id=product.id,
name=product.name,
Expand Down

0 comments on commit 3153354

Please sign in to comment.