@fayz-ai/courses 0.8.1 → 0.9.0-next.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 DELETED
@@ -1,1182 +0,0 @@
1
- 'use strict';
2
-
3
- var core = require('@fayz-ai/core');
4
- var react = require('react');
5
-
6
- // src/provider.ts
7
- var _provider = null;
8
- function setCoursesProvider(provider) {
9
- _provider = provider;
10
- }
11
- function getCoursesProvider() {
12
- if (!_provider) {
13
- throw new Error("Courses provider not set. Call setCoursesProvider() (e.g. createMockCoursesProvider).");
14
- }
15
- return _provider;
16
- }
17
- function getCoursesProviderOptional() {
18
- return _provider;
19
- }
20
-
21
- // src/seed.ts
22
- function thumb(label, hue) {
23
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${hue},65%,55%)"/><stop offset="1" stop-color="hsl(${(hue + 40) % 360},65%,40%)"/></linearGradient></defs><rect width="640" height="360" fill="url(#g)"/><text x="32" y="320" fill="white" font-family="system-ui" font-size="40" font-weight="700">${label}</text></svg>`;
24
- return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
25
- }
26
- var YT = (id) => `https://www.youtube.com/embed/${id}`;
27
- var t0 = "2026-01-01T00:00:00.000Z";
28
- function buildCourseCatalog(input) {
29
- const courses = [];
30
- const modules = [];
31
- const lessons = [];
32
- const offers = [];
33
- input.forEach((c, ci) => {
34
- const courseId = `course-${String(ci + 1).padStart(2, "0")}`;
35
- const price = c.price ?? 197;
36
- offers.push({
37
- id: `${courseId}-offer-01`,
38
- courseId,
39
- name: c.title,
40
- price,
41
- currency: "BRL",
42
- kind: "one_time",
43
- recurringInterval: null,
44
- isDefault: true,
45
- isOrderBump: false,
46
- sortOrder: 0
47
- });
48
- if (ci === 0) {
49
- offers.push({
50
- id: `${courseId}-offer-02`,
51
- courseId,
52
- name: `${c.title} + Club (mensal)`,
53
- price: Math.round(price * 0.24 * 100) / 100,
54
- currency: "BRL",
55
- kind: "subscription",
56
- recurringInterval: "month",
57
- isDefault: false,
58
- isOrderBump: false,
59
- sortOrder: 1
60
- });
61
- offers.push({
62
- id: `${courseId}-offer-03`,
63
- courseId,
64
- name: "Templates & B\xF4nus (order-bump)",
65
- price: 47,
66
- currency: "BRL",
67
- kind: "one_time",
68
- recurringInterval: null,
69
- isDefault: false,
70
- isOrderBump: true,
71
- sortOrder: 2
72
- });
73
- }
74
- courses.push({
75
- id: courseId,
76
- slug: c.slug,
77
- title: c.title,
78
- subtitle: c.subtitle ?? null,
79
- description: c.description ?? null,
80
- thumbnailUrl: thumb(c.title, c.hue ?? ci * 70 % 360),
81
- price: c.price ?? 197,
82
- currency: "BRL",
83
- status: "published",
84
- deliveryType: "online",
85
- sortOrder: ci,
86
- createdAt: t0,
87
- updatedAt: t0
88
- });
89
- c.modules.forEach((m, mi) => {
90
- const moduleId = `${courseId}-m${String(mi + 1).padStart(2, "0")}`;
91
- modules.push({ id: moduleId, courseId, title: m.title, sortOrder: mi });
92
- m.lessons.forEach((l, li) => {
93
- lessons.push({
94
- id: `${moduleId}-l${String(li + 1).padStart(2, "0")}`,
95
- courseId,
96
- moduleId,
97
- title: l.title,
98
- description: l.description ?? null,
99
- videoUrl: YT(l.youtubeId),
100
- durationSec: l.durationSec ?? 600,
101
- sortOrder: li
102
- });
103
- });
104
- });
105
- });
106
- return { courses, modules, lessons, offers };
107
- }
108
- var DEMO_PLATFORM_FEE_BPS = 500;
109
- function daysFromBase(days) {
110
- return new Date(Date.parse(t0) + days * 864e5).toISOString();
111
- }
112
- var DEMO_BUYERS = [
113
- { name: "William Ribeiro", email: "william@example.com" },
114
- { name: "Alan Brancalh\xE3o", email: "alan@example.com" },
115
- { name: "Luciano Rufatto", email: "luciano@example.com" },
116
- { name: "Gabriel Boni", email: "gabriel@example.com" },
117
- { name: "Leonardo Lorenzoni", email: "leonardo@example.com" }
118
- ];
119
- var DEMO_METHODS = ["pix", "card", "boleto"];
120
- function feeFor(total) {
121
- return Math.round(total * DEMO_PLATFORM_FEE_BPS / 1e4 * 100) / 100;
122
- }
123
- function buildDemoLedger(catalog) {
124
- const orders = [];
125
- const subscriptions = [];
126
- const oneTime = catalog.offers.filter((o) => o.kind === "one_time" && !o.isOrderBump);
127
- oneTime.forEach((offer, oi) => {
128
- for (let i = 0; i < 3; i++) {
129
- const buyer = DEMO_BUYERS[(oi * 3 + i) % DEMO_BUYERS.length];
130
- const total = offer.price;
131
- const platformFee = feeFor(total);
132
- orders.push({
133
- id: `order-${offer.courseId}-${String(i + 1).padStart(2, "0")}`,
134
- courseId: offer.courseId,
135
- offerId: offer.id,
136
- customerId: `cust-${buyer.email}`,
137
- customerName: buyer.name,
138
- customerEmail: buyer.email,
139
- currency: offer.currency,
140
- total,
141
- platformFee,
142
- netValue: Math.round((total - platformFee) * 100) / 100,
143
- paymentMethod: DEMO_METHODS[(oi + i) % DEMO_METHODS.length],
144
- financialStatus: "paid",
145
- stripePaymentIntentId: null,
146
- createdAt: daysFromBase(160 + oi * 7 + i * 2)
147
- });
148
- }
149
- });
150
- const sub = catalog.offers.find((o) => o.kind === "subscription");
151
- if (sub) {
152
- for (let i = 0; i < 2; i++) {
153
- const buyer = DEMO_BUYERS[(3 + i) % DEMO_BUYERS.length];
154
- subscriptions.push({
155
- id: `sub-${sub.courseId}-${String(i + 1).padStart(2, "0")}`,
156
- courseId: sub.courseId,
157
- offerId: sub.id,
158
- customerId: `cust-${buyer.email}`,
159
- customerName: buyer.name,
160
- customerEmail: buyer.email,
161
- currency: sub.currency,
162
- netValue: Math.round((sub.price - feeFor(sub.price)) * 100) / 100,
163
- interval: sub.recurringInterval ?? "month",
164
- status: "active",
165
- stripeSubscriptionId: null,
166
- startedAt: daysFromBase(150 + i * 2),
167
- canceledAt: null
168
- });
169
- }
170
- }
171
- const payouts = [200, 216.33, 196.33, 801.33].map((amount, i) => ({
172
- id: `payout-${String(i + 1).padStart(2, "0")}`,
173
- amount,
174
- currency: "BRL",
175
- status: "paid",
176
- createdAt: daysFromBase(120 + i * 20)
177
- }));
178
- return { orders, subscriptions, payouts };
179
- }
180
- var DEFAULT_COURSE_CATALOG = buildCourseCatalog([
181
- {
182
- slug: "react-do-zero",
183
- title: "React do Zero ao Profissional",
184
- subtitle: "Construa interfaces modernas com React",
185
- description: "Do b\xE1sico de componentes a hooks avan\xE7ados e padr\xF5es de produ\xE7\xE3o.",
186
- price: 297,
187
- hue: 210,
188
- modules: [
189
- {
190
- title: "Fundamentos",
191
- lessons: [
192
- { title: "Boas-vindas e setup", youtubeId: "aqz-KE-bpKQ", durationSec: 420 },
193
- { title: "JSX e componentes", youtubeId: "LXb3EKWsInQ", durationSec: 720 }
194
- ]
195
- },
196
- {
197
- title: "Hooks",
198
- lessons: [
199
- { title: "useState e useEffect", youtubeId: "jNQXAC9IVRw", durationSec: 900 },
200
- { title: "Hooks customizados", youtubeId: "aqz-KE-bpKQ", durationSec: 840 }
201
- ]
202
- }
203
- ]
204
- },
205
- {
206
- slug: "design-de-produto",
207
- title: "Design de Produto na Pr\xE1tica",
208
- subtitle: "Do problema ao prot\xF3tipo validado",
209
- description: "Pesquisa, fluxos, wireframes e testes de usabilidade.",
210
- price: 247,
211
- hue: 320,
212
- modules: [
213
- {
214
- title: "Descoberta",
215
- lessons: [
216
- { title: "Entrevistas com usu\xE1rios", youtubeId: "LXb3EKWsInQ", durationSec: 660 },
217
- { title: "Mapeando jornadas", youtubeId: "jNQXAC9IVRw", durationSec: 540 }
218
- ]
219
- }
220
- ]
221
- },
222
- {
223
- slug: "marketing-digital",
224
- title: "Marketing Digital para Criadores",
225
- subtitle: "Audi\xEAncia, conte\xFAdo e convers\xE3o",
226
- description: "Estrat\xE9gias de tr\xE1fego, funil e lan\xE7amentos.",
227
- price: 197,
228
- hue: 30,
229
- modules: [
230
- {
231
- title: "Fundamentos",
232
- lessons: [
233
- { title: "Posicionamento", youtubeId: "aqz-KE-bpKQ", durationSec: 480 },
234
- { title: "Criando conte\xFAdo que converte", youtubeId: "LXb3EKWsInQ", durationSec: 600 }
235
- ]
236
- }
237
- ]
238
- }
239
- ]);
240
- var DEFAULT_DEMO_LEDGER = buildDemoLedger(DEFAULT_COURSE_CATALOG);
241
-
242
- // src/mock-provider.ts
243
- function uid() {
244
- return Math.random().toString(36).slice(2);
245
- }
246
- function now() {
247
- return (/* @__PURE__ */ new Date()).toISOString();
248
- }
249
- function slugify(s) {
250
- return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
251
- }
252
- var K = {
253
- courses: "fayz.courses.mock.courses.v1",
254
- modules: "fayz.courses.mock.modules.v1",
255
- lessons: "fayz.courses.mock.lessons.v1",
256
- enrollments: "fayz.courses.mock.enrollments.v1",
257
- progress: "fayz.courses.mock.progress.v1",
258
- offers: "fayz.courses.mock.offers.v1",
259
- orders: "fayz.courses.mock.orders.v1",
260
- subscriptions: "fayz.courses.mock.subscriptions.v1",
261
- payouts: "fayz.courses.mock.payouts.v1"
262
- };
263
- function load(key) {
264
- try {
265
- if (typeof localStorage === "undefined") return null;
266
- const raw = localStorage.getItem(key);
267
- return raw ? JSON.parse(raw) : null;
268
- } catch {
269
- return null;
270
- }
271
- }
272
- function save(key, value) {
273
- try {
274
- if (typeof localStorage !== "undefined") localStorage.setItem(key, JSON.stringify(value));
275
- } catch {
276
- }
277
- }
278
- var MockCoursesProvider = class {
279
- constructor(seed) {
280
- const catalog = seed?.catalog ?? DEFAULT_COURSE_CATALOG;
281
- const ledger = seed?.ledger ?? DEFAULT_DEMO_LEDGER;
282
- if (load(K.courses) == null) {
283
- save(K.courses, catalog.courses);
284
- save(K.modules, catalog.modules);
285
- save(K.lessons, catalog.lessons);
286
- save(K.offers, catalog.offers);
287
- save(K.orders, ledger.orders);
288
- save(K.subscriptions, ledger.subscriptions);
289
- save(K.payouts, ledger.payouts);
290
- }
291
- if (seed?.enrollAll?.length) {
292
- const courses = load(K.courses) ?? [];
293
- const enrollments = load(K.enrollments) ?? [];
294
- let changed = false;
295
- for (const customerId of seed.enrollAll) {
296
- for (const c of courses) {
297
- if (!enrollments.some((e) => e.customerId === customerId && e.courseId === c.id)) {
298
- enrollments.push({ id: uid(), courseId: c.id, customerId, status: "active", enrolledAt: now() });
299
- changed = true;
300
- }
301
- }
302
- }
303
- if (changed) save(K.enrollments, enrollments);
304
- }
305
- }
306
- courses() {
307
- return load(K.courses) ?? [];
308
- }
309
- modules() {
310
- return load(K.modules) ?? [];
311
- }
312
- lessons() {
313
- return load(K.lessons) ?? [];
314
- }
315
- enrollments() {
316
- return load(K.enrollments) ?? [];
317
- }
318
- progress() {
319
- return load(K.progress) ?? [];
320
- }
321
- offers() {
322
- return load(K.offers) ?? [];
323
- }
324
- orders() {
325
- return load(K.orders) ?? [];
326
- }
327
- subscriptions() {
328
- return load(K.subscriptions) ?? [];
329
- }
330
- payouts() {
331
- return load(K.payouts) ?? [];
332
- }
333
- // Courses -----------------------------------------------------------------
334
- async listCourses(opts) {
335
- let list = this.courses();
336
- if (opts?.status) list = list.filter((c) => c.status === opts.status);
337
- if (opts?.slug) list = list.filter((c) => c.slug === opts.slug);
338
- if (opts?.search) {
339
- const q = opts.search.toLowerCase();
340
- list = list.filter((c) => c.title.toLowerCase().includes(q) || (c.description ?? "").toLowerCase().includes(q));
341
- }
342
- return list.slice().sort((a, b) => a.sortOrder - b.sortOrder);
343
- }
344
- async getCourse(idOrSlug) {
345
- return this.courses().find((c) => c.id === idOrSlug || c.slug === idOrSlug) ?? null;
346
- }
347
- async createCourse(input) {
348
- const list = this.courses();
349
- const course = {
350
- id: uid(),
351
- slug: input.slug ?? slugify(input.title),
352
- title: input.title,
353
- subtitle: input.subtitle ?? null,
354
- description: input.description ?? null,
355
- thumbnailUrl: input.thumbnailUrl ?? null,
356
- price: input.price ?? 0,
357
- currency: input.currency ?? "BRL",
358
- status: input.status ?? "draft",
359
- deliveryType: input.deliveryType ?? "online",
360
- sortOrder: input.sortOrder ?? list.length,
361
- createdAt: now(),
362
- updatedAt: now()
363
- };
364
- save(K.courses, [...list, course]);
365
- return course;
366
- }
367
- async updateCourse(id, input) {
368
- const list = this.courses();
369
- const idx = list.findIndex((c) => c.id === id);
370
- if (idx < 0) throw new Error("Course not found");
371
- const updated = { ...list[idx], ...input, updatedAt: now() };
372
- list[idx] = updated;
373
- save(K.courses, list);
374
- return updated;
375
- }
376
- async deleteCourse(id) {
377
- save(K.courses, this.courses().filter((c) => c.id !== id));
378
- }
379
- // Modules -----------------------------------------------------------------
380
- async listModules(courseId) {
381
- return this.modules().filter((m) => m.courseId === courseId).sort((a, b) => a.sortOrder - b.sortOrder);
382
- }
383
- async createModule(input) {
384
- const list = this.modules();
385
- const mod = { id: uid(), courseId: input.courseId, title: input.title, sortOrder: input.sortOrder ?? list.filter((m) => m.courseId === input.courseId).length };
386
- save(K.modules, [...list, mod]);
387
- return mod;
388
- }
389
- async updateModule(id, input) {
390
- const list = this.modules();
391
- const idx = list.findIndex((m) => m.id === id);
392
- if (idx < 0) throw new Error("Module not found");
393
- list[idx] = { ...list[idx], ...input };
394
- save(K.modules, list);
395
- return list[idx];
396
- }
397
- async deleteModule(id) {
398
- save(K.modules, this.modules().filter((m) => m.id !== id));
399
- }
400
- // Lessons -----------------------------------------------------------------
401
- async listLessons(courseId) {
402
- return this.lessons().filter((l) => l.courseId === courseId).sort((a, b) => a.sortOrder - b.sortOrder);
403
- }
404
- async getLesson(id) {
405
- return this.lessons().find((l) => l.id === id) ?? null;
406
- }
407
- async createLesson(input) {
408
- const list = this.lessons();
409
- const lesson = {
410
- id: uid(),
411
- courseId: input.courseId,
412
- moduleId: input.moduleId,
413
- title: input.title,
414
- description: input.description ?? null,
415
- videoUrl: input.videoUrl,
416
- durationSec: input.durationSec ?? 600,
417
- sortOrder: input.sortOrder ?? list.filter((l) => l.moduleId === input.moduleId).length
418
- };
419
- save(K.lessons, [...list, lesson]);
420
- return lesson;
421
- }
422
- async updateLesson(id, input) {
423
- const list = this.lessons();
424
- const idx = list.findIndex((l) => l.id === id);
425
- if (idx < 0) throw new Error("Lesson not found");
426
- list[idx] = { ...list[idx], ...input };
427
- save(K.lessons, list);
428
- return list[idx];
429
- }
430
- async deleteLesson(id) {
431
- save(K.lessons, this.lessons().filter((l) => l.id !== id));
432
- }
433
- // Enrollments + progress --------------------------------------------------
434
- async listEnrollments(customerId) {
435
- return this.enrollments().filter((e) => e.customerId === customerId);
436
- }
437
- async enroll(courseId, customerId) {
438
- const list = this.enrollments();
439
- const existing = list.find((e) => e.courseId === courseId && e.customerId === customerId);
440
- if (existing) return existing;
441
- const enrollment = { id: uid(), courseId, customerId, status: "active", enrolledAt: now() };
442
- save(K.enrollments, [...list, enrollment]);
443
- return enrollment;
444
- }
445
- async listProgress(enrollmentId) {
446
- return this.progress().filter((p) => p.enrollmentId === enrollmentId);
447
- }
448
- async setLessonProgress(enrollmentId, lessonId, patch) {
449
- const list = this.progress();
450
- const idx = list.findIndex((p) => p.enrollmentId === enrollmentId && p.lessonId === lessonId);
451
- if (idx >= 0) {
452
- const updated = {
453
- ...list[idx],
454
- completed: patch.completed ?? list[idx].completed,
455
- lastPositionSec: patch.lastPositionSec ?? list[idx].lastPositionSec,
456
- completedAt: patch.completed ?? list[idx].completed ? list[idx].completedAt ?? now() : null
457
- };
458
- list[idx] = updated;
459
- save(K.progress, list);
460
- return updated;
461
- }
462
- const created = {
463
- id: uid(),
464
- enrollmentId,
465
- lessonId,
466
- completed: patch.completed ?? false,
467
- lastPositionSec: patch.lastPositionSec ?? 0,
468
- completedAt: patch.completed ? now() : null
469
- };
470
- save(K.progress, [...list, created]);
471
- return created;
472
- }
473
- // Offers ------------------------------------------------------------------
474
- async listOffers(courseId) {
475
- return this.offers().filter((o) => o.courseId === courseId).sort((a, b) => a.sortOrder - b.sortOrder);
476
- }
477
- async createOffer(input) {
478
- const list = this.offers();
479
- const offer = {
480
- id: uid(),
481
- courseId: input.courseId,
482
- name: input.name,
483
- price: input.price,
484
- currency: input.currency ?? "BRL",
485
- kind: input.kind ?? "one_time",
486
- recurringInterval: input.recurringInterval ?? (input.kind === "subscription" ? "month" : null),
487
- isDefault: input.isDefault ?? false,
488
- isOrderBump: input.isOrderBump ?? false,
489
- sortOrder: input.sortOrder ?? list.filter((o) => o.courseId === input.courseId).length
490
- };
491
- save(K.offers, [...list, offer]);
492
- return offer;
493
- }
494
- async updateOffer(id, input) {
495
- const list = this.offers();
496
- const idx = list.findIndex((o) => o.id === id);
497
- if (idx < 0) throw new Error("Offer not found");
498
- list[idx] = { ...list[idx], ...input };
499
- save(K.offers, list);
500
- return list[idx];
501
- }
502
- async deleteOffer(id) {
503
- save(K.offers, this.offers().filter((o) => o.id !== id));
504
- }
505
- // Sales ledger ------------------------------------------------------------
506
- async listOrders(opts) {
507
- let list = this.orders();
508
- if (opts?.courseId) list = list.filter((o) => o.courseId === opts.courseId);
509
- if (opts?.financialStatus) list = list.filter((o) => o.financialStatus === opts.financialStatus);
510
- if (opts?.search) {
511
- const q = opts.search.toLowerCase();
512
- list = list.filter(
513
- (o) => (o.customerName ?? "").toLowerCase().includes(q) || (o.customerEmail ?? "").toLowerCase().includes(q)
514
- );
515
- }
516
- return list.slice().sort((a, b) => a.createdAt < b.createdAt ? 1 : -1);
517
- }
518
- // Core-commerce course sales don't exist in the mock layer (no orders/financial).
519
- async listCoreSales() {
520
- return [];
521
- }
522
- async getOrder(id) {
523
- const o = this.orders().find((x) => x.id === id);
524
- if (!o) return null;
525
- const paid = o.financialStatus === "paid" ? o.total : 0;
526
- return { ...o, courseTitle: null, offerName: null, paidAmount: paid, balance: o.total - paid, installments: [] };
527
- }
528
- // Subscriptions -----------------------------------------------------------
529
- async listSubscriptions(opts) {
530
- let list = this.subscriptions();
531
- if (opts?.courseId) list = list.filter((s) => s.courseId === opts.courseId);
532
- if (opts?.status) list = list.filter((s) => s.status === opts.status);
533
- return list.slice().sort((a, b) => a.startedAt < b.startedAt ? 1 : -1);
534
- }
535
- // Financial / payouts / connect -------------------------------------------
536
- async getFinancialSummary() {
537
- const paid = this.orders().filter((o) => o.financialStatus === "paid");
538
- const refunded = this.orders().filter((o) => o.financialStatus === "refunded");
539
- const activeSubs = this.subscriptions().filter((s) => s.status === "active");
540
- const totalRevenue = round2(paid.reduce((s, o) => s + o.total, 0));
541
- const platformFeeTotal = round2(paid.reduce((s, o) => s + o.platformFee, 0));
542
- const netTotal = round2(paid.reduce((s, o) => s + o.netValue, 0));
543
- const paidOut = round2(this.payouts().filter((p) => p.status === "paid").reduce((s, p) => s + p.amount, 0));
544
- const mrr = round2(activeSubs.reduce((s, sub) => s + (sub.interval === "year" ? sub.netValue / 12 : sub.netValue), 0));
545
- const totalCount = paid.length + refunded.length;
546
- return {
547
- currency: "BRL",
548
- availableBalance: round2(Math.max(netTotal - paidOut, 0)),
549
- pendingBalance: round2(this.orders().filter((o) => o.financialStatus === "pending").reduce((s, o) => s + o.netValue, 0)),
550
- totalRevenue,
551
- platformFeeTotal,
552
- salesCount: paid.length,
553
- activeSubscriptions: activeSubs.length,
554
- mrr,
555
- refundRate: totalCount > 0 ? refunded.length / totalCount : 0,
556
- conversionRate: 0
557
- };
558
- }
559
- async listPayouts() {
560
- return this.payouts().slice().sort((a, b) => a.createdAt < b.createdAt ? 1 : -1);
561
- }
562
- async getCreatorAccount() {
563
- return {
564
- tenantId: "mock-tenant",
565
- stripeAccountId: null,
566
- chargesEnabled: false,
567
- payoutsEnabled: false,
568
- defaultCurrency: "BRL",
569
- platformFeeBps: DEMO_PLATFORM_FEE_BPS
570
- };
571
- }
572
- };
573
- function round2(n) {
574
- return Math.round(n * 100) / 100;
575
- }
576
- function createMockCoursesProvider(seed) {
577
- return new MockCoursesProvider(seed);
578
- }
579
-
580
- // src/tenant.ts
581
- var _resolver = null;
582
- function setCoursesTenantResolver(resolver) {
583
- _resolver = resolver;
584
- }
585
- function getCoursesTenantId() {
586
- if (!_resolver) return void 0;
587
- try {
588
- return _resolver();
589
- } catch {
590
- return void 0;
591
- }
592
- }
593
-
594
- // src/tables.ts
595
- var T = {
596
- courses: "plg_courses_courses",
597
- modules: "plg_courses_modules",
598
- lessons: "plg_courses_lessons",
599
- offers: "plg_courses_offers",
600
- enrollments: "plg_courses_enrollments",
601
- progress: "plg_courses_progress",
602
- orders: "plg_courses_orders",
603
- subscriptions: "plg_courses_subscriptions",
604
- creatorAccounts: "plg_courses_creator_accounts",
605
- payouts: "plg_courses_payouts"};
606
-
607
- // src/supabase-provider.ts
608
- function getDb() {
609
- const supabase = core.getSupabaseClientOptional();
610
- if (!supabase) throw new Error("@fayz-ai/courses: Supabase client not initialized. Call setGlobalSupabaseClient() first.");
611
- return supabase;
612
- }
613
- var getTenantId = getCoursesTenantId;
614
- function slugify2(s) {
615
- return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
616
- }
617
- function round22(n) {
618
- return Math.round(n * 100) / 100;
619
- }
620
- function rowToCourse(r) {
621
- return {
622
- id: r.id,
623
- slug: r.slug,
624
- title: r.title,
625
- subtitle: r.subtitle ?? null,
626
- description: r.description ?? null,
627
- thumbnailUrl: r.thumbnail_url ?? null,
628
- price: r.price ?? 0,
629
- currency: r.currency ?? "BRL",
630
- status: r.status ?? "draft",
631
- deliveryType: r.delivery_type ?? "online",
632
- sortOrder: r.sort_order ?? 0,
633
- createdAt: r.created_at,
634
- updatedAt: r.updated_at
635
- };
636
- }
637
- function rowToModule(r) {
638
- return { id: r.id, courseId: r.course_id, title: r.title, sortOrder: r.sort_order ?? 0 };
639
- }
640
- function rowToLesson(r) {
641
- return {
642
- id: r.id,
643
- courseId: r.course_id,
644
- moduleId: r.module_id,
645
- title: r.title,
646
- description: r.description ?? null,
647
- videoUrl: r.video_url ?? "",
648
- durationSec: r.duration_sec ?? 600,
649
- sortOrder: r.sort_order ?? 0
650
- };
651
- }
652
- function rowToOffer(r) {
653
- return {
654
- id: r.id,
655
- courseId: r.course_id,
656
- name: r.name,
657
- price: r.price ?? 0,
658
- currency: r.currency ?? "BRL",
659
- kind: r.kind ?? "one_time",
660
- recurringInterval: r.recurring_interval ?? null,
661
- isDefault: r.is_default ?? false,
662
- isOrderBump: r.is_order_bump ?? false,
663
- sortOrder: r.sort_order ?? 0
664
- };
665
- }
666
- function rowToEnrollment(r) {
667
- return { id: r.id, courseId: r.course_id, customerId: r.customer_id, status: r.status ?? "active", enrolledAt: r.enrolled_at };
668
- }
669
- function rowToProgress(r) {
670
- return {
671
- id: r.id,
672
- enrollmentId: r.enrollment_id,
673
- lessonId: r.lesson_id,
674
- completed: r.completed ?? false,
675
- lastPositionSec: r.last_position_sec ?? 0,
676
- completedAt: r.completed_at ?? null
677
- };
678
- }
679
- function rowToOrder(r) {
680
- return {
681
- id: r.id,
682
- courseId: r.course_id,
683
- offerId: r.offer_id ?? null,
684
- customerId: r.customer_id ?? null,
685
- customerName: r.customer_name ?? null,
686
- customerEmail: r.customer_email ?? null,
687
- currency: r.currency ?? "BRL",
688
- total: r.total ?? 0,
689
- platformFee: r.platform_fee ?? 0,
690
- netValue: r.net_value ?? 0,
691
- paymentMethod: r.payment_method ?? null,
692
- financialStatus: r.financial_status ?? "pending",
693
- stripePaymentIntentId: r.stripe_payment_intent_id ?? null,
694
- createdAt: r.created_at
695
- };
696
- }
697
- function rowToSubscription(r) {
698
- return {
699
- id: r.id,
700
- courseId: r.course_id,
701
- offerId: r.offer_id ?? null,
702
- customerId: r.customer_id ?? null,
703
- customerName: r.customer_name ?? null,
704
- customerEmail: r.customer_email ?? null,
705
- currency: r.currency ?? "BRL",
706
- netValue: r.net_value ?? 0,
707
- interval: r.interval ?? "month",
708
- status: r.status ?? "active",
709
- stripeSubscriptionId: r.stripe_subscription_id ?? null,
710
- startedAt: r.started_at,
711
- canceledAt: r.canceled_at ?? null
712
- };
713
- }
714
- function rowToPayout(r) {
715
- return { id: r.id, amount: r.amount ?? 0, currency: r.currency ?? "BRL", status: r.status ?? "pending", createdAt: r.created_at };
716
- }
717
- function createSupabaseCoursesProvider() {
718
- const scoped = (q) => {
719
- const tenantId = getTenantId();
720
- return tenantId ? q.eq("tenant_id", tenantId) : q;
721
- };
722
- return {
723
- // Courses ---------------------------------------------------------------
724
- async listCourses(opts) {
725
- let q = scoped(getDb().from(T.courses).select("*"));
726
- if (opts?.status) q = q.eq("status", opts.status);
727
- if (opts?.slug) q = q.eq("slug", opts.slug);
728
- if (opts?.search) q = q.ilike("title", `%${opts.search}%`);
729
- const { data, error } = await q.order("sort_order", { ascending: true });
730
- if (error) throw error;
731
- return (data ?? []).map(rowToCourse);
732
- },
733
- async getCourse(idOrSlug) {
734
- const col = /^[0-9a-f-]{36}$/i.test(idOrSlug) ? "id" : "slug";
735
- const { data, error } = await scoped(getDb().from(T.courses).select("*").eq(col, idOrSlug)).maybeSingle();
736
- if (error) throw error;
737
- return data ? rowToCourse(data) : null;
738
- },
739
- async createCourse(input) {
740
- const { data, error } = await getDb().from(T.courses).insert({
741
- tenant_id: getTenantId(),
742
- slug: input.slug ?? slugify2(input.title),
743
- title: input.title,
744
- subtitle: input.subtitle ?? null,
745
- description: input.description ?? null,
746
- thumbnail_url: input.thumbnailUrl ?? null,
747
- price: input.price ?? 0,
748
- currency: input.currency ?? "BRL",
749
- status: input.status ?? "draft",
750
- delivery_type: input.deliveryType ?? "online",
751
- sort_order: input.sortOrder ?? 0
752
- }).select("*").single();
753
- if (error) throw error;
754
- return rowToCourse(data);
755
- },
756
- async updateCourse(id, input) {
757
- const patch = {};
758
- if (input.title !== void 0) patch.title = input.title;
759
- if (input.slug !== void 0) patch.slug = input.slug;
760
- if (input.subtitle !== void 0) patch.subtitle = input.subtitle;
761
- if (input.description !== void 0) patch.description = input.description;
762
- if (input.thumbnailUrl !== void 0) patch.thumbnail_url = input.thumbnailUrl;
763
- if (input.price !== void 0) patch.price = input.price;
764
- if (input.currency !== void 0) patch.currency = input.currency;
765
- if (input.status !== void 0) patch.status = input.status;
766
- if (input.deliveryType !== void 0) patch.delivery_type = input.deliveryType;
767
- if (input.sortOrder !== void 0) patch.sort_order = input.sortOrder;
768
- const { data, error } = await scoped(getDb().from(T.courses).update(patch).eq("id", id)).select("*").single();
769
- if (error) throw error;
770
- return rowToCourse(data);
771
- },
772
- async deleteCourse(id) {
773
- const { error } = await scoped(getDb().from(T.courses).delete().eq("id", id));
774
- if (error) throw error;
775
- },
776
- // Modules ---------------------------------------------------------------
777
- async listModules(courseId) {
778
- const { data, error } = await scoped(getDb().from(T.modules).select("*").eq("course_id", courseId)).order("sort_order", { ascending: true });
779
- if (error) throw error;
780
- return (data ?? []).map(rowToModule);
781
- },
782
- async createModule(input) {
783
- const { data, error } = await getDb().from(T.modules).insert({
784
- tenant_id: getTenantId(),
785
- course_id: input.courseId,
786
- title: input.title,
787
- sort_order: input.sortOrder ?? 0
788
- }).select("*").single();
789
- if (error) throw error;
790
- return rowToModule(data);
791
- },
792
- async updateModule(id, input) {
793
- const patch = {};
794
- if (input.title !== void 0) patch.title = input.title;
795
- if (input.sortOrder !== void 0) patch.sort_order = input.sortOrder;
796
- const { data, error } = await scoped(getDb().from(T.modules).update(patch).eq("id", id)).select("*").single();
797
- if (error) throw error;
798
- return rowToModule(data);
799
- },
800
- async deleteModule(id) {
801
- const { error } = await scoped(getDb().from(T.modules).delete().eq("id", id));
802
- if (error) throw error;
803
- },
804
- // Lessons ---------------------------------------------------------------
805
- async listLessons(courseId) {
806
- const { data, error } = await scoped(getDb().from(T.lessons).select("*").eq("course_id", courseId)).order("sort_order", { ascending: true });
807
- if (error) throw error;
808
- return (data ?? []).map(rowToLesson);
809
- },
810
- async getLesson(id) {
811
- const { data, error } = await scoped(getDb().from(T.lessons).select("*").eq("id", id)).maybeSingle();
812
- if (error) throw error;
813
- return data ? rowToLesson(data) : null;
814
- },
815
- async createLesson(input) {
816
- const { data, error } = await getDb().from(T.lessons).insert({
817
- tenant_id: getTenantId(),
818
- course_id: input.courseId,
819
- module_id: input.moduleId,
820
- title: input.title,
821
- description: input.description ?? null,
822
- video_url: input.videoUrl,
823
- duration_sec: input.durationSec ?? 600,
824
- sort_order: input.sortOrder ?? 0
825
- }).select("*").single();
826
- if (error) throw error;
827
- return rowToLesson(data);
828
- },
829
- async updateLesson(id, input) {
830
- const patch = {};
831
- if (input.title !== void 0) patch.title = input.title;
832
- if (input.description !== void 0) patch.description = input.description;
833
- if (input.videoUrl !== void 0) patch.video_url = input.videoUrl;
834
- if (input.durationSec !== void 0) patch.duration_sec = input.durationSec;
835
- if (input.sortOrder !== void 0) patch.sort_order = input.sortOrder;
836
- const { data, error } = await scoped(getDb().from(T.lessons).update(patch).eq("id", id)).select("*").single();
837
- if (error) throw error;
838
- return rowToLesson(data);
839
- },
840
- async deleteLesson(id) {
841
- const { error } = await scoped(getDb().from(T.lessons).delete().eq("id", id));
842
- if (error) throw error;
843
- },
844
- // Enrollments + progress ------------------------------------------------
845
- async listEnrollments(customerId) {
846
- const { data, error } = await getDb().from(T.enrollments).select("*").eq("customer_id", customerId);
847
- if (error) throw error;
848
- return (data ?? []).map(rowToEnrollment);
849
- },
850
- async enroll(courseId, customerId) {
851
- const { data, error } = await getDb().from(T.enrollments).upsert(
852
- { tenant_id: getTenantId(), course_id: courseId, customer_id: customerId, status: "active" },
853
- { onConflict: "course_id,customer_id" }
854
- ).select("*").single();
855
- if (error) throw error;
856
- return rowToEnrollment(data);
857
- },
858
- async listProgress(enrollmentId) {
859
- const { data, error } = await getDb().from(T.progress).select("*").eq("enrollment_id", enrollmentId);
860
- if (error) throw error;
861
- return (data ?? []).map(rowToProgress);
862
- },
863
- async setLessonProgress(enrollmentId, lessonId, patch) {
864
- const row = { tenant_id: getTenantId(), enrollment_id: enrollmentId, lesson_id: lessonId };
865
- if (patch.completed !== void 0) {
866
- row.completed = patch.completed;
867
- row.completed_at = patch.completed ? (/* @__PURE__ */ new Date()).toISOString() : null;
868
- }
869
- if (patch.lastPositionSec !== void 0) row.last_position_sec = patch.lastPositionSec;
870
- const { data, error } = await getDb().from(T.progress).upsert(row, { onConflict: "enrollment_id,lesson_id" }).select("*").single();
871
- if (error) throw error;
872
- return rowToProgress(data);
873
- },
874
- // Offers ----------------------------------------------------------------
875
- async listOffers(courseId) {
876
- const { data, error } = await scoped(getDb().from(T.offers).select("*").eq("course_id", courseId)).order("sort_order", { ascending: true });
877
- if (error) throw error;
878
- return (data ?? []).map(rowToOffer);
879
- },
880
- async createOffer(input) {
881
- const { data, error } = await getDb().from(T.offers).insert({
882
- tenant_id: getTenantId(),
883
- course_id: input.courseId,
884
- name: input.name,
885
- price: input.price,
886
- currency: input.currency ?? "BRL",
887
- kind: input.kind ?? "one_time",
888
- recurring_interval: input.recurringInterval ?? (input.kind === "subscription" ? "month" : null),
889
- is_default: input.isDefault ?? false,
890
- is_order_bump: input.isOrderBump ?? false,
891
- sort_order: input.sortOrder ?? 0
892
- }).select("*").single();
893
- if (error) throw error;
894
- return rowToOffer(data);
895
- },
896
- async updateOffer(id, input) {
897
- const patch = {};
898
- if (input.name !== void 0) patch.name = input.name;
899
- if (input.price !== void 0) patch.price = input.price;
900
- if (input.currency !== void 0) patch.currency = input.currency;
901
- if (input.kind !== void 0) patch.kind = input.kind;
902
- if (input.recurringInterval !== void 0) patch.recurring_interval = input.recurringInterval;
903
- if (input.isDefault !== void 0) patch.is_default = input.isDefault;
904
- if (input.isOrderBump !== void 0) patch.is_order_bump = input.isOrderBump;
905
- if (input.sortOrder !== void 0) patch.sort_order = input.sortOrder;
906
- const { data, error } = await scoped(getDb().from(T.offers).update(patch).eq("id", id)).select("*").single();
907
- if (error) throw error;
908
- return rowToOffer(data);
909
- },
910
- async deleteOffer(id) {
911
- const { error } = await scoped(getDb().from(T.offers).delete().eq("id", id));
912
- if (error) throw error;
913
- },
914
- // Sales -----------------------------------------------------------------
915
- async listOrders(opts) {
916
- let q = scoped(getDb().from(T.orders).select("*"));
917
- if (opts?.courseId) q = q.eq("course_id", opts.courseId);
918
- if (opts?.financialStatus) q = q.eq("financial_status", opts.financialStatus);
919
- if (opts?.search) q = q.or(`customer_name.ilike.%${opts.search}%,customer_email.ilike.%${opts.search}%`);
920
- const { data, error } = await q.order("created_at", { ascending: false });
921
- if (error) throw error;
922
- return (data ?? []).map(rowToOrder);
923
- },
924
- async listCoreSales() {
925
- const { data, error } = await scoped(getDb().from("v_plg_course_sales").select("*")).order("created_at", { ascending: false });
926
- if (error) throw error;
927
- return (data ?? []).map((r) => ({
928
- id: r.id,
929
- courseId: r.course_id ?? "",
930
- offerId: r.offer_id ?? null,
931
- customerId: r.party_id ?? null,
932
- customerName: r.customer_name ?? null,
933
- customerEmail: r.customer_email ?? null,
934
- currency: r.currency ?? "BRL",
935
- total: Number(r.total ?? 0),
936
- platformFee: Number(r.platform_fee ?? 0),
937
- netValue: Number(r.net_value ?? r.total ?? 0),
938
- paymentMethod: r.payment_method ?? null,
939
- financialStatus: r.financial_status ?? "pending",
940
- stripePaymentIntentId: null,
941
- createdAt: r.created_at,
942
- installmentCount: Number(r.installment_count ?? 1)
943
- }));
944
- },
945
- async getOrder(id) {
946
- const db = getDb();
947
- const { data: v } = await scoped(db.from("v_plg_course_sales").select("*")).eq("id", id).maybeSingle();
948
- if (!v) return null;
949
- const [{ data: course }, { data: bills }, { data: pays }] = await Promise.all([
950
- db.from(T.courses).select("title").eq("id", v.course_id).maybeSingle(),
951
- db.from("plg_financial_movements").select("*").eq("invoice_id", id).eq("movement_kind", "bill").order("installment_number"),
952
- db.from("plg_financial_movements").select("*").eq("invoice_id", id).eq("movement_kind", "payment")
953
- ]);
954
- let offerName = null;
955
- if (v.offer_id) {
956
- const { data: off } = await db.from(T.offers).select("name").eq("id", v.offer_id).maybeSingle();
957
- offerName = off?.name ?? null;
958
- }
959
- const paymentsByInst = /* @__PURE__ */ new Map();
960
- for (const p of pays ?? []) paymentsByInst.set(p.installment_number ?? 0, p);
961
- const installments = (bills ?? []).map((b) => {
962
- const p = paymentsByInst.get(b.installment_number ?? 0);
963
- return {
964
- installmentNumber: b.installment_number ?? 1,
965
- amount: Number(b.amount ?? 0),
966
- paidAmount: Number(b.paid_amount ?? 0),
967
- status: b.status ?? "pending",
968
- dueDate: b.due_date ?? null,
969
- paymentDate: p?.payment_date ?? b.payment_date ?? null,
970
- cardBrand: p?.card_brand ?? null,
971
- cardInstallments: p?.card_installments ?? null
972
- };
973
- });
974
- const paid = (bills ?? []).reduce((s, b) => s + Number(b.paid_amount ?? 0), 0);
975
- const total = Number(v.total ?? 0);
976
- return {
977
- id: v.id,
978
- courseId: v.course_id ?? "",
979
- offerId: v.offer_id ?? null,
980
- customerId: v.party_id ?? null,
981
- customerName: v.customer_name ?? null,
982
- customerEmail: v.customer_email ?? null,
983
- currency: v.currency ?? "BRL",
984
- total,
985
- platformFee: Number(v.platform_fee ?? 0),
986
- netValue: Number(v.net_value ?? total),
987
- paymentMethod: v.payment_method ?? null,
988
- financialStatus: v.financial_status ?? "pending",
989
- stripePaymentIntentId: null,
990
- createdAt: v.created_at,
991
- installmentCount: Number(v.installment_count ?? installments.length ?? 1),
992
- courseTitle: course?.title ?? null,
993
- offerName,
994
- paidAmount: paid,
995
- balance: Math.max(0, total - paid),
996
- installments
997
- };
998
- },
999
- // Subscriptions ---------------------------------------------------------
1000
- async listSubscriptions(opts) {
1001
- let q = scoped(getDb().from(T.subscriptions).select("*"));
1002
- if (opts?.courseId) q = q.eq("course_id", opts.courseId);
1003
- if (opts?.status) q = q.eq("status", opts.status);
1004
- const { data, error } = await q.order("started_at", { ascending: false });
1005
- if (error) throw error;
1006
- return (data ?? []).map(rowToSubscription);
1007
- },
1008
- // Financial -------------------------------------------------------------
1009
- async getFinancialSummary() {
1010
- const [orders, subs, payouts] = await Promise.all([
1011
- scoped(getDb().from(T.orders).select("total,platform_fee,net_value,financial_status")),
1012
- scoped(getDb().from(T.subscriptions).select("net_value,interval,status")),
1013
- scoped(getDb().from(T.payouts).select("amount,status"))
1014
- ]);
1015
- const orderRows = orders.data ?? [];
1016
- const paid = orderRows.filter((o) => o.financial_status === "paid");
1017
- const refunded = orderRows.filter((o) => o.financial_status === "refunded");
1018
- const activeSubs = (subs.data ?? []).filter((s) => s.status === "active");
1019
- const netTotal = round22(paid.reduce((s, o) => s + Number(o.net_value ?? 0), 0));
1020
- const paidOut = round22((payouts.data ?? []).filter((p) => p.status === "paid").reduce((s, p) => s + Number(p.amount ?? 0), 0));
1021
- const mrr = round22(activeSubs.reduce((s, sub) => s + (sub.interval === "year" ? Number(sub.net_value) / 12 : Number(sub.net_value)), 0));
1022
- const totalCount = paid.length + refunded.length;
1023
- return {
1024
- currency: "BRL",
1025
- availableBalance: round22(Math.max(netTotal - paidOut, 0)),
1026
- pendingBalance: round22(orderRows.filter((o) => o.financial_status === "pending").reduce((s, o) => s + Number(o.net_value ?? 0), 0)),
1027
- totalRevenue: round22(paid.reduce((s, o) => s + Number(o.total ?? 0), 0)),
1028
- platformFeeTotal: round22(paid.reduce((s, o) => s + Number(o.platform_fee ?? 0), 0)),
1029
- salesCount: paid.length,
1030
- activeSubscriptions: activeSubs.length,
1031
- mrr,
1032
- refundRate: totalCount > 0 ? refunded.length / totalCount : 0,
1033
- conversionRate: 0
1034
- };
1035
- },
1036
- async listPayouts() {
1037
- const { data, error } = await scoped(getDb().from(T.payouts).select("*")).order("created_at", { ascending: false });
1038
- if (error) throw error;
1039
- return (data ?? []).map(rowToPayout);
1040
- },
1041
- async getCreatorAccount() {
1042
- const tenantId = getTenantId();
1043
- const { data } = await scoped(getDb().from(T.creatorAccounts).select("*")).maybeSingle();
1044
- return {
1045
- tenantId: tenantId ?? "",
1046
- stripeAccountId: data?.stripe_account_id ?? null,
1047
- chargesEnabled: data?.charges_enabled ?? false,
1048
- payoutsEnabled: data?.payouts_enabled ?? false,
1049
- defaultCurrency: data?.default_currency ?? "BRL",
1050
- platformFeeBps: data?.platform_fee_bps ?? 500
1051
- };
1052
- }
1053
- };
1054
- }
1055
- function createSafeCoursesProvider() {
1056
- return core.createSafeDataProvider(
1057
- () => createSupabaseCoursesProvider(),
1058
- () => createMockCoursesProvider()
1059
- );
1060
- }
1061
- function useMyCourses(customerId) {
1062
- const [courses, setCourses] = react.useState([]);
1063
- const [loading, setLoading] = react.useState(false);
1064
- const [tick, setTick] = react.useState(0);
1065
- react.useEffect(() => {
1066
- if (!customerId) {
1067
- setCourses([]);
1068
- return;
1069
- }
1070
- let active = true;
1071
- setLoading(true);
1072
- (async () => {
1073
- const provider = getCoursesProvider();
1074
- const enrollments = await provider.listEnrollments(customerId);
1075
- const result = [];
1076
- for (const enrollment of enrollments) {
1077
- const course = await provider.getCourse(enrollment.courseId);
1078
- if (!course) continue;
1079
- const lessons = await provider.listLessons(course.id);
1080
- const progress = await provider.listProgress(enrollment.id);
1081
- const completedLessons = progress.filter((p) => p.completed).length;
1082
- result.push({
1083
- course,
1084
- enrollment,
1085
- totalLessons: lessons.length,
1086
- completedLessons,
1087
- progressPercent: lessons.length ? Math.round(completedLessons / lessons.length * 100) : 0
1088
- });
1089
- }
1090
- if (active) {
1091
- setCourses(result.sort((a, b) => a.course.sortOrder - b.course.sortOrder));
1092
- setLoading(false);
1093
- }
1094
- })();
1095
- return () => {
1096
- active = false;
1097
- };
1098
- }, [customerId, tick]);
1099
- return { courses, loading, refresh: () => setTick((t) => t + 1) };
1100
- }
1101
- function useCourse(idOrSlug) {
1102
- const [course, setCourse] = react.useState(null);
1103
- const [modules, setModules] = react.useState([]);
1104
- const [lessons, setLessons] = react.useState([]);
1105
- const [loading, setLoading] = react.useState(false);
1106
- react.useEffect(() => {
1107
- if (!idOrSlug) return;
1108
- let active = true;
1109
- setLoading(true);
1110
- (async () => {
1111
- const provider = getCoursesProvider();
1112
- const c = await provider.getCourse(idOrSlug);
1113
- if (!c) {
1114
- if (active) {
1115
- setCourse(null);
1116
- setLoading(false);
1117
- }
1118
- return;
1119
- }
1120
- const [m, l] = await Promise.all([provider.listModules(c.id), provider.listLessons(c.id)]);
1121
- if (active) {
1122
- setCourse(c);
1123
- setModules(m);
1124
- setLessons(l);
1125
- setLoading(false);
1126
- }
1127
- })();
1128
- return () => {
1129
- active = false;
1130
- };
1131
- }, [idOrSlug]);
1132
- return { course, modules, lessons, loading };
1133
- }
1134
- function useCourseProgress(enrollmentId) {
1135
- const [map, setMap] = react.useState({});
1136
- const [tick, setTick] = react.useState(0);
1137
- react.useEffect(() => {
1138
- if (!enrollmentId) return;
1139
- let active = true;
1140
- (async () => {
1141
- const list = await getCoursesProvider().listProgress(enrollmentId);
1142
- if (active) setMap(Object.fromEntries(list.map((p) => [p.lessonId, p])));
1143
- })();
1144
- return () => {
1145
- active = false;
1146
- };
1147
- }, [enrollmentId, tick]);
1148
- const markLessonComplete = react.useCallback(
1149
- async (lessonId, completed = true) => {
1150
- if (!enrollmentId) return;
1151
- const updated = await getCoursesProvider().setLessonProgress(enrollmentId, lessonId, { completed });
1152
- setMap((m) => ({ ...m, [lessonId]: updated }));
1153
- },
1154
- [enrollmentId]
1155
- );
1156
- return {
1157
- progressByLesson: map,
1158
- isCompleted: (lessonId) => !!map[lessonId]?.completed,
1159
- markLessonComplete,
1160
- refresh: () => setTick((t) => t + 1)
1161
- };
1162
- }
1163
-
1164
- exports.DEFAULT_COURSE_CATALOG = DEFAULT_COURSE_CATALOG;
1165
- exports.DEFAULT_DEMO_LEDGER = DEFAULT_DEMO_LEDGER;
1166
- exports.DEMO_PLATFORM_FEE_BPS = DEMO_PLATFORM_FEE_BPS;
1167
- exports.MockCoursesProvider = MockCoursesProvider;
1168
- exports.buildCourseCatalog = buildCourseCatalog;
1169
- exports.buildDemoLedger = buildDemoLedger;
1170
- exports.createMockCoursesProvider = createMockCoursesProvider;
1171
- exports.createSafeCoursesProvider = createSafeCoursesProvider;
1172
- exports.createSupabaseCoursesProvider = createSupabaseCoursesProvider;
1173
- exports.getCoursesProvider = getCoursesProvider;
1174
- exports.getCoursesProviderOptional = getCoursesProviderOptional;
1175
- exports.getCoursesTenantId = getCoursesTenantId;
1176
- exports.setCoursesProvider = setCoursesProvider;
1177
- exports.setCoursesTenantResolver = setCoursesTenantResolver;
1178
- exports.useCourse = useCourse;
1179
- exports.useCourseProgress = useCourseProgress;
1180
- exports.useMyCourses = useMyCourses;
1181
- //# sourceMappingURL=index.cjs.map
1182
- //# sourceMappingURL=index.cjs.map