"""Resource definitions: stages, editable fields, validators and labels.""" from datetime import datetime, timezone from validation import ( clean_amount, clean_email, clean_reference, clean_stage, clean_text, ) STAGES = ("lead", "qualified", "proposal", "won", "lost") DEFAULT_STAGE = "lead" def now_iso(): """Timestamp used by the records and by the activity log.""" return datetime.now(timezone.utc).isoformat(timespec="seconds") def validate_company(store, data): return { "name": clean_text(data.get("name"), "name", required=True), "website": clean_text(data.get("website"), "website"), "industry": clean_text(data.get("industry"), "industry"), } def validate_contact(store, data): return { "name": clean_text(data.get("name"), "name", required=True), "email": clean_email(data.get("email"), "email"), "phone": clean_text(data.get("phone"), "phone"), "company_id": clean_reference(store, data.get("company_id"), "companies", "company_id", "company"), } def validate_deal(store, data): return { "title": clean_text(data.get("title"), "title", required=True), "amount": clean_amount(data.get("amount"), "amount"), "stage": clean_stage(data.get("stage"), STAGES, "stage", DEFAULT_STAGE), "company_id": clean_reference(store, data.get("company_id"), "companies", "company_id", "company"), "contact_id": clean_reference(store, data.get("contact_id"), "contacts", "contact_id", "contact"), } RESOURCES = { "companies": { "table": "companies", "singular": "company", "search": ("name",), "fields": ("name", "website", "industry"), "validate": validate_company, "label": "name", "csv_columns": ("id", "name", "website", "industry"), }, "contacts": { "table": "contacts", "singular": "contact", "search": ("name", "email"), "fields": ("name", "email", "phone", "company_id"), "validate": validate_contact, "label": "name", "csv_columns": ("id", "name", "email", "phone", "company_id"), }, "deals": { "table": "deals", "singular": "deal", "search": ("title",), "fields": ("title", "amount", "stage", "company_id", "contact_id"), "validate": validate_deal, "auto": {"created_at": now_iso}, "label": "title", "csv_columns": ("id", "title", "amount", "stage", "company_id", "contact_id", "created_at"), }, } def record_label(resource, record): """Short human readable description used in the activity log.""" if resource == "notes": return note_label(record) field = RESOURCES[resource]["label"] label = (record.get(field) or "").strip() or "#%s" % record.get("id") return '%s "%s"' % (RESOURCES[resource]["singular"], label) def note_label(note): """Short description of a note, truncated to keep the log readable.""" body = " ".join((note.get("body") or "").split()) if len(body) > 80: body = body[:79] + "…" return 'note "%s"' % body