Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(commerce): surface inbound order and product messages
m7fz7c400af938d6f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c9899ec93..55958d29a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- Inbound WhatsApp Business commerce messages are no longer flattened to a bodyless `unknown`. A cart placed+ from the catalog arrives as type `order`, carrying `order { orderId, token? }`, and a shared product card+ as type `product`, carrying `product { productId, title?, description?, businessOwnerJid? }`. Both engines+ populate them, and both types are accepted by webhook and automation-rule message-type filters. The order+ token is scoped to that one order and is a correlation handle for its line items, which this API does not+ itself resolve. On Baileys the message `body` now falls back to the customer's order note or the product+ title instead of arriving empty; whatsapp-web.js already supplied a body of its own. Sharing a whole+ catalog rather than one product carries no product id and stays `unknown`.+### Fixed- A Baileys session retrying a dropped connection now reports the loop: `lastError` ondiff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 9e6f28953..2ca63f5e9 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -252,6 +252,8 @@ export const MESSAGE_TYPES = ['poll','call','revoked',+ 'order',+ 'product','masked','unknown',] as const;@@ -352,6 +354,10 @@ export interface EngineHistoryMessage {};quotedMessage?: { id: string; body: string };location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };+ /** Present on `order` messages only: the placed cart, plus the single-order token for its items. */+ order?: { orderId: string; token?: string };+ /** Present on `product` messages only: the catalog product shared into the chat. */+ product?: { productId: string; title?: string; description?: string; businessOwnerJid?: string };}// Mirrors the backend engine Channel / ChannelMessage (GET /sessions/:id/channels[/:id/messages]).diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 19a1633bc..5614d6b4b 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1301,7 +1301,7 @@ Returns a bare array of engine-neutral `IncomingMessage` objects:]```-Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `ephemeralDuration` (the chat's disappearing-messages timer in seconds, present only when one is set), `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, `call { video, missed }` (for `call` messages), and `location { latitude, longitude, description?, address?, url? }`. `senderPhone` is **not** among them: this endpoint reads live from the engine and performs no privacy-id resolution, which runs only on the inbound `message.received` path (§6.6). To map an `@lid` sender seen here, call `GET /api/sessions/:sessionId/contacts/:contactId/phone`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|poll|call|revoked|masked|unknown`. A `masked` message is one WhatsApp deliberately withholds from linked/companion devices — e.g. a high-security business OTP — so its `body` is empty by design (the content is only available on the primary phone) rather than a parsing failure; this occurs on the Baileys engine. `kind` is the user-facing chat discriminator of `chatId` — one of `individual|group|channel|status|broadcast|unknown`; it supersedes `isStatusBroadcast` (equivalent to `kind === 'status'`), which is retained for back-compat.+Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `ephemeralDuration` (the chat's disappearing-messages timer in seconds, present only when one is set), `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, `call { video, missed }` (for `call` messages), `location { latitude, longitude, description?, address?, url? }`, `order { orderId, token? }` (for `order` messages) and `product { productId, title?, description?, businessOwnerJid? }` (for `product` messages). `senderPhone` is **not** among them: this endpoint reads live from the engine and performs no privacy-id resolution, which runs only on the inbound `message.received` path (§6.6). To map an `@lid` sender seen here, call `GET /api/sessions/:sessionId/contacts/:contactId/phone`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|poll|call|revoked|order|product|masked|unknown`. An `order` is a cart the customer placed from the business catalog and a `product` is a single catalog product shared into the chat. Both engines populate the ids. The message carries no line items and this API exposes no order lookup, so `orderId` plus the single-order `token` are a correlation handle you redeem elsewhere rather than something the catalog routes resolve; `productId` resolves through `GET /api/sessions/:sessionId/catalog/products/:productId` only when the product came from the session's own catalog (`businessOwnerJid` says whose it is). Sharing a whole catalog rather than one product carries no product id and stays `unknown`. A `masked` message is one WhatsApp deliberately withholds from linked/companion devices — e.g. a high-security business OTP — so its `body` is empty by design (the content is only available on the primary phone) rather than a parsing failure; this occurs on the Baileys engine. `kind` is the user-facing chat discriminator of `chatId` — one of `individual|group|channel|status|broadcast|unknown`; it supersedes `isStatusBroadcast` (equivalent to `kind === 'status'`), which is retained for back-compat.**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` the whatsapp-web.js page died mid-read (retryable)@@ -6815,7 +6815,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| Event | When it fires | `data` payload sketch || ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `hasMedia`, `contact{…}` (plus optional `senderPhone` for `@lid` senders) |+| `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `hasMedia`, `contact{…}` (plus optional `senderPhone` for `@lid` senders, and `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages) || `message.sent` | An outbound message is created/sent from this session | Same message object shape as `message.received` || `message.ack` | A delivery/read receipt updates an outbound message | `{ id, messageId, status, ack }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it || `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1 }` |diff --git a/openapi.json b/openapi.jsonindex 7121dbb63..51bd94dc3 100644--- a/openapi.json+++ b/openapi.json@@ -12087,6 +12087,49 @@"longitude"]},+ "ChatHistoryOrderDto": {+ "type": "object",+ "properties": {+ "orderId": {+ "type": "string",+ "description": "Id of the cart the customer placed from the business catalog.",+ "example": "1000000000000001"+ },+ "token": {+ "type": "string",+ "description": "Opaque single-order credential that accompanies `orderId`. Pass through unchanged; do not log it."+ }+ },+ "required": [+ "orderId"+ ]+ },+ "ChatHistoryProductDto": {+ "type": "object",+ "properties": {+ "productId": {+ "type": "string",+ "description": "Id of the shared catalog product.",+ "example": "2000000000000002"+ },+ "title": {+ "type": "string",+ "example": "Sample product"+ },+ "description": {+ "type": "string",+ "example": "A sample product description."+ },+ "businessOwnerJid": {+ "type": "string",+ "description": "JID of the catalog's owner.",+ "example": "[email protected]"+ }+ },+ "required": [+ "productId"+ ]+ },"ChatHistoryMessageDto": {"type": "object","properties": {@@ -12125,6 +12168,8 @@"poll","call","revoked",+ "order",+ "product","masked","unknown"],@@ -12223,6 +12268,22 @@},"location": {"$ref": "#/components/schemas/ChatHistoryLocationDto"+ },+ "order": {+ "description": "Set for `order` messages.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ChatHistoryOrderDto"+ }+ ]+ },+ "product": {+ "description": "Set for `product` messages.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ChatHistoryProductDto"+ }+ ]}},"required": [diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 54831e8c0..5ef22ac19 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -293,6 +293,24 @@ type ChatHistoryMessage struct {Media *ChatHistoryMedia `json:"media,omitempty"`QuotedMessage *QuotedMessage `json:"quotedMessage,omitempty"`Location *MessageLocation `json:"location,omitempty"`+ Order *MessageOrder `json:"order,omitempty"`+ Product *MessageProduct `json:"product,omitempty"`+}++// MessageOrder is the order block on a live history message, present on order messages only: the+// cart the customer placed from the business catalog, plus the single-order token for its items.+type MessageOrder struct {+ OrderID string `json:"orderId"`+ Token string `json:"token,omitempty"`+}++// MessageProduct is the product block on a live history message, present on product messages only:+// the catalog product shared into the chat.+type MessageProduct struct {+ ProductID string `json:"productId"`+ Title string `json:"title,omitempty"`+ Description string `json:"description,omitempty"`+ BusinessOwnerJID string `json:"businessOwnerJid,omitempty"`}// MessageCall is the call block on a live history message, present on call messages only.@@ -438,6 +456,8 @@ const (MsgPoll MessageType = "poll"MsgCall MessageType = "call"MsgRevoked MessageType = "revoked"+ MsgOrder MessageType = "order"+ MsgProduct MessageType = "product"MsgMasked MessageType = "masked"MsgUnknown MessageType = "unknown")diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.javaindex c98c5acc4..9af781364 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java@@ -34,7 +34,9 @@ public record ChatHistoryMessage(Integer font,Media media,QuotedMessage quotedMessage,- Location location) {+ Location location,+ Order order,+ Product product) {/** Attached media; {@code data} is absent when the payload was omitted (too large). */public record Media(String mimetype, String filename, String data, Boolean omitted, Long sizeBytes) {}@@ -46,6 +48,15 @@ public record ChatHistoryMessage(/** Present on {@code call} messages only. */public record Call(Boolean video, Boolean missed) {}+ /**+ * Present on {@code order} messages only: the cart the customer placed from the business+ * catalog, plus the single-order {@code token} that resolves its line items.+ */+ public record Order(String orderId, String token) {}++ /** Present on {@code product} messages only: the catalog product shared into the chat. */+ public record Product(String productId, String title, String description, String businessOwnerJid) {}+/*** Sender contact info. History carries {@code pushName} only; the richer fields arrive on* {@code message.received} when {@code WEBHOOK_CONTACT_DETAILS} is enabled.diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MessageType.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MessageType.javaindex f909b7a2c..fd34f0eb2 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MessageType.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MessageType.java@@ -16,6 +16,8 @@ public enum MessageType {@SerializedName("poll") POLL,@SerializedName("call") CALL,@SerializedName("revoked") REVOKED,+ @SerializedName("order") ORDER,+ @SerializedName("product") PRODUCT,@SerializedName("masked") MASKED,@SerializedName("unknown") UNKNOWN}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 3d1239e05..ebabff0d7 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -535,6 +535,8 @@ export type MessageType =| 'poll'| 'call'| 'revoked'+ | 'order'+ | 'product'| 'masked'| 'unknown';@@ -593,6 +595,10 @@ export interface ChatHistoryMessage {};quotedMessage?: { id: string; body: string };location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };+ /** Present on `order` messages only: the placed cart, plus the single-order token for its items. */+ order?: { orderId: string; token?: string };+ /** Present on `product` messages only: the catalog product shared into the chat. */+ product?: { productId: string; title?: string; description?: string; businessOwnerJid?: Jid };}/** Paginated payload returned by `GET /sessions/:id/messages`. */diff --git a/sdk/javascript/test/wire-contract.test-d.ts b/sdk/javascript/test/wire-contract.test-d.tsindex 07a3290ae..9b9f070b8 100644--- a/sdk/javascript/test/wire-contract.test-d.ts+++ b/sdk/javascript/test/wire-contract.test-d.ts@@ -103,6 +103,8 @@ interface WireChatHistoryMessage {| 'poll'| 'call'| 'revoked'+ | 'order'+ | 'product'| 'masked'| 'unknown';timestamp: number;@@ -137,6 +139,8 @@ interface WireChatHistoryMessage {media?: { mimetype: string; filename?: string; data?: string; omitted?: boolean; sizeBytes?: number };quotedMessage?: { id: string; body: string };location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };+ order?: { orderId: string; token?: string };+ product?: { productId: string; title?: string; description?: string; businessOwnerJid?: string };}/** `Catalog` — the control: this pair already agreed before #754 and must stay agreeing. */diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex ab9f6d325..7297daf3f 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -15,8 +15,10 @@ import {import {buildIncomingMessageFromBaileys,extractBaileysBody,+ extractBaileysCommerce,extractBaileysContext,extractBaileysLocation,+ isBaileysCatalogShare,mapBaileysStatus,} from './baileys-message-mapper';import { buildEditedMessage } from './message-mapper';@@ -868,6 +870,9 @@ export class BaileysEvents {// The quote, the disappearing-messages timer, the mentions and the status styling all come from// one region of the content — see BaileysMessageContext.const context = extractBaileysContext(normalized);+ // Commerce ids (order token, product id): the generic path sees an empty body and drops them,+ // and they are the only handle a caller has on the order or the product.+ const commerce = extractBaileysCommerce(normalized, contentType);return buildIncomingMessageFromBaileys({@@ -884,6 +889,9 @@ export class BaileysEvents {media,location,quotedMessage: context.quotedMessage,+ order: commerce.order,+ product: commerce.product,+ isCatalogShare: isBaileysCatalogShare(normalized),ephemeralDuration: context.ephemeralDuration,mentionedJids: context.mentionedJids,backgroundArgb: context.backgroundArgb,diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.tsindex 8c60e54e4..dc79cedf3 100644--- a/src/engine/adapters/baileys-message-mapper.spec.ts+++ b/src/engine/adapters/baileys-message-mapper.spec.ts@@ -2,7 +2,9 @@ import {BaileysIncomingFields,buildIncomingMessageFromBaileys,extractBaileysBody,+ extractBaileysCommerce,extractBaileysContext,+ isBaileysCatalogShare,mapBaileysMessageType,mapBaileysStatus,} from './baileys-message-mapper';@@ -37,6 +39,10 @@ describe('mapBaileysMessageType (baileys content-type -> neutral MessageType)',// Regression trap: calls arrive via the `call` socket event, never as a message content type,// so any call-ish token must stay 'unknown' (no accidental mapping).['callLogMessage', false, 'unknown'],+ // WhatsApp Business commerce shapes carry ids the commerce APIs need, so they get their own+ // types instead of collapsing to a bodyless `unknown`.+ ['orderMessage', false, 'order'],+ ['productMessage', false, 'product'],])('maps %s (ptt=%s) -> %s', (raw, ptt, expected) => {// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertionexpect(mapBaileysMessageType(raw as string | undefined, ptt as boolean)).toBe(expected);@@ -335,4 +341,100 @@ describe('buildIncomingMessageFromBaileys', () => {expect(buildIncomingMessageFromBaileys(base).mentionedIds).toBeUndefined();expect(buildIncomingMessageFromBaileys({ ...base, mentionedJids: [] }).mentionedIds).toBeUndefined();});++ it('normalizes the catalog owner JID, so no commerce field escapes the @c.us convention', () => {+ const normalize = (jid: string) => jid.replace('@s.whatsapp.net', '@c.us');+ const r = buildIncomingMessageFromBaileys(+ {+ ...base,+ contentType: 'productMessage',+ product: { productId: '2', title: 'Sample', businessOwnerJid: '[email protected]' },+ },+ normalize,+ );+ expect(r.product).toEqual({ productId: '2', title: 'Sample', businessOwnerJid: '[email protected]' });+ });++ it('carries the order through untouched, and types a catalog share as unknown', () => {+ expect(+ buildIncomingMessageFromBaileys({ ...base, contentType: 'orderMessage', order: { orderId: '1', token: 't' } })+ .order,+ ).toEqual({ orderId: '1', token: 't' });+ expect(buildIncomingMessageFromBaileys({ ...base, contentType: 'productMessage', isCatalogShare: true }).type).toBe(+ 'unknown',+ );+ });+});++describe('extractBaileysCommerce (order / product ids)', () => {+ // Field-for-field shape of an inbound order as WhatsApp sends it; ids and token are placeholders.+ const orderContent = {+ orderMessage: {+ orderId: '1000000000000001',+ token: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',+ },+ };++ it('extracts the order id and its single-order token', () => {+ expect(extractBaileysCommerce(orderContent, 'orderMessage').order).toEqual({+ orderId: '1000000000000001',+ token: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',+ });+ });++ it('keeps the order id when no token came with it', () => {+ const { order } = extractBaileysCommerce({ orderMessage: { orderId: '1' } }, 'orderMessage');+ expect(order).toEqual({ orderId: '1', token: undefined });+ });++ it('extracts the product id and its descriptive fields from a shared product card', () => {+ const { product } = extractBaileysCommerce(+ {+ productMessage: {+ businessOwnerJid: '[email protected]',+ product: { productId: '2000000000000002', title: 'Sample', description: 'A sample' },+ },+ },+ 'productMessage',+ );+ expect(product).toEqual({+ productId: '2000000000000002',+ title: 'Sample',+ description: 'A sample',+ businessOwnerJid: '[email protected]',+ });+ });++ it('yields nothing when the id that makes it actionable is missing', () => {+ expect(extractBaileysCommerce({ orderMessage: { token: 'x' } }, 'orderMessage')).toEqual({});+ expect(extractBaileysCommerce({ productMessage: { product: { title: 'A' } } }, 'productMessage')).toEqual({});+ });++ it('yields nothing for a non-commerce content type', () => {+ expect(extractBaileysCommerce(orderContent, 'conversation')).toEqual({});+ expect(extractBaileysCommerce({}, undefined)).toEqual({});+ });+});++describe('isBaileysCatalogShare (the productMessage arm with no product)', () => {+ // There is no `catalogMessage` content type: sharing a whole catalog sends a `productMessage`+ // carrying `catalog` instead of `product`, which would otherwise surface as a `product` message+ // with no product object and an empty body.+ it('detects the catalog arm and maps it to unknown rather than product', () => {+ const content = { productMessage: { catalog: { title: 'Storefront' } } };+ expect(isBaileysCatalogShare(content)).toBe(true);+ expect(mapBaileysMessageType('productMessage', false, true)).toBe('unknown');+ expect(extractBaileysCommerce(content, 'productMessage')).toEqual({});+ });++ it('flattens the catalog title into the body so the message is not empty', () => {+ expect(extractBaileysBody({ productMessage: { catalog: { title: 'Storefront' } } })).toBe('Storefront');+ });++ it('is false for a real product card, and for a productMessage carrying both arms', () => {+ expect(isBaileysCatalogShare({ productMessage: { product: { productId: '2' } } })).toBe(false);+ expect(isBaileysCatalogShare({ productMessage: { product: { productId: '2' }, catalog: { title: 'S' } } })).toBe(+ false,+ );+ });});diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex d08fb7802..6aba8cc29 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -11,7 +11,11 @@ import { chatKind } from '../identity/wa-id';* intentionally not produced on this engine — unlike the wwjs adapter, which sources call detail* from the gated `getChatHistory` path.*/-export function mapBaileysMessageType(contentType: string | undefined, isPtt = false): MessageType {+export function mapBaileysMessageType(+ contentType: string | undefined,+ isPtt = false,+ isCatalogShare = false,+): MessageType {switch (contentType) {case 'conversation':case 'extendedTextMessage':@@ -46,6 +50,14 @@ export function mapBaileysMessageType(contentType: string | undefined, isPtt = f// carry display text that {@link extractBaileysBody} flattens into `body`, so they surface as// `text` instead of being dropped as `unknown` with an empty body (#562).return 'text';+ case 'orderMessage':+ return 'order';+ case 'productMessage':+ // A shared product card — or, with the `catalog` arm set instead of `product`, a share of the+ // whole catalog (there is no `catalogMessage` content type). A catalog share carries no+ // product id, so it stays `unknown` rather than a `product` with nothing to act on; its title+ // still reaches `body` via {@link extractBaileysBody}.+ return isCatalogShare ? 'unknown' : 'product';case 'placeholderMessage':// Meta masks high-security business messages (enterprise OTPs, banking alerts) on linked/// companion devices — which Baileys is — delivering a bodyless `placeholderMessage` (its only@@ -89,6 +101,14 @@ export interface BaileysBodyContent {contactMessage?: { vcard?: string | null } | null;/** Several contact cards shared together; each carries its own vCard. */contactsArrayMessage?: { contacts?: Array<{ vcard?: string | null }> | null } | null;+ /** A placed order: the customer's note, else the order's own title. */+ orderMessage?: { message?: string | null; orderTitle?: string | null } | null;+ /** A shared product card: the accompanying text, else the product's — or the catalog's — title. */+ productMessage?: {+ body?: string | null;+ product?: { title?: string | null } | null;+ catalog?: { title?: string | null } | null;+ } | null;}/**@@ -123,6 +143,11 @@ export function extractBaileysBody(content: BaileysBodyContent): string {content.templateButtonReplyMessage?.selectedDisplayText ??content.contactMessage?.vcard ??extractContactsArrayVcards(content.contactsArrayMessage) ??+ content.orderMessage?.message ??+ content.orderMessage?.orderTitle ??+ content.productMessage?.body ??+ content.productMessage?.product?.title ??+ content.productMessage?.catalog?.title ??'');}@@ -142,6 +167,74 @@ function extractContactsArrayVcards(return vcards.length > 0 ? vcards.join('\n') : undefined;}+/**+ * The inbound message-content subset the commerce extractor reads. Declared structurally, as+ * {@link BaileysBodyContent} is.+ */+export interface BaileysCommerceContent {+ orderMessage?: { orderId?: string | null; token?: string | null } | null;+ productMessage?: {+ businessOwnerJid?: string | null;+ product?: { productId?: string | null; title?: string | null; description?: string | null } | null;+ /** Set instead of `product` when the whole catalog was shared — see {@link isBaileysCatalogShare}. */+ catalog?: { title?: string | null } | null;+ } | null;+}++/** Both commerce shapes an inbound message can carry; each arm is set only for its content type. */+export interface BaileysCommerce {+ order?: IncomingMessage['order'];+ product?: IncomingMessage['product'];+}++/**+ * Extract the ids a commerce message carries: an order's `orderId`/`token` (the correlation handle+ * for its line items) and a shared product's `productId` (what the catalog routes take). Both are+ * dropped by the generic path, which sees only an empty body.+ *+ * An order or product without its id yields nothing: a client cannot act on either, and an entry+ * with an empty id would look actionable while failing at the API. Pass the NORMALIZED content, as+ * the adapter does — a commerce message in a disappearing chat nests under `ephemeralMessage`.+ */+export function extractBaileysCommerce(+ content: BaileysCommerceContent,+ contentType: string | undefined,+): BaileysCommerce {+ if (contentType === 'orderMessage') {+ const orderId = content.orderMessage?.orderId;+ if (!orderId) {+ return {};+ }+ return { order: { orderId, token: content.orderMessage?.token ?? undefined } };+ }++ if (contentType === 'productMessage') {+ const snapshot = content.productMessage?.product;+ return snapshot?.productId+ ? {+ product: {+ productId: snapshot.productId,+ title: snapshot.title ?? undefined,+ description: snapshot.description ?? undefined,+ businessOwnerJid: content.productMessage?.businessOwnerJid ?? undefined,+ },+ }+ : {};+ }++ return {};+}++/**+ * A catalog share arrives as a `productMessage` too, carrying the `catalog` arm instead of+ * `product` (there is no `catalogMessage` content type). It names a whole catalog and carries no+ * product id, so it must not surface as a `product` with no product — see+ * {@link mapBaileysMessageType}.+ */+export function isBaileysCatalogShare(content: BaileysCommerceContent): boolean {+ return !content.productMessage?.product?.productId && content.productMessage?.catalog != null;+}+/*** The inbound message-content subset the location extractor reads. Declared structurally (not* `proto.IMessage`) for the same reason as {@link BaileysBodyContent}. The live variant carries@@ -318,6 +411,11 @@ export interface BaileysIncomingFields {location?: IncomingMessage['location'];/** Pre-extracted quoted message context. Populated by the adapter when `contextInfo` is present. */quotedMessage?: IncomingMessage['quotedMessage'];+ /** Pre-extracted commerce ids. Populated by the adapter for `orderMessage` / `productMessage`. */+ order?: IncomingMessage['order'];+ product?: IncomingMessage['product'];+ /** A `productMessage` that shares the whole catalog rather than one product — see `isBaileysCatalogShare`. */+ isCatalogShare?: boolean;/** Ephemeral/disappearing-messages timer from `contextInfo.expiration` on the Baileys message. */ephemeralDuration?: number;/** @mentioned engine JIDs from `contextInfo.mentionedJid`; normalized and surfaced as `mentionedIds`. */@@ -353,7 +451,7 @@ export function buildIncomingMessageFromBaileys(to: fields.fromMe ? chatId : self,chatId,body: fields.body,- type: mapBaileysMessageType(fields.contentType, fields.isPtt),+ type: mapBaileysMessageType(fields.contentType, fields.isPtt, fields.isCatalogShare),timestamp: fields.timestamp,fromMe: fields.fromMe,isGroup,@@ -399,6 +497,19 @@ export function buildIncomingMessageFromBaileys(incoming.quotedMessage = fields.quotedMessage;}+ if (fields.order) {+ incoming.order = fields.order;+ }++ if (fields.product) {+ // The catalog owner goes through the same normalizer as every other JID on the payload, so an+ // order/product never emits `@s.whatsapp.net` or `@lid` next to `@c.us` fields in one object.+ const { businessOwnerJid } = fields.product;+ incoming.product = businessOwnerJid+ ? { ...fields.product, businessOwnerJid: normalizeJid(businessOwnerJid) }+ : fields.product;+ }+// Ephemeral/disappearing-messages timer, when the chat has one set.if (fields.ephemeralDuration && fields.ephemeralDuration > 0) {incoming.ephemeralDuration = fields.ephemeralDuration;diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.tsindex 6282cb531..61e306c62 100644--- a/src/engine/adapters/message-mapper.spec.ts+++ b/src/engine/adapters/message-mapper.spec.ts@@ -126,6 +126,45 @@ describe('buildIncomingMessageBase', () => {expect(buildIncomingMessageBase(base).mentionedIds).toBeUndefined();expect(buildIncomingMessageBase({ ...base, mentionedIds: [] }).mentionedIds).toBeUndefined();});++ it('maps an order id and its single-order token', () => {+ const r = buildIncomingMessageBase({ ...base, type: 'order', orderId: '1000000000000001', token: 'tok' });+ expect(r.order).toEqual({ orderId: '1000000000000001', token: 'tok' });+ expect(r.product).toBeUndefined();+ });++ it('maps an order that arrived without a token', () => {+ expect(buildIncomingMessageBase({ ...base, type: 'order', orderId: '1' }).order).toEqual({ orderId: '1' });+ });++ it('maps a shared product card with the fields whatsapp-web.js exposes', () => {+ const r = buildIncomingMessageBase({+ ...base,+ type: 'product',+ productId: '2000000000000002',+ title: 'Sample',+ description: 'A sample',+ businessOwnerJid: '[email protected]',+ });+ expect(r.product).toEqual({+ productId: '2000000000000002',+ title: 'Sample',+ description: 'A sample',+ businessOwnerJid: '[email protected]',+ });+ expect(r.order).toBeUndefined();+ });++ it('yields nothing when the id that makes the message actionable is missing', () => {+ expect(buildIncomingMessageBase({ ...base, type: 'order', token: 'tok' }).order).toBeUndefined();+ expect(buildIncomingMessageBase({ ...base, type: 'product', title: 'Sample' }).product).toBeUndefined();+ });++ it('does not fabricate a product from a title on a non-commerce message', () => {+ const r = buildIncomingMessageBase({ ...base, title: 'Sample', productId: '2', orderId: '1' });+ expect(r.product).toBeUndefined();+ expect(r.order).toBeUndefined();+ });});describe('mapWwebjsMessageType (engine type-token -> neutral MessageType boundary, #265)', () => {@@ -143,6 +182,8 @@ describe('mapWwebjsMessageType (engine type-token -> neutral MessageType boundar['call_log', 'call'],['revoked', 'revoked'],['poll_creation', 'poll'],+ ['order', 'order'],+ ['product', 'product'],['e2e_notification', 'unknown'], // any unmapped wwebjs type])('maps wwebjs type %s -> %s', (raw, expected) => {expect(mapWwebjsMessageType(raw)).toBe(expected);diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.tsindex 5066d634c..101a6bfe1 100644--- a/src/engine/adapters/message-mapper.ts+++ b/src/engine/adapters/message-mapper.ts@@ -35,6 +35,10 @@ export function mapWwebjsMessageType(raw: string): MessageType {return 'poll';case 'revoked':return 'revoked';+ case 'order':+ return 'order';+ case 'product':+ return 'product';default:return 'unknown';}@@ -65,6 +69,16 @@ export interface RawMessageFields {mentionedIds?: string[];/** Raw wwebjs payload; `notifyName` carries the sender's push name without an extra lookup. */_data?: { notifyName?: string; ephemeralDuration?: number };+ /** Set on `order` messages: the placed order's id, and the single-order token that unlocks its items. */+ orderId?: string;+ token?: string;+ /** Set on `product` messages: the shared catalog product. */+ productId?: string;+ /** Product title / description. whatsapp-web.js exposes these only for a product card. */+ title?: string;+ description?: string;+ /** The catalog owner's JID, on a shared product card. */+ businessOwnerJid?: string;}/**@@ -125,6 +139,19 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessageincoming.ephemeralDuration = msg._data.ephemeralDuration;}+ // Commerce ids, keyed off the mapped type so a stray `title` on some other message shape cannot+ // fabricate a product. Without the id neither entry is actionable, so both are then left unset.+ if (incoming.type === 'order' && msg.orderId) {+ incoming.order = { orderId: msg.orderId, ...(msg.token ? { token: msg.token } : {}) };+ } else if (incoming.type === 'product' && msg.productId) {+ incoming.product = {+ productId: msg.productId,+ ...(msg.title ? { title: msg.title } : {}),+ ...(msg.description ? { description: msg.description } : {}),+ ...(msg.businessOwnerJid ? { businessOwnerJid: msg.businessOwnerJid } : {}),+ };+ }+return incoming;}diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 281178577..105e3dddb 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -78,6 +78,10 @@ export type MessageType =| 'poll'| 'call'| 'revoked'+ // WhatsApp Business commerce: a customer's cart placed from the catalog, and a single product+ // card shared into a chat. Both carry the ids the commerce APIs need — see `IncomingMessage`.+ | 'order'+ | 'product'// A message WhatsApp deliberately withheld from linked/companion devices (e.g. high-security// business OTPs): the payload is absent by design, not unparseable. See `mapBaileysMessageType`.| 'masked'@@ -110,6 +114,28 @@ export interface IncomingMessage {mentionedIds?: string[];/** Set for `call` (call_log) messages: video vs voice, and whether an incoming call went unanswered. */call?: { video: boolean; missed: boolean };+ /**+ * Set for `order` messages: a cart the customer placed from the business catalog. The message+ * carries no line items — `orderId` plus the single-order `token` are the correlation handle a+ * caller redeems against WhatsApp's own order lookup, which this project does not expose, so both+ * must survive to that caller. Both engines populate them.+ */+ order?: {+ orderId: string;+ /** Opaque, single-order credential. Pass through unchanged; do not log it. */+ token?: string;+ };+ /**+ * Set for `product` messages: the catalog product shared into the chat. `productId` identifies it+ * within `businessOwnerJid`'s catalog, so it resolves through the catalog routes only when that+ * catalog is the session's own. Both engines populate `productId`; the rest are best-effort.+ */+ product?: {+ productId: string;+ title?: string;+ description?: string;+ businessOwnerJid?: string;+ };/*** Set by the adapter when the sender is identified by a privacy id (e.g. a WhatsApp `@lid`) rather* than a phone number, so engine-neutral code can decide whether to attempt phone resolution withoutdiff --git a/src/modules/message/dto/message-responses.dto.ts b/src/modules/message/dto/message-responses.dto.tsindex 2495dd7eb..6ff557b78 100644--- a/src/modules/message/dto/message-responses.dto.ts+++ b/src/modules/message/dto/message-responses.dto.ts@@ -22,6 +22,8 @@ const MESSAGE_TYPES: MessageType[] = ['poll','call','revoked',+ 'order',+ 'product','masked','unknown',];@@ -218,6 +220,33 @@ export class ChatHistoryCallDto {missed!: boolean;}+export class ChatHistoryOrderDto {+ @ApiProperty({+ description: 'Id of the cart the customer placed from the business catalog.',+ example: '1000000000000001',+ })+ orderId!: string;++ @ApiPropertyOptional({+ description: 'Opaque single-order credential that accompanies `orderId`. Pass through unchanged; do not log it.',+ })+ token?: string;+}++export class ChatHistoryProductDto {+ @ApiProperty({ description: 'Id of the shared catalog product.', example: '2000000000000002' })+ productId!: string;++ @ApiPropertyOptional({ example: 'Sample product' })+ title?: string;++ @ApiPropertyOptional({ example: 'A sample product description.' })+ description?: string;++ @ApiPropertyOptional({ description: "JID of the catalog's owner.", example: '[email protected]' })+ businessOwnerJid?: string;+}+/** OpenAPI mirror of the engine `IncomingMessage` served by the live chat-history route. */export class ChatHistoryMessageDto {@ApiProperty({ example: '[email protected]_3EB0123456789' })@@ -296,6 +325,12 @@ export class ChatHistoryMessageDto {@ApiPropertyOptional({ type: ChatHistoryLocationDto })location?: ChatHistoryLocationDto;++ @ApiPropertyOptional({ type: ChatHistoryOrderDto, description: 'Set for `order` messages.' })+ order?: ChatHistoryOrderDto;++ @ApiPropertyOptional({ type: ChatHistoryProductDto, description: 'Set for `product` messages.' })+ product?: ChatHistoryProductDto;}export class MessageReactionSenderDto {diff --git a/src/modules/webhook/filters/filter-types.ts b/src/modules/webhook/filters/filter-types.tsindex 6ee1b36ab..8a1e1656b 100644--- a/src/modules/webhook/filters/filter-types.ts+++ b/src/modules/webhook/filters/filter-types.ts@@ -57,6 +57,8 @@ const MESSAGE_TYPE_FLAGS: Record<MessageType, true> = {poll: true,call: true,revoked: true,+ order: true,+ product: true,masked: true,unknown: true,};