Spaces:
Sleeping
Sleeping
Download backend/brands.py from Success-dev/receipter-pro: direct link, hf CLI and curl.
- Browser
- Download file 5.22 kB
-
https://huggingface.co/spaces/Success-dev/receipter-pro/resolve/main/backend/brands.py
- Command line
-
hf download hf://spaces/Success-dev/receipter-pro/backend/brands.py
-
curl -L -o brands.py https://huggingface.co/spaces/Success-dev/receipter-pro/resolve/main/backend/brands.py
5.22 kB
| """ | |
| Brands: the businesses one organisation sends for. Each has its own name, logo, domain, | |
| sender name and replies address, and owns some of the org's mailboxes. Lists, saved | |
| emails and the team stay shared across brands. | |
| A mailbox belongs to at most one brand. When a campaign goes out, the brand that owns | |
| the chosen mailbox supplies the sender details the mailbox doesn't set itself (mailbox, | |
| then brand, then organisation defaults). | |
| Firestore layout: | |
| orgs/{org_id}/brands/{brand_id} — {name, logo_url, domain, from_name, reply_to, mailbox_ids, created_at} | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import uuid | |
| from datetime import datetime, timezone | |
| from backend import firestore_client as db | |
| from backend import mailboxes, orgs | |
| _EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") | |
| _DOMAIN = re.compile(r"^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$") | |
| FIELDS = ("name", "logo_url", "domain", "from_name", "reply_to", "mailbox_ids") | |
| def _path(org_id: str, brand_id: str) -> str: | |
| return f"orgs/{org_id}/brands/{brand_id}" | |
| def list_brands(org_id: str) -> list[dict]: | |
| prefix = f"orgs/{org_id}/brands/" | |
| items = [{"brand_id": path[len(prefix):], **data} for path, data in db.query_prefix(prefix).items()] | |
| return sorted(items, key=lambda b: b["name"].lower()) | |
| def get_brand(org_id: str, brand_id: str) -> dict: | |
| doc = db.get_doc(_path(org_id, brand_id)) | |
| if doc is None: | |
| raise orgs.NotFoundError(f"No brand {brand_id!r}") | |
| return doc | |
| def brand_for_mailbox(org_id: str, connection_id: str) -> dict | None: | |
| return next((b for b in list_brands(org_id) if connection_id in b.get("mailbox_ids", [])), None) | |
| def _clean(org_id: str, values: dict, brand_id: str | None) -> dict: | |
| unknown = set(values) - set(FIELDS) | |
| if unknown: | |
| raise ValueError(f"Unknown brand field: {', '.join(sorted(unknown))}") | |
| out = {k: values[k] for k in FIELDS if k in values} | |
| for key in ("name", "from_name"): | |
| if key in out: | |
| out[key] = " ".join(str(out[key] or "").split()).replace('"', "") | |
| if len(out[key]) > 80: | |
| raise ValueError("Keep names to 80 characters or fewer") | |
| if "name" in out: | |
| if not out["name"]: | |
| raise ValueError("Give the brand a name") | |
| if any(b["name"].lower() == out["name"].lower() and b["brand_id"] != brand_id for b in list_brands(org_id)): | |
| raise ValueError(f"There is already a brand called {out['name']!r}") | |
| if "reply_to" in out: | |
| out["reply_to"] = str(out["reply_to"] or "").strip() | |
| if out["reply_to"] and not _EMAIL.match(out["reply_to"]): | |
| raise ValueError("The replies address doesn't look like an email address") | |
| if "domain" in out: | |
| domain = str(out["domain"] or "").strip().lower().removeprefix("https://").removeprefix("http://").removeprefix("www.").rstrip("/") | |
| if domain and not _DOMAIN.match(domain): | |
| raise ValueError("Enter a domain like yourbrand.com") | |
| out["domain"] = domain | |
| if "logo_url" in out: | |
| logo = str(out["logo_url"] or "").strip() | |
| if logo and not logo.startswith("https://"): | |
| raise ValueError("The logo address must start with https://") | |
| out["logo_url"] = logo | |
| if "mailbox_ids" in out: | |
| ids = list(dict.fromkeys(str(i) for i in out["mailbox_ids"] or [])) | |
| for cid in ids: | |
| mailboxes.get_mailbox(org_id, cid) # NotFoundError for anything not in this org | |
| out["mailbox_ids"] = ids | |
| return out | |
| def _take_mailboxes(org_id: str, brand_id: str, ids: list[str]) -> None: | |
| """A mailbox moves to this brand: it leaves whichever brand had it.""" | |
| for other in list_brands(org_id): | |
| if other["brand_id"] != brand_id and set(other.get("mailbox_ids", [])) & set(ids): | |
| db.update_doc(_path(org_id, other["brand_id"]), {"mailbox_ids": [i for i in other["mailbox_ids"] if i not in ids]}) | |
| def create_brand(org_id: str, actor_uid: str, values: dict) -> str: | |
| orgs.require_permission(org_id, actor_uid, "manage_settings") | |
| clean = _clean(org_id, {"name": values.get("name", "")} | values, None) | |
| brand_id = uuid.uuid4().hex | |
| doc = {"logo_url": "", "domain": "", "from_name": "", "reply_to": "", "mailbox_ids": []} | clean | |
| _take_mailboxes(org_id, brand_id, doc["mailbox_ids"]) | |
| db.set_doc(_path(org_id, brand_id), doc | {"created_at": datetime.now(timezone.utc).isoformat()}) | |
| return brand_id | |
| def update_brand(org_id: str, actor_uid: str, brand_id: str, values: dict) -> dict: | |
| orgs.require_permission(org_id, actor_uid, "manage_settings") | |
| get_brand(org_id, brand_id) | |
| clean = _clean(org_id, values, brand_id) | |
| if "mailbox_ids" in clean: | |
| _take_mailboxes(org_id, brand_id, clean["mailbox_ids"]) | |
| db.update_doc(_path(org_id, brand_id), clean) | |
| return {"brand_id": brand_id, **get_brand(org_id, brand_id)} | |
| def delete_brand(org_id: str, actor_uid: str, brand_id: str) -> None: | |
| """Its mailboxes stay connected and go back to using the organisation's defaults.""" | |
| orgs.require_permission(org_id, actor_uid, "manage_settings") | |
| get_brand(org_id, brand_id) | |
| db.delete_doc(_path(org_id, brand_id)) | |