# Chat (developers)

Module `packages/core/src/Modules/Chat`.

- Tables: `chat_conversations` (visitor token stored as a sha256 hash, customer, e-mail, status `open|ticket|closed`,
  assignee, page), `chat_messages` (author `customer|staff|bot`, `internal` notes, `automated`), `chat_agents`
  (presence `online|away|offline` and `seen_at`).
- `Hours\WorkingHours` (weekly hours, dated exceptions, `Hours\RomanianHolidays`: Codul muncii art. 139 with Orthodox
  Easter by Meeus' Julian algorithm) and `Actions\Availability::staffed()` (open and someone online, seen in the last
  two minutes). Settings: `Settings\ChatSettings`.
- `Actions\Conversations`: `start()` (open, or a ticket with an automated reply naming the next opening), messages
  from customer and staff (first response and assignee set by the first public staff reply), notes, close. Bodies are
  plain text, control characters removed, 4000 characters at most.
- Widget JSON under `/chat` (`chat.*`, throttles `chat-read`/`chat-write`, honeypot `website`): the visitor's token is
  the httpOnly `ss_chat` cookie; internal notes are never returned. A conversation with a `customer_id` opens only
  while that customer is signed in (a shared computer after sign-out sees nothing), and a token that opens nothing is
  cleared by the next state call. The widget (`packages/theme-default/resources/js/store/chat.js`) loads
  after the page is idle from the `chat._widget` anchor (view composer in the provider), sends `X-XSRF-TOKEN` from the
  cookie (no CSRF meta on cached pages), polls every 4 s while open and writes every text with `textContent`.
- Inbox `admin.chat.*` (`chat.reply`): folders, conversation, customer card (`CustomerAccounts`, `OrderBook::forCustomer`),
  reply / note / assign / close, presence; `packages/core/resources/js/admin/chat.js` heartbeats presence and refreshes on the
  `chat.changed` broadcast (private `chat.inbox.{shop}`, `{shop}` from `syncshop.broadcast.shop`, `shop` on-premises; payload `{id}` only) or polls every 5 s without Reverb.
  A reply to a ticket is mailed (`Mail\ChatReplyMail`).
- Order-status bot: `Actions\OrderStatusBot` (`OrderBook::findByNumber()` / `forCustomer()`, `Shipments::forOrder()`):
  the customer's own order, or number + e-mail (case-insensitive) or phone (last nine digits); one refusal text for
  every failure. Endpoint `POST /chat/comanda`, throttle `chat-order` (5/min and 20/h per IP, and 10 a day per order
  number and per normalised contact, so rotating addresses does not help); inside a conversation the
  question and the automated answer are stored.
- Saved replies: `chat_replies`, `admin.chat.replies.*` (`chat.manage`); `Actions\ReplyVariables` fills `{nume}`,
  `{comanda}`, `{link_urmarire}` for the inbox picker.
- Attachments: `Actions\Attachments` (finfo type check: JPEG, PNG, WebP, PDF; 5 MB; `private` disk under
  `chat/<conversation>/`), `POST /chat/fisier`; staff download `admin.chat.attachment` (attachment disposition, nosniff).
- Privacy: `Privacy\ChatPersonalData` (tag `personal-data`: export and erase by customer id, or the account's e-mail
  once it is confirmed; files included; staff notes are not in the export) and `Privacy\ChatRetention` (tag `retention`: conversations quiet longer than `retention_months`).
- `chat:remind` (every 10 minutes, registry): conversations whose last non-automated public message is the customer's,
  older than max(15, 3 × reply minutes), mailed once (`alerted_at`) to users with `chat.manage` (links only).
- Settings `admin.settings.chat.*` (`chat.manage`).

Tests: `tests/Feature/Chat/ChatTest.php`, `OrderBotAndRepliesTest.php`, `AttachmentsAndPrivacyTest.php` (JSON test requests need `withCredentials()` to send cookies).

## Shopping assistant

