@memberjunction/actions-bizapps-lms 5.3.1 → 5.4.1

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 (194) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +26 -0
  3. package/LEARNWORLDS_SIDECAR_PLAN.md +845 -0
  4. package/dist/base/base-lms.action.d.ts +26 -4
  5. package/dist/base/base-lms.action.d.ts.map +1 -1
  6. package/dist/base/base-lms.action.js +73 -17
  7. package/dist/base/base-lms.action.js.map +1 -1
  8. package/dist/providers/learnworlds/actions/attach-tags.action.d.ts +26 -0
  9. package/dist/providers/learnworlds/actions/attach-tags.action.d.ts.map +1 -0
  10. package/dist/providers/learnworlds/actions/attach-tags.action.js +79 -0
  11. package/dist/providers/learnworlds/actions/attach-tags.action.js.map +1 -0
  12. package/dist/providers/learnworlds/actions/create-user.action.d.ts +24 -1
  13. package/dist/providers/learnworlds/actions/create-user.action.d.ts.map +1 -1
  14. package/dist/providers/learnworlds/actions/create-user.action.js +166 -142
  15. package/dist/providers/learnworlds/actions/create-user.action.js.map +1 -1
  16. package/dist/providers/learnworlds/actions/detach-tags.action.d.ts +26 -0
  17. package/dist/providers/learnworlds/actions/detach-tags.action.d.ts.map +1 -0
  18. package/dist/providers/learnworlds/actions/detach-tags.action.js +79 -0
  19. package/dist/providers/learnworlds/actions/detach-tags.action.js.map +1 -0
  20. package/dist/providers/learnworlds/actions/enroll-user.action.d.ts +31 -3
  21. package/dist/providers/learnworlds/actions/enroll-user.action.d.ts.map +1 -1
  22. package/dist/providers/learnworlds/actions/enroll-user.action.js +179 -125
  23. package/dist/providers/learnworlds/actions/enroll-user.action.js.map +1 -1
  24. package/dist/providers/learnworlds/actions/get-bulk-data.action.d.ts +79 -0
  25. package/dist/providers/learnworlds/actions/get-bulk-data.action.d.ts.map +1 -0
  26. package/dist/providers/learnworlds/actions/get-bulk-data.action.js +359 -0
  27. package/dist/providers/learnworlds/actions/get-bulk-data.action.js.map +1 -0
  28. package/dist/providers/learnworlds/actions/get-bundles.action.d.ts +34 -0
  29. package/dist/providers/learnworlds/actions/get-bundles.action.d.ts.map +1 -0
  30. package/dist/providers/learnworlds/actions/get-bundles.action.js +107 -0
  31. package/dist/providers/learnworlds/actions/get-bundles.action.js.map +1 -0
  32. package/dist/providers/learnworlds/actions/get-certificates.action.d.ts +33 -2
  33. package/dist/providers/learnworlds/actions/get-certificates.action.d.ts.map +1 -1
  34. package/dist/providers/learnworlds/actions/get-certificates.action.js +311 -244
  35. package/dist/providers/learnworlds/actions/get-certificates.action.js.map +1 -1
  36. package/dist/providers/learnworlds/actions/get-course-analytics.action.d.ts +14 -14
  37. package/dist/providers/learnworlds/actions/get-course-analytics.action.d.ts.map +1 -1
  38. package/dist/providers/learnworlds/actions/get-course-analytics.action.js +234 -226
  39. package/dist/providers/learnworlds/actions/get-course-analytics.action.js.map +1 -1
  40. package/dist/providers/learnworlds/actions/get-course-details.action.d.ts +42 -6
  41. package/dist/providers/learnworlds/actions/get-course-details.action.d.ts.map +1 -1
  42. package/dist/providers/learnworlds/actions/get-course-details.action.js +182 -148
  43. package/dist/providers/learnworlds/actions/get-course-details.action.js.map +1 -1
  44. package/dist/providers/learnworlds/actions/get-courses.action.d.ts +29 -82
  45. package/dist/providers/learnworlds/actions/get-courses.action.d.ts.map +1 -1
  46. package/dist/providers/learnworlds/actions/get-courses.action.js +188 -207
  47. package/dist/providers/learnworlds/actions/get-courses.action.js.map +1 -1
  48. package/dist/providers/learnworlds/actions/get-quiz-results.action.d.ts +22 -2
  49. package/dist/providers/learnworlds/actions/get-quiz-results.action.d.ts.map +1 -1
  50. package/dist/providers/learnworlds/actions/get-quiz-results.action.js +316 -294
  51. package/dist/providers/learnworlds/actions/get-quiz-results.action.js.map +1 -1
  52. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts +23 -59
  53. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts.map +1 -1
  54. package/dist/providers/learnworlds/actions/get-user-details.action.js +113 -114
  55. package/dist/providers/learnworlds/actions/get-user-details.action.js.map +1 -1
  56. package/dist/providers/learnworlds/actions/get-user-enrollments.action.d.ts +43 -5
  57. package/dist/providers/learnworlds/actions/get-user-enrollments.action.d.ts.map +1 -1
  58. package/dist/providers/learnworlds/actions/get-user-enrollments.action.js +191 -147
  59. package/dist/providers/learnworlds/actions/get-user-enrollments.action.js.map +1 -1
  60. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts +21 -92
  61. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts.map +1 -1
  62. package/dist/providers/learnworlds/actions/get-user-progress.action.js +145 -166
  63. package/dist/providers/learnworlds/actions/get-user-progress.action.js.map +1 -1
  64. package/dist/providers/learnworlds/actions/get-users.action.d.ts +14 -28
  65. package/dist/providers/learnworlds/actions/get-users.action.d.ts.map +1 -1
  66. package/dist/providers/learnworlds/actions/get-users.action.js +122 -143
  67. package/dist/providers/learnworlds/actions/get-users.action.js.map +1 -1
  68. package/dist/providers/learnworlds/actions/index.d.ts +7 -0
  69. package/dist/providers/learnworlds/actions/index.d.ts.map +1 -1
  70. package/dist/providers/learnworlds/actions/index.js +7 -0
  71. package/dist/providers/learnworlds/actions/index.js.map +1 -1
  72. package/dist/providers/learnworlds/actions/onboard-learner.action.d.ts +53 -0
  73. package/dist/providers/learnworlds/actions/onboard-learner.action.d.ts.map +1 -0
  74. package/dist/providers/learnworlds/actions/onboard-learner.action.js +236 -0
  75. package/dist/providers/learnworlds/actions/onboard-learner.action.js.map +1 -0
  76. package/dist/providers/learnworlds/actions/sso-login.action.d.ts +35 -0
  77. package/dist/providers/learnworlds/actions/sso-login.action.d.ts.map +1 -0
  78. package/dist/providers/learnworlds/actions/sso-login.action.js +101 -0
  79. package/dist/providers/learnworlds/actions/sso-login.action.js.map +1 -0
  80. package/dist/providers/learnworlds/actions/update-user-progress.action.d.ts +12 -1
  81. package/dist/providers/learnworlds/actions/update-user-progress.action.d.ts.map +1 -1
  82. package/dist/providers/learnworlds/actions/update-user-progress.action.js +167 -210
  83. package/dist/providers/learnworlds/actions/update-user-progress.action.js.map +1 -1
  84. package/dist/providers/learnworlds/actions/update-user.action.d.ts +39 -0
  85. package/dist/providers/learnworlds/actions/update-user.action.d.ts.map +1 -0
  86. package/dist/providers/learnworlds/actions/update-user.action.js +168 -0
  87. package/dist/providers/learnworlds/actions/update-user.action.js.map +1 -0
  88. package/dist/providers/learnworlds/index.d.ts +1 -0
  89. package/dist/providers/learnworlds/index.d.ts.map +1 -1
  90. package/dist/providers/learnworlds/index.js +2 -0
  91. package/dist/providers/learnworlds/index.js.map +1 -1
  92. package/dist/providers/learnworlds/interfaces/bundle.types.d.ts +16 -0
  93. package/dist/providers/learnworlds/interfaces/bundle.types.d.ts.map +1 -0
  94. package/dist/providers/learnworlds/interfaces/bundle.types.js +2 -0
  95. package/dist/providers/learnworlds/interfaces/bundle.types.js.map +1 -0
  96. package/dist/providers/learnworlds/interfaces/certificate.types.d.ts +66 -0
  97. package/dist/providers/learnworlds/interfaces/certificate.types.d.ts.map +1 -0
  98. package/dist/providers/learnworlds/interfaces/certificate.types.js +2 -0
  99. package/dist/providers/learnworlds/interfaces/certificate.types.js.map +1 -0
  100. package/dist/providers/learnworlds/interfaces/common.types.d.ts +221 -0
  101. package/dist/providers/learnworlds/interfaces/common.types.d.ts.map +1 -0
  102. package/dist/providers/learnworlds/interfaces/common.types.js +2 -0
  103. package/dist/providers/learnworlds/interfaces/common.types.js.map +1 -0
  104. package/dist/providers/learnworlds/interfaces/course.types.d.ts +393 -0
  105. package/dist/providers/learnworlds/interfaces/course.types.d.ts.map +1 -0
  106. package/dist/providers/learnworlds/interfaces/course.types.js +2 -0
  107. package/dist/providers/learnworlds/interfaces/course.types.js.map +1 -0
  108. package/dist/providers/learnworlds/interfaces/enrollment.types.d.ts +165 -0
  109. package/dist/providers/learnworlds/interfaces/enrollment.types.d.ts.map +1 -0
  110. package/dist/providers/learnworlds/interfaces/enrollment.types.js +2 -0
  111. package/dist/providers/learnworlds/interfaces/enrollment.types.js.map +1 -0
  112. package/dist/providers/learnworlds/interfaces/index.d.ts +12 -0
  113. package/dist/providers/learnworlds/interfaces/index.d.ts.map +1 -0
  114. package/dist/providers/learnworlds/interfaces/index.js +13 -0
  115. package/dist/providers/learnworlds/interfaces/index.js.map +1 -0
  116. package/dist/providers/learnworlds/interfaces/onboarding.types.d.ts +39 -0
  117. package/dist/providers/learnworlds/interfaces/onboarding.types.d.ts.map +1 -0
  118. package/dist/providers/learnworlds/interfaces/onboarding.types.js +2 -0
  119. package/dist/providers/learnworlds/interfaces/onboarding.types.js.map +1 -0
  120. package/dist/providers/learnworlds/interfaces/quiz.types.d.ts +108 -0
  121. package/dist/providers/learnworlds/interfaces/quiz.types.d.ts.map +1 -0
  122. package/dist/providers/learnworlds/interfaces/quiz.types.js +2 -0
  123. package/dist/providers/learnworlds/interfaces/quiz.types.js.map +1 -0
  124. package/dist/providers/learnworlds/interfaces/sso.types.d.ts +18 -0
  125. package/dist/providers/learnworlds/interfaces/sso.types.d.ts.map +1 -0
  126. package/dist/providers/learnworlds/interfaces/sso.types.js +2 -0
  127. package/dist/providers/learnworlds/interfaces/sso.types.js.map +1 -0
  128. package/dist/providers/learnworlds/interfaces/sync.types.d.ts +44 -0
  129. package/dist/providers/learnworlds/interfaces/sync.types.d.ts.map +1 -0
  130. package/dist/providers/learnworlds/interfaces/sync.types.js +2 -0
  131. package/dist/providers/learnworlds/interfaces/sync.types.js.map +1 -0
  132. package/dist/providers/learnworlds/interfaces/tag.types.d.ts +17 -0
  133. package/dist/providers/learnworlds/interfaces/tag.types.d.ts.map +1 -0
  134. package/dist/providers/learnworlds/interfaces/tag.types.js +2 -0
  135. package/dist/providers/learnworlds/interfaces/tag.types.js.map +1 -0
  136. package/dist/providers/learnworlds/interfaces/user.types.d.ts +198 -0
  137. package/dist/providers/learnworlds/interfaces/user.types.d.ts.map +1 -0
  138. package/dist/providers/learnworlds/interfaces/user.types.js +2 -0
  139. package/dist/providers/learnworlds/interfaces/user.types.js.map +1 -0
  140. package/dist/providers/learnworlds/learnworlds-base.action.d.ts +111 -7
  141. package/dist/providers/learnworlds/learnworlds-base.action.d.ts.map +1 -1
  142. package/dist/providers/learnworlds/learnworlds-base.action.js +293 -56
  143. package/dist/providers/learnworlds/learnworlds-base.action.js.map +1 -1
  144. package/package.json +8 -7
  145. package/src/__tests__/attach-tags.action.test.ts +137 -0
  146. package/src/__tests__/create-user.action.test.ts +311 -0
  147. package/src/__tests__/detach-tags.action.test.ts +136 -0
  148. package/src/__tests__/enroll-user.action.test.ts +283 -0
  149. package/src/__tests__/get-bulk-data.action.test.ts +649 -0
  150. package/src/__tests__/get-bundles.action.test.ts +215 -0
  151. package/src/__tests__/lms.test.ts +275 -184
  152. package/src/__tests__/onboard-learner.action.test.ts +455 -0
  153. package/src/__tests__/sso-login.action.test.ts +256 -0
  154. package/src/__tests__/update-user.action.test.ts +350 -0
  155. package/src/base/base-lms.action.ts +226 -163
  156. package/src/providers/learnworlds/actions/attach-tags.action.ts +90 -0
  157. package/src/providers/learnworlds/actions/create-user.action.ts +291 -235
  158. package/src/providers/learnworlds/actions/detach-tags.action.ts +90 -0
  159. package/src/providers/learnworlds/actions/enroll-user.action.ts +326 -220
  160. package/src/providers/learnworlds/actions/get-bulk-data.action.ts +438 -0
  161. package/src/providers/learnworlds/actions/get-bundles.action.ts +139 -0
  162. package/src/providers/learnworlds/actions/get-certificates.action.ts +499 -309
  163. package/src/providers/learnworlds/actions/get-course-analytics.action.ts +470 -337
  164. package/src/providers/learnworlds/actions/get-course-details.action.ts +395 -249
  165. package/src/providers/learnworlds/actions/get-courses.action.ts +508 -565
  166. package/src/providers/learnworlds/actions/get-quiz-results.action.ts +606 -381
  167. package/src/providers/learnworlds/actions/get-user-details.action.ts +335 -349
  168. package/src/providers/learnworlds/actions/get-user-enrollments.action.ts +328 -228
  169. package/src/providers/learnworlds/actions/get-user-progress.action.ts +522 -571
  170. package/src/providers/learnworlds/actions/get-users.action.ts +231 -282
  171. package/src/providers/learnworlds/actions/index.ts +8 -1
  172. package/src/providers/learnworlds/actions/onboard-learner.action.ts +286 -0
  173. package/src/providers/learnworlds/actions/sso-login.action.ts +116 -0
  174. package/src/providers/learnworlds/actions/update-user-progress.action.ts +301 -263
  175. package/src/providers/learnworlds/actions/update-user.action.ts +181 -0
  176. package/src/providers/learnworlds/index.ts +4 -1
  177. package/src/providers/learnworlds/interfaces/bundle.types.ts +17 -0
  178. package/src/providers/learnworlds/interfaces/certificate.types.ts +69 -0
  179. package/src/providers/learnworlds/interfaces/common.types.ts +233 -0
  180. package/src/providers/learnworlds/interfaces/course.types.ts +411 -0
  181. package/src/providers/learnworlds/interfaces/enrollment.types.ts +176 -0
  182. package/src/providers/learnworlds/interfaces/index.ts +12 -0
  183. package/src/providers/learnworlds/interfaces/onboarding.types.ts +41 -0
  184. package/src/providers/learnworlds/interfaces/quiz.types.ts +118 -0
  185. package/src/providers/learnworlds/interfaces/sso.types.ts +19 -0
  186. package/src/providers/learnworlds/interfaces/sync.types.ts +46 -0
  187. package/src/providers/learnworlds/interfaces/tag.types.ts +18 -0
  188. package/src/providers/learnworlds/interfaces/user.types.ts +204 -0
  189. package/src/providers/learnworlds/learnworlds-base.action.ts +468 -210
  190. package/tsconfig.json +1 -1
  191. package/dist/__tests__/lms.test.d.ts +0 -2
  192. package/dist/__tests__/lms.test.d.ts.map +0 -1
  193. package/dist/__tests__/lms.test.js +0 -232
  194. package/dist/__tests__/lms.test.js.map +0 -1
