receipter-pro / backend /automations.py
M8ion deploy
Deploy backend
45dc2a1
Raw History Blame Contribute Delete
12.9 kB
"""Sequences, recurring sends and date-based sends.
An automation is a saved rule that makes ordinary campaigns when its time comes. Each campaign it
makes goes through `sending.queue_campaign`, so the sending window, daily limits, unsubscribe and
suppression, pause and cancel all apply exactly as they do to a campaign sent by hand.
orgs/{org}/automations/{id} the rule and its progress
active_automations/{org}_{id} the index the timer reads
Kinds
sequence a list of steps; each person gets step 1, then step 2 `delay_days` after, and so on.
People added to the list later join automatically.
recurring one message to the whole list every N days, weeks or months until it ends.
date one message sent to each person on a date taken from a column (a birthday, an expiry,
an event), a number of days before or after it, optionally every year.
"""
from __future__ import annotations
import calendar
import uuid
from datetime import date, datetime, timedelta, timezone
from backend import databases, mailboxes, orgs, sending
from backend import firestore_client as db
KINDS = ("sequence", "recurring", "date")
UNITS = ("day", "week", "month")
MAX_STEPS = 10
MAX_DELAY_DAYS = 365
class AutomationError(ValueError):
"""Raised for an invalid automation."""
def _path(org_id: str, automation_id: str) -> str:
return f"orgs/{org_id}/automations/{automation_id}"
def _index(org_id: str, automation_id: str) -> str:
return f"active_automations/{org_id}_{automation_id}"
def _now() -> datetime:
return datetime.now(timezone.utc)
def _parse(value: str, field: str) -> datetime:
try:
when = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
raise AutomationError(f"{field} is not a date and time") from None
return when if when.tzinfo else when.replace(tzinfo=timezone.utc)
def _add_months(day: date, months: int) -> date:
index = day.month - 1 + months
year, month = day.year + index // 12, index % 12 + 1
return date(year, month, min(day.day, calendar.monthrange(year, month)[1]))
def next_after(when: datetime, every: dict) -> datetime:
n, unit = every["interval"], every["unit"]
if unit == "day":
return when + timedelta(days=n)
if unit == "week":
return when + timedelta(weeks=n)
return datetime.combine(_add_months(when.date(), n), when.timetz())
def _clean_steps(steps: list[dict] | None) -> list[dict]:
if not steps or len(steps) > MAX_STEPS:
raise AutomationError(f"A sequence has 1 to {MAX_STEPS} steps")
out = []
for i, step in enumerate(steps):
subject, body = str(step.get("subject") or "").strip(), str(step.get("html_body") or "")
delay = step.get("delay_days", 0)
if not subject or not body.strip():
raise AutomationError(f"Step {i + 1} needs a subject and a message")
if not isinstance(delay, int) or not 0 <= delay <= MAX_DELAY_DAYS:
raise AutomationError(f"Step {i + 1}: wait between 0 and {MAX_DELAY_DAYS} days")
out.append({"subject": subject, "html_body": body, "delay_days": delay})
return out
def create(org_id: str, actor_uid: str, spec: dict) -> dict:
orgs.require_permission(org_id, actor_uid, "send")
kind = spec.get("kind")
if kind not in KINDS:
raise AutomationError("Choose sequence, recurring or date")
name = str(spec.get("name") or "").strip()
if not name:
raise AutomationError("Give it a name")
mailboxes.get_mailbox(org_id, spec["mailbox_connection_id"])
database = databases.get_database(org_id, spec["database_id"])
doc = {
"kind": kind, "name": name[:120], "status": "active", "note": "",
"mailbox_connection_id": spec["mailbox_connection_id"], "database_id": spec["database_id"],
"email_column": spec.get("email_column"), "segment": spec.get("segment") or [],
"created_by": actor_uid, "created_at": _now().isoformat(), "runs": 0,
}
start = _parse(spec["start_at"], "Start") if spec.get("start_at") else _now()
if kind == "sequence":
doc |= {"steps": _clean_steps(spec.get("steps")), "start_at": start.isoformat(), "enrolled": {}}
else:
subject, body = str(spec.get("subject") or "").strip(), str(spec.get("html_body") or "")
if not subject or not body.strip():
raise AutomationError("It needs a subject and a message")
doc |= {"subject": subject, "html_body": body}
if kind == "recurring":
every = spec.get("every") or {}
if every.get("unit") not in UNITS or not isinstance(every.get("interval"), int) or not 1 <= every["interval"] <= 365:
raise AutomationError("Choose how often: every N days, weeks or months")
end = _parse(spec["end_at"], "End").isoformat() if spec.get("end_at") else None
doc |= {"every": {"unit": every["unit"], "interval": every["interval"]}, "next_at": start.isoformat(), "end_at": end}
else:
column = spec.get("date_column")
if column not in [c["name"] for c in database["columns"]]:
raise AutomationError("Choose the column that holds the date")
offset = spec.get("offset_days", 0)
if not isinstance(offset, int) or abs(offset) > MAX_DELAY_DAYS:
raise AutomationError(f"Offset must be within {MAX_DELAY_DAYS} days")
doc |= {"date_column": column, "offset_days": offset, "yearly": bool(spec.get("yearly")), "fired": {}}
automation_id = uuid.uuid4().hex
db.set_doc(_path(org_id, automation_id), doc)
db.set_doc(_index(org_id, automation_id), {"org_id": org_id, "automation_id": automation_id})
return get(org_id, actor_uid, automation_id)
def get(org_id: str, actor_uid: str, automation_id: str) -> dict:
orgs.require_permission(org_id, actor_uid, "send")
doc = db.get_doc(_path(org_id, automation_id))
if not doc:
raise orgs.NotFoundError(f"Automation {automation_id!r} not found")
return _public(automation_id, doc)
def _public(automation_id: str, doc: dict) -> dict:
out = {k: v for k, v in doc.items() if k not in ("enrolled", "fired")}
out["automation_id"] = automation_id
if doc["kind"] == "sequence":
steps = len(doc["steps"])
out["people"] = len(doc.get("enrolled", {}))
out["finished"] = sum(1 for e in doc.get("enrolled", {}).values() if e["step"] >= steps)
return out
def list_for(org_id: str, actor_uid: str) -> list[dict]:
orgs.require_permission(org_id, actor_uid, "send")
docs = db.query_prefix(f"orgs/{org_id}/automations/")
rows = [_public(path.rsplit("/", 1)[-1], d) for path, d in docs.items()]
return sorted(rows, key=lambda a: a["created_at"], reverse=True)
def control(org_id: str, actor_uid: str, automation_id: str, action: str) -> dict:
orgs.require_permission(org_id, actor_uid, "send")
doc = db.get_doc(_path(org_id, automation_id))
if not doc:
raise orgs.NotFoundError(f"Automation {automation_id!r} not found")
status = doc["status"]
if action == "pause" and status == "active":
new = "paused"
elif action == "resume" and status == "paused":
new = "active"
elif action == "stop" and status in ("active", "paused"):
new = "stopped"
else:
raise AutomationError(f"This is {status}, so it cannot be {action}d")
db.update_doc(_path(org_id, automation_id), {"status": new, "note": ""})
if new == "active":
db.set_doc(_index(org_id, automation_id), {"org_id": org_id, "automation_id": automation_id})
else:
db.delete_doc(_index(org_id, automation_id))
return get(org_id, actor_uid, automation_id)
def delete(org_id: str, actor_uid: str, automation_id: str) -> None:
orgs.require_permission(org_id, actor_uid, "send")
db.delete_doc(_path(org_id, automation_id))
db.delete_doc(_index(org_id, automation_id))
# --- The timer ---------------------------------------------------------------
def _queue(org_id: str, doc: dict, subject: str, html_body: str, row_ids: list[str]) -> None:
sending.queue_campaign(
org_id, doc["created_by"], subject, html_body, doc["mailbox_connection_id"], doc["database_id"],
doc.get("segment"), email_column=doc.get("email_column"), only_row_ids=row_ids, automated=True,
)
def _rows(org_id: str, doc: dict) -> list[dict]:
database = databases.get_database(org_id, doc["database_id"])
return sending._recipient_rows(org_id, doc["database_id"], database, doc.get("segment"), doc.get("email_column"))
def _row_date(value) -> date | None:
text = str(value or "").strip()
for fmt, size in (("%Y-%m-%d", 10), ("%d/%m/%Y", 10)):
try:
return datetime.strptime(text[:size], fmt).date()
except ValueError:
continue
return None
def _step_sequence(org_id: str, doc: dict, now: datetime) -> bool:
if _parse(doc["start_at"], "Start") > now:
return False
enrolled = doc["enrolled"]
rows = _rows(org_id, doc)
for row in rows: # anyone new on the list joins at step one
enrolled.setdefault(row["row_id"], {"step": 0, "next_at": (now + timedelta(days=doc["steps"][0]["delay_days"])).isoformat()})
live = {r["row_id"] for r in rows}
due: dict[int, list[str]] = {}
for row_id, state in enrolled.items():
if row_id in live and state["step"] < len(doc["steps"]) and _parse(state["next_at"], "") <= now:
due.setdefault(state["step"], []).append(row_id)
for step_no, row_ids in sorted(due.items()):
step = doc["steps"][step_no]
_queue(org_id, doc, step["subject"], step["html_body"], row_ids)
following = doc["steps"][step_no + 1]["delay_days"] if step_no + 1 < len(doc["steps"]) else 0
for row_id in row_ids:
enrolled[row_id] = {"step": step_no + 1, "next_at": (now + timedelta(days=following)).isoformat()}
doc["runs"] += 1
return True # enrolling new people changes the record even when nothing is due
def _step_recurring(org_id: str, doc: dict, now: datetime) -> bool:
if _parse(doc["next_at"], "") > now:
return False
end = _parse(doc["end_at"], "") if doc.get("end_at") else None
if end and now > end:
doc["status"] = "done"
return True
_queue(org_id, doc, doc["subject"], doc["html_body"], [r["row_id"] for r in _rows(org_id, doc)])
doc["runs"] += 1
nxt = next_after(_parse(doc["next_at"], ""), doc["every"])
while nxt <= now: # missed periods are skipped, not sent in a burst
nxt = next_after(nxt, doc["every"])
doc["next_at"] = nxt.isoformat()
return True
def _step_date(org_id: str, doc: dict, now: datetime) -> bool:
today = now.date()
due = []
for row in _rows(org_id, doc):
day = _row_date(row.get(doc["date_column"]))
if day is None:
continue
if doc["yearly"]:
try:
day = day.replace(year=today.year)
except ValueError: # 29 February in a year without one
day = date(today.year, 3, 1)
target = day + timedelta(days=doc["offset_days"])
key = str(target.year if doc["yearly"] else target)
if target == today and doc["fired"].get(row["row_id"]) != key:
due.append((row["row_id"], key))
if not due:
return False
_queue(org_id, doc, doc["subject"], doc["html_body"], [r for r, _ in due])
for row_id, key in due:
doc["fired"][row_id] = key
doc["runs"] += 1
return True
_STEPS = {"sequence": _step_sequence, "recurring": _step_recurring, "date": _step_date}
def run_one(org_id: str, automation_id: str, now: datetime | None = None) -> None:
now = now or _now()
doc = db.get_doc(_path(org_id, automation_id))
if not doc:
raise orgs.NotFoundError(automation_id)
if doc["status"] != "active":
db.delete_doc(_index(org_id, automation_id))
return
try:
changed = _STEPS[doc["kind"]](org_id, doc, now)
except (ValueError, orgs.NotFoundError) as err: # e.g. the mailbox needs attention: wait for a person
db.update_doc(_path(org_id, automation_id), {"status": "paused", "note": f"Paused: {err}"})
db.delete_doc(_index(org_id, automation_id))
return
if changed:
db.set_doc(_path(org_id, automation_id), doc)
if doc["status"] != "active":
db.delete_doc(_index(org_id, automation_id))
def run_due(now: datetime | None = None) -> dict:
checked = 0
for entry in list(db.query_prefix("active_automations/").values()):
try:
run_one(entry["org_id"], entry["automation_id"], now)
except orgs.NotFoundError:
db.delete_doc(_index(entry["org_id"], entry["automation_id"]))
checked += 1
return {"checked": checked}