forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.prisma
More file actions
525 lines (461 loc) · 20.2 KB
/
Copy pathschema.prisma
File metadata and controls
525 lines (461 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
}
model Customer {
id String @id @default(uuid())
merchantId String @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
name String
email String?
notes String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
invoices Invoice[]
recurringSchedules RecurringSchedule[]
@@unique([merchantId, email])
@@index([merchantId])
@@index([name])
@@map("customers")
}
model Merchant {
id String @id @default(uuid())
name String
stellarPublicKey String @unique @map("stellar_public_key")
businessEmail String? @map("business_email")
preferredAsset String @default("XLM") @map("preferred_asset")
payoutWallet String? @map("payout_wallet")
webhookUrl String? @map("webhook_url")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
users User[]
invoices Invoice[]
activities ActivityEvent[]
customers Customer[]
activationChecklist MerchantActivationChecklist?
paymentReviews PaymentReview[]
recurringSchedules RecurringSchedule[]
pushNotifications PushNotification[]
engagementEvents InvoiceEngagementEvent[]
@@map("merchants")
}
model MerchantActivationChecklist {
id String @id @default(uuid())
merchantId String @unique @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
// Checklist steps
profileCompleted Boolean @default(false) @map("profile_completed")
payoutKeyCompleted Boolean @default(false) @map("payout_key_completed")
assetPreferenceCompleted Boolean @default(false) @map("asset_preference_completed")
firstInvoiceCompleted Boolean @default(false) @map("first_invoice_completed")
// Overall completion
isCompleted Boolean @default(false) @map("is_completed")
completedAt DateTime? @map("completed_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("merchant_activation_checklists")
}
// User model matching backend/src/users/user.entity.ts
model User {
id String @id @default(uuid())
merchantId String @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Restrict)
publicKey String @unique
email String?
nonce String?
nonceExpiresAt BigInt? @map("nonce_expires_at")
nonceUsedAt DateTime? @map("nonce_used_at")
tokenVersion Int @default(0) @map("token_version")
isAdmin Boolean @default(false) @map("is_admin")
role MerchantRole @default(owner)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
webhookUrl String? @map("webhook_url")
webhookSecret String? @map("webhook_secret")
pushTokens String[] @default([]) @map("push_tokens")
pushNotificationsEnabled Boolean @default(true) @map("push_notifications_enabled")
invoices Invoice[]
webhooks WebhookDelivery[]
activities ActivityEvent[]
webhookDeadLetters WebhookDeadLetter[]
recurringSchedules RecurringSchedule[]
pushNotifications PushNotification[]
@@index([merchantId])
@@map("users")
}
model WebhookDelivery {
id String @id @default(uuid())
invoiceId String @map("invoice_id")
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
deadLetterId String? @map("dead_letter_id")
deadLetter WebhookDeadLetter? @relation(fields: [deadLetterId], references: [id], onDelete: SetNull)
url String
payload Json
status DeliveryStatus @default(pending)
attempts Int @default(0)
lastAttemptAt DateTime? @map("last_attempt_at")
nextAttemptAt DateTime? @map("next_attempt_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("webhook_deliveries")
}
model WebhookDeadLetter {
id String @id @default(uuid())
originalDeliveryId String @unique @map("original_delivery_id")
invoiceId String @map("invoice_id")
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
merchantId String @map("merchant_id")
url String
payload Json
lastError String? @map("last_error")
lastHttpStatus Int? @map("last_http_status")
failedAttempts Int @map("failed_attempts")
exhaustedAt DateTime @default(now()) @map("exhausted_at")
manualRetryCount Int @default(0) @map("manual_retry_count")
lastRetriedAt DateTime? @map("last_retried_at")
recoveredAt DateTime? @map("recovered_at")
status DeadLetterStatus @default(pending_retry)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
redriveDeliveries WebhookDelivery[]
@@index([merchantId])
@@index([status, exhaustedAt])
@@map("webhook_dead_letters")
}
enum DeliveryStatus {
pending
success
failed
}
enum DeadLetterStatus {
pending_retry
requeued
recovered
}
enum MerchantRole {
owner
admin
operator
viewer
}
enum PushNotificationStatus {
queued
ticket_ok
ticket_error
receipt_ok
receipt_error_permanent
receipt_error_retryable
token_removed
}
enum PushNotificationFailureReason {
DeviceNotRegistered
InvalidCredentials
MessageTooBig
MessageRateExceeded
ProviderError
InvalidProviderError
DeviceNotRegisteredOnPlatform
Unknown
}
// Invoice model matching backend/src/invoices/entities/invoice.entity.ts
model Invoice {
id String @id @default(uuid())
merchantId String @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Restrict)
userId String? @map("user_id")
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
invoiceNumber String @unique @map("invoice_number")
clientName String @map("client_name")
clientEmail String @map("client_email")
description String?
amount Decimal @db.Decimal(18, 7)
amountPaid Decimal @default(0) @db.Decimal(18, 7) @map("amount_paid")
amountDue Decimal @db.Decimal(18, 7) @map("amount_due")
assetCode String @map("asset_code")
assetIssuer String? @map("asset_issuer")
memo String @unique
memoType String @default("ID") @map("memo_type")
status InvoiceStatus @default(draft)
destinationAddress String @map("destination_address")
txHash String? @map("tx_hash")
sorobanTxHash String? @map("soroban_tx_hash")
sorobanContractId String? @map("soroban_contract_id")
metadata Json?
dueDate DateTime? @map("due_date")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
// Draft-specific fields
isDraft Boolean @default(true) @map("is_draft")
lastAutoSavedAt DateTime? @map("last_auto_saved_at")
draftVersion Int @default(1) @map("draft_version")
draftData Json? @map("draft_data")
customerId String? @map("customer_id")
customer Customer? @relation(fields: [customerId], references: [id], onDelete: SetNull)
webhooks WebhookDelivery[]
webhookDeadLetters WebhookDeadLetter[]
statusHistory InvoiceStatusHistory[]
payments Payment[]
activities ActivityEvent[]
paymentReviews PaymentReview[]
recurringInvoiceRun RecurringInvoiceRun?
engagementEvents InvoiceEngagementEvent[]
@@index([merchantId])
@@index([isDraft, merchantId])
@@index([lastAutoSavedAt])
@@map("invoices")
}
model InvoiceStatusHistory {
id String @id @default(uuid())
invoiceId String @map("invoice_id")
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
status String
createdAt DateTime @default(now()) @map("created_at")
@@index([invoiceId])
@@map("invoice_status_history")
}
enum InvoiceStatus {
draft
pending
partially_paid
paid
overdue
cancelled
}
model Payment {
id String @id @default(uuid())
invoiceId String @map("invoice_id")
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
amount Decimal @db.Decimal(18, 7)
txHash String? @unique @map("tx_hash")
createdAt DateTime @default(now()) @map("created_at")
@@index([invoiceId])
@@map("payments")
}
// Funnel signals captured from the public (unauthenticated) invoice view —
// impressions and payment-intent actions (wallet launch, copy, etc.) — kept
// separate from Payment/InvoiceStatusHistory since they never confirm
// on-chain settlement, only payer engagement prior to it.
enum InvoiceEngagementEventType {
view
wallet_launch
copy
other
}
model InvoiceEngagementEvent {
id String @id @default(uuid())
invoiceId String @map("invoice_id")
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
merchantId String @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
type InvoiceEngagementEventType
target String?
createdAt DateTime @default(now()) @map("created_at")
@@index([invoiceId, createdAt])
@@index([merchantId, type, createdAt])
@@map("invoice_engagement_events")
}
// Backfill tracking tables
model ActivityEvent {
id String @id @default(uuid())
merchantId String @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Restrict)
userId String? @map("user_id")
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
invoiceId String? @map("invoice_id")
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull)
type String // e.g. "invoice_created", "payment_received", "reminder_sent", "webhook_delivered"
description String
metadata Json?
createdAt DateTime @default(now()) @map("created_at")
@@index([merchantId])
@@index([merchantId, type])
@@index([createdAt])
@@map("activity_events")
}
enum BackfillRunStatus {
pending
running
paused
cancelled
completed
failed
}
model BackfillRun {
id Int @id @default(autoincrement())
contractId String @map("contract_id")
startedAt DateTime @default(now()) @map("started_at")
completedAt DateTime? @map("completed_at")
startLedger BigInt @map("start_ledger")
endLedger BigInt @map("end_ledger")
lastCheckpointLedger BigInt? @map("last_checkpoint_ledger")
lastCheckpointCursor String? @map("last_checkpoint_cursor")
lastCheckpointAt DateTime? @map("last_checkpoint_at")
eventsProcessed Int @default(0) @map("events_processed")
eventsMatched Int @default(0) @map("events_matched")
eventsSkipped Int @default(0) @map("events_skipped")
eventsFailed Int @default(0) @map("events_failed")
status BackfillRunStatus @default(pending)
cancelledAt DateTime? @map("cancelled_at")
cancelledBy String? @map("cancelled_by")
cancellationNote String? @map("cancellation_note")
errorMessage String? @map("error_message")
parentRunId Int? @map("parent_run_id")
parentRun BackfillRun? @relation("BackfillRunResume", fields: [parentRunId], references: [id])
resumedRuns BackfillRun[] @relation("BackfillRunResume")
checkpoints BackfillCheckpoint[]
createdAt DateTime @default(now()) @map("created_at")
@@index([contractId, status])
@@index([contractId, startLedger, endLedger])
@@map("backfill_runs")
}
model BackfillCheckpoint {
id Int @id @default(autoincrement())
runId Int @map("run_id")
run BackfillRun @relation(fields: [runId], references: [id], onDelete: Cascade)
contractId String @map("contract_id")
checkpointLedger BigInt @map("checkpoint_ledger")
startLedgerRange BigInt @map("start_ledger_range")
endLedgerRange BigInt @map("end_ledger_range")
lastEventCursor String? @map("last_event_cursor")
lastEventId String? @map("last_event_id")
eventsInBatch Int @default(0) @map("events_in_batch")
eventsProcessedBefore Int @default(0) @map("events_processed_before")
eventsMatchedBefore Int @default(0) @map("events_matched_before")
eventsSkippedBefore Int @default(0) @map("events_skipped_before")
eventsFailedBefore Int @default(0) @map("events_failed_before")
note String?
createdAt DateTime @default(now()) @map("created_at")
@@index([runId])
@@index([contractId, checkpointLedger])
@@map("backfill_checkpoints")
}
model ProcessedEvent {
id Int @id @default(autoincrement())
txHash String @map("tx_hash")
ledger BigInt
invoiceId String @map("invoice_id")
contractId String @map("contract_id")
status String @default("success") // success | skipped | failed
errorMessage String? @map("error_message")
processedAt DateTime @default(now()) @map("processed_at")
@@unique([txHash, invoiceId, contractId])
@@index([ledger])
@@index([invoiceId])
@@index([status])
@@map("processed_events")
}
model PaymentReview {
id String @id @default(uuid())
merchantId String? @map("merchant_id")
merchant Merchant? @relation(fields: [merchantId], references: [id], onDelete: Cascade)
invoiceId String? @map("invoice_id")
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull)
txHash String @unique @map("tx_hash")
contractId String @map("contract_id")
amount Decimal @db.Decimal(18, 7)
assetCode String? @map("asset_code")
assetIssuer String? @map("asset_issuer")
payer String?
originalMemo String? @map("original_memo")
issueType String @map("issue_type") // 'unmatched', 'underpaid', 'overpaid'
status String @default("pending") // 'pending', 'resolved', 'ignored'
resolutionNote String? @map("resolution_note")
resolvedAt DateTime? @map("resolved_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([merchantId])
@@index([status])
@@map("payment_reviews")
}
// Recurring billing: merchant-defined rules that generate invoices on a
// schedule. Lives on the same Prisma persistence layer as the rest of the
// app (previously a disconnected TypeORM entity that was never wired in).
enum RecurringFrequency {
WEEKLY
MONTHLY
}
enum RecurringScheduleStatus {
active
paused
cancelled
}
model RecurringSchedule {
id String @id @default(uuid())
merchantId String @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
customerId String @map("customer_id")
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
createdByUserId String @map("created_by_user_id")
createdByUser User @relation(fields: [createdByUserId], references: [id], onDelete: Restrict)
amount Decimal @db.Decimal(18, 7)
assetCode String @map("asset_code")
assetIssuer String? @map("asset_issuer")
description String?
frequency RecurringFrequency
status RecurringScheduleStatus @default(active)
nextRunDate DateTime @map("next_run_date")
lastGeneratedAt DateTime? @map("last_generated_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
runs RecurringInvoiceRun[]
@@index([merchantId])
@@index([status, nextRunDate])
@@map("recurring_schedules")
}
// One row per generated cycle. The unique (scheduleId, periodKey) constraint
// prevents a schedule from generating two invoices for the same period,
// even under concurrent cron ticks or a retried run.
model RecurringInvoiceRun {
id String @id @default(uuid())
scheduleId String @map("schedule_id")
schedule RecurringSchedule @relation(fields: [scheduleId], references: [id], onDelete: Cascade)
periodKey String @map("period_key")
invoiceId String? @unique @map("invoice_id")
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now()) @map("created_at")
@@unique([scheduleId, periodKey])
@@map("recurring_invoice_runs")
}
model PushNotification {
id String @id @default(uuid())
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
merchantId String @map("merchant_id")
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
pushToken String @map("push_token")
eventType String @map("event_type")
title String
body String
payload Json?
status PushNotificationStatus @default(queued)
expoTicketId String? @unique @map("expo_ticket_id")
ticketError String? @map("ticket_error")
ticketErrorDetails Json? @map("ticket_error_details")
ticketCreatedAt DateTime? @map("ticket_created_at")
receiptStatus String? @map("receipt_status")
receiptMessage String? @map("receipt_message")
receiptFailureReason PushNotificationFailureReason? @map("receipt_failure_reason")
receiptFetchedAt DateTime? @map("receipt_fetched_at")
receiptDetails Json? @map("receipt_details")
retryCount Int @default(0) @map("retry_count")
lastRetriedAt DateTime? @map("last_retried_at")
removedTokenAt DateTime? @map("removed_token_at")
removedTokenNote String? @map("removed_token_note")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([merchantId])
@@index([userId])
@@index([status])
@@index([expoTicketId])
@@index([pushToken])
@@index([status, receiptFetchedAt])
@@map("push_notifications")
}