diff --git a/.changeset/reditus-server-destination.md b/.changeset/reditus-server-destination.md new file mode 100644 index 000000000..9400be82d --- /dev/null +++ b/.changeset/reditus-server-destination.md @@ -0,0 +1,9 @@ +--- +'@walkeros/server-destination-reditus': minor +--- + +New Reditus server destination for affiliate and referral programs. Each rule +sends a referral conversion (`POST /v2/tracking/conversion`, with `gr_id` or an +affiliate/advocate slug) or a payment (`POST /v1/payments`, amount in cents, +idempotent on the event id). An existing referral (409) or a customer who was +never referred (404) counts as delivered. diff --git a/package-lock.json b/package-lock.json index 97459145a..0c49d6c1e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19889,6 +19889,10 @@ "resolved": "packages/server/destinations/redis", "link": true }, + "node_modules/@walkeros/server-destination-reditus": { + "resolved": "packages/server/destinations/reditus", + "link": true + }, "node_modules/@walkeros/server-destination-rudderstack": { "resolved": "packages/server/destinations/rudderstack", "link": true @@ -49668,6 +49672,24 @@ "@walkeros/collector": "4.9.0" } }, + "packages/server/destinations/reditus": { + "name": "@walkeros/server-destination-reditus", + "version": "4.9.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/elbwalker" + } + ], + "license": "MIT", + "dependencies": { + "@walkeros/core": "4.9.0", + "@walkeros/server-core": "4.9.0" + }, + "devDependencies": { + "@walkeros/collector": "4.9.0" + } + }, "packages/server/destinations/rudderstack": { "name": "@walkeros/server-destination-rudderstack", "version": "4.9.0", diff --git a/packages/server/destinations/reditus/README.md b/packages/server/destinations/reditus/README.md new file mode 100644 index 000000000..c9f5fad1a --- /dev/null +++ b/packages/server/destinations/reditus/README.md @@ -0,0 +1,65 @@ +

+ + walkerOS + +

+ +# @walkeros/server-destination-reditus + +Server-side referral conversions and payments to +[Reditus](https://www.getreditus.com), the affiliate and referral platform: a +referred sign-up or demo becomes a conversion, a referred customer's payment is +credited to the partner. + +[Documentation](https://www.walkeros.io/docs/destinations/server/reditus) • +[NPM Package](https://www.npmjs.com/package/@walkeros/server-destination-reditus) +• +[Source Code](https://github.com/elbwalker/walkerOS/tree/main/packages/server/destinations/reditus) + +## Installation + +```bash +npm install @walkeros/server-destination-reditus +``` + +## Quick start + +```json +{ + "version": 4, + "flows": { + "default": { + "config": { "platform": "server" }, + "destinations": { + "reditus": { + "package": "@walkeros/server-destination-reditus", + "config": { + "settings": { + "apiKey": "$secret.REDITUS_API_KEY" + } + } + } + } + } + } +} +``` + +This quick start sets no consent: add `consent: { marketing: true }` to `config` +before you go live, see the docs. + +## Documentation + +Full configuration, mapping, and examples live in the docs: +**https://www.walkeros.io/docs/destinations/server/reditus** + +## Contribute + +Feel free to contribute by submitting an +[issue](https://github.com/elbwalker/walkerOS/issues), starting a +[discussion](https://github.com/elbwalker/walkerOS/discussions), or getting in +[contact](https://calendly.com/elb-alexander/30min). + +## License + +MIT diff --git a/packages/server/destinations/reditus/jest.config.mjs b/packages/server/destinations/reditus/jest.config.mjs new file mode 100644 index 000000000..d1e06ddf6 --- /dev/null +++ b/packages/server/destinations/reditus/jest.config.mjs @@ -0,0 +1,5 @@ +import baseConfig from '@walkeros/config/jest'; + +const config = {}; + +export default { ...baseConfig, ...config }; diff --git a/packages/server/destinations/reditus/package.json b/packages/server/destinations/reditus/package.json new file mode 100644 index 000000000..ef94ed5e6 --- /dev/null +++ b/packages/server/destinations/reditus/package.json @@ -0,0 +1,76 @@ +{ + "name": "@walkeros/server-destination-reditus", + "description": "Reditus affiliate and referral server destination for walkerOS", + "version": "4.9.0", + "license": "MIT", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./dev": { + "types": "./dist/dev.d.ts", + "import": "./dist/dev.mjs", + "require": "./dist/dev.js" + }, + "./walkerOS.json": "./dist/walkerOS.json", + "./examples": { + "types": "./dist/examples/index.d.ts", + "import": "./dist/examples/index.mjs", + "require": "./dist/examples/index.js" + } + }, + "files": [ + "dist/**", + "CHANGELOG.md" + ], + "scripts": { + "build": "tsup --silent", + "clean": "rm -rf .turbo && rm -rf dist", + "dev": "jest --watchAll --colors", + "typecheck": "tsc --noEmit", + "lint": "eslint \"**/*.ts*\"", + "test": "jest", + "update": "npx npm-check-updates -u && npm update" + }, + "dependencies": { + "@walkeros/core": "4.9.0", + "@walkeros/server-core": "4.9.0" + }, + "devDependencies": { + "@walkeros/collector": "4.9.0" + }, + "repository": { + "url": "git+https://github.com/elbwalker/walkerOS.git", + "directory": "packages/server/destinations/reditus" + }, + "author": "elbwalker ", + "homepage": "https://github.com/elbwalker/walkerOS#readme", + "bugs": { + "url": "https://github.com/elbwalker/walkerOS/issues" + }, + "walkerOS": { + "type": "destination", + "platform": [ + "server" + ], + "docs": "https://www.walkeros.io/docs/destinations/server/reditus" + }, + "keywords": [ + "walkerOS", + "walkerOS-destination", + "destination", + "server", + "reditus", + "affiliate", + "referral", + "conversions" + ], + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/elbwalker" + } + ] +} diff --git a/packages/server/destinations/reditus/src/__tests__/conformance.test.ts b/packages/server/destinations/reditus/src/__tests__/conformance.test.ts new file mode 100644 index 000000000..cc820239b --- /dev/null +++ b/packages/server/destinations/reditus/src/__tests__/conformance.test.ts @@ -0,0 +1,21 @@ +import path from 'path'; +import { conformance } from '@walkeros/collector/dev'; +import { destinationReditus } from '..'; +import { examples, schemas } from '../dev'; + +describe('reditus conformance', () => { + beforeEach(() => { + jest.useRealTimers(); + }); + + it('conforms', async () => { + await conformance('destination', destinationReditus, { + profile: 'http', + examples: examples.step, + schema: schemas.settings, + settings: examples.minimal.settings, + minimal: examples.minimal, + root: path.join(__dirname, '..', '..'), + }); + }); +}); diff --git a/packages/server/destinations/reditus/src/__tests__/index.test.ts b/packages/server/destinations/reditus/src/__tests__/index.test.ts new file mode 100644 index 000000000..cedeb704f --- /dev/null +++ b/packages/server/destinations/reditus/src/__tests__/index.test.ts @@ -0,0 +1,197 @@ +import type { Collector, WalkerOS } from '@walkeros/core'; +import type { Settings } from '../types'; +import { + clone, + createMockContext, + createMockLogger, + getEvent, + StepError, +} from '@walkeros/core'; +import { destinationReditus as destination } from '..'; +import { examples } from '../dev'; + +describe('Server Destination Reditus', () => { + const apiKey = 's3cr3t'; + const mockSendServer = jest.fn(); + const testEnv = clone(examples.env.push); + testEnv.sendServer = mockSendServer; + + const call = () => mockSendServer.mock.calls[0]; + const body = () => JSON.parse(call()[1]); + const event: WalkerOS.Event = getEvent('order complete', { + id: 'ev-1', + timestamp: 1700000900000, + }); + + async function push( + data: Record, + settings: Partial = {}, + rule?: Record, + ) { + return destination.push( + event, + createMockContext({ + config: { settings: { apiKey, ...settings } }, + data, + env: testEnv, + ...(rule ? { rule } : {}), + }), + ); + } + + async function init(settings: Record) { + return destination.init({ + config: { settings: settings as unknown as Settings }, + collector: {} as Collector.Instance, + env: testEnv, + logger: createMockLogger(), + id: 'test-reditus', + }); + } + + beforeEach(() => { + jest.clearAllMocks(); + mockSendServer.mockResolvedValue({ data: {} }); + }); + + test('init fails without apiKey or with an unknown type', async () => { + await expect(init({})).rejects.toThrow('Config settings apiKey missing'); + await expect(init({ apiKey, type: 'refund' })).rejects.toThrow( + 'type must be "conversion" or "payment"', + ); + }); + + test('conversion by default, with Bearer token', async () => { + await push({ email: 'a@b.c', gr_id: 'gr_1' }); + expect(call()[0]).toBe( + 'https://api.getreditus.com/api/v2/tracking/conversion', + ); + expect(call()[2].headers.Authorization).toBe('Bearer s3cr3t'); + expect(body()).toEqual({ email: 'a@b.c', gr_id: 'gr_1' }); + }); + + test('custom url without trailing slash duplication', async () => { + await push( + { uid: 'u1', advocate_slug: 'adv' }, + { + url: 'https://example.com/api/', + }, + ); + expect(call()[0]).toBe('https://example.com/api/v2/tracking/conversion'); + }); + + test('conversion needs email or uid', async () => { + await expect(push({ gr_id: 'gr_1' })).rejects.toMatchObject({ + code: 'mapping', + retryable: false, + }); + expect(mockSendServer).not.toHaveBeenCalled(); + }); + + test('conversion needs a referral identifier', async () => { + await expect(push({ email: 'a@b.c' })).rejects.toThrow( + 'needs gr_id, affiliate_slug or advocate_slug', + ); + }); + + test('settings type payment applies when the rule sets none', async () => { + await push({ email: 'a@b.c', amount: 10 }, { type: 'payment' }); + expect(call()[0]).toBe('https://api.getreditus.com/api/v1/payments'); + expect(body()).toEqual({ + idempotency_key: 'ev-1', + amount: 1000, + currency: 'eur', + referral_email: 'a@b.c', + }); + }); + + test('rule type wins over settings type', async () => { + await push( + { email: 'a@b.c', gr_id: 'gr_1' }, + { type: 'payment' }, + { + settings: { type: 'conversion' }, + }, + ); + expect(call()[0]).toContain('/v2/tracking/conversion'); + }); + + test('payment fields', async () => { + await push( + { + uid: 'u1', + amount: '19.99', + currency: 'USD', + subscription_id: 'sub_1', + interval: 'month', + interval_count: 3, + idempotency_key: 'pay_1', + }, + { type: 'payment' }, + ); + expect(body()).toEqual({ + idempotency_key: 'pay_1', + amount: 1999, + currency: 'usd', + referral_uid: 'u1', + subscription_id: 'sub_1', + interval: 'month', + interval_count: 3, + }); + }); + + test('payment drops an unknown interval and a non-integer count', async () => { + await push( + { uid: 'u1', amount: 5, interval: 'week', interval_count: 1.5 }, + { type: 'payment' }, + ); + expect(body()).not.toHaveProperty('interval'); + expect(body()).not.toHaveProperty('interval_count'); + }); + + test('payment needs a positive amount and a customer', async () => { + await expect(push({ uid: 'u1' }, { type: 'payment' })).rejects.toThrow( + 'positive amount', + ); + await expect(push({ amount: 5 }, { type: 'payment' })).rejects.toThrow( + 'needs uid or email', + ); + expect(mockSendServer).not.toHaveBeenCalled(); + }); + + test('409 on a conversion counts as delivered', async () => { + mockSendServer.mockRejectedValue( + new StepError('HTTP 409', { code: 'transport', status: 409 }), + ); + await expect(push({ uid: 'u1', gr_id: 'gr_1' })).resolves.toBeUndefined(); + }); + + test('404 on a payment counts as delivered', async () => { + mockSendServer.mockRejectedValue( + new StepError('HTTP 404', { code: 'transport', status: 404 }), + ); + await expect( + push({ uid: 'u1', amount: 5 }, { type: 'payment' }), + ).resolves.toBeUndefined(); + }); + + test('other errors fail the push', async () => { + mockSendServer.mockRejectedValue( + new StepError('HTTP 404', { code: 'transport', status: 404 }), + ); + await expect(push({ uid: 'u1', gr_id: 'gr_1' })).rejects.toThrow( + 'HTTP 404', + ); + mockSendServer.mockRejectedValue( + new StepError('HTTP 500', { code: 'transport', status: 500 }), + ); + await expect( + push({ uid: 'u1', amount: 5 }, { type: 'payment' }), + ).rejects.toThrow('HTTP 500'); + }); + + test('silent rule sends nothing', async () => { + await push({ uid: 'u1', gr_id: 'gr_1' }, {}, { silent: true }); + expect(mockSendServer).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/server/destinations/reditus/src/__tests__/stepExamples.test.ts b/packages/server/destinations/reditus/src/__tests__/stepExamples.test.ts new file mode 100644 index 000000000..fa13ebb39 --- /dev/null +++ b/packages/server/destinations/reditus/src/__tests__/stepExamples.test.ts @@ -0,0 +1,68 @@ +import type { WalkerOS } from '@walkeros/core'; +import { startFlow } from '@walkeros/collector'; +import { clone, isObject } from '@walkeros/core'; +import { examples } from '../dev'; +import { expectSimulationResolves } from '@walkeros/core/dev'; + +type Captured = [callable: string, ...args: unknown[]]; + +/** + * Reditus destination invokes `env.sendServer(url, body, options)` + * exactly once per push. Stateless: no init-time calls to filter. + */ +describe('Step Examples', () => { + const mockSendServer = jest.fn(); + + beforeEach(() => { + jest.clearAllMocks(); + mockSendServer.mockResolvedValue({ + data: { success: true }, + }); + }); + + // Non-public examples (silent, failures) run in the conformance test. + const published = Object.entries(examples.step).filter( + ([, example]) => example.public !== false, + ); + + it.each(published)('%s', async (_name, example) => { + const event = example.in as WalkerOS.Event; + const mapping = example.mapping; + + const testEnv = clone(examples.env.push); + testEnv.sendServer = mockSendServer; + + const dest = jest.requireActual('../').default; + const { elb } = await startFlow(); + + const mappingConfig = mapping + ? { [event.entity]: { [event.action]: mapping } } + : undefined; + + await elb('walker destination', { + code: { ...dest, env: testEnv }, + config: { + settings: { apiKey: 's3cr3t' }, + mapping: mappingConfig, + }, + }); + + await elb(event); + + const captured: Captured[] = mockSendServer.mock.calls.map( + (args) => ['sendServer', ...args] as Captured, + ); + + expect(captured).toEqual(example.out); + }); +}); + +it('declares simulation paths that resolve', () => + expectSimulationResolves(examples.env)); + +it('gives every example event a timestamp in milliseconds', () => { + for (const example of Object.values(examples.step)) { + const timestamp = isObject(example.in) ? example.in.timestamp : undefined; + expect(timestamp).toBeGreaterThan(1e12); + } +}); diff --git a/packages/server/destinations/reditus/src/config.ts b/packages/server/destinations/reditus/src/config.ts new file mode 100644 index 000000000..5d8935f9e --- /dev/null +++ b/packages/server/destinations/reditus/src/config.ts @@ -0,0 +1,17 @@ +import type { Config, Settings, PartialConfig } from './types'; +import { StepError } from '@walkeros/core'; + +export function getConfig(partialConfig: PartialConfig = {}): Config { + const settings: Partial = partialConfig.settings || {}; + const { apiKey, type } = settings; + + if (!apiKey) + throw new StepError('Config settings apiKey missing', { code: 'config' }); + if (type !== undefined && type !== 'conversion' && type !== 'payment') + throw new StepError( + 'Config settings type must be "conversion" or "payment"', + { code: 'config' }, + ); + + return { ...partialConfig, settings: { ...settings, apiKey } }; +} diff --git a/packages/server/destinations/reditus/src/dev.ts b/packages/server/destinations/reditus/src/dev.ts new file mode 100644 index 000000000..706f4127d --- /dev/null +++ b/packages/server/destinations/reditus/src/dev.ts @@ -0,0 +1,2 @@ +export * as schemas from './schemas'; +export * as examples from './examples'; diff --git a/packages/server/destinations/reditus/src/examples/env.ts b/packages/server/destinations/reditus/src/examples/env.ts new file mode 100644 index 000000000..87699b1ff --- /dev/null +++ b/packages/server/destinations/reditus/src/examples/env.ts @@ -0,0 +1,40 @@ +import type { SendDataValue, SendResponse } from '@walkeros/core'; +import type { SendServerOptions } from '@walkeros/server-core'; +import type { Env } from '../types'; + +/** + * Example environment configurations for Reditus destination + * + * These environments provide standardized mock structures for testing + * and development without requiring actual HTTP requests. + */ + +type MockSendServer = ( + url: string, + data?: SendDataValue, + options?: SendServerOptions, +) => Promise; + +/** + * Mock sendServer function that simulates successful HTTP responses + */ +const mockSendServer: MockSendServer = async () => { + // Simulate a successful Reditus API response + return { + data: { + success: true, + }, + }; +}; + +/** + * Standard mock environment for push operations + * + * Use this for testing Reditus calls without making + * actual HTTP requests to Reditus. + */ +export const push: Env = { + sendServer: mockSendServer, +}; + +export const simulation = ['sendServer']; diff --git a/packages/server/destinations/reditus/src/examples/index.ts b/packages/server/destinations/reditus/src/examples/index.ts new file mode 100644 index 000000000..181dfc860 --- /dev/null +++ b/packages/server/destinations/reditus/src/examples/index.ts @@ -0,0 +1,3 @@ +export * as env from './env'; +export * as step from './step'; +export { minimal } from './minimal'; diff --git a/packages/server/destinations/reditus/src/examples/minimal.ts b/packages/server/destinations/reditus/src/examples/minimal.ts new file mode 100644 index 000000000..524bd127b --- /dev/null +++ b/packages/server/destinations/reditus/src/examples/minimal.ts @@ -0,0 +1,10 @@ +import type { Flow } from '@walkeros/core'; + +/** + * The settings Reditus needs to deliver: the API token, read from the + * environment. + */ +export const minimal: Flow.MinimalExample = { + settings: { apiKey: 's3cr3t' }, + secrets: { apiKey: 'REDITUS_API_KEY' }, +}; diff --git a/packages/server/destinations/reditus/src/examples/step.ts b/packages/server/destinations/reditus/src/examples/step.ts new file mode 100644 index 000000000..28c9c7952 --- /dev/null +++ b/packages/server/destinations/reditus/src/examples/step.ts @@ -0,0 +1,134 @@ +import type { Flow } from '@walkeros/core'; +import { createEvent, getEvent } from '@walkeros/core'; + +/** + * Reditus step examples. + * + * At push time, the destination calls + * `env.sendServer(endpoint, JSON.stringify(body), options)` once: + * - conversion: `POST /v2/tracking/conversion` with + * `{ affiliate_slug?, advocate_slug?, email?, uid?, gr_id? }`; + * - payment: `POST /v1/payments` with `{ idempotency_key, amount + * (cents), currency, referral_uid?, referral_email?, subscription_id?, + * interval?, interval_count? }`. + * + * The test fixture pins `apiKey = 's3cr3t'` and the default url. + */ +const URL = 'https://api.getreditus.com/api'; +const OPTIONS = { + headers: { + Authorization: 'Bearer s3cr3t', + 'Content-Type': 'application/json', + }, +}; + +export const signUp: Flow.StepExample = { + title: 'Referred sign-up', + description: + 'A sign-up of a visitor who came through a Reditus link is sent as a conversion with the gr_id from the Reditus cookie.', + in: createEvent({ + name: 'user register', + id: 'ev-1700000900', + timestamp: 1700000900000, + data: { id: 'cus_42', email: 'jane@example.com', gr_id: 'gr_7f3a' }, + }), + mapping: { + data: { + map: { uid: 'data.id', email: 'data.email', gr_id: 'data.gr_id' }, + }, + }, + out: [ + [ + 'sendServer', + `${URL}/v2/tracking/conversion`, + JSON.stringify({ + email: 'jane@example.com', + uid: 'cus_42', + gr_id: 'gr_7f3a', + }), + OPTIONS, + ], + ], +}; + +export const affiliateSlug: Flow.StepExample = { + title: 'Conversion by affiliate slug', + description: + 'A demo request with the affiliate slug kept from the landing URL is sent as a conversion.', + in: createEvent({ + name: 'form submit', + id: 'ev-1700000901', + timestamp: 1700000901000, + data: { type: 'demo', email: 'jane@example.com', ref: 'partner-x' }, + }), + mapping: { + data: { map: { email: 'data.email', affiliate_slug: 'data.ref' } }, + }, + out: [ + [ + 'sendServer', + `${URL}/v2/tracking/conversion`, + JSON.stringify({ + affiliate_slug: 'partner-x', + email: 'jane@example.com', + }), + OPTIONS, + ], + ], +}; + +export const payment: Flow.StepExample = { + title: 'Payment', + description: + 'A first subscription payment of a referred customer is sent as a Reditus payment in cents, keyed by the event id.', + in: createEvent({ + name: 'subscription start', + id: 'ev-1700000902', + timestamp: 1700000902000, + data: { + customer: 'cus_42', + subscription: 'sub_9', + total: 99.9, + currency: 'EUR', + interval: 'year', + }, + }), + mapping: { + settings: { type: 'payment' }, + data: { + map: { + uid: 'data.customer', + amount: 'data.total', + currency: 'data.currency', + subscription_id: 'data.subscription', + interval: 'data.interval', + interval_count: { value: 1 }, + }, + }, + }, + out: [ + [ + 'sendServer', + `${URL}/v1/payments`, + JSON.stringify({ + idempotency_key: 'ev-1700000902', + amount: 9990, + currency: 'eur', + referral_uid: 'cus_42', + subscription_id: 'sub_9', + interval: 'year', + interval_count: 1, + }), + OPTIONS, + ], + ], +}; + +/** A silent rule sends nothing to Reditus. */ +export const silentRule: Flow.StepExample = { + public: false, + description: 'A rule with silent: true sends no request to Reditus.', + in: getEvent('page view', { timestamp: 1700000990000 }), + mapping: { silent: true }, + out: [], +}; diff --git a/packages/server/destinations/reditus/src/index.ts b/packages/server/destinations/reditus/src/index.ts new file mode 100644 index 000000000..283c32060 --- /dev/null +++ b/packages/server/destinations/reditus/src/index.ts @@ -0,0 +1,22 @@ +import type { Destination } from './types'; +import { getConfig } from './config'; +import { push } from './push'; + +// Types +export * as DestinationReditus from './types'; + +export const destinationReditus: Destination = { + type: 'reditus', + + config: {}, + + async init({ config: partialConfig }) { + return getConfig(partialConfig); + }, + + async push(event, context) { + return await push(event, context); + }, +}; + +export default destinationReditus; diff --git a/packages/server/destinations/reditus/src/push.ts b/packages/server/destinations/reditus/src/push.ts new file mode 100644 index 000000000..f025b59a2 --- /dev/null +++ b/packages/server/destinations/reditus/src/push.ts @@ -0,0 +1,124 @@ +import type { CallType, ConversionBody, PaymentBody, PushFn } from './types'; +import type { WalkerOS } from '@walkeros/core'; +import { isObject, StepError } from '@walkeros/core'; +import { sendServer } from '@walkeros/server-core'; + +const DEFAULT_URL = 'https://api.getreditus.com/api'; + +interface Call { + path: string; + body: ConversionBody | PaymentBody; + /** HTTP status that means Reditus already has, or will never have, it */ + accept: number; +} + +const text = (value: unknown): string | undefined => + typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; + +function withoutUndefined(value: T): T { + return Object.fromEntries( + Object.entries(value).filter(([, item]) => item !== undefined), + ) as T; +} + +function inputError(message: string): StepError { + return new StepError(message, { code: 'mapping', retryable: false }); +} + +function conversionCall(data: Record): Call { + const body: ConversionBody = withoutUndefined({ + affiliate_slug: text(data.affiliate_slug), + advocate_slug: text(data.advocate_slug), + email: text(data.email), + uid: text(data.uid), + gr_id: text(data.gr_id), + }); + if (!body.email && !body.uid) + throw inputError('Reditus conversion needs email or uid'); + if (!body.gr_id && !body.affiliate_slug && !body.advocate_slug) + throw inputError( + 'Reditus conversion needs gr_id, affiliate_slug or advocate_slug', + ); + // 409: the referral already exists. + return { path: '/v2/tracking/conversion', body, accept: 409 }; +} + +function paymentCall( + event: WalkerOS.Event, + data: Record, +): Call { + const amount = Number(data.amount); + if (!Number.isFinite(amount) || amount <= 0) + throw inputError('Reditus payment needs a positive amount'); + const { interval, interval_count } = data; + const body: PaymentBody = withoutUndefined({ + idempotency_key: text(data.idempotency_key) ?? String(event.id), + amount: Math.round(amount * 100), + currency: (text(data.currency) ?? 'eur').toLowerCase(), + referral_uid: text(data.uid), + referral_email: text(data.email), + subscription_id: text(data.subscription_id), + interval: + interval === 'month' || interval === 'year' ? interval : undefined, + interval_count: + typeof interval_count === 'number' && Number.isInteger(interval_count) + ? interval_count + : undefined, + }); + if (!body.referral_uid && !body.referral_email) + throw inputError('Reditus payment needs uid or email'); + // 404: no referral for this customer, nothing to credit. + return { path: '/v1/payments', body, accept: 404 }; +} + +// A silent rule has no Reditus call of its own: nothing to send. +export const push: PushFn = async function (event, context) { + if (!context.rule?.silent) await send(event, context); +}; + +const send: PushFn = async function ( + event, + { config, data, rule, env, logger }, +) { + const { + apiKey, + type: defaultType, + url = DEFAULT_URL, + } = config.settings ?? {}; + if (!apiKey) + throw new StepError('Reditus settings missing, init() not run', { + code: 'not-ready', + }); + + const type: CallType = rule?.settings?.type ?? defaultType ?? 'conversion'; + const mapped = isObject(data) ? data : {}; + const call = + type === 'payment' ? paymentCall(event, mapped) : conversionCall(mapped); + const endpoint = `${url.replace(/\/$/, '')}${call.path}`; + + logger.debug('Calling Reditus API', { + endpoint, + method: 'POST', + type, + eventId: event.id, + }); + + const sendServerFn = env?.sendServer || sendServer; + try { + await sendServerFn(endpoint, JSON.stringify(call.body), { + headers: { + Authorization: `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + }); + } catch (error) { + if (error instanceof StepError && error.status === call.accept) { + logger.debug('Reditus already has this, skipped', { + status: error.status, + eventId: event.id, + }); + return; + } + throw error; + } +}; diff --git a/packages/server/destinations/reditus/src/schemas/index.ts b/packages/server/destinations/reditus/src/schemas/index.ts new file mode 100644 index 000000000..9dcaf388d --- /dev/null +++ b/packages/server/destinations/reditus/src/schemas/index.ts @@ -0,0 +1,12 @@ +import { zodToSchema } from '@walkeros/core/dev'; +import { SettingsSchema } from './settings'; +import { MappingSchema } from './mapping'; + +export * from './primitives'; + +export { SettingsSchema, type Settings } from './settings'; +export { MappingSchema, type Mapping } from './mapping'; + +// JSON Schema +export const settings = zodToSchema(SettingsSchema); +export const mapping = zodToSchema(MappingSchema); diff --git a/packages/server/destinations/reditus/src/schemas/mapping.ts b/packages/server/destinations/reditus/src/schemas/mapping.ts new file mode 100644 index 000000000..e3719694a --- /dev/null +++ b/packages/server/destinations/reditus/src/schemas/mapping.ts @@ -0,0 +1,10 @@ +import { z } from '@walkeros/core/dev'; +import { CallTypeSchema } from './primitives'; + +export const MappingSchema = z.object({ + type: CallTypeSchema.describe( + 'Reditus call for this rule: conversion (POST /v2/tracking/conversion) or payment (POST /v1/payments). Default: settings.type, else conversion', + ).optional(), +}); + +export type Mapping = z.infer; diff --git a/packages/server/destinations/reditus/src/schemas/primitives.ts b/packages/server/destinations/reditus/src/schemas/primitives.ts new file mode 100644 index 000000000..1d4c9ce6f --- /dev/null +++ b/packages/server/destinations/reditus/src/schemas/primitives.ts @@ -0,0 +1,4 @@ +import { z } from '@walkeros/core/dev'; + +/** Reditus call: a referral conversion (sign-up, demo) or a payment. */ +export const CallTypeSchema = z.enum(['conversion', 'payment']); diff --git a/packages/server/destinations/reditus/src/schemas/settings.ts b/packages/server/destinations/reditus/src/schemas/settings.ts new file mode 100644 index 000000000..8a48697b9 --- /dev/null +++ b/packages/server/destinations/reditus/src/schemas/settings.ts @@ -0,0 +1,21 @@ +import { z } from '@walkeros/core/dev'; +import { CallTypeSchema } from './primitives'; + +export const SettingsSchema = z + .object({ + apiKey: z + .string() + .min(1) + .describe('Reditus API token, sent as Bearer token (like rds_ABC123...)'), + type: CallTypeSchema.describe( + 'Call made when the rule sets no type: conversion or payment. Default: conversion', + ).optional(), + url: z + .string() + .url() + .describe('Reditus API base URL (like https://api.getreditus.com/api)') + .optional(), + }) + .strict(); + +export type Settings = z.infer; diff --git a/packages/server/destinations/reditus/src/types/index.ts b/packages/server/destinations/reditus/src/types/index.ts new file mode 100644 index 000000000..484393a9f --- /dev/null +++ b/packages/server/destinations/reditus/src/types/index.ts @@ -0,0 +1,72 @@ +import type { + Mapping as WalkerOSMapping, + Destination as CoreDestination, +} from '@walkeros/core'; +import type { DestinationServer, sendServer } from '@walkeros/server-core'; + +export type CallType = 'conversion' | 'payment'; + +export interface Settings { + /** Reditus API token, sent as Bearer token */ + apiKey: string; + /** Call made when the rule sets no type. @default 'conversion' */ + type?: CallType; + /** API base URL. @default 'https://api.getreditus.com/api' */ + url?: string; +} + +export type InitSettings = Partial; + +export interface Mapping { + /** Reditus call for this rule: a referral conversion or a payment */ + type?: CallType; +} + +export interface Env extends DestinationServer.Env { + sendServer?: typeof sendServer; +} + +export type Types = CoreDestination.Types; + +export interface Destination extends DestinationServer.Destination { + init: DestinationServer.InitFn; +} + +export type Config = { + settings: Settings; +} & DestinationServer.Config; + +export type InitFn = DestinationServer.InitFn; +export type PushFn = DestinationServer.PushFn; + +export type PartialConfig = DestinationServer.PartialConfig; + +export type PushEvents = DestinationServer.PushEvents; + +export type Rule = WalkerOSMapping.Rule; +export type Rules = WalkerOSMapping.Rules; + +// Reditus API types +// https://docs.getreditus.com + +/** POST /v2/tracking/conversion: a referred visitor signed up */ +export interface ConversionBody { + affiliate_slug?: string; + advocate_slug?: string; + email?: string; + uid?: string; + gr_id?: string; +} + +/** POST /v1/payments: a referred customer paid */ +export interface PaymentBody { + idempotency_key: string; + /** In cents */ + amount: number; + currency: string; + referral_uid?: string; + referral_email?: string; + subscription_id?: string; + interval?: 'month' | 'year'; + interval_count?: number; +} diff --git a/packages/server/destinations/reditus/tsconfig.json b/packages/server/destinations/reditus/tsconfig.json new file mode 100644 index 000000000..b1c75c589 --- /dev/null +++ b/packages/server/destinations/reditus/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@walkeros/config/tsconfig/node.json", + "compilerOptions": { + "rootDir": "src" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/server/destinations/reditus/tsup.config.ts b/packages/server/destinations/reditus/tsup.config.ts new file mode 100644 index 000000000..0f100c52d --- /dev/null +++ b/packages/server/destinations/reditus/tsup.config.ts @@ -0,0 +1,14 @@ +import { + defineConfig, + buildModules, + buildExamples, + buildDev, +} from '@walkeros/config/tsup'; + +export default defineConfig([ + buildModules({ + terserOptions: { mangle: false }, + }), + buildExamples(), + buildDev(), +]); diff --git a/website/docs/destinations/index.mdx b/website/docs/destinations/index.mdx index 4351459f1..ada0e0832 100644 --- a/website/docs/destinations/index.mdx +++ b/website/docs/destinations/index.mdx @@ -106,6 +106,7 @@ destination batches answer `queued` until the flush. | Meta | Meta Pixel | Meta Conversions API | | Pinterest | Pinterest Tag | Pinterest Conversions API | | Reddit | - | Reddit Conversions API | +| Reditus | - | Reditus affiliate conversions | | Slack | - | Slack | | Snapchat | - | Snapchat Conversions API | | TikTok | TikTok Pixel | TikTok Events API | diff --git a/website/docs/destinations/server/reditus.mdx b/website/docs/destinations/server/reditus.mdx new file mode 100644 index 000000000..f748d2395 --- /dev/null +++ b/website/docs/destinations/server/reditus.mdx @@ -0,0 +1,79 @@ +--- +title: Reditus +description: "Server-side referral conversions and payments to the Reditus affiliate platform" +path: /docs/destinations/server/reditus +sidebar_position: 19 +package: '@walkeros/server-destination-reditus' +--- +import data from '@walkeros/server-destination-reditus/walkerOS.json'; +import Configuration from '@site/src/components/snippets/_configuration.mdx'; +import Quickstart from '@site/src/components/snippets/_quickstart.mdx'; + +import WhereThisFits from '@site/src/components/snippets/_where-this-fits.mdx'; + +# Reditus + + + +Server-side delivery to [Reditus](https://www.getreditus.com), the affiliate and referral platform: a sign-up or demo of a referred visitor becomes a referral conversion, and a referred customer's payment is credited to the partner. + +Reditus is a server destination in the walkerOS flow:} + flowMap={{ + destinations: { default: { label: 'Destination', text: 'Reditus', highlight: true } }, + }} + post={<>Sends one request per event to the Reditus API with the API token as Bearer token, using raw HTTP (no SDK): a conversion or a payment, chosen per rule.} +/> + +## Installation + + + + + +## Calls + +Each rule picks its call with `settings.type`; without it, `settings.type` of the destination applies, else `conversion`. + +| Type | Reditus call | Mapped `data` | +|---|---|---| +| `conversion` | `POST /v2/tracking/conversion` | `email` or `uid`, plus at least one of `gr_id` (the Reditus script's cookie), `affiliate_slug`, `advocate_slug` | +| `payment` | `POST /v1/payments` | `uid` or `email` (sent as `referral_uid`, `referral_email`), `amount` in currency units (sent in cents), `currency` (default `eur`, lowercased), optional `subscription_id`, `interval` (`month` or `year`), `interval_count`, `idempotency_key` (default: the walkerOS event id) | + + + +The `gr_id` cookie and the affiliate slug from the landing URL live in the browser: carry them to the server event (as `globals`, or from your app) so the conversion can be attributed. A visitor who came without a Reditus link has none of them: filter such events with a mapping `condition` instead of letting them fail. + +## Consent + +The quickstart sets no `config.consent`, so Reditus receives every event, whatever consent the event carries. Add `consent: { marketing: true }` to `config`, next to `settings`, to send only events with marketing consent (see [Gate a destination with consent](/docs/guides/consent#gate-a-destination-with-consent)). + +## Failures + +- Reditus answers `409` to a conversion whose referral already exists and `404` to a payment of a customer who was never referred: both count as delivered, with one DEBUG line. +- A conversion without `email`/`uid` or without a referral identifier, and a payment without a positive `amount` or without `uid`/`email`, fail with the code `mapping`, marked not retryable, and nothing is sent. +- Any other response outside the 2xx range, a network error or no answer within 5 seconds fails with `transport` (with the HTTP status) or `timeout`, and the event goes to the dead-letter queue. 429 and 5xx are marked retryable, other 4xx not; nothing resends the event by itself. +- Without `apiKey`, or with a `type` other than `conversion` or `payment`, the destination does not start: every push answers `failed` with the code `config`. +- A rule with `silent: true` sends nothing. + +## Links + +- [Reditus API documentation](https://docs.getreditus.com) diff --git a/website/package.json b/website/package.json index 9999364b6..660c23efa 100644 --- a/website/package.json +++ b/website/package.json @@ -47,6 +47,7 @@ "@walkeros/server-destination-piwikpro": "^4.9.0", "@walkeros/server-destination-posthog": "^4.9.0", "@walkeros/server-destination-reddit": "^4.9.0", + "@walkeros/server-destination-reditus": "^4.9.0", "@walkeros/server-destination-redis": "^4.9.0", "@walkeros/server-destination-rudderstack": "^4.9.0", "@walkeros/server-destination-segment": "^4.9.0", diff --git a/website/sidebars.ts b/website/sidebars.ts index 5696f2b85..b5f5a78d6 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -561,6 +561,11 @@ const sidebars: SidebarsConfig = { id: 'destinations/server/kafka', className: 'sidebar-badge-server', }, + { + type: 'doc', + id: 'destinations/server/reditus', + className: 'sidebar-badge-server', + }, { type: 'doc', id: 'destinations/server/redis',