Skip to content

Intake Flow

Mohammad Hasan Kaman edited this page Nov 17, 2026 · 3 revisions

Intake Flow

Every tenant owns its own conversation script. The script — the flow — is a JSON document stored in the tenants.flow_config column, and the widget executes it step by step. There is no hard-coded questionnaire: the eleven steps of the seeded demo flow and the seven steps of the default flow for new tenants are the same code running on different data.

The engine lives in app/session_store.py; the flows themselves are defined in app/tenants.py.


The flow document

{
  "welcome": "🌸 **سلام! به سامانه هوشمند پذیرش مرکز «مشاوره نمونه» خوش آمدید.** ...",
  "steps": [ ... ],
  "ghq": true,
  "ending": "recommend",
  "thanks_text": "متشکریم! اطلاعات شما ثبت شد و در اسرع وقت با شما تماس می‌گیریم."
}
Key Meaning
welcome The first message. Also the text shown after "شروع مجدد".
steps The ordered list of questions.
ghq true → offer the GHQ-28 screen before ending. false → skip it.
ending "recommend" → show matched counselors. "lead_capture" → just confirm.
thanks_text The message shown in lead_capture mode.

Step fields

Field Meaning
key The name the value is stored under.
type text · phone · number · choice · chips · chips+text.
label The question text. If absent, a default label is derived from the key.
options For choice steps — the allowed answers. Defaults to ["بله", "خیر"].
source Which standard field the value feeds. Defaults to key.
conditional A "key=value" rule — the step is skipped unless it holds.

source decides where the answer lands. If it is one of the ten standard fields, the value goes there; anything else goes into the custom_data blob. That is how a tenant adds its own question without touching the schema.

The standard fields are:

full_name, phone, gender, age, topic, has_prev_therapy,
prev_detail, expectation, preferred_gender, branch

The two shipped flows

The demo tenant

DEFAULT_DEMO_FLOW — the flow seeded for the demo tenant («مرکز مشاوره نمونه»): eleven steps, GHQ on, ends with a recommendation, and for_other enabled (the first step asks who the intake is for):

# Key Type Question
1 relationship choice این اطلاعات برای چه کسی وارد می‌شود؟ (۸ گزینه: برای خودم / برای فرزندم / …)
2 spouse_relation choice conditional (relationship=برای فرزندم) — کیفیت ارتباط شما با همسرتان چگونه است؟
3 full_name text نام و نام خانوادگی
4 phone phone شماره تماس
5 gender choice آقا / خانم
6 age number سن
7 topic text لطفاً موضوع اصلی یا مشکلی که برای آن به مشاوره نیاز دارید را بنویسید:
8 prev_therapy choice آیا سابقه مراجعه قبلی به روان‌شناس یا روان‌پزشک داشته‌اید؟ (بله / خیر)
9 prev_detail text conditional (has_prev_therapy=بله) — توضیح مختصری درباره درمان قبلی
10 preferred_gender choice ترجیح می‌دهید جنسیت مشاور شما چه باشد؟ (آقا / خانم / فرقی ندارد)
11 branch choice کدام شعبه مرکز مشاوره نمونه برای شما مناسب‌تر است؟ (شعبه مرکزی / شعبه شمال / اهمیتی ندارد)

New tenants

default_public_flow() — the flow a newly created tenant starts with, and the fallback when a stored flow cannot be parsed: seven steps, GHQ on, ends with a recommendation:

# Key Type Question
1 relationship choice این اطلاعات برای چه کسی وارد می‌شود؟
2 spouse_relation choice conditional (relationship=برای فرزندم) — کیفیت ارتباط با همسر
3 full_name text نام و نام خانوادگی
4 phone phone شماره تماس
5 topic text موضوع اصلی یا مشکلی که برای آن به مشاوره نیاز دارید
6 age number سن
7 preferred_gender choice ترجیح جنسیت مشاور

There is deliberately no branch step: branch names are center-specific, and the tenant's admin adds one in the flow editor when the center has branches.


The state machine

The session state is a single integer in widget_sessions.state:

State Meaning
0 The welcome message was sent; the next message is the answer to step 0.
1 … N-1 Answering step n.
-3 The GHQ opt-in question is pending.
-1 The GHQ questionnaire is in progress.
-2 The flow has finished.

handle_message() dispatches on this value:

if state == -2:      return _restart(session, flow)   # any text after the end restarts
if state == -3:      # GHQ opt-in: بله / خیر
if state == -1:      return _handle_ghq(session, flow, text)
if state >= len(flow["steps"]):  return _restart(session, flow)
return _handle_step(session, flow, text)

The restart words are شروع مجدد, شروع and /start — they work at any point, including mid-questionnaire.

How the state advances

After a step is answered, _advance_state() walks forward from the current index and returns the next step whose conditional holds. If it runs off the end of the list it returns "ask_ghq" (when flow["ghq"] is true) or "end".

"ask_ghq" sets the state to -3 and sends the opt-in question. "end" calls _finish().


Conditional steps

A conditional is a single string of the form "key=value":

{"key": "prev_detail", "type": "text",
 "conditional": "has_prev_therapy=بله",
 "label": "در صورت تمایل توضیح مختصری درباره درمان قبلی بنویسید …"}

