Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/mail-and-timeline-through-platform-doors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
"hotcrm": patch
---

Clause-②: no
Metadata-protocol: none

**Send Email and the activity actions hand their mail and timeline entries to the platform.** Send Email gives its message to the platform's mail service and adds its timeline entry through the platform's activity service. Log a Call, Log a Meeting and Schedule a Meeting add their timeline entry the same way. An app action no longer writes the mail log or the activity feed itself; the platform records who sent or logged it, under which organization, and which action added the entry.

**What a user sees changes in one place.** An email sent with Send Email now goes out from the deployment's configured sender address, with the rep named in the sender's display name (the rep's name, then "via" and the organization's name), instead of from the rep's own address. Replies still reach the rep: the rep's address is the message's reply-to.

The timeline entries look as before and name the rep by their display name. An email's entry no longer links to the mail log row, which a sales rep cannot open; it carries the message's id in its details. A logged call's or meeting's entry keeps the first 4,000 characters of its notes in its details; the event keeps all of them.

Requires ObjectStack 18.4.0.
4 changes: 2 additions & 2 deletions content/docs/guides/email-and-calendar.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ HotCRM turns customer conversations into **records you can query**: an email you
**Send Email** is registered on the **contact** record, and it is hidden on a contact with *Email Opt Out* ticked. Opportunities and cases carry the three activity actions below, not this one.

1. The action asks for a **Subject** and a **Body**. The recipient is the contact's own email address; there is no template picker and no merge-field expansion.
2. On submit an email row is written with status **Queued**, sent from your user's email address and linked back to the contact under *Related Object*.
3. The contact's **Activity** timeline gains an entry — `Email: <subject>` — that points at that email row, so the drill-through opens the message rather than a summary string.
2. On submit the platform's mail service writes an email row with status **Queued**. The message goes out from your deployment's configured sender address, with your name in the sender's display name, and a reply comes back to your own address. The row is linked back to the contact under *Related Object* and records you as its sender.
3. The contact's **Activity** timeline gains an entry under your name — `Email: <subject>`. The entry carries the message's id in its details; it does not link to the email row, which a sales rep cannot open.
4. The contact's **Last Contacted Date**, and the parent account's **Last Activity Date**, are stamped. An email is an interaction, even though it is not a calendar slot, so it refreshes the same recency clock a held meeting does — see [Meetings & Calls](/docs/sales/meetings-and-calls).

Delivery belongs to the platform's email service, which owns the states the row moves through: **Queued → Sent**, or **Failed** with the transport's error message and an attempt count. Whether the message leaves the building depends on the transport your deployment configures — with no provider configured the platform falls back to a log-only transport, which records the message and sends nothing.
Expand Down
4 changes: 2 additions & 2 deletions content/docs/guides/email-and-calendar.zh-Hans.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ HotCRM 把客户沟通变成**可查询的记录**:你从联系人发出的一
**发送邮件** 注册在**联系人**记录上,并且对勾选了*拒绝邮件*的联系人隐藏。商机与工单上带的是下文那三个活动操作,而不是这一个。

1. 该操作只要求填写**主题**与**正文**。收件人就是该联系人自己的邮件地址;没有模板选择器,也没有合并字段展开。
2. 提交后会写入一条状态为 **已排队** 的邮件行,发件人是你的用户邮箱地址,并在*关联对象*下链接回该联系人。
3. 联系人的**活动**时间线会新增一条条目——`Email: <主题>`——它指向那条邮件行,因此下钻打开的是邮件本身,而不是一句摘要文本。
2. 提交后,平台邮件服务会写入一条状态为 **已排队** 的邮件行。邮件从你的部署所配置的发件地址发出,发件人显示名中带有你的名字;客户的回复会回到你自己的邮箱。这条记录在*关联对象*下链接回该联系人,并记下你是发件人。
3. 联系人的**活动**时间线会新增一条以你署名的条目——`Email: <主题>`。条目在详情里记下这封邮件的 id;它不链接到那条邮件行,因为销售代表打不开它。
4. 联系人的**最近联系日期**、以及其上级客户的**最近活动日期**会被打上时间戳。邮件虽然不是一个日历时段,但它是一次互动,因此它刷新的是与"已举行的会议"同一个时点时钟——参见[会议与通话](/zh-Hans/docs/sales/meetings-and-calls)。

投递本身属于平台邮件服务,它掌管这条记录会经过的状态:**已排队 → 已发送**,或者**失败**并附上传输层的错误信息与尝试次数。邮件是否真的发得出去,取决于你的部署配置了什么传输方式——若未配置任何提供方,平台会回落到只记日志的传输方式:消息被记录下来,但什么也不会发出。
Expand Down
4 changes: 2 additions & 2 deletions content/docs/guides/email-and-calendar.zh-Hant.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ HotCRM 把客戶溝通變成**可查詢的記錄**:你從聯絡人寄出的一
**傳送郵件** 註冊在**聯絡人**記錄上,並且對勾選了*拒絕郵件*的聯絡人隱藏。商機與工單上帶的是下文那三個活動操作,而不是這一個。

