Spaces:
Running
Running
GitHub Actions commited on
Commit ·
dbce54a
0
Parent(s):
Deploy backend 1aa0210a from KevsOno/Muzoscents-funnel-old
Browse filesFiles changed (21)
- .gitattributesAdded+4
- DockerfileAdded+28
- README.mdAdded+34
- customers.pyAdded+226
- delivery_zones.pyAdded+133
- deps.pyAdded+1280
- exec_profitability.pyAdded+223
- expenses.pyAdded+381
- geo.pyAdded+227
- hr.pyAdded+847
- inventory.pyAdded+723
- main.pyAdded
- migrations_geo.pyAdded+294
- netlify.tomlAdded+133
- pos_transfers.pyAdded+706
- procurement.pyAdded+193
- requirements.txtAdded+14
- support_chat.pyAdded+204
- support_tickets.pyAdded+696
- tailwind.config.jsAdded+20
- tracking.pyAdded+289
1234*.webp filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728# Use a lightweight Python imageFROM python:3.11-slim
# Set working directoryWORKDIR /app
# Install system dependencies required for sentence-transformers & cryptographyRUN apt-get update && apt-get install -y --no-install-recommends \ gcc \ g++ \ libffi-dev \ libssl-dev \ && rm -rf /var/lib/apt/lists/*
# Copy requirements first (better layer caching)COPY requirements.txt .
# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy the entire application (Python files, HTML, JS, config, etc.)COPY . .
# Expose the port used by FastAPIEXPOSE 7860
# Command to start the serverCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]12345678910111213141516171819202122232425262728293031323334---
title: Kevs Digital bOS
emoji: 🚀
colorFrom: blue
colorTo: green
sdk: docker
app_port: 7860
pinned: false
short_description: Kevs Digital bOS backend API
---
# Kevs Digital bOS
Backend API for the Kevs Digital bOS platform.
Multi-tenant inventory, POS, accounting, HR, procurement, and storefront infrastructure.
## Endpoints
- `/health` — service health check
- `/auth/*` — authentication
- `/inventory/*` — inventory management
- `/store/{slug}` — public storefront routing
- `/public/*` — public data endpoints
## Stack
- FastAPI
- Supabase (PostgreSQL)
- Docker on Hugging Face Spaces
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226from fastapi import APIRouter, Depends, HTTPException, Request, Queryfrom pydantic import BaseModel, Fieldfrom typing import Optional, Tuple, Listfrom datetime import datetime, timezoneimport secrets, stringimport httpx
from main import ( get_supabase, run_sync_db_call, rate_limit, get_client_ip, SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, PRODUCTION_HOST, send_sendgrid_email, escape_html)from deps import require_role, get_user_branches, get_visible_user_ids, resolve_request_branch_for_write, resolve_request_branch, resolve_default_branch, is_user_in_branch, ensure_default_branch
router = APIRouter(prefix="/customers", tags=["Customers"])
class CustomerCreate(BaseModel): first_name: str last_name: str email: str phone: str = Field(..., min_length=1) tier: str = "bronze" loyalty_points: int = 0 address: Optional[str] = None
@router.get("")async def list_customers( request: Request, search: Optional[str] = Query(None), limit: int = Query(50, ge=1, le=200), offset: int = Query(0, ge=0), user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "support"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase()
# Query the crm_customers view q = client.table("crm_customers").select("*", count="exact").eq("org_id", org_id)
if search: q = q.or_(f"name.ilike.%{search}%,email.ilike.%{search}%,phone.ilike.%{search}%")
res = await run_sync_db_call(q.order("created_at", desc=True).range(offset, offset + limit - 1).execute)
return { "customers": res.data or [], "total": res.count or 0, "limit": limit, "offset": offset, }
@router.post("")async def create_customer( request: Request, customer: CustomerCreate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "support"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data
if not SUPABASE_SERVICE_ROLE_KEY: raise HTTPException(status_code=500, detail="Service role key not configured")
headers = { "apikey": SUPABASE_SERVICE_ROLE_KEY, "Authorization": f"Bearer {SUPABASE_SERVICE_ROLE_KEY}", "Content-Type": "application/json", }
async with httpx.AsyncClient() as http_client: # ── Step 1: does a profile already exist for this email? ── check_url = f"{SUPABASE_URL}/rest/v1/profiles?select=id&email=eq.{customer.email}" check_resp = await http_client.get(check_url, headers=headers) existing_profiles = check_resp.json() if check_resp.status_code == 200 else []
if existing_profiles: user_id = existing_profiles[0]["id"] created_new_user = False
# ── Step 1a: refuse if already a member of THIS org ── # # Without this, the subsequent org_members insert fails with # a raw 23505 unique-constraint error that surfaces as a # 500 to the operator with no actionable message. member_check_url = ( f"{SUPABASE_URL}/rest/v1/org_members" f"?select=user_id&user_id=eq.{user_id}&org_id=eq.{org_id}" ) member_resp = await http_client.get(member_check_url, headers=headers) if member_resp.status_code == 200 and member_resp.json(): raise HTTPException( status_code=409, detail="This email is already a customer of this organisation.", ) else: # ── Step 2: create a fresh auth user + profile ── temp_password = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(12)) admin_url = f"{SUPABASE_URL}/auth/v1/admin/users" admin_payload = { "email": customer.email, "password": temp_password, "email_confirm": True, "user_metadata": { "first_name": customer.first_name, "last_name": customer.last_name, "phone": customer.phone, }, } admin_resp = await http_client.post(admin_url, json=admin_payload, headers=headers) if admin_resp.status_code != 200: raise HTTPException(status_code=500, detail=f"Failed to create auth user: {admin_resp.text}")
user_id = admin_resp.json().get("id") if not user_id: raise HTTPException(status_code=500, detail="Auth user created but no id returned") created_new_user = True
# ── Step 2a: create the identity-only profile ── # # IMPORTANT: profiles is identity-only now. Loyalty state # (current_points, tier, membership_id) lives on org_leads. # Writing loyalty columns here silently fails with a 400 # from PostgREST ("column does not exist"), and the profile # is never created — the customer then has an auth user and # org_members row but no profile, which breaks every # profile-dependent read. now_iso = datetime.now(timezone.utc).isoformat() profile_data = { "id": user_id, "email": customer.email, "first_name": customer.first_name, "last_name": customer.last_name, "phone": customer.phone, "status": "active", "address": customer.address, "created_at": now_iso, "updated_at": now_iso, } profile_resp = await http_client.post( f"{SUPABASE_URL}/rest/v1/profiles", json=profile_data, headers=headers, ) if profile_resp.status_code not in (200, 201): # Roll back the auth user so we don't leave an orphan. await http_client.delete( f"{SUPABASE_URL}/auth/v1/admin/users/{user_id}", headers=headers, ) raise HTTPException( status_code=500, detail=f"Failed to create profile: {profile_resp.text}", )
# ── Step 3: add to org_members (role: customer) ── member_data = { "user_id": user_id, "org_id": org_id, "role": "customer", "joined_at": datetime.now(timezone.utc).isoformat(), } member_resp = await http_client.post( f"{SUPABASE_URL}/rest/v1/org_members", json=member_data, headers=headers, ) if member_resp.status_code not in (200, 201): # Roll back the newly-created auth user and profile if the # membership couldn't be created. Leaving orphans behind is # worse than failing loudly. if created_new_user: await http_client.delete( f"{SUPABASE_URL}/rest/v1/profiles?id=eq.{user_id}", headers=headers, ) await http_client.delete( f"{SUPABASE_URL}/auth/v1/admin/users/{user_id}", headers=headers, ) raise HTTPException( status_code=500, detail=f"Failed to add customer to organisation: {member_resp.text}", )
# ── Step 4: upsert org_leads (source of truth for crm_customers) ── # # Loyalty state goes here — current_points and tier belong on # org_leads, not profiles. The crm_customers view is built on # this table. client = get_supabase() await run_sync_db_call( client.table("org_leads").upsert({ "org_id": org_id, "profile_id": user_id, "name": f"{customer.first_name} {customer.last_name}".strip(), "email": customer.email, "phone": customer.phone, "status": "active", "tier": customer.tier, "current_points": customer.loyalty_points, "updated_at": datetime.now(timezone.utc).isoformat(), }, on_conflict="org_id,profile_id").execute() )
# ── Step 5: welcome email with credentials for new accounts ── if created_new_user: login_link = f"{PRODUCTION_HOST}/kdsiginin" html = f""" <h2>Welcome to Kevs Digital!</h2> <p>Hello {escape_html(customer.first_name)},</p> <p>Your customer account has been created. Use the credentials below to log in:</p> <p><strong>Email:</strong> {customer.email}<br> <strong>Temporary Password:</strong> <code>{temp_password}</code></p> <p><a href="{login_link}">Click here to log in</a> and change your password.</p> """ await send_sendgrid_email(customer.email, "Your customer account has been created", html)
return { "message": "Customer processed successfully", "user_id": user_id, "created": created_new_user, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# delivery_zones.pyfrom fastapi import APIRouter, Depends, HTTPException, Requestfrom datetime import datetime, timezone
from deps import ( get_supabase, run_sync_db_call, require_role, rate_limit, get_client_ip, PUBLIC_STORE_ORG_ID, resolve_store_org,)from geo import proxy_aws_places, calculate_intelligent_fee, resolve_delivery_coords
router = APIRouter(prefix="/api/delivery", tags=["Delivery & Zones"])
@router.post("/places/{endpoint}")async def handle_places_proxy(endpoint: str, body: dict, request: Request): # Public endpoint (guest checkout must geocode). Protected only by # IP rate limit. Aggressive limit protects the AWS quota. await rate_limit(get_client_ip(request), request=request)
if endpoint not in {"autocomplete", "geocode", "reverse-geocode"}: raise HTTPException(400, "Invalid endpoint")
try: return await proxy_aws_places(endpoint, body) except ValueError as e: raise HTTPException(502, str(e))
@router.get("/areas")async def get_zones(user_data = Depends(require_role(["owner", "admin", "logistics"]))): _, org_id, _ = user_data client = get_supabase() res = await run_sync_db_call( client.rpc("get_delivery_areas_geojson", {"p_org_id": org_id}).execute ) return {"areas": res.data or []}
@router.post("/areas")async def create_zone(payload: dict, user_data = Depends(require_role(["owner", "admin"]))): _, org_id, _ = user_data client = get_supabase() res = await run_sync_db_call( client.rpc("insert_delivery_area", { "p_org_id": org_id, "p_name": payload["name"], "p_fee": int(payload["fee"]), "p_geojson": payload["polygon"], }).execute ) if not res.data: raise HTTPException(500, "Failed to create zone") return res.data[0]
@router.delete("/areas/{area_id}")async def delete_zone(area_id: int, user_data = Depends(require_role(["owner", "admin"]))): """ Delete a delivery area by id. Org-scoped: a caller can only delete an area belonging to their own organisation. Returns 404 when the id does not exist OR belongs to a different tenant — the two cases are indistinguishable to the caller, so this endpoint does not leak the existence of another tenant's area ids.
No FK in the schema references delivery_areas, so the delete has no cascade side effects. Historical orders that were priced against this zone keep their recorded fee; the zone is only removed from future estimates and checkouts. """ _, org_id, _ = user_data client = get_supabase() res = await run_sync_db_call( client.table("delivery_areas") .delete() .eq("id", area_id) .eq("org_id", org_id) .execute ) if not res.data: raise HTTPException(404, "Area not found") return {"deleted": area_id}
@router.post("/estimate")async def estimate_fee(payload: dict, request: Request): await rate_limit(get_client_ip(request), request=request)
org_id = await resolve_store_org(request, org_id=payload.get("org_id"))
# FIX: Resolve coordinates dynamically using AWS Geocoding coords = await resolve_delivery_coords( address=payload.get("address"), client_lat=payload.get("lat"), client_lng=payload.get("lng"), customer_email=payload.get("customer_email") )
if not coords: return {"covered": False, "message": "Address not found. Please check and try again."}
lat, lng = coords client = get_supabase()
zone_res = await run_sync_db_call( client.rpc("find_delivery_area", { "p_org_id": org_id, "p_lat": lat, "p_lng": lng, }).execute ) if not zone_res.data: return {"covered": False, "message": "Address is outside our delivery area."}
area = zone_res.data[0]
fee_calc = await calculate_intelligent_fee( org_id=org_id, base_fee=area["fee"], order_value=int(payload.get("order_total", 0)), items=payload.get("items", []), # FIX: Timezone-aware datetime order_time=datetime.now(timezone.utc), customer_email=payload.get("customer_email"), db_client=client, )
return {"covered": True, "area_name": area["name"], **fee_calc}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280# deps.py"""Shared dependencies and primitives for all Kevs Digital modules.
This module is the leaf of the import graph: it imports only fromexternal packages, never from main.py, tracking.py, delivery_zones.py,or geo.py. That guarantees no circular imports when any of thoseimport from here.
Single source of truth for: - Environment configuration - Logging - Supabase clients (cached service role, fresh admin, fresh user) - Async DB helper, single-row fetcher - Rate limiting - Auth pipeline (JWT -> user_id, org_id, role) - Feature gates (plan tiers, overrides, suspension) - FastAPI dependencies (require_role, require_feature, require_feature_any)"""
import osimport asynciofrom datetime import datetime, timezonefrom typing import Optional, Tuple, List, Dict, Anyimport logging
import httpximport structlogfrom fastapi import Header, HTTPException, Request, Dependsfrom supabase import create_client, Client
# ============================================================# LOGGING# ============================================================log_level = os.environ.get("LOG_LEVEL", "INFO").upper()logging.basicConfig( level=getattr(logging, log_level), format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)
if os.environ.get("STRUCTLOG_JSON", "true").lower() == "true": renderer = structlog.processors.JSONRenderer()else: renderer = structlog.dev.ConsoleRenderer()
structlog.configure( processors=[ structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, renderer, ], context_class=dict, logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True,)logger = structlog.get_logger()
# ============================================================# ENVIRONMENT# ============================================================SUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY")SUPABASE_SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY")
PUBLIC_STORE_ORG_ID = os.environ.get("PUBLIC_STORE_ORG_ID")PRODUCTION_HOST = os.environ.get("PRODUCTION_HOST", "https://kevsono-kevs-digital-bos.hf.space")ADMIN_SECRET_KEY = os.environ.get("ADMIN_SECRET_KEY", "change_this_in_production")
RATE_LIMIT_ENABLED = os.environ.get("RATE_LIMIT_ENABLED", "true").lower() == "true"RATE_LIMIT_REQUESTS = int(os.environ.get("RATE_LIMIT_REQUESTS", "100"))RATE_LIMIT_WINDOW = int(os.environ.get("RATE_LIMIT_WINDOW", "60"))
ENFORCE_FEATURES = os.environ.get("ENFORCE_FEATURES", "false").lower() == "true"ORG_SCOPE_CANARY = os.environ.get("ORG_SCOPE_CANARY", "false").lower() == "true"
# ============================================================# REQUEST IDENTITY# ============================================================def get_client_ip(request: Request) -> str: forwarded = request.headers.get("X-Forwarded-For") if forwarded: return forwarded.split(",")[0].strip() return request.client.host if request.client else "unknown"
# ============================================================# SUPABASE CLIENTS# ============================================================_ORG_SCOPED_TABLES = frozenset({ "alert_log", "stock_limits", "transfer_suggestions", "products", "inventory", "inventory_batches", "sales", "sale_items", "locations", "location_stocks", "stock_transfers", "branches", "suppliers", "purchase_orders", "purchase_order_items", "grn", "grn_items", "org_leads", "support_tickets", "ticket_messages", "chat_sessions", "chat_messages", "general_knowledge", "knowledge_audit", "chart_of_accounts", "journal_entries", "journal_lines", "accounts_receivable", "accounts_payable", "profit_loss_summary", "hr_departments", "hr_employees", "hr_attendance", "hr_leave_requests", "hr_leave_balances", "hr_payroll", "system_logs", "webhook_events", "admin_audit", "audit_events", "delivery_areas", "delivery_fee_rules", "delivery_peak_settings", "delivery_loyalty_settings", "delivery_item_surcharge_rules", "driver_locations", "geofences", "geofence_events", "sale_events",})
_AUTH_MUTATORS = frozenset({ "sign_in", "sign_in_with_password", "sign_in_with_otp", "sign_up", "sign_out", "refresh_session", "set_session", "verify_otp", "reauthenticate", "reset_password_for_email",})
class _GuardedAuth: __slots__ = ("_inner",) def __init__(self, inner): self._inner = inner def __getattr__(self, name): if name in _AUTH_MUTATORS: raise RuntimeError( f"auth.{name}() mutates the shared Supabase client. " f"Use get_user_supabase() for authentication calls." ) return getattr(self._inner, name)
class _CanaryBuilder: __slots__ = ("_inner", "_table") def __init__(self, inner, table): self._inner = inner self._table = table def execute(self, *args, **kwargs): self._maybe_warn() return self._inner.execute(*args, **kwargs) def _maybe_warn(self): if not ORG_SCOPE_CANARY: return if self._table not in _ORG_SCOPED_TABLES: return params = getattr(self._inner, "params", None) if params is None: return try: keys = list(params.keys()) except Exception: return for k in keys: if k == "org_id" or k.endswith(".org_id"): return logger.warning("org_scope_canary", table=self._table) def __getattr__(self, name): attr = getattr(self._inner, name) if not callable(attr): return attr def wrapped(*args, **kwargs): result = attr(*args, **kwargs) if hasattr(result, "execute"): return _CanaryBuilder(result, self._table) return result return wrapped
class _GuardedClient: __slots__ = ("_inner",) def __init__(self, inner): self._inner = inner def __getattr__(self, name): if name == "auth": return _GuardedAuth(self._inner.auth) if name == "table": def wrapped_table(table_name): builder = self._inner.table(table_name) if ORG_SCOPE_CANARY: return _CanaryBuilder(builder, table_name) return builder return wrapped_table return getattr(self._inner, name)
def _force_clear_auth_session(client: Client) -> None: try: auth = client.auth except Exception: return for attr in ("_current_session", "_current_user"): try: if hasattr(auth, attr): setattr(auth, attr, None) except Exception: pass try: storage = getattr(auth, "_storage", None) if storage is not None: url = (SUPABASE_URL or "").rstrip("/") for key in ("supabase.auth.token", f"sb-{url}-auth-token", "gotrue.auth.token"): try: storage.remove_item(key) except Exception: pass except Exception: pass
supabase_client: Optional[Client] = Nonelast_client_check = None
def get_supabase(): global supabase_client, last_client_check now = datetime.now(timezone.utc) if supabase_client is None or (last_client_check and (now - last_client_check).seconds > 3600): if not SUPABASE_URL or not SUPABASE_SERVICE_ROLE_KEY: if SUPABASE_ANON_KEY: logger.warning("SUPABASE_SERVICE_ROLE_KEY missing – falling back to anon (RLS may block)") raw = create_client(SUPABASE_URL, SUPABASE_ANON_KEY) else: raise RuntimeError("No Supabase credentials") else: raw = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY) logger.info("Supabase client created with SERVICE ROLE KEY (RLS bypassed)") _force_clear_auth_session(raw) supabase_client = _GuardedClient(raw) last_client_check = now return supabase_client
def get_admin_supabase() -> Client: if not SUPABASE_URL or not SUPABASE_SERVICE_ROLE_KEY: raise RuntimeError("Missing service role key for admin client") client = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY) _force_clear_auth_session(client) return client
def get_user_supabase() -> Client: if not SUPABASE_URL or not SUPABASE_ANON_KEY: raise RuntimeError("Missing anon key for user auth client") client = create_client(SUPABASE_URL, SUPABASE_ANON_KEY) _force_clear_auth_session(client) return client
# ============================================================# ASYNC DB HELPERS# ============================================================async def run_sync_db_call(sync_func, *args, **kwargs): return await asyncio.to_thread(sync_func, *args, **kwargs)
async def fetch_one(query) -> Optional[Dict]: try: res = await run_sync_db_call(query.execute) except Exception as e: msg = str(e) if "PGRST116" in msg or "JSON object requested" in msg: return None raise if res is None: return None data = getattr(res, "data", None) if data is None: return None if isinstance(data, list): return data[0] if data else None return data
# ============================================================# RATE LIMITING# ============================================================async def rate_limit(client_id: str, org_id: Optional[str] = None, request: Optional[Request] = None): if not RATE_LIMIT_ENABLED: return if request and request.headers.get("X-Load-Test") == "true": return
supabase = get_supabase() now = datetime.now(timezone.utc) window_start = datetime.fromtimestamp( (now.timestamp() // RATE_LIMIT_WINDOW) * RATE_LIMIT_WINDOW, tz=timezone.utc ) try: query = supabase.table("rate_limits").select("request_count").eq("client_id", client_id).eq("window_start", window_start.isoformat()) if org_id is not None: query = query.eq("org_id", org_id) existing = await run_sync_db_call(query.execute)
if existing.data and len(existing.data) > 0: new_count = existing.data[0]["request_count"] + 1 update_query = supabase.table("rate_limits").update({"request_count": new_count}).eq("client_id", client_id).eq("window_start", window_start.isoformat()) if org_id is not None: update_query = update_query.eq("org_id", org_id) await run_sync_db_call(update_query.execute) else: insert_data = {"client_id": client_id, "window_start": window_start.isoformat(), "request_count": 1} if org_id is not None: insert_data["org_id"] = org_id await run_sync_db_call(supabase.table("rate_limits").insert(insert_data).execute) new_count = 1
if new_count > RATE_LIMIT_REQUESTS: raise HTTPException(status_code=429, detail="Rate limit exceeded. Please try again later.") except HTTPException: raise except Exception as e: logger.error(f"Rate limit error: {e}")
# ============================================================# PLAN TIERS# ============================================================PLAN_TIERS: Dict[str, Dict] = { # ── Retail ─────────────────────────────────────────────────── "convenience": { "label": "Convenience Store", "vertical": "retail", "monthly_naira": 150_000, "setup_base": 200_000, "max_skus": 1_500, "max_locations": 1, "features": { "ecommerce": True, "offline_pos": True, "multi_location": False, "expiry_tracking": False, "accounting": True, "hr_module": False, "procurement": True, "ai_assistant": False, "loyalty": True, "fulfillment": False, "mobile_apps": False, "kitchen_display": False, "live_dispatch": False, }, }, "pharmacy_indie": { "label": "Independent Pharmacy", "vertical": "retail", "monthly_naira": 250_000, "setup_base": 200_000, "max_skus": 3_000, "max_locations": 1, "features": { "ecommerce": True, "offline_pos": True, "multi_location": False, "expiry_tracking": True, "accounting": True, "hr_module": False, "procurement": True, "ai_assistant": False, "loyalty": True, "fulfillment": False, "mobile_apps": False, "kitchen_display": False, "live_dispatch": False, }, }, "pharmacy_chain": { "label": "Pharmacy Chain", "vertical": "retail", "monthly_naira": 350_000, "setup_base": 200_000, "max_skus": 5_000, "max_locations": 10, "features": { "ecommerce": True, "offline_pos": True, "multi_location": True, "expiry_tracking": True, "accounting": True, "hr_module": True, "procurement": True, "ai_assistant": False, "loyalty": True, "fulfillment": False, "mobile_apps": False, "kitchen_display": False, "live_dispatch": False, }, }, "supermarket_med": { "label": "Supermarket (Medium)", "vertical": "retail", "monthly_naira": 400_000, "setup_base": 200_000, "max_skus": 15_000, "max_locations": 5, "features": { "ecommerce": True, "offline_pos": True, "multi_location": True, "expiry_tracking": True, "accounting": True, "hr_module": True, "procurement": True, "ai_assistant": True, "loyalty": True, "fulfillment": True, "mobile_apps": True, "kitchen_display": False, "live_dispatch": False, }, }, "supermarket_large": { "label": "Supermarket (Large)", "vertical": "retail", "monthly_naira": 500_000, "setup_base": 200_000, "max_skus": None, "max_locations": None, "features": { "ecommerce": True, "offline_pos": True, "multi_location": True, "expiry_tracking": True, "accounting": True, "hr_module": True, "procurement": True, "ai_assistant": True, "loyalty": True, "fulfillment": True, "mobile_apps": True, "kitchen_display": False, "live_dispatch": False, }, },
# ── Food & Beverage ───────────────────────────────────────── "fb_express": { "label": "F&B Express", "vertical": "food", "monthly_naira": 220_000, "setup_base": 750_000, "max_skus": 500, "max_locations": 1, "features": { "ecommerce": True, "offline_pos": True, "multi_location": False, "expiry_tracking": True, "accounting": True, "hr_module": False, "procurement": True, "ai_assistant": False, "loyalty": True, "fulfillment": False, "mobile_apps": False, "kitchen_display": True, "live_dispatch": False, }, }, "fb_multi": { "label": "F&B Multi-Chain", "vertical": "food", "monthly_naira": 350_000, "setup_base": 1_200_000, "max_skus": 2_000, "max_locations": 20, "features": { "ecommerce": True, "offline_pos": True, "multi_location": True, "expiry_tracking": True, "accounting": True, "hr_module": True, "procurement": True, "ai_assistant": True, "loyalty": True, "fulfillment": True, "mobile_apps": True, "kitchen_display": True, "live_dispatch": True, }, }, "qsr_enterprise": { "label": "QSR Enterprise AI", "vertical": "food", "monthly_naira": 500_000, "setup_base": 1_800_000, "max_skus": None, "max_locations": None, "features": { "ecommerce": True, "offline_pos": True, "multi_location": True, "expiry_tracking": True, "accounting": True, "hr_module": True, "procurement": True, "ai_assistant": True, "loyalty": True, "fulfillment": True, "mobile_apps": True, "kitchen_display": True, "live_dispatch": True, }, },
# ── Service ───────────────────────────────────────────────── "service_basic": { "label": "Service Business", "vertical": "service", "monthly_naira": 150_000, "setup_base": 200_000, "max_skus": None, "max_locations": None, "features": { "ecommerce": True, "offline_pos": True, "multi_location": False, "expiry_tracking": False, "accounting": True, "hr_module": True, "procurement": False, "ai_assistant": True, "loyalty": True, "fulfillment": False, "mobile_apps": False, "kitchen_display": False, "live_dispatch": False, }, },}
FEATURE_CATALOG: Dict[str, Dict[str, str]] = { "ecommerce": {"label": "Public storefront", "category": "commerce"}, "offline_pos": {"label": "Offline POS", "category": "sales"}, "multi_location": {"label": "Multi-location stock", "category": "inventory"}, "expiry_tracking": {"label": "Expiry & batch tracking", "category": "inventory"}, "accounting": {"label": "Accounting module", "category": "finance"}, "hr_module": {"label": "HR & payroll", "category": "operations"}, "procurement": {"label": "Purchase orders & GRN", "category": "operations"}, "ai_assistant": {"label": "AI customer assistant", "category": "ai"}, "loyalty": {"label": "Loyalty points", "category": "commerce"}, "fulfillment": {"label": "Fulfillment dashboard", "category": "logistics"}, "mobile_apps": {"label": "iOS + Android apps", "category": "mobile"}, "kitchen_display": {"label": "KDS + tableside QR", "category": "food"}, "live_dispatch": {"label": "Live spatial dispatch", "category": "food"},}
METRIC_CATALOG: Dict[str, Dict[str, str]] = { "skus": {"label": "SKUs", "unit": "count"}, "members": {"label": "Team members", "unit": "count"}, "locations": {"label": "Locations", "unit": "count"}, "orders_30d": {"label": "Orders (30d)", "unit": "count"}, "gmv_30d": {"label": "GMV (30d)", "unit": "naira"}, "ai_queries_30d": {"label": "AI queries (30d)", "unit": "count"}, "storage_mb": {"label": "Storage", "unit": "MB"}, "active_users_7d": {"label": "Active users (7d)","unit": "count"},}
def effective_features(org: Dict) -> Dict[str, bool]: status = (org or {}).get("status") or "active" if status in ("suspended", "churned"): return {k: False for k in FEATURE_CATALOG} tier = PLAN_TIERS.get((org or {}).get("plan_tier") or "", {}) base = dict(tier.get("features") or {}) base.update((org or {}).get("feature_overrides") or {}) for key in FEATURE_CATALOG: base.setdefault(key, False) return base
def effective_limit(org: Dict, metric: str): overrides = (org or {}).get("limits_overrides") or {} if metric in overrides: return overrides[metric] tier = PLAN_TIERS.get((org or {}).get("plan_tier") or "", {}) return tier.get(f"max_{metric}")
# ============================================================# FEATURE GATES# ============================================================async def fetch_org_flags(org_id: str) -> Optional[Dict]: if not org_id: return None client = get_admin_supabase() try: res = await run_sync_db_call( client.table("organisations") .select("id, status, plan_tier, feature_overrides, limits_overrides") .eq("id", org_id) .maybe_single() .execute ) return res.data if res else None except Exception as e: logger.error("fetch_org_flags failed", org_id=org_id, error=str(e)) return None
async def check_org_feature(org_id: str, feature_key: str) -> None: if not ENFORCE_FEATURES: return org = await fetch_org_flags(org_id) if not org: raise HTTPException(status_code=404, detail="Organisation not found") if (org.get("status") or "active") in ("suspended", "churned"): raise HTTPException(status_code=402, detail="Organisation suspended. Contact support to reactivate.") features = effective_features(org) if not features.get(feature_key, False): raise HTTPException( status_code=402, detail=f"Feature '{feature_key}' is not enabled for this organisation. " f"Contact support to upgrade your plan.", )
# ============================================================# AUTH PIPELINE# ============================================================async def get_current_user(authorization: str = Header(None)) -> Optional[Tuple[str, str]]: if not authorization or not authorization.startswith("Bearer "): return None token = authorization.split(" ")[1] try: auth_client = get_user_supabase() user = await run_sync_db_call(auth_client.auth.get_user, token) if user and user.user: email = getattr(user.user, "email", None) logger.info("get_current_user", user_id=user.user.id, email=email) return user.user.id, email logger.warning("get_current_user: no user from token") return None except Exception as e: logger.warning(f"get_current_user: invalid token - {e}") return None
async def _pick_default_org(client, org_rows: List[Dict]) -> Optional[Dict]: if not org_rows: return None org_ids = [r["org_id"] for r in org_rows] status_by_id: Dict[str, str] = {} try: status_res = await run_sync_db_call( client.table("organisations") .select("id, status") .in_("id", org_ids) .execute ) status_by_id = {o["id"]: (o.get("status") or "active") for o in (status_res.data or [])} except Exception as e: logger.warning(f"_pick_default_org: status lookup failed: {e}")
_prio = {"owner": 0, "admin": 1}
def sort_key(r): role_rank = _prio.get(r.get("role"), 2) status = status_by_id.get(r["org_id"], "active") status_rank = 1 if status in ("suspended", "churned") else 0 return (role_rank, status_rank, r.get("org_id") or "")
return sorted(org_rows, key=sort_key)[0]
async def get_current_org( authorization: str = Header(None), x_selected_org_id: Optional[str] = Header(None, alias="X-Selected-Org-Id"),) -> Tuple[str, str]: user_info = await get_current_user(authorization) if not user_info: raise HTTPException(status_code=401, detail="Not authenticated") token_user_id, email = user_info
client = get_supabase() resolved_user_id = token_user_id
try: res = await run_sync_db_call( client.table("org_members") .select("org_id, role") .eq("user_id", token_user_id) .order("org_id", desc=False) .execute ) org_rows = getattr(res, "data", []) or []
if x_selected_org_id: user_role_in_tenant = next( (org.get("role") for org in org_rows if str(org.get("org_id")) == str(x_selected_org_id)), None, ) if not user_role_in_tenant: raise HTTPException(status_code=403, detail="You are not a member of the requested organisation") return token_user_id, x_selected_org_id elif org_rows: chosen = await _pick_default_org(client, org_rows) return token_user_id, chosen["org_id"] except HTTPException: raise except Exception as e: logger.warning(f"Direct org lookup failed: {e}", exc_info=True)
if email: try: profile_res = await run_sync_db_call( client.table("profiles").select("id").eq("email", email).maybe_single().execute ) if profile_res and profile_res.data: resolved_user_id = profile_res.data["id"] res2 = await run_sync_db_call( client.table("org_members").select("org_id, role").eq("user_id", resolved_user_id).execute ) org_rows = getattr(res2, "data", []) or [] if x_selected_org_id: user_role_in_tenant = next( (org.get("role") for org in org_rows if str(org.get("org_id")) == str(x_selected_org_id)), None, ) if not user_role_in_tenant: raise HTTPException(status_code=403, detail="You are not a member of the requested organisation") return resolved_user_id, x_selected_org_id elif org_rows: chosen = await _pick_default_org(client, org_rows) return resolved_user_id, chosen["org_id"] except HTTPException: raise except Exception as e: logger.warning(f"Email fallback lookup failed: {e}", exc_info=True)
raise HTTPException( status_code=403, detail="Workspace Access Denied. Your credentials match, but you have not been assigned to an organization profile yet.", )
async def get_current_user_with_role( authorization: str = Header(None), x_selected_org_id: Optional[str] = Header(None, alias="X-Selected-Org-Id"),) -> Tuple[str, str, str]: user_id, org_id = await get_current_org(authorization, x_selected_org_id) client = get_supabase() member = await run_sync_db_call( client.table("org_members") .select("role") .eq("user_id", user_id) .eq("org_id", org_id) .maybe_single() .execute ) role = member.data["role"] if member and member.data else "customer" return user_id, org_id, role
async def _assert_org_not_suspended(org_id: str) -> None: if not org_id: return client = get_admin_supabase() try: res = await run_sync_db_call( client.table("organisations").select("status").eq("id", org_id).maybe_single().execute ) except Exception as e: logger.error("_assert_org_not_suspended: status read failed", org_id=org_id, error=str(e)) return if res and res.data and res.data.get("status") in ("suspended", "churned"): raise HTTPException(status_code=402, detail="Organisation suspended. Contact support to reactivate.")
async def _assert_branch_not_suspended( org_id: str, branch_id: Optional[str] = None, location_id: Optional[str] = None,) -> None: if not org_id: return client = get_admin_supabase() target_branch_id = (branch_id or "").strip() or None try: if not target_branch_id and location_id: loc_res = await run_sync_db_call( client.table("locations") .select("branch_id") .eq("id", str(location_id).strip()) .eq("org_id", org_id) .maybe_single() .execute ) if loc_res and loc_res.data: target_branch_id = loc_res.data.get("branch_id")
if not target_branch_id: return
br_res = await run_sync_db_call( client.table("branches") .select("id, is_active") .eq("id", target_branch_id) .eq("org_id", org_id) .maybe_single() .execute ) except Exception as e: logger.warning("_assert_branch_not_suspended: branch status read skipped", org_id=org_id, error=str(e)) return
if br_res and br_res.data and br_res.data.get("is_active") is False: raise HTTPException(status_code=403, detail="Branch suspended. Contact support to reactivate.")
# ============================================================# FASTAPI DEPENDENCIES# ============================================================def require_role(allowed_roles: List[str]): async def role_checker( request: Request, user_data: Tuple[str, str, str] = Depends(get_current_user_with_role), ): user_id, org_id, role = user_data if role not in allowed_roles: raise HTTPException(status_code=403, detail=f"Access denied. Required role: {allowed_roles}") await _assert_org_not_suspended(org_id) await _assert_branch_not_suspended( org_id, branch_id=request.headers.get("x-branch-id") or request.query_params.get("branch_id"), location_id=request.headers.get("x-location-id") or request.query_params.get("location_id"), ) return user_data return role_checker
def require_feature(feature_key: str, allowed_roles: Optional[List[str]] = None): async def check(user_data: Tuple[str, str, str] = Depends(get_current_user_with_role)): user_id, org_id, role = user_data if allowed_roles is not None and role not in allowed_roles: raise HTTPException(status_code=403, detail=f"Access denied. Required role: {allowed_roles}") await _assert_org_not_suspended(org_id) await check_org_feature(org_id, feature_key) return user_data return check
def require_feature_any(*feature_keys: str, allowed_roles: Optional[List[str]] = None): async def check(user_data: Tuple[str, str, str] = Depends(get_current_user_with_role)): user_id, org_id, role = user_data if allowed_roles is not None and role not in allowed_roles: raise HTTPException(status_code=403, detail=f"Access denied. Required role: {allowed_roles}") await _assert_org_not_suspended(org_id) if not ENFORCE_FEATURES: return user_data org = await fetch_org_flags(org_id) if not org: raise HTTPException(status_code=404, detail="Organisation not found") features = effective_features(org) if not any(features.get(k, False) for k in feature_keys): raise HTTPException(status_code=402, detail=f"None of {list(feature_keys)} is enabled for this organisation.") return user_data return check
# ============================================================# JWT ENRICHMENT# ============================================================async def _admin_set_app_metadata(user_id: str, metadata: dict) -> bool: if not SUPABASE_URL or not SUPABASE_SERVICE_ROLE_KEY: logger.warning("_admin_set_app_metadata: missing service role credentials") return False url = f"{SUPABASE_URL}/auth/v1/admin/users/{user_id}" headers = { "apikey": SUPABASE_SERVICE_ROLE_KEY, "Authorization": f"Bearer {SUPABASE_SERVICE_ROLE_KEY}", "Content-Type": "application/json", } try: async with httpx.AsyncClient(timeout=15.0) as http: resp = await http.put(url, json={"app_metadata": metadata}, headers=headers) if resp.status_code not in (200, 201): logger.error("_admin_set_app_metadata failed", user_id=user_id, status=resp.status_code, body=resp.text[:300]) return False logger.info("_admin_set_app_metadata ok", user_id=user_id, keys=list(metadata.keys())) return True except Exception as e: logger.error("_admin_set_app_metadata exception", user_id=user_id, error=str(e)) return False
# ============================================================# BRANCH RESOLUTION# ============================================================async def resolve_default_branch(org_id: str) -> Optional[str]: if not org_id: return None client = get_admin_supabase() default_res = await run_sync_db_call( client.table("branches").select("id") .eq("org_id", org_id).eq("is_default", True).limit(1).execute ) if default_res.data: return default_res.data[0]["id"] oldest_res = await run_sync_db_call( client.table("branches").select("id") .eq("org_id", org_id).order("created_at", desc=False).limit(1).execute ) return oldest_res.data[0]["id"] if oldest_res.data else None
async def ensure_default_branch(org_id: str) -> Optional[str]: if not org_id: return None existing = await resolve_default_branch(org_id) if existing: return existing client = get_admin_supabase() now = datetime.now(timezone.utc).isoformat() try: ins = await run_sync_db_call( client.table("branches").insert({ "org_id": org_id, "name": "Main", "code": "MAIN", "is_default": True, "created_at": now, "updated_at": now, }).execute ) if ins.data: return ins.data[0]["id"] except Exception as e: logger.warning("ensure_default_branch: insert lost race", org_id=org_id, error=str(e)[:200]) return await resolve_default_branch(org_id)
async def get_user_branches(user_id: str, org_id: str) -> List[Dict]: client = get_supabase() role_res = await run_sync_db_call( client.table("org_members").select("role") .eq("user_id", user_id).eq("org_id", org_id).limit(1).execute ) role = role_res.data[0].get("role") if role_res.data else "customer" if role == "owner": branches_res = await run_sync_db_call( client.table("branches").select("id, name, code, is_default") .eq("org_id", org_id).order("is_default", desc=True).order("name").execute ) return [ {"id": b["id"], "name": b.get("name"), "code": b.get("code"), "is_default": bool(b.get("is_default"))} for b in (branches_res.data or []) ] mem_res = await run_sync_db_call( client.table("branch_members") .select("branch_id, branches(id, name, code, is_default)") .eq("org_id", org_id).eq("user_id", user_id).execute ) branches = [] for row in (mem_res.data or []): b = row.get("branches") or {} if b: branches.append({ "id": b.get("id"), "name": b.get("name"), "code": b.get("code"), "is_default": bool(b.get("is_default")), }) branches.sort(key=lambda x: (not x["is_default"], (x["name"] or "").lower())) return branches
async def is_user_in_branch(user_id: str, org_id: str, branch_id: str) -> bool: if not branch_id or not org_id or not user_id: return False client = get_admin_supabase() role_res = await run_sync_db_call( client.table("org_members").select("role") .eq("user_id", user_id).eq("org_id", org_id).limit(1).execute ) role = role_res.data[0].get("role") if role_res.data else None if role == "owner": branch_res = await run_sync_db_call( client.table("branches").select("id") .eq("id", branch_id).eq("org_id", org_id).limit(1).execute ) return bool(branch_res.data) mem_res = await run_sync_db_call( client.table("branch_members").select("id") .eq("org_id", org_id).eq("user_id", user_id).eq("branch_id", branch_id).limit(1).execute ) return bool(mem_res.data)
async def resolve_request_branch(request: Request, user_id: str, org_id: str, role: str) -> Optional[str]: header_branch = (request.headers.get("X-Selected-Branch-Id") or "").strip() if header_branch: if not await is_user_in_branch(user_id, org_id, header_branch): raise HTTPException(403, "You are not a member of the selected branch") return header_branch try: auth_header = request.headers.get("authorization", "") if auth_header.startswith("Bearer "): token = auth_header.split(" ", 1)[1] auth_client = get_user_supabase() user_resp = await run_sync_db_call(auth_client.auth.get_user, token) if user_resp and user_resp.user: app_meta = getattr(user_resp.user, "app_metadata", None) or {} meta_branch = app_meta.get("branch_scope") if meta_branch and await is_user_in_branch(user_id, org_id, meta_branch): return meta_branch except Exception as e: logger.warning(f"resolve_request_branch: app_metadata read failed: {e}") if role == "owner": return None branches = await get_user_branches(user_id, org_id) if len(branches) == 1: return branches[0]["id"] if len(branches) == 0: default_id = await ensure_default_branch(org_id) if default_id: return default_id raise HTTPException(400, "No branch assigned. Contact your administrator.") raise HTTPException(400, "Multiple branches available. Send X-Selected-Branch-Id header.")
async def resolve_request_branch_for_write(request: Request, user_id: str, org_id: str, role: str) -> str: branch = await resolve_request_branch(request, user_id, org_id, role) if branch: return branch default_id = await ensure_default_branch(org_id) if not default_id: raise HTTPException(500, "No default branch for this organisation") return default_id
async def get_visible_user_ids(user_id: str, org_id: str, role: str) -> Optional[set]: if role == "owner": return None client = get_supabase() my_branches_res = await run_sync_db_call( client.table("branch_members").select("branch_id") .eq("user_id", user_id).eq("org_id", org_id).execute ) branch_ids = [r["branch_id"] for r in (my_branches_res.data or []) if r.get("branch_id")] if not branch_ids: return {user_id} members_res = await run_sync_db_call( client.table("branch_members").select("user_id") .eq("org_id", org_id).in_("branch_id", branch_ids).execute ) visible = {r["user_id"] for r in (members_res.data or []) if r.get("user_id")} visible.add(user_id) return visible
import timefrom typing import Optional, Dict, Tuple
# ── SHARED INVENTORY/CHANNEL HELPERS ──_LOC_CHANNEL_CACHE: Dict[Tuple[str, str], Tuple[Optional[str], float]] = {}_LOC_CHANNEL_TTL = 300.0
async def get_location_for_channel(org_id: str, channel: str) -> Optional[str]: if not org_id: return None cache_key = (org_id, channel) now = time.time() hit = _LOC_CHANNEL_CACHE.get(cache_key) if hit is not None and (now - hit[1]) < _LOC_CHANNEL_TTL: return hit[0]
priority = {"pos": ["store", "warehouse"], "online": ["online_fulfillment", "warehouse"]}.get(channel, ["warehouse"]) client = get_admin_supabase() resolved: Optional[str] = None
for loc_type in priority: result = await run_sync_db_call( client.table("locations").select("id").eq("org_id", org_id).eq("type", loc_type).eq("is_active", True).order("created_at", desc=False).limit(1).execute ) if result.data: resolved = result.data[0]["id"] break
if resolved is None: fallback = await run_sync_db_call( client.table("locations").select("id").eq("org_id", org_id).eq("is_active", True).order("created_at", desc=False).limit(1).execute ) resolved = fallback.data[0]["id"] if fallback.data else None
_LOC_CHANNEL_CACHE[cache_key] = (resolved, now) return resolved
_SALE_CACHE: Dict[str, Tuple[Dict[int, Dict], float]] = {}_SALE_TTL = 60.0
async def get_active_sale_prices(org_id: str, inventory_ids: Optional[List[int]] = None) -> Dict[int, Dict]: if not org_id: return {} now = time.time() hit = _SALE_CACHE.get(org_id) if hit is not None and (now - hit[1]) < _SALE_TTL: sale_map = hit[0] else: client = get_supabase() now_iso = datetime.now(timezone.utc).isoformat() try: q = (client.table("flash_sales").select("id, name, ends_at, flash_sale_items(inventory_id, original_price, sale_price)").eq("org_id", org_id).eq("is_active", True).lte("starts_at", now_iso).gte("ends_at", now_iso)) res = await run_sync_db_call(q.execute) except Exception as e: logger.error("get_active_sale_prices failed", org_id=org_id, error=str(e)) return {}
out: Dict[int, Dict] = {} for sale in (res.data or []): for item in (sale.get("flash_sale_items") or []): inv_id = item.get("inventory_id") if inv_id is None: continue sale_price = float(item.get("sale_price") or 0) existing = out.get(inv_id) if existing is None or sale_price < existing["sale_price"]: out[inv_id] = {"sale_price": sale_price, "original_price": float(item.get("original_price") or 0), "sale_id": sale.get("id"), "sale_name": sale.get("name"), "ends_at": sale.get("ends_at")} sale_map = out _SALE_CACHE[org_id] = (sale_map, now)
if inventory_ids is None: return dict(sale_map) wanted = set(inventory_ids) return {k: v for k, v in sale_map.items() if k in wanted}
async def _assert_storefront_live(org_id: str) -> None: if not org_id: raise HTTPException(status_code=404, detail="Store not found") from deps import fetch_org_flags org = await fetch_org_flags(org_id) if not org: raise HTTPException(status_code=404, detail="Store not found") if (org.get("status") or "active") in ("suspended", "churned"): raise HTTPException(status_code=404, detail="Store not found")
# ============================================================# LOCATION-SCOPED INVENTORY READ (moved from main.py — do not duplicate)# ============================================================async def fetch_inventory_scoped_to_location( org_id: str, location_id: str, limit: int, offset: int, q: Optional[str] = None, category: Optional[str] = None, sort_by: str = "newest", require_positive_stock: bool = False, include_count: bool = True,) -> Tuple[List[Dict], int]: """ Read inventory rows scoped to a single location. Response row = full inventory row + location-scoped overrides: - current_qty : OVERRIDDEN to location-specific quantity - location_qty : same value, explicit - global_qty : original inventory.current_qty (org-wide) - location_id : the location we scoped to
include_count: When True (default), PostgREST returns an exact total via count="exact", which costs a second COUNT(*) round trip (2 network calls total for the list query). Callers that need a real total for a pager (storefront) should leave this at True. Callers that do not (POS terminal) should pass include_count=False and save the second round trip.
When False, PostgREST returns no Content-Range header, so result.count is None and total falls through to 0. Callers that opted out of counting do not have a use for a total, so returning 0 is the honest value: "we did not count." """ client = get_supabase()
query = ( client.table("inventory") .select( "*, location_stocks!inner(location_id, quantity, reserved_quantity)", count="exact" if include_count else None, ) .eq("org_id", org_id) .eq("location_stocks.location_id", location_id) )
if q: or_condition = ( f"description.ilike.%{q}%," f"item_code.ilike.%{q}%," f"product_group.ilike.%{q}%" ) # supabase-py's SyncSelectRequestBuilder has no .or_() method, so # set the raw PostgREST "or" parameter directly — same pattern as # the /inventory/search endpoint. When ORG_SCOPE_CANARY is on, # `query` is wrapped in _CanaryBuilder, whose __slots__ blocks # attribute assignment, so unwrap via _inner before writing .params. target = getattr(query, "_inner", query) target.params = target.params.set("or", f"({or_condition})")
if category: query = query.eq("product_group", category)
if require_positive_stock: query = query.gt("location_stocks.quantity", 0)
if sort_by == "price_asc": query = query.order("price_naira", desc=False) elif sort_by == "price_desc": query = query.order("price_naira", desc=True) else: query = query.order("id", desc=True)
result = await run_sync_db_call(query.range(offset, offset + limit - 1).execute) rows = result.data or [] total = result.count or 0
items: List[Dict] = [] for row in rows: stocks = row.pop("location_stocks", None) or [] # Sum across every batch at this location. The distribute_batch_to_locations # trigger creates one location_stocks row per batch, so stocks[0] would # report only the first batch's quantity once a second delivery lands. loc_qty = sum(int(s.get("quantity") or 0) for s in stocks) if stocks else 0 global_qty = int(row.get("current_qty") or 0) row["current_qty"] = loc_qty row["location_qty"] = loc_qty row["global_qty"] = global_qty row["location_id"] = location_id items.append(row)
return items, total
# ============================================================# STOREFRONT ORG RESOLUTION# ============================================================async def resolve_store_org( request: Request, org_id: Optional[str] = None, store_slug: Optional[str] = None,) -> str: """ Resolve the org that owns the storefront being requested.
Resolution order (first match wins): 1. X-Selected-Org-Id request header (multi-tenant client) 2. explicit `org_id` query / body param 3. `store_slug` lookup in organisations.store_slug 4. PUBLIC_STORE_ORG_ID — ONLY when SINGLE_TENANT_STOREFRONT=true
Raises 404 if none match. Never silently falls back to a global org id in a multi-tenant deploy — that was the 2026-11 regression. """ header_org = (request.headers.get("X-Selected-Org-Id") or "").strip() if header_org: return header_org
if org_id: return org_id
if store_slug: client = get_admin_supabase() try: res = await run_sync_db_call( client.table("organisations") .select("id") .eq("store_slug", store_slug) .maybe_single() .execute ) if res and res.data: return res.data["id"] except Exception as e: logger.warning( "resolve_store_org slug lookup failed", store_slug=store_slug, error=str(e)[:200], )
if ( os.environ.get("SINGLE_TENANT_STOREFRONT", "false").lower() == "true" and PUBLIC_STORE_ORG_ID ): return PUBLIC_STORE_ORG_ID
raise HTTPException(status_code=404, detail="Store not found")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Extended executive dashboard — profitability view."""from fastapi import APIRouter, Depends, Request, Queryfrom typing import Tuplefrom datetime import date, datetime, timezone, timedelta
from main import ( get_supabase, run_sync_db_call, rate_limit, get_client_ip,)from deps import require_feature, require_role, get_user_branches, get_visible_user_ids, resolve_request_branch_for_write, resolve_request_branch, resolve_default_branch, is_user_in_branch, ensure_default_branch
router = APIRouter(prefix="/dashboard", tags=["Executive Dashboard"])
@router.get("/profitability")async def profitability( request: Request, from_date: date = Query(...), to_date: date = Query(...), user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "finance"]) ),): """ One-shot profitability analysis for a date range, scoped to the caller's selected branch. """ await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase()
selected_branch = await resolve_request_branch(request, user_id, org_id, role)
from_iso = from_date.isoformat() to_iso = to_date.isoformat()
# ── 1. Revenue & COGS from sales ────────────────────────────── sales_q = ( client.table("sales") .select("id, total_amount, created_at") .eq("org_id", org_id) .eq("status", "completed") .gte("created_at", f"{from_iso}T00:00:00") .lte("created_at", f"{to_iso}T23:59:59") ) if selected_branch: sales_q = sales_q.eq("branch_id", selected_branch)
sales_res = await run_sync_db_call(sales_q.execute) sales_rows = sales_res.data or [] revenue = sum(float(s.get("total_amount") or 0) for s in sales_rows) sales_ids = [s["id"] for s in sales_rows]
cogs = 0.0 cogs_by_product: dict = {} if sales_ids: si_res = await run_sync_db_call( client.table("sale_items") .select("inventory_id, product_name, quantity, subtotal") .in_("sale_id", sales_ids) .execute ) si_rows = si_res.data or [] inv_ids = list({r["inventory_id"] for r in si_rows if r.get("inventory_id")}) cost_map = {} if inv_ids: inv_res = await run_sync_db_call( client.table("inventory") .select("id, cost_price_naira") .eq("org_id", org_id) .in_("id", inv_ids) .execute ) cost_map = {r["id"]: float(r.get("cost_price_naira") or 0) for r in (inv_res.data or [])}
for si in si_rows: unit_cost = cost_map.get(si["inventory_id"], 0) line_cogs = unit_cost * int(si["quantity"] or 0) cogs += line_cogs name = si.get("product_name") or f"Item {si['inventory_id']}" cogs_by_product[name] = cogs_by_product.get(name, 0.0) + line_cogs
gross_profit = revenue - cogs
# ── 2. Operating expenses ──────────────────────────────────── exp_q = ( client.table("expenses") .select("category, amount") .eq("org_id", org_id) .eq("status", "posted") .gte("expense_date", from_iso) .lte("expense_date", to_iso) ) if selected_branch: exp_q = exp_q.eq("branch_id", selected_branch)
exp_res = await run_sync_db_call(exp_q.execute) exp_rows = exp_res.data or [] total_expenses = sum(float(r.get("amount") or 0) for r in exp_rows)
expense_by_cat: dict = {} for r in exp_rows: cat = r.get("category") or "Uncategorised" expense_by_cat[cat] = expense_by_cat.get(cat, 0.0) + float(r.get("amount") or 0)
net_income = gross_profit - total_expenses
# ── 3. Waste ───────────────────────────────────────────────── # # FIX: `inventory` must be in the SELECT with !inner, otherwise # PostgREST cannot resolve the filter `.eq("inventory.org_id", ...)` # and returns 400 — which is why /dashboard/profitability was 500ing # and the dashboard showed "Failed to load profitability data". waste_value = 0.0 expired_q = ( client.table("inventory_batches") .select("id, quantity, cost_price_naira, inventory:inventory_id!inner(org_id)") .eq("inventory.org_id", org_id) .gte("expiry_date", from_iso) .lte("expiry_date", to_iso) ) expired_res = await run_sync_db_call(expired_q.execute) expired_batches = {r["id"]: r for r in (expired_res.data or [])}
if expired_batches and not selected_branch: waste_value = sum( float(b.get("quantity") or 0) * float(b.get("cost_price_naira") or 0) for b in expired_batches.values() ) elif expired_batches and selected_branch: ls_res = await run_sync_db_call( client.table("location_stocks") .select("batch_id, quantity, location:locations!inner(branch_id)") .in_("batch_id", list(expired_batches.keys())) .eq("location.branch_id", selected_branch) .execute ) waste_value = sum( float(r.get("quantity") or 0) * float(expired_batches[r["batch_id"]].get("cost_price_naira") or 0) for r in (ls_res.data or []) if r.get("batch_id") in expired_batches )
# ── 4. Uncollected A/R ─────────────────────────────────────── ar_q = ( client.table("accounts_receivable") .select("amount, paid_amount, status, due_date") .eq("org_id", org_id) .gte("due_date", from_iso) .lte("due_date", to_iso) .in_("status", ["pending", "partial", "overdue"]) ) if selected_branch: ar_q = ar_q.eq("branch_id", selected_branch)
ar_res = await run_sync_db_call(ar_q.execute) ar_rows = ar_res.data or [] uncollected_ar = sum( float(r.get("amount") or 0) - float(r.get("paid_amount") or 0) for r in ar_rows )
# ── 5. Month-by-month breakdown ────────────────────────────── monthly: dict = {} for s in sales_rows: m = (s.get("created_at") or "")[:7] if m not in monthly: monthly[m] = {"revenue": 0.0, "expenses": 0.0} monthly[m]["revenue"] += float(s.get("total_amount") or 0) for e in exp_rows: m = (e.get("expense_date") or "")[:7] if m not in monthly: monthly[m] = {"revenue": 0.0, "expenses": 0.0} monthly[m]["expenses"] += float(e.get("amount") or 0)
# ── 6. Compose response ────────────────────────────────────── top_cogs = [ {"product": k, "cogs": round(v, 2)} for k, v in sorted(cogs_by_product.items(), key=lambda x: -x[1])[:10] ] top_expenses = [ {"category": k, "amount": round(v, 2)} for k, v in sorted(expense_by_cat.items(), key=lambda x: -x[1])[:10] ]
def pct(num, den): return round((num / den) * 100, 2) if den else 0.0
return { "period": {"from": from_iso, "to": to_iso}, "branch_id": selected_branch, "revenue": round(revenue, 2), "cogs": round(cogs, 2), "gross_profit": round(gross_profit, 2), "gross_margin_pct": pct(gross_profit, revenue), "operating_expenses": round(total_expenses, 2), "net_income": round(net_income, 2), "net_margin_pct": pct(net_income, revenue), "waste_value": round(waste_value, 2), "uncollected_ar": round(uncollected_ar, 2), "top_cogs_products": top_cogs, "top_expense_categories": top_expenses, "monthly_breakdown": [ { "month": m, "revenue": round(v.get("revenue", 0.0), 2), "expenses": round(v.get("expenses", 0.0), 2), } for m, v in sorted(monthly.items()) ], "cost_drivers_summary": { "largest_cogs_product": top_cogs[0]["product"] if top_cogs else None, "largest_cogs_value": top_cogs[0]["cogs"] if top_cogs else 0.0, "largest_expense_category": top_expenses[0]["category"] if top_expenses else None, "largest_expense_value": top_expenses[0]["amount"] if top_expenses else 0.0, "waste_vs_revenue_pct": pct(waste_value, revenue), }, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381"""Expense entry module.Register at the bottom of main.py: from expenses import router as expenses_router app.include_router(expenses_router)"""from fastapi import APIRouter, Depends, HTTPException, Request, Queryfrom pydantic import BaseModel, Fieldfrom typing import Optional, Tuple, Literal, Listfrom datetime import date, datetime, timezonefrom uuid import UUID
# These live in main.py today. The bottom-of-file include# ensures this import resolves.from main import ( # noqa: E402 get_supabase, run_sync_db_call, rate_limit, get_client_ip, resolve_branch_for_write, create_journal_entry, _log_audit_event,)from deps import require_feature, require_role, get_user_branches, get_visible_user_ids, resolve_request_branch_for_write, resolve_request_branch, resolve_default_branch, is_user_in_branch, ensure_default_branch
router = APIRouter(prefix="/expenses", tags=["Expenses"])
# ─── Models ──────────────────────────────────────────────────────────
class ExpenseCreate(BaseModel): expense_date: date category: str = Field(..., min_length=1, max_length=100) account_id: Optional[UUID] = None vendor: Optional[str] = Field(None, max_length=200) description: Optional[str] = Field(None, max_length=1000) amount: float = Field(..., gt=0) payment_method: Literal["cash", "bank_transfer", "card", "cheque", "credit"] = "cash" reference: Optional[str] = Field(None, max_length=100) receipt_url: Optional[str] = Field(None, max_length=500)
class ExpenseUpdate(BaseModel): expense_date: Optional[date] = None category: Optional[str] = Field(None, min_length=1, max_length=100) account_id: Optional[UUID] = None vendor: Optional[str] = Field(None, max_length=200) description: Optional[str] = Field(None, max_length=1000) amount: Optional[float] = Field(None, gt=0) payment_method: Optional[Literal["cash", "bank_transfer", "card", "cheque", "credit"]] = None reference: Optional[str] = Field(None, max_length=100) receipt_url: Optional[str] = Field(None, max_length=500)
# ─── Helpers ─────────────────────────────────────────────────────────
async def _resolve_cash_account(client, org_id: str) -> Optional[str]: """Prefer a cash account, fall back to any asset account.""" res = await run_sync_db_call( client.table("chart_of_accounts") .select("id") .eq("org_id", org_id) .eq("type", "asset") .ilike("name", "%cash%") .limit(1) .execute ) if res.data: return res.data[0]["id"]
res = await run_sync_db_call( client.table("chart_of_accounts") .select("id") .eq("org_id", org_id) .eq("type", "asset") .limit(1) .execute ) return res.data[0]["id"] if res.data else None
async def _resolve_expense_account(client, org_id: str) -> Optional[str]: """Fall back to any expense-type account.""" res = await run_sync_db_call( client.table("chart_of_accounts") .select("id") .eq("org_id", org_id) .eq("type", "expense") .limit(1) .execute ) return res.data[0]["id"] if res.data else None
# ─── Endpoints ───────────────────────────────────────────────────────
@router.post("")async def create_expense( request: Request, payload: ExpenseCreate, user_data: Tuple[str, str, str] = Depends( require_feature("accounting", allowed_roles=["owner", "admin", "finance"]) ),): """ Create an expense. Also posts a balanced journal entry: Debit Expense account amount Credit Cash (or AP) amount
If `payment_method == 'credit'`, the credit side goes to an A/P account; otherwise to a cash account. """ await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, _ = user_data client = get_supabase()
# Validate the category if not payload.category.strip(): raise HTTPException(status_code=400, detail="Category is required")
# Resolve accounts expense_account_id = str(payload.account_id) if payload.account_id else await _resolve_expense_account(client, org_id) if not expense_account_id: raise HTTPException( status_code=400, detail="No expense-type account exists in chart_of_accounts for this org. Create one first.", )
if payload.payment_method == "credit": ap_res = await run_sync_db_call( client.table("chart_of_accounts") .select("id") .eq("org_id", org_id) .eq("type", "liability") .ilike("name", "%accounts payable%") .limit(1) .execute ) credit_account_id = ap_res.data[0]["id"] if ap_res.data else None else: credit_account_id = await _resolve_cash_account(client, org_id)
if not credit_account_id: raise HTTPException( status_code=400, detail="No cash/ap account available to post the credit side of the entry.", )
# Insert the expense row branch_id = await resolve_branch_for_write(org_id) now_iso = datetime.now(timezone.utc).isoformat()
insert_res = await run_sync_db_call( client.table("expenses").insert({ "org_id": org_id, "branch_id": branch_id, "expense_date": payload.expense_date.isoformat(), "category": payload.category.strip(), "account_id": expense_account_id, "vendor": payload.vendor, "description": payload.description, "amount": payload.amount, "payment_method": payload.payment_method, "reference": payload.reference, "receipt_url": payload.receipt_url, "status": "posted", "created_by": user_id, "created_at": now_iso, "updated_at": now_iso, }).execute ) if not insert_res.data: raise HTTPException(status_code=500, detail="Failed to record expense")
expense = insert_res.data[0]
# Journal entry try: journal = await create_journal_entry( org_id=org_id, entry_date=payload.expense_date, description=f"Expense: {payload.category}" + (f" — {payload.vendor}" if payload.vendor else ""), lines=[ {"account_id": expense_account_id, "debit": payload.amount, "credit": 0}, {"account_id": credit_account_id, "debit": 0, "credit": payload.amount}, ], reference=payload.reference or f"EXP-{str(expense['id'])[:8]}", created_by=user_id, status="posted", ) # Link the journal back to the expense await run_sync_db_call( client.table("expenses") .update({"journal_entry_id": journal["id"]}) .eq("id", expense["id"]) .execute ) expense["journal_entry_id"] = journal["id"] except Exception as e: # Journal failure should not roll back the expense record itself; # surface it so the operator can fix the chart_of_accounts. raise HTTPException( status_code=500, detail=f"Expense saved but journal posting failed: {e}", )
await _log_audit_event(org_id, user_id, "expenses", "create", UUID(expense["id"]), None, expense)
return {"expense": expense}
@router.get("")async def list_expenses( request: Request, from_date: Optional[date] = Query(None, description="Filter: expense_date >= from_date (YYYY-MM-DD)"), to_date: Optional[date] = Query(None, description="Filter: expense_date <= to_date (YYYY-MM-DD)"), category: Optional[str] = Query(None), payment_method: Optional[str] = Query(None), limit: int = Query(500, ge=1, le=2000), offset: int = Query(0, ge=0), user_data: Tuple[str, str, str] = Depends( require_feature("accounting", allowed_roles=["owner", "admin", "finance", "auditor"]) ),): """ List expenses. Filters by date range (expense_date), category, payment method, and — when the caller has picked a branch — by branch. `total` is the exact number of matching rows from `count="exact"`, independent of the limit/offset slice. """ await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase()
# Branch scoping. Owners with no branch header see all branches; # everyone else sees their selected branch (or their single # branch if they only have one). selected_branch = await resolve_request_branch(request, user_id, org_id, role)
q = client.table("expenses").select("*", count="exact").eq("org_id", org_id)
if selected_branch: q = q.eq("branch_id", selected_branch)
if from_date: q = q.gte("expense_date", from_date.isoformat()) if to_date: q = q.lte("expense_date", to_date.isoformat()) if category: q = q.eq("category", category) if payment_method: q = q.eq("payment_method", payment_method)
res = await run_sync_db_call( q.order("expense_date", desc=True).range(offset, offset + limit - 1).execute ) return { "expenses": res.data or [], "total": res.count or 0, "limit": limit, "offset": offset, }
@router.get("/summary")async def expenses_summary( request: Request, from_date: date = Query(...), to_date: date = Query(...), user_data: Tuple[str, str, str] = Depends( require_feature("accounting", allowed_roles=["owner", "admin", "finance", "auditor"]) ),): """ Totals grouped by category, plus a daily series for charting. Branch-scoped: if the caller has selected a branch, the totals match the list endpoint for that same branch. """ await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase()
selected_branch = await resolve_request_branch(request, user_id, org_id, role)
q = ( client.table("expenses") .select("expense_date, category, amount, payment_method") .eq("org_id", org_id) .gte("expense_date", from_date.isoformat()) .lte("expense_date", to_date.isoformat()) .eq("status", "posted") ) if selected_branch: q = q.eq("branch_id", selected_branch)
res = await run_sync_db_call(q.execute) rows = res.data or []
by_category: dict = {} by_day: dict = {} by_method: dict = {} total = 0.0
for r in rows: amt = float(r.get("amount") or 0) total += amt
cat = r.get("category") or "Uncategorised" by_category[cat] = by_category.get(cat, 0.0) + amt
day = r.get("expense_date") by_day[day] = by_day.get(day, 0.0) + amt
m = r.get("payment_method") or "unknown" by_method[m] = by_method.get(m, 0.0) + amt
return { "period": {"from": from_date.isoformat(), "to": to_date.isoformat()}, "total": round(total, 2), "by_category": [ {"category": k, "amount": round(v, 2)} for k, v in sorted(by_category.items(), key=lambda x: -x[1]) ], "by_payment_method": [ {"method": k, "amount": round(v, 2)} for k, v in sorted(by_method.items(), key=lambda x: -x[1]) ], "daily_series": [ {"date": k, "amount": round(v, 2)} for k, v in sorted(by_day.items()) ], }
@router.delete("/{expense_id}")async def delete_expense( request: Request, expense_id: UUID, user_data: Tuple[str, str, str] = Depends( require_feature("accounting", allowed_roles=["owner", "admin", "finance"]) ),): """ Soft-delete: sets status='void'. The journal entry is left in place so the audit trail stays intact. To truly reverse the accounting, create a reversing journal entry manually. """ await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, _ = user_data client = get_supabase()
existing = await run_sync_db_call( client.table("expenses") .select("id, status") .eq("id", str(expense_id)) .eq("org_id", org_id) .maybe_single() .execute ) if not existing or not existing.data: raise HTTPException(status_code=404, detail="Expense not found") if existing.data.get("status") == "void": return {"message": "Already void"}
await run_sync_db_call( client.table("expenses") .update({ "status": "void", "updated_at": datetime.now(timezone.utc).isoformat(), }) .eq("id", str(expense_id)) .eq("org_id", org_id) .execute )
await _log_audit_event( org_id, user_id, "expenses", "void", expense_id, existing.data, {"status": "void"}, ) return {"message": "Expense voided"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227# geo.pyimport osimport mathimport httpximport loggingfrom datetime import datetime, timezonefrom zoneinfo import ZoneInfofrom typing import Optional, Tuplefrom deps import run_sync_db_call
logger = logging.getLogger(__name__)
LOCAL_TZ = ZoneInfo("Africa/Lagos")AWS_LOCATION_API_KEY = os.environ.get("AWS_LOCATION_API_KEY")AWS_LOCATION_REGION = os.environ.get("AWS_LOCATION_REGION", "eu-west-1")CLIENT_COORD_MAX_DISCREPANCY_M = float(os.environ.get("CLIENT_COORD_MAX_DISCREPANCY_M", "1000"))
def haversine_m(lat1: float, lng1: float, lat2: float, lng2: float) -> float: R = 6371000.0 phi1, phi2 = math.radians(lat1), math.radians(lat2) dphi = math.radians(lat2 - lat1) dlambda = math.radians(lng2 - lng1) a = math.sin(dphi / 2.0) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2.0) ** 2 return 2.0 * R * math.asin(math.sqrt(a))
def is_peak_hour(order_time: datetime, peak_settings: list) -> bool: if not order_time: order_time = datetime.now(LOCAL_TZ) elif order_time.tzinfo is None: # Naive input: assume UTC (matches datetime.now(timezone.utc) and Render/HF servers) order_time = order_time.replace(tzinfo=timezone.utc).astimezone(LOCAL_TZ) else: order_time = order_time.astimezone(LOCAL_TZ)
dow = order_time.weekday() hour_min = order_time.strftime("%H:%M")
for setting in peak_settings: if setting.get("day_of_week") is not None and setting["day_of_week"] != dow: continue start = setting.get("start_time") end = setting.get("end_time") if start and end: if str(start)[:5] <= hour_min <= str(end)[:5]: return True return False
async def proxy_aws_places(endpoint: str, body: dict) -> dict: if not AWS_LOCATION_API_KEY: raise ValueError("AWS Location not configured") url = f"https://places.geo.{AWS_LOCATION_REGION}.amazonaws.com/v2/{endpoint}" async with httpx.AsyncClient(timeout=10.0) as client: resp = await client.post(url, params={"key": AWS_LOCATION_API_KEY}, json=body) if resp.status_code != 200: logger.error(f"AWS Places error: {resp.text}") raise ValueError(f"Places API error: {resp.status_code}") return resp.json()
async def resolve_delivery_coords( address: Optional[str], client_lat: Optional[float], client_lng: Optional[float], customer_email: Optional[str] = None,) -> Optional[Tuple[float, float]]: """Verify client coordinates against server geocoding to prevent zone-fee spoofing.""" if not address or not address.strip(): return None
client_coords = None if client_lat is not None and client_lng is not None: try: client_coords = (float(client_lat), float(client_lng)) except (TypeError, ValueError): pass
server_coords = None try: geo_res = await proxy_aws_places("geocode", {"QueryText": address, "MaxResults": 1}) items = geo_res.get("ResultItems", []) if items: lng, lat = items[0]["Position"] server_coords = (lat, lng) except Exception as e: logger.warning(f"AWS geocode failed for '{address}': {e}")
if server_coords and client_coords: dist_m = haversine_m(server_coords[0], server_coords[1], client_coords[0], client_coords[1]) if dist_m <= CLIENT_COORD_MAX_DISCREPANCY_M: return client_coords logger.warning( f"Coord mismatch for '{address}' (customer={customer_email}): " f"client={client_coords} server={server_coords} dist={dist_m:.0f}m. Using server." ) return server_coords
return server_coords or client_coords
async def calculate_intelligent_fee( org_id: str, base_fee: int, order_value: int, items: list, order_time: datetime, customer_email: str, db_client) -> dict: """Ported from Hot Portion, adapted for bOS org-scoping""" fee = base_fee value_discount = 0 item_surcharge = 0 peak_surcharge = 0 loyalty_discount = 0 volume_surcharge = 0 minimum_fee = 500
# 1. Fetch product details for weight/bulky logic. # ORG FILTER IS MANDATORY — without it, an attacker can pass # arbitrary inventory_ids and read another tenant's weight/category # by observing the calculated fee. inv_ids = [i.get("inventory_id") for i in items if i.get("inventory_id")] prod_map = {} if inv_ids: res = await run_sync_db_call( db_client.table("inventory") .select("id, weight_kg, handling_category") .eq("org_id", org_id) .in_("id", inv_ids) .execute ) prod_map = {p["id"]: p for p in (res.data or [])}
main_count, total_weight, bulky_count = 0, 0.0, 0 total_items = sum(i.get("quantity", 1) for i in items)
for item in items: prod = prod_map.get(item.get("inventory_id", 0), {}) main_count += item.get("quantity", 1) total_weight += float(prod.get("weight_kg") or 0.5) * item.get("quantity", 1) if prod.get("handling_category") == "bulky": bulky_count += item.get("quantity", 1)
# 2. Volume / Weight Surcharges if total_items >= 10: volume_surcharge += 500 elif total_items >= 6: volume_surcharge += 300 elif total_items >= 4: volume_surcharge += 150
if total_weight > 5.0: volume_surcharge += int((total_weight - 5.0) * 100) if bulky_count > 0: volume_surcharge += bulky_count * 200
# 3. Item Surcharge Rules rules_res = await run_sync_db_call( db_client.table("delivery_item_surcharge_rules").select("*").eq("org_id", org_id).execute ) for rule in (rules_res.data or []): min_i, max_i = rule.get("min_main_items"), rule.get("max_main_items") if (min_i is None or main_count >= min_i) and (max_i is None or main_count <= max_i): item_surcharge += rule.get("surcharge_amount", 0) break
# 4. Peak Settings peak_res = await run_sync_db_call( db_client.table("delivery_peak_settings").select("*").eq("org_id", org_id).eq("is_active", True).execute ) if is_peak_hour(order_time, peak_res.data or []): peak_surcharge = 200
# 5. Loyalty Discount if customer_email: loy_res = await run_sync_db_call( db_client.table("delivery_loyalty_settings").select("*").eq("org_id", org_id).eq("is_active", True).limit(1).execute ) if loy_res.data: setting = loy_res.data[0] orders_res = await run_sync_db_call( db_client.table("sales") .select("id", count="exact") .eq("org_id", org_id) .eq("customer_email", customer_email) .in_("status", ["paid", "confirmed", "completed"]) .execute ) if (orders_res.count or 0) >= setting.get("min_orders", 5): disc_pct = min(setting.get("discount_percentage", 20), 15) loyalty_discount = int(fee * disc_pct / 100) fee -= loyalty_discount
fee += volume_surcharge + item_surcharge + peak_surcharge
# 6. Value Discounts val_res = await run_sync_db_call( db_client.table("delivery_fee_rules").select("*").eq("org_id", org_id).order("min_order_value").execute ) for rule in (val_res.data or []): min_v, max_v = rule.get("min_order_value", 0), rule.get("max_order_value") if order_value >= min_v and (max_v is None or order_value <= max_v): if rule.get("free_delivery"): value_discount = fee fee = 0 else: new_fee = fee * rule.get("fee_multiplier", 1.0) - rule.get("fee_discount", 0) value_discount = fee - new_fee fee = max(0, new_fee) break
if fee > 0 and fee < minimum_fee: fee = minimum_fee
return { "base_fee": base_fee, "volume_surcharge": volume_surcharge, "item_surcharge": item_surcharge, "peak_surcharge": peak_surcharge, "loyalty_discount": loyalty_discount, "value_discount": value_discount, "final_fee": round(fee), "breakdown": { "base": base_fee, "volume_surcharge": volume_surcharge, "item_surcharge": item_surcharge, "peak_surcharge": peak_surcharge, "loyalty_discount": -loyalty_discount, "value_discount": -value_discount, "final": round(fee) } }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847from datetime import datetime, timezone, datefrom typing import Optional, Tuple, List, Dict, Literal
from fastapi import APIRouter, Depends, HTTPException, Requestfrom pydantic import BaseModel, Field
from deps import ( logger, get_supabase, run_sync_db_call, get_client_ip, rate_limit, require_role, require_feature, resolve_request_branch, resolve_request_branch_for_write, get_visible_user_ids,)
hr_router = APIRouter( prefix="/hr", tags=["Human Resources"], dependencies=[Depends(require_feature("hr_module"))],)
# ===================== HR MODULE MODELS =====================class DepartmentCreate(BaseModel): name: str = Field(..., min_length=1, max_length=100) description: Optional[str] = None
class DepartmentUpdate(BaseModel): name: Optional[str] = Field(None, min_length=1, max_length=100) description: Optional[str] = None
class EmployeeCreate(BaseModel): user_id: Optional[str] = None first_name: str last_name: str email: str phone: Optional[str] = None department_id: Optional[int] = None position: Optional[str] = None hire_date: date date_of_birth: Optional[date] = None salary: float = 0.0 status: str = "active"
class EmployeeUpdate(BaseModel): first_name: Optional[str] = None last_name: Optional[str] = None email: Optional[str] = None phone: Optional[str] = None department_id: Optional[int] = None position: Optional[str] = None hire_date: Optional[date] = None date_of_birth: Optional[date] = None salary: Optional[float] = None status: Optional[str] = None
class AttendanceClockIn(BaseModel): employee_id: int clock_in: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
class AttendanceClockOut(BaseModel): employee_id: int clock_out: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
class LeaveRequestCreate(BaseModel): employee_id: int leave_type: str = Field(..., pattern="^(annual|sick|personal)$") start_date: date end_date: date reason: Optional[str] = None
class LeaveRequestUpdate(BaseModel): status: str = Field(..., pattern="^(approved|rejected)$") approved_by: Optional[str] = None notes: Optional[str] = None
class PayrollGenerate(BaseModel): month: int = Field(..., ge=1, le=12) year: int
# ===================== HR HELPERS =====================async def get_employee_by_user_id(user_id: str, org_id: str) -> Optional[Dict]: client = get_supabase() result = await run_sync_db_call( client.table("hr_employees") .select("*") .eq("user_id", user_id) .eq("org_id", org_id) .limit(1) # FIXED: was .limit(1) .execute ) return result.data[0] if result.data else None
async def get_employee_by_id(employee_id: int, org_id: str) -> Optional[Dict]: client = get_supabase() result = await run_sync_db_call( client.table("hr_employees") .select("*") .eq("id", employee_id) .eq("org_id", org_id) .limit(1) # FIXED: was .limit(1) .execute ) return result.data[0] if result.data else None
# ===================== HR ROUTER (Wave 3: feature-gated) =====================# ===================== HR ENDPOINTS =====================@hr_router.get("/departments")async def list_departments( request: Request, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() result = await run_sync_db_call( client.table("hr_departments") .select("*") .eq("org_id", org_id) .order("name") .execute ) return {"departments": result.data}
@hr_router.post("/departments")async def create_department( request: Request, dept: DepartmentCreate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() data = dept.dict() data["org_id"] = org_id data["created_at"] = datetime.now(timezone.utc).isoformat() result = await run_sync_db_call(client.table("hr_departments").insert(data).execute) if not result.data: raise HTTPException(status_code=500, detail="Failed to create department") return result.data[0]
@hr_router.put("/departments/{dept_id}")async def update_department( request: Request, dept_id: int, dept: DepartmentUpdate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() existing = await run_sync_db_call( client.table("hr_departments") .select("id") .eq("id", dept_id) .eq("org_id", org_id) .limit(1) .execute ) if not existing.data: raise HTTPException(status_code=404, detail="Department not found") update_data = {k: v for k, v in dept.dict().items() if v is not None} result = await run_sync_db_call( client.table("hr_departments") .update(update_data) .eq("id", dept_id) .eq("org_id", org_id) .execute ) if not result.data: raise HTTPException(status_code=500, detail="Failed to update department") return result.data[0]
@hr_router.delete("/departments/{dept_id}")async def delete_department( request: Request, dept_id: int, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() emp_check = await run_sync_db_call( client.table("hr_employees") .select("id") .eq("department_id", dept_id) .eq("org_id", org_id) .limit(1) .execute ) if emp_check.data: raise HTTPException(status_code=400, detail="Cannot delete department with employees assigned") result = await run_sync_db_call( client.table("hr_departments") .delete() .eq("id", dept_id) .eq("org_id", org_id) .execute ) if not result.data: raise HTTPException(status_code=404, detail="Department not found") return {"message": "Department deleted"}
@hr_router.get("/employees")async def list_employees( request: Request, department_id: Optional[int] = None, status: Optional[str] = None, limit: int = 100, offset: int = 0, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "finance"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase()
selected_branch = await resolve_request_branch(request, user_id, org_id, role) visible_user_ids = await get_visible_user_ids(user_id, org_id, role)
query = client.table("hr_employees").select("*").eq("org_id", org_id) if department_id: query = query.eq("department_id", department_id) if status: query = query.eq("status", status) if selected_branch: query = query.eq("branch_id", selected_branch)
result = await run_sync_db_call(query.order("last_name").range(offset, offset + limit - 1).execute) rows = result.data or []
# Owners (visible_user_ids is None) see everything. Everyone else sees # only HR records whose linked user_id is in their branch-sharing set, # plus unlinked records (no user_id → nothing to gate on yet). if visible_user_ids is not None: rows = [ r for r in rows if not r.get("user_id") or r["user_id"] in visible_user_ids ]
return {"employees": rows, "total": len(rows)}
@hr_router.post("/employees")async def create_employee( request: Request, emp: EmployeeCreate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase() if emp.user_id: member_check = await run_sync_db_call( client.table("org_members") .select("user_id") .eq("user_id", emp.user_id) .eq("org_id", org_id) .limit(1) .execute ) if not member_check.data: raise HTTPException(status_code=400, detail="User is not a member of this organisation") email_check = await run_sync_db_call( client.table("hr_employees") .select("id") .eq("email", emp.email) .eq("org_id", org_id) .limit(1) .execute ) if email_check.data: raise HTTPException(status_code=400, detail="Employee with this email already exists")
data = emp.dict() if data.get("hire_date"): data["hire_date"] = data["hire_date"].isoformat() if data.get("date_of_birth"): data["date_of_birth"] = data["date_of_birth"].isoformat() data["org_id"] = org_id data["branch_id"] = await resolve_request_branch_for_write(request, user_id, org_id, role) data["created_at"] = datetime.now(timezone.utc).isoformat() data["updated_at"] = datetime.now(timezone.utc).isoformat() result = await run_sync_db_call(client.table("hr_employees").insert(data).execute) if not result.data: raise HTTPException(status_code=500, detail="Failed to create employee") return result.data[0]
@hr_router.get("/employees/{employee_id}")async def get_employee( request: Request, employee_id: int, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "finance", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase() if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp or emp["id"] != employee_id: raise HTTPException(status_code=403, detail="Not authorised to view this employee") result = await run_sync_db_call( client.table("hr_employees") .select("*") .eq("id", employee_id) .eq("org_id", org_id) .limit(1) .execute ) if not result.data: raise HTTPException(status_code=404, detail="Employee not found") return result.data[0]
@hr_router.put("/employees/{employee_id}")async def update_employee( request: Request, employee_id: int, emp: EmployeeUpdate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() existing = await get_employee_by_id(employee_id, org_id) if not existing: raise HTTPException(status_code=404, detail="Employee not found") update_data = {k: v for k, v in emp.dict().items() if v is not None} if update_data.get("hire_date"): update_data["hire_date"] = update_data["hire_date"].isoformat() if update_data.get("date_of_birth"): update_data["date_of_birth"] = update_data["date_of_birth"].isoformat() update_data["updated_at"] = datetime.now(timezone.utc).isoformat() result = await run_sync_db_call( client.table("hr_employees") .update(update_data) .eq("id", employee_id) .eq("org_id", org_id) .execute ) if not result.data: raise HTTPException(status_code=500, detail="Failed to update employee") return result.data[0]
@hr_router.delete("/employees/{employee_id}")async def delete_employee( request: Request, employee_id: int, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() existing = await get_employee_by_id(employee_id, org_id) if not existing: raise HTTPException(status_code=404, detail="Employee not found") result = await run_sync_db_call( client.table("hr_employees") .delete() .eq("id", employee_id) .eq("org_id", org_id) .execute ) if not result.data: raise HTTPException(status_code=500, detail="Failed to delete employee") return {"message": "Employee deleted"}
@hr_router.get("/me")async def get_my_employee_profile( request: Request, user_data: Tuple[str, str, str] = Depends(require_role(["employee"]))): user_id, org_id, _ = user_data emp = await get_employee_by_user_id(user_id, org_id) if not emp: raise HTTPException(status_code=404, detail="No employee profile found for this user") return emp
@hr_router.post("/attendance/clock-in")async def clock_in( request: Request, clock: AttendanceClockIn, user_data: Tuple[str, str, str] = Depends(require_role(["employee"]))): user_id, org_id, role = user_data emp = await get_employee_by_user_id(user_id, org_id) if not emp or emp["id"] != clock.employee_id: raise HTTPException(status_code=403, detail="Not authorised to clock in for this employee") client = get_supabase() today = date.today().isoformat() existing = await run_sync_db_call( client.table("hr_attendance") .select("id") .eq("employee_id", clock.employee_id) .eq("date", today) .is_("clock_out", "null") .limit(1) .execute ) if existing.data: raise HTTPException(status_code=400, detail="Already clocked in today; please clock out first") data = { "employee_id": clock.employee_id, "branch_id": (emp.get("branch_id") if emp else None) or await resolve_request_branch_for_write(request, user_id, org_id, role), "date": today, "clock_in": clock.clock_in.isoformat(), "status": "present" } result = await run_sync_db_call(client.table("hr_attendance").insert(data).execute) if not result.data: raise HTTPException(status_code=500, detail="Failed to clock in") return {"message": "Clocked in", "attendance": result.data[0]}
@hr_router.post("/attendance/clock-out")async def clock_out( request: Request, clock: AttendanceClockOut, user_data: Tuple[str, str, str] = Depends(require_role(["employee"]))): user_id, org_id, _ = user_data emp = await get_employee_by_user_id(user_id, org_id) if not emp or emp["id"] != clock.employee_id: raise HTTPException(status_code=403, detail="Not authorised") client = get_supabase() today = date.today().isoformat() record = await run_sync_db_call( client.table("hr_attendance") .select("id") .eq("employee_id", clock.employee_id) .eq("date", today) .is_("clock_out", "null") .limit(1) .execute ) if not record.data: raise HTTPException(status_code=400, detail="No open clock-in found for today") update_data = { "clock_out": clock.clock_out.isoformat(), "updated_at": datetime.now(timezone.utc).isoformat() } result = await run_sync_db_call( client.table("hr_attendance") .update(update_data) .eq("id", record.data[0]["id"]) .execute ) if not result.data: raise HTTPException(status_code=500, detail="Failed to clock out") return {"message": "Clocked out", "attendance": result.data[0]}
@hr_router.get("/attendance")async def get_attendance( request: Request, employee_id: Optional[int] = None, start_date: Optional[date] = None, end_date: Optional[date] = None, limit: int = 100, offset: int = 0, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase() target_employee_id = employee_id if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp: raise HTTPException(status_code=404, detail="No employee profile") if employee_id and employee_id != emp["id"]: raise HTTPException(status_code=403, detail="Can only view own attendance") target_employee_id = emp["id"]
selected_branch = await resolve_request_branch(request, user_id, org_id, role) visible_user_ids = await get_visible_user_ids(user_id, org_id, role)
query = client.table("hr_attendance").select("*").eq("org_id", org_id) if target_employee_id: query = query.eq("employee_id", target_employee_id) if start_date: query = query.gte("date", start_date.isoformat()) if end_date: query = query.lte("date", end_date.isoformat()) if selected_branch: query = query.eq("branch_id", selected_branch) result = await run_sync_db_call(query.order("date", desc=True).range(offset, offset + limit - 1).execute) rows = result.data or []
if visible_user_ids is not None: hr_emp_ids_res = await run_sync_db_call( client.table("hr_employees").select("id, user_id") .eq("org_id", org_id) .in_("user_id", list(visible_user_ids)) .execute ) allowed_emp_ids = {r["id"] for r in (hr_emp_ids_res.data or [])} rows = [r for r in rows if r.get("employee_id") in allowed_emp_ids]
return {"attendance": rows, "total": len(rows)}
@hr_router.post("/leave-requests")async def create_leave_request( request: Request, leave: LeaveRequestCreate, user_data: Tuple[str, str, str] = Depends(require_role(["employee"]))): user_id, org_id, role = user_data emp = await get_employee_by_user_id(user_id, org_id) if not emp or emp["id"] != leave.employee_id: raise HTTPException(status_code=403, detail="Not authorised") if leave.start_date > leave.end_date: raise HTTPException(status_code=400, detail="Start date must be before end date") client = get_supabase() data = leave.dict() if data.get("start_date"): data["start_date"] = data["start_date"].isoformat() if data.get("end_date"): data["end_date"] = data["end_date"].isoformat() data["org_id"] = org_id data["branch_id"] = (emp.get("branch_id") if emp else None) or await resolve_request_branch_for_write(request, user_id, org_id, role) data["status"] = "pending" data["created_at"] = datetime.now(timezone.utc).isoformat() data["updated_at"] = datetime.now(timezone.utc).isoformat() result = await run_sync_db_call(client.table("hr_leave_requests").insert(data).execute) if not result.data: raise HTTPException(status_code=500, detail="Failed to create leave request") return result.data[0]
@hr_router.get("/leave-requests")async def list_leave_requests( request: Request, employee_id: Optional[int] = None, status: Optional[str] = None, limit: int = 100, offset: int = 0, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase() target_employee_id = employee_id if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp: raise HTTPException(status_code=404, detail="No employee profile") if employee_id and employee_id != emp["id"]: raise HTTPException(status_code=403, detail="Can only view own leave requests") target_employee_id = emp["id"]
selected_branch = await resolve_request_branch(request, user_id, org_id, role) visible_user_ids = await get_visible_user_ids(user_id, org_id, role)
query = client.table("hr_leave_requests").select("*").eq("org_id", org_id) if target_employee_id: query = query.eq("employee_id", target_employee_id) if status: query = query.eq("status", status) if selected_branch: query = query.eq("branch_id", selected_branch) result = await run_sync_db_call(query.order("created_at", desc=True).range(offset, offset + limit - 1).execute) rows = result.data or []
if visible_user_ids is not None: hr_emp_ids_res = await run_sync_db_call( client.table("hr_employees").select("id, user_id") .eq("org_id", org_id) .in_("user_id", list(visible_user_ids)) .execute ) allowed_emp_ids = {r["id"] for r in (hr_emp_ids_res.data or [])} rows = [r for r in rows if r.get("employee_id") in allowed_emp_ids]
return {"requests": rows, "total": len(rows)}
@hr_router.put("/leave-requests/{request_id}")async def update_leave_request( request: Request, request_id: int, update: LeaveRequestUpdate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() req = await run_sync_db_call( client.table("hr_leave_requests") .select("*") .eq("id", request_id) .eq("org_id", org_id) .limit(1) .execute ) if not req.data: raise HTTPException(status_code=404, detail="Leave request not found") if req.data[0]["status"] != "pending": raise HTTPException(status_code=400, detail="Request already processed") update_data = { "status": update.status, "approved_by": update.approved_by, "notes": update.notes, "updated_at": datetime.now(timezone.utc).isoformat() } result = await run_sync_db_call( client.table("hr_leave_requests") .update(update_data) .eq("id", request_id) .eq("org_id", org_id) .execute ) if not result.data: raise HTTPException(status_code=500, detail="Failed to update leave request") return result.data[0]
@hr_router.get("/leave-balances")async def get_leave_balances( request: Request, employee_id: Optional[int] = None, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase() target_employee_id = employee_id if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp: raise HTTPException(status_code=404, detail="No employee profile") if employee_id and employee_id != emp["id"]: raise HTTPException(status_code=403, detail="Can only view own balances") target_employee_id = emp["id"] query = client.table("hr_leave_balances").select("*").eq("org_id", org_id) if target_employee_id: query = query.eq("employee_id", target_employee_id) result = await run_sync_db_call(query.execute) return {"balances": result.data}
@hr_router.post("/payroll/generate")async def generate_payroll( request: Request, payload: PayrollGenerate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "finance"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase() employees = await run_sync_db_call( client.table("hr_employees") .select("id, salary") .eq("org_id", org_id) .eq("status", "active") .execute ) if not employees.data: raise HTTPException(status_code=400, detail="No active employees") payrolls = [] month = payload.month year = payload.year for emp in employees.data: existing = await run_sync_db_call( client.table("hr_payroll") .select("id") .eq("employee_id", emp["id"]) .eq("month", month) .eq("year", year) .eq("org_id", org_id) .limit(1) .execute ) if existing.data: continue branch_id_for_payroll = await resolve_request_branch_for_write(request, user_id, org_id, role) payroll_data = { "org_id": org_id, "branch_id": branch_id_for_payroll, "employee_id": emp["id"], "month": month, "year": year, "base_salary": emp["salary"], "allowances": 0.0, "deductions": 0.0, "net_pay": emp["salary"], "status": "draft", "created_at": datetime.now(timezone.utc).isoformat() } payrolls.append(payroll_data) if payrolls: result = await run_sync_db_call(client.table("hr_payroll").insert(payrolls).execute) if not result.data: raise HTTPException(status_code=500, detail="Failed to generate payroll") return {"message": f"Generated payroll for {len(payrolls)} employees", "payrolls": result.data if payrolls else []}
@hr_router.get("/payroll")async def list_payroll( request: Request, employee_id: Optional[int] = None, month: Optional[int] = None, year: Optional[int] = None, limit: int = 100, offset: int = 0, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "finance", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase() target_employee_id = employee_id if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp: raise HTTPException(status_code=404, detail="No employee profile") if employee_id and employee_id != emp["id"]: raise HTTPException(status_code=403, detail="Can only view own payroll") target_employee_id = emp["id"]
selected_branch = await resolve_request_branch(request, user_id, org_id, role) visible_user_ids = await get_visible_user_ids(user_id, org_id, role)
query = client.table("hr_payroll").select("*").eq("org_id", org_id) if target_employee_id: query = query.eq("employee_id", target_employee_id) if month: query = query.eq("month", month) if year: query = query.eq("year", year) if selected_branch: query = query.eq("branch_id", selected_branch) result = await run_sync_db_call(query.order("year", desc=True).order("month", desc=True).range(offset, offset + limit - 1).execute) rows = result.data or []
if visible_user_ids is not None: hr_emp_ids_res = await run_sync_db_call( client.table("hr_employees").select("id, user_id") .eq("org_id", org_id) .in_("user_id", list(visible_user_ids)) .execute ) allowed_emp_ids = {r["id"] for r in (hr_emp_ids_res.data or [])} rows = [r for r in rows if r.get("employee_id") in allowed_emp_ids]
return {"payroll": rows, "total": len(rows)}
# ===================== INCLUDE ROUTERS =====================
# ===================== HR TASKS & NOTIFICATIONS =====================class TaskCreate(BaseModel): employee_id: int title: str = Field(..., min_length=1, max_length=200) description: Optional[str] = None priority: Literal["Low", "Normal", "High"] = "Normal" due_date: Optional[date] = None
class TaskUpdate(BaseModel): status: Literal["Pending", "In Progress", "Completed"]
@hr_router.get("/tasks")async def list_tasks( request: Request, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase()
query = client.table("hr_tasks").select("*, hr_employees(first_name, last_name)").eq("org_id", org_id) if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp: return {"tasks": []} query = query.eq("employee_id", emp["id"])
result = await run_sync_db_call(query.order("created_at", desc=True).execute) return {"tasks": result.data or []}
@hr_router.post("/tasks")async def create_task( request: Request, task: TaskCreate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, _ = user_data client = get_supabase()
data = task.dict() if data.get("due_date"): data["due_date"] = data["due_date"].isoformat() data["org_id"] = org_id data["assigned_by"] = user_id result = await run_sync_db_call(client.table("hr_tasks").insert(data).execute) if not result.data: raise HTTPException(status_code=500, detail="Failed to create task") return result.data[0]
@hr_router.put("/tasks/{task_id}")async def update_task_status( request: Request, task_id: int, update: TaskUpdate, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase()
query = client.table("hr_tasks").update({"status": update.status}).eq("id", task_id).eq("org_id", org_id) if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp: raise HTTPException(403, "Unauthorized") query = query.eq("employee_id", emp["id"])
result = await run_sync_db_call(query.execute) if not result.data: raise HTTPException(404, "Task not found or unauthorized") return result.data[0]
@hr_router.get("/notifications")async def get_notifications( request: Request, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, role = user_data client = get_supabase()
query = client.table("hr_notifications").select("*").eq("org_id", org_id).eq("is_read", False) if role == "employee": emp = await get_employee_by_user_id(user_id, org_id) if not emp: return {"notifications": [], "count": 0} query = query.eq("employee_id", emp["id"])
result = await run_sync_db_call(query.order("created_at", desc=True).execute) return {"notifications": result.data or [], "count": len(result.data or [])}
@hr_router.put("/notifications/{notification_id}/read")async def mark_notification_read( request: Request, notification_id: int, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "hr", "employee"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase()
result = await run_sync_db_call( client.table("hr_notifications").update({"is_read": True}) .eq("id", notification_id).eq("org_id", org_id).execute ) return {"success": True}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723from fastapi import APIRouter, Depends, HTTPException, Request, Query, File, UploadFilefrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Field, validatorfrom typing import Optional, Tuple, List, Dict, Anyfrom datetime import datetime, timezone, date, timedeltaimport uuidimport csvimport ioimport re
from deps import ( logger, get_supabase, get_admin_supabase, run_sync_db_call, get_client_ip, rate_limit, require_role, require_feature, resolve_request_branch, resolve_request_branch_for_write, check_org_feature, _assert_storefront_live, get_location_for_channel, get_active_sale_prices, fetch_inventory_scoped_to_location, resolve_store_org,)
router = APIRouter(tags=["Inventory"])
# ==========================================# MODELS & HELPERS# ==========================================class InventoryItem(BaseModel): item_code: Optional[str] = None description: str product_group: Optional[str] = None price_naira: float current_qty: Optional[int] = 0 image_url: Optional[str] = None cost_price_naira: Optional[float] = 0.0 weight_kg: Optional[float] = 0.0 size_factor: Optional[float] = 1.0 handling_category: Optional[str] = "standard"
expiry_date: Optional[str] = None batch_number: Optional[str] = None lot_number: Optional[str] = None manufacture_date: Optional[str] = None supplier_name: Optional[str] = None supplier_invoice: Optional[str] = None
@validator('handling_category') def validate_handling_category(cls, v): allowed = {"standard", "fragile", "bulky", "hazardous"} if v and v not in allowed: raise ValueError(f"handling_category must be one of {allowed}") return v
SENTINEL_BATCH_NUMBER = "UNBATCHED"SENTINEL_EXPIRY_DATE = "2099-12-31"
async def get_next_auto_batch_number() -> str: client = get_supabase() try: result = await run_sync_db_call(client.rpc('get_next_auto_batch_number', {}).execute) next_num = result.data return f"autogen{next_num:03d}" except Exception as e: logger.error(f"Failed to get next auto batch number: {e}") return f"autogen{int(datetime.now(timezone.utc).timestamp()) % 10000:03d}"
async def _resolve_or_create_batch( client, inventory_id: int, batch_number: Optional[str], expiry_date: Optional[str], *, lot_number: Optional[str] = None, manufacture_date: Optional[str] = None, cost_price_naira: Optional[float] = None, supplier_name: Optional[str] = None, supplier_invoice: Optional[str] = None, received_quantity: int = 0,) -> Dict: provided_batch = (batch_number or "").strip() provided_expiry = (expiry_date or "").strip()
if not provided_expiry: parent_inv = await run_sync_db_call( client.table("inventory") .select("expiry_date") .eq("id", inventory_id) .maybe_single() .execute ) if parent_inv and parent_inv.data and parent_inv.data.get("expiry_date"): candidate = parent_inv.data["expiry_date"] try: year = int(str(candidate)[:4]) except (TypeError, ValueError): year = 0 if 2020 <= year <= 2050: provided_expiry = candidate
if provided_batch: resolved_batch_number = provided_batch elif provided_expiry: resolved_batch_number = await get_next_auto_batch_number() else: resolved_batch_number = SENTINEL_BATCH_NUMBER
resolved_expiry = provided_expiry or SENTINEL_EXPIRY_DATE
existing = await run_sync_db_call( client.table("inventory_batches") .select("*") .eq("inventory_id", inventory_id) .eq("batch_number", resolved_batch_number) .maybe_single() .execute ) if existing and existing.data: return existing.data
now_iso = datetime.now(timezone.utc).isoformat() batch_data = { "inventory_id": inventory_id, "batch_number": resolved_batch_number, "lot_number": lot_number, "quantity": int(received_quantity or 0), "reserved_quantity": 0, "manufacture_date": manufacture_date, "expiry_date": resolved_expiry, "cost_price_naira": cost_price_naira if cost_price_naira is not None else 0, "supplier_name": supplier_name, "supplier_invoice": supplier_invoice, "created_at": now_iso, "updated_at": now_iso, } created = await run_sync_db_call( client.table("inventory_batches").insert(batch_data).execute ) if not created.data: raise HTTPException( status_code=500, detail=( f"Failed to create batch '{resolved_batch_number}' " f"for inventory {inventory_id}" ), ) return created.data[0]
async def _write_location_stock( client, location_id: str, inventory_id: int, batch_id: int, quantity_delta: int,) -> None: now_iso = datetime.now(timezone.utc).isoformat()
existing = await run_sync_db_call( client.table("location_stocks") .select("id, quantity") .eq("location_id", location_id) .eq("inventory_id", inventory_id) .eq("batch_id", batch_id) .maybe_single() .execute )
if existing and existing.data: current = int(existing.data.get("quantity") or 0) new_qty = current + int(quantity_delta) if new_qty < 0: raise HTTPException( status_code=400, detail=( f"Cannot reduce location_stocks below zero " f"(location={location_id}, inventory={inventory_id}, " f"batch={batch_id}, current={current}, delta={quantity_delta})" ), ) if new_qty == 0: await run_sync_db_call( client.table("location_stocks") .delete() .eq("id", existing.data["id"]) .execute ) else: await run_sync_db_call( client.table("location_stocks") .update({"quantity": new_qty, "updated_at": now_iso}) .eq("id", existing.data["id"]) .execute ) return
if quantity_delta <= 0: return
await run_sync_db_call( client.table("location_stocks").insert({ "location_id": location_id, "inventory_id": inventory_id, "batch_id": batch_id, "quantity": int(quantity_delta), "reserved_quantity": 0, "updated_at": now_iso, }).execute )
# ------------------------------------------------------------------# OPTIMIZED STREAMING EXPORT (Backend CSV Generation)# ------------------------------------------------------------------@router.get("/inventory/export-csv")async def export_inventory_csv( request: Request, location_id: Optional[str] = None, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "inventory_manager"]))): _, org_id, _ = user_data client = get_supabase()
async def generate_csv(): output = io.StringIO() writer = csv.writer(output) writer.writerow(["SKU", "Description", "Category", "Price (NGN)", "Cost (NGN)", "Current Stock", "Handling Category", "Weight (kg)", "Expiry Date"]) yield output.getvalue() output.seek(0); output.truncate(0)
last_id = 0 chunk_size = 2000 while True: if location_id: query = client.table("inventory") \ .select("id, item_code, description, product_group, price_naira, cost_price_naira, handling_category, weight_kg, expiry_date, location_stocks!inner(quantity)") \ .eq("org_id", org_id) \ .eq("location_stocks.location_id", location_id) \ .gt("id", last_id) \ .order("id", desc=False) \ .limit(chunk_size) else: query = client.table("inventory") \ .select("id, item_code, description, product_group, price_naira, cost_price_naira, current_qty, handling_category, weight_kg, expiry_date") \ .eq("org_id", org_id) \ .gt("id", last_id) \ .order("id", desc=False) \ .limit(chunk_size)
res = await run_sync_db_call(query.execute) rows = res.data or [] if not rows: break
for row in rows: qty = row.get("current_qty", 0) if not location_id else sum(int(s.get("quantity") or 0) for s in (row.get("location_stocks") or [])) writer.writerow([ row.get("item_code", ""), row.get("description", ""), row.get("product_group", ""), row.get("price_naira", 0), row.get("cost_price_naira", 0), qty, row.get("handling_category", "standard"), row.get("weight_kg", 0), row.get("expiry_date", "") ]) last_id = rows[-1]["id"] yield output.getvalue() output.seek(0); output.truncate(0)
return StreamingResponse( generate_csv(), media_type="text/csv", headers={"Content-Disposition": f"attachment; filename=inventory_export_{datetime.now().date()}.csv"} )
@router.get("/inventory")async def get_inventory(request: Request, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "inventory_manager", "sales_rep", "finance"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() result = await run_sync_db_call(client.table("inventory").select("*").eq("org_id", org_id).order("id", desc=False).execute) return result.data
@router.post("/inventory")async def create_inventory_item( request: Request, item: InventoryItem, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "inventory_manager"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) user_id, org_id, _ = user_data client = get_supabase()
data = item.dict() data["org_id"] = org_id data["created_by"] = user_id data["created_via"] = "inventory_manual" data["created_at"] = datetime.now(timezone.utc).isoformat() data["updated_at"] = datetime.now(timezone.utc).isoformat()
# Deprecated columns: strip from the inventory payload before insert. # The batch table (inventory_batches) is the authoritative home for # expiry and batch identity. Existing clients still send these on the # Pydantic model; the values are read into locals below and routed # into the batch resolver, but never written to inventory. expiry_date = data.pop("expiry_date", None) batch_number = data.pop("batch_number", None) lot_number = data.get("lot_number")
if expiry_date and not batch_number: batch_number = await get_next_auto_batch_number() if not lot_number: lot_number = "LEGACY-IMPORT" data["lot_number"] = lot_number
inv_result = await run_sync_db_call(client.table("inventory").insert(data).execute) if not inv_result.data: raise HTTPException(status_code=500, detail="Failed to create inventory item") new_inv = inv_result.data[0]
# ── Resolve or create the batch ── batch_row = await _resolve_or_create_batch( client=client, inventory_id=new_inv["id"], batch_number=batch_number, expiry_date=expiry_date, lot_number=data.get("lot_number"), manufacture_date=data.get("manufacture_date"), cost_price_naira=data.get("cost_price_naira"), supplier_name=data.get("supplier_name"), supplier_invoice=data.get("supplier_invoice"), received_quantity=int(data.get("current_qty") or 0), )
# ── Write the location_stocks row through the shared helper ── try: main_location = await run_sync_db_call( client.table("locations") .select("id") .eq("org_id", org_id) .eq("is_warehouse", True) .maybe_single() .execute ) if main_location and main_location.data: await _write_location_stock( client=client, location_id=main_location.data["id"], inventory_id=new_inv["id"], batch_id=batch_row["id"], quantity_delta=int(data.get("current_qty") or 0), ) except Exception as loc_err: logger.error(f"Failed to create location stock for inv={new_inv['id']}: {loc_err}")
return new_inv
@router.put("/inventory/{item_id}")async def update_inventory( request: Request, item_id: int, item: InventoryItem, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "inventory_manager"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase()
existing = await run_sync_db_call( client.table("inventory") .select("id, current_qty") .eq("id", item_id) .eq("org_id", org_id) .maybe_single() .execute )
if not existing.data: raise HTTPException(status_code=404, detail="Inventory item not found")
update_data = {k: v for k, v in item.dict().items() if v is not None} # Deprecated columns: never write them back to inventory. The batch # table is authoritative. Existing clients still send them; the # values are read from the Pydantic model directly and routed into # the batch resolver. update_data.pop("expiry_date", None) update_data.pop("batch_number", None) update_data["updated_at"] = datetime.now(timezone.utc).isoformat()
new_expiry = item.expiry_date new_batch = item.batch_number new_lot = item.lot_number
old_qty = int(existing.data.get("current_qty") or 0) new_qty = int(item.current_qty if item.current_qty is not None else old_qty)
# ── Determine which batch the location_stocks delta applies to. ── # Precedence: caller-named batch > earliest-expiring existing batch # for this inventory. Replaces the deprecated inventory.batch_number # read with a lookup against the authoritative inventory_batches. target_batch_number = new_batch resolved_expiry = new_expiry if not target_batch_number: current_batch_res = await run_sync_db_call( client.table("inventory_batches") .select("batch_number, expiry_date") .eq("inventory_id", item_id) .order("expiry_date", desc=False) .limit(1) .execute ) if current_batch_res and current_batch_res.data: target_batch_number = current_batch_res.data[0].get("batch_number") if not resolved_expiry: resolved_expiry = current_batch_res.data[0].get("expiry_date")
# ── Resolve or create the batch through the shared helper. ── batch_row = await _resolve_or_create_batch( client=client, inventory_id=item_id, batch_number=target_batch_number, expiry_date=resolved_expiry, lot_number=new_lot, manufacture_date=item.manufacture_date, cost_price_naira=item.cost_price_naira, supplier_name=item.supplier_name, supplier_invoice=item.supplier_invoice, received_quantity=0, )
# ── Apply the location_stocks delta FIRST. ── delta = new_qty - old_qty if delta != 0: try: main_location = await run_sync_db_call( client.table("locations") .select("id") .eq("org_id", org_id) .eq("is_warehouse", True) .maybe_single() .execute ) if main_location and main_location.data: await _write_location_stock( client=client, location_id=main_location.data["id"], inventory_id=item_id, batch_id=batch_row["id"], quantity_delta=delta, ) else: logger.warning( f"update_inventory: no warehouse location for org {org_id}, " f"location_stocks not reconciled for inv {item_id} (delta={delta})" ) except HTTPException: raise except Exception as loc_err: logger.error( f"update_inventory: failed to reconcile location_stocks " f"for inv {item_id}: {loc_err}" )
result = await run_sync_db_call( client.table("inventory") .update(update_data) .eq("id", item_id) .eq("org_id", org_id) .execute )
if not result.data: raise HTTPException(status_code=404, detail="Inventory item not found")
return result.data[0]
@router.delete("/inventory/{item_id}")async def delete_inventory(request: Request, item_id: int, user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "inventory_manager"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() result = await run_sync_db_call(client.table("inventory").delete().eq("id", item_id).eq("org_id", org_id).execute) if not result.data: raise HTTPException(status_code=404, detail="Inventory item not found") return {"message": "Deleted successfully"}
# ------------------------------------------------------------------# PUBLIC INVENTORY ENDPOINTS (no authentication required)# ------------------------------------------------------------------
@router.get("/inventory/public-list")async def public_inventory( request: Request, org_id: Optional[str] = Query(None), limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), q: Optional[str] = Query(None), category: Optional[str] = Query(None), sort_by: str = Query("newest"),): await rate_limit(get_client_ip(request))
resolved_org_id = await resolve_store_org(request, org_id=org_id) if not resolved_org_id: raise HTTPException(status_code=400, detail="Organisation not specified")
# Suspension is unconditional. A suspended org's storefront data # endpoints are dark regardless of ENFORCE_FEATURES. 404, not 402, # so a visitor cannot probe billing status. await _assert_storefront_live(resolved_org_id) await check_org_feature(resolved_org_id, "ecommerce")
online_location_id = await get_location_for_channel(resolved_org_id, "online")
if not online_location_id: logger.warning( f"/inventory/public-list: no online location for org " f"{resolved_org_id}, falling back to legacy global read" ) client = get_supabase() query = client.table("inventory").select("*", count="exact") \ .eq("org_id", resolved_org_id).gt("current_qty", 0) if q: query = query.ilike("description", f"%{q}%") if category: query = query.eq("product_group", category) query = query.range(offset, offset + limit - 1) fallback = await run_sync_db_call(query.execute) items = fallback.data or []
# ── Flash-sale price override ── sale_map = await get_active_sale_prices( resolved_org_id, [it["id"] for it in items] ) for it in items: s = sale_map.get(it["id"]) if s: it["base_price_naira"] = it.get("price_naira") it["price_naira"] = s["sale_price"] it["on_sale"] = True it["sale_name"] = s["sale_name"] it["sale_ends_at"] = s["ends_at"] it["discount_pct"] = ( round(((s["original_price"] - s["sale_price"]) / s["original_price"]) * 100, 1) if s["original_price"] > 0 else 0 ) else: it["on_sale"] = False
return { "items": items, "total": fallback.count or 0, "location_id": None, "org_id": resolved_org_id, }
items, total = await fetch_inventory_scoped_to_location( org_id=resolved_org_id, location_id=str(online_location_id), limit=limit, offset=offset, q=q, category=category, sort_by=sort_by, require_positive_stock=True, )
# ── Flash-sale price override ── sale_map = await get_active_sale_prices( resolved_org_id, [it["id"] for it in items] ) for it in items: s = sale_map.get(it["id"]) if s: it["base_price_naira"] = it.get("price_naira") it["price_naira"] = s["sale_price"] it["on_sale"] = True it["sale_name"] = s["sale_name"] it["sale_ends_at"] = s["ends_at"] it["discount_pct"] = ( round(((s["original_price"] - s["sale_price"]) / s["original_price"]) * 100, 1) if s["original_price"] > 0 else 0 ) else: it["on_sale"] = False
return { "items": items, "total": total, "location_id": str(online_location_id), "org_id": resolved_org_id, }
@router.get("/inventory/public-categories")async def public_categories( request: Request, org_id: Optional[str] = Query(None),): await rate_limit(get_client_ip(request)) resolved_org_id = await resolve_store_org(request, org_id=org_id) if not resolved_org_id: raise HTTPException(status_code=400, detail="Organisation not specified")
# Suspension is unconditional — see _assert_storefront_live. await _assert_storefront_live(resolved_org_id) await check_org_feature(resolved_org_id, "ecommerce")
online_location_id = await get_location_for_channel(resolved_org_id, "online") client = get_supabase()
if not online_location_id: result = await run_sync_db_call( client.table("inventory") .select("product_group") .eq("org_id", resolved_org_id) .gt("current_qty", 0) .execute ) groups = {row["product_group"] for row in result.data if row.get("product_group")} return {"categories": sorted(list(groups)), "location_id": None, "org_id": resolved_org_id}
ls_result = await run_sync_db_call( client.table("location_stocks") .select("quantity, inventory:inventory_id(product_group, org_id)") .eq("location_id", str(online_location_id)) .gt("quantity", 0) .execute ) groups = set() for row in (ls_result.data or []): inv = row.get("inventory") or {} if inv.get("org_id") and str(inv["org_id"]) != str(resolved_org_id): continue pg = inv.get("product_group") if pg: groups.add(pg) return { "categories": sorted(groups), "location_id": str(online_location_id), "org_id": resolved_org_id, }
@router.get("/inventory/pos")async def pos_inventory( request: Request, limit: int = Query(200, ge=1, le=500), offset: int = Query(0, ge=0), q: Optional[str] = Query(None), location_id: Optional[str] = Query(None, description="Override the POS channel's default location"), skip_count: bool = Query( False, description=( "Skip COUNT(*). Use on pages > 0 during a full catalog sync — " "the sync loop terminates on an empty page, so only page 0 " "needs the total. Saves one COUNT per page on 15k+ SKU catalogs." ), ), user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "sales_rep"]))): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data
resolved_location_id = location_id if not resolved_location_id: resolved_location_id = await get_location_for_channel(org_id, "pos")
# ── Fallback: no POS location resolved ── if not resolved_location_id: logger.warning(f"/inventory/pos: no location resolved for org {org_id}, falling back to global inventory") client = get_supabase() query = client.table("inventory").select( "*", count="planned" if not skip_count else None, ).eq("org_id", org_id) if q: or_condition = f"description.ilike.%{q}%,item_code.ilike.%{q}%,product_group.ilike.%{q}%" inner = getattr(query, "_inner", query) inner.params = inner.params.set("or", f"({or_condition})") result = await run_sync_db_call(query.range(offset, offset + limit - 1).execute) return { "items": result.data or [], "total": (result.count or 0) if not skip_count else len(result.data or []), "location_id": None, }
# ── Primary path: location-scoped read ── # # include_count semantics: # skip_count=False → include_count=True → PostgREST issues COUNT(*), # result.count is populated, `total` is accurate. # Required on page 0 (populates CATALOG_EXPECTED_KEY) # and on every search page (drives infinite scroll). # skip_count=True → include_count=False → no COUNT(*). `total` is 0. # Safe only on sync pages 1+ where the loop # terminates on `pageItems.length === 0`. items, total = await fetch_inventory_scoped_to_location( org_id=org_id, location_id=str(resolved_location_id), limit=limit, offset=offset, q=q, sort_by="newest", require_positive_stock=False, include_count=not skip_count, )
sale_map = await get_active_sale_prices(org_id, [it["id"] for it in items]) for it in items: s = sale_map.get(it["id"]) if s: it["base_price_naira"] = it.get("price_naira") it["price_naira"] = s["sale_price"] it["on_sale"] = True it["sale_name"] = s["sale_name"] it["sale_ends_at"] = s["ends_at"] else: it["on_sale"] = False
return {"items": items, "total": total, "location_id": str(resolved_location_id)}
# ------------------------------------------------------------------# PUBLIC STOREFRONT ENDPOINTS# ------------------------------------------------------------------123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294# migrations_geo.pyimport httpx
from deps import ( SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, SUPABASE_ANON_KEY, logger,)
_SRK = SUPABASE_SERVICE_ROLE_KEY or SUPABASE_ANON_KEY
async def _exec_sql(sql: str): headers = { "apikey": _SRK, "Authorization": f"Bearer {_SRK}", "Content-Type": "application/json", } async with httpx.AsyncClient(timeout=60.0) as client: resp = await client.post( f"{SUPABASE_URL}/rest/v1/rpc/exec_sql", json={"query": sql}, headers=headers, ) if resp.status_code not in (200, 204): logger.error(f"Geo migration failed: {resp.text}") raise RuntimeError(f"Geo migration failed: {resp.text}")
async def ensure_geo_schema(): """ Idempotent additive migration for geospatial, dispatch, and zones. Safe to run on every boot. """ # 1. Enable PostGIS await _exec_sql("CREATE EXTENSION IF NOT EXISTS postgis;")
# 2. Delivery Zones Tables await _exec_sql(""" CREATE TABLE IF NOT EXISTS public.delivery_areas ( id SERIAL PRIMARY KEY, org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, name TEXT NOT NULL, fee INTEGER NOT NULL DEFAULT 0, polygon geometry(Polygon, 4326) NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS public.delivery_fee_rules ( id SERIAL PRIMARY KEY, org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, min_order_value INTEGER NOT NULL, max_order_value INTEGER, fee_multiplier NUMERIC DEFAULT 1.0, fee_discount INTEGER DEFAULT 0, free_delivery BOOLEAN DEFAULT FALSE, description TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS public.delivery_peak_settings ( id SERIAL PRIMARY KEY, org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, day_of_week INTEGER, start_time TIME, end_time TIME, surcharge_amount INTEGER DEFAULT 200, is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS public.delivery_loyalty_settings ( id SERIAL PRIMARY KEY, org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, min_orders INTEGER DEFAULT 5, discount_percentage INTEGER DEFAULT 20, is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS public.delivery_item_surcharge_rules ( id SERIAL PRIMARY KEY, org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, min_main_items INTEGER, max_main_items INTEGER, surcharge_amount INTEGER DEFAULT 0, weight_threshold_kg NUMERIC(6,2), surcharge_per_kg INTEGER, description TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); """)
# 3. Dispatch & Tracking Tables await _exec_sql(""" CREATE TABLE IF NOT EXISTS public.driver_locations ( org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, driver_id UUID NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE, branch_id UUID REFERENCES public.branches(id) ON DELETE RESTRICT, lat DOUBLE PRECISION NOT NULL CHECK (lat >= -90 AND lat <= 90), lng DOUBLE PRECISION NOT NULL CHECK (lng >= -180 AND lng <= 180), accuracy DOUBLE PRECISION, battery INTEGER CHECK (battery >= 0 AND battery <= 100), is_charging BOOLEAN, updated_at TIMESTAMPTZ DEFAULT now(), PRIMARY KEY (org_id, driver_id) );
CREATE TABLE IF NOT EXISTS public.geofences ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, branch_id UUID REFERENCES public.branches(id) ON DELETE CASCADE, name TEXT NOT NULL, description TEXT, polygon JSONB NOT NULL, aws_geofence_id TEXT UNIQUE, is_active BOOLEAN DEFAULT TRUE, color TEXT DEFAULT '#E53935', kind TEXT DEFAULT 'coverage', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() );
CREATE TABLE IF NOT EXISTS public.geofence_events ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, geofence_id UUID REFERENCES public.geofences(id) ON DELETE CASCADE, driver_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE, event_type TEXT NOT NULL CHECK (event_type IN ('enter', 'exit')), lat DOUBLE PRECISION NOT NULL, lng DOUBLE PRECISION NOT NULL, aws_event_id TEXT UNIQUE, occurred_at TIMESTAMPTZ DEFAULT NOW(), created_at TIMESTAMPTZ DEFAULT NOW() ); """)
# 4. Sale Events (Audit Trail) & Sales Columns await _exec_sql(""" CREATE TABLE IF NOT EXISTS public.sale_events ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, sale_id UUID NOT NULL REFERENCES public.sales(id) ON DELETE CASCADE, from_status TEXT, to_status TEXT NOT NULL, changed_by UUID REFERENCES public.profiles(id), created_at TIMESTAMPTZ DEFAULT NOW() );
ALTER TABLE public.sales ADD COLUMN IF NOT EXISTS delivery_lat DOUBLE PRECISION, ADD COLUMN IF NOT EXISTS delivery_lng DOUBLE PRECISION, ADD COLUMN IF NOT EXISTS delivery_breakdown JSONB, ADD COLUMN IF NOT EXISTS assigned_driver_id UUID REFERENCES public.profiles(id) ON DELETE SET NULL, ADD COLUMN IF NOT EXISTS picked_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS dispatched_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS delivered_at TIMESTAMPTZ; """)
# 5. RPCs (Org-Scoped Rewrites) await _exec_sql(""" -- Drop old signatures to allow clean recreation DROP FUNCTION IF EXISTS public.find_delivery_area(uuid, double precision, double precision); DROP FUNCTION IF EXISTS public.get_delivery_areas_geojson(uuid); DROP FUNCTION IF EXISTS public.insert_delivery_area(uuid, text, integer, text); DROP FUNCTION IF EXISTS public.update_delivery_area(integer, uuid, text, integer, text);
CREATE OR REPLACE FUNCTION public.find_delivery_area( p_org_id uuid, p_lat double precision, p_lng double precision ) RETURNS TABLE(id integer, name text, fee integer) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT da.id, da.name, da.fee FROM public.delivery_areas da WHERE da.org_id = p_org_id AND ST_Contains( da.polygon, ST_SetSRID(ST_MakePoint(p_lng, p_lat), 4326) ) LIMIT 1; END; $$;
CREATE OR REPLACE FUNCTION public.get_delivery_areas_geojson(p_org_id uuid) RETURNS TABLE(id integer, name text, fee integer, polygon jsonb, created_at timestamptz, updated_at timestamptz) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT da.id, da.name, da.fee, ST_AsGeoJSON(da.polygon)::jsonb, da.created_at, da.updated_at FROM public.delivery_areas da WHERE da.org_id = p_org_id ORDER BY da.id; END; $$;
CREATE OR REPLACE FUNCTION public.insert_delivery_area( p_org_id uuid, p_name text, p_fee integer, p_geojson text ) RETURNS TABLE(id integer, name text, fee integer, polygon jsonb, created_at timestamptz, updated_at timestamptz) LANGUAGE plpgsql AS $$ DECLARE v_geom geometry; v_result RECORD; BEGIN v_geom := ST_SetSRID(ST_GeomFromGeoJSON(p_geojson), 4326); IF ST_GeometryType(v_geom) != 'ST_Polygon' THEN RAISE EXCEPTION 'Geometry must be a Polygon'; END IF; INSERT INTO public.delivery_areas (org_id, name, fee, polygon, created_at, updated_at) VALUES (p_org_id, p_name, p_fee, v_geom, NOW(), NOW()) RETURNING delivery_areas.id, delivery_areas.name, delivery_areas.fee, delivery_areas.polygon, delivery_areas.created_at, delivery_areas.updated_at INTO v_result; RETURN QUERY SELECT v_result.id, v_result.name, v_result.fee, ST_AsGeoJSON(v_result.polygon)::jsonb, v_result.created_at, v_result.updated_at; END; $$;
CREATE OR REPLACE FUNCTION public.update_delivery_area( p_id integer, p_org_id uuid, p_name text, p_fee integer, p_geojson text ) RETURNS TABLE(id integer, name text, fee integer, polygon jsonb, created_at timestamptz, updated_at timestamptz) LANGUAGE plpgsql AS $$ DECLARE v_geom geometry; v_result RECORD; BEGIN v_geom := ST_SetSRID(ST_GeomFromGeoJSON(p_geojson), 4326); IF ST_GeometryType(v_geom) != 'ST_Polygon' THEN RAISE EXCEPTION 'Geometry must be a Polygon'; END IF; UPDATE public.delivery_areas SET name = p_name, fee = p_fee, polygon = v_geom, updated_at = NOW() WHERE id = p_id AND org_id = p_org_id RETURNING delivery_areas.id, delivery_areas.name, delivery_areas.fee, delivery_areas.polygon, delivery_areas.created_at, delivery_areas.updated_at INTO v_result; IF NOT FOUND THEN RAISE EXCEPTION 'Delivery area with ID % not found in this org', p_id; END IF; RETURN QUERY SELECT v_result.id, v_result.name, v_result.fee, ST_AsGeoJSON(v_result.polygon)::jsonb, v_result.created_at, v_result.updated_at; END; $$; """)
# 6. Realtime Publication await _exec_sql(""" DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_publication_tables WHERE pubname='supabase_realtime' AND tablename='driver_locations') THEN ALTER PUBLICATION supabase_realtime ADD TABLE public.driver_locations; END IF; IF NOT EXISTS (SELECT 1 FROM pg_publication_tables WHERE pubname='supabase_realtime' AND tablename='geofences') THEN ALTER PUBLICATION supabase_realtime ADD TABLE public.geofences; END IF; IF NOT EXISTS (SELECT 1 FROM pg_publication_tables WHERE pubname='supabase_realtime' AND tablename='geofence_events') THEN ALTER PUBLICATION supabase_realtime ADD TABLE public.geofence_events; END IF; IF NOT EXISTS (SELECT 1 FROM pg_publication_tables WHERE pubname='supabase_realtime' AND tablename='sales') THEN ALTER PUBLICATION supabase_realtime ADD TABLE public.sales; END IF; END $$; """)
logger.info("Geospatial and Dispatch schema installed successfully.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133[build] command = '''RAW_SF="$(printf '%s' "${STOREFRONT_SITE:-}" | tr -d '[:space:]')"SF_LOWER="$(printf '%s' "$RAW_SF" | tr '[:upper:]' '[:lower:]')"RAW_BR="$(printf '%s' "${BACKROOM:-}" | tr -d '[:space:]')"BR_LOWER="$(printf '%s' "$RAW_BR" | tr '[:upper:]' '[:lower:]')"
IS_BR="0"IS_SF="0"if [ "$BR_LOWER" = "true" ] || [ "$BR_LOWER" = "1" ] || [ "$BR_LOWER" = "yes" ]; then IS_BR="1"fiif [ "$SF_LOWER" = "true" ] || [ "$SF_LOWER" = "1" ] || [ "$SF_LOWER" = "yes" ]; then IS_SF="1"fi
if [ "$IS_BR" = "1" ]; then echo "Building backroom mode..." cp "muzoscents-funnel old/_redirects.backroom" "muzoscents-funnel old/_redirects" (cd "muzoscents-funnel old/netlify/functions" && npm install --no-audit --no-fund) (cd "muzoscents-funnel old/dispatch-portal" && npm install --legacy-peer-deps --no-audit --no-fund && npm run build)elif [ "$IS_SF" = "1" ]; then echo "Building storefront mode..." cp "muzoscents-funnel old/_redirects.storefront" "muzoscents-funnel old/_redirects" cp "muzoscents-funnel old/robots.storefront.txt" "muzoscents-funnel old/robots.txt" cp "muzoscents-funnel old/kdstore.html" "muzoscents-funnel old/index.html"else echo "Building backroom mode..." cp "muzoscents-funnel old/_redirects.backroom" "muzoscents-funnel old/_redirects" (cd "muzoscents-funnel old/netlify/functions" && npm install --no-audit --no-fund) (cd "muzoscents-funnel old/dispatch-portal" && npm install --legacy-peer-deps --no-audit --no-fund && npm run build)fi''' publish = "muzoscents-funnel old"
[build.environment] SECRETS_SCAN_OMIT_KEYS = "VITE_SUPABASE_URL,VITE_SUPABASE_ANON_KEY,API_BASE,STOREFRONT_SITE,BACKROOM"
[functions] node_bundler = "esbuild" directory = "muzoscents-funnel old/netlify/functions" external_node_modules = ["@supabase/supabase-js", "node-fetch", "mongodb", "@getbrevo/brevo"]
[[redirects]] from = "/proxy/*" to = "/.netlify/functions/api-proxy/:splat" status = 200 force = true
[[redirects]] from = "/dispatch/*" to = "/dispatch/index.html" status = 200
# ================================================================# GLOBAL SECURITY HEADERS (applies to ALL pages)# ================================================================[[headers]] for = "/*" [headers.values] Strict-Transport-Security = "max-age=31536000; includeSubDomains; preload" X-Frame-Options = "DENY" X-Content-Type-Options = "nosniff" X-XSS-Protection = "1; mode=block" Content-Security-Policy = "default-src 'self'; script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: https:; font-src 'self' data: https:; connect-src 'self' https: wss://*.supabase.co; frame-ancestors 'none';" Permissions-Policy = "camera=(), microphone=(), geolocation=(), payment=()" Referrer-Policy = "strict-origin-when-cross-origin" Cross-Origin-Opener-Policy = "same-origin" Cross-Origin-Resource-Policy = "same-origin"
# ================================================================# ROUTE-SPECIFIC: DISPATCH PORTAL (GPS + Maps enabled)# ================================================================[[headers]] for = "/dispatch*" [headers.values] Permissions-Policy = "geolocation=(self), camera=(), microphone=(), payment=()" Content-Security-Policy = "default-src 'self'; script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: https:; font-src 'self' data: https:; connect-src 'self' https: wss://*.supabase.co https://nominatim.openstreetmap.org; frame-ancestors 'none';" Strict-Transport-Security = "max-age=31536000; includeSubDomains; preload" X-Frame-Options = "DENY" X-Content-Type-Options = "nosniff" X-XSS-Protection = "1; mode=block" Referrer-Policy = "strict-origin-when-cross-origin" Cross-Origin-Opener-Policy = "same-origin" Cross-Origin-Resource-Policy = "same-origin"
# ================================================================# ROUTE-SPECIFIC: POS TERMINAL (Offline + Scanners)# ================================================================[[headers]] for = "/kdpos*" [headers.values] Permissions-Policy = "camera=(self), microphone=(), geolocation=(), payment=()" Content-Security-Policy = "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://unpkg.com; style-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdnjs.cloudflare.com https:; img-src 'self' data: https:; font-src 'self' data: https://cdnjs.cloudflare.com; connect-src 'self' https://kevsono-kevs-digital-bos.hf.space https://*.supabase.co wss://*.supabase.co; frame-ancestors 'none';" Strict-Transport-Security = "max-age=31536000; includeSubDomains; preload" X-Frame-Options = "DENY" X-Content-Type-Options = "nosniff" X-XSS-Protection = "1; mode=block" Referrer-Policy = "strict-origin-when-cross-origin" Cross-Origin-Opener-Policy = "same-origin" Cross-Origin-Resource-Policy = "same-origin"
# ================================================================# ROUTE-SPECIFIC: ADMIN INVENTORY (Online + Scanners)# ================================================================[[headers]] for = "/kdadmin*" [headers.values] Permissions-Policy = "camera=(self), microphone=(), geolocation=(), payment=()" Content-Security-Policy = "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://unpkg.com; style-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdnjs.cloudflare.com https:; img-src 'self' data: https:; font-src 'self' data: https://cdnjs.cloudflare.com; connect-src 'self' https://kevsono-kevs-digital-bos.hf.space https://*.supabase.co wss://*.supabase.co; frame-ancestors 'none';" Strict-Transport-Security = "max-age=31536000; includeSubDomains; preload" X-Frame-Options = "DENY" X-Content-Type-Options = "nosniff" X-XSS-Protection = "1; mode=block" Referrer-Policy = "strict-origin-when-cross-origin" Cross-Origin-Opener-Policy = "same-origin" Cross-Origin-Resource-Policy = "same-origin"
# ================================================================# ROUTE-SPECIFIC: STOREFRONT (GPS enabled)# ================================================================[[headers]] for = "/kdstore*" [headers.values] Content-Security-Policy = "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://www.googletagmanager.com https://connect.facebook.net https://analytics.tiktok.com; style-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdnjs.cloudflare.com https:; img-src 'self' data: https:; font-src 'self' data: https://cdnjs.cloudflare.com; connect-src 'self' https://kevsono-kevs-digital-bos.hf.space https://*.supabase.co https://api.paystack.co https://nominatim.openstreetmap.org; frame-ancestors 'none';" Permissions-Policy = "geolocation=(self), camera=(), microphone=(), payment=()" Strict-Transport-Security = "max-age=31536000; includeSubDomains; preload" X-Frame-Options = "DENY" X-Content-Type-Options = "nosniff" X-XSS-Protection = "1; mode=block" Referrer-Policy = "strict-origin-when-cross-origin" Cross-Origin-Opener-Policy = "same-origin" Cross-Origin-Resource-Policy = "same-origin"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706# ====================================================================# pos_transfers.py## Bank-transfer tracking for the POS terminal.## WHY THIS MODULE EXISTS# ----------------------# In Nigeria, the majority of in-person POS transactions are bank# transfers: the customer opens their banking app and sends money to one# of the merchant's Opay / Moniepoint / Palmpay / GTB / Access / etc.# accounts. The existing `payment_method='transfer'` enum value exists# in the sales table, but nothing records WHICH account the money landed# in. Reconciling the POS against the bank statement therefore requires# manually eyeballing receipt amounts and timestamps.## This module adds:## 1. org_payment_accounts — a per-org registry of receiving accounts# (label, provider, account_number, account_name, is_default).## 2. Four new columns on sales:# payment_account_id UUID → FK to org_payment_accounts# payment_transfer_reference TEXT → the bank's own txn ref# payment_confirmed_at TIMESTAMPTZ# payment_confirmed_by UUID → cashier who confirmed## 3. CRUD endpoints under /payment-accounts.## 4. Audit endpoints:# GET /payment-accounts/summary → per-account totals# GET /payment-accounts/transfers → filterable transfer log## The POS checkout flow is patched in main.py to REQUIRE an account id# when payment_method='transfer', and to stamp the sale with all four# columns immediately after the RPC creates it.# ====================================================================from fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom pydantic import BaseModel, Field, validatorfrom typing import Optional, List, Dict, Tuple, Literal, Anyfrom datetime import datetime, date, timezonefrom uuid import UUIDfrom collections import defaultdictimport httpximport os
from deps import ( SUPABASE_URL, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, logger, get_supabase, run_sync_db_call, get_current_user_with_role, require_role, rate_limit, get_client_ip,)
# ─────────────────────────────────────────────────────────────────────# Migration# ─────────────────────────────────────────────────────────────────────
async def ensure_payment_accounts_schema() -> None: """ Idempotent. Safe on every boot. """ sql = """ CREATE TABLE IF NOT EXISTS public.org_payment_accounts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), org_id UUID NOT NULL REFERENCES public.organisations(id) ON DELETE CASCADE, label TEXT NOT NULL, provider TEXT NOT NULL, account_number TEXT NOT NULL, account_name TEXT NOT NULL, is_active BOOLEAN NOT NULL DEFAULT TRUE, is_default BOOLEAN NOT NULL DEFAULT FALSE, sort_order INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), UNIQUE (org_id, provider, account_number) );
CREATE INDEX IF NOT EXISTS idx_org_payment_accounts_org ON public.org_payment_accounts(org_id, is_active);
CREATE UNIQUE INDEX IF NOT EXISTS idx_org_payment_accounts_default ON public.org_payment_accounts(org_id) WHERE is_default = TRUE;
ALTER TABLE public.sales ADD COLUMN IF NOT EXISTS payment_account_id UUID, ADD COLUMN IF NOT EXISTS payment_transfer_reference TEXT, ADD COLUMN IF NOT EXISTS payment_confirmed_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS payment_confirmed_by UUID;
DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM pg_constraint c JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey) WHERE c.conrelid = 'public.sales'::regclass AND c.contype = 'f' AND a.attname = 'payment_account_id' ) THEN ALTER TABLE public.sales ADD CONSTRAINT sales_payment_account_id_fkey FOREIGN KEY (payment_account_id) REFERENCES public.org_payment_accounts(id) ON DELETE SET NULL; END IF;
IF NOT EXISTS ( SELECT 1 FROM pg_constraint c JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey) WHERE c.conrelid = 'public.sales'::regclass AND c.contype = 'f' AND a.attname = 'payment_confirmed_by' ) THEN ALTER TABLE public.sales ADD CONSTRAINT sales_payment_confirmed_by_fkey FOREIGN KEY (payment_confirmed_by) REFERENCES public.profiles(id) ON DELETE SET NULL; END IF; END $$;
CREATE INDEX IF NOT EXISTS idx_sales_payment_account ON public.sales(payment_account_id, created_at DESC) WHERE payment_account_id IS NOT NULL; """ headers = { "apikey": SUPABASE_SERVICE_ROLE_KEY or SUPABASE_ANON_KEY, "Authorization": f"Bearer {SUPABASE_SERVICE_ROLE_KEY or SUPABASE_ANON_KEY}", "Content-Type": "application/json", } async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.post( f"{SUPABASE_URL}/rest/v1/rpc/exec_sql", json={"query": sql}, headers=headers, ) if resp.status_code not in (200, 204): logger.error(f"org_payment_accounts migration failed: {resp.text}") raise RuntimeError(f"org_payment_accounts migration failed: {resp.text}") logger.info("org_payment_accounts schema installed (or already present)")
# ─────────────────────────────────────────────────────────────────────# Pydantic models# ─────────────────────────────────────────────────────────────────────
ALLOWED_PROVIDERS = { "opay", "moniepoint", "palmpay", "kuda", "palmpay", "pocketapp", "gtb", "access", "zenith", "uba", "first_bank", "union", "fidelity", "sterling", "wema", "polaris", "fcmb", "stanbic", "ecobank", "heritage", "keystone", "providus", "unity", "suntrust", "other",}
class PaymentAccountCreate(BaseModel): label: str = Field(..., min_length=1, max_length=100) provider: str = Field(..., min_length=1, max_length=50) account_number: str = Field(..., min_length=10, max_length=20) account_name: str = Field(..., min_length=1, max_length=200) is_default: bool = False sort_order: int = 0
@validator("provider") def _provider_ok(cls, v): v = (v or "").strip().lower() if v not in ALLOWED_PROVIDERS: raise ValueError(f"provider must be one of {sorted(ALLOWED_PROVIDERS)}") return v
@validator("account_number") def _account_number_ok(cls, v): v = (v or "").strip() if not v.isdigit() or not (10 <= len(v) <= 20): raise ValueError("account_number must be 10-20 digits") return v
class PaymentAccountUpdate(BaseModel): label: Optional[str] = Field(None, min_length=1, max_length=100) provider: Optional[str] = Field(None, min_length=1, max_length=50) account_number: Optional[str] = Field(None, min_length=10, max_length=20) account_name: Optional[str] = Field(None, min_length=1, max_length=200) is_active: Optional[bool] = None is_default: Optional[bool] = None sort_order: Optional[int] = None
@validator("provider") def _provider_ok(cls, v): if v is None: return v v = v.strip().lower() if v not in ALLOWED_PROVIDERS: raise ValueError(f"provider must be one of {sorted(ALLOWED_PROVIDERS)}") return v
@validator("account_number") def _account_number_ok(cls, v): if v is None: return v v = v.strip() if not v.isdigit() or not (10 <= len(v) <= 20): raise ValueError("account_number must be 10-20 digits") return v
# ─────────────────────────────────────────────────────────────────────# Router# ─────────────────────────────────────────────────────────────────────
router = APIRouter(prefix="/payment-accounts", tags=["Payment Accounts"])
def _serialize_account(row: Dict) -> Dict: return { "id": row.get("id"), "label": row.get("label"), "provider": row.get("provider"), "account_number": row.get("account_number"), "account_name": row.get("account_name"), "is_active": bool(row.get("is_active", True)), "is_default": bool(row.get("is_default", False)), "sort_order": int(row.get("sort_order") or 0), "created_at": row.get("created_at"), "updated_at": row.get("updated_at"), }
@router.get("")async def list_payment_accounts( request: Request, include_inactive: bool = Query(False), include_totals: bool = Query(False, description="Attach per-account transfer stats"), user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "sales_rep", "finance", "inventory_manager"]) ),): """ List the org's registered receiving accounts.
`include_totals=true` attaches a `stats` object to each account: { count, total, today_count, today_total, mtd_count, mtd_total }
Filterable flags: - include_inactive=false (default) → only `is_active=TRUE` """ await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase()
query = ( client.table("org_payment_accounts") .select("*") .eq("org_id", org_id) .order("is_default", desc=True) .order("sort_order", desc=False) .order("label", desc=False) ) if not include_inactive: query = query.eq("is_active", True)
res = await run_sync_db_call(query.execute) accounts = [_serialize_account(r) for r in (res.data or [])]
if include_totals and accounts: stats_by_account = await _compute_transfer_stats(org_id, [a["id"] for a in accounts]) for acc in accounts: acc["stats"] = stats_by_account.get( acc["id"], {"count": 0, "total": 0.0, "today_count": 0, "today_total": 0.0, "mtd_count": 0, "mtd_total": 0.0}, )
return {"accounts": accounts, "total": len(accounts)}
async def _compute_transfer_stats(org_id: str, account_ids: List[str]) -> Dict[str, Dict]: """ Group transfer sales by payment_account_id.
Single full scan of the org's transfer sales, aggregated in Python. At 10k transfers/org/month this is a ~50ms query. If a shop ever exceeds that, promote to a materialized view; the aggregation logic below is the authoritative shape. """ client = get_supabase() res = await run_sync_db_call( client.table("sales") .select("payment_account_id, total_amount, created_at") .eq("org_id", org_id) .eq("payment_method", "transfer") .not_.is_("payment_account_id", "null") .execute )
today = date.today() month_start = today.replace(day=1) today_iso = today.isoformat() month_iso = month_start.isoformat()
bucket: Dict[str, Dict] = defaultdict( lambda: {"count": 0, "total": 0.0, "today_count": 0, "today_total": 0.0, "mtd_count": 0, "mtd_total": 0.0} )
wanted = set(account_ids) for row in (res.data or []): acc_id = row.get("payment_account_id") if acc_id not in wanted: continue amt = float(row.get("total_amount") or 0) b = bucket[acc_id] b["count"] += 1 b["total"] += amt created = (row.get("created_at") or "")[:10] if created == today_iso: b["today_count"] += 1 b["today_total"] += amt if created and created >= month_iso: b["mtd_count"] += 1 b["mtd_total"] += amt
return dict(bucket)
@router.post("")async def create_payment_account( request: Request, payload: PaymentAccountCreate, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "finance"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() now = datetime.now(timezone.utc).isoformat()
# If this is being made the default, unset any existing default first. if payload.is_default: await run_sync_db_call( client.table("org_payment_accounts") .update({"is_default": False, "updated_at": now}) .eq("org_id", org_id) .eq("is_default", True) .execute )
insert_data = { "org_id": org_id, "label": payload.label.strip(), "provider": payload.provider, "account_number": payload.account_number, "account_name": payload.account_name.strip(), "is_active": True, "is_default": payload.is_default, "sort_order": payload.sort_order, "created_at": now, "updated_at": now, }
try: ins = await run_sync_db_call( client.table("org_payment_accounts").insert(insert_data).execute ) except Exception as e: msg = str(e) if "duplicate key" in msg or "23505" in msg: raise HTTPException( status_code=409, detail="An account with this provider and account number already exists", ) raise HTTPException(status_code=500, detail=f"Failed to create account: {msg}")
if not ins.data: raise HTTPException(status_code=500, detail="Failed to create account") return {"account": _serialize_account(ins.data[0])}
@router.patch("/{account_id}")async def update_payment_account( request: Request, account_id: UUID, payload: PaymentAccountUpdate, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "finance"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() now = datetime.now(timezone.utc).isoformat()
existing = await run_sync_db_call( client.table("org_payment_accounts") .select("id, is_default") .eq("id", str(account_id)) .eq("org_id", org_id) .maybe_single() .execute ) if not existing or not existing.data: raise HTTPException(status_code=404, detail="Payment account not found")
updates = {k: v for k, v in payload.dict(exclude_unset=True).items() if v is not None} if not updates: raise HTTPException(status_code=400, detail="Nothing to update")
# Becoming default: unset any other default first. if updates.get("is_default") is True: await run_sync_db_call( client.table("org_payment_accounts") .update({"is_default": False, "updated_at": now}) .eq("org_id", org_id) .eq("is_default", True) .neq("id", str(account_id)) .execute )
updates["updated_at"] = now
try: res = await run_sync_db_call( client.table("org_payment_accounts") .update(updates) .eq("id", str(account_id)) .eq("org_id", org_id) .execute ) except Exception as e: msg = str(e) if "duplicate key" in msg or "23505" in msg: raise HTTPException( status_code=409, detail="An account with this provider and account number already exists", ) raise HTTPException(status_code=500, detail=f"Failed to update account: {msg}")
if not res.data: raise HTTPException(status_code=404, detail="Payment account not found") return {"account": _serialize_account(res.data[0])}
@router.delete("/{account_id}")async def delete_payment_account( request: Request, account_id: UUID, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin"]) ),): """ Soft-delete by setting is_active=FALSE.
We never hard-delete an account because historical sales point at it via payment_account_id. Keeping the row lets the audit view resolve the label for old transfers. If the admin really wants it gone, they can deactivate (this endpoint) — the POS dropdown will hide it but historical reports stay correct. """ await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase() now = datetime.now(timezone.utc).isoformat()
res = await run_sync_db_call( client.table("org_payment_accounts") .update({ "is_active": False, "is_default": False, "updated_at": now, }) .eq("id", str(account_id)) .eq("org_id", org_id) .execute ) if not res.data: raise HTTPException(status_code=404, detail="Payment account not found") return {"deactivated": True, "account_id": str(account_id)}
@router.get("/summary")async def payment_accounts_summary( request: Request, from_date: Optional[date] = Query(None), to_date: Optional[date] = Query(None), user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "finance", "auditor"]) ),): """ Per-account totals for the accounting dashboard.
Returns one row per active account: total received, count of transfers, average ticket, and last transfer timestamp. Optionally scoped to a date range. """ await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase()
accounts_res = await run_sync_db_call( client.table("org_payment_accounts") .select("id, label, provider, account_number, account_name, is_default") .eq("org_id", org_id) .eq("is_active", True) .order("is_default", desc=True) .order("label", desc=False) .execute ) accounts = accounts_res.data or []
if not accounts: return {"accounts": [], "period": {"from": None, "to": None}}
query = ( client.table("sales") .select("payment_account_id, total_amount, created_at") .eq("org_id", org_id) .eq("payment_method", "transfer") .not_.is_("payment_account_id", "null") ) if from_date: query = query.gte("created_at", f"{from_date.isoformat()}T00:00:00") if to_date: query = query.lte("created_at", f"{to_date.isoformat()}T23:59:59")
sales_res = await run_sync_db_call(query.execute) sales_rows = sales_res.data or []
by_id: Dict[str, List[Dict]] = defaultdict(list) for row in sales_rows: by_id[row.get("payment_account_id")].append(row)
out = [] for acc in accounts: rows = by_id.get(acc["id"], []) total = sum(float(r.get("total_amount") or 0) for r in rows) count = len(rows) last = max((r.get("created_at") for r in rows), default=None) out.append({ **_serialize_account(acc), "transfer_count": count, "total_received": round(total, 2), "average_ticket": round(total / count, 2) if count else 0.0, "last_transfer_at": last, })
return { "accounts": out, "period": { "from": from_date.isoformat() if from_date else None, "to": to_date.isoformat() if to_date else None, }, }
@router.get("/transfers")async def list_transfers( request: Request, account_id: Optional[UUID] = Query(None), provider: Optional[str] = Query(None), from_date: Optional[date] = Query(None), to_date: Optional[date] = Query(None), cashier_id: Optional[UUID] = Query(None), limit: int = Query(200, ge=1, le=1000), offset: int = Query(0, ge=0), user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "finance", "auditor"]) ),): """ The audit trail. Every POS transfer, filterable by account / date / cashier. Use this to reconcile the POS against the bank statement.
Each row carries the sale data AND the account that received it, so the accountant sees: receipt#, cashier, amount, which account, bank reference, confirmed timestamp — all in one row. """ await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase()
query = ( client.table("sales") .select( "id, receipt_number, total_amount, payment_method, " "payment_account_id, payment_transfer_reference, " "payment_confirmed_at, payment_confirmed_by, " "customer_name, customer_phone, created_at, user_id, " "org_payment_account:org_payment_accounts!payment_account_id(" "id, label, provider, account_number, account_name)", count="exact", ) .eq("org_id", org_id) .eq("payment_method", "transfer") )
if account_id: query = query.eq("payment_account_id", str(account_id)) if from_date: query = query.gte("created_at", f"{from_date.isoformat()}T00:00:00") if to_date: query = query.lte("created_at", f"{to_date.isoformat()}T23:59:59") if cashier_id: query = query.eq("user_id", str(cashier_id))
res = await run_sync_db_call( query.order("created_at", desc=True) .range(offset, offset + limit - 1) .execute ) rows = res.data or []
# Provider filter applied in Python because it lives on the joined # account row — PostgREST cannot filter on an embedded resource # without a second round trip, and this is a small result set. if provider: provider = provider.strip().lower() rows = [ r for r in rows if (r.get("org_payment_account") or {}).get("provider") == provider ]
# Enrich with cashier name for the audit display. cashier_ids = list({r.get("user_id") for r in rows if r.get("user_id")}) profiles_map: Dict[str, Dict] = {} if cashier_ids: prof_res = await run_sync_db_call( client.table("profiles") .select("id, first_name, last_name, email") .in_("id", cashier_ids) .execute ) profiles_map = {p["id"]: p for p in (prof_res.data or [])}
sale_ids = list({str(r.get("id")).strip() for r in rows if r.get("id")}) items_by_sale: Dict[str, List[Dict]] = defaultdict(list) if sale_ids: try: items_res = await run_sync_db_call( client.table("sale_items") .select("sale_id, product_name, quantity, unit_price, subtotal") .in_("sale_id", sale_ids) .execute ) for it in (items_res.data or []): sid = str(it.get("sale_id") or "").strip() if sid: items_by_sale[sid].append({ "product_name": it.get("product_name") or "Item", "quantity": it.get("quantity") or 1, "unit_price": float(it.get("unit_price") or 0), "subtotal": float(it.get("subtotal") or 0), }) except Exception as e: logger.warning(f"sale_items lookup failed for transfers: {e}")
transfers: List[Dict] = [] for r in rows: acc = r.get("org_payment_account") or {} cashier = profiles_map.get(r.get("user_id")) or {} cashier_name = " ".join( filter(None, [cashier.get("first_name"), cashier.get("last_name")]) ).strip() or None
transfers.append({ "sale_id": r.get("id"), "receipt_number": r.get("receipt_number"), "amount": float(r.get("total_amount") or 0), "customer_name": r.get("customer_name"), "customer_phone": r.get("customer_phone"), "created_at": r.get("created_at"), "payment_confirmed_at": r.get("payment_confirmed_at"), "payment_transfer_reference": r.get("payment_transfer_reference"), "cashier_id": r.get("user_id"), "cashier_name": cashier_name, "items": items_by_sale.get(str(r.get("id") or "").strip(), []), "account": { "id": acc.get("id"), "label": acc.get("label"), "provider": acc.get("provider"), "account_number": acc.get("account_number"), "account_name": acc.get("account_name"), } if acc else None, })
return { "transfers": transfers, "total": res.count if hasattr(res, "count") and res.count is not None else len(transfers), "returned": len(transfers), "limit": limit, "offset": offset, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""procurement.py — Procurement routes.
Extracted from main.py to keep the monolith from growing further.Currently hosts /restock-hub. The remaining procurement endpoints(/suppliers, /purchase-orders, /grn) will migrate here incrementallyonce their dependencies on main.py helpers (create_ap_from_po,post_grn's A/P linkage, etc.) are resolved."""from fastapi import APIRouter, Depends, Requestfrom typing import Dict, List, Optional, Tuplefrom datetime import datetime, timezone
from deps import ( logger, get_supabase, run_sync_db_call, rate_limit, get_client_ip, require_feature,)
router = APIRouter(tags=["Procurement"])
@router.get("/restock-hub")async def get_restock_hub( request: Request, user_data: Tuple[str, str, str] = Depends( require_feature( "procurement", allowed_roles=["owner", "admin", "inventory_manager"], ) )): """ Aggregated procurement intelligence for the Restock Hub tab.
Combines stock_limits (per-location reorder points / max stock) with active OUT_OF_STOCK alerts (for the "out for N days" figure) into a single list of items that need replenishment.
Gated on `procurement` because this endpoint exists only to feed the Restock Hub — a procurement surface. The shared inventory endpoints (`/stock-limits`, `/alerts`) remain on their own feature gates and are not affected. """ await rate_limit(get_client_ip(request), user_data[1], request=request) _, org_id, _ = user_data client = get_supabase()
# ── 1. Fetch stock limits for the org ── try: limits_res = await run_sync_db_call( client.table("stock_limits") .select( "inventory_id, location_id, avg_daily_demand, " "reorder_point, max_stock" ) .eq("org_id", org_id) .execute ) limits = limits_res.data or [] except Exception as e: logger.error(f"restock-hub: stock_limits read failed: {e}") return { "items": [], "summary": {"out_of_stock": 0, "low_stock": 0, "estimated_value": 0.0}, }
inventory_ids = {l["inventory_id"] for l in limits if l.get("inventory_id")} if not inventory_ids: return { "items": [], "summary": {"out_of_stock": 0, "low_stock": 0, "estimated_value": 0.0}, }
# ── 2. Fetch inventory details (name, sku, current_qty, cost) ── try: inv_res = await run_sync_db_call( client.table("inventory") .select("id, description, item_code, current_qty, cost_price_naira") .eq("org_id", org_id) .in_("id", list(inventory_ids)) .execute ) inv_map = {p["id"]: p for p in (inv_res.data or [])} except Exception as e: logger.error(f"restock-hub: inventory read failed: {e}") inv_map = {}
# ── 3. Fetch active OUT_OF_STOCK alerts (for "out for N days") ── out_since_map: Dict[int, str] = {} try: alerts_res = await run_sync_db_call( client.table("alert_log") .select("inventory_id, created_at") .eq("org_id", org_id) .eq("alert_type", "OUT_OF_STOCK") .is_("action_taken", "null") .order("created_at", desc=False) .execute ) for a in (alerts_res.data or []): inv_id = a.get("inventory_id") if inv_id and inv_id not in out_since_map: out_since_map[inv_id] = a.get("created_at") except Exception as e: logger.warning(f"restock-hub: alerts read failed: {e}")
# ── 4. Aggregate stock limits by inventory_id ── aggregated: Dict[int, Dict] = {} for l in limits: inv_id = l.get("inventory_id") if not inv_id: continue if inv_id not in aggregated: aggregated[inv_id] = { "total_reorder": 0, "total_max": 0, "total_demand": 0.0, } aggregated[inv_id]["total_reorder"] += int(l.get("reorder_point") or 0) aggregated[inv_id]["total_max"] += int(l.get("max_stock") or 0) aggregated[inv_id]["total_demand"] += float(l.get("avg_daily_demand") or 0)
# ── 5. Build the restock list ── now = datetime.now(timezone.utc) items: List[Dict] = [] out_of_stock_count = 0 low_stock_count = 0 estimated_value = 0.0
for inv_id, agg in aggregated.items(): product = inv_map.get(inv_id) if not product: continue current_qty = int(product.get("current_qty") or 0)
if current_qty > agg["total_reorder"] and current_qty > 0: continue
if current_qty <= 0: out_of_stock_count += 1 out_since = out_since_map.get(inv_id) if out_since: try: out_dt = datetime.fromisoformat(out_since.replace("Z", "+00:00")) if out_dt.tzinfo is None: out_dt = out_dt.replace(tzinfo=timezone.utc) days_out = max(0, (now - out_dt).days) days_left_display = f"Out for {days_out} days" except Exception: days_left_display = "Out of stock" else: days_left_display = "Out of stock" else: low_stock_count += 1 if agg["total_demand"] > 0: days_left = round(current_qty / agg["total_demand"]) days_left_display = f"{days_left} days" else: days_left_display = "∞"
suggested_order = ( max(0, agg["total_max"] - current_qty) if agg["total_max"] > 0 else 10 ) cost = float(product.get("cost_price_naira") or 0) estimated_value += suggested_order * cost
items.append({ "inventory_id": inv_id, "name": product.get("description") or "Unknown", "sku": product.get("item_code") or "N/A", "current_qty": current_qty, "total_reorder": agg["total_reorder"], "total_max": agg["total_max"], "days_left_display": days_left_display, "suggested_order": suggested_order, "is_out_of_stock": current_qty <= 0, })
items.sort(key=lambda x: (not x["is_out_of_stock"], x["current_qty"]))
return { "items": items, "summary": { "out_of_stock": out_of_stock_count, "low_stock": low_stock_count, "estimated_value": round(estimated_value, 2), }, }1234567891011121314fastapi==0.104.1uvicorn==0.24.0supabase==1.2.0gotrue==1.1.0httpx==0.24.1groq==0.4.2google-generativeai==0.3.2python-multipart==0.0.6sentence-transformers==2.7.0tenacity==8.2.3torchtransformersstructlogboto3>=1.34.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204from fastapi import APIRouter, Depends, HTTPException, Requestfrom pydantic import BaseModel, Fieldfrom typing import Tuple, Optionalfrom datetime import datetime, timezonefrom uuid import UUID, uuid4from main import get_supabase, run_sync_db_call, rate_limit, get_client_ipfrom deps import require_role, get_user_branches, get_visible_user_ids, resolve_request_branch_for_write, resolve_request_branch, resolve_default_branch, is_user_in_branch, ensure_default_branch
router = APIRouter(prefix="/chat", tags=["Live Chat"])
class ChatMessageCreate(BaseModel): message: str = Field(..., max_length=2000)
class ComplaintCreate(BaseModel): subject: str = Field(..., max_length=200) message: str = Field(..., max_length=2000)
@router.get("/sessions")async def list_chat_sessions( request: Request, status: str = "open", user_data: Tuple[str, str, str] = Depends(require_role(["owner", "admin", "support"]))): """List live chat sessions for the org — used by the support dashboard.""" _, org_id, _ = user_data client = get_supabase()
res = await run_sync_db_call( client.table("chat_sessions") .select("id, user_id, channel, status, started_at") .eq("org_id", org_id) .eq("status", status) .eq("channel", "live_chat") .order("started_at", desc=True) .execute # ← no parens, deferred to worker thread )
sessions = res.data or [] if sessions: user_ids = list({s["user_id"] for s in sessions if s.get("user_id")}) if user_ids: profiles = await run_sync_db_call( client.table("profiles") .select("id, first_name, last_name, email") .in_("id", user_ids) .execute ) pmap = {p["id"]: p for p in (profiles.data or [])} for s in sessions: p = pmap.get(s.get("user_id"), {}) s["customer_name"] = ( f"{p.get('first_name', '')} {p.get('last_name', '')}".strip() or "Guest" ) s["customer_email"] = p.get("email", "")
return {"sessions": sessions}
@router.get("/availability")async def check_agent_availability( request: Request, user_data: Tuple[str, str, str] = Depends(require_role(["customer", "owner", "admin"]))): """Check if there are support agents available for this org.""" _, org_id, _ = user_data client = get_supabase() # Simple check: are there any users with support/owner/admin roles? res = await run_sync_db_call( client.table("org_members") .select("user_id") .eq("org_id", org_id) .in_("role", ["owner", "admin", "support"]) .limit(1) .execute ) return {"available": len(res.data) > 0}
@router.post("/complaint")async def submit_complaint( request: Request, payload: ComplaintCreate, user_data: Tuple[str, str, str] = Depends(require_role(["customer", "owner", "admin"]))): """Submit a complaint if no agents are available. Requires login.""" user_id, org_id, _ = user_data client = get_supabase() ticket_id = str(uuid4()) now = datetime.now(timezone.utc).isoformat() # 1. Create the support ticket await run_sync_db_call( client.table("support_tickets").insert({ "id": ticket_id, "user_id": user_id, "org_id": org_id, "subject": payload.subject, "priority": "high", "status": "open", "created_at": now }).execute ) # 2. Add the complaint message await run_sync_db_call( client.table("ticket_messages").insert({ "ticket_id": ticket_id, "sender_type": "customer", "sender_id": user_id, "message": payload.message, "created_at": now }).execute ) return {"message": "Complaint submitted successfully", "ticket_id": ticket_id}
@router.post("/session")async def start_chat_session( request: Request, user_data: Tuple[str, str, str] = Depends(require_role(["customer", "owner", "admin"]))): """Start or resume an open live chat session.""" user_id, org_id, _ = user_data client = get_supabase() existing = await run_sync_db_call( client.table("chat_sessions") .select("id") .eq("user_id", user_id) .eq("org_id", org_id) .eq("status", "open") .eq("channel", "live_chat") .order("started_at", desc=True) .limit(1) .execute )
if existing.data: return {"session_id": existing.data[0]["id"], "status": "open"}
session_id = str(uuid4()) await run_sync_db_call( client.table("chat_sessions").insert({ "id": session_id, "user_id": user_id, "org_id": org_id, "channel": "live_chat", "status": "open", "started_at": datetime.now(timezone.utc).isoformat() }).execute ) return {"session_id": session_id, "status": "open"}
@router.post("/session/{session_id}/message")async def send_chat_message( request: Request, session_id: str, payload: ChatMessageCreate, user_data: Tuple[str, str, str] = Depends(require_role(["customer", "owner", "admin", "support"]))): """Send a message in a live chat.""" user_id, org_id, role = user_data client = get_supabase() session = await run_sync_db_call( client.table("chat_sessions").select("id").eq("id", session_id).eq("org_id", org_id).maybe_single().execute ) if not session or not session.data: raise HTTPException(status_code=404, detail="Session not found")
sender_type = "agent" if role in ["owner", "admin", "support"] else "customer" # inside send_chat_message — change .execute() → .execute await run_sync_db_call( client.table("chat_messages").insert({ "session_id": session_id, "user_id": user_id, "org_id": org_id, "sender_type": sender_type, "message": payload.message, "created_at": datetime.now(timezone.utc).isoformat() }).execute # ← no parens ) return {"status": "sent"}
@router.get("/session/{session_id}/messages")async def get_chat_messages( request: Request, session_id: str, user_data: Tuple[str, str, str] = Depends(require_role(["customer", "owner", "admin", "support"]))): """Fetch all messages in a live chat session.""" _, org_id, _ = user_data client = get_supabase() res = await run_sync_db_call( client.table("chat_messages") .select("id, sender_type, message, created_at") .eq("session_id", session_id) .eq("org_id", org_id) .order("created_at", desc=False) .execute ) return {"messages": res.data or []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696# support_tickets.py## Multi-tenant, multi-branch support-ticket module.## Architecture:## - Recipients live in organisations.escalation_config (JSONB), not in# environment variables. Environment variables are platform-wide and# would notify every tenant's customers on behalf of every other# tenant — a leak, not a feature.## - Email and WhatsApp delivery go through the existing abstractions# already exported from main.py:# send_sendgrid_email (email provider — swap Brevo→SES# in that one function)# send_whatsapp_message_with_retry (WhatsApp provider)# This module never imports a provider SDK, never names a provider,# and never needs to change when the provider changes.## - Access control is role + branch aware:# customer → only their own tickets# owner → all tickets in the org# admin / support → tickets in their assigned branch(es)# Branch scoping uses branch_members via get_user_branches(), the# same rule /stock-transfers, /grn, and /fulfillment/orders use.## - Ticket creation supports both legacy and new field names:# POST /api/support/ticket (legacy: `message`)# POST /support/tickets (new: `description`)# Both routes registered, both fields accepted.
from datetime import datetime, timezonefrom typing import Tuple, Optional, List
from fastapi import APIRouter, Depends, HTTPException, Requestfrom pydantic import BaseModel, Field
from main import ( get_supabase, run_sync_db_call, rate_limit, get_client_ip, send_sendgrid_email, send_whatsapp_message_with_retry, logger,)from deps import require_role, get_user_branches, get_visible_user_ids, resolve_request_branch_for_write, resolve_request_branch, resolve_default_branch, is_user_in_branch, ensure_default_branch
router = APIRouter(tags=["Support Tickets"])
# ─────────────────────────────────────────────────────────────────────# Pydantic models# ─────────────────────────────────────────────────────────────────────
class TicketCreate(BaseModel): subject: str = Field(..., min_length=1, max_length=200) priority: str = "normal" message: Optional[str] = None description: Optional[str] = None user_id: Optional[str] = None # honoured for agent callers only
@property def body_text(self) -> str: return (self.message or self.description or "").strip()
class TicketMessageReq(BaseModel): message: str = Field(..., min_length=1, max_length=4000)
class ResolveReq(BaseModel): resolution_notes: str = Field("", max_length=4000)
class EscalateReq(BaseModel): department: str = Field(..., min_length=1, max_length=100) method: str = Field("email", description="'email' or 'whatsapp'") note: str = Field("", max_length=4000)
# ─────────────────────────────────────────────────────────────────────# Department name ↔ config key normalisation## The frontend dropdown sends human-readable values ("Technical Support").# The config JSONB uses snake_case keys ("technical_support") because that# is the conventional shape for keys inside JSONB blobs — no spaces, no# case sensitivity headaches.# ─────────────────────────────────────────────────────────────────────
KNOWN_DEPARTMENTS = { "Technical Support": "technical_support", "Billing": "billing", "Logistics": "logistics", "Sales": "sales", "Management": "management",}
def _dept_key(department: str) -> str: """Normalise a department label to a config key.""" if department in KNOWN_DEPARTMENTS: return KNOWN_DEPARTMENTS[department] return department.strip().lower().replace(" ", "_")
# ─────────────────────────────────────────────────────────────────────# Access scoping — role + branch aware# ─────────────────────────────────────────────────────────────────────
async def _scope_for_caller(user_id: str, org_id: str, role: str) -> dict: """ Resolve the filter to apply to any ticket query for this caller.
Returns: {"user_filter": <uuid>|None, "branch_filter": <uuid>|<list>|None} """ if role == "customer": return {"user_filter": user_id, "branch_filter": None}
if role == "owner": return {"user_filter": None, "branch_filter": None}
# admin / support / any other staff role branches = await get_user_branches(user_id, org_id) if not branches: raise HTTPException( status_code=403, detail="You are not assigned to any branch, so you have no ticket access.", ) if len(branches) == 1: return {"user_filter": None, "branch_filter": branches[0]["id"]} return {"user_filter": None, "branch_filter": [b["id"] for b in branches]}
def _apply_scope(query, scope: dict): if scope.get("user_filter"): query = query.eq("user_id", scope["user_filter"]) bf = scope.get("branch_filter") if isinstance(bf, list): query = query.in_("branch_id", bf) elif bf: query = query.eq("branch_id", bf) return query
async def _fetch_accessible_ticket( ticket_id: str, org_id: str, user_id: str, role: str) -> dict: """ Fetch a ticket and confirm the caller can access it. Raises 404 (never 403) so a caller cannot distinguish "does not exist" from "belongs to another branch". """ scope = await _scope_for_caller(user_id, org_id, role) client = get_supabase()
query = ( client.table("support_tickets") .select("*") .eq("id", ticket_id) .eq("org_id", org_id) ) query = _apply_scope(query, scope)
res = await run_sync_db_call(query.maybe_single().execute) if not res or not res.data: raise HTTPException(status_code=404, detail="Ticket not found") return res.data
# ─────────────────────────────────────────────────────────────────────# Escalation-config resolution## Config lives on organisations.escalation_config. The lookup order at# escalate time is:## 1. ticket.branch_id → config.branches[ticket.branch_id].departments[dept][method]# 2. config.departments[dept][method]# 3. HTTPException 422 with a message that points at the config endpoint## There is no env-var fallback. That is deliberate.# ─────────────────────────────────────────────────────────────────────
async def _read_escalation_config(org_id: str) -> dict: client = get_supabase() res = await run_sync_db_call( client.table("organisations") .select("escalation_config") .eq("id", org_id) .maybe_single() .execute ) if not res or not res.data: raise HTTPException(status_code=404, detail="Organisation not found") return res.data.get("escalation_config") or {}
def _resolve_escalation_target( config: dict, department: str, method: str, branch_id: Optional[str],) -> Optional[str]: """ Walk the resolution order and return the target, or None.
`config` is the raw escalation_config JSONB from the org. """ dept_key = _dept_key(department) if method not in ("email", "whatsapp"): return None
# 1. branch-specific if branch_id: branch_cfg = (config.get("branches") or {}).get(str(branch_id)) or {} dept_cfg = (branch_cfg.get("departments") or {}).get(dept_key) or {} target = (dept_cfg.get(method) or "").strip() if target: return target
# 2. org-level dept_cfg = (config.get("departments") or {}).get(dept_key) or {} target = (dept_cfg.get(method) or "").strip() if target: return target
return None
# ─────────────────────────────────────────────────────────────────────# Config management endpoints# ─────────────────────────────────────────────────────────────────────
@router.get("/support/escalation-config")async def get_escalation_config( user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "support"]) ),): _, org_id, _ = user_data return { "config": await _read_escalation_config(org_id), "known_departments": KNOWN_DEPARTMENTS, }
class EscalationConfigUpdate(BaseModel): config: dict
@router.put("/support/escalation-config")async def put_escalation_config( payload: EscalationConfigUpdate, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin"]) ),): """ Replace the org's entire escalation_config.
PUT, not PATCH. Config is a small complete document; "here is the full new config" is simpler to validate and safer than a partial merge that could leave stale targets behind.
Shape validation is intentionally loose at the top level (JSONB is flexible) but strict about the fields that matter:
- config.departments must be a dict of dicts - config.branches must be a dict of dicts - email values must contain '@' - whatsapp values must start with '+'
Bad values are rejected with a 400 so the caller knows immediately rather than discovering it during a live escalation. """ _, org_id, _ = user_data cfg = payload.config
if not isinstance(cfg, dict): raise HTTPException(status_code=400, detail="config must be an object")
def _validate_contacts(block: dict, path: str) -> None: if not isinstance(block, dict): raise HTTPException(status_code=400, detail=f"{path} must be an object") for dept, contacts in block.items(): if not isinstance(contacts, dict): raise HTTPException( status_code=400, detail=f"{path}.{dept} must be an object", ) email = contacts.get("email") if email is not None: if not isinstance(email, str) or "@" not in email: raise HTTPException( status_code=400, detail=f"{path}.{dept}.email must be a valid email", ) whatsapp = contacts.get("whatsapp") if whatsapp is not None: if not isinstance(whatsapp, str) or not whatsapp.startswith("+"): raise HTTPException( status_code=400, detail=f"{path}.{dept}.whatsapp must start with '+'", )
if "departments" in cfg: _validate_contacts(cfg["departments"], "departments")
if "branches" in cfg: branches = cfg["branches"] if not isinstance(branches, dict): raise HTTPException(status_code=400, detail="branches must be an object") for branch_id, branch_cfg in branches.items(): if not isinstance(branch_cfg, dict): raise HTTPException( status_code=400, detail=f"branches.{branch_id} must be an object", ) if "departments" in branch_cfg: _validate_contacts( branch_cfg["departments"], f"branches.{branch_id}.departments", )
client = get_supabase() res = await run_sync_db_call( client.table("organisations") .update({ "escalation_config": cfg, "updated_at": datetime.now(timezone.utc).isoformat(), }) .eq("id", org_id) .execute ) if not res.data: raise HTTPException(status_code=500, detail="Failed to save config")
return {"config": cfg}
# ─────────────────────────────────────────────────────────────────────# Create ticket# ─────────────────────────────────────────────────────────────────────
@router.post("/support/tickets")@router.post("/api/support/ticket")async def create_ticket_endpoint( request: Request, ticket: TicketCreate, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "support", "customer"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) caller_id, org_id, role = user_data client = get_supabase()
body = ticket.body_text if not body: raise HTTPException( status_code=400, detail="Either 'message' or 'description' must be provided", )
# Attribution. A customer can only file on their own behalf even if # they send a user_id — no impersonation. An agent can file on behalf # of a customer, provided that customer belongs to this org. ticket_owner = caller_id if ticket.user_id and ticket.user_id != caller_id: if role not in ("owner", "admin", "support"): raise HTTPException( status_code=403, detail="Only agents can create tickets on behalf of another user", ) m = await run_sync_db_call( client.table("org_members") .select("user_id") .eq("user_id", ticket.user_id) .eq("org_id", org_id) .maybe_single() .execute ) l = await run_sync_db_call( client.table("org_leads") .select("profile_id") .eq("profile_id", ticket.user_id) .eq("org_id", org_id) .maybe_single() .execute ) if not (m and m.data) and not (l and l.data): raise HTTPException( status_code=400, detail="Target customer is not part of this organisation", ) ticket_owner = ticket.user_id
branch_id = await resolve_request_branch_for_write( request, caller_id, org_id, role ) now = datetime.now(timezone.utc).isoformat()
ins = await run_sync_db_call( client.table("support_tickets").insert({ "user_id": ticket_owner, "org_id": org_id, "branch_id": branch_id, "subject": ticket.subject, "priority": ticket.priority or "normal", "status": "open", "created_at": now, }).execute ) if not ins.data: raise HTTPException(status_code=500, detail="Failed to create ticket") ticket_id = ins.data[0]["id"]
await run_sync_db_call( client.table("ticket_messages").insert({ "ticket_id": ticket_id, "sender_type": "user" if ticket_owner == caller_id else "agent", "sender_id": caller_id, "message": body, "created_at": now, }).execute )
return { "ticket_id": ticket_id, "confirmation": f"Ticket #{ticket_id[:8]} created", }
# ─────────────────────────────────────────────────────────────────────# List / get / message / resolve# ─────────────────────────────────────────────────────────────────────
@router.get("/support/tickets")async def list_tickets_endpoint( request: Request, status: Optional[str] = None, from_date: Optional[str] = None, to_date: Optional[str] = None, limit: int = 100, offset: int = 0, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "support", "customer"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) caller_id, org_id, role = user_data client = get_supabase()
scope = await _scope_for_caller(caller_id, org_id, role)
query = client.table("support_tickets").select("*").eq("org_id", org_id) query = _apply_scope(query, scope)
if status: query = query.eq("status", status) if from_date: query = query.gte("created_at", f"{from_date}T00:00:00Z") if to_date: query = query.lte("created_at", f"{to_date}T23:59:59.999999Z")
result = await run_sync_db_call( query.order("created_at", desc=True) .range(offset, offset + limit - 1) .execute ) return {"tickets": result.data or []}
@router.get("/support/tickets/{ticket_id}")async def get_ticket_endpoint( request: Request, ticket_id: str, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "support", "customer"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) caller_id, org_id, role = user_data client = get_supabase()
ticket = await _fetch_accessible_ticket(ticket_id, org_id, caller_id, role)
messages = await run_sync_db_call( client.table("ticket_messages") .select("*") .eq("ticket_id", ticket_id) .order("created_at", desc=False) .execute ) return {"ticket": ticket, "messages": messages.data or []}
@router.post("/support/tickets/{ticket_id}/message")async def add_ticket_message_endpoint( request: Request, ticket_id: str, msg: TicketMessageReq, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "support", "customer"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) caller_id, org_id, role = user_data client = get_supabase()
await _fetch_accessible_ticket(ticket_id, org_id, caller_id, role)
sender_type = "agent" if role in ("owner", "admin", "support") else "customer"
await run_sync_db_call( client.table("ticket_messages").insert({ "ticket_id": ticket_id, "sender_type": sender_type, "sender_id": caller_id, "message": msg.message, "created_at": datetime.now(timezone.utc).isoformat(), }).execute )
messages = await run_sync_db_call( client.table("ticket_messages") .select("*") .eq("ticket_id", ticket_id) .order("created_at", desc=False) .execute ) return {"messages": messages.data or []}
@router.post("/support/tickets/{ticket_id}/resolve")async def resolve_ticket_endpoint( request: Request, ticket_id: str, req: ResolveReq, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "support"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) caller_id, org_id, role = user_data client = get_supabase()
await _fetch_accessible_ticket(ticket_id, org_id, caller_id, role)
upd = await run_sync_db_call( client.table("support_tickets").update({ "status": "resolved", "resolution_notes": req.resolution_notes, "resolved_at": datetime.now(timezone.utc).isoformat(), }).eq("id", ticket_id).eq("org_id", org_id).execute )
return { "message": "Ticket resolved", "ticket": upd.data[0] if upd.data else None, }
# ─────────────────────────────────────────────────────────────────────# Escalate# ─────────────────────────────────────────────────────────────────────
@router.post("/support/tickets/{ticket_id}/escalate")async def escalate_ticket_endpoint( request: Request, ticket_id: str, req: EscalateReq, user_data: Tuple[str, str, str] = Depends( require_role(["owner", "admin", "support"]) ),): await rate_limit(get_client_ip(request), user_data[1], request=request) caller_id, org_id, role = user_data
ticket = await _fetch_accessible_ticket(ticket_id, org_id, caller_id, role)
method = (req.method or "email").lower() if method not in ("email", "whatsapp"): raise HTTPException( status_code=400, detail="method must be 'email' or 'whatsapp'", )
# Look up the recipient from the org's own config. Branch-specific # entries win over org-level entries, which is what makes this # multi-branch: a ticket raised at Branch A notifies Branch A's # Billing contact if one is configured, otherwise falls back to # Org-wide Billing. No environment variables involved. config = await _read_escalation_config(org_id) target = _resolve_escalation_target( config, req.department, method, ticket.get("branch_id") ) if not target: dept_key = _dept_key(req.department) raise HTTPException( status_code=422, detail=( f"No {method} escalation target is configured for " f"'{req.department}'" + (f" at this branch" if ticket.get("branch_id") else "") + f". Configure it via PUT /support/escalation-config " f"under departments.{dept_key}.{method}." ), )
short_id = str(ticket.get("id", ticket_id))[:8] subject_line = f"[ESCALATION] Ticket #{short_id} – {ticket.get('subject', '')}"
plain_body = ( f"Ticket #{short_id} has been escalated.\n\n" f"Department: {req.department}\n" f"Priority: {ticket.get('priority', 'normal')}\n" f"Status: {ticket.get('status', 'open')}\n" f"Subject: {ticket.get('subject', '')}\n\n" f"Agent note:\n{req.note or '(no note provided)'}\n\n" f"— Kevs bOS Support" )
html_body = ( f"<h2>Ticket #{short_id} — Escalated</h2>" f"<table cellpadding='4'>" f"<tr><td><strong>Department</strong></td><td>{req.department}</td></tr>" f"<tr><td><strong>Priority</strong></td><td>{ticket.get('priority', 'normal')}</td></tr>" f"<tr><td><strong>Status</strong></td><td>{ticket.get('status', 'open')}</td></tr>" f"<tr><td><strong>Subject</strong></td><td>{ticket.get('subject', '')}</td></tr>" f"</table>" f"<hr>" f"<p><strong>Agent note</strong></p>" f"<pre>{req.note or '(no note provided)'}</pre>" )
# Deliver. Both senders are provider-agnostic thin wrappers already # defined in main.py. If the org migrates Brevo → SES tomorrow, only # send_sendgrid_email's body changes. This module stays untouched. delivery_error: Optional[str] = None try: if method == "email": ok = await send_sendgrid_email(target, subject_line, html_body) if not ok: delivery_error = "email provider reported a failure" else: await send_whatsapp_message_with_retry(target, plain_body) except Exception as e: delivery_error = str(e)
# Log on the ticket regardless of delivery outcome, so the ticket # history always reflects that an escalation was attempted. log_line = ( f"Escalated to {req.department} via {method} ({target})" + (f" — delivery FAILED: {delivery_error}" if delivery_error else " — delivered.") + (f" Note: {req.note}" if req.note else "") ) client = get_supabase() await run_sync_db_call( client.table("ticket_messages").insert({ "ticket_id": ticket_id, "sender_type": "system", "sender_id": caller_id, "message": log_line, "created_at": datetime.now(timezone.utc).isoformat(), }).execute )
# Move to the Escalated queue even on delivery failure — the ticket # state changed (an agent tried to escalate it), and hiding that # would leave the ticket looking untouched. await run_sync_db_call( client.table("support_tickets") .update({"status": "pending"}) .eq("id", ticket_id) .eq("org_id", org_id) .execute )
if delivery_error: raise HTTPException( status_code=502, detail=( f"Escalation recorded on the ticket but delivery via " f"{method} failed: {delivery_error}. The ticket has been " f"moved to the Escalated queue." ), )
return { "message": f"Ticket escalated to {req.department} via {method}", "ticket_id": ticket_id, "target": target, }1234567891011121314151617181920/** @type {import('tailwindcss').Config} */module.exports = { content: [ "./**/*.html", "./**/*.js", "!./node_modules/**", "!.git/**", ], theme: { extend: { colors: { brand: { DEFAULT: 'var(--brand-primary, #3b82f6)', accent: 'var(--brand-accent, #f59e0b)', }, }, }, }, plugins: [],};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289# tracking.pyimport osimport jsonimport asynciofrom datetime import datetime, timezone
import boto3import httpxfrom botocore.auth import SigV4Authfrom botocore.awsrequest import AWSRequestfrom fastapi import APIRouter, Depends, HTTPException, Request
from deps import ( logger, get_supabase, run_sync_db_call, fetch_one, require_role, rate_limit, get_client_ip,)
router = APIRouter(prefix="/delivery/track", tags=["Live Tracking"])
AWS_REGION = os.environ.get("AWS_REGION", "eu-west-1")AWS_TRACKER_NAME = os.environ.get("AWS_TRACKER_NAME")AWS_GEOFENCE_COLLECTION_NAME = os.environ.get("AWS_GEOFENCE_COLLECTION_NAME")AWS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")AWS_SECRET = os.environ.get("AWS_SECRET_ACCESS_KEY")GEOFENCE_WEBHOOK_SECRET = os.environ.get("GEOFENCE_WEBHOOK_SECRET")
# Dispatch state machine — driver role is constrained to these# transitions. owner / admin / logistics retain override authority# (they still hit the status whitelist in advance_status).VALID_DRIVER_TRANSITIONS = { "confirmed": ["picked", "cancelled"], "dispatched": ["picked", "cancelled"], "picked": ["in_transit", "cancelled"], "in_transit": ["delivered", "failed"],}
async def fire_aws_geofence_event(driver_id: str, lat: float, lng: float, accuracy: float, timestamp: str): """Push a driver position to AWS Tracker so geofences evaluate instantly.""" if not AWS_TRACKER_NAME: return url = f"https://tracking.geo.{AWS_REGION}.amazonaws.com/tracking/v0/trackers/{AWS_TRACKER_NAME}/positions" payload = { "Updates": [{ "DeviceId": driver_id, "Position": [lng, lat], "SampleTime": timestamp, "Accuracy": {"Horizontal": accuracy} if accuracy else {}, }] } try: req = AWSRequest( method="POST", url=url, data=json.dumps(payload), headers={"Content-Type": "application/json"}, ) SigV4Auth(boto3.Session().get_credentials(), "geo", AWS_REGION).add_auth(req) async with httpx.AsyncClient(timeout=10.0) as client: await client.post(url, data=req.body, headers=dict(req.headers)) except Exception as e: logger.error(f"AWS Tracker sync failed for {driver_id}: {e}")
@router.post("/location")async def push_location( payload: dict, user_data = Depends(require_role(["driver", "logistics"])),): user_id, org_id, role = user_data client = get_supabase()
try: lat = float(payload["lat"]) lng = float(payload["lng"]) except (KeyError, TypeError, ValueError): raise HTTPException(400, "lat and lng are required numeric fields")
acc = payload.get("accuracy") bat = payload.get("battery") chg = payload.get("is_charging") now = datetime.now(timezone.utc).isoformat() driver_id = user_id
await run_sync_db_call( client.table("driver_locations").upsert({ "org_id": org_id, "driver_id": driver_id, "lat": lat, "lng": lng, "accuracy": acc, "battery": bat, "is_charging": chg, "updated_at": now, }, on_conflict="org_id,driver_id").execute )
asyncio.create_task(fire_aws_geofence_event(driver_id, lat, lng, acc, now))
return {"status": "ok"}
@router.get("/public/{tracking_code}")async def public_track(tracking_code: str, request: Request): await rate_limit(get_client_ip(request), request=request) client = get_supabase()
# driver_locations has no FK path from sales, so we do it in two # queries rather than rely on PostgREST embed inference. sale_res = await run_sync_db_call( client.table("sales").select( "id, status, shipping_address, created_at, assigned_driver_id, " "profiles!assigned_driver_id(first_name, last_name, phone)" ).eq("receipt_number", tracking_code).maybe_single().execute ) if not sale_res or not sale_res.data: raise HTTPException(404, "Order not found")
order = sale_res.data driver = order.get("profiles") or {} driver_loc = None
if order.get("assigned_driver_id"): loc_res = await run_sync_db_call( client.table("driver_locations") .select("lat, lng, updated_at") .eq("driver_id", order["assigned_driver_id"]) .maybe_single() .execute ) if loc_res and loc_res.data: driver_loc = loc_res.data
driver_name = None if driver: first = driver.get("first_name") or "" last = driver.get("last_name") or "" driver_name = f"{first} {last}".strip() or None
return { "tracking_code": tracking_code, "status": order["status"], "delivery_address": order.get("shipping_address"), "created_at": order.get("created_at"), "driver": {"name": driver_name, "phone": driver.get("phone")} if driver else None, "position": driver_loc, }
@router.patch("/status/{sale_id}")async def advance_status( request: Request, sale_id: str, payload: dict, user_data = Depends(require_role(["driver", "owner", "admin", "logistics"])),): # Local import — tracking.py is imported at the top of main.py, so # main is only partially loaded at module-import time. # resolve_request_branch is defined later in main.py, so we defer # the import to request time when main is fully loaded. from main import resolve_request_branch # noqa: E402
user_id, org_id, role = user_data next_status = payload.get("status")
if next_status not in ["picked", "in_transit", "delivered", "cancelled", "failed"]: raise HTTPException(400, "Invalid status")
# Branch scope for non-driver roles only. Drivers are already # gated by assigned_driver_id — that's stricter than branch, and a # driver may legitimately be assigned to a branch's order without # being a member of that branch. selected_branch = None if role in ("owner", "admin", "logistics"): selected_branch = await resolve_request_branch(request, user_id, org_id, role)
client = get_supabase()
q = ( client.table("sales") .select("status, assigned_driver_id") .eq("id", sale_id) .eq("org_id", org_id) ) if selected_branch: q = q.eq("branch_id", selected_branch)
sale = await fetch_one(q.maybe_single()) if not sale: # 404, not 403 — a wrong-branch sale and a nonexistent sale # are indistinguishable to the caller. No cross-tenant info leak. raise HTTPException(404, "Sale not found")
if role == "driver" and sale["assigned_driver_id"] != user_id: raise HTTPException(403, "Not your order")
current = sale["status"] if role == "driver": allowed = VALID_DRIVER_TRANSITIONS.get(current, []) if next_status not in allowed: raise HTTPException(400, f"Invalid transition from {current} to {next_status}")
now = datetime.now(timezone.utc).isoformat() upd = {"status": next_status, "updated_at": now} if next_status == "picked": upd["picked_at"] = now if next_status == "in_transit": upd["dispatched_at"] = now if next_status == "delivered": upd["delivered_at"] = now
await run_sync_db_call( client.table("sales").update(upd).eq("id", sale_id).execute )
await run_sync_db_call( client.table("sale_events").insert({ "org_id": org_id, "sale_id": sale_id, "from_status": current, "to_status": next_status, "changed_by": user_id, }).execute )
return {"status": next_status}
@router.post("/webhook/aws")async def aws_geofence_webhook(request: Request): if not GEOFENCE_WEBHOOK_SECRET: logger.error("aws_geofence_webhook: GEOFENCE_WEBHOOK_SECRET not set — refusing all calls") raise HTTPException(503, "Geofence webhook not configured") if request.headers.get("x-webhook-secret") != GEOFENCE_WEBHOOK_SECRET: raise HTTPException(401, "Unauthorized")
event = await request.json() detail = event.get("detail", {})
aws_geofence_id = detail.get("GeofenceId") driver_id = detail.get("DeviceId") event_type_raw = detail.get("EventType", "") position = detail.get("Position")
if not aws_geofence_id or not driver_id or not event_type_raw or not position: raise HTTPException(400, "Missing fields")
event_type = event_type_raw.lower() if event_type not in ("enter", "exit"): return {"status": "ignored", "reason": f"unknown event type: {event_type_raw}"}
try: lng, lat = position except (TypeError, ValueError): raise HTTPException(400, "Invalid position payload")
client = get_supabase()
fence = await fetch_one( client.table("geofences") .select("id, org_id") .eq("aws_geofence_id", aws_geofence_id) .maybe_single() ) if not fence: return {"status": "ignored", "reason": "unknown geofence"}
try: await run_sync_db_call( client.table("geofence_events").insert({ "org_id": fence["org_id"], "geofence_id": fence["id"], "driver_id": driver_id, "event_type": event_type, "lat": lat, "lng": lng, "aws_event_id": detail.get("EventId"), "occurred_at": detail.get("SampleTime") or datetime.now(timezone.utc).isoformat(), }).execute ) except Exception as e: if "23505" in str(e) or "duplicate" in str(e).lower(): return {"status": "duplicate"} logger.error(f"AWS geofence webhook insert failed: {e}") raise HTTPException(500, "Insert failed")
return {"status": "ok"}.gitattributesAdded+4
DockerfileAdded+28
README.mdAdded+34
customers.pyAdded+226
delivery_zones.pyAdded+133
deps.pyAdded+1280
exec_profitability.pyAdded+223
expenses.pyAdded+381
geo.pyAdded+227
hr.pyAdded+847
inventory.pyAdded+723
main.pyAdded
migrations_geo.pyAdded+294
netlify.tomlAdded+133
pos_transfers.pyAdded+706
procurement.pyAdded+193
requirements.txtAdded+14
support_chat.pyAdded+204
support_tickets.pyAdded+696
tailwind.config.jsAdded+20
tracking.pyAdded+289