Skip to content
Open
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
25 changes: 23 additions & 2 deletions app/api/v1/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,36 @@ async def evolution_webhook(request: Request, db: Session = Depends(get_db)):
if not media_url:
media_url = "https://images.unsplash.com/photo-1523275335684-37898b6baf30"

tenant = db.query(Tenant).first()
# Identify Tenant securely
instance_name = payload.get("instance")
tenant = db.query(Tenant).join(SocialAccount).filter(
SocialAccount.platform == "whatsapp",
SocialAccount.external_id == instance_name
).first()

if not tenant:
# Fallback to remote_jid lookup if instance not linked yet
tenant = db.query(Tenant).filter(Tenant.admin_jids.contains([remote_jid])).first()

if not tenant:
# For this exercise, create a tenant if not found, but associate with the sender
tenant = Tenant(
business_name="Default Business",
business_name=f"Business {instance_name or 'Default'}",
niche="E-commerce",
admin_jids=[remote_jid], # Add the sender as admin for testing
required_approvals=2
)
db.add(tenant)
db.flush()

if instance_name:
social = SocialAccount(
tenant_id=tenant.id,
platform="whatsapp",
external_id=instance_name
)
db.add(social)

db.commit()
db.refresh(tenant)

Expand Down
6 changes: 4 additions & 2 deletions app/services/interaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ async def handle_message(self, remote_jid: str, text: str):
cmd = text.strip().lower()

# Find the most recent job for this sender or related tenant
# In a real multi-tenant app, we'd filter by sender's association to a tenant
job = self.db.query(ContentJob).order_by(desc(ContentJob.created_at)).first()
# Filtered by sender's association to a tenant for security (Ticket 🔒 Tenant Isolation)
job = self.db.query(ContentJob).join(Tenant).filter(
Tenant.admin_jids.contains([remote_jid])
).order_by(desc(ContentJob.created_at)).first()

if not job:
return {"status": "error", "message": "No job found"}
Expand Down