1. 該操作只要求填寫**主旨**與**內文**。收件人就是該聯絡人自己的郵件地址;沒有範本選擇器,也沒有合併欄位展開。
2. 送出後會寫入一筆狀態為 **已排隊** 的郵件列,寄件人是你的使用者信箱地址,並在*關聯物件*下連結回該聯絡人。
3. 聯絡人的**活動**時間軸會新增一條條目——`Email: <主旨>`——它指向那筆郵件列,因此下鑽打開的是郵件本身,而不是一句摘要文字。
2. 送出後,平台郵件服務會寫入一筆狀態為 **已排隊** 的郵件列。郵件從你的部署所設定的寄件地址寄出,寄件人顯示名稱中帶有你的名字;客戶的回覆會回到你自己的信箱。這筆記錄在*關聯物件*下連結回該聯絡人,並記下你是寄件人。
3. 聯絡人的**活動**時間軸會新增一條以你署名的條目——`Email: <主旨>`。條目在詳細資訊裡記下這封郵件的 id;它不連結到那筆郵件列,因為業務代表打不開它。
4. 聯絡人的**最近聯絡日期**、以及其上層客戶的**最近活動日期**會被打上時間戳記。郵件雖然不是一個行事曆時段,但它是一次互動,因此它刷新的是與「已舉行的會議」同一個時點時鐘——參見[會議與通話](/zh-Hant/docs/sales/meetings-and-calls)。