- `Chat\Assistant\ShoppingAssistant`:
  - `takes(now)` follows `ChatSettings::assistant` (off | first | out_of_hours) and `Assistant::available(AiFeature::ShoppingAssistant)`.
  - `introduce()` sets `chat_conversations.assistant_active` and writes the AI disclosure.
  - `answer(conversationId, messageId)` runs in `Jobs\AnswerInChat`, which the widget's start and send dispatch. It only
    answers the latest customer message, while the assistant is active.
- Order of checks in `answer()`:
  1. The shop's own word lists (refund or complaint, a person) hand over without a model call.
  2. The 30-answer cap.
  3. The plan call (structured: action products | order | policy | stores | handover | reply).
  4. The tool: `AssistedSearch` + `ProductSearch` + `CatalogBrowser::cards()`, `OrderStatusBot` for the signed-in
     customer only, `Pages::legal()`, or `Locations::storefront()`.
  5. The reply call (structured: reply, product_ids from the offered ones, handover).
  6. `quotesFacts()` replaces a reply that states a price, amount or stock.
- Calls go through `Assistant::ask(..., forShopper: true)` with a screened transcript (`Ai\Data\PersonalText`).
- Messages it writes are `automated` and `ai`, with `products` (ids). `WidgetController::messages()` turns those into
  cards through `Assistant\ProductCards`: catalogue card, Pricing price lowered by a running offer, stock, at display time.
- A hand-over clears `assistant_active`, sets the status (open or ticket by availability), tells the shopper, and adds an
  internal note with the reason and a model summary. `Conversations::fromStaff()` clears `assistant_active` when a
  person answers.

Tests: `tests/Feature/Chat/ShoppingAssistantTest.php`.

## Proactive messages

- `chat_proactive_rules` / `Models\ProactiveRule` (translatable `text`): trigger (`Data\ProactiveTrigger`: cart_value,
  payment_failed, returning, page), threshold (bani, VAT included), path prefix, delay, only while staffed, active,
  position, and `shown` / `answered` counters. Admin: `ProactiveRulesController` (`admin.chat.proactive.*`,
  `chat.manage`).
- `Proactive\ProactiveMessages::pick($request, $path, $event)`: none when the session already has one
  (`chat_proactive`, one a visit); the first active rule whose prefix fits, staffed when it asks, with text in the
  current language and its trigger met; it stores the rule id in the session and counts `shown`.
- The basket value comes through `Contracts\VisitorBasket` (default `Proactive\NoBasket`; the Storefront binds
  `Support\ChatBasket`, which reads the cart cookie). A returning customer is a signed-in one with an order
  (`OrderBook::forCustomer()`). A failed card payment is the `data-chat-event="payment_failed"` the order page puts on
  its message.
- `GET /chat/proactiv?page=&event=` (`WidgetController::proactive`) answers `{message: {rule, text, delay} | null}`,
  never while the visitor's conversation cookie opens one. The widget asks once per page load, not while the cookie
  banner is open, and shows the card after the delay; answering sends `proactive` with the first message, and
  `Conversations::start(..., $opening)` writes the shown rule's text first as an automated bot message (only the rule
  this session showed; `answered` counted).

Tests: `tests/Feature/Chat/ProactiveMessagesTest.php`.

## WhatsApp and Messenger

- A channel conversation has `channel` (whatsapp, messenger), `channel_driver` and `channel_contact` (the customer's
  number or page-scoped id); a customer message keeps the provider's id in `chat_messages.external_id` (unique), so a
  repeated webhook is taken once (`Channels\ReceiveChannelMessage`, which continues the latest conversation with that
  contact, reopening a closed one, or starts one through `Conversations::start(..., via: [...])`).
- `Conversations::add()` queues `Jobs\DeliverChannelMessage` (after commit) for every non-internal staff or bot message
  in a channel conversation: it sends through the driver with the hours since the customer last wrote, sets
  `delivered_at`, or `delivery_error` for a refusal (final) or after three failed tries.
- `Channels\ChannelReplies` gives the driver and whether the window is open; `InboxController::reply()` refuses a reply
  once it has closed, and the inbox shows the window, the channel and each reply's delivery.
- Drivers and the webhook path: see [Drivers](drivers.md#messaging-chat-module). The shopping assistant does not take
  channel conversations.

Tests: `tests/Feature/Chat/MessagingChannelsTest.php`.
