habulaj commited on
Commit
746d8ca
·
verified ·
1 Parent(s): 66205ec

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +55 -23
routes/subscription.py CHANGED
@@ -117,35 +117,67 @@ async def sync_emergency_payments(request: Request, data: EmergencyPaymentReques
117
  existing_payments = response_payments.json()
118
  logger.info(f"Found {len(existing_payments)} emergency payments for stylist {stylist_id} and customer {user_id}")
119
 
120
- # Passo 5: Verificar os pagamentos e inserir os que faltam
121
- for payment in existing_payments:
122
- payment_id = payment.get("payment_id")
123
- if not payment_id:
124
- # Inserir pagamento de emergência que não foi encontrado
125
- emergency_sub_data = {
126
- "stylist_id": stylist_id,
127
- "client_id": user_id,
128
- "payment_id": payment_id, # Exemplo de dado de pagamento
129
- "price": 0, # Valor do pagamento
130
- # Adicione outros campos se necessário
131
- }
132
- response_insert = requests.post(
133
- f"{SUPABASE_URL}/rest/v1/Emergency_sub",
134
- headers=SUPABASE_HEADERS,
135
- json=emergency_sub_data
136
- )
137
-
138
- if response_insert.status_code == 201:
139
- logger.info(f"Payment {payment_id} added successfully")
140
- else:
141
- logger.error(f"Failed to add payment {payment_id}: {response_insert.status_code} - {response_insert.text}")
142
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  return {"status": "success", "message": "Emergency payments synchronized successfully"}
144
 
145
  except jwt.ExpiredSignatureError:
146
  raise HTTPException(status_code=401, detail="Token has expired")
147
  except jwt.InvalidTokenError:
148
  raise HTTPException(status_code=401, detail="Invalid token")
 
 
 
149
  except Exception as e:
150
  logger.error(f"Error in syncing emergency payments: {str(e)}")
151
  raise HTTPException(status_code=500, detail=f"Error in syncing emergency payments: {str(e)}")
 
117
  existing_payments = response_payments.json()
118
  logger.info(f"Found {len(existing_payments)} emergency payments for stylist {stylist_id} and customer {user_id}")
119
 
120
+ # Passo 5: Buscar pagamentos no Stripe para esse user_id e stylist_id
121
+ stripe_payments = stripe.PaymentIntent.list(
122
+ customer=stripe_id,
123
+ expand=["data.charges"]
124
+ )
125
+
126
+ # Passo 6: Verificar os pagamentos e inserir os que faltam
127
+ for stripe_payment in stripe_payments["data"]:
128
+ payment_id = stripe_payment["id"]
129
+
130
+ # Verificar se o payment_id já existe no Supabase
131
+ existing_payment = next((payment for payment in existing_payments if payment["payment_id"] == payment_id), None)
132
+
133
+ if existing_payment:
134
+ logger.info(f"Payment {payment_id} already exists in database, skipping.")
135
+ continue # Pular se já existe
136
+
137
+ # Se não existe, adicionar pagamento de emergência ao Supabase
138
+ amount = stripe_payment["amount_received"] / 100 # Valor recebido
139
+ currency = stripe_payment["currency"].upper() # Moeda
140
+
141
+ payment_method = stripe_payment.get("payment_method")
142
+ payment_type = "N/A"
143
+ last4 = "N/A"
144
+ if payment_method:
145
+ payment_method_details = stripe.PaymentMethod.retrieve(payment_method)
146
+ payment_type = payment_method_details["type"]
147
+ last4 = payment_method_details[payment_type].get("last4", "N/A")
148
+
149
+ emergency_sub_data = {
150
+ "stylist_id": stylist_id,
151
+ "client_id": user_id,
152
+ "payment_id": payment_id,
153
+ "amount": amount,
154
+ "currency": currency,
155
+ "payment_method": f"{payment_type.upper()} ending in {last4}",
156
+ "status": stripe_payment["status"], # Status do pagamento
157
+ # Adicione outros campos necessários
158
+ }
159
+
160
+ # Inserir o novo pagamento de emergência no Supabase
161
+ response_insert = requests.post(
162
+ f"{SUPABASE_URL}/rest/v1/Emergency_sub",
163
+ headers=SUPABASE_HEADERS,
164
+ json=emergency_sub_data
165
+ )
166
+
167
+ if response_insert.status_code == 201:
168
+ logger.info(f"Payment {payment_id} added successfully")
169
+ else:
170
+ logger.error(f"Failed to add payment {payment_id}: {response_insert.status_code} - {response_insert.text}")
171
+
172
  return {"status": "success", "message": "Emergency payments synchronized successfully"}
173
 
174
  except jwt.ExpiredSignatureError:
175
  raise HTTPException(status_code=401, detail="Token has expired")
176
  except jwt.InvalidTokenError:
177
  raise HTTPException(status_code=401, detail="Invalid token")
178
+ except stripe.error.StripeError as e:
179
+ logger.error(f"Stripe error: {str(e)}")
180
+ raise HTTPException(status_code=500, detail=f"Stripe error: {str(e)}")
181
  except Exception as e:
182
  logger.error(f"Error in syncing emergency payments: {str(e)}")
183
  raise HTTPException(status_code=500, detail=f"Error in syncing emergency payments: {str(e)}")