@paid-ai/paid-node 0.4.1 → 0.5.0-alpha2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/cjs/Client.js +2 -2
  2. package/dist/cjs/index.d.ts +1 -0
  3. package/dist/cjs/index.js +2 -1
  4. package/dist/cjs/integrations/adapters/nextjs/base-adapter.d.ts +10 -0
  5. package/dist/cjs/integrations/adapters/nextjs/base-adapter.js +58 -0
  6. package/dist/cjs/integrations/adapters/nextjs/index.d.ts +5 -0
  7. package/dist/cjs/integrations/adapters/nextjs/index.js +17 -0
  8. package/dist/cjs/integrations/adapters/nextjs/routes.d.ts +225 -0
  9. package/dist/cjs/integrations/adapters/nextjs/routes.js +246 -0
  10. package/dist/cjs/integrations/client.d.ts +49 -0
  11. package/dist/cjs/integrations/client.js +93 -0
  12. package/dist/cjs/integrations/controllers/billing.d.ts +196 -0
  13. package/dist/cjs/integrations/controllers/billing.js +267 -0
  14. package/dist/cjs/integrations/controllers/contacts.d.ts +66 -0
  15. package/dist/cjs/integrations/controllers/contacts.js +145 -0
  16. package/dist/cjs/integrations/controllers/customers.d.ts +96 -0
  17. package/dist/cjs/integrations/controllers/customers.js +206 -0
  18. package/dist/cjs/integrations/controllers/index.d.ts +6 -0
  19. package/dist/cjs/integrations/controllers/index.js +30 -0
  20. package/dist/cjs/integrations/controllers/invoices.d.ts +40 -0
  21. package/dist/cjs/integrations/controllers/invoices.js +72 -0
  22. package/dist/cjs/integrations/controllers/orders.d.ts +72 -0
  23. package/dist/cjs/integrations/controllers/orders.js +194 -0
  24. package/dist/cjs/integrations/controllers/provision-users.d.ts +62 -0
  25. package/dist/cjs/integrations/controllers/provision-users.js +130 -0
  26. package/dist/cjs/integrations/index.d.ts +29 -0
  27. package/dist/cjs/integrations/index.js +44 -0
  28. package/dist/cjs/integrations/types.d.ts +119 -0
  29. package/dist/cjs/integrations/types.js +2 -0
  30. package/dist/cjs/integrations/utils/api-fetch.d.ts +18 -0
  31. package/dist/cjs/integrations/utils/api-fetch.js +53 -0
  32. package/dist/cjs/integrations/utils/base-handler.d.ts +79 -0
  33. package/dist/cjs/integrations/utils/base-handler.js +168 -0
  34. package/dist/cjs/integrations/utils/create-adapter.d.ts +29 -0
  35. package/dist/cjs/integrations/utils/create-adapter.js +56 -0
  36. package/dist/cjs/version.d.ts +1 -1
  37. package/dist/cjs/version.js +1 -1
  38. package/dist/esm/Client.mjs +2 -2
  39. package/dist/esm/index.d.mts +1 -0
  40. package/dist/esm/index.mjs +1 -0
  41. package/dist/esm/integrations/adapters/nextjs/base-adapter.d.mts +10 -0
  42. package/dist/esm/integrations/adapters/nextjs/base-adapter.mjs +55 -0
  43. package/dist/esm/integrations/adapters/nextjs/index.d.mts +5 -0
  44. package/dist/esm/integrations/adapters/nextjs/index.mjs +5 -0
  45. package/dist/esm/integrations/adapters/nextjs/routes.d.mts +225 -0
  46. package/dist/esm/integrations/adapters/nextjs/routes.mjs +235 -0
  47. package/dist/esm/integrations/client.d.mts +49 -0
  48. package/dist/esm/integrations/client.mjs +89 -0
  49. package/dist/esm/integrations/controllers/billing.d.mts +196 -0
  50. package/dist/esm/integrations/controllers/billing.mjs +259 -0
  51. package/dist/esm/integrations/controllers/contacts.d.mts +66 -0
  52. package/dist/esm/integrations/controllers/contacts.mjs +140 -0
  53. package/dist/esm/integrations/controllers/customers.d.mts +96 -0
  54. package/dist/esm/integrations/controllers/customers.mjs +199 -0
  55. package/dist/esm/integrations/controllers/index.d.mts +6 -0
  56. package/dist/esm/integrations/controllers/index.mjs +6 -0
  57. package/dist/esm/integrations/controllers/invoices.d.mts +40 -0
  58. package/dist/esm/integrations/controllers/invoices.mjs +68 -0
  59. package/dist/esm/integrations/controllers/orders.d.mts +72 -0
  60. package/dist/esm/integrations/controllers/orders.mjs +189 -0
  61. package/dist/esm/integrations/controllers/provision-users.d.mts +62 -0
  62. package/dist/esm/integrations/controllers/provision-users.mjs +126 -0
  63. package/dist/esm/integrations/index.d.mts +29 -0
  64. package/dist/esm/integrations/index.mjs +28 -0
  65. package/dist/esm/integrations/types.d.mts +119 -0
  66. package/dist/esm/integrations/types.mjs +1 -0
  67. package/dist/esm/integrations/utils/api-fetch.d.mts +18 -0
  68. package/dist/esm/integrations/utils/api-fetch.mjs +50 -0
  69. package/dist/esm/integrations/utils/base-handler.d.mts +79 -0
  70. package/dist/esm/integrations/utils/base-handler.mjs +164 -0
  71. package/dist/esm/integrations/utils/create-adapter.d.mts +29 -0
  72. package/dist/esm/integrations/utils/create-adapter.mjs +53 -0
  73. package/dist/esm/version.d.mts +1 -1
  74. package/dist/esm/version.mjs +1 -1
  75. package/package.json +32 -3
