@fayz-ai/courses 0.2.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.
@@ -0,0 +1,90 @@
1
+ export type CourseStatus = 'draft' | 'published' | 'archived';
2
+ export interface Course {
3
+ id: string;
4
+ slug: string;
5
+ title: string;
6
+ subtitle: string | null;
7
+ description: string | null;
8
+ thumbnailUrl: string | null;
9
+ price: number;
10
+ currency: string;
11
+ status: CourseStatus;
12
+ sortOrder: number;
13
+ createdAt: string;
14
+ updatedAt: string;
15
+ }
16
+ export interface Module {
17
+ id: string;
18
+ courseId: string;
19
+ title: string;
20
+ sortOrder: number;
21
+ }
22
+ export interface Lesson {
23
+ id: string;
24
+ courseId: string;
25
+ moduleId: string;
26
+ title: string;
27
+ description: string | null;
28
+ /** Embed URL (YouTube/Vimeo) in the mock layer; a storage URL with a real backend. */
29
+ videoUrl: string;
30
+ durationSec: number;
31
+ sortOrder: number;
32
+ }
33
+ export interface Enrollment {
34
+ id: string;
35
+ courseId: string;
36
+ customerId: string;
37
+ status: 'active' | 'refunded';
38
+ enrolledAt: string;
39
+ }
40
+ export interface Progress {
41
+ id: string;
42
+ enrollmentId: string;
43
+ lessonId: string;
44
+ completed: boolean;
45
+ lastPositionSec: number;
46
+ completedAt: string | null;
47
+ }
48
+ export interface CreateCourseInput {
49
+ title: string;
50
+ slug?: string;
51
+ subtitle?: string;
52
+ description?: string;
53
+ thumbnailUrl?: string;
54
+ price?: number;
55
+ currency?: string;
56
+ status?: CourseStatus;
57
+ sortOrder?: number;
58
+ }
59
+ export type UpdateCourseInput = Partial<CreateCourseInput>;
60
+ export interface CreateModuleInput {
61
+ courseId: string;
62
+ title: string;
63
+ sortOrder?: number;
64
+ }
65
+ export type UpdateModuleInput = Partial<Omit<CreateModuleInput, 'courseId'>>;
66
+ export interface CreateLessonInput {
67
+ courseId: string;
68
+ moduleId: string;
69
+ title: string;
70
+ description?: string;
71
+ videoUrl: string;
72
+ durationSec?: number;
73
+ sortOrder?: number;
74
+ }
75
+ export type UpdateLessonInput = Partial<Omit<CreateLessonInput, 'courseId' | 'moduleId'>>;
76
+ export interface ListCoursesOptions {
77
+ status?: CourseStatus;
78
+ slug?: string;
79
+ search?: string;
80
+ }
81
+ /** A course plus the customer's enrollment + progress %, for "my courses". */
82
+ export interface EnrolledCourse {
83
+ course: Course;
84
+ enrollment: Enrollment;
85
+ totalLessons: number;
86
+ completedLessons: number;
87
+ /** 0..100 */
88
+ progressPercent: number;
89
+ }
90
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@fayz-ai/courses",
3
+ "version": "0.2.0",
4
+ "description": "Fayz SDK education domain — courses, modules, lessons, enrollments, progress",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "source": "./src/index.ts",
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "src"
20
+ ],
21
+ "dependencies": {
22
+ "@fayz-ai/core": "^0.2.0"
23
+ },
24
+ "peerDependencies": {
25
+ "react": "^18.0.0 || ^19.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "@types/react": "^18.3.0",
29
+ "react": "^18.3.0",
30
+ "tsup": "^8.2.0",
31
+ "typescript": "^5.5.0"
32
+ },
33
+ "license": "MIT",
34
+ "keywords": [
35
+ "fayz",
36
+ "courses",
37
+ "education",
38
+ "lms"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup && tsc --emitDeclarationOnly --declaration --declarationMap --noEmit false",
45
+ "dev": "tsup --watch",
46
+ "typecheck": "tsc --noEmit",
47
+ "clean": "rm -rf dist"
48
+ }
49
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,125 @@
1
+ import { useEffect, useState, useCallback } from 'react'
2
+ import { getCoursesProvider } from './provider'
3
+ import type { Course, Module, Lesson, Enrollment, Progress, EnrolledCourse } from './types'
4
+
5
+ /** Courses a customer owns, with progress % — the "my courses" data. */
6
+ export function useMyCourses(customerId: string | null): { courses: EnrolledCourse[]; loading: boolean; refresh: () => void } {
7
+ const [courses, setCourses] = useState<EnrolledCourse[]>([])
8
+ const [loading, setLoading] = useState(false)
9
+ const [tick, setTick] = useState(0)
10
+
11
+ useEffect(() => {
12
+ if (!customerId) {
13
+ setCourses([])
14
+ return
15
+ }
16
+ let active = true
17
+ setLoading(true)
18
+ ;(async () => {
19
+ const provider = getCoursesProvider()
20
+ const enrollments = await provider.listEnrollments(customerId)
21
+ const result: EnrolledCourse[] = []
22
+ for (const enrollment of enrollments) {
23
+ const course = await provider.getCourse(enrollment.courseId)
24
+ if (!course) continue
25
+ const lessons = await provider.listLessons(course.id)
26
+ const progress = await provider.listProgress(enrollment.id)
27
+ const completedLessons = progress.filter((p) => p.completed).length
28
+ result.push({
29
+ course,
30
+ enrollment,
31
+ totalLessons: lessons.length,
32
+ completedLessons,
33
+ progressPercent: lessons.length ? Math.round((completedLessons / lessons.length) * 100) : 0,
34
+ })
35
+ }
36
+ if (active) {
37
+ setCourses(result.sort((a, b) => a.course.sortOrder - b.course.sortOrder))
38
+ setLoading(false)
39
+ }
40
+ })()
41
+ return () => {
42
+ active = false
43
+ }
44
+ }, [customerId, tick])
45
+
46
+ return { courses, loading, refresh: () => setTick((t) => t + 1) }
47
+ }
48
+
49
+ /** A course's full content tree (modules + lessons) for the player. */
50
+ export function useCourse(idOrSlug: string | null): {
51
+ course: Course | null
52
+ modules: Module[]
53
+ lessons: Lesson[]
54
+ loading: boolean
55
+ } {
56
+ const [course, setCourse] = useState<Course | null>(null)
57
+ const [modules, setModules] = useState<Module[]>([])
58
+ const [lessons, setLessons] = useState<Lesson[]>([])
59
+ const [loading, setLoading] = useState(false)
60
+
61
+ useEffect(() => {
62
+ if (!idOrSlug) return
63
+ let active = true
64
+ setLoading(true)
65
+ ;(async () => {
66
+ const provider = getCoursesProvider()
67
+ const c = await provider.getCourse(idOrSlug)
68
+ if (!c) {
69
+ if (active) { setCourse(null); setLoading(false) }
70
+ return
71
+ }
72
+ const [m, l] = await Promise.all([provider.listModules(c.id), provider.listLessons(c.id)])
73
+ if (active) {
74
+ setCourse(c)
75
+ setModules(m)
76
+ setLessons(l)
77
+ setLoading(false)
78
+ }
79
+ })()
80
+ return () => {
81
+ active = false
82
+ }
83
+ }, [idOrSlug])
84
+
85
+ return { course, modules, lessons, loading }
86
+ }
87
+
88
+ /** Per-enrollment progress + a completion toggle. */
89
+ export function useCourseProgress(enrollmentId: string | null): {
90
+ progressByLesson: Record<string, Progress>
91
+ isCompleted: (lessonId: string) => boolean
92
+ markLessonComplete: (lessonId: string, completed?: boolean) => Promise<void>
93
+ refresh: () => void
94
+ } {
95
+ const [map, setMap] = useState<Record<string, Progress>>({})
96
+ const [tick, setTick] = useState(0)
97
+
98
+ useEffect(() => {
99
+ if (!enrollmentId) return
100
+ let active = true
101
+ ;(async () => {
102
+ const list = await getCoursesProvider().listProgress(enrollmentId)
103
+ if (active) setMap(Object.fromEntries(list.map((p) => [p.lessonId, p])))
104
+ })()
105
+ return () => {
106
+ active = false
107
+ }
108
+ }, [enrollmentId, tick])
109
+
110
+ const markLessonComplete = useCallback(
111
+ async (lessonId: string, completed = true) => {
112
+ if (!enrollmentId) return
113
+ const updated = await getCoursesProvider().setLessonProgress(enrollmentId, lessonId, { completed })
114
+ setMap((m) => ({ ...m, [lessonId]: updated }))
115
+ },
116
+ [enrollmentId],
117
+ )
118
+
119
+ return {
120
+ progressByLesson: map,
121
+ isCompleted: (lessonId) => !!map[lessonId]?.completed,
122
+ markLessonComplete,
123
+ refresh: () => setTick((t) => t + 1),
124
+ }
125
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ // @fayz-ai/courses — the education domain (the counterpart of @fayz-ai/shop).
2
+ export type {
3
+ Course, CourseStatus, Module, Lesson, Enrollment, Progress, EnrolledCourse,
4
+ CreateCourseInput, UpdateCourseInput,
5
+ CreateModuleInput, UpdateModuleInput,
6
+ CreateLessonInput, UpdateLessonInput,
7
+ ListCoursesOptions,
8
+ } from './types'
9
+
10
+ export type { CoursesProvider } from './provider'
11
+ export { setCoursesProvider, getCoursesProvider, getCoursesProviderOptional } from './provider'
12
+
13
+ export { MockCoursesProvider, createMockCoursesProvider } from './mock-provider'
14
+ export type { MockCoursesSeed } from './mock-provider'
15
+
16
+ export { buildCourseCatalog, DEFAULT_COURSE_CATALOG } from './seed'
17
+ export type { CourseCatalog, CourseSeedInput } from './seed'
18
+
19
+ export { useMyCourses, useCourse, useCourseProgress } from './hooks'
@@ -0,0 +1,235 @@
1
+ import type { CoursesProvider } from './provider'
2
+ import type {
3
+ Course, Module, Lesson, Enrollment, Progress,
4
+ CreateCourseInput, UpdateCourseInput,
5
+ CreateModuleInput, UpdateModuleInput,
6
+ CreateLessonInput, UpdateLessonInput,
7
+ ListCoursesOptions,
8
+ } from './types'
9
+ import { DEFAULT_COURSE_CATALOG, type CourseCatalog } from './seed'
10
+
11
+ function uid() {
12
+ return Math.random().toString(36).slice(2)
13
+ }
14
+ function now() {
15
+ return new Date().toISOString()
16
+ }
17
+ function slugify(s: string) {
18
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
19
+ }
20
+
21
+ const K = {
22
+ courses: 'fayz.courses.mock.courses.v1',
23
+ modules: 'fayz.courses.mock.modules.v1',
24
+ lessons: 'fayz.courses.mock.lessons.v1',
25
+ enrollments: 'fayz.courses.mock.enrollments.v1',
26
+ progress: 'fayz.courses.mock.progress.v1',
27
+ }
28
+
29
+ function load<T>(key: string): T[] | null {
30
+ try {
31
+ if (typeof localStorage === 'undefined') return null
32
+ const raw = localStorage.getItem(key)
33
+ return raw ? (JSON.parse(raw) as T[]) : null
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+ function save<T>(key: string, value: T[]): void {
39
+ try {
40
+ if (typeof localStorage !== 'undefined') localStorage.setItem(key, JSON.stringify(value))
41
+ } catch {
42
+ /* non-fatal in mock mode */
43
+ }
44
+ }
45
+
46
+ export interface MockCoursesSeed {
47
+ catalog?: CourseCatalog
48
+ /** Customer ids auto-enrolled in all courses (so the member area has data on first run). */
49
+ enrollAll?: string[]
50
+ }
51
+
52
+ /**
53
+ * Mock courses provider. Courses/modules/lessons are seeded from the catalog on
54
+ * first run, then PERSISTED (so admin edits survive). Enrollments/progress are
55
+ * persisted too. Both example apps share the default catalog, so admin↔member
56
+ * stay consistent.
57
+ */
58
+ export class MockCoursesProvider implements CoursesProvider {
59
+ constructor(seed?: MockCoursesSeed) {
60
+ const catalog = seed?.catalog ?? DEFAULT_COURSE_CATALOG
61
+ if (load<Course>(K.courses) == null) {
62
+ save(K.courses, catalog.courses)
63
+ save(K.modules, catalog.modules)
64
+ save(K.lessons, catalog.lessons)
65
+ }
66
+ // Auto-enroll demo customers in every course (idempotent).
67
+ if (seed?.enrollAll?.length) {
68
+ const courses = load<Course>(K.courses) ?? []
69
+ const enrollments = load<Enrollment>(K.enrollments) ?? []
70
+ let changed = false
71
+ for (const customerId of seed.enrollAll) {
72
+ for (const c of courses) {
73
+ if (!enrollments.some((e) => e.customerId === customerId && e.courseId === c.id)) {
74
+ enrollments.push({ id: uid(), courseId: c.id, customerId, status: 'active', enrolledAt: now() })
75
+ changed = true
76
+ }
77
+ }
78
+ }
79
+ if (changed) save(K.enrollments, enrollments)
80
+ }
81
+ }
82
+
83
+ private courses() { return load<Course>(K.courses) ?? [] }
84
+ private modules() { return load<Module>(K.modules) ?? [] }
85
+ private lessons() { return load<Lesson>(K.lessons) ?? [] }
86
+ private enrollments() { return load<Enrollment>(K.enrollments) ?? [] }
87
+ private progress() { return load<Progress>(K.progress) ?? [] }
88
+
89
+ // Courses -----------------------------------------------------------------
90
+ async listCourses(opts?: ListCoursesOptions): Promise<Course[]> {
91
+ let list = this.courses()
92
+ if (opts?.status) list = list.filter((c) => c.status === opts.status)
93
+ if (opts?.slug) list = list.filter((c) => c.slug === opts.slug)
94
+ if (opts?.search) {
95
+ const q = opts.search.toLowerCase()
96
+ list = list.filter((c) => c.title.toLowerCase().includes(q) || (c.description ?? '').toLowerCase().includes(q))
97
+ }
98
+ return list.slice().sort((a, b) => a.sortOrder - b.sortOrder)
99
+ }
100
+ async getCourse(idOrSlug: string): Promise<Course | null> {
101
+ return this.courses().find((c) => c.id === idOrSlug || c.slug === idOrSlug) ?? null
102
+ }
103
+ async createCourse(input: CreateCourseInput): Promise<Course> {
104
+ const list = this.courses()
105
+ const course: Course = {
106
+ id: uid(),
107
+ slug: input.slug ?? slugify(input.title),
108
+ title: input.title,
109
+ subtitle: input.subtitle ?? null,
110
+ description: input.description ?? null,
111
+ thumbnailUrl: input.thumbnailUrl ?? null,
112
+ price: input.price ?? 0,
113
+ currency: input.currency ?? 'BRL',
114
+ status: input.status ?? 'draft',
115
+ sortOrder: input.sortOrder ?? list.length,
116
+ createdAt: now(),
117
+ updatedAt: now(),
118
+ }
119
+ save(K.courses, [...list, course])
120
+ return course
121
+ }
122
+ async updateCourse(id: string, input: UpdateCourseInput): Promise<Course> {
123
+ const list = this.courses()
124
+ const idx = list.findIndex((c) => c.id === id)
125
+ if (idx < 0) throw new Error('Course not found')
126
+ const updated = { ...list[idx], ...input, updatedAt: now() } as Course
127
+ list[idx] = updated
128
+ save(K.courses, list)
129
+ return updated
130
+ }
131
+ async deleteCourse(id: string): Promise<void> {
132
+ save(K.courses, this.courses().filter((c) => c.id !== id))
133
+ }
134
+
135
+ // Modules -----------------------------------------------------------------
136
+ async listModules(courseId: string): Promise<Module[]> {
137
+ return this.modules().filter((m) => m.courseId === courseId).sort((a, b) => a.sortOrder - b.sortOrder)
138
+ }
139
+ async createModule(input: CreateModuleInput): Promise<Module> {
140
+ const list = this.modules()
141
+ const mod: Module = { id: uid(), courseId: input.courseId, title: input.title, sortOrder: input.sortOrder ?? list.filter((m) => m.courseId === input.courseId).length }
142
+ save(K.modules, [...list, mod])
143
+ return mod
144
+ }
145
+ async updateModule(id: string, input: UpdateModuleInput): Promise<Module> {
146
+ const list = this.modules()
147
+ const idx = list.findIndex((m) => m.id === id)
148
+ if (idx < 0) throw new Error('Module not found')
149
+ list[idx] = { ...list[idx], ...input } as Module
150
+ save(K.modules, list)
151
+ return list[idx]
152
+ }
153
+ async deleteModule(id: string): Promise<void> {
154
+ save(K.modules, this.modules().filter((m) => m.id !== id))
155
+ }
156
+
157
+ // Lessons -----------------------------------------------------------------
158
+ async listLessons(courseId: string): Promise<Lesson[]> {
159
+ return this.lessons().filter((l) => l.courseId === courseId).sort((a, b) => a.sortOrder - b.sortOrder)
160
+ }
161
+ async getLesson(id: string): Promise<Lesson | null> {
162
+ return this.lessons().find((l) => l.id === id) ?? null
163
+ }
164
+ async createLesson(input: CreateLessonInput): Promise<Lesson> {
165
+ const list = this.lessons()
166
+ const lesson: Lesson = {
167
+ id: uid(),
168
+ courseId: input.courseId,
169
+ moduleId: input.moduleId,
170
+ title: input.title,
171
+ description: input.description ?? null,
172
+ videoUrl: input.videoUrl,
173
+ durationSec: input.durationSec ?? 600,
174
+ sortOrder: input.sortOrder ?? list.filter((l) => l.moduleId === input.moduleId).length,
175
+ }
176
+ save(K.lessons, [...list, lesson])
177
+ return lesson
178
+ }
179
+ async updateLesson(id: string, input: UpdateLessonInput): Promise<Lesson> {
180
+ const list = this.lessons()
181
+ const idx = list.findIndex((l) => l.id === id)
182
+ if (idx < 0) throw new Error('Lesson not found')
183
+ list[idx] = { ...list[idx], ...input } as Lesson
184
+ save(K.lessons, list)
185
+ return list[idx]
186
+ }
187
+ async deleteLesson(id: string): Promise<void> {
188
+ save(K.lessons, this.lessons().filter((l) => l.id !== id))
189
+ }
190
+
191
+ // Enrollments + progress --------------------------------------------------
192
+ async listEnrollments(customerId: string): Promise<Enrollment[]> {
193
+ return this.enrollments().filter((e) => e.customerId === customerId)
194
+ }
195
+ async enroll(courseId: string, customerId: string): Promise<Enrollment> {
196
+ const list = this.enrollments()
197
+ const existing = list.find((e) => e.courseId === courseId && e.customerId === customerId)
198
+ if (existing) return existing
199
+ const enrollment: Enrollment = { id: uid(), courseId, customerId, status: 'active', enrolledAt: now() }
200
+ save(K.enrollments, [...list, enrollment])
201
+ return enrollment
202
+ }
203
+ async listProgress(enrollmentId: string): Promise<Progress[]> {
204
+ return this.progress().filter((p) => p.enrollmentId === enrollmentId)
205
+ }
206
+ async setLessonProgress(enrollmentId: string, lessonId: string, patch: { completed?: boolean; lastPositionSec?: number }): Promise<Progress> {
207
+ const list = this.progress()
208
+ const idx = list.findIndex((p) => p.enrollmentId === enrollmentId && p.lessonId === lessonId)
209
+ if (idx >= 0) {
210
+ const updated: Progress = {
211
+ ...list[idx],
212
+ completed: patch.completed ?? list[idx].completed,
213
+ lastPositionSec: patch.lastPositionSec ?? list[idx].lastPositionSec,
214
+ completedAt: (patch.completed ?? list[idx].completed) ? (list[idx].completedAt ?? now()) : null,
215
+ }
216
+ list[idx] = updated
217
+ save(K.progress, list)
218
+ return updated
219
+ }
220
+ const created: Progress = {
221
+ id: uid(),
222
+ enrollmentId,
223
+ lessonId,
224
+ completed: patch.completed ?? false,
225
+ lastPositionSec: patch.lastPositionSec ?? 0,
226
+ completedAt: patch.completed ? now() : null,
227
+ }
228
+ save(K.progress, [...list, created])
229
+ return created
230
+ }
231
+ }
232
+
233
+ export function createMockCoursesProvider(seed?: MockCoursesSeed): MockCoursesProvider {
234
+ return new MockCoursesProvider(seed)
235
+ }
@@ -0,0 +1,57 @@
1
+ import type {
2
+ Course, Module, Lesson, Enrollment, Progress,
3
+ CreateCourseInput, UpdateCourseInput,
4
+ CreateModuleInput, UpdateModuleInput,
5
+ CreateLessonInput, UpdateLessonInput,
6
+ ListCoursesOptions,
7
+ } from './types'
8
+
9
+ export interface CoursesProvider {
10
+ // Courses
11
+ listCourses(options?: ListCoursesOptions): Promise<Course[]>
12
+ getCourse(idOrSlug: string): Promise<Course | null>
13
+ createCourse(input: CreateCourseInput): Promise<Course>
14
+ updateCourse(id: string, input: UpdateCourseInput): Promise<Course>
15
+ deleteCourse(id: string): Promise<void>
16
+
17
+ // Modules
18
+ listModules(courseId: string): Promise<Module[]>
19
+ createModule(input: CreateModuleInput): Promise<Module>
20
+ updateModule(id: string, input: UpdateModuleInput): Promise<Module>
21
+ deleteModule(id: string): Promise<void>
22
+
23
+ // Lessons
24
+ listLessons(courseId: string): Promise<Lesson[]>
25
+ getLesson(id: string): Promise<Lesson | null>
26
+ createLesson(input: CreateLessonInput): Promise<Lesson>
27
+ updateLesson(id: string, input: UpdateLessonInput): Promise<Lesson>
28
+ deleteLesson(id: string): Promise<void>
29
+
30
+ // Enrollments + progress (member side)
31
+ listEnrollments(customerId: string): Promise<Enrollment[]>
32
+ enroll(courseId: string, customerId: string): Promise<Enrollment>
33
+ listProgress(enrollmentId: string): Promise<Progress[]>
34
+ setLessonProgress(
35
+ enrollmentId: string,
36
+ lessonId: string,
37
+ patch: { completed?: boolean; lastPositionSec?: number },
38
+ ): Promise<Progress>
39
+ }
40
+
41
+ // Global provider holder (mirrors @fayz-ai/shop's setShopProvider/getShopProvider).
42
+ let _provider: CoursesProvider | null = null
43
+
44
+ export function setCoursesProvider(provider: CoursesProvider): void {
45
+ _provider = provider
46
+ }
47
+
48
+ export function getCoursesProvider(): CoursesProvider {
49
+ if (!_provider) {
50
+ throw new Error('Courses provider not set. Call setCoursesProvider() (e.g. createMockCoursesProvider).')
51
+ }
52
+ return _provider
53
+ }
54
+
55
+ export function getCoursesProviderOptional(): CoursesProvider | null {
56
+ return _provider
57
+ }