@teleporthq/teleport-plugin-next-workflows 0.44.5 → 0.44.7
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.
- package/__tests__/credential-columns-reply.test.ts +286 -0
- package/__tests__/invoice-paid-status.test.ts +382 -0
- package/__tests__/invoice-tender.test.ts +5 -3
- package/dist/cjs/api-route-generator.d.ts.map +1 -1
- package/dist/cjs/api-route-generator.js +3 -2
- package/dist/cjs/api-route-generator.js.map +1 -1
- package/dist/cjs/credential-columns-code.d.ts +17 -0
- package/dist/cjs/credential-columns-code.d.ts.map +1 -0
- package/dist/cjs/credential-columns-code.js +61 -0
- package/dist/cjs/credential-columns-code.js.map +1 -0
- package/dist/cjs/data-api-route-generator.d.ts +1 -0
- package/dist/cjs/data-api-route-generator.d.ts.map +1 -1
- package/dist/cjs/data-api-route-generator.js +13 -5
- package/dist/cjs/data-api-route-generator.js.map +1 -1
- package/dist/cjs/executor-generator.d.ts.map +1 -1
- package/dist/cjs/executor-generator.js +12 -2
- package/dist/cjs/executor-generator.js.map +1 -1
- package/dist/cjs/invoice/invoice-assembly-code.d.ts.map +1 -1
- package/dist/cjs/invoice/invoice-assembly-code.js +19 -2
- package/dist/cjs/invoice/invoice-assembly-code.js.map +1 -1
- package/dist/cjs/invoice/invoice-html-code.d.ts.map +1 -1
- package/dist/cjs/invoice/invoice-html-code.js +100 -71
- package/dist/cjs/invoice/invoice-html-code.js.map +1 -1
- package/dist/cjs/tsconfig.tsbuildinfo +1 -1
- package/dist/esm/api-route-generator.d.ts.map +1 -1
- package/dist/esm/api-route-generator.js +3 -2
- package/dist/esm/api-route-generator.js.map +1 -1
- package/dist/esm/credential-columns-code.d.ts +17 -0
- package/dist/esm/credential-columns-code.d.ts.map +1 -0
- package/dist/esm/credential-columns-code.js +57 -0
- package/dist/esm/credential-columns-code.js.map +1 -0
- package/dist/esm/data-api-route-generator.d.ts +1 -0
- package/dist/esm/data-api-route-generator.d.ts.map +1 -1
- package/dist/esm/data-api-route-generator.js +11 -3
- package/dist/esm/data-api-route-generator.js.map +1 -1
- package/dist/esm/executor-generator.d.ts.map +1 -1
- package/dist/esm/executor-generator.js +12 -2
- package/dist/esm/executor-generator.js.map +1 -1
- package/dist/esm/invoice/invoice-assembly-code.d.ts.map +1 -1
- package/dist/esm/invoice/invoice-assembly-code.js +19 -2
- package/dist/esm/invoice/invoice-assembly-code.js.map +1 -1
- package/dist/esm/invoice/invoice-html-code.d.ts.map +1 -1
- package/dist/esm/invoice/invoice-html-code.js +100 -71
- package/dist/esm/invoice/invoice-html-code.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/src/api-route-generator.ts +3 -2
- package/src/credential-columns-code.ts +59 -0
- package/src/data-api-route-generator.ts +11 -3
- package/src/executor-generator.ts +12 -2
- package/src/invoice/invoice-assembly-code.ts +19 -2
- package/src/invoice/invoice-html-code.ts +100 -71
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/* tslint:disable:function-constructor */
|
|
2
|
+
import { TableAccess } from '@teleporthq/teleport-shared'
|
|
3
|
+
import { generateDataAPIRoute } from '../src/data-api-route-generator'
|
|
4
|
+
import {
|
|
5
|
+
generateServerSegmentAPIRoute,
|
|
6
|
+
generateStreamingServerSegmentAPIRoute,
|
|
7
|
+
} from '../src/api-route-generator'
|
|
8
|
+
import { generateSharedRuntimeUtilsCode } from '../src/executor-generator'
|
|
9
|
+
import type { WorkflowSegment } from '../src/types'
|
|
10
|
+
import { loadServerRuntime } from './_helpers/load-server-runtime'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The auth users table's credentials — the password hash and the OAuth tokens
|
|
14
|
+
* (`TableAccess.AUTH_CREDENTIAL_COLUMNS`) — never leave the server in a row.
|
|
15
|
+
* A browser read of the data route was already served without them; a create
|
|
16
|
+
* or an update answered the whole row it wrote, and a server segment replied
|
|
17
|
+
* its data nodes' rows to the browser as they came.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const SECRET = 'server-secret'
|
|
21
|
+
|
|
22
|
+
const USER_ROW = {
|
|
23
|
+
id: 'u-1',
|
|
24
|
+
email: 'member@example.com',
|
|
25
|
+
name: 'Member',
|
|
26
|
+
password: '$2a$10$hash',
|
|
27
|
+
access_token: 'oauth-access',
|
|
28
|
+
refresh_token: 'oauth-refresh',
|
|
29
|
+
id_token: 'oauth-id',
|
|
30
|
+
session_state: 'state',
|
|
31
|
+
token_type: 'Bearer',
|
|
32
|
+
scope: 'openid email',
|
|
33
|
+
expires_at: 1767225600,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const PROFILE = { id: 'u-1', email: 'member@example.com', name: 'Member' }
|
|
37
|
+
|
|
38
|
+
function bootDataRoute(rows: Array<Record<string, unknown>>) {
|
|
39
|
+
const code = generateDataAPIRoute({ authUsersTableName: 'users' })
|
|
40
|
+
class FakeClient {
|
|
41
|
+
public async connect(): Promise<void> {
|
|
42
|
+
return
|
|
43
|
+
}
|
|
44
|
+
public async end(): Promise<void> {
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
public async query(sql: string): Promise<{ rows: unknown[]; rowCount: number }> {
|
|
48
|
+
if (/information_schema/i.test(sql)) {
|
|
49
|
+
return { rows: [], rowCount: 0 }
|
|
50
|
+
}
|
|
51
|
+
return { rows, rowCount: rows.length }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const moduleObj: { exports: any } = { exports: {} }
|
|
55
|
+
const fakeRequire = (name: string): unknown => {
|
|
56
|
+
if (name === 'pg') {
|
|
57
|
+
return { Client: FakeClient }
|
|
58
|
+
}
|
|
59
|
+
if (name === 'next-auth/jwt') {
|
|
60
|
+
return { getToken: async () => ({ id: 'u-1' }) }
|
|
61
|
+
}
|
|
62
|
+
throw new Error('unexpected require: ' + name)
|
|
63
|
+
}
|
|
64
|
+
new Function('require', 'module', 'exports', 'process', 'console', code)(
|
|
65
|
+
fakeRequire,
|
|
66
|
+
moduleObj,
|
|
67
|
+
moduleObj.exports,
|
|
68
|
+
{ env: { NEXTAUTH_SECRET: SECRET, TELEPORT_DB_CONNECTION_STRING: 'postgresql://x' } },
|
|
69
|
+
{ error: (): void => undefined, warn: (): void => undefined, log: (): void => undefined }
|
|
70
|
+
)
|
|
71
|
+
return async (operation: string, body: Record<string, unknown>, headers = {}) => {
|
|
72
|
+
let status = 0
|
|
73
|
+
let payload: any = null
|
|
74
|
+
const res = {
|
|
75
|
+
status(statusCode: number) {
|
|
76
|
+
status = statusCode
|
|
77
|
+
return this
|
|
78
|
+
},
|
|
79
|
+
json(value: unknown) {
|
|
80
|
+
payload = value
|
|
81
|
+
return this
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
await moduleObj.exports(
|
|
85
|
+
{ method: 'POST', query: { params: ['ds-1', operation] }, headers, body },
|
|
86
|
+
res
|
|
87
|
+
)
|
|
88
|
+
return { status, body: payload }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const internal = { 'x-internal-data-secret': SECRET }
|
|
93
|
+
|
|
94
|
+
describe('data route — the row a create or update answers with', () => {
|
|
95
|
+
it('leaves the credentials out of a created users row, for the server caller too', async () => {
|
|
96
|
+
const route = bootDataRoute([USER_ROW])
|
|
97
|
+
const reply = await route(
|
|
98
|
+
'create',
|
|
99
|
+
{ tableName: 'users', columnMappings: [{ column: 'email', value: 'member@example.com' }] },
|
|
100
|
+
internal
|
|
101
|
+
)
|
|
102
|
+
expect(reply.status).toBe(200)
|
|
103
|
+
expect(reply.body).toEqual({ item: PROFILE, id: 'u-1' })
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it('leaves them out of an updated users row, however the table is spelled', async () => {
|
|
107
|
+
const route = bootDataRoute([USER_ROW])
|
|
108
|
+
for (const tableName of ['users', 'public.users', '"users"']) {
|
|
109
|
+
const reply = await route(
|
|
110
|
+
'update',
|
|
111
|
+
{
|
|
112
|
+
tableName,
|
|
113
|
+
filters: [{ field: 'id', operator: '=', value: 'u-1' }],
|
|
114
|
+
columnMappings: [{ column: 'name', value: 'Member' }],
|
|
115
|
+
},
|
|
116
|
+
internal
|
|
117
|
+
)
|
|
118
|
+
expect(reply.status).toBe(200)
|
|
119
|
+
expect(reply.body).toEqual({ updatedCount: 1, item: PROFILE, id: 'u-1' })
|
|
120
|
+
}
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it("keeps another table's columns, even ones named like a credential elsewhere", async () => {
|
|
124
|
+
const card = { id: 'g-1', code: 'GIFT', expires_at: '2027-01-01', scope: 'store' }
|
|
125
|
+
const route = bootDataRoute([card])
|
|
126
|
+
const reply = await route(
|
|
127
|
+
'create',
|
|
128
|
+
{ tableName: 'teleport_gift_cards', columnMappings: [{ column: 'code', value: 'GIFT' }] },
|
|
129
|
+
internal
|
|
130
|
+
)
|
|
131
|
+
expect(reply.body).toEqual({ item: card, id: 'g-1' })
|
|
132
|
+
})
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
interface SegmentReply {
|
|
136
|
+
status: number
|
|
137
|
+
body: { success: boolean; results?: Record<string, any>; error?: string }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function bootSegment(segment: WorkflowSegment, dataReplies: Record<string, unknown>) {
|
|
141
|
+
const source = generateServerSegmentAPIRoute(segment, 'Credentials')
|
|
142
|
+
const runtime = loadServerRuntime()
|
|
143
|
+
const routeModule: { exports: unknown } = { exports: {} }
|
|
144
|
+
new Function('module', 'exports', 'require', source)(
|
|
145
|
+
routeModule,
|
|
146
|
+
routeModule.exports,
|
|
147
|
+
(id: string) => (id.endsWith('server-runtime') ? runtime : {})
|
|
148
|
+
)
|
|
149
|
+
const handler = routeModule.exports as (req: unknown, res: unknown) => Promise<void>
|
|
150
|
+
return async (): Promise<SegmentReply> => {
|
|
151
|
+
const originalFetch = globalThis.fetch
|
|
152
|
+
globalThis.fetch = (async (url: string) => ({
|
|
153
|
+
ok: true,
|
|
154
|
+
status: 200,
|
|
155
|
+
json: async () => dataReplies[String(url).split('/').pop() as string],
|
|
156
|
+
})) as unknown as typeof fetch
|
|
157
|
+
try {
|
|
158
|
+
const reply: SegmentReply = { status: 0, body: { success: false } }
|
|
159
|
+
const res = {
|
|
160
|
+
status(code: number) {
|
|
161
|
+
reply.status = code
|
|
162
|
+
return this
|
|
163
|
+
},
|
|
164
|
+
json(payload: SegmentReply['body']) {
|
|
165
|
+
reply.body = payload
|
|
166
|
+
return this
|
|
167
|
+
},
|
|
168
|
+
}
|
|
169
|
+
await handler(
|
|
170
|
+
{ method: 'POST', body: { context: {} }, headers: { host: 'shop.example' } },
|
|
171
|
+
res
|
|
172
|
+
)
|
|
173
|
+
return reply
|
|
174
|
+
} finally {
|
|
175
|
+
globalThis.fetch = originalFetch
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const step = (id: string, type: string, stepNumber: number, config: Record<string, unknown>) => ({
|
|
181
|
+
id,
|
|
182
|
+
type,
|
|
183
|
+
label: id,
|
|
184
|
+
executionEnv: 'server' as const,
|
|
185
|
+
stepNumber,
|
|
186
|
+
config,
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
const segmentOf = (nodes: Array<ReturnType<typeof step>>): WorkflowSegment => ({
|
|
190
|
+
id: 'server-1',
|
|
191
|
+
env: 'server',
|
|
192
|
+
nodeIds: nodes.map((node) => node.id),
|
|
193
|
+
nodes,
|
|
194
|
+
edges: nodes.slice(1).map((node, index) => ({
|
|
195
|
+
id: `e${index}`,
|
|
196
|
+
source: nodes[index].id,
|
|
197
|
+
target: node.id,
|
|
198
|
+
})) as WorkflowSegment['edges'],
|
|
199
|
+
entryNodeIds: [nodes[0].id],
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
describe('server segment — the rows it replies to the browser with', () => {
|
|
203
|
+
const secret = process.env.NEXTAUTH_SECRET
|
|
204
|
+
beforeAll(() => {
|
|
205
|
+
process.env.NEXTAUTH_SECRET = SECRET
|
|
206
|
+
})
|
|
207
|
+
afterAll(() => {
|
|
208
|
+
process.env.NEXTAUTH_SECRET = secret
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
it('replies a data node of the users table without its credentials', async () => {
|
|
212
|
+
const segment = segmentOf([
|
|
213
|
+
step('read', 'data-select', 1, { dataSourceId: 'ds-1', tableName: 'users' }),
|
|
214
|
+
step('save', 'data-update-item', 2, {
|
|
215
|
+
dataSourceId: 'ds-1',
|
|
216
|
+
tableName: 'users',
|
|
217
|
+
filters: [{ field: 'id', operator: '=', value: 'u-1' }],
|
|
218
|
+
columnMappings: [{ column: 'name', value: 'Member' }],
|
|
219
|
+
}),
|
|
220
|
+
])
|
|
221
|
+
const reply = await bootSegment(segment, {
|
|
222
|
+
select: { rows: [USER_ROW], count: 1 },
|
|
223
|
+
update: { item: USER_ROW, id: 'u-1', updatedCount: 1 },
|
|
224
|
+
})()
|
|
225
|
+
expect(reply.status).toBe(200)
|
|
226
|
+
const results = reply.body.results || {}
|
|
227
|
+
expect(results.read).toEqual({ rows: [PROFILE], count: 1 })
|
|
228
|
+
expect(results.save).toEqual({ ...PROFILE, updatedCount: 1, affected: 1 })
|
|
229
|
+
expect(JSON.stringify(results)).not.toMatch(/hash|oauth-/)
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
it("strips a raw statement's rows of the credentials no other table uses", async () => {
|
|
233
|
+
const segment = segmentOf([
|
|
234
|
+
step('raw', 'data-raw-query', 1, { dataSourceId: 'ds-1', query: 'SELECT * FROM users' }),
|
|
235
|
+
])
|
|
236
|
+
const reply = await bootSegment(segment, { 'raw-query': { rows: [USER_ROW] } })()
|
|
237
|
+
const row = { ...PROFILE, scope: 'openid email', expires_at: 1767225600 }
|
|
238
|
+
expect(reply.body.results?.raw).toEqual({ rows: [row], result: [row] })
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
it("leaves another table's rows, and every node that reads no rows, as they are", async () => {
|
|
242
|
+
const card = { id: 'g-1', expires_at: '2027-01-01', scope: 'store' }
|
|
243
|
+
const segment = segmentOf([
|
|
244
|
+
step('cards', 'data-select', 1, { dataSourceId: 'ds-1', tableName: 'teleport_gift_cards' }),
|
|
245
|
+
step('form', 'general-custom-js', 2, {
|
|
246
|
+
code: 'function customHandler(params) { return { password: "typed" } }',
|
|
247
|
+
context: 'server',
|
|
248
|
+
}),
|
|
249
|
+
])
|
|
250
|
+
const reply = await bootSegment(segment, { select: { rows: [card], count: 1 } })()
|
|
251
|
+
expect(reply.body.results?.cards).toEqual({ rows: [card], count: 1 })
|
|
252
|
+
expect(reply.body.results?.form).toEqual({ password: 'typed' })
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
it('signs the result it replies, so a later segment can verify what the browser holds', async () => {
|
|
256
|
+
const segment = segmentOf([
|
|
257
|
+
step('read', 'data-select', 1, { dataSourceId: 'ds-1', tableName: 'users' }),
|
|
258
|
+
])
|
|
259
|
+
const reply = await bootSegment(segment, { select: { rows: [USER_ROW], count: 1 } })()
|
|
260
|
+
const later = loadServerRuntime()
|
|
261
|
+
const context: Record<string, unknown> = { ...reply.body.results }
|
|
262
|
+
later.claimSegmentContext({ signedNodeIds: ['read'], nodes: [], edges: [] }, context)
|
|
263
|
+
expect(context.read).toEqual({ rows: [PROFILE], count: 1 })
|
|
264
|
+
})
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
describe('one credential list', () => {
|
|
268
|
+
it('is the shared AUTH_CREDENTIAL_COLUMNS, in the runtime and in a streamed node result', () => {
|
|
269
|
+
const runtime = generateSharedRuntimeUtilsCode()
|
|
270
|
+
expect(runtime).toContain(JSON.stringify(TableAccess.AUTH_CREDENTIAL_COLUMNS))
|
|
271
|
+
expect(runtime).toContain(JSON.stringify(TableAccess.UNAMBIGUOUS_CREDENTIAL_COLUMNS))
|
|
272
|
+
const streaming = generateStreamingServerSegmentAPIRoute(
|
|
273
|
+
segmentOf([step('ai', 'ai-custom-prompt', 1, { streaming: true })])
|
|
274
|
+
)
|
|
275
|
+
expect(streaming).toContain('utils.withoutCredentialColumns(kept, result)')
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
it('strips a streamed data node the same way the reply does', () => {
|
|
279
|
+
const utils = loadServerRuntime()
|
|
280
|
+
const node = { id: 'read', type: 'data-select', config: { tableName: 'users' } }
|
|
281
|
+
expect(utils.withoutCredentialColumns(node, { rows: [USER_ROW], count: 1 })).toEqual({
|
|
282
|
+
rows: [PROFILE],
|
|
283
|
+
count: 1,
|
|
284
|
+
})
|
|
285
|
+
})
|
|
286
|
+
})
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
/* tslint:disable:function-constructor */
|
|
2
|
+
import { generateInvoiceAssemblyCode } from '../src/invoice/invoice-assembly-code'
|
|
3
|
+
import { generatePdfGeneratorCode } from '../src/invoice/pdf-generator-code'
|
|
4
|
+
import type { UIDLInvoiceSettings } from '@teleporthq/teleport-types'
|
|
5
|
+
import { evaluateEmittedModule } from './_helpers/load-invoice-route'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* What the invoice says about being paid, and how it writes money.
|
|
9
|
+
*
|
|
10
|
+
* A store invoices an order the moment its payment webhook marks it paid, so
|
|
11
|
+
* that invoice — its email and its PDF — must not ask for a payment already
|
|
12
|
+
* made: no due date, no amount due. A cash-on-delivery order is invoiced
|
|
13
|
+
* unpaid when it is placed and keeps both. A summary line whose amount is zero
|
|
14
|
+
* (no delivery, no discount, no tax, no gift card) is left out. And an empty
|
|
15
|
+
* field on the real invoice prints nothing — never the design canvas's sample.
|
|
16
|
+
*
|
|
17
|
+
* Every piece below is the EMITTED code, run: the assembly the generate route
|
|
18
|
+
* builds the invoice with, then the renderer the email and the PDF go through
|
|
19
|
+
* (`email-sender-code.ts` fills the body with `buildDataContext` +
|
|
20
|
+
* `replacePlaceholders`).
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const SETTINGS = {
|
|
24
|
+
invoicePrefix: 'INV-',
|
|
25
|
+
defaultTaxRate: 0,
|
|
26
|
+
showDiscount: false,
|
|
27
|
+
taxIncludedInPrice: false,
|
|
28
|
+
companyDetails: {},
|
|
29
|
+
template: { document: null as unknown },
|
|
30
|
+
tables: { invoicesTable: 'teleport_invoices', invoiceItemsTable: 'teleport_invoice_items' },
|
|
31
|
+
emailDelivery: { enabled: false },
|
|
32
|
+
} as unknown as UIDLInvoiceSettings
|
|
33
|
+
|
|
34
|
+
type Row = Record<string, unknown>
|
|
35
|
+
|
|
36
|
+
interface AssemblyModule {
|
|
37
|
+
assembleInvoiceData: (body: Row, order: Row | null, items: Row[]) => Row
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface PdfGeneratorModule {
|
|
41
|
+
buildInvoiceDataScope: (invoiceData: Row) => {
|
|
42
|
+
invoiceData: { Invoice: Record<string, string>; Company: Record<string, string> }
|
|
43
|
+
}
|
|
44
|
+
buildInvoiceHtml: (invoiceData: Row) => string
|
|
45
|
+
replacePlaceholders: (template: string, data: Row) => string
|
|
46
|
+
buildDataContext: (invoiceData: Row) => Row
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function loadAssembly(): AssemblyModule {
|
|
50
|
+
const requireFn = ((id: string) => {
|
|
51
|
+
if (id.indexOf('pdf-generator') !== -1) {
|
|
52
|
+
return { COMPANY_DETAILS: {} }
|
|
53
|
+
}
|
|
54
|
+
if (id.indexOf('data-access') !== -1) {
|
|
55
|
+
return {}
|
|
56
|
+
}
|
|
57
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
58
|
+
return require(id)
|
|
59
|
+
}) as unknown as NodeRequire
|
|
60
|
+
return evaluateEmittedModule<AssemblyModule>(generateInvoiceAssemblyCode(SETTINGS), requireFn)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function loadPdfGenerator(templateUidl: unknown = null): PdfGeneratorModule {
|
|
64
|
+
return evaluateEmittedModule<PdfGeneratorModule>(
|
|
65
|
+
generatePdfGeneratorCode(SETTINGS, templateUidl, templateUidl ? {} : null),
|
|
66
|
+
require
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// The date the renderer prints for a stored date: it reads the calendar day in
|
|
71
|
+
// the server's own time zone, so the expectation does too.
|
|
72
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
|
73
|
+
const printedDate = (raw: unknown): string => {
|
|
74
|
+
const date = new Date(raw as string)
|
|
75
|
+
return MONTHS[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// The editor's invoice email design (teleport-gui purposed-email-designs.ts) as
|
|
79
|
+
// it is published: each summary row is a <div> of <span>s, copied from a body a
|
|
80
|
+
// store sent on 2026-10-23 with its values put back to their tokens.
|
|
81
|
+
const SUMMARY_ROW_STYLE =
|
|
82
|
+
'color: #374151; margin: 0; padding: 10px 0; font-size: 14px; line-height: 1.5'
|
|
83
|
+
const summaryRow = (label: string, value: string, last = false) =>
|
|
84
|
+
`<div style="${SUMMARY_ROW_STYLE}${last ? '' : '; border-bottom: 1px solid #f0f1f3'}">` +
|
|
85
|
+
`<span>${label}: </span>${value}</div>`
|
|
86
|
+
const INVOICE_EMAIL_BODY =
|
|
87
|
+
'<div style="color: #1f2937; margin: 0 auto; padding: 8px; max-width: 600px; font-family: \'Segoe UI\',Roboto,Helvetica,Arial,sans-serif">' +
|
|
88
|
+
'<div style="border: 1px solid #e5e7eb; overflow: hidden; background: #ffffff; border-radius: 14px">' +
|
|
89
|
+
'<div style="padding: 24px 32px; background: #1e293b"><small style="color: #94a3b8; margin: 0; font-size: 12px; font-weight: 600; letter-spacing: 1px; text-transform: uppercase">Invoice</small>' +
|
|
90
|
+
'<p style="color: #ffffff; margin: 6px 0 0; font-size: 22px; font-weight: 700">Your invoice</p></div>' +
|
|
91
|
+
'<div style="padding: 28px 32px">' +
|
|
92
|
+
'<div style="color: #1f2937; margin: 0 0 16px; font-size: 15px; line-height: 1.6"><span>Dear </span><span>{{customerName}}</span><span>,</span></div>' +
|
|
93
|
+
'<p style="color: #4b5563; margin: 0 0 18px; font-size: 15px; line-height: 1.6">Thank you for your purchase. Your invoice is attached to this email. Here is a quick summary:</p>' +
|
|
94
|
+
'<div style="margin: 0 0 22px">' +
|
|
95
|
+
summaryRow('Invoice number', '<span>{{invoiceNumber}}</span>') +
|
|
96
|
+
summaryRow('Invoice date', '<span>{{invoiceDate}}</span>') +
|
|
97
|
+
summaryRow('Due date', '<span>{{dueDate}}</span>') +
|
|
98
|
+
summaryRow('Subtotal', '<span>{{subtotal}}</span>') +
|
|
99
|
+
summaryRow('Discount', '<span>−</span><span>{{discountAmount}}</span>') +
|
|
100
|
+
summaryRow('Tax', '<span>{{taxAmount}}</span>') +
|
|
101
|
+
summaryRow('Delivery', '<span>{{shippingAmount}}</span>') +
|
|
102
|
+
summaryRow('Total', '<span>{{totalAmount}}</span>') +
|
|
103
|
+
summaryRow('Paid by gift card', '<span>−</span><span>{{giftCardAmount}}</span>') +
|
|
104
|
+
summaryRow('Amount due', '<span>{{amountDue}}</span>', true) +
|
|
105
|
+
'</div>' +
|
|
106
|
+
'<div style="color: #4b5563; margin: 4px 0 0; font-size: 14px; line-height: 1.6"><span>If you have any questions about this invoice, contact us at </span><span>{{companyEmail}}</span><span>.</span></div>' +
|
|
107
|
+
'<p style="color: #4b5563; margin: 20px 0 2px; font-size: 14px; line-height: 1.6">Best regards,</p>' +
|
|
108
|
+
'<p style="color: #1f2937; margin: 0; font-size: 14px; font-weight: 600; line-height: 1.6">{{companyName}}</p>' +
|
|
109
|
+
'</div></div></div>'
|
|
110
|
+
|
|
111
|
+
// ORD-2 of the store this was found on: one 119.00 lei line paid by card, no
|
|
112
|
+
// delivery, discount, tax or gift card. The payment webhook marked it paid —
|
|
113
|
+
// `payment_status` and the `updated_at` that write stamps — then asked for the
|
|
114
|
+
// invoice with just the order id.
|
|
115
|
+
const PAID_CARD_ORDER: Row = {
|
|
116
|
+
id: 'order-2',
|
|
117
|
+
order_number: 'ORD-2',
|
|
118
|
+
currency: 'RON',
|
|
119
|
+
total_amount: 119,
|
|
120
|
+
shipping_amount: 0,
|
|
121
|
+
discount_amount: 0,
|
|
122
|
+
gift_card_amount: 0,
|
|
123
|
+
status: 'confirmed',
|
|
124
|
+
payment_status: 'paid',
|
|
125
|
+
payment_method: 'stripe',
|
|
126
|
+
payment_provider: 'stripe',
|
|
127
|
+
updated_at: '2026-10-23T09:15:00.000Z',
|
|
128
|
+
billing_name: 'Card Buyer',
|
|
129
|
+
}
|
|
130
|
+
const LINES: Row[] = [
|
|
131
|
+
{ product_id: 'p1', product_name: 'Bouquet', quantity: 1, unit_price: 119, total_price: 119 },
|
|
132
|
+
]
|
|
133
|
+
// The same basket, delivered and paid in cash at the door: invoiced when it is
|
|
134
|
+
// placed, before any money moved.
|
|
135
|
+
const CASH_ORDER: Row = {
|
|
136
|
+
...PAID_CARD_ORDER,
|
|
137
|
+
id: 'order-3',
|
|
138
|
+
order_number: 'ORD-3',
|
|
139
|
+
total_amount: 134,
|
|
140
|
+
shipping_amount: 15,
|
|
141
|
+
status: 'pending',
|
|
142
|
+
payment_status: 'unpaid',
|
|
143
|
+
payment_method: 'cash_on_delivery',
|
|
144
|
+
payment_provider: '',
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// The editor's default invoice template, reduced to the parts this covers: the
|
|
148
|
+
// <context> carrying the design canvas's sample (teleport-gui
|
|
149
|
+
// invoice-template-builder.ts), the dates under the number, the total, the
|
|
150
|
+
// notes and the seller's VAT number.
|
|
151
|
+
const SAMPLE_NOTES = 'Payment is due within 30 days. Thank you for your business.'
|
|
152
|
+
const boundText = (path: string) => ({
|
|
153
|
+
type: 'element',
|
|
154
|
+
content: {
|
|
155
|
+
elementType: 'text',
|
|
156
|
+
semanticType: 'p',
|
|
157
|
+
children: [{ type: 'expr', content: `invoiceData?.${path}` }],
|
|
158
|
+
},
|
|
159
|
+
})
|
|
160
|
+
const INVOICE_TEMPLATE = {
|
|
161
|
+
name: 'invoice-template',
|
|
162
|
+
node: {
|
|
163
|
+
type: 'element',
|
|
164
|
+
content: {
|
|
165
|
+
elementType: 'context',
|
|
166
|
+
attrs: {
|
|
167
|
+
Company: {
|
|
168
|
+
type: 'static',
|
|
169
|
+
content: { name: 'Acme Corporation', vat: 'US123456789', logoUrl: '' },
|
|
170
|
+
},
|
|
171
|
+
Invoice: {
|
|
172
|
+
type: 'static',
|
|
173
|
+
content: {
|
|
174
|
+
invoiceNumber: '#INV-001',
|
|
175
|
+
status: 'paid',
|
|
176
|
+
issueDate: 'Jan 15, 2025',
|
|
177
|
+
dueDate: 'Feb 14, 2025',
|
|
178
|
+
paidDate: 'Jan 20, 2025',
|
|
179
|
+
total: '371.49',
|
|
180
|
+
currency: 'USD',
|
|
181
|
+
notes: SAMPLE_NOTES,
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
children: [
|
|
186
|
+
boundText('Invoice?.invoiceNumber'),
|
|
187
|
+
boundText('Invoice?.issueDate'),
|
|
188
|
+
boundText('Invoice?.dueDate'),
|
|
189
|
+
boundText('Invoice?.total'),
|
|
190
|
+
boundText('Invoice?.notes'),
|
|
191
|
+
boundText('Invoice?.paidDate'),
|
|
192
|
+
boundText('Company?.vat'),
|
|
193
|
+
],
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const assembly = loadAssembly()
|
|
199
|
+
const pdfGenerator = loadPdfGenerator()
|
|
200
|
+
|
|
201
|
+
function invoiceFor(order: Row, body: Row = {}): Row {
|
|
202
|
+
const invoice = assembly.assembleInvoiceData(
|
|
203
|
+
{ orderId: order.id, issueDate: '2026-10-23', ...body },
|
|
204
|
+
order,
|
|
205
|
+
LINES
|
|
206
|
+
)
|
|
207
|
+
return { ...invoice, invoiceNumber: 'INV-0002' }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function emailFor(invoice: Row, body = INVOICE_EMAIL_BODY): string {
|
|
211
|
+
return pdfGenerator.replacePlaceholders(body, pdfGenerator.buildDataContext(invoice))
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
describe('the invoice of a paid order', () => {
|
|
215
|
+
it('is issued paid, at the time the payment marked the order', () => {
|
|
216
|
+
const invoice = invoiceFor(PAID_CARD_ORDER)
|
|
217
|
+
expect(invoice.status).toBe('paid')
|
|
218
|
+
expect(invoice.paidAt).toBe('2026-10-23T09:15:00.000Z')
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
it('keeps the status and payment time a caller states', () => {
|
|
222
|
+
const invoice = invoiceFor(PAID_CARD_ORDER, { status: 'issued' })
|
|
223
|
+
expect(invoice.status).toBe('issued')
|
|
224
|
+
expect(invoice.paidAt).toBeNull()
|
|
225
|
+
const stated = invoiceFor(PAID_CARD_ORDER, { status: 'paid', paidAt: '2026-10-20T08:00:00Z' })
|
|
226
|
+
expect(stated.paidAt).toBe('2026-10-20T08:00:00Z')
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
it('emails no due date, no amount due and no zero lines', () => {
|
|
230
|
+
const email = emailFor(invoiceFor(PAID_CARD_ORDER))
|
|
231
|
+
expect(email).toContain('<span>Invoice number: </span><span>INV-0002</span>')
|
|
232
|
+
expect(email).toContain(
|
|
233
|
+
'<span>Invoice date: </span><span>' + printedDate('2026-10-23') + '</span>'
|
|
234
|
+
)
|
|
235
|
+
expect(email).toContain('<span>Subtotal: </span><span>lei 119.00</span>')
|
|
236
|
+
expect(email).toContain('<span>Total: </span><span>lei 119.00</span>')
|
|
237
|
+
for (const gone of ['Due date', 'Amount due', 'Discount', 'Tax', 'Delivery', 'gift card']) {
|
|
238
|
+
expect(email).not.toContain(gone)
|
|
239
|
+
}
|
|
240
|
+
// Only the rows went: the summary box and the rest of the message stay.
|
|
241
|
+
expect(email).toContain('<div style="margin: 0 0 22px">')
|
|
242
|
+
expect(email).toContain('Best regards,')
|
|
243
|
+
})
|
|
244
|
+
|
|
245
|
+
it('prints a paid line where the PDF printed the due date', () => {
|
|
246
|
+
const invoice = invoiceFor(PAID_CARD_ORDER)
|
|
247
|
+
const html = loadPdfGenerator(INVOICE_TEMPLATE).buildInvoiceHtml(invoice)
|
|
248
|
+
expect(html).toContain('<p>Paid on ' + printedDate('2026-10-23T09:15:00.000Z') + '</p>')
|
|
249
|
+
expect(html).not.toContain(printedDate(invoice.dueDate))
|
|
250
|
+
expect(html).toContain('<p>lei 119.00</p>')
|
|
251
|
+
// The built-in layout of a store without a template says so too.
|
|
252
|
+
expect(pdfGenerator.buildInvoiceHtml(invoice)).toContain(
|
|
253
|
+
'Paid on ' + printedDate('2026-10-23T09:15:00.000Z')
|
|
254
|
+
)
|
|
255
|
+
})
|
|
256
|
+
})
|
|
257
|
+
|
|
258
|
+
describe('the invoice of a cash-on-delivery order', () => {
|
|
259
|
+
it('is issued unpaid and due in 30 days', () => {
|
|
260
|
+
const invoice = invoiceFor(CASH_ORDER)
|
|
261
|
+
expect(invoice.status).toBe('issued')
|
|
262
|
+
expect(invoice.paidAt).toBeNull()
|
|
263
|
+
expect(invoice.dueDate).toBe('2026-11-22')
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
it('emails its due date and the delivery, and no amount due without a gift card', () => {
|
|
267
|
+
const email = emailFor(invoiceFor(CASH_ORDER))
|
|
268
|
+
expect(email).toContain(
|
|
269
|
+
'<span>Due date: </span><span>' + printedDate('2026-11-22') + '</span></div>'
|
|
270
|
+
)
|
|
271
|
+
expect(email).toContain('<span>Delivery: </span><span>lei 15.00</span>')
|
|
272
|
+
expect(email).toContain('<span>Total: </span><span>lei 134.00</span>')
|
|
273
|
+
for (const gone of ['Amount due', 'Discount', 'Tax', 'gift card']) {
|
|
274
|
+
expect(email).not.toContain(gone)
|
|
275
|
+
}
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
it('keeps the due date on its PDF', () => {
|
|
279
|
+
const invoice = invoiceFor(CASH_ORDER)
|
|
280
|
+
const html = loadPdfGenerator(INVOICE_TEMPLATE).buildInvoiceHtml(invoice)
|
|
281
|
+
expect(html).toContain('<p>' + printedDate('2026-11-22') + '</p>')
|
|
282
|
+
expect(html).not.toContain('Paid on')
|
|
283
|
+
expect(pdfGenerator.buildInvoiceHtml(invoice)).not.toContain('Paid on')
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
it('emails what a gift card paid and what is left to pay at the door', () => {
|
|
287
|
+
const email = emailFor(invoiceFor({ ...CASH_ORDER, gift_card_amount: 50 }))
|
|
288
|
+
expect(email).toContain(
|
|
289
|
+
'<span>Paid by gift card: </span><span>−</span><span>lei 50.00</span></div>'
|
|
290
|
+
)
|
|
291
|
+
expect(email).toContain('<span>Amount due: </span><span>lei 84.00</span></div>')
|
|
292
|
+
expect(email).toContain('<span>Due date: </span>')
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
it('emails no amount due once the rest was paid by card', () => {
|
|
296
|
+
const email = emailFor(invoiceFor({ ...PAID_CARD_ORDER, gift_card_amount: 50 }))
|
|
297
|
+
expect(email).toContain('<span>Paid by gift card: </span><span>−</span><span>lei 50.00</span>')
|
|
298
|
+
expect(email).not.toContain('Amount due')
|
|
299
|
+
})
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
describe('the invoice email drops a zero line, never what holds it', () => {
|
|
303
|
+
const zeroDeliveryInvoice = invoiceFor(CASH_ORDER, { shippingAmount: 0 })
|
|
304
|
+
|
|
305
|
+
it("keeps a merchant's own block around the line it drops", () => {
|
|
306
|
+
const body =
|
|
307
|
+
'<div class="merchant-summary">' +
|
|
308
|
+
'<div class="row"><span>Delivery: </span><span>{{shippingAmount}}</span></div>' +
|
|
309
|
+
'<div class="row"><span>Total: </span><span>{{totalAmount}}</span></div>' +
|
|
310
|
+
'<p>Thank you for shopping with us.</p>' +
|
|
311
|
+
'</div>'
|
|
312
|
+
expect(emailFor(zeroDeliveryInvoice, body)).toBe(
|
|
313
|
+
'<div class="merchant-summary">' +
|
|
314
|
+
'<div class="row"><span>Total: </span><span>lei 119.00</span></div>' +
|
|
315
|
+
'<p>Thank you for shopping with us.</p>' +
|
|
316
|
+
'</div>'
|
|
317
|
+
)
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
it('keeps a block that holds more than the line', () => {
|
|
321
|
+
const withBlocks =
|
|
322
|
+
'<div class="note"><span>Delivery {{shippingAmount}}</span><p>See you soon.</p></div>'
|
|
323
|
+
expect(emailFor(zeroDeliveryInvoice, withBlocks)).toBe(
|
|
324
|
+
'<div class="note"><span>Delivery lei 0.00</span><p>See you soon.</p></div>'
|
|
325
|
+
)
|
|
326
|
+
const withFigures = '<div>Delivery {{shippingAmount}}, total {{totalAmount}}.</div>'
|
|
327
|
+
expect(emailFor(zeroDeliveryInvoice, withFigures)).toBe(
|
|
328
|
+
'<div>Delivery lei 0.00, total lei 119.00.</div>'
|
|
329
|
+
)
|
|
330
|
+
})
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
describe('money on the invoice', () => {
|
|
334
|
+
it.each([
|
|
335
|
+
['RON', 'lei 119.00'],
|
|
336
|
+
['CHF', 'CHF 119.00'],
|
|
337
|
+
['USD', '$119.00'],
|
|
338
|
+
['EUR', '€119.00'],
|
|
339
|
+
])('writes %s as %s in the email and the PDF alike', (currency, printed) => {
|
|
340
|
+
const invoice = invoiceFor({ ...PAID_CARD_ORDER, currency })
|
|
341
|
+
expect(emailFor(invoice, '<span>{{totalAmount}}</span>')).toBe(`<span>${printed}</span>`)
|
|
342
|
+
expect(pdfGenerator.buildInvoiceDataScope(invoice).invoiceData.Invoice.total).toBe(printed)
|
|
343
|
+
})
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
describe("the invoice PDF never prints the template's sample", () => {
|
|
347
|
+
it('prints nothing for a field the real invoice leaves empty', () => {
|
|
348
|
+
const html = loadPdfGenerator(INVOICE_TEMPLATE).buildInvoiceHtml(
|
|
349
|
+
invoiceFor(CASH_ORDER, { notes: '' })
|
|
350
|
+
)
|
|
351
|
+
expect(html).not.toContain(SAMPLE_NOTES)
|
|
352
|
+
expect(html).not.toContain('Jan 20, 2025')
|
|
353
|
+
expect(html).not.toContain('US123456789')
|
|
354
|
+
expect(html).not.toContain('371.49')
|
|
355
|
+
expect(html).toContain('<p>#INV-0002</p>')
|
|
356
|
+
expect(html).toContain('<p>lei 134.00</p>')
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
it("prints the invoice's own notes", () => {
|
|
360
|
+
const html = loadPdfGenerator(INVOICE_TEMPLATE).buildInvoiceHtml(
|
|
361
|
+
invoiceFor(CASH_ORDER, { notes: 'Leave it with the neighbour.' })
|
|
362
|
+
)
|
|
363
|
+
expect(html).toContain('<p>Leave it with the neighbour.</p>')
|
|
364
|
+
})
|
|
365
|
+
|
|
366
|
+
it("keeps the company logo the editor wrote onto the template's context", () => {
|
|
367
|
+
const withLogo = {
|
|
368
|
+
...INVOICE_TEMPLATE,
|
|
369
|
+
node: {
|
|
370
|
+
...INVOICE_TEMPLATE.node,
|
|
371
|
+
content: {
|
|
372
|
+
...INVOICE_TEMPLATE.node.content,
|
|
373
|
+
attrs: {
|
|
374
|
+
Company: { type: 'static', content: { name: '', logoUrl: 'https://cdn/logo.png' } },
|
|
375
|
+
},
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
}
|
|
379
|
+
const scope = loadPdfGenerator(withLogo).buildInvoiceDataScope(invoiceFor(CASH_ORDER))
|
|
380
|
+
expect(scope.invoiceData.Company.logoUrl).toBe('https://cdn/logo.png')
|
|
381
|
+
})
|
|
382
|
+
})
|