@@ -2,332 +2,522 @@ import { RegisterClass } from '@memberjunction/global';
2
2
  import { LearnWorldsBaseAction } from '../learnworlds-base.action';
3
3
  import { ActionParam, ActionResultSimple, RunActionParams } from '@memberjunction/actions-base';
4
4
  import { BaseAction } from '@memberjunction/actions';
5
+ import { UserInfo } from '@memberjunction/core';
6
+ import { GetCertificatesParams, GetCertificatesResult, FormattedCertificate, CertificatesSummary } from '../interfaces';
7
+
8
+ // ----------------------------------------------------------------
9
+ // File-local interfaces for raw LearnWorlds API shapes
10
+ // ----------------------------------------------------------------
11
+
12
+ /** Query parameters sent to the certificates endpoint */
13
+ interface LWCertificateQueryParams {
14
+ limit: number;
15
+ sort: string;
16
+ order: string;
17
+ issued_after?: string;
18
+ issued_before?: string;
19
+ [key: string]: string | number | boolean | undefined;
20
+ }
21
+
22
+ /** Raw certificate data from the LearnWorlds API */
23
+ interface LWRawCertificate {
24
+ id?: string;
25
+ certificate_id?: string;
26
+ user_id?: string;
27
+ course_id?: string;
28
+ certificate_number?: string;
29
+ number?: string;
30
+ issued_at?: string;
31
+ created_at?: string;
32
+ expires_at?: string;
33
+ status?: string;
34
+ grade?: number;
35
+ score?: number;
36
+ completion_percentage?: number;
37
+ user?: {
38
+ id?: string;
39
+ email?: string;
40
+ name?: string;
41
+ first_name?: string;
42
+ last_name?: string;
43
+ username?: string;
44
+ };
45
+ course?: {
46
+ id?: string;
47
+ title?: string;
48
+ duration?: number;
49
+ };
50
+ pdf_url?: string;
51
+ download_url?: string;
52
+ image_url?: string;
53
+ public_url?: string;
54
+ certificate_url?: string;
55
+ verification_url?: string;
56
+ verification_code?: string;
57
+ qr_code_url?: string;
58
+ }
59
+
60
+ /** Wrapper response that may contain a data array */
61
+ interface LWCertificatesApiResponse {
62
+ success?: boolean;
63
+ message?: string;
64
+ data?: LWRawCertificate[] | LWCertificatesNestedData | LWRawCertificate;
65
+ }
66
+
67
+ /** Nested data shape when the API wraps certificates inside .data.data */
68
+ interface LWCertificatesNestedData {
69
+ data?: LWRawCertificate[];
70
+ id?: string;
71
+ [key: string]: unknown;
72
+ }
73
+
74
+ /** User lookup response */
75
+ interface LWUserLookup {
76
+ success?: boolean;
77
+ data?: {
78
+ id?: string;
79
+ email?: string;
80
+ first_name?: string;
81
+ last_name?: string;
82
+ username?: string;
83
+ };
84
+ }
85
+
86
+ /** Course lookup response */
87
+ interface LWCourseLookup {
88
+ success?: boolean;
89
+ data?: {
90
+ id?: string;
91
+ title?: string;
92
+ duration?: number;
93
+ };
94
+ }
5
95
 