_conditional_satisfied() does the comparison:

  1. Split on = into key and value; trim both.
  2. Look up data.get(key).
  3. If the key is missing, try the legacy alias — prev_therapy ↔ has_prev_therapy. The two names have been swapped at different points in the project's history, and both spellings keep working.
  4. If the stored value is a boolean, convert it: True → "بله", False → "خیر".
  5. Compare as strings.

So the comparison is a string equality against the stored value — not a numeric comparison, not an operator DSL. There is no gt, lt, in or ne; if you need something else, express it as a key whose value is the answer itself.


Input validation

Each type has its own rule, and each failure re-asks without consuming the step:

text

An empty message re-prompts with the same label. Everything else is accepted as-is.

phone

phone = normalize_phone(text)   # digits folded, separators stripped, +98 → 0…
err = phone_error(phone)        # None when the number is acceptable
if err:
    return BotReply(err)
  • Persian and Arabic digits are converted to ASCII first.
  • Spaces and dashes are stripped, and the +98 / 0098 / 98 prefixes are folded to the local 0… form — those forms are accepted.
  • The result must be exactly 11 digits starting with 09, with a known Iranian mobile prefix (0901–0905, 0910–0919, 0930–0939, 0990–0999).
  • A suspicious patterned number (long repeated runs and similar) is rejected with an error, not merely flagged.

After a valid number, the flow counts prior requests with the same phone:

is_valid, req_count, _ = validate_phone_and_get_count(phone, full_name, tenant_id)
data["request_count"] = req_count

A number already registered under a different name is refused, so two people's records never merge.

number

t = text.translate(PERSIAN_DIGITS)
if not t.isdigit() or not (0 < int(t) < 150):
    return BotReply("لطفاً یک عدد معتبر وارد فرمایید:")

The only rule is 0 < n < 150 — the same range is used for age and for any other numeric step. There is no per-step minimum or maximum. On an LLM plan the free text is first interpreted by the LLM (so «سی و پنج» works) and this rule is the fallback.

choice

The message must be exactly one of the options. Anything else returns:

لطفاً یکی از گزینه‌های زیر را انتخاب کنید:

with the options as chips and input_type="chips". In the rule engine the comparison is exact — no fuzzy matching, no Persian-digit normalisation on this path. On an LLM plan the LLM first maps the free text onto one of the options, with the exact match as the fallback.


The dual key problem

has_prev_therapy is stored as a boolean (_CHOICE_LABELS maps بله → True, خیر → False), while the flow step key is prev_therapy and the value is the string "بله"/"خیر". The code keeps both in sync:

if key == "prev_therapy" and value in ("بله", "خیر"):
    data["has_prev_therapy"] = "بله" if value == "بله" else "خیر"

if cond.partition("=")[0].strip() == "has_prev_therapy" and data.get("prev_therapy") in ("بله", "خیر"):
    data["has_prev_therapy"] = "بله" if data["prev_therapy"] == "بله" else "خیر"

and _build_user_info() reads it back with a fallback:

prev = data.get("has_prev_therapy", data.get("prev_therapy", False))

The result is that the same question can be expressed with either key name, in either the old or the new flow format, and the answer still lands in the right place.


Ending the flow

_finish() runs the flow's ending:

"recommend"

  1. _build_user_info() assembles the dict the matching engine consumes.
  2. engine.match(user_info, tenant_id) returns up to two counselors.
  3. save_user_consultation() records the request — even when no counselor is found, so a request is never lost.
  4. Each recommendation is fed back into the learning table as a success.
  5. The message lists the counselors with their reason and a booking link, resolved from the tenant's name → URL mapping (falling back to TEAM_PAGE_URL).

When nothing matched, the visitor still gets a reply — the request has already been recorded:

متأسفانه در حال حاضر مشاوری با این مشخصات یافت نشد؛ اما اطلاعات شما ثبت شد و کارشناسان مرکز آن را بررسی می‌کنند.

"lead_capture"

The request is recorded with no recommendation, and the flow's thanks_text is returned.

In both cases

  • The state becomes -2.
  • The quick reply is شروع مجدد and the reply is marked done=True.
  • If GHQ was completed, the result message is prepended to the ending text.

Editing a flow in the admin panel

The flow editor posts a single form to POST /admin/flow with the fields welcome, ghq, ending, thanks_text and steps_json (the steps as a JSON array). The steps are sanitised server-side before they are stored — unknown fields and malformed steps are dropped rather than saved.

When a tenant's flow_config is empty or unparseable, _parse_flow_config() (in app/tenants.py) falls back to default_public_flow() instead of raising — a broken flow degrades to the default seven-step version rather than a 500.


Recovery after a refresh

The session data is written to SQLite after every answer, and expires_at is set when the session is created. If the visitor reloads the page, _state_prompt() rebuilds the current question from the stored state:

  • 0 → the welcome message.
  • -3 → the GHQ opt-in question.
  • -1 → the current GHQ question, reconstructed from ghq_index.
  • -2 → the "شروع مجدد" prompt.
  • 0 ≤ state < len(steps) → the prompt for that step.

Related pages

Clone this wiki locally