feat(segments): add live consent-aware customer audiences #44

Merged
mihir merged 1 commits from feat/customer-segmentation into main 2026-10-07 15:47:39 +05:30
15 changed files with 478 additions and 2 deletions

View File

@ -84,3 +84,5 @@ Private idle cart recovery: see [Phase 4E API guide](docs/cart-recovery-api.md).
Explicit messaging consent and eligibility: see [Phase 4F API guide](docs/messaging-consent-api.md).
Blog drafts, publication and SEO metadata: see [Phase 4G API guide](docs/blog-publishing-api.md).
Live customer segments and consent-aware audience checks: see [Phase 4H API guide](docs/customer-segments-api.md).

View File

@ -0,0 +1,25 @@
# Live customer segmentation (Phase 4H)
Staff can inspect three fixed, live segments based on current commerce records. Accounts must be active and belong to the caller's organization. Membership contains only account IDs, not names, contacts, addresses, purchase evidence, or cart/wishlist contents. Accounts with staff roles are included if they have the same qualifying commerce activity; the current identity model has no separate customer-only account type.
| Segment key | Definition |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WISHLIST_INTEREST` | At least one saved wishlist variant is currently active and its product published. Multiple saved items count the account once. |
| `RECOVERABLE_CART` | A nonempty cart has a known activity timestamp at least 24 hours old, using the same cutoff as private cart recovery. Empty/undated/recently edited carts are excluded. Catalog/stock eligibility remains authoritative at recovery and checkout. |
| `VERIFIED_BUYER` | At least one unrevoked external purchase verification exists under the verified-review evidence workflow. Pending-payment orders and cancelled orders do not establish completed purchase evidence. |
`GET /api/v1/customer-segments` requires `segments.read` and returns `asOf` plus a `segments` array of `{ key, description, total }`. The groups can overlap; their counts should not be summed to infer unique customers. No account without the qualifying evidence is included merely because it is active.
`GET /api/v1/customer-segments/:segment/members` requires `segments.read` and returns `{ segment, asOf, total, members: [{ userId }] }`. Members are distinct and ordered by UUID ascending. `limit` defaults to 25 with a maximum of 100, and `offset` defaults to zero with a maximum of 10,000. `total` is the complete filtered count, not the size of this page. Unknown segment keys, invalid pagination, scope overrides, and extra query fields return 400. Missing sessions return 401; missing permission returns 403.
Both routes optionally accept `channel=EMAIL&purpose=PROMOTIONS` (also `WHATSAPP` and `CART_RECOVERY`). Supply both fields together. This intersects the segment with the latest explicit grant for that channel and purpose; absent consent and later withdrawal exclude the account. A grant for another channel/purpose does not qualify, and replaying an old grant after withdrawal does not restore membership. Consent-filtered reads additionally require the caller's **live** `messaging.read` permission, preventing consent disclosure through a segment-only role.
Inactive accounts, unavailable wishlist merchandise, cart edits/clearing, and purchase-evidence revocation affect the next read immediately. Reads recheck the staff session and permissions inside the existing organization-locked transaction. One server time is used across each response's segment checks; total and page use the same query predicate. Source API writes share the lock. Different requests/pages are live evaluations and can change between reads; `asOf` is an evaluation timestamp, not a persistent audience snapshot or paging token.
All SQL values are bound parameters. Fixed predicate fragments use scoped joins and `EXISTS`, so multiple qualifying source records do not duplicate accounts. Queries use the existing user, wishlist, cart, verification, and consent indexes. No materialized audience, copied contact list, custom rule DSL, saved segment, scheduler, CSV export, or provider delivery is introduced. Keep live reads until measured dataset size and query latency justify cached/materialized audiences.
These are staff analysis and planning APIs, not permission to deliver messages. Future adapters must recheck live consent, recipient status/contact ownership, channel policy, campaign/cart eligibility and suppressions at dispatch and retries. A filtered preview can become stale after withdrawal. Existing transactional notifications and customer preferences are unchanged.
Deploy the additive permission migration before the application. Existing system Owners gain `segments.read`; custom roles remain explicit. There are no new audience tables or schema changes. Existing migrations and source evidence remain unchanged. Older code ignores the new permission; rollback preserves all commerce records and consent history. Existing native PostgreSQL CI requirements continue to apply.
Verification covers deduplication, live catalog/account changes, shared recovery timing and empty/undated carts, revoked purchase evidence, unpaid-order exclusion, newest consent and stale-grant replay, channel/purpose isolation, separate permissions, organization isolation, strict inputs, pagination, private projections, migration drift, and prior recovery regressions.

View File

@ -61,6 +61,7 @@ Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recov
- 4E (implemented): private discovery and versioned resumption of carts idle for 24 hours, current catalog previews, unavailable-item redaction/removal, and audited activity tracking. Outbound recovery reminders remain dependent on consent-aware messaging and provider enablement.
- 4F (consent and eligibility implemented; live delivery deferred): explicit, independent email/WhatsApp opt-in and withdrawal for promotions/cart reminders, immutable versioned evidence, private history, and scoped live eligibility checks. Provider delivery, verified channel destinations, suppression-aware dispatch and unsubscribe links remain separate milestones.
- 4G (backend implemented): versioned blog drafts, separate publication permission, stable-slug public snapshots, private revisions, reasoned withdrawal, and public SEO metadata. Frontend pages, sitemap/canonical integration, rich text/media and historical revision restoration remain separate milestones; live channel integrations remain deferred.
- 4H (implemented): live staff segmentation for wishlist interest, recoverable carts and externally verified buyers, with deduplicated scoped account IDs/counts and optional separately permissioned current-consent filtering. Saved/custom rules, materialized audiences, exports and provider dispatch remain separate milestones.
## Phase 5: Community and optimization

View File

@ -49,5 +49,6 @@
"20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017",
"20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31",
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd",
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4"
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4",
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a"
}

View File

@ -0,0 +1,3 @@
-- Audiences are derived from current source records, not persisted member copies.
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['segments.read']))
WHERE is_system = true AND name = 'Owner';

View File

@ -16,9 +16,11 @@ import { ReviewsModule } from './reviews/reviews.module';
import { CampaignsModule } from './campaigns/campaigns.module';
import { MessagingModule } from './messaging/messaging.module';
import { BlogModule } from './blog/blog.module';
import { SegmentsModule } from './segments/segments.module';
@Module({
imports: [
SegmentsModule,
BlogModule,
MessagingModule,
CampaignsModule,

View File

@ -4,6 +4,10 @@ import type { Principal } from '../identity/identity.types';
import { recordAudit } from '../identity/audit';
import { AppError } from '../common/errors/app-error';
export function recoveryCutoff(now: Date) {
return new Date(now.getTime() - 24 * 3600000);
}
export function isRecoverable(
lastActivityAt: Date | null,
count: number,
@ -12,7 +16,7 @@ export function isRecoverable(
return (
count > 0 &&
lastActivityAt !== null &&
now.getTime() - lastActivityAt.getTime() >= 24 * 3600000
lastActivityAt.getTime() <= recoveryCutoff(now).getTime()
);
}

View File

@ -1,4 +1,5 @@
export const PERMISSIONS = [
'segments.read',
'blog.read',
'blog.manage',
'blog.publish',

View File

@ -0,0 +1,45 @@
import { Prisma } from '../generated/prisma/client';
import { recoveryCutoff } from '../checkout/cart-recovery.store';
import type { SegmentKey, SegmentFilter } from './segment.schemas';
function evidence(key: SegmentKey, now: Date) {
if (key === 'WISHLIST_INTEREST')
return Prisma.sql`EXISTS (
SELECT 1 FROM wishlist_items w
JOIN product_variants v ON v.id = w.variant_id AND v.organization_id = w.organization_id
JOIN products p ON p.id = v.product_id AND p.organization_id = v.organization_id
WHERE w.user_id = u.id AND w.organization_id = u.organization_id
AND v.active = true AND p.status = 'PUBLISHED'
)`;
if (key === 'VERIFIED_BUYER')
return Prisma.sql`EXISTS (
SELECT 1 FROM review_purchase_verifications v
WHERE v.user_id = u.id AND v.organization_id = u.organization_id AND NOT EXISTS (
SELECT 1 FROM review_purchase_revocations r
WHERE r.verification_id = v.id AND r.organization_id = v.organization_id
)
)`;
return Prisma.sql`EXISTS (
SELECT 1 FROM carts c WHERE c.user_id = u.id AND c.organization_id = u.organization_id
AND c.last_activity_at <= ${recoveryCutoff(now)} AND EXISTS (
SELECT 1 FROM cart_lines l WHERE l.cart_id = c.id AND l.organization_id = c.organization_id
)
)`;
}
export function segmentAudience(
key: SegmentKey,
organizationId: string,
now: Date,
filter: SegmentFilter,
) {
const consent = filter.channel
? Prisma.sql`AND COALESCE((
SELECT d.granted FROM messaging_consent_decisions d
WHERE d.user_id = u.id AND d.organization_id = u.organization_id
AND d.channel = ${filter.channel} AND d.purpose = ${filter.purpose}
ORDER BY d.version DESC LIMIT 1
), false)`
: Prisma.empty;
return Prisma.sql`u.organization_id = ${organizationId}::uuid AND u.status = 'ACTIVE'
AND ${evidence(key, now)} ${consent}`;
}

View File

@ -0,0 +1,34 @@
import { z } from 'zod';
import { pageSchema } from '../identity/identity.schemas';
import { consentQuerySchema } from '../messaging/consent.schemas';
export const SEGMENT_KEYS = [
'WISHLIST_INTEREST',
'RECOVERABLE_CART',
'VERIFIED_BUYER',
] as const;
export const segmentKeySchema = z.enum(SEGMENT_KEYS);
const fields = {
channel: consentQuerySchema.shape.channel.optional(),
purpose: consentQuerySchema.shape.purpose.optional(),
};
const pairedConsent = (input: { channel?: string; purpose?: string }) =>
Boolean(input.channel) === Boolean(input.purpose);
export const segmentFilterSchema = z
.object(fields)
.strict()
.refine(pairedConsent, 'Provide both channel and purpose');
export const segmentPageSchema = pageSchema
.extend(fields)
.strict()
.refine(pairedConsent, 'Provide both channel and purpose');
export type SegmentKey = z.infer<typeof segmentKeySchema>;
export type SegmentFilter = z.infer<typeof segmentFilterSchema>;
export type SegmentPage = z.infer<typeof segmentPageSchema>;
export const SEGMENT_DESCRIPTIONS: Record<SegmentKey, string> = {
WISHLIST_INTEREST:
'Active accounts with at least one active, published variant saved to their wishlist.',
RECOVERABLE_CART:
'Active accounts with a nonempty, dated cart idle for at least 24 hours.',
VERIFIED_BUYER:
'Active accounts with at least one unrevoked external purchase verification.',
};

View File

@ -0,0 +1,58 @@
import { Injectable } from '@nestjs/common';
import { AccessStore } from '../identity/access.store';
import type { Principal } from '../identity/identity.types';
import { AppError } from '../common/errors/app-error';
import { Prisma } from '../generated/prisma/client';
import { segmentAudience } from './segment-query';
import {
SEGMENT_KEYS,
SEGMENT_DESCRIPTIONS,
type SegmentKey,
type SegmentFilter,
type SegmentPage,
} from './segment.schemas';
function requireConsentAccess(current: Principal, filter: SegmentFilter) {
if (filter.channel && !current.permissions.includes('messaging.read'))
throw new AppError('ACCESS_DENIED');
}
async function total(tx: Prisma.TransactionClient, audience: Prisma.Sql) {
const [row] = await tx.$queryRaw<{ total: number }[]>(
Prisma.sql`SELECT COUNT(*)::integer AS total FROM users u WHERE ${audience}`,
);
return row.total;
}
@Injectable()
export class SegmentStore {
constructor(private readonly access: AccessStore) {}
summary(actor: Principal, filter: SegmentFilter) {
// ponytail: reuse the organization lock; use repeatable-read snapshots if audience reads delay checkout.
return this.access.mutate(actor, 'segments.read', async (tx, current) => {
requireConsentAccess(current, filter);
const now = new Date();
const segments = [];
for (const key of SEGMENT_KEYS)
segments.push({
key,
description: SEGMENT_DESCRIPTIONS[key],
total: await total(
tx,
segmentAudience(key, actor.organizationId, now, filter),
),
});
return { asOf: now.toISOString(), segments };
});
}
members(actor: Principal, key: SegmentKey, page: SegmentPage) {
return this.access.mutate(actor, 'segments.read', async (tx, current) => {
requireConsentAccess(current, page);
const now = new Date();
const audience = segmentAudience(key, actor.organizationId, now, page);
const count = await total(tx, audience);
const members = await tx.$queryRaw<{ userId: string }[]>(
Prisma.sql`SELECT u.id AS "userId" FROM users u WHERE ${audience} ORDER BY u.id ASC LIMIT ${page.limit} OFFSET ${page.offset}`,
);
return { segment: key, asOf: now.toISOString(), total: count, members };
});
}
}

View File

@ -0,0 +1,36 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import {
CurrentPrincipal,
RequirePermission,
} from '../identity/access.decorator';
import type { Principal } from '../identity/identity.types';
import { SchemaPipe } from '../common/validation.pipe';
import {
segmentKeySchema,
segmentFilterSchema,
segmentPageSchema,
type SegmentKey,
type SegmentFilter,
type SegmentPage,
} from './segment.schemas';
import { SegmentStore } from './segment.store';
@Controller('customer-segments')
@RequirePermission('segments.read')
export class SegmentsController {
constructor(private readonly segments: SegmentStore) {}
@Get()
summary(
@CurrentPrincipal() actor: Principal,
@Query(new SchemaPipe(segmentFilterSchema)) filter: SegmentFilter,
) {
return this.segments.summary(actor, filter);
}
@Get(':segment/members')
members(
@CurrentPrincipal() actor: Principal,
@Param('segment', new SchemaPipe(segmentKeySchema)) key: SegmentKey,
@Query(new SchemaPipe(segmentPageSchema)) page: SegmentPage,
) {
return this.segments.members(actor, key, page);
}
}

View File

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { IdentityModule } from '../identity/identity.module';
import { SegmentsController } from './segments.controller';
import { SegmentStore } from './segment.store';
@Module({
imports: [IdentityModule],
controllers: [SegmentsController],
providers: [SegmentStore],
})
export class SegmentsModule {}

View File

@ -0,0 +1,230 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor, seedProduct } from './helpers/commerce';
import { checkoutFixture } from './helpers/checkout';
import { reviewFixture } from './helpers/reviews';
describe('live privacy-preserving customer segments', () => {
let ctx: IdentityApp;
beforeAll(async () => {
ctx = await identityApp();
});
afterAll(async () => {
await ctx.close();
});
beforeEach(async () => {
await ctx.clearLimits();
await ctx.db.user.updateMany({
where: {
organizationId: ctx.owner.organizationId,
id: { not: ctx.owner.userId },
},
data: { status: 'SUSPENDED' },
});
});
const members = (key: string, token = ctx.token, query: object = {}) =>
ctx
.api()
.get('/api/v1/customer-segments/' + key + '/members')
.auth(token, { type: 'bearer' })
.query(query);
const save = (token: string, variantId: string) =>
ctx
.api()
.put('/api/v1/wishlist/' + variantId)
.auth(token, { type: 'bearer' })
.send({})
.expect(200);
it('deduplicates current wishlist interest and excludes unavailable and inactive accounts', async () => {
const actor = await secondActor(ctx);
const a = await seedProduct(ctx, true);
const b = await seedProduct(ctx, true);
await save(actor.token, a.variant.id);
await save(actor.token, b.variant.id);
const result = await members('WISHLIST_INTEREST').expect(200);
expect(result.body).toMatchObject({
segment: 'WISHLIST_INTEREST',
total: 1,
members: [{ userId: actor.userId }],
});
expect(JSON.stringify(result.body)).not.toMatch(
/email|name|phone|password|address|note|reference/,
);
await ctx.db.productVariant.update({
where: { id: a.variant.id },
data: { active: false },
});
expect((await members('WISHLIST_INTEREST').expect(200)).body.total).toBe(1);
await ctx.db.product.update({
where: { id: b.product.id },
data: { status: 'DRAFT' },
});
expect((await members('WISHLIST_INTEREST').expect(200)).body.total).toBe(0);
await ctx.db.productVariant.update({
where: { id: a.variant.id },
data: { active: true },
});
await ctx.db.user.update({
where: { id: actor.userId },
data: { status: 'SUSPENDED' },
});
expect((await members('WISHLIST_INTEREST').expect(200)).body.total).toBe(0);
});
it('shares cart recovery timing, excludes empty carts and reacts immediately to edits', async () => {
const f = await checkoutFixture(ctx);
expect((await members('RECOVERABLE_CART').expect(200)).body.total).toBe(0);
await ctx.db.cart.updateMany({
where: { userId: f.actor.userId },
data: { lastActivityAt: new Date(Date.now() - 25 * 3600000) },
});
expect(
(await members('RECOVERABLE_CART').expect(200)).body.members,
).toEqual([{ userId: f.actor.userId }]);
await ctx
.api()
.put('/api/v1/cart/lines/' + f.variant.id)
.auth(f.actor.token, { type: 'bearer' })
.send({ version: 1, quantity: 3 })
.expect(200);
expect((await members('RECOVERABLE_CART').expect(200)).body.total).toBe(0);
await ctx.db.cart.updateMany({
where: { userId: f.actor.userId },
data: { lastActivityAt: null },
});
expect((await members('RECOVERABLE_CART').expect(200)).body.total).toBe(0);
await ctx.db.cart.updateMany({
where: { userId: f.actor.userId },
data: { lastActivityAt: new Date(Date.now() - 25 * 3600000) },
});
await ctx
.api()
.delete('/api/v1/cart/lines/' + f.variant.id)
.auth(f.actor.token, { type: 'bearer' })
.send({ version: 2 })
.expect(200);
await ctx.db.cart.updateMany({
where: { userId: f.actor.userId },
data: { lastActivityAt: new Date(Date.now() - 25 * 3600000) },
});
expect((await members('RECOVERABLE_CART').expect(200)).body.total).toBe(0);
});
it('uses external verified evidence and removes revoked buyers without counting unpaid orders', async () => {
const f = await reviewFixture(ctx);
const checkout = await checkoutFixture(ctx);
await ctx
.api()
.post('/api/v1/checkout')
.auth(checkout.actor.token, { type: 'bearer' })
.send(checkout.input)
.expect(201);
expect((await members('VERIFIED_BUYER').expect(200)).body.members).toEqual([
{ userId: f.buyer.userId },
]);
await ctx
.api()
.post('/api/v1/review-verifications/' + f.proof.id + '/revoke')
.auth(ctx.token, { type: 'bearer' })
.send({ reason: 'Evidence invalidated', idempotencyKey: randomUUID() })
.expect(201);
expect((await members('VERIFIED_BUYER').expect(200)).body.total).toBe(0);
});
it('uses the latest channel/purpose consent and requires its separate read permission', async () => {
const actor = await secondActor(ctx);
const item = await seedProduct(ctx, true);
await save(actor.token, item.variant.id);
const staff = await secondActor(ctx, true, ['segments.read']);
const filter = { channel: 'EMAIL', purpose: 'PROMOTIONS' };
await members('WISHLIST_INTEREST', staff.token).expect(200);
await members('WISHLIST_INTEREST', staff.token, filter).expect(403);
expect(
(await members('WISHLIST_INTEREST', ctx.token, filter).expect(200)).body
.total,
).toBe(0);
const input = {
...filter,
version: 0,
granted: true,
noticeVersion: '2026-10-07',
idempotencyKey: randomUUID(),
};
const consent = (body: object) =>
ctx
.api()
.post('/api/v1/messaging/preferences')
.auth(actor.token, { type: 'bearer' })
.send(body)
.expect(201);
await consent(input);
expect(
(await members('WISHLIST_INTEREST', ctx.token, filter).expect(200)).body
.total,
).toBe(1);
expect(
(
await members('WISHLIST_INTEREST', ctx.token, {
channel: 'WHATSAPP',
purpose: 'PROMOTIONS',
}).expect(200)
).body.total,
).toBe(0);
expect(
(
await members('WISHLIST_INTEREST', ctx.token, {
channel: 'EMAIL',
purpose: 'CART_RECOVERY',
}).expect(200)
).body.total,
).toBe(0);
await consent({
...filter,
version: 1,
granted: false,
idempotencyKey: randomUUID(),
});
await consent(input);
expect(
(await members('WISHLIST_INTEREST', ctx.token, filter).expect(200)).body
.total,
).toBe(0);
});
it('isolates organization audiences, paginates IDs and validates all filter inputs', async () => {
const first = await secondActor(ctx);
const second = await secondActor(ctx);
const item = await seedProduct(ctx, true);
await save(first.token, item.variant.id);
await save(second.token, item.variant.id);
const result = await members('WISHLIST_INTEREST', ctx.token, {
limit: 1,
offset: 1,
}).expect(200);
expect(result.body.total).toBe(2);
expect(result.body.members).toHaveLength(1);
const foreign = await secondActor(ctx, false, ['segments.read']);
expect(
(await members('WISHLIST_INTEREST', foreign.token).expect(200)).body
.total,
).toBe(0);
await members('WISHLIST_INTEREST', first.token).expect(403);
await members('UNKNOWN').expect(400);
for (const query of [
{ limit: 101 },
{ offset: -1 },
{ channel: 'EMAIL' },
{ purpose: 'PROMOTIONS' },
{ channel: 'SMS', purpose: 'PROMOTIONS' },
{ organizationId: foreign.organizationId },
])
await members('WISHLIST_INTEREST', ctx.token, query).expect(400);
await ctx.api().get('/api/v1/customer-segments').expect(401);
const summary = await ctx
.api()
.get('/api/v1/customer-segments')
.auth(ctx.token, { type: 'bearer' })
.expect(200);
expect(summary.body.segments).toHaveLength(3);
expect(
summary.body.segments.find((s: any) => s.key === 'WISHLIST_INTEREST')
.total,
).toBe(2);
});
});

View File

@ -0,0 +1,24 @@
import {
segmentFilterSchema,
segmentPageSchema,
segmentKeySchema,
} from '../src/segments/segment.schemas';
it('validates fixed segment keys, bounded pages and paired channel/purpose filters', () => {
expect(segmentFilterSchema.safeParse({}).success).toBe(true);
expect(
segmentFilterSchema.safeParse({ channel: 'EMAIL', purpose: 'PROMOTIONS' })
.success,
).toBe(true);
expect(segmentPageSchema.parse({})).toEqual({ limit: 25, offset: 0 });
for (const query of [
{ channel: 'EMAIL' },
{ purpose: 'PROMOTIONS' },
{ channel: 'SMS', purpose: 'PROMOTIONS' },
{ limit: 101 },
{ offset: 10001 },
{ organizationId: 'other' },
])
expect(segmentPageSchema.safeParse(query).success).toBe(false);
expect(segmentKeySchema.safeParse('UNKNOWN').success).toBe(false);
});