6
96
  /**
7
97
  * Action to retrieve certificates earned by users in LearnWorlds
8
98
  */
9
99
  @RegisterClass(BaseAction, 'GetCertificatesAction')
10
100
  export class GetCertificatesAction extends LearnWorldsBaseAction {
11
- /**
12
- * Get certificates for a user or course
13
- */
14
- public async InternalRunAction(params: RunActionParams): Promise<ActionResultSimple> {
15
- const { Params, ContextUser } = params;
16
- this.params = Params;
17
-
18
- try {
19
- // Extract and validate parameters
20
- const userId = this.getParamValue(Params, 'UserID');
21
- const courseId = this.getParamValue(Params, 'CourseID');
22
- const dateFrom = this.getParamValue(Params, 'DateFrom');
23
- const dateTo = this.getParamValue(Params, 'DateTo');
24
- const includeDownloadLinks = this.getParamValue(Params, 'IncludeDownloadLinks') !== false;
25
- const sortBy = this.getParamValue(Params, 'SortBy') || 'issued_at';
26
- const sortOrder = this.getParamValue(Params, 'SortOrder') || 'desc';
27
- const maxResults = this.getParamValue(Params, 'MaxResults') || 100;
28
-
29
- // Require either userId or courseId
30
- if (!userId && !courseId) {
31
- return {
32
- Success: false,
33
- ResultCode: 'VALIDATION_ERROR',
34
- Message: 'Either UserID or CourseID is required',
35
- Params
36
- };
37
- }
38
-
39
-
40
- // Build query parameters
41
- const queryParams: any = {
42
- limit: Math.min(maxResults, 100),
43
- sort: sortBy,
44
- order: sortOrder
45
- };
101
+ // ----------------------------------------------------------------
102
+ // Typed public method – can be called directly from code
103
+ // ----------------------------------------------------------------
46
104
 
47
- if (dateFrom) {
48
- queryParams.issued_after = new Date(dateFrom).toISOString();
49
- }
50
- if (dateTo) {
51
- queryParams.issued_before = new Date(dateTo).toISOString();
52
- }
53
-
54
- // Determine endpoint based on parameters
55
- let endpoint = '/certificates';
56
- if (userId && courseId) {
57
- // Get specific certificate for user/course combination
58
- endpoint = `/users/${userId}/courses/${courseId}/certificate`;
59
- } else if (userId) {
60
- // Get all certificates for a user
61
- endpoint = `/users/${userId}/certificates`;
62
- } else if (courseId) {
63
- // Get all certificates issued for a course
64
- endpoint = `/courses/${courseId}/certificates`;
65
- }
66
-
67
- // Build query string
68
- const queryString = Object.keys(queryParams).length > 0
69
- ? '?' + new URLSearchParams(queryParams).toString()
70
- : '';
71
-
72
- // Get certificates
73
- const certificatesResponse = await this.makeLearnWorldsRequest(
74
- endpoint + queryString,
75
- 'GET',
76
- null,
77
- ContextUser
78
- );
79
-
80
- if (!certificatesResponse.success) {
81
- return {
82
- Success: false,
83
- ResultCode: 'API_ERROR',
84
- Message: certificatesResponse.message || 'Failed to retrieve certificates',
85
- Params
86
- };
87
- }
88
-
89
- // Handle single certificate vs array
90
- const rawData = certificatesResponse.data;
91
- const certificatesArray = Array.isArray(rawData)
92
- ? rawData
93
- : (rawData?.data || (rawData?.id ? [rawData] : []));
94
-
95
- const formattedCertificates: any[] = [];
96
-
97
- // Process each certificate
98
- for (const cert of certificatesArray) {
99
- const formattedCert: any = {
100
- id: cert.id || cert.certificate_id,
101
- userId: cert.user_id || userId,
102
- courseId: cert.course_id || courseId,
103
- certificateNumber: cert.certificate_number || cert.number,
104
- issuedAt: cert.issued_at || cert.created_at,
105
- expiresAt: cert.expires_at,
106
- status: cert.status || 'active',
107
- grade: cert.grade,
108
- score: cert.score,
109
- completionPercentage: cert.completion_percentage || 100
110
- };
111
-
112
- // Add user info if available
113
- if (cert.user) {
114
- formattedCert.user = {
115
- id: cert.user.id || cert.user_id,
116
- email: cert.user.email,
117
- name: cert.user.name || `${cert.user.first_name || ''} ${cert.user.last_name || ''}`.trim()
118
- };
119
- } else if (!userId && cert.user_id) {
120
- // Try to get user info
121
- const userResponse = await this.makeLearnWorldsRequest(
122
- `/users/${cert.user_id}`,
123
- 'GET',
124
- null,
125
- ContextUser
126
- );
127
-
128
- if (userResponse.success && userResponse.data) {
129
- const user = userResponse.data;
130
- formattedCert.user = {
131
- id: user.id,
132
- email: user.email,
133
- name: `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username
134
- };
135
- }
136
- }
137
-
138
- // Add course info if available
139
- if (cert.course) {
140
- formattedCert.course = {
141
- id: cert.course.id || cert.course_id,
142
- title: cert.course.title,
143
- duration: cert.course.duration
144
- };
145
- } else if (!courseId && cert.course_id) {
146
- // Try to get course info
147
- const courseResponse = await this.makeLearnWorldsRequest(
148
- `/courses/${cert.course_id}`,
149
- 'GET',
150
- null,
151
- ContextUser
152
- );
153
-
154
- if (courseResponse.success && courseResponse.data) {
155
- const course = courseResponse.data;
156
- formattedCert.course = {
157
- id: course.id,
158
- title: course.title,
159
- duration: course.duration
160
- };
161
- }
162
- }
163
-
164
- // Add download links if requested
165
- if (includeDownloadLinks) {
166
- formattedCert.downloadLinks = {
167
- pdf: cert.pdf_url || cert.download_url,
168
- image: cert.image_url,
169
- publicUrl: cert.public_url || cert.certificate_url
170
- };
171
- }
172
-
173
- // Add verification info
174
- formattedCert.verification = {
175
- url: cert.verification_url,
176
- code: cert.verification_code,
177
- qrCode: cert.qr_code_url
178
- };
179
-
180
- formattedCertificates.push(formattedCert);
181
- }
182
-
183
- // Calculate summary statistics
184
- const totalCertificates = formattedCertificates.length;
185
- const activeCertificates = formattedCertificates.filter(c =>
186
- c.status === 'active' && (!c.expiresAt || new Date(c.expiresAt) > new Date())
187
- ).length;
188
- const expiredCertificates = formattedCertificates.filter(c =>
189
- c.expiresAt && new Date(c.expiresAt) <= new Date()
190
- ).length;
191
-
192
- // Group by course if getting user certificates
193
- const certificatesByCourse: any = {};
194
- if (userId && !courseId) {
195
- formattedCertificates.forEach(cert => {
196
- const courseTitle = cert.course?.title || 'Unknown Course';
197
- if (!certificatesByCourse[courseTitle]) {
198
- certificatesByCourse[courseTitle] = [];
199
- }
200
- certificatesByCourse[courseTitle].push(cert);
201
- });
202
- }
203
-
204
- // Group by user if getting course certificates
205
- const certificatesByUser: any = {};
206
- if (courseId && !userId) {
207
- formattedCertificates.forEach(cert => {
208
- const userName = cert.user?.name || cert.user?.email || 'Unknown User';
209
- if (!certificatesByUser[userName]) {
210
- certificatesByUser[userName] = [];
211
- }
212
- certificatesByUser[userName].push(cert);
213
- });
214
- }
215
-
216
- // Create summary
217
- const summary = {
218
- totalCertificates: totalCertificates,
219
- activeCertificates: activeCertificates,
220
- expiredCertificates: expiredCertificates,
221
- dateRange: {
222
- from: dateFrom || 'all-time',
223
- to: dateTo || 'current'
224
- },
225
- filterType: userId && courseId ? 'user-course' : (userId ? 'user' : 'course'),
226
- groupedData: userId && !courseId ? certificatesByCourse : (courseId && !userId ? certificatesByUser : null)
227
- };
105
+ /**
106
+ * Get certificates for a user or course.
107
+ * Throws on any error.
108
+ */
109
+ public async GetCertificates(params: GetCertificatesParams, contextUser: UserInfo): Promise<GetCertificatesResult> {
110
+ this.SetCompanyContext(params.CompanyID);
111
+
112
+ const {
113
+ UserID: userId,
114
+ CourseID: courseId,
115
+ DateFrom: dateFrom,
116
+ DateTo: dateTo,
117
+ IncludeDownloadLinks: includeDownloadLinksRaw,
118
+ SortBy: sortBy = 'issued_at',
119
+ SortOrder: sortOrder = 'desc',
120
+ MaxResults: maxResults = 100,
121
+ } = params;
122
+
123
+ const includeDownloadLinks = includeDownloadLinksRaw !== false;
124
+
125
+ // Require either userId or courseId
126
+ if (!userId && !courseId) {
127
+ throw new Error('Either UserID or CourseID is required');
128
+ }
129
+
130
+ // Build query parameters
131
+ const queryParams: LWCertificateQueryParams = {
132
+ limit: Math.min(maxResults, LearnWorldsBaseAction.LW_MAX_PAGE_SIZE),
133
+ sort: sortBy,
134
+ order: sortOrder,
135
+ };
136
+
137
+ const parsedFrom = this.safeParseDateToISO(dateFrom);
138
+ if (parsedFrom) {
139
+ queryParams.issued_after = parsedFrom;
140
+ }
141
+ const parsedTo = this.safeParseDateToISO(dateTo);
142
+ if (parsedTo) {
143
+ queryParams.issued_before = parsedTo;
144
+ }
145
+
146
+ // Validate path segments before URL interpolation
147
+ if (userId) this.validatePathSegment(userId, 'UserID');
148
+ if (courseId) this.validatePathSegment(courseId, 'CourseID');
149
+
150
+ // Determine endpoint based on parameters
151
+ const endpoint = this.buildCertificatesEndpoint(userId, courseId);
152
+
153
+ // Build query string
154
+ const queryString = this.buildQueryString(queryParams);
155
+
156
+ // Get certificates
157
+ const certificatesResponse = await this.makeLearnWorldsRequest<LWCertificatesApiResponse>(endpoint + queryString, 'GET', null, contextUser);
158
+
159
+ if (certificatesResponse.success === false) {
160
+ throw new Error(certificatesResponse.message || 'Failed to retrieve certificates');
161
+ }
162
+
163
+ // Handle single certificate vs array
164
+ const certificatesArray = this.extractCertificatesArray(certificatesResponse);
165
+
166
+ // Process each certificate
167
+ const formattedCertificates = await this.processCertificates(certificatesArray, userId, courseId, includeDownloadLinks, contextUser);
168
+
169
+ // Calculate summary
170
+ const summary = this.buildCertificatesSummary(formattedCertificates, userId, courseId, dateFrom, dateTo);
171
+
172
+ return {
173
+ Certificates: formattedCertificates,
174
+ TotalCount: formattedCertificates.length,
175
+ Summary: summary,
176
+ };
177
+ }
178
+
179
+ // ----------------------------------------------------------------
180
+ // Framework wrapper – thin delegation to the public method
181
+ // ----------------------------------------------------------------
182
+
183
+ protected async InternalRunAction(params: RunActionParams): Promise<ActionResultSimple> {
184
+ const { Params, ContextUser } = params;
185
+ this.params = Params;
186
+
187
+ try {
188
+ const typedParams = this.extractCertificatesParams(Params);
189
+ const result = await this.GetCertificates(typedParams, ContextUser);
190
+
191
+ this.setOutputParam(Params, 'Certificates', result.Certificates);
192
+ this.setOutputParam(Params, 'TotalCount', result.TotalCount);
193
+ this.setOutputParam(Params, 'Summary', result.Summary);
194
+
195
+ return this.buildSuccessResult(`Retrieved ${result.TotalCount} certificate(s)`, Params);
196
+ } catch (error) {
197
+ const msg = error instanceof Error ? error.message : 'Unknown error';
198
+ return this.buildErrorResult('ERROR', `Error retrieving certificates: ${msg}`, Params);
199
+ }
200
+ }
201
+
202
+ // ----------------------------------------------------------------
203
+ // Private helpers
204
+ // ----------------------------------------------------------------
205
+
206
+ private extractCertificatesParams(params: ActionParam[]): GetCertificatesParams {
207
+ return {
208
+ CompanyID: this.getRequiredStringParam(params, 'CompanyID'),
209
+ UserID: this.getOptionalStringParam(params, 'UserID'),
210
+ CourseID: this.getOptionalStringParam(params, 'CourseID'),
211
+ DateFrom: this.getOptionalStringParam(params, 'DateFrom'),
212
+ DateTo: this.getOptionalStringParam(params, 'DateTo'),
213
+ IncludeDownloadLinks: this.getOptionalBooleanParam(params, 'IncludeDownloadLinks', true),
214
+ SortBy: this.getOptionalStringParam(params, 'SortBy'),
215
+ SortOrder: (this.getOptionalStringParam(params, 'SortOrder') || 'desc') as 'asc' | 'desc',
216
+ MaxResults: this.getOptionalNumberParam(params, 'MaxResults', LearnWorldsBaseAction.LW_MAX_PAGE_SIZE),
217
+ };
218
+ }
219
+
220
+ private buildCertificatesEndpoint(userId?: string, courseId?: string): string {
221
+ if (userId && courseId) {
222
+ return `/users/${userId}/courses/${courseId}/certificate`;
223
+ } else if (userId) {
224
+ return `/users/${userId}/certificates`;
225
+ } else if (courseId) {
226
+ return `/courses/${courseId}/certificates`;
227
+ }
228
+ return '/certificates';
229
+ }
230
+
231
+ private buildQueryString(queryParams: Record<string, string | number | boolean | undefined>): string {
232
+ const filtered: Record<string, string> = {};
233
+ for (const [key, value] of Object.entries(queryParams)) {
234
+ if (value !== undefined) {
235
+ filtered[key] = String(value);
236
+ }
237
+ }
238
+ const keys = Object.keys(filtered);
239
+ if (keys.length === 0) return '';
240
+ return '?' + new URLSearchParams(filtered).toString();
241
+ }
242
+
243
+ private extractCertificatesArray(response: LWCertificatesApiResponse): LWRawCertificate[] {
244
+ const rawData = response.data;
245
+ if (Array.isArray(rawData)) {
246
+ return rawData;
247
+ }
248
+ if (rawData && typeof rawData === 'object') {
249
+ const nested = rawData as LWCertificatesNestedData;
250
+ if (Array.isArray(nested.data)) {
251
+ return nested.data;
252
+ }
253
+ if (nested.id) {
254
+ return [rawData as LWRawCertificate];
255
+ }
256
+ }
257
+ return [];
258
+ }
259
+
260
+ private async processCertificates(
261
+ certificatesArray: LWRawCertificate[],
262
+ userId: string | undefined,
263
+ courseId: string | undefined,
264
+ includeDownloadLinks: boolean,
265
+ contextUser: UserInfo,
266
+ ): Promise<FormattedCertificate[]> {
267
+ // Pre-fetch all user and course info in batch to avoid per-item API calls
268
+ const userInfoMap = await this.batchResolveUserInfo(certificatesArray, userId, contextUser);
269
+ const courseInfoMap = await this.batchResolveCourseInfo(certificatesArray, courseId, contextUser);
270
+
271
+ return certificatesArray.map((cert) => {
272
+ const formattedCert = this.buildBaseCertificate(cert, userId, courseId);
273
+
274
+ // Attach user info from pre-fetched map
275
+ const certUserId = cert.user_id || '';
276
+ formattedCert.user = cert.user ? this.extractInlineUserInfo(cert) : userInfoMap.get(certUserId);
277
+
278
+ // Attach course info from pre-fetched map
279
+ const certCourseId = cert.course_id || '';
280
+ formattedCert.course = cert.course ? this.extractInlineCourseInfo(cert) : courseInfoMap.get(certCourseId);
281
+
282
+ // Attach download links if requested
283
+ if (includeDownloadLinks) {
284
+ formattedCert.downloadLinks = {
285
+ pdf: cert.pdf_url || cert.download_url,
286
+ image: cert.image_url,
287
+ publicUrl: cert.public_url || cert.certificate_url,
288
+ };
289
+ }
290
+
291
+ // Attach verification info
292
+ formattedCert.verification = {
293
+ url: cert.verification_url,
294
+ code: cert.verification_code,
295
+ qrCode: cert.qr_code_url,
296
+ };
228
297
 
229
- // Update output parameters
230
- const outputParams = [...Params];
231
- const certificatesParam = outputParams.find(p => p.Name === 'Certificates');
232
- if (certificatesParam) {
233
- certificatesParam.Value = formattedCertificates;
234
- }
235
- const totalCountParam = outputParams.find(p => p.Name === 'TotalCount');
236
- if (totalCountParam) {
237
- totalCountParam.Value = totalCertificates;
238
- }
239
- const summaryParam = outputParams.find(p => p.Name === 'Summary');
240
- if (summaryParam) {
241
- summaryParam.Value = summary;
242
- }
298
+ return formattedCert;
299
+ });
300
+ }
243
301
 
302
+ /**
303
+ * Extracts inline user info when the cert already includes user data.
304
+ */
305
+ private extractInlineUserInfo(cert: LWRawCertificate): { id: string; email: string; name: string } | undefined {
306
+ if (!cert.user) return undefined;
307
+ return {
308
+ id: cert.user.id || cert.user_id || '',
309
+ email: cert.user.email || '',
310
+ name: cert.user.name || `${cert.user.first_name || ''} ${cert.user.last_name || ''}`.trim(),
311
+ };
312
+ }
313
+
314
+ /**
315
+ * Extracts inline course info when the cert already includes course data.
316
+ */
317
+ private extractInlineCourseInfo(cert: LWRawCertificate): { id: string; title: string; duration?: number } | undefined {
318
+ if (!cert.course) return undefined;
319
+ return {
320
+ id: cert.course.id || cert.course_id || '',
321
+ title: cert.course.title || '',
322
+ duration: cert.course.duration,
323
+ };
324
+ }
325
+
326
+ /**
327
+ * Batch-fetches user info for all certificates that need external lookup.
328
+ * Returns a map from userId to user info.
329
+ */
330
+ private async batchResolveUserInfo(
331
+ certs: LWRawCertificate[],
332
+ filterUserId: string | undefined,
333
+ contextUser: UserInfo,
334
+ ): Promise<Map<string, { id: string; email: string; name: string }>> {
335
+ const map = new Map<string, { id: string; email: string; name: string }>();
336
+
337
+ // Only need to look up users when cert doesn't include inline user data
338
+ // and we're not filtering by a single user
339
+ if (filterUserId) return map;
340
+
341
+ const idsToFetch = [...new Set(certs.filter((c) => !c.user && c.user_id).map((c) => c.user_id!))];
342
+
343
+ const results = await Promise.all(
344
+ idsToFetch.map(async (uid) => {
345
+ try {
346
+ const resp = await this.makeLearnWorldsRequest<LWUserLookup>(`/users/${uid}`, 'GET', null, contextUser);
347
+ if (resp.success !== false && resp.data) {
244
348
  return {
245
- Success: true,
246
- ResultCode: 'SUCCESS',
247
- Message: `Retrieved ${totalCertificates} certificate(s)`,
248
- Params: outputParams
349
+ id: uid,
350
+ info: {
351
+ id: resp.data.id || '',
352
+ email: resp.data.email || '',
353
+ name: `${resp.data.first_name || ''} ${resp.data.last_name || ''}`.trim() || resp.data.username || '',
354
+ },
249
355
  };
250
-
356
+ }
251
357
  } catch (error) {
252
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
358
+ console.warn(`Failed to fetch user info for ${uid}:`, error instanceof Error ? error.message : error);
359
+ }
360
+ return null;
361
+ }),
362
+ );
363
+
364
+ for (const result of results) {
365
+ if (result) map.set(result.id, result.info);
366
+ }
367
+ return map;
368
+ }
369
+
370
+ /**
371
+ * Batch-fetches course info for all certificates that need external lookup.
372
+ * Returns a map from courseId to course info.
373
+ */
374
+ private async batchResolveCourseInfo(
375
+ certs: LWRawCertificate[],
376
+ filterCourseId: string | undefined,
377
+ contextUser: UserInfo,
378
+ ): Promise<Map<string, { id: string; title: string; duration?: number }>> {
379
+ const map = new Map<string, { id: string; title: string; duration?: number }>();
380
+
381
+ // Only need to look up courses when cert doesn't include inline course data
382
+ // and we're not filtering by a single course
383
+ if (filterCourseId) return map;
384
+
385
+ const idsToFetch = [...new Set(certs.filter((c) => !c.course && c.course_id).map((c) => c.course_id!))];
386
+
387
+ const results = await Promise.all(
388
+ idsToFetch.map(async (cid) => {
389
+ try {
390
+ const resp = await this.makeLearnWorldsRequest<LWCourseLookup>(`/courses/${cid}`, 'GET', null, contextUser);
391
+ if (resp.success !== false && resp.data) {
253
392
  return {
254
- Success: false,
255
- ResultCode: 'EXECUTION_ERROR',
256
- Message: `Error retrieving certificates: ${errorMessage}`,
257
- Params
393
+ id: cid,
394
+ info: {
395
+ id: resp.data.id || '',
396
+ title: resp.data.title || '',
397
+ duration: resp.data.duration,
398
+ },
258
399
  };
400
+ }
401
+ } catch (error) {
402
+ console.warn(`Failed to fetch course info for ${cid}:`, error instanceof Error ? error.message : error);
259
403
  }
404
+ return null;
405
+ }),
406
+ );
407
+
408
+ for (const result of results) {
409
+ if (result) map.set(result.id, result.info);
260
410
  }
411
+ return map;
412
+ }
413
+
414
+ private buildBaseCertificate(cert: LWRawCertificate, userId: string | undefined, courseId: string | undefined): FormattedCertificate {
415
+ return {
416
+ id: cert.id || cert.certificate_id || '',
417
+ userId: cert.user_id || userId || '',
418
+ courseId: cert.course_id || courseId || '',
419
+ certificateNumber: cert.certificate_number || cert.number,
420
+ issuedAt: cert.issued_at || cert.created_at,
421
+ expiresAt: cert.expires_at,
422
+ status: cert.status || 'active',
423
+ grade: cert.grade,
424
+ score: cert.score,
425
+ completionPercentage: cert.completion_percentage || 100,
426
+ verification: { url: undefined, code: undefined, qrCode: undefined },
427
+ };
428
+ }
429
+
430
+ private buildCertificatesSummary(
431
+ certificates: FormattedCertificate[],
432
+ userId: string | undefined,
433
+ courseId: string | undefined,
434
+ dateFrom: string | undefined,
435
+ dateTo: string | undefined,
436
+ ): CertificatesSummary {
437
+ const totalCertificates = certificates.length;
438
+ const now = new Date();
439
+
440
+ const activeCertificates = certificates.filter((c) => c.status === 'active' && (!c.expiresAt || new Date(c.expiresAt) > now)).length;
261
441
 
262
- /**
263
- * Define the parameters this action expects
264
- */
265
- public get Params(): ActionParam[] {
266
- const baseParams = this.getCommonLMSParams();
267
- const specificParams: ActionParam[] = [
268
- {
269
- Name: 'UserID',
270
- Type: 'Input',
271
- Value: null
272
- },
273
- {
274
- Name: 'CourseID',
275
- Type: 'Input',
276
- Value: null
277
- },
278
- {
279
- Name: 'DateFrom',
280
- Type: 'Input',
281
- Value: null
282
- },
283
- {
284
- Name: 'DateTo',
285
- Type: 'Input',
286
- Value: null
287
- },
288
- {
289
- Name: 'IncludeDownloadLinks',
290
- Type: 'Input',
291
- Value: true
292
- },
293
- {
294
- Name: 'SortBy',
295
- Type: 'Input',
296
- Value: 'issued_at'
297
- },
298
- {
299
- Name: 'SortOrder',
300
- Type: 'Input',
301
- Value: 'desc'
302
- },
303
- {
304
- Name: 'MaxResults',
305
- Type: 'Input',
306
- Value: 100
307
- },
308
- {
309
- Name: 'Certificates',
310
- Type: 'Output',
311
- Value: null
312
- },
313
- {
314
- Name: 'TotalCount',
315
- Type: 'Output',
316
- Value: null
317
- },
318
- {
319
- Name: 'Summary',
320
- Type: 'Output',
321
- Value: null
322
- }
323
- ];
324
- return [...baseParams, ...specificParams];
442
+ const expiredCertificates = certificates.filter((c) => c.expiresAt && new Date(c.expiresAt) <= now).length;
443
+
444
+ // Group by course or user depending on the filter
445
+ let groupedData: Record<string, FormattedCertificate[]> | null = null;
446
+
447
+ if (userId && !courseId) {
448
+ groupedData = this.groupCertificatesByCourse(certificates);
449
+ } else if (courseId && !userId) {
450
+ groupedData = this.groupCertificatesByUser(certificates);
325
451
  }
326
452
 
327
- /**
328
- * Metadata about this action
329
- */
330
- public get Description(): string {
331
- return 'Retrieves certificates earned by users in LearnWorlds courses with download links and verification info';
453
+ const filterType = userId && courseId ? 'user-course' : userId ? 'user' : 'course';
454
+
455
+ return {
456
+ totalCertificates,
457
+ activeCertificates,
458
+ expiredCertificates,
459
+ dateRange: {
460
+ from: dateFrom || 'all-time',
461
+ to: dateTo || 'current',
462
+ },
463
+ filterType,
464
+ groupedData,
465
+ };
466
+ }
467
+
468
+ private groupCertificatesByCourse(certificates: FormattedCertificate[]): Record<string, FormattedCertificate[]> {
469
+ const grouped: Record<string, FormattedCertificate[]> = {};
470
+ for (const cert of certificates) {
471
+ const courseTitle = cert.course?.title || 'Unknown Course';
472
+ if (!grouped[courseTitle]) {
473
+ grouped[courseTitle] = [];
474
+ }
475
+ grouped[courseTitle].push(cert);
332
476
  }
333
- }
477
+ return grouped;
478
+ }
479
+
480
+ private groupCertificatesByUser(certificates: FormattedCertificate[]): Record<string, FormattedCertificate[]> {
481
+ const grouped: Record<string, FormattedCertificate[]> = {};
482
+ for (const cert of certificates) {
483
+ const userName = cert.user?.name || cert.user?.email || 'Unknown User';
484
+ if (!grouped[userName]) {
485
+ grouped[userName] = [];
486
+ }
487
+ grouped[userName].push(cert);
488
+ }
489
+ return grouped;
490
+ }
491
+
492
+ // ----------------------------------------------------------------
493
+ // Params & Description metadata
494
+ // ----------------------------------------------------------------
495
+
496
+ /**
497
+ * Define the parameters this action expects
498
+ */
499
+ public get Params(): ActionParam[] {
500
+ const baseParams = this.getCommonLMSParams();
501
+ const specificParams: ActionParam[] = [
502
+ { Name: 'UserID', Type: 'Input', Value: null },
503
+ { Name: 'CourseID', Type: 'Input', Value: null },
504
+ { Name: 'DateFrom', Type: 'Input', Value: null },
505
+ { Name: 'DateTo', Type: 'Input', Value: null },
506
+ { Name: 'IncludeDownloadLinks', Type: 'Input', Value: true },
507
+ { Name: 'SortBy', Type: 'Input', Value: 'issued_at' },
508
+ { Name: 'SortOrder', Type: 'Input', Value: 'desc' },
509
+ { Name: 'MaxResults', Type: 'Input', Value: 100 },
510
+ { Name: 'Certificates', Type: 'Output', Value: null },
511
+ { Name: 'TotalCount', Type: 'Output', Value: null },
512
+ { Name: 'Summary', Type: 'Output', Value: null },
513
+ ];
514
+ return [...baseParams, ...specificParams];
515
+ }
516
+
517
+ /**
518
+ * Metadata about this action
519
+ */
520
+ public get Description(): string {
521
+ return 'Retrieves certificates earned by users in LearnWorlds courses with download links and verification info';
522
+ }
523
+ }