@memberjunction/actions-bizapps-lms 5.23.0 → 5.25.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.
Files changed (60) hide show
  1. package/.env.integration.example +4 -0
  2. package/.turbo/turbo-build.log +1 -1
  3. package/CHANGELOG.md +28 -0
  4. package/dist/base/base-lms.action.d.ts +5 -0
  5. package/dist/base/base-lms.action.d.ts.map +1 -1
  6. package/dist/base/base-lms.action.js +11 -4
  7. package/dist/base/base-lms.action.js.map +1 -1
  8. package/dist/providers/learnworlds/actions/create-user.action.d.ts.map +1 -1
  9. package/dist/providers/learnworlds/actions/create-user.action.js +3 -0
  10. package/dist/providers/learnworlds/actions/create-user.action.js.map +1 -1
  11. package/dist/providers/learnworlds/actions/get-course-details.action.js +6 -6
  12. package/dist/providers/learnworlds/actions/get-course-details.action.js.map +1 -1
  13. package/dist/providers/learnworlds/actions/get-courses.action.d.ts +5 -0
  14. package/dist/providers/learnworlds/actions/get-courses.action.d.ts.map +1 -1
  15. package/dist/providers/learnworlds/actions/get-courses.action.js +73 -48
  16. package/dist/providers/learnworlds/actions/get-courses.action.js.map +1 -1
  17. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts +3 -3
  18. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts.map +1 -1
  19. package/dist/providers/learnworlds/actions/get-user-details.action.js +23 -23
  20. package/dist/providers/learnworlds/actions/get-user-details.action.js.map +1 -1
  21. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts +4 -1
  22. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts.map +1 -1
  23. package/dist/providers/learnworlds/actions/get-user-progress.action.js +48 -37
  24. package/dist/providers/learnworlds/actions/get-user-progress.action.js.map +1 -1
  25. package/dist/providers/learnworlds/actions/get-users.action.d.ts +3 -0
  26. package/dist/providers/learnworlds/actions/get-users.action.d.ts.map +1 -1
  27. package/dist/providers/learnworlds/actions/get-users.action.js +21 -15
  28. package/dist/providers/learnworlds/actions/get-users.action.js.map +1 -1
  29. package/dist/providers/learnworlds/actions/onboard-learner.action.js +4 -4
  30. package/dist/providers/learnworlds/actions/onboard-learner.action.js.map +1 -1
  31. package/dist/providers/learnworlds/actions/update-user-progress.action.js +2 -2
  32. package/dist/providers/learnworlds/actions/update-user-progress.action.js.map +1 -1
  33. package/dist/providers/learnworlds/learnworlds-base.action.d.ts +44 -0
  34. package/dist/providers/learnworlds/learnworlds-base.action.d.ts.map +1 -1
  35. package/dist/providers/learnworlds/learnworlds-base.action.js +107 -2
  36. package/dist/providers/learnworlds/learnworlds-base.action.js.map +1 -1
  37. package/package.json +6 -6
  38. package/src/__tests__/get-certificates.action.test.ts +467 -0
  39. package/src/__tests__/get-course-analytics.action.test.ts +340 -0
  40. package/src/__tests__/get-course-details.action.test.ts +510 -0
  41. package/src/__tests__/get-courses.action.test.ts +1191 -0
  42. package/src/__tests__/get-quiz-results.action.test.ts +575 -0
  43. package/src/__tests__/get-user-details.action.test.ts +533 -0
  44. package/src/__tests__/get-user-enrollments.action.test.ts +387 -0
  45. package/src/__tests__/get-user-progress.action.test.ts +588 -0
  46. package/src/__tests__/get-users.action.test.ts +464 -0
  47. package/src/__tests__/integration.test.ts +252 -3
  48. package/src/__tests__/rate-limit-retry.test.ts +296 -0
  49. package/src/__tests__/update-user-progress.action.test.ts +312 -0
  50. package/src/base/base-lms.action.ts +12 -4
  51. package/src/providers/learnworlds/actions/create-user.action.ts +4 -0
  52. package/src/providers/learnworlds/actions/get-course-details.action.ts +6 -6
  53. package/src/providers/learnworlds/actions/get-courses.action.ts +78 -58
  54. package/src/providers/learnworlds/actions/get-user-details.action.ts +32 -25
  55. package/src/providers/learnworlds/actions/get-user-progress.action.ts +54 -41
  56. package/src/providers/learnworlds/actions/get-users.action.ts +24 -16
  57. package/src/providers/learnworlds/actions/onboard-learner.action.ts +4 -4
  58. package/src/providers/learnworlds/actions/update-user-progress.action.ts +2 -2
  59. package/src/providers/learnworlds/learnworlds-base.action.ts +128 -2
  60. package/tsconfig.json +2 -1
