@fayz-ai/courses 0.6.0 → 0.7.0
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/dist/index.cjs +627 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +621 -3
- package/dist/index.js.map +1 -1
- package/dist/mock-provider.d.ts +17 -2
- package/dist/mock-provider.d.ts.map +1 -1
- package/dist/provider.d.ts +10 -1
- package/dist/provider.d.ts.map +1 -1
- package/dist/safe-provider.d.ts +9 -0
- package/dist/safe-provider.d.ts.map +1 -0
- package/dist/seed.d.ts +14 -1
- package/dist/seed.d.ts.map +1 -1
- package/dist/supabase-provider.d.ts +3 -0
- package/dist/supabase-provider.d.ts.map +1 -0
- package/dist/tenant.d.ts +4 -0
- package/dist/tenant.d.ts.map +1 -0
- package/dist/types.d.ts +112 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +16 -2
- package/src/mock-provider.ts +122 -1
- package/src/provider.ts +21 -0
- package/src/safe-provider.ts +17 -0
- package/src/seed.ts +152 -2
- package/src/supabase-provider.ts +344 -0
- package/src/tenant.ts +21 -0
- package/src/types.ts +131 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { getSupabaseClientOptional } from '@fayz-ai/core'
|
|
2
|
+
import type { CoursesProvider } from './provider'
|
|
3
|
+
import { getCoursesTenantId } from './tenant'
|
|
4
|
+
import type {
|
|
5
|
+
Course, Module, Lesson, Enrollment, Progress,
|
|
6
|
+
CreateCourseInput, UpdateCourseInput,
|
|
7
|
+
CreateModuleInput, UpdateModuleInput,
|
|
8
|
+
CreateLessonInput, UpdateLessonInput,
|
|
9
|
+
ListCoursesOptions,
|
|
10
|
+
Offer, CreateOfferInput, UpdateOfferInput,
|
|
11
|
+
Order, ListOrdersOptions,
|
|
12
|
+
Subscription, ListSubscriptionsOptions,
|
|
13
|
+
Payout, CreatorAccount, FinancialSummary,
|
|
14
|
+
} from './types'
|
|
15
|
+
|
|
16
|
+
// Supabase-backed CoursesProvider for the central "fayz-course" DB. Every query
|
|
17
|
+
// is tenant-scoped (creator) via getCoursesTenantId(); RLS enforces isolation
|
|
18
|
+
// server-side regardless. Mirrors @fayz-ai/shop's supabase-provider.
|
|
19
|
+
|
|
20
|
+
function getDb(): any {
|
|
21
|
+
const supabase = getSupabaseClientOptional()
|
|
22
|
+
if (!supabase) throw new Error('@fayz-ai/courses: Supabase client not initialized. Call setGlobalSupabaseClient() first.')
|
|
23
|
+
return supabase
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const getTenantId = getCoursesTenantId
|
|
27
|
+
|
|
28
|
+
function slugify(s: string): string {
|
|
29
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
|
30
|
+
}
|
|
31
|
+
function round2(n: number): number {
|
|
32
|
+
return Math.round(n * 100) / 100
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Row → domain mappers ------------------------------------------------------
|
|
36
|
+
function rowToCourse(r: any): Course {
|
|
37
|
+
return {
|
|
38
|
+
id: r.id, slug: r.slug, title: r.title, subtitle: r.subtitle ?? null,
|
|
39
|
+
description: r.description ?? null, thumbnailUrl: r.thumbnail_url ?? null,
|
|
40
|
+
price: r.price ?? 0, currency: r.currency ?? 'BRL', status: r.status ?? 'draft',
|
|
41
|
+
sortOrder: r.sort_order ?? 0, createdAt: r.created_at, updatedAt: r.updated_at,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function rowToModule(r: any): Module {
|
|
45
|
+
return { id: r.id, courseId: r.course_id, title: r.title, sortOrder: r.sort_order ?? 0 }
|
|
46
|
+
}
|
|
47
|
+
function rowToLesson(r: any): Lesson {
|
|
48
|
+
return {
|
|
49
|
+
id: r.id, courseId: r.course_id, moduleId: r.module_id, title: r.title,
|
|
50
|
+
description: r.description ?? null, videoUrl: r.video_url ?? '',
|
|
51
|
+
durationSec: r.duration_sec ?? 600, sortOrder: r.sort_order ?? 0,
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function rowToOffer(r: any): Offer {
|
|
55
|
+
return {
|
|
56
|
+
id: r.id, courseId: r.course_id, name: r.name, price: r.price ?? 0,
|
|
57
|
+
currency: r.currency ?? 'BRL', kind: r.kind ?? 'one_time',
|
|
58
|
+
recurringInterval: r.recurring_interval ?? null,
|
|
59
|
+
isDefault: r.is_default ?? false, isOrderBump: r.is_order_bump ?? false,
|
|
60
|
+
sortOrder: r.sort_order ?? 0,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function rowToEnrollment(r: any): Enrollment {
|
|
64
|
+
return { id: r.id, courseId: r.course_id, customerId: r.customer_id, status: r.status ?? 'active', enrolledAt: r.enrolled_at }
|
|
65
|
+
}
|
|
66
|
+
function rowToProgress(r: any): Progress {
|
|
67
|
+
return {
|
|
68
|
+
id: r.id, enrollmentId: r.enrollment_id, lessonId: r.lesson_id,
|
|
69
|
+
completed: r.completed ?? false, lastPositionSec: r.last_position_sec ?? 0,
|
|
70
|
+
completedAt: r.completed_at ?? null,
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function rowToOrder(r: any): Order {
|
|
74
|
+
return {
|
|
75
|
+
id: r.id, courseId: r.course_id, offerId: r.offer_id ?? null,
|
|
76
|
+
customerId: r.customer_id ?? null, customerName: r.customer_name ?? null,
|
|
77
|
+
customerEmail: r.customer_email ?? null, currency: r.currency ?? 'BRL',
|
|
78
|
+
total: r.total ?? 0, platformFee: r.platform_fee ?? 0, netValue: r.net_value ?? 0,
|
|
79
|
+
paymentMethod: r.payment_method ?? null, financialStatus: r.financial_status ?? 'pending',
|
|
80
|
+
stripePaymentIntentId: r.stripe_payment_intent_id ?? null, createdAt: r.created_at,
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function rowToSubscription(r: any): Subscription {
|
|
84
|
+
return {
|
|
85
|
+
id: r.id, courseId: r.course_id, offerId: r.offer_id ?? null,
|
|
86
|
+
customerId: r.customer_id ?? null, customerName: r.customer_name ?? null,
|
|
87
|
+
customerEmail: r.customer_email ?? null, currency: r.currency ?? 'BRL',
|
|
88
|
+
netValue: r.net_value ?? 0, interval: r.interval ?? 'month',
|
|
89
|
+
status: r.status ?? 'active', stripeSubscriptionId: r.stripe_subscription_id ?? null,
|
|
90
|
+
startedAt: r.started_at, canceledAt: r.canceled_at ?? null,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function rowToPayout(r: any): Payout {
|
|
94
|
+
return { id: r.id, amount: r.amount ?? 0, currency: r.currency ?? 'BRL', status: r.status ?? 'pending', createdAt: r.created_at }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function createSupabaseCoursesProvider(): CoursesProvider {
|
|
98
|
+
const scoped = (q: any) => {
|
|
99
|
+
const tenantId = getTenantId()
|
|
100
|
+
return tenantId ? q.eq('tenant_id', tenantId) : q
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
// Courses ---------------------------------------------------------------
|
|
105
|
+
async listCourses(opts?: ListCoursesOptions): Promise<Course[]> {
|
|
106
|
+
let q = scoped(getDb().from('course_courses').select('*'))
|
|
107
|
+
if (opts?.status) q = q.eq('status', opts.status)
|
|
108
|
+
if (opts?.slug) q = q.eq('slug', opts.slug)
|
|
109
|
+
if (opts?.search) q = q.ilike('title', `%${opts.search}%`)
|
|
110
|
+
const { data, error } = await q.order('sort_order', { ascending: true })
|
|
111
|
+
if (error) throw error
|
|
112
|
+
return (data ?? []).map(rowToCourse)
|
|
113
|
+
},
|
|
114
|
+
async getCourse(idOrSlug: string): Promise<Course | null> {
|
|
115
|
+
const col = /^[0-9a-f-]{36}$/i.test(idOrSlug) ? 'id' : 'slug'
|
|
116
|
+
const { data, error } = await scoped(getDb().from('course_courses').select('*').eq(col, idOrSlug)).maybeSingle()
|
|
117
|
+
if (error) throw error
|
|
118
|
+
return data ? rowToCourse(data) : null
|
|
119
|
+
},
|
|
120
|
+
async createCourse(input: CreateCourseInput): Promise<Course> {
|
|
121
|
+
const { data, error } = await getDb().from('course_courses').insert({
|
|
122
|
+
tenant_id: getTenantId(),
|
|
123
|
+
slug: input.slug ?? slugify(input.title),
|
|
124
|
+
title: input.title, subtitle: input.subtitle ?? null, description: input.description ?? null,
|
|
125
|
+
thumbnail_url: input.thumbnailUrl ?? null, price: input.price ?? 0,
|
|
126
|
+
currency: input.currency ?? 'BRL', status: input.status ?? 'draft', sort_order: input.sortOrder ?? 0,
|
|
127
|
+
}).select('*').single()
|
|
128
|
+
if (error) throw error
|
|
129
|
+
return rowToCourse(data)
|
|
130
|
+
},
|
|
131
|
+
async updateCourse(id: string, input: UpdateCourseInput): Promise<Course> {
|
|
132
|
+
const patch: any = {}
|
|
133
|
+
if (input.title !== undefined) patch.title = input.title
|
|
134
|
+
if (input.slug !== undefined) patch.slug = input.slug
|
|
135
|
+
if (input.subtitle !== undefined) patch.subtitle = input.subtitle
|
|
136
|
+
if (input.description !== undefined) patch.description = input.description
|
|
137
|
+
if (input.thumbnailUrl !== undefined) patch.thumbnail_url = input.thumbnailUrl
|
|
138
|
+
if (input.price !== undefined) patch.price = input.price
|
|
139
|
+
if (input.currency !== undefined) patch.currency = input.currency
|
|
140
|
+
if (input.status !== undefined) patch.status = input.status
|
|
141
|
+
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
142
|
+
const { data, error } = await scoped(getDb().from('course_courses').update(patch).eq('id', id)).select('*').single()
|
|
143
|
+
if (error) throw error
|
|
144
|
+
return rowToCourse(data)
|
|
145
|
+
},
|
|
146
|
+
async deleteCourse(id: string): Promise<void> {
|
|
147
|
+
const { error } = await scoped(getDb().from('course_courses').delete().eq('id', id))
|
|
148
|
+
if (error) throw error
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
// Modules ---------------------------------------------------------------
|
|
152
|
+
async listModules(courseId: string): Promise<Module[]> {
|
|
153
|
+
const { data, error } = await scoped(getDb().from('course_modules').select('*').eq('course_id', courseId)).order('sort_order', { ascending: true })
|
|
154
|
+
if (error) throw error
|
|
155
|
+
return (data ?? []).map(rowToModule)
|
|
156
|
+
},
|
|
157
|
+
async createModule(input: CreateModuleInput): Promise<Module> {
|
|
158
|
+
const { data, error } = await getDb().from('course_modules').insert({
|
|
159
|
+
tenant_id: getTenantId(), course_id: input.courseId, title: input.title, sort_order: input.sortOrder ?? 0,
|
|
160
|
+
}).select('*').single()
|
|
161
|
+
if (error) throw error
|
|
162
|
+
return rowToModule(data)
|
|
163
|
+
},
|
|
164
|
+
async updateModule(id: string, input: UpdateModuleInput): Promise<Module> {
|
|
165
|
+
const patch: any = {}
|
|
166
|
+
if (input.title !== undefined) patch.title = input.title
|
|
167
|
+
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
168
|
+
const { data, error } = await scoped(getDb().from('course_modules').update(patch).eq('id', id)).select('*').single()
|
|
169
|
+
if (error) throw error
|
|
170
|
+
return rowToModule(data)
|
|
171
|
+
},
|
|
172
|
+
async deleteModule(id: string): Promise<void> {
|
|
173
|
+
const { error } = await scoped(getDb().from('course_modules').delete().eq('id', id))
|
|
174
|
+
if (error) throw error
|
|
175
|
+
},
|
|
176
|
+
|
|
177
|
+
// Lessons ---------------------------------------------------------------
|
|
178
|
+
async listLessons(courseId: string): Promise<Lesson[]> {
|
|
179
|
+
const { data, error } = await scoped(getDb().from('course_lessons').select('*').eq('course_id', courseId)).order('sort_order', { ascending: true })
|
|
180
|
+
if (error) throw error
|
|
181
|
+
return (data ?? []).map(rowToLesson)
|
|
182
|
+
},
|
|
183
|
+
async getLesson(id: string): Promise<Lesson | null> {
|
|
184
|
+
const { data, error } = await scoped(getDb().from('course_lessons').select('*').eq('id', id)).maybeSingle()
|
|
185
|
+
if (error) throw error
|
|
186
|
+
return data ? rowToLesson(data) : null
|
|
187
|
+
},
|
|
188
|
+
async createLesson(input: CreateLessonInput): Promise<Lesson> {
|
|
189
|
+
const { data, error } = await getDb().from('course_lessons').insert({
|
|
190
|
+
tenant_id: getTenantId(), course_id: input.courseId, module_id: input.moduleId,
|
|
191
|
+
title: input.title, description: input.description ?? null, video_url: input.videoUrl,
|
|
192
|
+
duration_sec: input.durationSec ?? 600, sort_order: input.sortOrder ?? 0,
|
|
193
|
+
}).select('*').single()
|
|
194
|
+
if (error) throw error
|
|
195
|
+
return rowToLesson(data)
|
|
196
|
+
},
|
|
197
|
+
async updateLesson(id: string, input: UpdateLessonInput): Promise<Lesson> {
|
|
198
|
+
const patch: any = {}
|
|
199
|
+
if (input.title !== undefined) patch.title = input.title
|
|
200
|
+
if (input.description !== undefined) patch.description = input.description
|
|
201
|
+
if (input.videoUrl !== undefined) patch.video_url = input.videoUrl
|
|
202
|
+
if (input.durationSec !== undefined) patch.duration_sec = input.durationSec
|
|
203
|
+
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
204
|
+
const { data, error } = await scoped(getDb().from('course_lessons').update(patch).eq('id', id)).select('*').single()
|
|
205
|
+
if (error) throw error
|
|
206
|
+
return rowToLesson(data)
|
|
207
|
+
},
|
|
208
|
+
async deleteLesson(id: string): Promise<void> {
|
|
209
|
+
const { error } = await scoped(getDb().from('course_lessons').delete().eq('id', id))
|
|
210
|
+
if (error) throw error
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
// Enrollments + progress ------------------------------------------------
|
|
214
|
+
async listEnrollments(customerId: string): Promise<Enrollment[]> {
|
|
215
|
+
const { data, error } = await getDb().from('course_enrollments').select('*').eq('customer_id', customerId)
|
|
216
|
+
if (error) throw error
|
|
217
|
+
return (data ?? []).map(rowToEnrollment)
|
|
218
|
+
},
|
|
219
|
+
async enroll(courseId: string, customerId: string): Promise<Enrollment> {
|
|
220
|
+
const { data, error } = await getDb().from('course_enrollments')
|
|
221
|
+
.upsert({ tenant_id: getTenantId(), course_id: courseId, customer_id: customerId, status: 'active' },
|
|
222
|
+
{ onConflict: 'course_id,customer_id' })
|
|
223
|
+
.select('*').single()
|
|
224
|
+
if (error) throw error
|
|
225
|
+
return rowToEnrollment(data)
|
|
226
|
+
},
|
|
227
|
+
async listProgress(enrollmentId: string): Promise<Progress[]> {
|
|
228
|
+
const { data, error } = await getDb().from('course_progress').select('*').eq('enrollment_id', enrollmentId)
|
|
229
|
+
if (error) throw error
|
|
230
|
+
return (data ?? []).map(rowToProgress)
|
|
231
|
+
},
|
|
232
|
+
async setLessonProgress(enrollmentId: string, lessonId: string, patch: { completed?: boolean; lastPositionSec?: number }): Promise<Progress> {
|
|
233
|
+
const row: any = { tenant_id: getTenantId(), enrollment_id: enrollmentId, lesson_id: lessonId }
|
|
234
|
+
if (patch.completed !== undefined) { row.completed = patch.completed; row.completed_at = patch.completed ? new Date().toISOString() : null }
|
|
235
|
+
if (patch.lastPositionSec !== undefined) row.last_position_sec = patch.lastPositionSec
|
|
236
|
+
const { data, error } = await getDb().from('course_progress')
|
|
237
|
+
.upsert(row, { onConflict: 'enrollment_id,lesson_id' }).select('*').single()
|
|
238
|
+
if (error) throw error
|
|
239
|
+
return rowToProgress(data)
|
|
240
|
+
},
|
|
241
|
+
|
|
242
|
+
// Offers ----------------------------------------------------------------
|
|
243
|
+
async listOffers(courseId: string): Promise<Offer[]> {
|
|
244
|
+
const { data, error } = await scoped(getDb().from('course_offers').select('*').eq('course_id', courseId)).order('sort_order', { ascending: true })
|
|
245
|
+
if (error) throw error
|
|
246
|
+
return (data ?? []).map(rowToOffer)
|
|
247
|
+
},
|
|
248
|
+
async createOffer(input: CreateOfferInput): Promise<Offer> {
|
|
249
|
+
const { data, error } = await getDb().from('course_offers').insert({
|
|
250
|
+
tenant_id: getTenantId(), course_id: input.courseId, name: input.name, price: input.price,
|
|
251
|
+
currency: input.currency ?? 'BRL', kind: input.kind ?? 'one_time',
|
|
252
|
+
recurring_interval: input.recurringInterval ?? (input.kind === 'subscription' ? 'month' : null),
|
|
253
|
+
is_default: input.isDefault ?? false, is_order_bump: input.isOrderBump ?? false, sort_order: input.sortOrder ?? 0,
|
|
254
|
+
}).select('*').single()
|
|
255
|
+
if (error) throw error
|
|
256
|
+
return rowToOffer(data)
|
|
257
|
+
},
|
|
258
|
+
async updateOffer(id: string, input: UpdateOfferInput): Promise<Offer> {
|
|
259
|
+
const patch: any = {}
|
|
260
|
+
if (input.name !== undefined) patch.name = input.name
|
|
261
|
+
if (input.price !== undefined) patch.price = input.price
|
|
262
|
+
if (input.currency !== undefined) patch.currency = input.currency
|
|
263
|
+
if (input.kind !== undefined) patch.kind = input.kind
|
|
264
|
+
if (input.recurringInterval !== undefined) patch.recurring_interval = input.recurringInterval
|
|
265
|
+
if (input.isDefault !== undefined) patch.is_default = input.isDefault
|
|
266
|
+
if (input.isOrderBump !== undefined) patch.is_order_bump = input.isOrderBump
|
|
267
|
+
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
268
|
+
const { data, error } = await scoped(getDb().from('course_offers').update(patch).eq('id', id)).select('*').single()
|
|
269
|
+
if (error) throw error
|
|
270
|
+
return rowToOffer(data)
|
|
271
|
+
},
|
|
272
|
+
async deleteOffer(id: string): Promise<void> {
|
|
273
|
+
const { error } = await scoped(getDb().from('course_offers').delete().eq('id', id))
|
|
274
|
+
if (error) throw error
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
// Sales -----------------------------------------------------------------
|
|
278
|
+
async listOrders(opts?: ListOrdersOptions): Promise<Order[]> {
|
|
279
|
+
let q = scoped(getDb().from('course_orders').select('*'))
|
|
280
|
+
if (opts?.courseId) q = q.eq('course_id', opts.courseId)
|
|
281
|
+
if (opts?.financialStatus) q = q.eq('financial_status', opts.financialStatus)
|
|
282
|
+
if (opts?.search) q = q.or(`customer_name.ilike.%${opts.search}%,customer_email.ilike.%${opts.search}%`)
|
|
283
|
+
const { data, error } = await q.order('created_at', { ascending: false })
|
|
284
|
+
if (error) throw error
|
|
285
|
+
return (data ?? []).map(rowToOrder)
|
|
286
|
+
},
|
|
287
|
+
|
|
288
|
+
// Subscriptions ---------------------------------------------------------
|
|
289
|
+
async listSubscriptions(opts?: ListSubscriptionsOptions): Promise<Subscription[]> {
|
|
290
|
+
let q = scoped(getDb().from('course_subscriptions').select('*'))
|
|
291
|
+
if (opts?.courseId) q = q.eq('course_id', opts.courseId)
|
|
292
|
+
if (opts?.status) q = q.eq('status', opts.status)
|
|
293
|
+
const { data, error } = await q.order('started_at', { ascending: false })
|
|
294
|
+
if (error) throw error
|
|
295
|
+
return (data ?? []).map(rowToSubscription)
|
|
296
|
+
},
|
|
297
|
+
|
|
298
|
+
// Financial -------------------------------------------------------------
|
|
299
|
+
async getFinancialSummary(): Promise<FinancialSummary> {
|
|
300
|
+
const [orders, subs, payouts] = await Promise.all([
|
|
301
|
+
scoped(getDb().from('course_orders').select('total,platform_fee,net_value,financial_status')),
|
|
302
|
+
scoped(getDb().from('course_subscriptions').select('net_value,interval,status')),
|
|
303
|
+
scoped(getDb().from('course_payouts').select('amount,status')),
|
|
304
|
+
])
|
|
305
|
+
const orderRows: any[] = orders.data ?? []
|
|
306
|
+
const paid = orderRows.filter((o) => o.financial_status === 'paid')
|
|
307
|
+
const refunded = orderRows.filter((o) => o.financial_status === 'refunded')
|
|
308
|
+
const activeSubs = (subs.data ?? []).filter((s: any) => s.status === 'active')
|
|
309
|
+
const netTotal = round2(paid.reduce((s, o) => s + Number(o.net_value ?? 0), 0))
|
|
310
|
+
const paidOut = round2((payouts.data ?? []).filter((p: any) => p.status === 'paid').reduce((s: number, p: any) => s + Number(p.amount ?? 0), 0))
|
|
311
|
+
const mrr = round2(activeSubs.reduce((s: number, sub: any) => s + (sub.interval === 'year' ? Number(sub.net_value) / 12 : Number(sub.net_value)), 0))
|
|
312
|
+
const totalCount = paid.length + refunded.length
|
|
313
|
+
return {
|
|
314
|
+
currency: 'BRL',
|
|
315
|
+
availableBalance: round2(Math.max(netTotal - paidOut, 0)),
|
|
316
|
+
pendingBalance: round2(orderRows.filter((o) => o.financial_status === 'pending').reduce((s, o) => s + Number(o.net_value ?? 0), 0)),
|
|
317
|
+
totalRevenue: round2(paid.reduce((s, o) => s + Number(o.total ?? 0), 0)),
|
|
318
|
+
platformFeeTotal: round2(paid.reduce((s, o) => s + Number(o.platform_fee ?? 0), 0)),
|
|
319
|
+
salesCount: paid.length,
|
|
320
|
+
activeSubscriptions: activeSubs.length,
|
|
321
|
+
mrr,
|
|
322
|
+
refundRate: totalCount > 0 ? refunded.length / totalCount : 0,
|
|
323
|
+
conversionRate: 0,
|
|
324
|
+
}
|
|
325
|
+
},
|
|
326
|
+
async listPayouts(): Promise<Payout[]> {
|
|
327
|
+
const { data, error } = await scoped(getDb().from('course_payouts').select('*')).order('created_at', { ascending: false })
|
|
328
|
+
if (error) throw error
|
|
329
|
+
return (data ?? []).map(rowToPayout)
|
|
330
|
+
},
|
|
331
|
+
async getCreatorAccount(): Promise<CreatorAccount> {
|
|
332
|
+
const tenantId = getTenantId()
|
|
333
|
+
const { data } = await scoped(getDb().from('course_creator_accounts').select('*')).maybeSingle()
|
|
334
|
+
return {
|
|
335
|
+
tenantId: tenantId ?? '',
|
|
336
|
+
stripeAccountId: data?.stripe_account_id ?? null,
|
|
337
|
+
chargesEnabled: data?.charges_enabled ?? false,
|
|
338
|
+
payoutsEnabled: data?.payouts_enabled ?? false,
|
|
339
|
+
defaultCurrency: data?.default_currency ?? 'BRL',
|
|
340
|
+
platformFeeBps: data?.platform_fee_bps ?? 500,
|
|
341
|
+
}
|
|
342
|
+
},
|
|
343
|
+
}
|
|
344
|
+
}
|
package/src/tenant.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Tenant scoping for course queries. @fayz-ai/courses has no dependency on
|
|
2
|
+
// @fayz-ai/saas — the host app (or @fayz-ai/plugin-courses) registers a resolver
|
|
3
|
+
// that returns the current tenant id (the creator that owns the courses). When
|
|
4
|
+
// no resolver is set, queries are unscoped (RLS still applies server-side).
|
|
5
|
+
|
|
6
|
+
export type TenantResolver = () => string | undefined
|
|
7
|
+
|
|
8
|
+
let _resolver: TenantResolver | null = null
|
|
9
|
+
|
|
10
|
+
export function setCoursesTenantResolver(resolver: TenantResolver): void {
|
|
11
|
+
_resolver = resolver
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function getCoursesTenantId(): string | undefined {
|
|
15
|
+
if (!_resolver) return undefined
|
|
16
|
+
try {
|
|
17
|
+
return _resolver()
|
|
18
|
+
} catch {
|
|
19
|
+
return undefined
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -106,3 +106,134 @@ export interface EnrolledCourse {
|
|
|
106
106
|
/** 0..100 */
|
|
107
107
|
progressPercent: number
|
|
108
108
|
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// Commerce layer — the "mini-Kiwify" money model. A Course is the product; an
|
|
112
|
+
// Offer is a sellable price point (one-time or recurring). An Order is a
|
|
113
|
+
// concluded sale; a Subscription is a recurring plan. CreatorAccount holds the
|
|
114
|
+
// Stripe Connect link + the platform markup. All of these are tenant-scoped in
|
|
115
|
+
// the real backend (the creator that owns the course).
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
export type OfferKind = 'one_time' | 'subscription'
|
|
119
|
+
export type RecurringInterval = 'month' | 'year'
|
|
120
|
+
|
|
121
|
+
export interface Offer {
|
|
122
|
+
id: string
|
|
123
|
+
courseId: string
|
|
124
|
+
name: string
|
|
125
|
+
price: number
|
|
126
|
+
currency: string
|
|
127
|
+
kind: OfferKind
|
|
128
|
+
/** Set when kind === 'subscription'; null for one-time offers. */
|
|
129
|
+
recurringInterval: RecurringInterval | null
|
|
130
|
+
/** The offer pre-selected on the checkout (Kiwify's "default offer"). */
|
|
131
|
+
isDefault: boolean
|
|
132
|
+
/** Shown as an order-bump on another offer's checkout. */
|
|
133
|
+
isOrderBump: boolean
|
|
134
|
+
sortOrder: number
|
|
135
|
+
}
|
|
136
|
+
export interface CreateOfferInput {
|
|
137
|
+
courseId: string
|
|
138
|
+
name: string
|
|
139
|
+
price: number
|
|
140
|
+
currency?: string
|
|
141
|
+
kind?: OfferKind
|
|
142
|
+
recurringInterval?: RecurringInterval | null
|
|
143
|
+
isDefault?: boolean
|
|
144
|
+
isOrderBump?: boolean
|
|
145
|
+
sortOrder?: number
|
|
146
|
+
}
|
|
147
|
+
export type UpdateOfferInput = Partial<Omit<CreateOfferInput, 'courseId'>>
|
|
148
|
+
|
|
149
|
+
export type PaymentMethod = 'card' | 'pix' | 'boleto'
|
|
150
|
+
export type FinancialStatus = 'pending' | 'paid' | 'refunded' | 'chargeback'
|
|
151
|
+
|
|
152
|
+
/** A concluded (or pending) sale — the Sales ledger row. */
|
|
153
|
+
export interface Order {
|
|
154
|
+
id: string
|
|
155
|
+
courseId: string
|
|
156
|
+
offerId: string | null
|
|
157
|
+
customerId: string | null
|
|
158
|
+
customerName: string | null
|
|
159
|
+
customerEmail: string | null
|
|
160
|
+
currency: string
|
|
161
|
+
/** Gross amount charged to the student. */
|
|
162
|
+
total: number
|
|
163
|
+
/** The platform's markup on this sale (Stripe application_fee). */
|
|
164
|
+
platformFee: number
|
|
165
|
+
/** total - platformFee — what the creator receives. */
|
|
166
|
+
netValue: number
|
|
167
|
+
paymentMethod: PaymentMethod | null
|
|
168
|
+
financialStatus: FinancialStatus
|
|
169
|
+
stripePaymentIntentId: string | null
|
|
170
|
+
createdAt: string
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export type SubscriptionStatus = 'active' | 'canceled' | 'past_due'
|
|
174
|
+
|
|
175
|
+
export interface Subscription {
|
|
176
|
+
id: string
|
|
177
|
+
courseId: string
|
|
178
|
+
offerId: string | null
|
|
179
|
+
customerId: string | null
|
|
180
|
+
customerName: string | null
|
|
181
|
+
customerEmail: string | null
|
|
182
|
+
currency: string
|
|
183
|
+
/** Per-period net value to the creator. */
|
|
184
|
+
netValue: number
|
|
185
|
+
interval: RecurringInterval
|
|
186
|
+
status: SubscriptionStatus
|
|
187
|
+
stripeSubscriptionId: string | null
|
|
188
|
+
startedAt: string
|
|
189
|
+
canceledAt: string | null
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export type PayoutStatus = 'pending' | 'paid' | 'failed'
|
|
193
|
+
|
|
194
|
+
export interface Payout {
|
|
195
|
+
id: string
|
|
196
|
+
amount: number
|
|
197
|
+
currency: string
|
|
198
|
+
status: PayoutStatus
|
|
199
|
+
createdAt: string
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The creator's Stripe Connect account + platform markup config (1:1 tenant). */
|
|
203
|
+
export interface CreatorAccount {
|
|
204
|
+
tenantId: string
|
|
205
|
+
stripeAccountId: string | null
|
|
206
|
+
chargesEnabled: boolean
|
|
207
|
+
payoutsEnabled: boolean
|
|
208
|
+
defaultCurrency: string
|
|
209
|
+
/** Platform markup in basis points (e.g. 500 = 5%). Drives Order.platformFee. */
|
|
210
|
+
platformFeeBps: number
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Aggregates for the Financial page + dashboard KPIs. */
|
|
214
|
+
export interface FinancialSummary {
|
|
215
|
+
currency: string
|
|
216
|
+
availableBalance: number
|
|
217
|
+
pendingBalance: number
|
|
218
|
+
/** Sum of paid orders' total. */
|
|
219
|
+
totalRevenue: number
|
|
220
|
+
platformFeeTotal: number
|
|
221
|
+
salesCount: number
|
|
222
|
+
activeSubscriptions: number
|
|
223
|
+
/** Monthly recurring revenue (net). */
|
|
224
|
+
mrr: number
|
|
225
|
+
/** 0..1 */
|
|
226
|
+
refundRate: number
|
|
227
|
+
/** 0..1 (placeholder in the mock layer). */
|
|
228
|
+
conversionRate: number
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export interface ListOrdersOptions {
|
|
232
|
+
courseId?: string
|
|
233
|
+
financialStatus?: FinancialStatus
|
|
234
|
+
search?: string
|
|
235
|
+
}
|
|
236
|
+
export interface ListSubscriptionsOptions {
|
|
237
|
+
courseId?: string
|
|
238
|
+
status?: SubscriptionStatus
|
|
239
|
+
}
|