Spaces:
Paused
Paused
Deploy Loopable
Browse files- core/odoo.py +136 -16
- odoo_client.py +9 -5
core/odoo.py
CHANGED
|
@@ -14,6 +14,7 @@ import sys
|
|
| 14 |
import queue as _queue
|
| 15 |
import threading
|
| 16 |
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
| 17 |
from functools import lru_cache
|
| 18 |
from pathlib import Path
|
| 19 |
|
|
@@ -24,7 +25,10 @@ if str(_ROOT) not in sys.path:
|
|
| 24 |
sys.path.insert(0, str(_ROOT))
|
| 25 |
from odoo_client import OdooClient # noqa: E402 (read-only, write-guarded)
|
| 26 |
|
| 27 |
-
# ---- business constants ----
|
|
|
|
|
|
|
|
|
|
| 28 |
TEAM_IDS = [5, 6]
|
| 29 |
TEAM_NAMES = {5: 'Fisch', 6: 'Royal'}
|
| 30 |
# Partners to exclude from analytics (not part of RI/FFS). Sourced from env so no
|
|
@@ -32,6 +36,8 @@ TEAM_NAMES = {5: 'Fisch', 6: 'Royal'}
|
|
| 32 |
EXCLUDE_PARTNER_NAMES = {n.strip() for n in os.environ.get('EXCLUDE_PARTNER_NAMES', '').split(',') if n.strip()}
|
| 33 |
|
| 34 |
# Confirmed sale.order.line scope for RI+FFS (the analytics "sales universe").
|
|
|
|
|
|
|
| 35 |
SALE_LINE_BASE = [
|
| 36 |
('state', 'in', ['sale', 'done']),
|
| 37 |
('order_id.team_id', 'in', TEAM_IDS),
|
|
@@ -46,10 +52,91 @@ INVOICE_BASE = [
|
|
| 46 |
|
| 47 |
@lru_cache(maxsize=1)
|
| 48 |
def _global_client():
|
| 49 |
-
"""
|
| 50 |
return OdooClient()
|
| 51 |
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
# ---- concurrent read pool -------------------------------------------------------------------
|
| 54 |
# Each Odoo XML-RPC call is a round-trip; a heavy drawer fires a dozen of them and they add up to
|
| 55 |
# many seconds when run one-by-one. `parallel()` runs independent READ tasks across a small pool of
|
|
@@ -79,10 +166,22 @@ def _checkin(c):
|
|
| 79 |
|
| 80 |
|
| 81 |
def get_odoo():
|
| 82 |
-
"""The active read-only client
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
def set_doc_mode(mode):
|
|
@@ -107,15 +206,19 @@ def parallel(tasks):
|
|
| 107 |
return [tasks[0]()]
|
| 108 |
|
| 109 |
caller_mode = doc_mode() # propagate the submitter's basis to each worker
|
|
|
|
|
|
|
| 110 |
def _run(fn):
|
| 111 |
c = _checkout()
|
| 112 |
_tlocal.client = c
|
| 113 |
_tlocal.doc_mode = caller_mode
|
|
|
|
| 114 |
try:
|
| 115 |
return fn()
|
| 116 |
finally:
|
| 117 |
_tlocal.client = None
|
| 118 |
_tlocal.doc_mode = 'order'
|
|
|
|
| 119 |
_checkin(c)
|
| 120 |
with ThreadPoolExecutor(max_workers=min(len(tasks), _POOL_MAX)) as ex:
|
| 121 |
return list(ex.map(_run, tasks))
|
|
@@ -135,16 +238,30 @@ def m2o_name(v):
|
|
| 135 |
return v[1] if isinstance(v, list) and len(v) > 1 else ''
|
| 136 |
|
| 137 |
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
| 139 |
def excluded_partner_ids():
|
| 140 |
-
"""Resolve the excluded partner names
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
|
| 150 |
def sale_line_domain(date_from=None, date_to=None, team_id=None, extra=None, partner_ids=None):
|
|
@@ -152,7 +269,10 @@ def sale_line_domain(date_from=None, date_to=None, team_id=None, extra=None, par
|
|
| 152 |
the configured house accounts, with optional date window / single team / extra clauses.
|
| 153 |
partner_ids (a collection, possibly empty) restricts to those customers β the carrier for
|
| 154 |
the Customer module's Agent filter; None = no partner restriction (an empty set matches none)."""
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
| 156 |
if team_id is not None:
|
| 157 |
dom = [d for d in dom if not (isinstance(d, tuple) and d[0] == 'order_id.team_id')]
|
| 158 |
dom.append(('order_id.team_id', '=', team_id))
|
|
|
|
| 14 |
import queue as _queue
|
| 15 |
import threading
|
| 16 |
from concurrent.futures import ThreadPoolExecutor
|
| 17 |
+
from contextlib import contextmanager
|
| 18 |
from functools import lru_cache
|
| 19 |
from pathlib import Path
|
| 20 |
|
|
|
|
| 25 |
sys.path.insert(0, str(_ROOT))
|
| 26 |
from odoo_client import OdooClient # noqa: E402 (read-only, write-guarded)
|
| 27 |
|
| 28 |
+
# ---- business constants (TENANT #0's scope, kept as module attributes for its modules) ----
|
| 29 |
+
# These are Royal Imports' config β the default a request gets when nothing binds a tenant.
|
| 30 |
+
# The canonical per-tenant home is `harness/tenants.py` Tenant.config; a BOUND tenant (see
|
| 31 |
+
# `tenant_scope` below) carries its own team ids / exclusions and never reads these.
|
| 32 |
TEAM_IDS = [5, 6]
|
| 33 |
TEAM_NAMES = {5: 'Fisch', 6: 'Royal'}
|
| 34 |
# Partners to exclude from analytics (not part of RI/FFS). Sourced from env so no
|
|
|
|
| 36 |
EXCLUDE_PARTNER_NAMES = {n.strip() for n in os.environ.get('EXCLUDE_PARTNER_NAMES', '').split(',') if n.strip()}
|
| 37 |
|
| 38 |
# Confirmed sale.order.line scope for RI+FFS (the analytics "sales universe").
|
| 39 |
+
# β Documentation of tenant #0's base scope β `sale_line_domain()` below BUILDS its domain from
|
| 40 |
+
# `active_team_ids()` (binding-aware) rather than reading this list; edit both or neither.
|
| 41 |
SALE_LINE_BASE = [
|
| 42 |
('state', 'in', ['sale', 'done']),
|
| 43 |
('order_id.team_id', 'in', TEAM_IDS),
|
|
|
|
| 52 |
|
| 53 |
@lru_cache(maxsize=1)
|
| 54 |
def _global_client():
|
| 55 |
+
"""TENANT #0's read-only client (env/.env credentials) β the default for every unbound call."""
|
| 56 |
return OdooClient()
|
| 57 |
|
| 58 |
|
| 59 |
+
# ---- per-tenant connections (R3 keychain cutover, 2026-08-04) --------------------------------
|
| 60 |
+
# One client per tenant slug, keyed by a fingerprint of its credentials so a rotated key
|
| 61 |
+
# reconnects on the next call with no restart. The DEFAULT slug maps to the env client above.
|
| 62 |
+
# β FAIL-CLOSED: a bound NON-default tenant with no credentials raises β the env fallback
|
| 63 |
+
# would silently answer tenant B's question over tenant A's connection, which is the exact
|
| 64 |
+
# failure this section exists to remove.
|
| 65 |
+
_DEFAULT_SLUG = 'royal-imports'
|
| 66 |
+
_TENANT_CLIENTS = {} # slug -> (creds fingerprint, OdooClient)
|
| 67 |
+
_TC_LOCK = threading.Lock()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class TenantOdooUnavailable(RuntimeError):
|
| 71 |
+
"""A bound tenant has no Odoo credentials. Callers surface 'connect a source', never
|
| 72 |
+
another tenant's data."""
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _client_for(slug, creds):
|
| 76 |
+
"""The client for a BOUND tenant. creds None: default slug -> env client; anyone else -> raise."""
|
| 77 |
+
slug = str(slug or _DEFAULT_SLUG)
|
| 78 |
+
if not creds:
|
| 79 |
+
if slug == _DEFAULT_SLUG:
|
| 80 |
+
return _global_client()
|
| 81 |
+
raise TenantOdooUnavailable(
|
| 82 |
+
f"tenant {slug!r} has no Odoo credentials β store them under Settings β Keychains. "
|
| 83 |
+
f"(Refusing the environment fallback: that is another tenant's connection.)")
|
| 84 |
+
fp = (str(creds.get('url') or ''), str(creds.get('db') or ''),
|
| 85 |
+
str(creds.get('user') or ''), str(creds.get('api_key') or ''))
|
| 86 |
+
with _TC_LOCK:
|
| 87 |
+
cur = _TENANT_CLIENTS.get(slug)
|
| 88 |
+
if cur and cur[0] == fp:
|
| 89 |
+
return cur[1]
|
| 90 |
+
cli = OdooClient(creds=creds) # built OUTSIDE the lock: it authenticates over the wire
|
| 91 |
+
with _TC_LOCK:
|
| 92 |
+
cur = _TENANT_CLIENTS.get(slug)
|
| 93 |
+
if cur and cur[0] == fp:
|
| 94 |
+
return cur[1] # another thread won the race β keep ONE client
|
| 95 |
+
_TENANT_CLIENTS[slug] = (fp, cli)
|
| 96 |
+
return cli
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@contextmanager
|
| 100 |
+
def tenant_scope(slug, creds=None, team_ids=None, team_names=None, exclude_partner_names=None):
|
| 101 |
+
"""Bind THIS THREAD's Odoo context to a tenant: its connection + its scope constants.
|
| 102 |
+
|
| 103 |
+
Unbound (the default) = tenant #0 via env, which is every existing Streamlit/API caller.
|
| 104 |
+
The connector layer (harness/connectors/odoo.py) wraps each query in this, so a second
|
| 105 |
+
tenant's keychain credentials reach the wire without any module knowing. Scope constants
|
| 106 |
+
are PUSHED here from Tenant.config because core/ may not import harness/ (layering)."""
|
| 107 |
+
prev = getattr(_tlocal, 'tenant_ctx', None)
|
| 108 |
+
_tlocal.tenant_ctx = {
|
| 109 |
+
'slug': str(slug or _DEFAULT_SLUG),
|
| 110 |
+
'creds': creds,
|
| 111 |
+
'team_ids': list(team_ids) if team_ids else None,
|
| 112 |
+
'team_names': dict(team_names) if team_names else None,
|
| 113 |
+
'exclude_partner_names': set(exclude_partner_names) if exclude_partner_names else None,
|
| 114 |
+
}
|
| 115 |
+
try:
|
| 116 |
+
yield
|
| 117 |
+
finally:
|
| 118 |
+
_tlocal.tenant_ctx = prev
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _ctx():
|
| 122 |
+
return getattr(_tlocal, 'tenant_ctx', None)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def active_team_ids():
|
| 126 |
+
"""The bound tenant's team ids; unbound or default slug -> tenant #0's TEAM_IDS."""
|
| 127 |
+
c = _ctx()
|
| 128 |
+
if c is not None and c['slug'] != _DEFAULT_SLUG:
|
| 129 |
+
return list(c['team_ids'] or [])
|
| 130 |
+
return list(TEAM_IDS)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def active_team_names():
|
| 134 |
+
c = _ctx()
|
| 135 |
+
if c is not None and c['slug'] != _DEFAULT_SLUG:
|
| 136 |
+
return dict(c['team_names'] or {})
|
| 137 |
+
return dict(TEAM_NAMES)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
# ---- concurrent read pool -------------------------------------------------------------------
|
| 141 |
# Each Odoo XML-RPC call is a round-trip; a heavy drawer fires a dozen of them and they add up to
|
| 142 |
# many seconds when run one-by-one. `parallel()` runs independent READ tasks across a small pool of
|
|
|
|
| 166 |
|
| 167 |
|
| 168 |
def get_odoo():
|
| 169 |
+
"""The active read-only client, in priority order:
|
| 170 |
+
1. a NON-default tenant binding (tenant_scope) β its own client, ALWAYS. The parallel()
|
| 171 |
+
pool below holds tenant-#0 connections, so a pooled client must never answer a bound
|
| 172 |
+
tenant's call (that is the cross-tenant leak R3's cutover removes);
|
| 173 |
+
2. this task's pooled connection (parallel(), and the app's dedicated-bg-thread pattern);
|
| 174 |
+
3. an explicit default-slug binding β the env client;
|
| 175 |
+
4. unbound: the shared env singleton. Transparent to every read_group/... caller."""
|
| 176 |
+
c = _ctx()
|
| 177 |
+
if c is not None and c['slug'] != _DEFAULT_SLUG:
|
| 178 |
+
return _client_for(c['slug'], c['creds'])
|
| 179 |
+
task_client = getattr(_tlocal, 'client', None)
|
| 180 |
+
if task_client is not None:
|
| 181 |
+
return task_client
|
| 182 |
+
if c is not None:
|
| 183 |
+
return _client_for(c['slug'], c['creds'])
|
| 184 |
+
return _global_client()
|
| 185 |
|
| 186 |
|
| 187 |
def set_doc_mode(mode):
|
|
|
|
| 206 |
return [tasks[0]()]
|
| 207 |
|
| 208 |
caller_mode = doc_mode() # propagate the submitter's basis to each worker
|
| 209 |
+
caller_ctx = _ctx() # and the tenant binding β a worker thread must
|
| 210 |
+
# answer for the SAME tenant as its submitter
|
| 211 |
def _run(fn):
|
| 212 |
c = _checkout()
|
| 213 |
_tlocal.client = c
|
| 214 |
_tlocal.doc_mode = caller_mode
|
| 215 |
+
_tlocal.tenant_ctx = caller_ctx
|
| 216 |
try:
|
| 217 |
return fn()
|
| 218 |
finally:
|
| 219 |
_tlocal.client = None
|
| 220 |
_tlocal.doc_mode = 'order'
|
| 221 |
+
_tlocal.tenant_ctx = None
|
| 222 |
_checkin(c)
|
| 223 |
with ThreadPoolExecutor(max_workers=min(len(tasks), _POOL_MAX)) as ex:
|
| 224 |
return list(ex.map(_run, tasks))
|
|
|
|
| 238 |
return v[1] if isinstance(v, list) and len(v) > 1 else ''
|
| 239 |
|
| 240 |
|
| 241 |
+
_EXCL_IDS = {} # slug -> tuple of excluded partner ids (resolved once per process)
|
| 242 |
+
_EXCL_LOCK = threading.Lock()
|
| 243 |
+
|
| 244 |
+
|
| 245 |
def excluded_partner_ids():
|
| 246 |
+
"""Resolve the ACTIVE tenant's excluded partner names to ids, for fast domain filtering.
|
| 247 |
+
Cached per tenant slug β the old lru_cache(1) would have handed tenant B whatever tenant A
|
| 248 |
+
resolved first. Unbound/default = tenant #0's env-sourced names; a bound tenant's names come
|
| 249 |
+
from its scope config (none configured -> nothing excluded)."""
|
| 250 |
+
c = _ctx()
|
| 251 |
+
bound_other = c is not None and c['slug'] != _DEFAULT_SLUG
|
| 252 |
+
slug = c['slug'] if bound_other else _DEFAULT_SLUG
|
| 253 |
+
names = (c['exclude_partner_names'] or set()) if bound_other else EXCLUDE_PARTNER_NAMES
|
| 254 |
+
with _EXCL_LOCK:
|
| 255 |
+
if slug in _EXCL_IDS:
|
| 256 |
+
return _EXCL_IDS[slug]
|
| 257 |
+
if not names:
|
| 258 |
+
res = tuple()
|
| 259 |
+
else:
|
| 260 |
+
rows = get_odoo().search_read('res.partner', [('name', 'in', list(names))], ['id'])
|
| 261 |
+
res = tuple(r['id'] for r in rows)
|
| 262 |
+
with _EXCL_LOCK:
|
| 263 |
+
_EXCL_IDS[slug] = res
|
| 264 |
+
return res
|
| 265 |
|
| 266 |
|
| 267 |
def sale_line_domain(date_from=None, date_to=None, team_id=None, extra=None, partner_ids=None):
|
|
|
|
| 269 |
the configured house accounts, with optional date window / single team / extra clauses.
|
| 270 |
partner_ids (a collection, possibly empty) restricts to those customers β the carrier for
|
| 271 |
the Customer module's Agent filter; None = no partner restriction (an empty set matches none)."""
|
| 272 |
+
tids = active_team_ids()
|
| 273 |
+
dom = [('state', 'in', ['sale', 'done']), ('product_id', '!=', False)]
|
| 274 |
+
if tids:
|
| 275 |
+
dom.insert(1, ('order_id.team_id', 'in', tids))
|
| 276 |
if team_id is not None:
|
| 277 |
dom = [d for d in dom if not (isinstance(d, tuple) and d[0] == 'order_id.team_id')]
|
| 278 |
dom.append(('order_id.team_id', '=', team_id))
|
odoo_client.py
CHANGED
|
@@ -58,11 +58,15 @@ def _proxy(uri):
|
|
| 58 |
class OdooClient:
|
| 59 |
READ_ONLY = True
|
| 60 |
|
| 61 |
-
def __init__(self):
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
missing = [k for k, v in [('ODOO_URL', self.url), ('ODOO_DB', self.db),
|
| 67 |
('ODOO_USER', self.user), ('ODOO_API_KEY', self.api_key)] if not v]
|
| 68 |
if missing:
|
|
|
|
| 58 |
class OdooClient:
|
| 59 |
READ_ONLY = True
|
| 60 |
|
| 61 |
+
def __init__(self, creds=None):
|
| 62 |
+
"""`creds` (R3 keychain cutover): an explicit {url, db, user, api_key} dict β a TENANT'S
|
| 63 |
+
stored credentials β wins over the environment. None keeps the env/.env behavior every
|
| 64 |
+
existing caller relies on (tenant #0's connection)."""
|
| 65 |
+
creds = creds or {}
|
| 66 |
+
self.url = str(creds.get('url') or os.environ.get('ODOO_URL', '')).rstrip('/')
|
| 67 |
+
self.db = str(creds.get('db') or os.environ.get('ODOO_DB', ''))
|
| 68 |
+
self.user = str(creds.get('user') or os.environ.get('ODOO_USER', ''))
|
| 69 |
+
self.api_key = str(creds.get('api_key') or os.environ.get('ODOO_API_KEY', ''))
|
| 70 |
missing = [k for k, v in [('ODOO_URL', self.url), ('ODOO_DB', self.db),
|
| 71 |
('ODOO_USER', self.user), ('ODOO_API_KEY', self.api_key)] if not v]
|
| 72 |
if missing:
|