@@ -0,0 +1,1191 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ // Mock dependencies (same pattern as get-bundles.action.test.ts)
4
+ vi.mock('@memberjunction/actions', () => ({
5
+ BaseAction: class BaseAction {
6
+ protected async InternalRunAction(): Promise<unknown> {
7
+ return {};
8
+ }
9
+ },
10
+ }));
11
+
12
+ vi.mock('@memberjunction/global', () => ({
13
+ RegisterClass: () => (target: unknown) => target,
14
+ }));
15
+
16
+ vi.mock('@memberjunction/core', () => ({
17
+ UserInfo: class UserInfo {},
18
+ Metadata: vi.fn(),
19
+ RunView: vi.fn().mockImplementation(() => ({
20
+ RunView: vi.fn().mockResolvedValue({ Success: true, Results: [] }),
21
+ })),
22
+ }));
23
+
24
+ vi.mock('@memberjunction/core-entities', () => ({
25
+ MJCompanyIntegrationEntity: class MJCompanyIntegrationEntity {
26
+ CompanyID: string = '';
27
+ APIKey: string | null = null;
28
+ AccessToken: string | null = null;
29
+ ExternalSystemID: string | null = null;
30
+ CustomAttribute1: string | null = null;
31
+ },
32
+ }));
33
+
34
+ vi.mock('@memberjunction/actions-base', () => ({
35
+ ActionParam: class ActionParam {
36
+ Name: string = '';
37
+ Value: unknown = null;
38
+ Type: string = 'Input';
39
+ },
40
+ }));
41
+
42
+ import { UserInfo } from '@memberjunction/core';
43
+ import { GetLearnWorldsCoursesAction } from '../providers/learnworlds/actions/get-courses.action';
44
+ import { ActionResultSimple, RunActionParams } from '@memberjunction/actions-base';
45
+ import { LearnWorldsCourse, CourseCatalogSummary } from '../providers/learnworlds/interfaces';
46
+
47
+ /**
48
+ * Helper to create a mock UserInfo for test context
49
+ */
50
+ function createMockContextUser(): UserInfo {
51
+ return { ID: 'test-user-id', Name: 'Test User', Email: 'test@example.com' } as unknown as UserInfo;
52
+ }
53
+
54
+ /**
55
+ * Helper to build a raw LW API course object matching the LWApiCourse interface.
56
+ * Provides sensible defaults that can be selectively overridden per test.
57
+ */
58
+ function createRawApiCourse(overrides: Record<string, unknown> = {}): Record<string, unknown> {
59
+ return {
60
+ id: 'course-1',
61
+ title: 'Intro to TypeScript',
62
+ subtitle: 'Learn TypeScript from scratch',
63
+ description: 'A comprehensive course on TypeScript.',
64
+ short_description: 'TS basics',
65
+ status: 'published',
66
+ visibility: 'public',
67
+ is_active: true,
68
+ is_free: false,
69
+ price: 49.99,
70
+ currency: 'USD',
71
+ original_price: 79.99,
72
+ category_id: 'cat-1',
73
+ category_name: 'Programming',
74
+ tags: ['typescript', 'programming'],
75
+ level: 'beginner',
76
+ language: 'en',
77
+ duration: 3600,
78
+ estimated_duration: 7200,
79
+ thumbnail_url: 'https://example.com/thumb.jpg',
80
+ cover_image_url: 'https://example.com/cover.jpg',
81
+ promo_video_url: 'https://example.com/promo.mp4',
82
+ instructor_id: 'inst-1',
83
+ instructor_name: 'Jane Doe',
84
+ instructor_bio: 'Senior developer',
85
+ instructor_avatar: 'https://example.com/avatar.jpg',
86
+ total_units: 10,
87
+ total_lessons: 25,
88
+ total_quizzes: 5,
89
+ total_assignments: 3,
90
+ total_enrollments: 150,
91
+ active_enrollments: 80,
92
+ completion_rate: 72,
93
+ average_rating: 4.5,
94
+ total_reviews: 42,
95
+ created_at: '2024-06-15T10:00:00Z',
96
+ updated_at: '2024-06-20T12:00:00Z',
97
+ published_at: '2024-06-16T08:00:00Z',
98
+ requires_approval: false,
99
+ has_prerequisites: true,
100
+ prerequisites: ['course-0'],
101
+ certificate_available: true,
102
+ objectives: ['Learn TS basics', 'Build projects'],
103
+ target_audience: ['Beginners', 'JS developers'],
104
+ requirements: ['Basic JS knowledge'],
105
+ ...overrides,
106
+ };
107
+ }
108
+
109
+ describe('GetLearnWorldsCoursesAction', () => {
110
+ let action: GetLearnWorldsCoursesAction;
111
+ let contextUser: UserInfo;
112
+
113
+ beforeEach(() => {
114
+ action = new GetLearnWorldsCoursesAction();
115
+ contextUser = createMockContextUser();
116
+ });
117
+
118
+ // ─── GetCourses() typed public method ──────────────────────────────
119
+
120
+ describe('GetCourses() typed method', () => {
121
+ it('should return mapped courses with summary on happy path', async () => {
122
+ const rawCourse = createRawApiCourse();
123
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
124
+
125
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
126
+
127
+ expect(result.TotalCount).toBe(1);
128
+ expect(result.Courses).toHaveLength(1);
129
+ expect(result.Summary).toBeDefined();
130
+ expect(result.Summary.totalCourses).toBe(1);
131
+
132
+ const course: LearnWorldsCourse = result.Courses[0];
133
+ expect(course.id).toBe('course-1');
134
+ expect(course.title).toBe('Intro to TypeScript');
135
+ expect(course.subtitle).toBe('Learn TypeScript from scratch');
136
+ expect(course.description).toBe('A comprehensive course on TypeScript.');
137
+ expect(course.shortDescription).toBe('TS basics');
138
+ expect(course.status).toBe('published');
139
+ expect(course.visibility).toBe('public');
140
+ expect(course.isActive).toBe(true);
141
+ expect(course.isFree).toBe(false);
142
+ expect(course.price).toBe(49.99);
143
+ expect(course.currency).toBe('USD');
144
+ expect(course.originalPrice).toBe(79.99);
145
+ expect(course.discountPercentage).toBe(38); // Math.round(((79.99 - 49.99) / 79.99) * 100)
146
+ expect(course.categoryId).toBe('cat-1');
147
+ expect(course.categoryName).toBe('Programming');
148
+ expect(course.tags).toEqual(['typescript', 'programming']);
149
+ expect(course.level).toBe('beginner');
150
+ expect(course.language).toBe('en');
151
+ expect(course.duration).toBe(3600);
152
+ expect(course.thumbnailUrl).toBe('https://example.com/thumb.jpg');
153
+ expect(course.coverImageUrl).toBe('https://example.com/cover.jpg');
154
+ expect(course.promoVideoUrl).toBe('https://example.com/promo.mp4');
155
+ expect(course.instructorId).toBe('inst-1');
156
+ expect(course.instructorName).toBe('Jane Doe');
157
+ expect(course.instructorBio).toBe('Senior developer');
158
+ expect(course.instructorAvatarUrl).toBe('https://example.com/avatar.jpg');
159
+ expect(course.totalUnits).toBe(10);
160
+ expect(course.totalLessons).toBe(25);
161
+ expect(course.totalQuizzes).toBe(5);
162
+ expect(course.totalAssignments).toBe(3);
163
+ expect(course.totalEnrollments).toBe(150);
164
+ expect(course.activeEnrollments).toBe(80);
165
+ expect(course.completionRate).toBe(72);
166
+ expect(course.averageRating).toBe(4.5);
167
+ expect(course.totalReviews).toBe(42);
168
+ expect(course.requiresApproval).toBe(false);
169
+ expect(course.hasPrerequisites).toBe(true);
170
+ expect(course.prerequisites).toEqual(['course-0']);
171
+ expect(course.certificateAvailable).toBe(true);
172
+ expect(course.objectives).toEqual(['Learn TS basics', 'Build projects']);
173
+ expect(course.targetAudience).toEqual(['Beginners', 'JS developers']);
174
+ expect(course.requirements).toEqual(['Basic JS knowledge']);
175
+ });
176
+
177
+ it('should handle empty course list', async () => {
178
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
179
+
180
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
181
+
182
+ expect(result.TotalCount).toBe(0);
183
+ expect(result.Courses).toEqual([]);
184
+ expect(result.Summary.totalCourses).toBe(0);
185
+ expect(result.Summary.publishedCourses).toBe(0);
186
+ expect(result.Summary.draftCourses).toBe(0);
187
+ expect(result.Summary.freeCourses).toBe(0);
188
+ expect(result.Summary.paidCourses).toBe(0);
189
+ });
190
+ });
191
+
192
+ // ─── Course mapping: identity ──────────────────────────────────────
193
+
194
+ describe('mapCourseIdentity', () => {
195
+ it('should use _id fallback when id is undefined', async () => {
196
+ const rawCourse = createRawApiCourse({ id: undefined, _id: 'alt-course-id' });
197
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
198
+
199
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
200
+
201
+ expect(result.Courses[0].id).toBe('alt-course-id');
202
+ });
203
+
204
+ it('should default id to empty string when both id and _id are missing', async () => {
205
+ const rawCourse = createRawApiCourse({ id: undefined, _id: undefined });
206
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
207
+
208
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
209
+
210
+ expect(result.Courses[0].id).toBe('');
211
+ });
212
+
213
+ it('should default isActive to true when is_active is not explicitly false', async () => {
214
+ const rawCourse = createRawApiCourse({ is_active: undefined });
215
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
216
+
217
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
218
+
219
+ expect(result.Courses[0].isActive).toBe(true);
220
+ });
221
+
222
+ it('should set isActive to false when is_active is explicitly false', async () => {
223
+ const rawCourse = createRawApiCourse({ is_active: false });
224
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
225
+
226
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
227
+
228
+ expect(result.Courses[0].isActive).toBe(false);
229
+ });
230
+
231
+ it('should mark course as free when is_free is true', async () => {
232
+ const rawCourse = createRawApiCourse({ is_free: true, price: 0 });
233
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
234
+
235
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
236
+
237
+ expect(result.Courses[0].isFree).toBe(true);
238
+ });
239
+
240
+ it('should mark course as free when price is 0', async () => {
241
+ const rawCourse = createRawApiCourse({ is_free: false, price: 0 });
242
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
243
+
244
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
245
+
246
+ expect(result.Courses[0].isFree).toBe(true);
247
+ });
248
+
249
+ it('should use excerpt as shortDescription fallback', async () => {
250
+ const rawCourse = createRawApiCourse({ short_description: undefined, excerpt: 'Excerpt text' });
251
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
252
+
253
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
254
+
255
+ expect(result.Courses[0].shortDescription).toBe('Excerpt text');
256
+ });
257
+
258
+ it('should use category.id and category.name as fallbacks', async () => {
259
+ const rawCourse = createRawApiCourse({
260
+ category_id: undefined,
261
+ category_name: undefined,
262
+ category: { id: 'cat-nested', name: 'Nested Category' },
263
+ });
264
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
265
+
266
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
267
+
268
+ expect(result.Courses[0].categoryId).toBe('cat-nested');
269
+ expect(result.Courses[0].categoryName).toBe('Nested Category');
270
+ });
271
+
272
+ it('should map status aliases correctly', async () => {
273
+ const tests: Array<{ input: string; expected: string }> = [
274
+ { input: 'published', expected: 'published' },
275
+ { input: 'active', expected: 'published' },
276
+ { input: 'draft', expected: 'draft' },
277
+ { input: 'unpublished', expected: 'draft' },
278
+ { input: 'coming_soon', expected: 'coming_soon' },
279
+ { input: 'upcoming', expected: 'coming_soon' },
280
+ { input: 'unknown_status', expected: 'draft' },
281
+ ];
282
+
283
+ for (const { input, expected } of tests) {
284
+ const rawCourse = createRawApiCourse({ status: input });
285
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
286
+
287
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
288
+
289
+ expect(result.Courses[0].status).toBe(expected);
290
+ }
291
+ });
292
+
293
+ it('should map visibility aliases correctly', async () => {
294
+ const tests: Array<{ input: string; expected: string }> = [
295
+ { input: 'public', expected: 'public' },
296
+ { input: 'open', expected: 'public' },
297
+ { input: 'private', expected: 'private' },
298
+ { input: 'closed', expected: 'private' },
299
+ { input: 'hidden', expected: 'hidden' },
300
+ { input: 'unlisted', expected: 'hidden' },
301
+ { input: 'unknown_vis', expected: 'public' },
302
+ ];
303
+
304
+ for (const { input, expected } of tests) {
305
+ const rawCourse = createRawApiCourse({ visibility: input });
306
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
307
+
308
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
309
+
310
+ expect(result.Courses[0].visibility).toBe(expected);
311
+ }
312
+ });
313
+
314
+ it('should use access_type as fallback for visibility', async () => {
315
+ const rawCourse = createRawApiCourse({ visibility: undefined, access_type: 'closed' });
316
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
317
+
318
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
319
+
320
+ expect(result.Courses[0].visibility).toBe('private');
321
+ });
322
+
323
+ it('should map level aliases correctly', async () => {
324
+ const tests: Array<{ input: string; expected: string }> = [
325
+ { input: 'beginner', expected: 'beginner' },
326
+ { input: 'basic', expected: 'beginner' },
327
+ { input: 'introductory', expected: 'beginner' },
328
+ { input: 'intermediate', expected: 'intermediate' },
329
+ { input: 'medium', expected: 'intermediate' },
330
+ { input: 'advanced', expected: 'advanced' },
331
+ { input: 'expert', expected: 'advanced' },
332
+ { input: 'all', expected: 'all' },
333
+ { input: 'any', expected: 'all' },
334
+ { input: 'mixed', expected: 'all' },
335
+ { input: 'unknown_level', expected: 'all' },
336
+ ];
337
+
338
+ for (const { input, expected } of tests) {
339
+ const rawCourse = createRawApiCourse({ level: input });
340
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
341
+
342
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
343
+
344
+ expect(result.Courses[0].level).toBe(expected);
345
+ }
346
+ });
347
+
348
+ it('should use difficulty as fallback for level', async () => {
349
+ const rawCourse = createRawApiCourse({ level: undefined, difficulty: 'expert' });
350
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
351
+
352
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
353
+
354
+ expect(result.Courses[0].level).toBe('advanced');
355
+ });
356
+
357
+ it('should default language to en when missing', async () => {
358
+ const rawCourse = createRawApiCourse({ language: undefined });
359
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
360
+
361
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
362
+
363
+ expect(result.Courses[0].language).toBe('en');
364
+ });
365
+
366
+ it('should use image as fallback for thumbnailUrl', async () => {
367
+ const rawCourse = createRawApiCourse({ thumbnail_url: undefined, image: 'https://example.com/image.jpg' });
368
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
369
+
370
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
371
+
372
+ expect(result.Courses[0].thumbnailUrl).toBe('https://example.com/image.jpg');
373
+ });
374
+
375
+ it('should use cover_image as fallback for coverImageUrl', async () => {
376
+ const rawCourse = createRawApiCourse({ cover_image_url: undefined, cover_image: 'https://example.com/cover2.jpg' });
377
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
378
+
379
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
380
+
381
+ expect(result.Courses[0].coverImageUrl).toBe('https://example.com/cover2.jpg');
382
+ });
383
+
384
+ it('should use video_url as fallback for promoVideoUrl', async () => {
385
+ const rawCourse = createRawApiCourse({ promo_video_url: undefined, video_url: 'https://example.com/vid.mp4' });
386
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
387
+
388
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
389
+
390
+ expect(result.Courses[0].promoVideoUrl).toBe('https://example.com/vid.mp4');
391
+ });
392
+
393
+ it('should use estimated_duration as fallback for duration', async () => {
394
+ const rawCourse = createRawApiCourse({ duration: undefined, estimated_duration: 5400 });
395
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
396
+
397
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
398
+
399
+ expect(result.Courses[0].duration).toBe(5400);
400
+ });
401
+ });
402
+
403
+ // ─── Course mapping: pricing ───────────────────────────────────────
404
+
405
+ describe('mapCoursePricing', () => {
406
+ it('should default currency to USD when missing', async () => {
407
+ const rawCourse = createRawApiCourse({ currency: undefined });
408
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
409
+
410
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
411
+
412
+ expect(result.Courses[0].currency).toBe('USD');
413
+ });
414
+ });
415
+
416
+ // ─── Discount calculation ─────────────────────────────────────────
417
+
418
+ describe('discount calculation', () => {
419
+ it('should return undefined when original_price is not set', async () => {
420
+ const rawCourse = createRawApiCourse({ original_price: undefined });
421
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
422
+
423
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
424
+
425
+ expect(result.Courses[0].discountPercentage).toBeUndefined();
426
+ });
427
+
428
+ it('should return undefined when original_price equals current price', async () => {
429
+ const rawCourse = createRawApiCourse({ original_price: 49.99, price: 49.99 });
430
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
431
+
432
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
433
+
434
+ expect(result.Courses[0].discountPercentage).toBeUndefined();
435
+ });
436
+
437
+ it('should return undefined when original_price is less than current price', async () => {
438
+ const rawCourse = createRawApiCourse({ original_price: 30, price: 49.99 });
439
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
440
+
441
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
442
+
443
+ expect(result.Courses[0].discountPercentage).toBeUndefined();
444
+ });
445
+
446
+ it('should calculate correct discount percentage', async () => {
447
+ const rawCourse = createRawApiCourse({ original_price: 100, price: 75 });
448
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
449
+
450
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
451
+
452
+ expect(result.Courses[0].discountPercentage).toBe(25);
453
+ });
454
+
455
+ it('should round discount percentage to nearest integer', async () => {
456
+ const rawCourse = createRawApiCourse({ original_price: 99.99, price: 66.66 });
457
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
458
+
459
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
460
+
461
+ // Math.round(((99.99 - 66.66) / 99.99) * 100) = Math.round(33.33...) = 33
462
+ expect(result.Courses[0].discountPercentage).toBe(33);
463
+ });
464
+
465
+ it('should return undefined when current price is 0 (falsy)', async () => {
466
+ const rawCourse = createRawApiCourse({ original_price: 100, price: 0 });
467
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
468
+
469
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
470
+
471
+ // !currentPrice evaluates to true for 0, so undefined
472
+ expect(result.Courses[0].discountPercentage).toBeUndefined();
473
+ });
474
+ });
475
+
476
+ // ─── Course mapping: instructor ───────────────────────────────────
477
+
478
+ describe('mapCourseInstructor', () => {
479
+ it('should use nested instructor object as fallback', async () => {
480
+ const rawCourse = createRawApiCourse({
481
+ instructor_id: undefined,
482
+ instructor_name: undefined,
483
+ instructor_bio: undefined,
484
+ instructor_avatar: undefined,
485
+ instructor: { id: 'nested-inst', name: 'Nested Instructor', bio: 'Nested bio', avatar_url: 'https://example.com/nested.jpg' },
486
+ });
487
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
488
+
489
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
490
+
491
+ expect(result.Courses[0].instructorId).toBe('nested-inst');
492
+ expect(result.Courses[0].instructorName).toBe('Nested Instructor');
493
+ expect(result.Courses[0].instructorBio).toBe('Nested bio');
494
+ expect(result.Courses[0].instructorAvatarUrl).toBe('https://example.com/nested.jpg');
495
+ });
496
+
497
+ it('should use author_id and author_name as last-resort fallbacks', async () => {
498
+ const rawCourse = createRawApiCourse({
499
+ instructor_id: undefined,
500
+ instructor_name: undefined,
501
+ instructor: undefined,
502
+ author_id: 'author-1',
503
+ author_name: 'Author Name',
504
+ });
505
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
506
+
507
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
508
+
509
+ expect(result.Courses[0].instructorId).toBe('author-1');
510
+ expect(result.Courses[0].instructorName).toBe('Author Name');
511
+ });
512
+ });
513
+
514
+ // ─── Course mapping: content stats ────────────────────────────────
515
+
516
+ describe('mapCourseContentStats', () => {
517
+ it('should use sections_count and lessons_count as fallbacks', async () => {
518
+ const rawCourse = createRawApiCourse({
519
+ total_units: undefined,
520
+ total_lessons: undefined,
521
+ total_quizzes: undefined,
522
+ total_assignments: undefined,
523
+ sections_count: 8,
524
+ lessons_count: 20,
525
+ quizzes_count: 4,
526
+ assignments_count: 2,
527
+ });
528
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
529
+
530
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
531
+
532
+ expect(result.Courses[0].totalUnits).toBe(8);
533
+ expect(result.Courses[0].totalLessons).toBe(20);
534
+ expect(result.Courses[0].totalQuizzes).toBe(4);
535
+ expect(result.Courses[0].totalAssignments).toBe(2);
536
+ });
537
+
538
+ it('should default content stats to 0 when all are missing', async () => {
539
+ const rawCourse = createRawApiCourse({
540
+ total_units: undefined,
541
+ sections_count: undefined,
542
+ total_lessons: undefined,
543
+ lessons_count: undefined,
544
+ total_quizzes: undefined,
545
+ quizzes_count: undefined,
546
+ total_assignments: undefined,
547
+ assignments_count: undefined,
548
+ total_enrollments: undefined,
549
+ students_count: undefined,
550
+ active_enrollments: undefined,
551
+ active_students: undefined,
552
+ completion_rate: undefined,
553
+ });
554
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
555
+
556
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
557
+
558
+ expect(result.Courses[0].totalUnits).toBe(0);
559
+ expect(result.Courses[0].totalLessons).toBe(0);
560
+ expect(result.Courses[0].totalQuizzes).toBe(0);
561
+ expect(result.Courses[0].totalAssignments).toBe(0);
562
+ expect(result.Courses[0].totalEnrollments).toBe(0);
563
+ expect(result.Courses[0].activeEnrollments).toBe(0);
564
+ expect(result.Courses[0].completionRate).toBe(0);
565
+ });
566
+
567
+ it('should use students_count as fallback for totalEnrollments', async () => {
568
+ const rawCourse = createRawApiCourse({ total_enrollments: undefined, students_count: 99 });
569
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
570
+
571
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
572
+
573
+ expect(result.Courses[0].totalEnrollments).toBe(99);
574
+ });
575
+
576
+ it('should use active_students as fallback for activeEnrollments', async () => {
577
+ const rawCourse = createRawApiCourse({ active_enrollments: undefined, active_students: 33 });
578
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
579
+
580
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
581
+
582
+ expect(result.Courses[0].activeEnrollments).toBe(33);
583
+ });
584
+
585
+ it('should use rating as fallback for averageRating', async () => {
586
+ const rawCourse = createRawApiCourse({ average_rating: undefined, rating: 3.8 });
587
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
588
+
589
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
590
+
591
+ expect(result.Courses[0].averageRating).toBe(3.8);
592
+ });
593
+
594
+ it('should use reviews_count as fallback for totalReviews', async () => {
595
+ const rawCourse = createRawApiCourse({ total_reviews: undefined, reviews_count: 17 });
596
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
597
+
598
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
599
+
600
+ expect(result.Courses[0].totalReviews).toBe(17);
601
+ });
602
+
603
+ it('should use total_duration as fallback for estimatedDuration', async () => {
604
+ const rawCourse = createRawApiCourse({ estimated_duration: undefined, total_duration: 4500 });
605
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
606
+
607
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
608
+
609
+ expect(result.Courses[0].estimatedDuration).toBe(4500);
610
+ });
611
+ });
612
+
613
+ // ─── Course mapping: meta ─────────────────────────────────────────
614
+
615
+ describe('mapCourseMeta', () => {
616
+ it('should use created/updated fallbacks', async () => {
617
+ const rawCourse = createRawApiCourse({
618
+ created_at: undefined,
619
+ created: '2023-01-01T00:00:00Z',
620
+ updated_at: undefined,
621
+ updated: '2023-02-01T00:00:00Z',
622
+ });
623
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
624
+
625
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
626
+
627
+ expect(result.Courses[0].createdAt).toEqual(new Date('2023-01-01T00:00:00Z'));
628
+ expect(result.Courses[0].updatedAt).toEqual(new Date('2023-02-01T00:00:00Z'));
629
+ });
630
+
631
+ it('should parse epoch timestamps (seconds) for date fields', async () => {
632
+ const epochSeconds = 1700000000; // ~2023-11-14
633
+ const rawCourse = createRawApiCourse({
634
+ created_at: undefined,
635
+ created: epochSeconds,
636
+ updated_at: undefined,
637
+ updated: epochSeconds,
638
+ });
639
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
640
+
641
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
642
+
643
+ expect(result.Courses[0].createdAt).toEqual(new Date(epochSeconds * 1000));
644
+ expect(result.Courses[0].updatedAt).toEqual(new Date(epochSeconds * 1000));
645
+ });
646
+
647
+ it('should set publishedAt to undefined when not provided', async () => {
648
+ const rawCourse = createRawApiCourse({ published_at: undefined });
649
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
650
+
651
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
652
+
653
+ expect(result.Courses[0].publishedAt).toBeUndefined();
654
+ });
655
+
656
+ it('should set enrollment dates to undefined when not provided', async () => {
657
+ const rawCourse = createRawApiCourse({ enrollment_start: undefined, enrollment_end: undefined });
658
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
659
+
660
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
661
+
662
+ expect(result.Courses[0].enrollmentStartDate).toBeUndefined();
663
+ expect(result.Courses[0].enrollmentEndDate).toBeUndefined();
664
+ });
665
+
666
+ it('should default boolean meta fields to false when missing', async () => {
667
+ const rawCourse = createRawApiCourse({
668
+ requires_approval: undefined,
669
+ has_prerequisites: undefined,
670
+ certificate_available: undefined,
671
+ has_certificate: undefined,
672
+ });
673
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
674
+
675
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
676
+
677
+ expect(result.Courses[0].requiresApproval).toBe(false);
678
+ expect(result.Courses[0].hasPrerequisites).toBe(false);
679
+ expect(result.Courses[0].certificateAvailable).toBe(false);
680
+ });
681
+
682
+ it('should use has_certificate as fallback for certificateAvailable', async () => {
683
+ const rawCourse = createRawApiCourse({ certificate_available: undefined, has_certificate: true });
684
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
685
+
686
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
687
+
688
+ expect(result.Courses[0].certificateAvailable).toBe(true);
689
+ });
690
+
691
+ it('should use learning_objectives as fallback for objectives', async () => {
692
+ const rawCourse = createRawApiCourse({ objectives: undefined, learning_objectives: ['Objective A'] });
693
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
694
+
695
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
696
+
697
+ expect(result.Courses[0].objectives).toEqual(['Objective A']);
698
+ });
699
+
700
+ it('should use prerequisites_text as fallback for requirements', async () => {
701
+ const rawCourse = createRawApiCourse({ requirements: undefined, prerequisites_text: ['Prereq text'] });
702
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
703
+
704
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
705
+
706
+ expect(result.Courses[0].requirements).toEqual(['Prereq text']);
707
+ });
708
+
709
+ it('should default array meta fields to empty arrays when missing', async () => {
710
+ const rawCourse = createRawApiCourse({
711
+ prerequisites: undefined,
712
+ objectives: undefined,
713
+ learning_objectives: undefined,
714
+ target_audience: undefined,
715
+ requirements: undefined,
716
+ prerequisites_text: undefined,
717
+ });
718
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([rawCourse] as never);
719
+
720
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
721
+
722
+ expect(result.Courses[0].prerequisites).toEqual([]);
723
+ expect(result.Courses[0].objectives).toEqual([]);
724
+ expect(result.Courses[0].targetAudience).toEqual([]);
725
+ expect(result.Courses[0].requirements).toEqual([]);
726
+ });
727
+ });
728
+
729
+ // ─── Catalog summary: category, level, language counts ────────────
730
+
731
+ describe('catalog summary counts', () => {
732
+ it('should count categories, levels, and languages correctly', async () => {
733
+ const courses = [
734
+ createRawApiCourse({ id: 'c1', category_name: 'Programming', level: 'beginner', language: 'en' }),
735
+ createRawApiCourse({ id: 'c2', category_name: 'Programming', level: 'intermediate', language: 'en' }),
736
+ createRawApiCourse({ id: 'c3', category_name: 'Design', level: 'beginner', language: 'es' }),
737
+ ];
738
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
739
+
740
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
741
+ const summary: CourseCatalogSummary = result.Summary;
742
+
743
+ expect(summary.categoryCounts).toEqual({ Programming: 2, Design: 1 });
744
+ expect(summary.levelCounts).toEqual({ beginner: 2, intermediate: 1 });
745
+ expect(summary.languageCounts).toEqual({ en: 2, es: 1 });
746
+ });
747
+
748
+ it('should count published vs draft vs free vs paid correctly', async () => {
749
+ const courses = [
750
+ createRawApiCourse({ id: 'c1', status: 'published', is_free: true, price: 0 }),
751
+ createRawApiCourse({ id: 'c2', status: 'published', is_free: false, price: 50 }),
752
+ createRawApiCourse({ id: 'c3', status: 'draft', is_free: false, price: 30 }),
753
+ ];
754
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
755
+
756
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
757
+ const summary = result.Summary;
758
+
759
+ expect(summary.totalCourses).toBe(3);
760
+ expect(summary.publishedCourses).toBe(2);
761
+ expect(summary.draftCourses).toBe(1);
762
+ expect(summary.freeCourses).toBe(1);
763
+ expect(summary.paidCourses).toBe(2);
764
+ });
765
+
766
+ it('should skip missing category names in categoryCounts', async () => {
767
+ const courses = [
768
+ createRawApiCourse({ id: 'c1', category_name: undefined }),
769
+ createRawApiCourse({ id: 'c2', category_name: 'Design' }),
770
+ ];
771
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
772
+
773
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
774
+
775
+ // Only 'Design' should appear; the undefined category should be skipped
776
+ expect(result.Summary.categoryCounts).toEqual({ Design: 1 });
777
+ });
778
+ });
779
+
780
+ // ─── Catalog summary: enrollment stats ────────────────────────────
781
+
782
+ describe('catalog summary enrollment stats', () => {
783
+ it('should calculate totalEnrollments and averagePerCourse', async () => {
784
+ const courses = [
785
+ createRawApiCourse({ id: 'c1', total_enrollments: 100 }),
786
+ createRawApiCourse({ id: 'c2', total_enrollments: 50 }),
787
+ createRawApiCourse({ id: 'c3', total_enrollments: 150 }),
788
+ ];
789
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
790
+
791
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
792
+ const stats = result.Summary.enrollmentStats;
793
+
794
+ expect(stats.totalEnrollments).toBe(300);
795
+ expect(stats.averageEnrollmentsPerCourse).toBe(100); // Math.round(300 / 3)
796
+ });
797
+
798
+ it('should identify most popular courses (top 5, sorted by enrollments desc)', async () => {
799
+ const courses = Array.from({ length: 7 }, (_, i) =>
800
+ createRawApiCourse({
801
+ id: `c${i}`,
802
+ title: `Course ${i}`,
803
+ total_enrollments: (i + 1) * 10,
804
+ status: 'published',
805
+ }),
806
+ );
807
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
808
+
809
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
810
+ const popular = result.Summary.enrollmentStats.mostPopularCourses;
811
+
812
+ expect(popular).toHaveLength(5);
813
+ // Most popular first
814
+ expect(popular[0].id).toBe('c6');
815
+ expect(popular[0].enrollments).toBe(70);
816
+ expect(popular[4].id).toBe('c2');
817
+ expect(popular[4].enrollments).toBe(30);
818
+ });
819
+
820
+ it('should exclude courses with 0 enrollments from most popular', async () => {
821
+ const courses = [
822
+ createRawApiCourse({ id: 'c1', title: 'Course 1', total_enrollments: 0 }),
823
+ createRawApiCourse({ id: 'c2', title: 'Course 2', total_enrollments: 10 }),
824
+ ];
825
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
826
+
827
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
828
+ const popular = result.Summary.enrollmentStats.mostPopularCourses;
829
+
830
+ expect(popular).toHaveLength(1);
831
+ expect(popular[0].id).toBe('c2');
832
+ });
833
+
834
+ it('should handle empty enrollment stats for empty course list', async () => {
835
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
836
+
837
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
838
+ const stats = result.Summary.enrollmentStats;
839
+
840
+ expect(stats.totalEnrollments).toBe(0);
841
+ expect(stats.averageEnrollmentsPerCourse).toBe(0);
842
+ expect(stats.mostPopularCourses).toEqual([]);
843
+ });
844
+ });
845
+
846
+ // ─── Catalog summary: price stats ─────────────────────────────────
847
+
848
+ describe('catalog summary price stats', () => {
849
+ it('should calculate average, min, max for paid courses', async () => {
850
+ const courses = [
851
+ createRawApiCourse({ id: 'c1', is_free: false, price: 20 }),
852
+ createRawApiCourse({ id: 'c2', is_free: false, price: 60 }),
853
+ createRawApiCourse({ id: 'c3', is_free: false, price: 100 }),
854
+ ];
855
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
856
+
857
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
858
+ const ps = result.Summary.priceStats;
859
+
860
+ expect(ps.averagePrice).toBe(60); // Math.round((20+60+100)/3) = 60
861
+ expect(ps.minPrice).toBe(20);
862
+ expect(ps.maxPrice).toBe(100);
863
+ expect(ps.currency).toBe('USD');
864
+ });
865
+
866
+ it('should exclude free courses from price stats', async () => {
867
+ const courses = [
868
+ createRawApiCourse({ id: 'c1', is_free: true, price: 0 }),
869
+ createRawApiCourse({ id: 'c2', is_free: false, price: 50 }),
870
+ createRawApiCourse({ id: 'c3', is_free: false, price: 100 }),
871
+ ];
872
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
873
+
874
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
875
+ const ps = result.Summary.priceStats;
876
+
877
+ expect(ps.averagePrice).toBe(75); // Math.round((50+100)/2) = 75
878
+ expect(ps.minPrice).toBe(50);
879
+ expect(ps.maxPrice).toBe(100);
880
+ });
881
+
882
+ it('should return zeroed price stats when all courses are free', async () => {
883
+ const courses = [
884
+ createRawApiCourse({ id: 'c1', is_free: true, price: 0 }),
885
+ createRawApiCourse({ id: 'c2', is_free: true, price: 0 }),
886
+ ];
887
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
888
+
889
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
890
+ const ps = result.Summary.priceStats;
891
+
892
+ // No paid courses means the default summary priceStats stays
893
+ expect(ps.averagePrice).toBe(0);
894
+ expect(ps.minPrice).toBe(0);
895
+ expect(ps.maxPrice).toBe(0);
896
+ expect(ps.currency).toBe('USD');
897
+ });
898
+
899
+ it('should use first paid course currency for priceStats', async () => {
900
+ const courses = [
901
+ createRawApiCourse({ id: 'c1', is_free: false, price: 50, currency: 'EUR' }),
902
+ createRawApiCourse({ id: 'c2', is_free: false, price: 75, currency: 'GBP' }),
903
+ ];
904
+ vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue(courses as never);
905
+
906
+ const result = await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
907
+
908
+ expect(result.Summary.priceStats.currency).toBe('EUR');
909
+ });
910
+ });
911
+
912
+ // ─── Query param building ─────────────────────────────────────────
913
+
914
+ describe('query param building', () => {
915
+ it('should pass search text as query param', async () => {
916
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
917
+
918
+ await action.GetCourses({ CompanyID: 'comp-1', SearchText: 'typescript' }, contextUser);
919
+
920
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
921
+ expect(queryParams.search).toBe('typescript');
922
+ });
923
+
924
+ it('should pass status filter', async () => {
925
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
926
+
927
+ await action.GetCourses({ CompanyID: 'comp-1', Status: 'published' }, contextUser);
928
+
929
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
930
+ expect(queryParams.status).toBe('published');
931
+ });
932
+
933
+ it('should pass category_id, level, language filters', async () => {
934
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
935
+
936
+ await action.GetCourses(
937
+ { CompanyID: 'comp-1', CategoryID: 'cat-1', Level: 'beginner', Language: 'es' },
938
+ contextUser,
939
+ );
940
+
941
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
942
+ expect(queryParams.category_id).toBe('cat-1');
943
+ expect(queryParams.level).toBe('beginner');
944
+ expect(queryParams.language).toBe('es');
945
+ });
946
+
947
+ it('should set is_free when OnlyFree is true', async () => {
948
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
949
+
950
+ await action.GetCourses({ CompanyID: 'comp-1', OnlyFree: true }, contextUser);
951
+
952
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
953
+ expect(queryParams.is_free).toBe(true);
954
+ });
955
+
956
+ it('should not set is_free when OnlyFree is false', async () => {
957
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
958
+
959
+ await action.GetCourses({ CompanyID: 'comp-1', OnlyFree: false }, contextUser);
960
+
961
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
962
+ expect(queryParams.is_free).toBeUndefined();
963
+ });
964
+
965
+ it('should pass price range filters when positive', async () => {
966
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
967
+
968
+ await action.GetCourses({ CompanyID: 'comp-1', MinPrice: 10, MaxPrice: 200 }, contextUser);
969
+
970
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
971
+ expect(queryParams.min_price).toBe(10);
972
+ expect(queryParams.max_price).toBe(200);
973
+ });
974
+
975
+ it('should not pass price filters when 0', async () => {
976
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
977
+
978
+ await action.GetCourses({ CompanyID: 'comp-1', MinPrice: 0, MaxPrice: 0 }, contextUser);
979
+
980
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
981
+ expect(queryParams.min_price).toBeUndefined();
982
+ expect(queryParams.max_price).toBeUndefined();
983
+ });
984
+
985
+ it('should pass tags and instructor_id filters', async () => {
986
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
987
+
988
+ await action.GetCourses({ CompanyID: 'comp-1', Tags: 'typescript,advanced', InstructorID: 'inst-1' }, contextUser);
989
+
990
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
991
+ expect(queryParams.tags).toBe('typescript,advanced');
992
+ expect(queryParams.instructor_id).toBe('inst-1');
993
+ });
994
+
995
+ it('should format date filters as ISO 8601', async () => {
996
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
997
+
998
+ await action.GetCourses(
999
+ { CompanyID: 'comp-1', CreatedAfter: '2024-01-01', CreatedBefore: '2024-12-31' },
1000
+ contextUser,
1001
+ );
1002
+
1003
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1004
+ // formatLearnWorldsDate returns ISO string
1005
+ expect(queryParams.created_after).toBe(new Date('2024-01-01').toISOString());
1006
+ expect(queryParams.created_before).toBe(new Date('2024-12-31').toISOString());
1007
+ });
1008
+
1009
+ it('should build sort param with desc prefix by default', async () => {
1010
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1011
+
1012
+ await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
1013
+
1014
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1015
+ expect(queryParams.sort).toBe('-created');
1016
+ });
1017
+
1018
+ it('should build sort param without prefix for asc order', async () => {
1019
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1020
+
1021
+ await action.GetCourses({ CompanyID: 'comp-1', SortBy: 'title', SortOrder: 'asc' }, contextUser);
1022
+
1023
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1024
+ expect(queryParams.sort).toBe('title');
1025
+ });
1026
+
1027
+ it('should build sort param with custom field and desc order', async () => {
1028
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1029
+
1030
+ await action.GetCourses({ CompanyID: 'comp-1', SortBy: 'price', SortOrder: 'desc' }, contextUser);
1031
+
1032
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1033
+ expect(queryParams.sort).toBe('-price');
1034
+ });
1035
+
1036
+ it('should include enrollment_stats by default', async () => {
1037
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1038
+
1039
+ await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
1040
+
1041
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1042
+ expect(queryParams.include).toBe('enrollment_stats');
1043
+ });
1044
+
1045
+ it('should omit enrollment_stats include when IncludeEnrollmentStats is false', async () => {
1046
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1047
+
1048
+ await action.GetCourses({ CompanyID: 'comp-1', IncludeEnrollmentStats: false }, contextUser);
1049
+
1050
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1051
+ expect(queryParams.include).toBeUndefined();
1052
+ });
1053
+
1054
+ it('should cap limit at 100 even when MaxResults is higher', async () => {
1055
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1056
+
1057
+ await action.GetCourses({ CompanyID: 'comp-1', MaxResults: 500 }, contextUser);
1058
+
1059
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1060
+ expect(queryParams.limit).toBe(100);
1061
+ });
1062
+
1063
+ it('should use MaxResults as limit when <= 100', async () => {
1064
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1065
+
1066
+ await action.GetCourses({ CompanyID: 'comp-1', MaxResults: 25 }, contextUser);
1067
+
1068
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1069
+ expect(queryParams.limit).toBe(25);
1070
+ });
1071
+
1072
+ it('should not include undefined optional params in query', async () => {
1073
+ const spy = vi.spyOn(action as never, 'makeLearnWorldsPaginatedRequest').mockResolvedValue([] as never);
1074
+
1075
+ await action.GetCourses({ CompanyID: 'comp-1' }, contextUser);
1076
+
1077
+ const queryParams = spy.mock.calls[0][1] as Record<string, string | number | boolean>;
1078
+ expect(queryParams.search).toBeUndefined();
1079
+ expect(queryParams.status).toBeUndefined();
1080
+ expect(queryParams.category_id).toBeUndefined();
1081
+ expect(queryParams.level).toBeUndefined();
1082
+ expect(queryParams.language).toBeUndefined();
1083
+ expect(queryParams.is_free).toBeUndefined();
1084
+ expect(queryParams.min_price).toBeUndefined();
1085
+ expect(queryParams.max_price).toBeUndefined();
1086
+ expect(queryParams.tags).toBeUndefined();
1087
+ expect(queryParams.instructor_id).toBeUndefined();
1088
+ expect(queryParams.created_after).toBeUndefined();
1089
+ expect(queryParams.created_before).toBeUndefined();
1090
+ });
1091
+ });
1092
+
1093
+ // ─── InternalRunAction() ──────────────────────────────────────────
1094
+
1095
+ describe('InternalRunAction()', () => {
1096
+ it('should return success when GetCourses succeeds', async () => {
1097
+ const mockCourses: LearnWorldsCourse[] = [
1098
+ {
1099
+ id: 'c1',
1100
+ title: 'Course A',
1101
+ status: 'published',
1102
+ visibility: 'public',
1103
+ isActive: true,
1104
+ isFree: false,
1105
+ price: 50,
1106
+ currency: 'USD',
1107
+ totalUnits: 5,
1108
+ totalLessons: 10,
1109
+ totalQuizzes: 2,
1110
+ totalAssignments: 1,
1111
+ totalEnrollments: 100,
1112
+ activeEnrollments: 50,
1113
+ completionRate: 60,
1114
+ createdAt: new Date('2024-01-01'),
1115
+ updatedAt: new Date('2024-01-02'),
1116
+ requiresApproval: false,
1117
+ hasPrerequisites: false,
1118
+ certificateAvailable: true,
1119
+ },
1120
+ ];
1121
+
1122
+ const mockSummary: CourseCatalogSummary = {
1123
+ totalCourses: 1,
1124
+ publishedCourses: 1,
1125
+ draftCourses: 0,
1126
+ freeCourses: 0,
1127
+ paidCourses: 1,
1128
+ categoryCounts: {},
1129
+ levelCounts: {},
1130
+ languageCounts: {},
1131
+ enrollmentStats: {
1132
+ totalEnrollments: 100,
1133
+ averageEnrollmentsPerCourse: 100,
1134
+ mostPopularCourses: [{ id: 'c1', title: 'Course A', enrollments: 100 }],
1135
+ },
1136
+ priceStats: { averagePrice: 50, minPrice: 50, maxPrice: 50, currency: 'USD' },
1137
+ };
1138
+
1139
+ vi.spyOn(action, 'GetCourses').mockResolvedValue({
1140
+ Courses: mockCourses,
1141
+ TotalCount: 1,
1142
+ Summary: mockSummary,
1143
+ });
1144
+
1145
+ const runParams: RunActionParams = {
1146
+ Params: [
1147
+ { Name: 'CompanyID', Type: 'Input', Value: 'comp-1' },
1148
+ { Name: 'SearchText', Type: 'Input', Value: undefined },
1149
+ { Name: 'MaxResults', Type: 'Input', Value: undefined },
1150
+ ],
1151
+ ContextUser: contextUser,
1152
+ } as unknown as RunActionParams;
1153
+
1154
+ const result = (await action['InternalRunAction'](runParams)) as ActionResultSimple;
1155
+
1156
+ expect(result.Success).toBe(true);
1157
+ expect(result.ResultCode).toBe('SUCCESS');
1158
+ expect(result.Message).toContain('Successfully retrieved 1 courses from LearnWorlds');
1159
+ });
1160
+
1161
+ it('should return error result when GetCourses throws', async () => {
1162
+ vi.spyOn(action, 'GetCourses').mockRejectedValue(new Error('API connection failed'));
1163
+
1164
+ const runParams: RunActionParams = {
1165
+ Params: [{ Name: 'CompanyID', Type: 'Input', Value: 'comp-1' }],
1166
+ ContextUser: contextUser,
1167
+ } as unknown as RunActionParams;
1168
+
1169
+ const result = (await action['InternalRunAction'](runParams)) as ActionResultSimple;
1170
+
1171
+ expect(result.Success).toBe(false);
1172
+ expect(result.ResultCode).toBe('ERROR');
1173
+ expect(result.Message).toContain('API connection failed');
1174
+ });
1175
+
1176
+ it('should handle non-Error thrown values gracefully', async () => {
1177
+ vi.spyOn(action, 'GetCourses').mockRejectedValue('plain string error');
1178
+
1179
+ const runParams: RunActionParams = {
1180
+ Params: [{ Name: 'CompanyID', Type: 'Input', Value: 'comp-1' }],
1181
+ ContextUser: contextUser,
1182
+ } as unknown as RunActionParams;
1183
+
1184
+ const result = (await action['InternalRunAction'](runParams)) as ActionResultSimple;
1185
+
1186
+ expect(result.Success).toBe(false);
1187
+ expect(result.ResultCode).toBe('ERROR');
1188
+ expect(result.Message).toContain('Unknown error occurred');
1189
+ });
1190
+ });
1191
+ });