"""Account-scoped HyperFlow operations and explicitly labelled planning models. These are HyperFlow-owned jobs, not access to a provider's inventory or fleet. Distances and ETAs are scenario estimates; no accuracy claim is made. """ from __future__ import annotations from copy import deepcopy from datetime import datetime, timezone from decimal import Decimal, ROUND_HALF_UP import hashlib import math from typing import Any ACTIVE = {"ASSIGNED", "PICKED_UP", "IN_TRANSIT"} TRANSITIONS = { "CREATED": {"CANCELLED"}, "ASSIGNED": {"PICKED_UP", "CANCELLED"}, "PICKED_UP": {"IN_TRANSIT"}, "IN_TRANSIT": {"DELIVERED"}, "DELIVERED": set(), "CANCELLED": set(), } def now() -> str: return datetime.now(timezone.utc).isoformat() def number(value: Any, field: str, minimum: float = 0, maximum: float | None = 1e12) -> float: if isinstance(value, bool): raise ValueError(f"{field} must be a finite number") try: result = float(value) except (ValueError, TypeError, OverflowError): raise ValueError(f"{field} must be a finite number") from None if not math.isfinite(result) or result < minimum or (maximum is not None and result > maximum): raise ValueError(f"{field} is outside its allowed range") return result def integer(value: Any, field: str, minimum: int = 0) -> int: result = number(value, field, minimum) if result != int(result): raise ValueError(f"{field} must be an integer") return int(result) def text(value: Any, field: str, limit: int = 1000) -> str: if not isinstance(value, str) or not value.strip() or len(value) > limit: raise ValueError(f"{field} must be non-empty text of at most {limit} characters") return value.strip() def coordinates(value: Any, field: str) -> dict: if not isinstance(value, dict): raise ValueError(f"{field} requires latitude and longitude") return { "latitude": number(value.get("latitude"), f"{field}.latitude", -90, 90), "longitude": number(value.get("longitude"), f"{field}.longitude", -180, 180), } def source(payload: dict) -> str: value = payload.get("source", "user_input") if not isinstance(value, str) or value not in {"user_input", "simulation"}: raise ValueError("Operations inputs require user_input or simulation provenance") return value def stamp(value: Any) -> datetime: try: result = datetime.fromisoformat(value.replace("Z", "+00:00")) if result.tzinfo is None: raise ValueError() return result.astimezone(timezone.utc) except (AttributeError, ValueError, TypeError): raise ValueError("captured_at must be an ISO timestamp with timezone") from None def require(account: dict, roles: set[str]) -> None: if not account.get("id") or account.get("role") not in roles: raise PermissionError("This role cannot perform this operation") def index_id(kind: str, *values: str) -> str: # Record IDs are globally unique in Store, including cross-account indexes. value = "\x00".join([kind, *values]) return hashlib.sha256(value.encode()).hexdigest() def distance_km(a: dict, b: dict) -> float: lat1, lat2 = math.radians(a["latitude"]), math.radians(b["latitude"]) dlat = lat2 - lat1 dlon = math.radians(b["longitude"] - a["longitude"]) half = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 return 6371.0088 * 2 * math.asin(math.sqrt(min(1, max(0, half)))) def dispatch_plan(jobs: list[dict], couriers: list[dict], strategy: str = "cost") -> dict: """Maximize assigned jobs, then minimize independent-trip distance under load limits. Capacity is a declared workload budget for this snapshot. This is not a multi-stop vehicle-routing or traffic model, and does not reserve capacity. """ if not isinstance(strategy, str) or strategy not in {"nearest_first", "cost"}: raise ValueError("strategy must be nearest_first or cost") if not isinstance(jobs, list) or not isinstance(couriers, list): raise ValueError("jobs and couriers must be lists") if len(jobs) > 200 or len(couriers) > 50: raise ValueError("A dispatch proposal supports at most 200 jobs and 50 couriers") parsed_jobs, parsed_couriers = [], [] for job in jobs: if not isinstance(job, dict): raise ValueError("Each job must be an object") parsed_jobs.append({ "id": text(job.get("id"), "job.id", 200), "pickup": coordinates(job.get("pickup"), "pickup"), "dropoff": coordinates(job.get("dropoff"), "dropoff"), "load_units": integer(job.get("load_units"), "load_units", 1), }) for courier in couriers: if not isinstance(courier, dict): raise ValueError("Each courier must be an object") parsed_couriers.append({ "id": text(courier.get("id"), "courier.id", 200), "position": coordinates(courier.get("position"), "position"), "capacity_units": integer(courier.get("capacity_units"), "capacity_units"), "speed_kmh": number(courier.get("speed_kmh"), "speed_kmh", 1, 150), "handling_minutes": number(courier.get("handling_minutes", 0), "handling_minutes", 0, 240), }) if len({j["id"] for j in parsed_jobs}) != len(parsed_jobs) or len({c["id"] for c in parsed_couriers}) != len(parsed_couriers): raise ValueError("Job and courier identifiers must be unique") nj, nc = len(parsed_jobs), len(parsed_couriers) distances = [[distance_km(c["position"], j["pickup"]) + distance_km(j["pickup"], j["dropoff"]) for c in parsed_couriers] for j in parsed_jobs] pairs: list[tuple[int, int]] = [] if nj and nc and strategy == "nearest_first": remaining = [c["capacity_units"] for c in parsed_couriers] for ji, job in enumerate(parsed_jobs): eligible = [ci for ci in range(nc) if remaining[ci] >= job["load_units"]] if eligible: ci = min(eligible, key=lambda i: (distances[ji][i], parsed_couriers[i]["id"])) pairs.append((ji, ci)) remaining[ci] -= job["load_units"] elif nj and nc: import numpy as np from scipy.optimize import Bounds, LinearConstraint, milp size = nj * nc matrix = np.zeros((nj + nc, size)) for ji, job in enumerate(parsed_jobs): matrix[ji, ji * nc:(ji + 1) * nc] = 1 for ci in range(nc): matrix[nj + ci, ji * nc + ci] = job["load_units"] upper = np.array([1] * nj + [c["capacity_units"] for c in parsed_couriers], dtype=float) constraints = [LinearConstraint(matrix, np.zeros(nj + nc), upper)] common = {"integrality": np.ones(size), "bounds": Bounds(np.zeros(size), np.ones(size)), "options": {"time_limit": 10, "mip_rel_gap": 0}} maximum = milp(-np.ones(size), constraints=constraints, **common) if not maximum.success or maximum.x is None: raise RuntimeError("Dispatch solver did not establish an optimum") assigned_count = int(round(float(np.sum(maximum.x)))) constraints.append(LinearConstraint(np.ones((1, size)), [assigned_count], [assigned_count])) minimum = milp(np.asarray(distances).ravel(), constraints=constraints, **common) if not minimum.success or minimum.x is None: raise RuntimeError("Dispatch cost solver did not establish an optimum") pairs = [(ji, ci) for ji in range(nj) for ci in range(nc) if minimum.x[ji * nc + ci] > .5] assignments = [] for ji, ci in pairs: courier, job = parsed_couriers[ci], parsed_jobs[ji] km = distances[ji][ci] assignments.append({"job_id": job["id"], "courier_id": courier["id"], "load_units": job["load_units"], "distance_km": round(km, 6), "estimated_minutes": round(km / courier["speed_kmh"] * 60 + courier["handling_minutes"], 3)}) assigned_ids = {a["job_id"] for a in assignments} return {"strategy": strategy, "assignments": assignments, "unassigned_job_ids": [j["id"] for j in parsed_jobs if j["id"] not in assigned_ids], "assigned_count": len(assignments), "total_distance_km": round(sum(distances[j][c] for j, c in pairs), 6), "model": "independent_straight_line_trips", "capacity_reserved": False, "eta_accuracy": None, "assumptions": ["Declared speed and workload capacity", "No traffic or multi-stop route sequencing"]} class Operations: def __init__(self, store): self.store = store def _all_deliveries(self, owner_id: str) -> list: rows = (self.store.scan("delivery", owner_id) if hasattr(self.store, "scan") else self.store.list("delivery", owner_id, limit=501)) if not hasattr(self.store, "scan") and len(rows) >= 500: raise ValueError("Cannot verify capacity: delivery history exceeds the listing limit") return rows def enroll_courier(self, account: dict, payload: dict) -> dict: """A courier explicitly authorizes one operator workspace to assign jobs.""" require(account, {"courier"}) owner_id = text(payload.get("owner_account_id"), "owner_account_id", 200) owner = self.store.account(owner_id) if not owner or owner.get("role") not in {"admin", "operator"}: raise ValueError("Enrollment requires a provisioned operator account") with self.store.atomic(account["id"]): try: enrollment = self.store.get("courier_enrollment", index_id("enrollment", account["id"]), account["id"]) if enrollment["data"]["owner_account_id"] != owner_id: raise ValueError("Courier is already enrolled in another workspace") except LookupError: enrollment = self.store.create("courier_enrollment", account["id"], {"owner_account_id": owner_id, "source": "user_input", "enrolled_at": now()}, record_id=index_id("enrollment", account["id"])) # This index is not authority: every assignment rechecks enrollment. try: self.store.get("courier_membership", index_id("membership", owner_id, account["id"]), owner_id) except LookupError: self.store.create("courier_membership", owner_id, {"courier_account_id": account["id"]}, record_id=index_id("membership", owner_id, account["id"])) return enrollment def couriers(self, account: dict) -> list: require(account, {"admin", "operator"}) members = [] for row in self.store.list("courier_membership", account["id"]): courier_id = row["data"]["courier_account_id"] try: enrollment = self.store.get("courier_enrollment", index_id("enrollment", courier_id), courier_id) except LookupError: continue identity = self.store.account(courier_id) if identity and identity.get("role") == "courier" and enrollment["data"]["owner_account_id"] == account["id"]: members.append({"courier_account_id": courier_id, "enrolled_at": enrollment["data"]["enrolled_at"], "source": "user_input"}) return members def _delivery(self, account: dict, delivery_id: str) -> dict: require(account, {"admin", "operator", "courier"}) owner_id = account["id"] if account["role"] == "courier": access = self.store.get("delivery_assignment", index_id("assignment", delivery_id, account["id"]), account["id"]) owner_id = access["data"]["owner_account_id"] record = self.store.get("delivery", delivery_id, owner_id) if account["role"] == "courier" and record["data"].get("courier_account_id") != account["id"]: raise PermissionError("Courier is not assigned to this job") return record def create_delivery(self, account: dict, payload: dict) -> dict: require(account, {"admin", "operator"}) data = {"label": text(payload.get("label"), "label", 200), "pickup": coordinates(payload.get("pickup"), "pickup"), "dropoff": coordinates(payload.get("dropoff"), "dropoff"), "load_units": integer(payload.get("load_units"), "load_units", 1), "source": source(payload), "owner": "hyperflow", "status": "CREATED", "courier_account_id": None, "history": [{"status": "CREATED", "at": now(), "actor_id": account["id"]}], "telemetry": None} return self.store.create("delivery", account["id"], data) def assign_delivery(self, account: dict, delivery_id: str, payload: dict) -> dict: require(account, {"admin", "operator"}) with self.store.atomic(account["id"]): return self._assign_delivery(account, delivery_id, payload) def _assign_delivery(self, account: dict, delivery_id: str, payload: dict) -> dict: record = self._delivery(account, delivery_id) if record["data"]["status"] != "CREATED": raise ValueError("Only a created delivery can be assigned") courier_id = text(payload.get("courier_account_id"), "courier_account_id", 200) if courier_id == account["id"]: raise ValueError("Courier must use a distinct provisioned courier account") # Parent Store resolves provisioned accounts; never create courier identities # from a client-selected role or a supplied display name. resolver = getattr(self.store, "account", None) if resolver is None: raise ValueError("Assignment requires provisioned account lookup") courier = resolver(courier_id) if not courier or courier.get("role") != "courier": raise ValueError("Assignment requires a provisioned courier account") try: membership = self.store.get("courier_enrollment", index_id("enrollment", courier_id), courier_id) except LookupError: raise PermissionError("Courier must enroll in this workspace before assignment") from None if membership["data"].get("owner_account_id") != account["id"]: raise PermissionError("Courier is enrolled in another workspace") capacity = integer(payload.get("capacity_units"), "capacity_units", 1) speed = number(payload.get("speed_kmh"), "speed_kmh", 1, 150) active_jobs = [r for r in self._all_deliveries(account["id"]) if r["data"].get("courier_account_id") == courier_id and r["data"]["status"] in ACTIVE] if any(r["data"].get("capacity_units") != capacity for r in active_jobs): raise ValueError("Capacity cannot change while this courier has active deliveries") if sum(r["data"]["load_units"] for r in active_jobs) + record["data"]["load_units"] > capacity: raise ValueError("Assignment exceeds declared courier workload capacity") data = deepcopy(record["data"]) data.update(courier_account_id=courier_id, status="ASSIGNED", capacity_units=capacity, speed_kmh=speed) data["history"].append({"status": "ASSIGNED", "at": now(), "actor_id": account["id"]}) # A link grants no access until the authoritative job assignment matches. # Creating it first fails closed if the job update fails or loses a race. try: access = self.store.get("delivery_assignment", index_id("assignment", delivery_id, courier_id), courier_id) if access["data"].get("owner_account_id") != account["id"]: raise PermissionError("Delivery assignment owner mismatch") except LookupError: self.store.create("delivery_assignment", courier_id, {"owner_account_id": account["id"], "delivery_id": delivery_id}, record_id=index_id("assignment", delivery_id, courier_id)) return self.store.update("delivery", delivery_id, account["id"], data, expected_version=payload.get("expected_version", record["version"]), event_type="delivery.assigned") def telemetry(self, account: dict, delivery_id: str, payload: dict) -> dict: require(account, {"courier"}) owner_id = self._delivery(account, delivery_id)["account_id"] with self.store.atomic(owner_id): return self._telemetry(account, delivery_id, payload) def _telemetry(self, account: dict, delivery_id: str, payload: dict) -> dict: record = self._delivery(account, delivery_id) if record["data"]["status"] not in ACTIVE: raise ValueError("GPS is accepted only for an active assigned delivery") if payload.get("location_consent") is not True: raise ValueError("Location permission and consent are required") captured = stamp(payload.get("captured_at")) age = (datetime.now(timezone.utc) - captured).total_seconds() if age < -30 or age > 300: raise ValueError("GPS observation must be from the last five minutes") data = deepcopy(record["data"]) previous = data.get("telemetry") if previous and captured <= stamp(previous["captured_at"]): raise ValueError("GPS observation must be newer than stored observation") data["telemetry"] = {**coordinates(payload.get("position"), "position"), "captured_at": captured.isoformat(), "accuracy_meters": number(payload.get("accuracy_meters"), "accuracy_meters", 0, 10000), "source": "user_input", "location_consent": True} if data.get("speed_kmh"): km = distance_km(data["telemetry"], data["dropoff"]) data["eta"] = {"estimated_minutes": round(km / data["speed_kmh"] * 60, 3), "model": "straight_line_declared_speed", "captured_at": captured.isoformat(), "accuracy": None} return self.store.update("delivery", delivery_id, record["account_id"], data, expected_version=record["version"], event_type="delivery.telemetry") def transition(self, account: dict, delivery_id: str, payload: dict) -> dict: owner_id = self._delivery(account, delivery_id)["account_id"] with self.store.atomic(owner_id): return self._transition(account, delivery_id, payload) def _transition(self, account: dict, delivery_id: str, payload: dict) -> dict: record = self._delivery(account, delivery_id) target = payload.get("status") current = record["data"]["status"] if not isinstance(target, str) or target not in TRANSITIONS[current]: raise ValueError(f"Cannot transition delivery from {current} to {target}") if account["role"] == "courier" and target == "CANCELLED": raise PermissionError("Only an operator may cancel a delivery") data = deepcopy(record["data"]) data["status"] = target data["history"].append({"status": target, "at": now(), "actor_id": account["id"]}) if target in {"DELIVERED", "CANCELLED"}: data["telemetry"] = None data.pop("eta", None) return self.store.update("delivery", delivery_id, record["account_id"], data, expected_version=payload.get("expected_version", record["version"]), event_type="delivery.status_changed") def deliveries(self, account: dict) -> list: require(account, {"admin", "operator", "courier"}) if account["role"] == "courier": rows = [] for link in self.store.list("delivery_assignment", account["id"]): try: rows.append(self._delivery(account, link["data"]["delivery_id"])) except (LookupError, PermissionError): continue return rows return self.store.list("delivery", account["id"]) def dispatch(self, account: dict, payload: dict) -> dict: require(account, {"admin", "operator"}) with self.store.atomic(account["id"]): return self._dispatch(account, payload) def _dispatch(self, account: dict, payload: dict) -> dict: ids = payload.get("delivery_ids", []) if not isinstance(ids, list) or not ids: raise ValueError("delivery_ids must be a non-empty list") jobs, versions = [], {} for delivery_id in ids: row = self._delivery(account, delivery_id) if row["data"]["status"] != "CREATED": raise ValueError("Dispatch proposals accept only unassigned deliveries") jobs.append({"id": row["id"], **row["data"]}) versions[row["id"]] = row["version"] couriers = payload.get("couriers", []) if not isinstance(couriers, list): raise ValueError("couriers must be a list") member_ids = {c["courier_account_id"] for c in self.couriers(account)} if any(not isinstance(c, dict) or c.get("id") not in member_ids for c in couriers): raise PermissionError("Dispatch proposals require enrolled courier accounts") active = [r for r in self._all_deliveries(account["id"]) if r["data"]["status"] in ACTIVE] available, capacity_snapshot = [], [] for courier in couriers: capacity = integer(courier.get("capacity_units"), "capacity_units") existing = [r["data"] for r in active if r["data"].get("courier_account_id") == courier["id"]] if any(r.get("capacity_units") != capacity for r in existing): raise ValueError("Capacity cannot change while this courier has active deliveries") used = sum(r["load_units"] for r in existing) if used > capacity: raise ValueError("Declared capacity is below the active workload") available.append({**courier, "capacity_units": capacity - used}) capacity_snapshot.append({"courier_id": courier["id"], "total_units": capacity, "active_units": used, "available_units": capacity - used}) result = dispatch_plan(jobs, available, payload.get("strategy", "cost")) result.update(source="simulation", captured_at=now(), job_versions=versions, capacity_snapshot=capacity_snapshot) return self.store.create("dispatch_proposal", account["id"], result) def create_review(self, account: dict, payload: dict) -> dict: require(account, {"admin", "operator"}) observations = payload.get("observations", {}) if not isinstance(observations, dict): raise ValueError("observations must be an object") if "duplicate_receipt" in observations and not isinstance(observations["duplicate_receipt"], bool): raise ValueError("duplicate_receipt must be a boolean") evidence = [] # These are explicit rules over caller-supplied evidence, not fraud probabilities. if "refund_requests_30d" in observations: count = integer(observations["refund_requests_30d"], "refund_requests_30d") if count >= 3: evidence.append({"rule": "repeat_refund_requests", "observed": count, "threshold": 3}) if "refund_minor" in observations: refund = integer(observations["refund_minor"], "refund_minor") order = integer(observations.get("order_total_minor"), "order_total_minor", 1) if refund > order: evidence.append({"rule": "refund_exceeds_order", "observed": refund, "threshold": order}) if observations.get("duplicate_receipt") is True: evidence.append({"rule": "duplicate_receipt", "observed": True, "threshold": True}) data = {"subject_ref": text(payload.get("subject_ref"), "subject_ref", 200), "source": source(payload), "rules_version": "review_rules_v1", "evidence": evidence, "status": "OPEN", "priority": "REVIEW" if evidence else "NO_RULE_MATCH", "fraud_probability": None, "history": [{"action": "CREATED", "actor_id": account["id"], "at": now()}]} return self.store.create("review", account["id"], data) def decide_review(self, account: dict, review_id: str, payload: dict) -> dict: require(account, {"admin", "operator"}) row = self.store.get("review", review_id, account["id"]) decision = payload.get("decision") if not isinstance(decision, str) or decision not in {"CONFIRMED_ISSUE", "CLEARED", "NEEDS_INFORMATION"}: raise ValueError("Unknown review decision") data = deepcopy(row["data"]) reason = text(payload.get("reason"), "reason", 2000) data.update(status=decision) data["history"].append({"action": decision, "reason": reason, "actor_id": account["id"], "at": now()}) return self.store.update("review", review_id, account["id"], data, expected_version=payload.get("expected_version", row["version"]), event_type="review.decided") def reviews(self, account: dict) -> list: require(account, {"admin", "operator", "reviewer"}) return self.store.list("review", account["id"]) def site_scenario(self, payload: dict) -> dict: """Monthly contribution sensitivity; inputs are explicit economic assumptions.""" currency = text(payload.get("currency"), "currency", 3).upper() if len(currency) != 3 or not currency.isalpha(): raise ValueError("currency must be a three-letter currency code") daily = number(payload.get("daily_orders"), "daily_orders") average = integer(payload.get("average_order_minor"), "average_order_minor") margin = number(payload.get("gross_margin_fraction"), "gross_margin_fraction", 0, 1) competition = number(payload.get("competition_loss_fraction"), "competition_loss_fraction", 0, 1) rent = integer(payload.get("monthly_rent_minor"), "monthly_rent_minor") fixed = integer(payload.get("monthly_other_fixed_minor"), "monthly_other_fixed_minor") variable = integer(payload.get("per_order_cost_minor"), "per_order_cost_minor") days = integer(payload.get("days_per_month", 30), "days_per_month", 1) if days > 31: raise ValueError("days_per_month cannot exceed 31") initial = integer(payload.get("setup_cost_minor"), "setup_cost_minor") # Sensitivities are named deterministic scenarios, never confidence intervals. adjustments = payload.get("sensitivity", [ {"name": "lower_demand", "demand_multiplier": .8, "rent_multiplier": 1}, {"name": "base", "demand_multiplier": 1, "rent_multiplier": 1}, {"name": "higher_demand", "demand_multiplier": 1.2, "rent_multiplier": 1}, ]) if not isinstance(adjustments, list) or not adjustments or len(adjustments) > 20: raise ValueError("sensitivity must contain 1 to 20 scenarios") scenarios = [] for item in adjustments: if not isinstance(item, dict): raise ValueError("Each sensitivity scenario must be an object") name = text(item.get("name"), "scenario.name", 100) demand_multiplier = number(item.get("demand_multiplier"), "demand_multiplier", 0, 10) rent_multiplier = number(item.get("rent_multiplier"), "rent_multiplier", 0, 10) monthly_orders = daily * days * (1 - competition) * demand_multiplier contribution = monthly_orders * (average * margin - variable) - rent * rent_multiplier - fixed contribution_minor = int(Decimal(str(contribution)).quantize(Decimal("1"), rounding=ROUND_HALF_UP)) scenarios.append({"name": name, "monthly_orders": round(monthly_orders, 3), "monthly_contribution_minor": contribution_minor, "setup_payback_months": round(initial / contribution, 2) if contribution > 0 else None, "demand_multiplier": demand_multiplier, "rent_multiplier": rent_multiplier}) return {"source": "simulation", "currency": currency, "inputs": deepcopy(payload), "scenarios": scenarios, "interpretation": "Deterministic sensitivity to user assumptions; not a forecast or confidence interval"} def replenish(self, payload: dict) -> dict: """Deterministic order-up-to recommendation with explicit inventory and cost inputs.""" stock = integer(payload.get("stock_units"), "stock_units") inbound = integer(payload.get("inbound_units"), "inbound_units") committed = integer(payload.get("committed_units"), "committed_units") demand = number(payload.get("daily_demand_units"), "daily_demand_units") lead = number(payload.get("lead_time_days"), "lead_time_days") review = number(payload.get("review_period_days"), "review_period_days") safety = integer(payload.get("safety_stock_units"), "safety_stock_units") unit_cost = integer(payload.get("unit_cost_minor"), "unit_cost_minor") order_cost = integer(payload.get("fixed_order_cost_minor"), "fixed_order_cost_minor") currency = text(payload.get("currency"), "currency", 3).upper() if len(currency) != 3 or not currency.isalpha(): raise ValueError("currency must be a three-letter currency code") target = math.ceil(Decimal(str(demand)) * (Decimal(str(lead)) + Decimal(str(review))) + safety) position = stock + inbound - committed quantity = max(0, target - position) return {"source": "simulation", "inputs": deepcopy(payload), "currency": currency, "inventory_position_units": position, "target_stock_units": target, "recommended_order_units": quantity, "estimated_cost_minor": quantity * unit_cost + (order_cost if quantity else 0), "method": "deterministic_order_up_to", "provider_inventory_verified": False}