@@ -0,0 +1,199 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { createHandler } from "../utils/base-handler.mjs";
11
+ /**
12
+ * Generate placeholder values for missing customer fields
13
+ * Creates valid but fake data for rapid prototyping
14
+ */
15
+ function generateCustomerDefaults(data) {
16
+ var _a, _b, _c, _d, _e, _f;
17
+ const timestamp = Date.now();
18
+ const randomId = Math.random().toString(36).substring(7);
19
+ const email = data.email || `user_${timestamp}@example.com`;
20
+ const name = data.name || `User ${randomId}`;
21
+ const nameParts = name.split(" ");
22
+ const firstName = data.firstName || nameParts[0] || "Joe";
23
+ const lastName = data.lastName || nameParts.slice(1).join(" ") || "Bloggs";
24
+ const billingAddress = {
25
+ line1: ((_a = data.billingAddress) === null || _a === void 0 ? void 0 : _a.line1) || "123 Placeholder Street",
26
+ line2: ((_b = data.billingAddress) === null || _b === void 0 ? void 0 : _b.line2) || "",
27
+ city: ((_c = data.billingAddress) === null || _c === void 0 ? void 0 : _c.city) || "London",
28
+ state: ((_d = data.billingAddress) === null || _d === void 0 ? void 0 : _d.state) || "London",
29
+ zipCode: ((_e = data.billingAddress) === null || _e === void 0 ? void 0 : _e.zipCode) || "SW1A 1AA",
30
+ country: ((_f = data.billingAddress) === null || _f === void 0 ? void 0 : _f.country) || "UK",
31
+ };
32
+ return {
33
+ externalId: data.externalId,
34
+ email,
35
+ name,
36
+ firstName,
37
+ lastName,
38
+ company: data.company || "",
39
+ phone: data.phone || "",
40
+ billingAddress,
41
+ metadata: data.metadata || {},
42
+ };
43
+ }
44
+ /**
45
+ * Internal helper to create a customer
46
+ */
47
+ function createCustomerInternal(client, data) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ const customer = yield client.customers.create({
50
+ externalId: data.externalId,
51
+ name: data.name,
52
+ billingAddress: {
53
+ line1: data.billingAddress.line1,
54
+ line2: data.billingAddress.line2,
55
+ city: data.billingAddress.city,
56
+ state: data.billingAddress.state,
57
+ zipCode: data.billingAddress.zipCode,
58
+ country: data.billingAddress.country,
59
+ },
60
+ });
61
+ if (!customer.id) {
62
+ throw new Error("Customer created but missing ID");
63
+ }
64
+ return {
65
+ id: customer.id,
66
+ externalId: data.externalId,
67
+ };
68
+ });
69
+ }
70
+ /**
71
+ * Create a customer with defaults for missing fields
72
+ *
73
+ * This helper generates reasonable placeholder values for any missing data,
74
+ * making it easy to create customers for prototyping and development.
75
+ *
76
+ * @param client - PaidClient instance
77
+ * @param data - Customer data (only externalId is required)
78
+ * @returns Created customer with ID
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const customer = await createCustomerWithDefaults(client, {
83
+ * externalId: 'user-123',
84
+ * email: 'user@example.com'
85
+ * });
86
+ * // Generates: name, address, etc.
87
+ * ```
88
+ */
89
+ export function createCustomerWithDefaults(client, data) {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ const completeData = generateCustomerDefaults(data);
92
+ return createCustomerInternal(client, completeData);
93
+ });
94
+ }
95
+ /**
96
+ * Create a customer with explicit data (NO defaults applied)
97
+ *
98
+ * Required fields: externalId, name, email, and complete billingAddress
99
+ * (line1, line2, city, state, zipCode, country)
100
+ *
101
+ * Use createCustomerWithDefaults() if you want automatic default values for missing fields.
102
+ *
103
+ * @param client - PaidClient instance
104
+ * @param data - Complete customer data with ALL required fields
105
+ * @returns Created customer with ID
106
+ * @throws Error if any required fields are missing
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const customer = await createCustomer(client, {
111
+ * externalId: 'user-123',
112
+ * email: 'user@example.com',
113
+ * name: 'John Doe',
114
+ * billingAddress: {
115
+ * line1: '123 Main St',
116
+ * line2: '',
117
+ * city: 'San Francisco',
118
+ * state: 'CA',
119
+ * zipCode: '94105',
120
+ * country: 'US'
121
+ * }
122
+ * });
123
+ * ```
124
+ */
125
+ export function createCustomer(client, data) {
126
+ return __awaiter(this, void 0, void 0, function* () {
127
+ return createCustomerInternal(client, data);
128
+ });
129
+ }
130
+ /**
131
+ * Create a framework-agnostic handler for customer creation
132
+ *
133
+ * This handler can be used with any framework adapter.
134
+ *
135
+ * @returns Handler function
136
+ */
137
+ export function createCustomersHandler() {
138
+ return createHandler((client, body) => __awaiter(this, void 0, void 0, function* () {
139
+ if (!body.externalId) {
140
+ throw new Error("externalId is required");
141
+ }
142
+ const customer = yield createCustomerWithDefaults(client, body);
143
+ return { success: true, data: customer };
144
+ }), { requiredFields: ['externalId'] });
145
+ }
146
+ /**
147
+ * Get a customer by external ID
148
+ *
149
+ * @param client - PaidClient instance
150
+ * @param customerExternalId - Customer's external ID
151
+ * @returns Customer data
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * const customer = await getCustomer(client, 'user-123');
156
+ * console.log(customer.name, customer.email);
157
+ * ```
158
+ */
159
+ export function getCustomer(client, customerExternalId) {
160
+ return __awaiter(this, void 0, void 0, function* () {
161
+ const customer = yield client.customers.getByExternalId(customerExternalId);
162
+ return customer;
163
+ });
164
+ }
165
+ /**
166
+ * Create a framework-agnostic handler for fetching a customer by external ID
167
+ *
168
+ * This handler can be used with any framework adapter.
169
+ * The customer external ID should be provided either in params or query string.
170
+ *
171
+ * @returns Handler function
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * // In Next.js route: /api/customers/[customerExternalId]/route.ts
176
+ * import { createGetCustomerHandler } from '@paid-ai/paid-node/integrations';
177
+ * import { nextjsAdapter } from '@paid-ai/paid-node/integrations/nextjs';
178
+ *
179
+ * const handler = createGetCustomerHandler();
180
+ * export const GET = nextjsAdapter(handler);
181
+ * ```
182
+ */
183
+ export function createGetCustomerHandler() {
184
+ return createHandler((client, _body, params) => __awaiter(this, void 0, void 0, function* () {
185
+ const customerExternalId = params === null || params === void 0 ? void 0 : params.customerExternalId;
186
+ if (!customerExternalId) {
187
+ return {
188
+ success: false,
189
+ error: "customerExternalId is required",
190
+ status: 400,
191
+ };
192
+ }
193
+ const customer = yield getCustomer(client, customerExternalId);
194
+ return { success: true, data: customer };
195
+ }), {
196
+ allowedMethods: ['GET'],
197
+ requireOrganizationId: false,
198
+ });
199
+ }
@@ -0,0 +1,6 @@
1
+ export { createCustomer, createCustomerWithDefaults, getCustomer, createGetCustomerHandler, createCustomersHandler, } from "./customers.mjs";
2
+ export { createContact, createContactWithDefaults, createContactsHandler, } from "./contacts.mjs";
3
+ export { createOrder, createOrderWithDefaults, createOrdersHandler, } from "./orders.mjs";
4
+ export { payInvoice, createPayInvoiceHandler, type PayInvoiceConfig, type PayInvoiceRequest, type PayInvoiceResult, activateOrderSync, createActivateOrderSyncHandler, type ActivateOrderSyncConfig, type ActivateOrderSyncRequest, type ActivateOrderSyncResult, createSetupIntent, createSetupIntentHandler, type SetupIntentConfig, type SetupIntentRequest, type SetupIntentResponse, } from "./billing.mjs";
5
+ export { getCustomerInvoices, createCustomerInvoicesHandler, type CustomerInvoicesResult, } from "./invoices.mjs";
6
+ export { provisionNewUser, createProvisioningHandler, } from "./provision-users.mjs";
@@ -0,0 +1,6 @@
1
+ export { createCustomer, createCustomerWithDefaults, getCustomer, createGetCustomerHandler, createCustomersHandler, } from "./customers.mjs";
2
+ export { createContact, createContactWithDefaults, createContactsHandler, } from "./contacts.mjs";
3
+ export { createOrder, createOrderWithDefaults, createOrdersHandler, } from "./orders.mjs";
4
+ export { payInvoice, createPayInvoiceHandler, activateOrderSync, createActivateOrderSyncHandler, createSetupIntent, createSetupIntentHandler, } from "./billing.mjs";
5
+ export { getCustomerInvoices, createCustomerInvoicesHandler, } from "./invoices.mjs";
6
+ export { provisionNewUser, createProvisioningHandler, } from "./provision-users.mjs";
@@ -0,0 +1,40 @@
1
+ import { PayInvoiceConfig } from "./billing.mjs";
2
+ export interface CustomerInvoicesResult {
3
+ data: any[];
4
+ }
5
+ /**
6
+ * Get customer invoices
7
+ * Fetches all invoices for a customer by their external ID.
8
+ *
9
+ * @param config - API configuration with organization context
10
+ * @param customerExternalId - Customer's external ID
11
+ * @returns Customer invoices
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const result = await getCustomerInvoices(
16
+ * {
17
+ * apiUrl: 'https://api.agentpaid.io',
18
+ * apiKey: process.env.PAID_API_KEY,
19
+ * organizationId: 'org_123'
20
+ * },
21
+ * 'user-123'
22
+ * );
23
+ *
24
+ * console.log(`Found ${result.data.length} invoices`);
25
+ * ```
26
+ */
27
+ export declare function getCustomerInvoices(config: PayInvoiceConfig, customerExternalId: string): Promise<CustomerInvoicesResult>;
28
+ interface CustomerInvoicesRequest {
29
+ customerExternalId: string;
30
+ }
31
+ /**
32
+ * Create a framework-agnostic handler for fetching customer invoices
33
+ *
34
+ * This handler can be used with any framework adapter.
35
+ * Organization ID is automatically fetched from the API key.
36
+ *
37
+ * @returns Handler function
38
+ */
39
+ export declare function createCustomerInvoicesHandler(): (request: import("../utils/base-handler.mjs").BaseRequestContext<CustomerInvoicesRequest, Record<string, string>>, response: import("../utils/base-handler.mjs").BaseResponseContext, config?: import("../utils/base-handler.mjs").BaseHandlerConfig) => Promise<any>;
40
+ export {};
@@ -0,0 +1,68 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { paidApiFetch } from "../utils/api-fetch.mjs";
11
+ import { createHandler } from "../utils/base-handler.mjs";
12
+ /**
13
+ * Get customer invoices
14
+ * Fetches all invoices for a customer by their external ID.
15
+ *
16
+ * @param config - API configuration with organization context
17
+ * @param customerExternalId - Customer's external ID
18
+ * @returns Customer invoices
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * const result = await getCustomerInvoices(
23
+ * {
24
+ * apiUrl: 'https://api.agentpaid.io',
25
+ * apiKey: process.env.PAID_API_KEY,
26
+ * organizationId: 'org_123'
27
+ * },
28
+ * 'user-123'
29
+ * );
30
+ *
31
+ * console.log(`Found ${result.data.length} invoices`);
32
+ * ```
33
+ */
34
+ export function getCustomerInvoices(config, customerExternalId) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ if (!customerExternalId) {
37
+ throw new Error("customerExternalId is required");
38
+ }
39
+ const data = yield paidApiFetch(config, `/api/organizations/${config.organizationId}/customer/external/${customerExternalId}/invoices`, { method: "GET" });
40
+ return { data: data.data || data || [] };
41
+ });
42
+ }
43
+ /**
44
+ * Create a framework-agnostic handler for fetching customer invoices
45
+ *
46
+ * This handler can be used with any framework adapter.
47
+ * Organization ID is automatically fetched from the API key.
48
+ *
49
+ * @returns Handler function
50
+ */
51
+ export function createCustomerInvoicesHandler() {
52
+ return createHandler((_client, _body, params, organizationId) => __awaiter(this, void 0, void 0, function* () {
53
+ if (!organizationId) {
54
+ return { success: false, error: 'Organization ID not found', status: 500 };
55
+ }
56
+ const customerExternalId = params === null || params === void 0 ? void 0 : params.customerExternalId;
57
+ if (!customerExternalId) {
58
+ return { success: false, error: 'customerExternalId is required', status: 400 };
59
+ }
60
+ const apiKey = process.env.PAID_API_KEY || '';
61
+ const apiUrl = process.env.PAID_API_URL || 'https://api.agentpaid.io';
62
+ const result = yield getCustomerInvoices({ apiUrl, apiKey, organizationId }, customerExternalId);
63
+ return {
64
+ success: true,
65
+ data: result.data,
66
+ };
67
+ }), { allowedMethods: ['GET'], requireOrganizationId: true });
68
+ }
@@ -0,0 +1,72 @@
1
+ import type { PaidClient } from "../../Client.mjs";
2
+ import type { OrderConfig, OrderCreationResult, OrderOptions } from "../types.mjs";
3
+ /**
4
+ * Create an order with defaults for missing fields
5
+ *
6
+ * This helper generates reasonable defaults for dates, names, and other fields,
7
+ * making it easy to create orders for prototyping and development.
8
+ *
9
+ * @param client - PaidClient instance
10
+ * @param config - Order configuration (customerId, customerExternalId, agentExternalId required)
11
+ * @param options - Additional options for order creation
12
+ * @returns Created order with ID
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const order = await createOrderWithDefaults(client, {
17
+ * customerId: 'cus_123',
18
+ * customerExternalId: 'user-123',
19
+ * agentExternalId: 'agent-prod'
20
+ * });
21
+ * // Generates: startDate, endDate (1 year), name, description, currency (USD)
22
+ * ```
23
+ */
24
+ export declare function createOrderWithDefaults(client: PaidClient, config: OrderConfig, options?: OrderOptions): Promise<OrderCreationResult>;
25
+ /**
26
+ * Create an order with explicit configuration (NO defaults applied)
27
+ *
28
+ * Required fields: customerId, customerExternalId, agentExternalId, name, description,
29
+ * startDate, endDate, currency, orderLines
30
+ *
31
+ * Use createOrderWithDefaults() if you want automatic default values for missing fields.
32
+ *
33
+ * @param client - PaidClient instance
34
+ * @param config - Complete order configuration with ALL required fields
35
+ * @param options - Additional options for order creation
36
+ * @returns Created order with ID
37
+ * @throws Error if any required fields are missing
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const order = await createOrder(client, {
42
+ * customerId: 'cus_123',
43
+ * customerExternalId: 'user-123',
44
+ * billingContactId: 'contact_123',
45
+ * agentExternalId: 'agent-prod',
46
+ * name: 'Pro Plan Subscription',
47
+ * description: 'Monthly subscription to Pro plan',
48
+ * startDate: '2024-01-01',
49
+ * endDate: '2025-01-01',
50
+ * currency: 'USD',
51
+ * orderLines: [{
52
+ * agentExternalId: 'agent-prod',
53
+ * name: 'Pro Plan',
54
+ * description: 'Pro plan features'
55
+ * }]
56
+ * }, { autoActivate: true });
57
+ * ```
58
+ */
59
+ export declare function createOrder(client: PaidClient, config: Required<OrderConfig>, options?: OrderOptions): Promise<OrderCreationResult>;
60
+ interface OrderRequest extends OrderConfig {
61
+ autoActivate?: boolean;
62
+ }
63
+ /**
64
+ * Create a framework-agnostic handler for order creation
65
+ *
66
+ * This handler can be used with any framework adapter.
67
+ *
68
+ * @param helperOptions - Default options for order creation
69
+ * @returns Handler function
70
+ */
71
+ export declare function createOrdersHandler(helperOptions?: OrderOptions): (request: import("../utils/base-handler.mjs").BaseRequestContext<OrderRequest, Record<string, string>>, response: import("../utils/base-handler.mjs").BaseResponseContext, config?: import("../utils/base-handler.mjs").BaseHandlerConfig) => Promise<any>;
72
+ export {};
@@ -0,0 +1,189 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { createHandler } from "../utils/base-handler.mjs";
11
+ /**
12
+ * Generate default values for missing order fields
13
+ */
14
+ function generateOrderDefaults(config, options = {}) {
15
+ var _a;
16
+ const { defaultDurationDays = 365 } = options;
17
+ const startDate = config.startDate || new Date().toISOString().split("T")[0];
18
+ const endDate = config.endDate ||
19
+ new Date(Date.now() + defaultDurationDays * 24 * 60 * 60 * 1000)
20
+ .toISOString()
21
+ .split("T")[0];
22
+ const name = config.name || "Subscription Order";
23
+ const description = config.description || "Annual subscription";
24
+ const currency = config.currency || "USD";
25
+ const orderLines = ((_a = config.orderLines) === null || _a === void 0 ? void 0 : _a.map(line => ({
26
+ agentExternalId: line.agentExternalId,
27
+ name: line.name || name,
28
+ description: line.description || description,
29
+ }))) || [{
30
+ agentExternalId: config.agentExternalId,
31
+ name,
32
+ description,
33
+ }];
34
+ return {
35
+ customerId: config.customerId,
36
+ customerExternalId: config.customerExternalId,
37
+ billingContactId: config.billingContactId,
38
+ agentExternalId: config.agentExternalId,
39
+ name,
40
+ description,
41
+ startDate,
42
+ endDate,
43
+ currency,
44
+ orderLines,
45
+ };
46
+ }
47
+ /**
48
+ * Internal helper to create and optionally activate an order
49
+ */
50
+ function createAndActivateOrder(client, config, autoActivate) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ const order = yield client.orders.create({
53
+ customerId: config.customerId,
54
+ customerExternalId: config.customerExternalId,
55
+ billingContactId: config.billingContactId,
56
+ name: config.name,
57
+ description: config.description,
58
+ startDate: config.startDate,
59
+ endDate: config.endDate,
60
+ currency: config.currency,
61
+ orderLines: config.orderLines.map(line => {
62
+ const orderLine = { agentExternalId: line.agentExternalId };
63
+ if (line.name)
64
+ orderLine.name = line.name;
65
+ if (line.description)
66
+ orderLine.description = line.description;
67
+ return orderLine;
68
+ }),
69
+ });
70
+ if (!order.id) {
71
+ throw new Error("Order created but missing ID");
72
+ }
73
+ if (autoActivate && order.creationState === "draft") {
74
+ try {
75
+ yield client.orders.activate(order.id);
76
+ return {
77
+ id: order.id,
78
+ creationState: "active",
79
+ };
80
+ }
81
+ catch (activationError) {
82
+ console.error(`Error activating order ${order.id}:`, activationError instanceof Error
83
+ ? activationError.message
84
+ : "Unknown error");
85
+ return {
86
+ id: order.id,
87
+ creationState: order.creationState,
88
+ };
89
+ }
90
+ }
91
+ return {
92
+ id: order.id,
93
+ creationState: order.creationState,
94
+ };
95
+ });
96
+ }
97
+ /**
98
+ * Create an order with defaults for missing fields
99
+ *
100
+ * This helper generates reasonable defaults for dates, names, and other fields,
101
+ * making it easy to create orders for prototyping and development.
102
+ *
103
+ * @param client - PaidClient instance
104
+ * @param config - Order configuration (customerId, customerExternalId, agentExternalId required)
105
+ * @param options - Additional options for order creation
106
+ * @returns Created order with ID
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const order = await createOrderWithDefaults(client, {
111
+ * customerId: 'cus_123',
112
+ * customerExternalId: 'user-123',
113
+ * agentExternalId: 'agent-prod'
114
+ * });
115
+ * // Generates: startDate, endDate (1 year), name, description, currency (USD)
116
+ * ```
117
+ */
118
+ export function createOrderWithDefaults(client_1, config_1) {
119
+ return __awaiter(this, arguments, void 0, function* (client, config, options = {}) {
120
+ const { autoActivate = true } = options;
121
+ const completeConfig = generateOrderDefaults(config, options);
122
+ return createAndActivateOrder(client, completeConfig, autoActivate);
123
+ });
124
+ }
125
+ /**
126
+ * Create an order with explicit configuration (NO defaults applied)
127
+ *
128
+ * Required fields: customerId, customerExternalId, agentExternalId, name, description,
129
+ * startDate, endDate, currency, orderLines
130
+ *
131
+ * Use createOrderWithDefaults() if you want automatic default values for missing fields.
132
+ *
133
+ * @param client - PaidClient instance
134
+ * @param config - Complete order configuration with ALL required fields
135
+ * @param options - Additional options for order creation
136
+ * @returns Created order with ID
137
+ * @throws Error if any required fields are missing
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * const order = await createOrder(client, {
142
+ * customerId: 'cus_123',
143
+ * customerExternalId: 'user-123',
144
+ * billingContactId: 'contact_123',
145
+ * agentExternalId: 'agent-prod',
146
+ * name: 'Pro Plan Subscription',
147
+ * description: 'Monthly subscription to Pro plan',
148
+ * startDate: '2024-01-01',
149
+ * endDate: '2025-01-01',
150
+ * currency: 'USD',
151
+ * orderLines: [{
152
+ * agentExternalId: 'agent-prod',
153
+ * name: 'Pro Plan',
154
+ * description: 'Pro plan features'
155
+ * }]
156
+ * }, { autoActivate: true });
157
+ * ```
158
+ */
159
+ export function createOrder(client_1, config_1) {
160
+ return __awaiter(this, arguments, void 0, function* (client, config, options = {}) {
161
+ const { autoActivate = true } = options;
162
+ return createAndActivateOrder(client, config, autoActivate);
163
+ });
164
+ }
165
+ /**
166
+ * Create a framework-agnostic handler for order creation
167
+ *
168
+ * This handler can be used with any framework adapter.
169
+ *
170
+ * @param helperOptions - Default options for order creation
171
+ * @returns Handler function
172
+ */
173
+ export function createOrdersHandler(helperOptions) {
174
+ return createHandler((client, body) => __awaiter(this, void 0, void 0, function* () {
175
+ var _a, _b;
176
+ if (!body.customerId) {
177
+ throw new Error("customerId is required");
178
+ }
179
+ if (!body.customerExternalId) {
180
+ throw new Error("customerExternalId is required");
181
+ }
182
+ if (!body.agentExternalId) {
183
+ throw new Error("agentExternalId is required");
184
+ }
185
+ const orderOptions = Object.assign(Object.assign({}, helperOptions), { autoActivate: (_b = (_a = body.autoActivate) !== null && _a !== void 0 ? _a : helperOptions === null || helperOptions === void 0 ? void 0 : helperOptions.autoActivate) !== null && _b !== void 0 ? _b : true });
186
+ const order = yield createOrderWithDefaults(client, body, orderOptions);
187
+ return { success: true, data: order };
188
+ }), { requiredFields: ['customerId', 'customerExternalId', 'agentExternalId'] });
189
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Provisioning helpers for Paid SDK
3
+ * Orchestrates customer + contact + order creation in one operation
4
+ */
5
+ import type { PaidClient } from "../../Client.mjs";
6
+ import type { OrderOptions, ProvisioningConfig, ProvisioningResult } from "../types.mjs";
7
+ /**
8
+ * Provision a new user with customer, contact, and optionally order
9
+ *
10
+ * This is a high-level helper that orchestrates the creation of all
11
+ * necessary Paid entities for a new user in one operation.
12
+ *
13
+ * @param client - PaidClient instance
14
+ * @param config - Provisioning configuration
15
+ * @returns Result with created customer, contact, and optional order
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const result = await provisionNewUser(client, {
20
+ * customer: {
21
+ * externalId: 'user-123',
22
+ * email: 'user@example.com'
23
+ * },
24
+ * agentExternalId: 'agent-prod'
25
+ * });
26
+ * // Creates customer, contact, and order with defaults
27
+ * ```
28
+ */
29
+ export declare function provisionNewUser(client: PaidClient, config: ProvisioningConfig): Promise<ProvisioningResult>;
30
+ /**
31
+ * Create a framework-agnostic handler for user provisioning
32
+ *
33
+ * This handler can be used with any framework adapter.
34
+ * Accepts partial provisioning configuration and fills in defaults for missing fields.
35
+ *
36
+ * @param orderOptions - Optional default order creation options
37
+ * @param defaultAgentExternalId - Optional default agent external ID
38
+ * @returns Handler function
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // Minimal - just externalId and email
43
+ * {
44
+ * customer: { externalId: 'org-123', email: 'user@example.com' }
45
+ * }
46
+ *
47
+ * // With full customer data
48
+ * {
49
+ * customer: {
50
+ * externalId: 'org-123',
51
+ * email: 'user@example.com',
52
+ * name: 'Acme Corp',
53
+ * billingAddress: { line1: '123 Main St', city: 'NYC', ... }
54
+ * },
55
+ * contact: {
56
+ * firstName: 'John',
57
+ * lastName: 'Doe'
58
+ * }
59
+ * }
60
+ * ```
61
+ */
62
+ export declare function createProvisioningHandler(orderOptions?: OrderOptions, defaultAgentExternalId?: string): (request: import("../utils/base-handler.mjs").BaseRequestContext<Partial<ProvisioningConfig>, Record<string, string>>, response: import("../utils/base-handler.mjs").BaseResponseContext, config?: import("../utils/base-handler.mjs").BaseHandlerConfig) => Promise<any>;