Song commited on
Commit
9f487cc
·
1 Parent(s): fa5c121
Files changed (3) hide show
  1. app.py +20 -4
  2. schemas.py +1 -1
  3. stripe_service.py +23 -11
app.py CHANGED
@@ -388,9 +388,12 @@ async def create_order_endpoint(
388
  db: AsyncSession = Depends(get_session)
389
  ):
390
  """Create a new food order and initiate Stripe checkout."""
 
 
391
  try:
392
  # Get user's profile
393
  profiles = await get_profiles_by_user(db, current_user.user_id)
 
394
  if not profiles:
395
  raise HTTPException(
396
  status_code=status.HTTP_400_BAD_REQUEST,
@@ -398,19 +401,27 @@ async def create_order_endpoint(
398
  )
399
 
400
  profile = profiles[0]
 
401
 
402
  # Create order in database
 
403
  order = await create_order(db, order_data, profile.id)
 
404
 
405
  # Get user's email - prefer frontend-provided email, fall back to authenticated user's email
406
  user_email = order_data.customer_email or current_user.email
 
407
 
408
  # Create Stripe checkout session with user's email
 
409
  checkout_url = create_checkout_session_for_order(order, customer_email=user_email)
 
410
 
411
  # Update order with Stripe session ID
412
  from crud import update_order_status
413
- await update_order_status(db, order.id, "pending", checkout_url.split('/')[-1])
 
 
414
 
415
  return {
416
  "id": order.id,
@@ -418,16 +429,21 @@ async def create_order_endpoint(
418
  "items": order.items,
419
  "total_amount": order.total_amount,
420
  "status": "pending",
421
- "stripe_session_id": checkout_url.split('/')[-1],
422
  "created_at": order.created_at,
423
  "updated_at": order.updated_at,
424
  "checkout_url": checkout_url
425
  }
 
 
426
  except Exception as e:
427
- logger.error(f"Error creating order: {str(e)}")
 
 
 
428
  raise HTTPException(
429
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
430
- detail="Failed to create order"
431
  )
432
 
433
 
 
388
  db: AsyncSession = Depends(get_session)
389
  ):
390
  """Create a new food order and initiate Stripe checkout."""
391
+ logger.info(f"[ORDER_DEBUG] Received order request from user: {current_user.user_id}")
392
+ logger.info(f"[ORDER_DEBUG] Order data: {order_data.dict()}")
393
  try:
394
  # Get user's profile
395
  profiles = await get_profiles_by_user(db, current_user.user_id)
396
+ logger.info(f"[ORDER_DEBUG] Found {len(profiles)} profiles for user")
397
  if not profiles:
398
  raise HTTPException(
399
  status_code=status.HTTP_400_BAD_REQUEST,
 
401
  )
402
 
403
  profile = profiles[0]
404
+ logger.info(f"[ORDER_DEBUG] Using profile: {profile.id}")
405
 
406
  # Create order in database
407
+ logger.info(f"[ORDER_DEBUG] Creating order with profile_id: {profile.id}")
408
  order = await create_order(db, order_data, profile.id)
409
+ logger.info(f"[ORDER_DEBUG] Order created with ID: {order.id}")
410
 
411
  # Get user's email - prefer frontend-provided email, fall back to authenticated user's email
412
  user_email = order_data.customer_email or current_user.email
413
+ logger.info(f"[ORDER_DEBUG] User email: {user_email}")
414
 
415
  # Create Stripe checkout session with user's email
416
+ logger.info(f"[ORDER_DEBUG] Creating Stripe checkout session for order: {order.id}")
417
  checkout_url = create_checkout_session_for_order(order, customer_email=user_email)
418
+ logger.info(f"[ORDER_DEBUG] Stripe checkout URL created: {checkout_url[:50]}...")
419
 
420
  # Update order with Stripe session ID
421
  from crud import update_order_status
422
+ session_id = checkout_url.split('/')[-1]
423
+ logger.info(f"[ORDER_DEBUG] Updating order with session_id: {session_id}")
424
+ await update_order_status(db, order.id, "pending", session_id)
425
 
426
  return {
427
  "id": order.id,
 
429
  "items": order.items,
430
  "total_amount": order.total_amount,
431
  "status": "pending",
432
+ "stripe_session_id": session_id,
433
  "created_at": order.created_at,
434
  "updated_at": order.updated_at,
435
  "checkout_url": checkout_url
436
  }
437
+ except HTTPException:
438
+ raise
439
  except Exception as e:
440
+ logger.error(f"[ORDER_DEBUG] Error creating order: {str(e)}")
441
+ logger.error(f"[ORDER_DEBUG] Error type: {type(e).__name__}")
442
+ import traceback
443
+ logger.error(f"[ORDER_DEBUG] Traceback: {traceback.format_exc()}")
444
  raise HTTPException(
445
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
446
+ detail=f"Failed to create order: {str(e)}"
447
  )
448
 
449
 
schemas.py CHANGED
@@ -139,7 +139,7 @@ class OrderBase(BaseModel):
139
  class OrderCreate(OrderBase):
140
  """Schema for creating a new order."""
141
 
142
- profile_id: UUID = Field(..., description="ID of the profile making the order")
143
  customer_email: Optional[str] = Field(default=None, description="Customer email for Stripe checkout")
144
 
145
 
 
139
  class OrderCreate(OrderBase):
140
  """Schema for creating a new order."""
141
 
142
+ profile_id: Optional[UUID] = Field(default=None, description="Optional profile ID - backend will use authenticated user's profile if not provided")
143
  customer_email: Optional[str] = Field(default=None, description="Customer email for Stripe checkout")
144
 
145
 
stripe_service.py CHANGED
@@ -29,22 +29,23 @@ def create_checkout_session_for_order(order, customer_email: str = None) -> str:
29
  import logging
30
  logger = logging.getLogger(__name__)
31
 
 
 
 
 
 
 
 
32
  try:
33
- # Debug: Log order structure
34
- logger.info(f"[DEBUG] Order ID: {getattr(order, 'id', 'unknown')}")
35
- logger.info(f"[DEBUG] Order items type: {type(order.items)}")
36
- logger.info(f"[DEBUG] Order items: {order.items}")
37
- logger.info(f"[DEBUG] Order total_amount: {order.total_amount}")
38
- logger.info(f"[DEBUG] Customer email: {customer_email}")
39
-
40
  # Extract order items for Stripe line items
41
  line_items = []
42
 
43
  # Assuming order.items contains a list of menu items with details
44
  # This would need to be parsed based on your order structure
45
  if isinstance(order.items, list):
46
- for item in order.items:
47
- logger.info(f"[DEBUG] Processing item: {item}")
 
48
  # Check if item has menu_item_id (frontend format)
49
  if 'menu_item_id' in item:
50
  # Need to fetch menu item details from menu_data
@@ -54,9 +55,9 @@ def create_checkout_session_for_order(order, customer_email: str = None) -> str:
54
  menu_item_name = menu_item.get('name', 'Menu Item')
55
  # Price in menu_data is already in cents
56
  menu_item_price = menu_item.get('price', order.total_amount)
57
- logger.info(f"[DEBUG] Fetched menu item: {menu_item_name}, price (cents): {menu_item_price}")
58
  except (ValueError, ImportError) as e:
59
- logger.error(f"[DEBUG] Failed to fetch menu item {item.get('menu_item_id')}: {e}")
60
  menu_item_name = f"Menu Item {item.get('menu_item_id', 'Unknown')}"
61
  menu_item_price = order.total_amount
62
  else:
@@ -65,6 +66,7 @@ def create_checkout_session_for_order(order, customer_email: str = None) -> str:
65
  menu_item_price = item.get('price', order.total_amount)
66
 
67
  quantity = item.get('quantity', 1)
 
68
 
69
  line_items.append({
70
  'price_data': {
@@ -78,6 +80,7 @@ def create_checkout_session_for_order(order, customer_email: str = None) -> str:
78
  })
79
  else:
80
  # Single item order - fallback
 
81
  line_items.append({
82
  'price_data': {
83
  'currency': settings.stripe_default_currency,
@@ -89,6 +92,8 @@ def create_checkout_session_for_order(order, customer_email: str = None) -> str:
89
  'quantity': 1,
90
  })
91
 
 
 
92
  # Create Stripe checkout session
93
  session_params = {
94
  'payment_method_types': ['card'],
@@ -112,12 +117,19 @@ def create_checkout_session_for_order(order, customer_email: str = None) -> str:
112
  # Add customer_email if provided
113
  if customer_email:
114
  session_params['customer_email'] = customer_email
 
115
 
 
116
  session = stripe.checkout.Session.create(**session_params)
 
117
 
118
  return session.url
119
 
120
  except Exception as e:
 
 
 
 
121
  raise Exception(f"Failed to create checkout session: {str(e)}")
122
 
123
 
 
29
  import logging
30
  logger = logging.getLogger(__name__)
31
 
32
+ logger.info(f"[STRIPE_DEBUG] Starting checkout session creation for order")
33
+ logger.info(f"[STRIPE_DEBUG] Order ID: {getattr(order, 'id', 'unknown')}")
34
+ logger.info(f"[STRIPE_DEBUG] Order items type: {type(order.items)}")
35
+ logger.info(f"[STRIPE_DEBUG] Order items: {order.items}")
36
+ logger.info(f"[STRIPE_DEBUG] Order total_amount: {order.total_amount}")
37
+ logger.info(f"[STRIPE_DEBUG] Customer email: {customer_email}")
38
+
39
  try:
 
 
 
 
 
 
 
40
  # Extract order items for Stripe line items
41
  line_items = []
42
 
43
  # Assuming order.items contains a list of menu items with details
44
  # This would need to be parsed based on your order structure
45
  if isinstance(order.items, list):
46
+ logger.info(f"[STRIPE_DEBUG] Processing {len(order.items)} order items")
47
+ for i, item in enumerate(order.items):
48
+ logger.info(f"[STRIPE_DEBUG] Processing item {i}: {item}")
49
  # Check if item has menu_item_id (frontend format)
50
  if 'menu_item_id' in item:
51
  # Need to fetch menu item details from menu_data
 
55
  menu_item_name = menu_item.get('name', 'Menu Item')
56
  # Price in menu_data is already in cents
57
  menu_item_price = menu_item.get('price', order.total_amount)
58
+ logger.info(f"[STRIPE_DEBUG] Fetched menu item: {menu_item_name}, price (cents): {menu_item_price}")
59
  except (ValueError, ImportError) as e:
60
+ logger.error(f"[STRIPE_DEBUG] Failed to fetch menu item {item.get('menu_item_id')}: {e}")
61
  menu_item_name = f"Menu Item {item.get('menu_item_id', 'Unknown')}"
62
  menu_item_price = order.total_amount
63
  else:
 
66
  menu_item_price = item.get('price', order.total_amount)
67
 
68
  quantity = item.get('quantity', 1)
69
+ logger.info(f"[STRIPE_DEBUG] Item: {menu_item_name}, quantity: {quantity}, price: {menu_item_price}")
70
 
71
  line_items.append({
72
  'price_data': {
 
80
  })
81
  else:
82
  # Single item order - fallback
83
+ logger.warning(f"[STRIPE_DEBUG] Order items is not a list, using fallback single item")
84
  line_items.append({
85
  'price_data': {
86
  'currency': settings.stripe_default_currency,
 
92
  'quantity': 1,
93
  })
94
 
95
+ logger.info(f"[STRIPE_DEBUG] Created {len(line_items)} line items for Stripe")
96
+
97
  # Create Stripe checkout session
98
  session_params = {
99
  'payment_method_types': ['card'],
 
117
  # Add customer_email if provided
118
  if customer_email:
119
  session_params['customer_email'] = customer_email
120
+ logger.info(f"[STRIPE_DEBUG] Added customer email to session")
121
 
122
+ logger.info(f"[STRIPE_DEBUG] Creating Stripe checkout session...")
123
  session = stripe.checkout.Session.create(**session_params)
124
+ logger.info(f"[STRIPE_DEBUG] Stripe session created successfully: {session.id}")
125
 
126
  return session.url
127
 
128
  except Exception as e:
129
+ logger.error(f"[STRIPE_DEBUG] Failed to create checkout session: {str(e)}")
130
+ logger.error(f"[STRIPE_DEBUG] Error type: {type(e).__name__}")
131
+ import traceback
132
+ logger.error(f"[STRIPE_DEBUG] Traceback: {traceback.format_exc()}")
133
  raise Exception(f"Failed to create checkout session: {str(e)}")
134
 
135