投遞本身屬於平台郵件服務,它掌管這筆記錄會經過的狀態:**已排隊 → 已寄出**,或者**失敗**並附上傳輸層的錯誤訊息與嘗試次數。郵件是否真的寄得出去,取決於你的部署設定了什麼傳輸方式——若未設定任何供應商,平台會回落到只記錄日誌的傳輸方式:訊息被記下來,但什麼也不會寄出。
Expand Down
132 changes: 39 additions & 93 deletions src/sales/actions/activity-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,21 @@ import * as salesObjects from '../objects';
* other object a rep sells to, and an object-less one is unreachable
* everywhere.
* 2. **Shape.** Each of these actions inserts a real `crm_event`, real
* `crm_event_attendee` rows, and keeps the `sys_activity` row purely as the
* unified-timeline pointer (ADR-0052 `source_object` / `source_id`), the
* same way `send_email` points at its `sys_email`. ⛔ Never move that
* structure back into a `metadata` JSON blob: a blob is not data — no view
* filters it, no dataset groups by it, no report counts it.
* `crm_event_attendee` rows, and keeps the timeline entry purely as the
* unified-timeline pointer (ADR-0052 `source_object` / `source_id`) to that
* event. ⛔ Never move that structure back into a `metadata` JSON blob: a
* blob is not data — no view filters it, no dataset groups by it, no report
* counts it.
*
* # The timeline entry goes through the platform's door
*
* The entry is added with `ctx.activity.append` (capability `activity.append`),
* never a raw insert into `sys_activity`: the activity feed is an append-only
* object its platform service writes. The door stamps the actor (the acting
* user, with the platform's display name), the organization, the time and the
* origin, reads the record and the event in the caller's own scope, and holds
* the timeline's bounds (a 500-character summary, a 255-character label,
* 8,000 characters of metadata as JSON).
*
* # Live platform workaround
*
Expand Down Expand Up @@ -106,73 +116,6 @@ export const ACTIVITY_TARGETS: Record<string, string> = {
/** JS string literal, safely quoted for splicing into a body source. */
const lit = (value: string): string => JSON.stringify(value);

/**
* The acting user's display name, as action-body SOURCE TEXT.
*
* Shared verbatim by every body that writes `sys_activity.actor_name`: the
* activity family below and `send_email` in `contact.actions.ts`.
*
* # Why a string and not a function
*
* An action body is shipped BODY-ONLY and evaluated in a QuickJS sandbox with
* no module scope, so a shared helper called from a body is not a closure at
* runtime — it is a `ReferenceError` (`_line-item-price-fill.ts` states the
* same constraint for the shared line-item price fill). A string spliced at
* AUTHORING time, while Node builds the metadata, has no such problem: what
* reaches the sandbox is one self-contained body with this text inlined,
* exactly as if it had been typed there. `test/script-bodies.test.ts` runs
* the bodies through the real action door AND pins that every `actor_name`
* writer still contains this constant, so the call sites cannot drift into
* disagreeing.
*
* # Contract for a splice site
*
* Splice into a body that has already declared `userId` (`ctx.user?.id ?? null`)
* and whose action declares `api.read`. Afterwards `actorName` holds a
* non-blank display name — the id only as a last resort, never `null`.
*/
export const ACTOR_NAME_RESOLUTION_SOURCE = `// The acting user's DISPLAY name, for the sys_activity row (#673 / #678).
//
// PLATFORM WORKAROUND. \`ctx.user.name\` is not a display name on the
// dispatch path the Console uses: the REST action dispatcher builds the
// body's user as \`{ id: ec.userId, name: ec.userId, … }\` — the key is
// present and carries the raw id, so \`ctx.user?.name\` reads as a
// plausible string and silently wrote ids like
// "grDEyLoIgnunJ2M7Y2muLgcuQbDUT0s2" into \`sys_activity.actor_name\`
// (@objectstack/runtime 17.0.0-rc.2, dist/index.js:5397-5399). The MCP
// dispatcher does try a display name first
// (\`ec.userName ?? ec.userDisplayName ?? ec.userId\`, dist/index.js:1776)
// but nothing in the installed platform ever populates either field, so
// it falls back to the id too.
//
// So the name is resolved HERE, from \`sys_user.name\` (the column the
// platform itself treats as the profile display name), with the id kept
// as the last resort — an opaque id is bad, a blank actor is worse.
// A name that differs from the id is taken as already-resolved, which is
// what makes this one query and not a query per activity write.
//
// DELETE THIS once the platform delivers a display name on ctx.user.name
// for REST-dispatched action bodies: every splice site collapses back to
// \`actor_name: ctx.user?.name\` (objectstack-ai/objectstack#5372).
const ctxName = ctx.user?.name ? String(ctx.user.name).trim() : '';
let actorName = ctxName && ctxName !== userId ? ctxName : '';
if (!actorName && userId) {
try {
const found = await ctx.api.object('sys_user').find({
where: { id: userId },
fields: ['name'],
top: 1,
});
const users = Array.isArray(found) ? found : (found?.records ?? []);
const resolved = users.length && users[0].name ? String(users[0].name).trim() : '';
if (resolved) actorName = resolved;
} catch (e) {
// A denied or unavailable sys_user read must not fail the log — the
// interaction the rep just recorded matters more than its label.
}
}
if (!actorName) actorName = userId;`;

/**
* The authored difference between one activity action and the next.
*
Expand Down Expand Up @@ -245,8 +188,6 @@ function activityAction(spec: ActivitySpec, objectName: string, nameField: strin
const userId = ctx.user?.id ?? null;
const nowIso = new Date().toISOString();

${ACTOR_NAME_RESOLUTION_SOURCE}

const subject = input.subject ? String(input.subject) : ${lit(spec.defaultSubject)};
const duration = input.duration ? Number(input.duration) : 0;
const notes = input.notes ? String(input.notes) : '';
Expand Down Expand Up @@ -350,29 +291,34 @@ function activityAction(spec: ActivitySpec, objectName: string, nameField: strin
if (row?.id) attendeeIds.push(row.id);
}

// 3. the unified-timeline pointer.
// 3. the unified-timeline pointer, through the activity door.
// \`metadata\` no longer carries the attendee list: it is a display hint
// beside a real record now, not the record itself. ADR-0052
// source_object/source_id is the queryable drill to the crm_event row.
// The door stamps the actor and the origin; the summary and the label are
// held to the timeline's column bounds, and the notes in the hint to a
// share of its metadata bound (the full notes are the event's description).
const summary = duration ? subject + ' (' + duration + ' min)' : subject;
const activity = await ctx.api.object('sys_activity').insert({
type: EVENT_STATUS === 'held' ? 'completed' : 'scheduled',
summary: ${lit(spec.summaryPrefix)} + summary,
actor_id: userId,
actor_name: actorName,
object_name: OBJECT_NAME,
record_id: recordId,
let activity = null;
if (recordId) {
const entry = {
object: OBJECT_NAME,
recordId: String(recordId),
type: EVENT_STATUS === 'held' ? 'completed' : 'scheduled',
summary: (${lit(spec.summaryPrefix)} + summary).slice(0, 500),
metadata: {
kind: EVENT_TYPE,
duration_minutes: duration,
notes: notes.slice(0, 4000),
attendee_count: attendeeIds.length,
},
};
// #514 item 2: the object's DECLARED nameField, not a hardcoded name.
record_label: record[NAME_FIELD] ?? null,
source_object: 'crm_event',
source_id: eventId,
metadata: JSON.stringify({
kind: EVENT_TYPE,
duration_minutes: duration,
notes: notes,
attendee_count: attendeeIds.length,
}),
});
const label = record[NAME_FIELD];
if (label !== null && label !== undefined && label !== '') entry.recordLabel = String(label).slice(0, 255);
if (eventId) entry.source = { object: 'crm_event', id: String(eventId) };
activity = await ctx.activity.append(entry);
}

// 4. SLA first-response stamp — NOT here. #575 B2 originally stamped
// \`crm_case.first_response_date\` from this body, which meant the metric
Expand All @@ -389,7 +335,7 @@ function activityAction(spec: ActivitySpec, objectName: string, nameField: strin

return { eventId: eventId, activityId: activity?.id ?? null, attendeeIds: attendeeIds };
`,
capabilities: ['api.read', 'api.write'],
capabilities: ['api.write', 'activity.append'],
timeoutMs: 5000,
},
locations: ['record_header', 'list_item', 'record_related'],
Expand Down
Loading
Loading