@fayz-ai/courses 0.9.0 → 0.10.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/README.md +1 -1
- package/dist/{mock-provider.d.ts → data/mock-provider.d.ts} +1 -1
- package/dist/data/mock-provider.d.ts.map +1 -0
- package/dist/{provider.d.ts → data/provider.d.ts} +1 -1
- package/dist/data/provider.d.ts.map +1 -0
- package/dist/data/safe-provider.d.ts.map +1 -0
- package/dist/{seed.d.ts → data/seed.d.ts} +1 -1
- package/dist/data/seed.d.ts.map +1 -0
- package/dist/data/supabase-provider.d.ts.map +1 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/data/tenant.d.ts.map +1 -0
- package/dist/{hooks.d.ts → hooks/index.d.ts} +2 -2
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/index.d.ts +10 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/package.json +3 -5
- package/dist/hooks.d.ts.map +0 -1
- package/dist/mock-provider.d.ts.map +0 -1
- package/dist/provider.d.ts.map +0 -1
- package/dist/safe-provider.d.ts.map +0 -1
- package/dist/seed.d.ts.map +0 -1
- package/dist/supabase-provider.d.ts.map +0 -1
- package/dist/tables.d.ts.map +0 -1
- package/dist/tenant.d.ts.map +0 -1
- package/src/hooks.ts +0 -125
- package/src/index.ts +0 -33
- package/src/mock-provider.ts +0 -369
- package/src/provider.ts +0 -85
- package/src/safe-provider.ts +0 -17
- package/src/seed.ts +0 -297
- package/src/supabase-provider.ts +0 -425
- package/src/tables.ts +0 -18
- package/src/tenant.ts +0 -21
- package/src/types.ts +0 -268
- /package/dist/{safe-provider.d.ts → data/safe-provider.d.ts} +0 -0
- /package/dist/{supabase-provider.d.ts → data/supabase-provider.d.ts} +0 -0
- /package/dist/{tables.d.ts → data/tables.d.ts} +0 -0
- /package/dist/{tenant.d.ts → data/tenant.d.ts} +0 -0
package/src/supabase-provider.ts
DELETED
|
@@ -1,425 +0,0 @@
|
|
|
1
|
-
import { getSupabaseClientOptional } from '@fayz-ai/core'
|
|
2
|
-
import type { CoursesProvider } from './provider'
|
|
3
|
-
import { getCoursesTenantId } from './tenant'
|
|
4
|
-
import { T } from './tables'
|
|
5
|
-
import type {
|
|
6
|
-
Course, Module, Lesson, Enrollment, Progress,
|
|
7
|
-
CreateCourseInput, UpdateCourseInput,
|
|
8
|
-
CreateModuleInput, UpdateModuleInput,
|
|
9
|
-
CreateLessonInput, UpdateLessonInput,
|
|
10
|
-
ListCoursesOptions,
|
|
11
|
-
Offer, CreateOfferInput, UpdateOfferInput,
|
|
12
|
-
Order, OrderDetail, OrderInstallment, PaymentMethod, ListOrdersOptions, FinancialStatus,
|
|
13
|
-
Subscription, ListSubscriptionsOptions,
|
|
14
|
-
Payout, CreatorAccount, FinancialSummary,
|
|
15
|
-
} from './types'
|
|
16
|
-
|
|
17
|
-
// Supabase-backed CoursesProvider for the central "fayz-course" DB. Every query
|
|
18
|
-
// is tenant-scoped (creator) via getCoursesTenantId(); RLS enforces isolation
|
|
19
|
-
// server-side regardless. Mirrors @fayz-ai/shop's supabase-provider.
|
|
20
|
-
|
|
21
|
-
function getDb(): any {
|
|
22
|
-
const supabase = getSupabaseClientOptional()
|
|
23
|
-
if (!supabase) throw new Error('@fayz-ai/courses: Supabase client not initialized. Call setGlobalSupabaseClient() first.')
|
|
24
|
-
return supabase
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const getTenantId = getCoursesTenantId
|
|
28
|
-
|
|
29
|
-
function slugify(s: string): string {
|
|
30
|
-
return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
|
31
|
-
}
|
|
32
|
-
function round2(n: number): number {
|
|
33
|
-
return Math.round(n * 100) / 100
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// Row → domain mappers ------------------------------------------------------
|
|
37
|
-
function rowToCourse(r: any): Course {
|
|
38
|
-
return {
|
|
39
|
-
id: r.id, slug: r.slug, title: r.title, subtitle: r.subtitle ?? null,
|
|
40
|
-
description: r.description ?? null, thumbnailUrl: r.thumbnail_url ?? null,
|
|
41
|
-
price: r.price ?? 0, currency: r.currency ?? 'BRL', status: r.status ?? 'draft',
|
|
42
|
-
deliveryType: r.delivery_type ?? 'online',
|
|
43
|
-
sortOrder: r.sort_order ?? 0, createdAt: r.created_at, updatedAt: r.updated_at,
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
function rowToModule(r: any): Module {
|
|
47
|
-
return { id: r.id, courseId: r.course_id, title: r.title, sortOrder: r.sort_order ?? 0 }
|
|
48
|
-
}
|
|
49
|
-
function rowToLesson(r: any): Lesson {
|
|
50
|
-
return {
|
|
51
|
-
id: r.id, courseId: r.course_id, moduleId: r.module_id, title: r.title,
|
|
52
|
-
description: r.description ?? null, videoUrl: r.video_url ?? '',
|
|
53
|
-
durationSec: r.duration_sec ?? 600, sortOrder: r.sort_order ?? 0,
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
function rowToOffer(r: any): Offer {
|
|
57
|
-
return {
|
|
58
|
-
id: r.id, courseId: r.course_id, name: r.name, price: r.price ?? 0,
|
|
59
|
-
currency: r.currency ?? 'BRL', kind: r.kind ?? 'one_time',
|
|
60
|
-
recurringInterval: r.recurring_interval ?? null,
|
|
61
|
-
isDefault: r.is_default ?? false, isOrderBump: r.is_order_bump ?? false,
|
|
62
|
-
sortOrder: r.sort_order ?? 0,
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
function rowToEnrollment(r: any): Enrollment {
|
|
66
|
-
return { id: r.id, courseId: r.course_id, customerId: r.customer_id, status: r.status ?? 'active', enrolledAt: r.enrolled_at }
|
|
67
|
-
}
|
|
68
|
-
function rowToProgress(r: any): Progress {
|
|
69
|
-
return {
|
|
70
|
-
id: r.id, enrollmentId: r.enrollment_id, lessonId: r.lesson_id,
|
|
71
|
-
completed: r.completed ?? false, lastPositionSec: r.last_position_sec ?? 0,
|
|
72
|
-
completedAt: r.completed_at ?? null,
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
function rowToOrder(r: any): Order {
|
|
76
|
-
return {
|
|
77
|
-
id: r.id, courseId: r.course_id, offerId: r.offer_id ?? null,
|
|
78
|
-
customerId: r.customer_id ?? null, customerName: r.customer_name ?? null,
|
|
79
|
-
customerEmail: r.customer_email ?? null, currency: r.currency ?? 'BRL',
|
|
80
|
-
total: r.total ?? 0, platformFee: r.platform_fee ?? 0, netValue: r.net_value ?? 0,
|
|
81
|
-
paymentMethod: r.payment_method ?? null, financialStatus: r.financial_status ?? 'pending',
|
|
82
|
-
stripePaymentIntentId: r.stripe_payment_intent_id ?? null, createdAt: r.created_at,
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
function rowToSubscription(r: any): Subscription {
|
|
86
|
-
return {
|
|
87
|
-
id: r.id, courseId: r.course_id, offerId: r.offer_id ?? null,
|
|
88
|
-
customerId: r.customer_id ?? null, customerName: r.customer_name ?? null,
|
|
89
|
-
customerEmail: r.customer_email ?? null, currency: r.currency ?? 'BRL',
|
|
90
|
-
netValue: r.net_value ?? 0, interval: r.interval ?? 'month',
|
|
91
|
-
status: r.status ?? 'active', stripeSubscriptionId: r.stripe_subscription_id ?? null,
|
|
92
|
-
startedAt: r.started_at, canceledAt: r.canceled_at ?? null,
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
function rowToPayout(r: any): Payout {
|
|
96
|
-
return { id: r.id, amount: r.amount ?? 0, currency: r.currency ?? 'BRL', status: r.status ?? 'pending', createdAt: r.created_at }
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export function createSupabaseCoursesProvider(): CoursesProvider {
|
|
100
|
-
const scoped = (q: any) => {
|
|
101
|
-
const tenantId = getTenantId()
|
|
102
|
-
return tenantId ? q.eq('tenant_id', tenantId) : q
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
return {
|
|
106
|
-
// Courses ---------------------------------------------------------------
|
|
107
|
-
async listCourses(opts?: ListCoursesOptions): Promise<Course[]> {
|
|
108
|
-
let q = scoped(getDb().from(T.courses).select('*'))
|
|
109
|
-
if (opts?.status) q = q.eq('status', opts.status)
|
|
110
|
-
if (opts?.slug) q = q.eq('slug', opts.slug)
|
|
111
|
-
if (opts?.search) q = q.ilike('title', `%${opts.search}%`)
|
|
112
|
-
const { data, error } = await q.order('sort_order', { ascending: true })
|
|
113
|
-
if (error) throw error
|
|
114
|
-
return (data ?? []).map(rowToCourse)
|
|
115
|
-
},
|
|
116
|
-
async getCourse(idOrSlug: string): Promise<Course | null> {
|
|
117
|
-
const col = /^[0-9a-f-]{36}$/i.test(idOrSlug) ? 'id' : 'slug'
|
|
118
|
-
const { data, error } = await scoped(getDb().from(T.courses).select('*').eq(col, idOrSlug)).maybeSingle()
|
|
119
|
-
if (error) throw error
|
|
120
|
-
return data ? rowToCourse(data) : null
|
|
121
|
-
},
|
|
122
|
-
async createCourse(input: CreateCourseInput): Promise<Course> {
|
|
123
|
-
const { data, error } = await getDb().from(T.courses).insert({
|
|
124
|
-
tenant_id: getTenantId(),
|
|
125
|
-
slug: input.slug ?? slugify(input.title),
|
|
126
|
-
title: input.title, subtitle: input.subtitle ?? null, description: input.description ?? null,
|
|
127
|
-
thumbnail_url: input.thumbnailUrl ?? null, price: input.price ?? 0,
|
|
128
|
-
currency: input.currency ?? 'BRL', status: input.status ?? 'draft',
|
|
129
|
-
delivery_type: input.deliveryType ?? 'online', sort_order: input.sortOrder ?? 0,
|
|
130
|
-
}).select('*').single()
|
|
131
|
-
if (error) throw error
|
|
132
|
-
return rowToCourse(data)
|
|
133
|
-
},
|
|
134
|
-
async updateCourse(id: string, input: UpdateCourseInput): Promise<Course> {
|
|
135
|
-
const patch: any = {}
|
|
136
|
-
if (input.title !== undefined) patch.title = input.title
|
|
137
|
-
if (input.slug !== undefined) patch.slug = input.slug
|
|
138
|
-
if (input.subtitle !== undefined) patch.subtitle = input.subtitle
|
|
139
|
-
if (input.description !== undefined) patch.description = input.description
|
|
140
|
-
if (input.thumbnailUrl !== undefined) patch.thumbnail_url = input.thumbnailUrl
|
|
141
|
-
if (input.price !== undefined) patch.price = input.price
|
|
142
|
-
if (input.currency !== undefined) patch.currency = input.currency
|
|
143
|
-
if (input.status !== undefined) patch.status = input.status
|
|
144
|
-
if (input.deliveryType !== undefined) patch.delivery_type = input.deliveryType
|
|
145
|
-
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
146
|
-
const { data, error } = await scoped(getDb().from(T.courses).update(patch).eq('id', id)).select('*').single()
|
|
147
|
-
if (error) throw error
|
|
148
|
-
return rowToCourse(data)
|
|
149
|
-
},
|
|
150
|
-
async deleteCourse(id: string): Promise<void> {
|
|
151
|
-
const { error } = await scoped(getDb().from(T.courses).delete().eq('id', id))
|
|
152
|
-
if (error) throw error
|
|
153
|
-
},
|
|
154
|
-
|
|
155
|
-
// Modules ---------------------------------------------------------------
|
|
156
|
-
async listModules(courseId: string): Promise<Module[]> {
|
|
157
|
-
const { data, error } = await scoped(getDb().from(T.modules).select('*').eq('course_id', courseId)).order('sort_order', { ascending: true })
|
|
158
|
-
if (error) throw error
|
|
159
|
-
return (data ?? []).map(rowToModule)
|
|
160
|
-
},
|
|
161
|
-
async createModule(input: CreateModuleInput): Promise<Module> {
|
|
162
|
-
const { data, error } = await getDb().from(T.modules).insert({
|
|
163
|
-
tenant_id: getTenantId(), course_id: input.courseId, title: input.title, sort_order: input.sortOrder ?? 0,
|
|
164
|
-
}).select('*').single()
|
|
165
|
-
if (error) throw error
|
|
166
|
-
return rowToModule(data)
|
|
167
|
-
},
|
|
168
|
-
async updateModule(id: string, input: UpdateModuleInput): Promise<Module> {
|
|
169
|
-
const patch: any = {}
|
|
170
|
-
if (input.title !== undefined) patch.title = input.title
|
|
171
|
-
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
172
|
-
const { data, error } = await scoped(getDb().from(T.modules).update(patch).eq('id', id)).select('*').single()
|
|
173
|
-
if (error) throw error
|
|
174
|
-
return rowToModule(data)
|
|
175
|
-
},
|
|
176
|
-
async deleteModule(id: string): Promise<void> {
|
|
177
|
-
const { error } = await scoped(getDb().from(T.modules).delete().eq('id', id))
|
|
178
|
-
if (error) throw error
|
|
179
|
-
},
|
|
180
|
-
|
|
181
|
-
// Lessons ---------------------------------------------------------------
|
|
182
|
-
async listLessons(courseId: string): Promise<Lesson[]> {
|
|
183
|
-
const { data, error } = await scoped(getDb().from(T.lessons).select('*').eq('course_id', courseId)).order('sort_order', { ascending: true })
|
|
184
|
-
if (error) throw error
|
|
185
|
-
return (data ?? []).map(rowToLesson)
|
|
186
|
-
},
|
|
187
|
-
async getLesson(id: string): Promise<Lesson | null> {
|
|
188
|
-
const { data, error } = await scoped(getDb().from(T.lessons).select('*').eq('id', id)).maybeSingle()
|
|
189
|
-
if (error) throw error
|
|
190
|
-
return data ? rowToLesson(data) : null
|
|
191
|
-
},
|
|
192
|
-
async createLesson(input: CreateLessonInput): Promise<Lesson> {
|
|
193
|
-
const { data, error } = await getDb().from(T.lessons).insert({
|
|
194
|
-
tenant_id: getTenantId(), course_id: input.courseId, module_id: input.moduleId,
|
|
195
|
-
title: input.title, description: input.description ?? null, video_url: input.videoUrl,
|
|
196
|
-
duration_sec: input.durationSec ?? 600, sort_order: input.sortOrder ?? 0,
|
|
197
|
-
}).select('*').single()
|
|
198
|
-
if (error) throw error
|
|
199
|
-
return rowToLesson(data)
|
|
200
|
-
},
|
|
201
|
-
async updateLesson(id: string, input: UpdateLessonInput): Promise<Lesson> {
|
|
202
|
-
const patch: any = {}
|
|
203
|
-
if (input.title !== undefined) patch.title = input.title
|
|
204
|
-
if (input.description !== undefined) patch.description = input.description
|
|
205
|
-
if (input.videoUrl !== undefined) patch.video_url = input.videoUrl
|
|
206
|
-
if (input.durationSec !== undefined) patch.duration_sec = input.durationSec
|
|
207
|
-
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
208
|
-
const { data, error } = await scoped(getDb().from(T.lessons).update(patch).eq('id', id)).select('*').single()
|
|
209
|
-
if (error) throw error
|
|
210
|
-
return rowToLesson(data)
|
|
211
|
-
},
|
|
212
|
-
async deleteLesson(id: string): Promise<void> {
|
|
213
|
-
const { error } = await scoped(getDb().from(T.lessons).delete().eq('id', id))
|
|
214
|
-
if (error) throw error
|
|
215
|
-
},
|
|
216
|
-
|
|
217
|
-
// Enrollments + progress ------------------------------------------------
|
|
218
|
-
async listEnrollments(customerId: string): Promise<Enrollment[]> {
|
|
219
|
-
const { data, error } = await getDb().from(T.enrollments).select('*').eq('customer_id', customerId)
|
|
220
|
-
if (error) throw error
|
|
221
|
-
return (data ?? []).map(rowToEnrollment)
|
|
222
|
-
},
|
|
223
|
-
async enroll(courseId: string, customerId: string): Promise<Enrollment> {
|
|
224
|
-
const { data, error } = await getDb().from(T.enrollments)
|
|
225
|
-
.upsert({ tenant_id: getTenantId(), course_id: courseId, customer_id: customerId, status: 'active' },
|
|
226
|
-
{ onConflict: 'course_id,customer_id' })
|
|
227
|
-
.select('*').single()
|
|
228
|
-
if (error) throw error
|
|
229
|
-
return rowToEnrollment(data)
|
|
230
|
-
},
|
|
231
|
-
async listProgress(enrollmentId: string): Promise<Progress[]> {
|
|
232
|
-
const { data, error } = await getDb().from(T.progress).select('*').eq('enrollment_id', enrollmentId)
|
|
233
|
-
if (error) throw error
|
|
234
|
-
return (data ?? []).map(rowToProgress)
|
|
235
|
-
},
|
|
236
|
-
async setLessonProgress(enrollmentId: string, lessonId: string, patch: { completed?: boolean; lastPositionSec?: number }): Promise<Progress> {
|
|
237
|
-
const row: any = { tenant_id: getTenantId(), enrollment_id: enrollmentId, lesson_id: lessonId }
|
|
238
|
-
if (patch.completed !== undefined) { row.completed = patch.completed; row.completed_at = patch.completed ? new Date().toISOString() : null }
|
|
239
|
-
if (patch.lastPositionSec !== undefined) row.last_position_sec = patch.lastPositionSec
|
|
240
|
-
const { data, error } = await getDb().from(T.progress)
|
|
241
|
-
.upsert(row, { onConflict: 'enrollment_id,lesson_id' }).select('*').single()
|
|
242
|
-
if (error) throw error
|
|
243
|
-
return rowToProgress(data)
|
|
244
|
-
},
|
|
245
|
-
|
|
246
|
-
// Offers ----------------------------------------------------------------
|
|
247
|
-
async listOffers(courseId: string): Promise<Offer[]> {
|
|
248
|
-
const { data, error } = await scoped(getDb().from(T.offers).select('*').eq('course_id', courseId)).order('sort_order', { ascending: true })
|
|
249
|
-
if (error) throw error
|
|
250
|
-
return (data ?? []).map(rowToOffer)
|
|
251
|
-
},
|
|
252
|
-
async createOffer(input: CreateOfferInput): Promise<Offer> {
|
|
253
|
-
const { data, error } = await getDb().from(T.offers).insert({
|
|
254
|
-
tenant_id: getTenantId(), course_id: input.courseId, name: input.name, price: input.price,
|
|
255
|
-
currency: input.currency ?? 'BRL', kind: input.kind ?? 'one_time',
|
|
256
|
-
recurring_interval: input.recurringInterval ?? (input.kind === 'subscription' ? 'month' : null),
|
|
257
|
-
is_default: input.isDefault ?? false, is_order_bump: input.isOrderBump ?? false, sort_order: input.sortOrder ?? 0,
|
|
258
|
-
}).select('*').single()
|
|
259
|
-
if (error) throw error
|
|
260
|
-
return rowToOffer(data)
|
|
261
|
-
},
|
|
262
|
-
async updateOffer(id: string, input: UpdateOfferInput): Promise<Offer> {
|
|
263
|
-
const patch: any = {}
|
|
264
|
-
if (input.name !== undefined) patch.name = input.name
|
|
265
|
-
if (input.price !== undefined) patch.price = input.price
|
|
266
|
-
if (input.currency !== undefined) patch.currency = input.currency
|
|
267
|
-
if (input.kind !== undefined) patch.kind = input.kind
|
|
268
|
-
if (input.recurringInterval !== undefined) patch.recurring_interval = input.recurringInterval
|
|
269
|
-
if (input.isDefault !== undefined) patch.is_default = input.isDefault
|
|
270
|
-
if (input.isOrderBump !== undefined) patch.is_order_bump = input.isOrderBump
|
|
271
|
-
if (input.sortOrder !== undefined) patch.sort_order = input.sortOrder
|
|
272
|
-
const { data, error } = await scoped(getDb().from(T.offers).update(patch).eq('id', id)).select('*').single()
|
|
273
|
-
if (error) throw error
|
|
274
|
-
return rowToOffer(data)
|
|
275
|
-
},
|
|
276
|
-
async deleteOffer(id: string): Promise<void> {
|
|
277
|
-
const { error } = await scoped(getDb().from(T.offers).delete().eq('id', id))
|
|
278
|
-
if (error) throw error
|
|
279
|
-
},
|
|
280
|
-
|
|
281
|
-
// Sales -----------------------------------------------------------------
|
|
282
|
-
async listOrders(opts?: ListOrdersOptions): Promise<Order[]> {
|
|
283
|
-
let q = scoped(getDb().from(T.orders).select('*'))
|
|
284
|
-
if (opts?.courseId) q = q.eq('course_id', opts.courseId)
|
|
285
|
-
if (opts?.financialStatus) q = q.eq('financial_status', opts.financialStatus)
|
|
286
|
-
if (opts?.search) q = q.or(`customer_name.ilike.%${opts.search}%,customer_email.ilike.%${opts.search}%`)
|
|
287
|
-
const { data, error } = await q.order('created_at', { ascending: false })
|
|
288
|
-
if (error) throw error
|
|
289
|
-
return (data ?? []).map(rowToOrder)
|
|
290
|
-
},
|
|
291
|
-
async listCoreSales(): Promise<Order[]> {
|
|
292
|
-
const { data, error } = await scoped(getDb().from('v_plg_course_sales').select('*'))
|
|
293
|
-
.order('created_at', { ascending: false })
|
|
294
|
-
if (error) throw error
|
|
295
|
-
return (data ?? []).map((r: any): Order => ({
|
|
296
|
-
id: r.id,
|
|
297
|
-
courseId: r.course_id ?? '',
|
|
298
|
-
offerId: r.offer_id ?? null,
|
|
299
|
-
customerId: r.party_id ?? null,
|
|
300
|
-
customerName: r.customer_name ?? null,
|
|
301
|
-
customerEmail: r.customer_email ?? null,
|
|
302
|
-
currency: r.currency ?? 'BRL',
|
|
303
|
-
total: Number(r.total ?? 0),
|
|
304
|
-
platformFee: Number(r.platform_fee ?? 0),
|
|
305
|
-
netValue: Number(r.net_value ?? r.total ?? 0),
|
|
306
|
-
paymentMethod: (r.payment_method ?? null) as PaymentMethod | null,
|
|
307
|
-
financialStatus: (r.financial_status ?? 'pending') as FinancialStatus,
|
|
308
|
-
stripePaymentIntentId: null,
|
|
309
|
-
createdAt: r.created_at,
|
|
310
|
-
installmentCount: Number(r.installment_count ?? 1),
|
|
311
|
-
}))
|
|
312
|
-
},
|
|
313
|
-
|
|
314
|
-
async getOrder(id: string): Promise<OrderDetail | null> {
|
|
315
|
-
const db = getDb()
|
|
316
|
-
const { data: v } = await scoped(db.from('v_plg_course_sales').select('*')).eq('id', id).maybeSingle()
|
|
317
|
-
if (!v) return null
|
|
318
|
-
const [{ data: course }, { data: bills }, { data: pays }] = await Promise.all([
|
|
319
|
-
db.from(T.courses).select('title').eq('id', v.course_id).maybeSingle(),
|
|
320
|
-
db.from('plg_financial_movements').select('*').eq('invoice_id', id).eq('movement_kind', 'bill').order('installment_number'),
|
|
321
|
-
db.from('plg_financial_movements').select('*').eq('invoice_id', id).eq('movement_kind', 'payment'),
|
|
322
|
-
])
|
|
323
|
-
let offerName: string | null = null
|
|
324
|
-
if (v.offer_id) {
|
|
325
|
-
const { data: off } = await db.from(T.offers).select('name').eq('id', v.offer_id).maybeSingle()
|
|
326
|
-
offerName = off?.name ?? null
|
|
327
|
-
}
|
|
328
|
-
const paymentsByInst = new Map<number, any>()
|
|
329
|
-
for (const p of pays ?? []) paymentsByInst.set(p.installment_number ?? 0, p)
|
|
330
|
-
const installments: OrderInstallment[] = (bills ?? []).map((b: any) => {
|
|
331
|
-
const p = paymentsByInst.get(b.installment_number ?? 0)
|
|
332
|
-
return {
|
|
333
|
-
installmentNumber: b.installment_number ?? 1,
|
|
334
|
-
amount: Number(b.amount ?? 0),
|
|
335
|
-
paidAmount: Number(b.paid_amount ?? 0),
|
|
336
|
-
status: b.status ?? 'pending',
|
|
337
|
-
dueDate: b.due_date ?? null,
|
|
338
|
-
paymentDate: p?.payment_date ?? b.payment_date ?? null,
|
|
339
|
-
cardBrand: p?.card_brand ?? null,
|
|
340
|
-
cardInstallments: p?.card_installments ?? null,
|
|
341
|
-
}
|
|
342
|
-
})
|
|
343
|
-
const paid = (bills ?? []).reduce((s: number, b: any) => s + Number(b.paid_amount ?? 0), 0)
|
|
344
|
-
const total = Number(v.total ?? 0)
|
|
345
|
-
return {
|
|
346
|
-
id: v.id,
|
|
347
|
-
courseId: v.course_id ?? '',
|
|
348
|
-
offerId: v.offer_id ?? null,
|
|
349
|
-
customerId: v.party_id ?? null,
|
|
350
|
-
customerName: v.customer_name ?? null,
|
|
351
|
-
customerEmail: v.customer_email ?? null,
|
|
352
|
-
currency: v.currency ?? 'BRL',
|
|
353
|
-
total,
|
|
354
|
-
platformFee: Number(v.platform_fee ?? 0),
|
|
355
|
-
netValue: Number(v.net_value ?? total),
|
|
356
|
-
paymentMethod: (v.payment_method ?? null) as PaymentMethod | null,
|
|
357
|
-
financialStatus: (v.financial_status ?? 'pending') as FinancialStatus,
|
|
358
|
-
stripePaymentIntentId: null,
|
|
359
|
-
createdAt: v.created_at,
|
|
360
|
-
installmentCount: Number(v.installment_count ?? installments.length ?? 1),
|
|
361
|
-
courseTitle: course?.title ?? null,
|
|
362
|
-
offerName,
|
|
363
|
-
paidAmount: paid,
|
|
364
|
-
balance: Math.max(0, total - paid),
|
|
365
|
-
installments,
|
|
366
|
-
}
|
|
367
|
-
},
|
|
368
|
-
|
|
369
|
-
// Subscriptions ---------------------------------------------------------
|
|
370
|
-
async listSubscriptions(opts?: ListSubscriptionsOptions): Promise<Subscription[]> {
|
|
371
|
-
let q = scoped(getDb().from(T.subscriptions).select('*'))
|
|
372
|
-
if (opts?.courseId) q = q.eq('course_id', opts.courseId)
|
|
373
|
-
if (opts?.status) q = q.eq('status', opts.status)
|
|
374
|
-
const { data, error } = await q.order('started_at', { ascending: false })
|
|
375
|
-
if (error) throw error
|
|
376
|
-
return (data ?? []).map(rowToSubscription)
|
|
377
|
-
},
|
|
378
|
-
|
|
379
|
-
// Financial -------------------------------------------------------------
|
|
380
|
-
async getFinancialSummary(): Promise<FinancialSummary> {
|
|
381
|
-
const [orders, subs, payouts] = await Promise.all([
|
|
382
|
-
scoped(getDb().from(T.orders).select('total,platform_fee,net_value,financial_status')),
|
|
383
|
-
scoped(getDb().from(T.subscriptions).select('net_value,interval,status')),
|
|
384
|
-
scoped(getDb().from(T.payouts).select('amount,status')),
|
|
385
|
-
])
|
|
386
|
-
const orderRows: any[] = orders.data ?? []
|
|
387
|
-
const paid = orderRows.filter((o) => o.financial_status === 'paid')
|
|
388
|
-
const refunded = orderRows.filter((o) => o.financial_status === 'refunded')
|
|
389
|
-
const activeSubs = (subs.data ?? []).filter((s: any) => s.status === 'active')
|
|
390
|
-
const netTotal = round2(paid.reduce((s, o) => s + Number(o.net_value ?? 0), 0))
|
|
391
|
-
const paidOut = round2((payouts.data ?? []).filter((p: any) => p.status === 'paid').reduce((s: number, p: any) => s + Number(p.amount ?? 0), 0))
|
|
392
|
-
const mrr = round2(activeSubs.reduce((s: number, sub: any) => s + (sub.interval === 'year' ? Number(sub.net_value) / 12 : Number(sub.net_value)), 0))
|
|
393
|
-
const totalCount = paid.length + refunded.length
|
|
394
|
-
return {
|
|
395
|
-
currency: 'BRL',
|
|
396
|
-
availableBalance: round2(Math.max(netTotal - paidOut, 0)),
|
|
397
|
-
pendingBalance: round2(orderRows.filter((o) => o.financial_status === 'pending').reduce((s, o) => s + Number(o.net_value ?? 0), 0)),
|
|
398
|
-
totalRevenue: round2(paid.reduce((s, o) => s + Number(o.total ?? 0), 0)),
|
|
399
|
-
platformFeeTotal: round2(paid.reduce((s, o) => s + Number(o.platform_fee ?? 0), 0)),
|
|
400
|
-
salesCount: paid.length,
|
|
401
|
-
activeSubscriptions: activeSubs.length,
|
|
402
|
-
mrr,
|
|
403
|
-
refundRate: totalCount > 0 ? refunded.length / totalCount : 0,
|
|
404
|
-
conversionRate: 0,
|
|
405
|
-
}
|
|
406
|
-
},
|
|
407
|
-
async listPayouts(): Promise<Payout[]> {
|
|
408
|
-
const { data, error } = await scoped(getDb().from(T.payouts).select('*')).order('created_at', { ascending: false })
|
|
409
|
-
if (error) throw error
|
|
410
|
-
return (data ?? []).map(rowToPayout)
|
|
411
|
-
},
|
|
412
|
-
async getCreatorAccount(): Promise<CreatorAccount> {
|
|
413
|
-
const tenantId = getTenantId()
|
|
414
|
-
const { data } = await scoped(getDb().from(T.creatorAccounts).select('*')).maybeSingle()
|
|
415
|
-
return {
|
|
416
|
-
tenantId: tenantId ?? '',
|
|
417
|
-
stripeAccountId: data?.stripe_account_id ?? null,
|
|
418
|
-
chargesEnabled: data?.charges_enabled ?? false,
|
|
419
|
-
payoutsEnabled: data?.payouts_enabled ?? false,
|
|
420
|
-
defaultCurrency: data?.default_currency ?? 'BRL',
|
|
421
|
-
platformFeeBps: data?.platform_fee_bps ?? 500,
|
|
422
|
-
}
|
|
423
|
-
},
|
|
424
|
-
}
|
|
425
|
-
}
|
package/src/tables.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
// Physical table names for @fayz-ai/courses. Renamed to the plg_courses_*
|
|
2
|
-
// industry-pool prefix (was course_*) when the core DB moved into the public
|
|
3
|
-
// schema. RPC function names (course_place_order, course_confirm_payment) are
|
|
4
|
-
// unchanged.
|
|
5
|
-
export const T = {
|
|
6
|
-
courses: 'plg_courses_courses',
|
|
7
|
-
modules: 'plg_courses_modules',
|
|
8
|
-
lessons: 'plg_courses_lessons',
|
|
9
|
-
offers: 'plg_courses_offers',
|
|
10
|
-
customers: 'plg_courses_customers',
|
|
11
|
-
enrollments: 'plg_courses_enrollments',
|
|
12
|
-
progress: 'plg_courses_progress',
|
|
13
|
-
orders: 'plg_courses_orders',
|
|
14
|
-
subscriptions: 'plg_courses_subscriptions',
|
|
15
|
-
creatorAccounts: 'plg_courses_creator_accounts',
|
|
16
|
-
payouts: 'plg_courses_payouts',
|
|
17
|
-
paymentEvents: 'plg_courses_payment_events',
|
|
18
|
-
} as const
|
package/src/tenant.ts
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
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
|
-
}
|