@winwinmbs/portal-api 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2144 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ActorType: () => ActorType,
34
+ EmailAPI: () => EmailAPI,
35
+ EventCategory: () => EventCategory,
36
+ EventLogApi: () => EventLogApi,
37
+ EventOutcome: () => EventOutcome,
38
+ EventRiskLevel: () => EventRiskLevel,
39
+ EventSeverity: () => EventSeverity,
40
+ FilesAPI: () => FilesAPI,
41
+ HealthAPI: () => HealthAPI,
42
+ LineAPI: () => LineAPI,
43
+ OrganizationAPI: () => OrganizationAPI,
44
+ OrganizationType: () => OrganizationType,
45
+ OtpAPI: () => OtpAPI,
46
+ PermissionAPI: () => PermissionAPI,
47
+ PermissionCategoryAPI: () => PermissionCategoryAPI,
48
+ PortalApiClient: () => PortalApiClient,
49
+ RoleAPI: () => RoleAPI,
50
+ SystemConfigAPI: () => SystemConfigAPI,
51
+ TodoAPI: () => TodoAPI,
52
+ TodoPriority: () => TodoPriority,
53
+ UserAPI: () => UserAPI,
54
+ WebhookAPI: () => WebhookAPI,
55
+ WorkflowAPI: () => WorkflowAPI
56
+ });
57
+ module.exports = __toCommonJS(index_exports);
58
+
59
+ // src/portal-api-client.ts
60
+ var import_axios = __toESM(require("axios"));
61
+
62
+ // src/api/health.api.ts
63
+ var HealthAPI = class {
64
+ constructor(axios2) {
65
+ this.axios = axios2;
66
+ }
67
+ /**
68
+ * Check API health
69
+ */
70
+ async check() {
71
+ const response = await this.axios.get("/health");
72
+ return response.data;
73
+ }
74
+ /**
75
+ * Validate if API key is still active
76
+ */
77
+ async validateApiKey() {
78
+ try {
79
+ await this.check();
80
+ return true;
81
+ } catch (error) {
82
+ return false;
83
+ }
84
+ }
85
+ };
86
+
87
+ // src/utils/logger.ts
88
+ var Logger = class {
89
+ constructor() {
90
+ this.config = {
91
+ enabled: true,
92
+ logLevel: typeof process !== "undefined" && process.env?.NODE_ENV === "production" ? "warn" : "debug"
93
+ };
94
+ }
95
+ shouldLog(level) {
96
+ if (!this.config.enabled) return false;
97
+ const levels = ["debug", "info", "warn", "error"];
98
+ const currentLevelIndex = levels.indexOf(this.config.logLevel);
99
+ const messageLevelIndex = levels.indexOf(level);
100
+ return messageLevelIndex >= currentLevelIndex;
101
+ }
102
+ debug(...args) {
103
+ if (this.shouldLog("debug")) {
104
+ console.log("[AuthClient]", ...args);
105
+ }
106
+ }
107
+ info(...args) {
108
+ if (this.shouldLog("info")) {
109
+ console.log("[AuthClient]", ...args);
110
+ }
111
+ }
112
+ warn(...args) {
113
+ if (this.shouldLog("warn")) {
114
+ console.warn("[AuthClient]", ...args);
115
+ }
116
+ }
117
+ error(...args) {
118
+ if (this.shouldLog("error")) {
119
+ console.error("[AuthClient]", ...args);
120
+ }
121
+ }
122
+ /**
123
+ * อัพเดท logging config
124
+ *
125
+ * @param config - Partial config เพื่อ merge กับ config ปัจจุบัน
126
+ */
127
+ setConfig(config) {
128
+ this.config = { ...this.config, ...config };
129
+ }
130
+ /**
131
+ * ตรวจสอบว่า logging เปิดอยู่หรือไม่
132
+ */
133
+ isEnabled() {
134
+ return this.config.enabled;
135
+ }
136
+ /**
137
+ * ดู log level ปัจจุบัน
138
+ */
139
+ getLogLevel() {
140
+ return this.config.logLevel;
141
+ }
142
+ };
143
+ var logger = new Logger();
144
+
145
+ // src/api/system-config.api.ts
146
+ var SystemConfigAPI = class {
147
+ constructor(axios2) {
148
+ this.axios = axios2;
149
+ }
150
+ /**
151
+ * GET /system-configs/categories/:category
152
+ * ดึง configs ตาม category - ส่ง object ที่รวมทุก key เป็น { key1: value1, key2: value2 }
153
+ */
154
+ async getByCategory(category) {
155
+ const response = await this.axios.get(
156
+ `/system-configs/categories/${category}`
157
+ );
158
+ logger.debug("SystemConfigAPI getByCategory response:", response.data.data);
159
+ return response.data.data;
160
+ }
161
+ /**
162
+ * GET /system-configs/categories/:category/:key
163
+ * ดึง config value ตรงๆ (API returns config.value directly, NOT the full SystemConfig row)
164
+ */
165
+ async getByCategoryAndKey(category, key) {
166
+ const response = await this.axios.get(`/system-configs/categories/${category}/${key}`);
167
+ logger.debug("SystemConfigAPI getByCategoryAndKey response:", response.data.data);
168
+ return response.data.data;
169
+ }
170
+ async get(category, key) {
171
+ if (key) {
172
+ return await this.getByCategoryAndKey(category, key);
173
+ }
174
+ return await this.getByCategory(category);
175
+ }
176
+ /**
177
+ * GET /system-configs/categories/security/session_management
178
+ * ดึง Session Management configuration (convenience method)
179
+ */
180
+ async getSessionManagement() {
181
+ return this.get("security", "session_management");
182
+ }
183
+ /**
184
+ * GET /system-configs/categories/security/jwt
185
+ * ดึง Security JWT configuration (convenience method)
186
+ */
187
+ async getSecurityJwt() {
188
+ return this.get("security", "jwt");
189
+ }
190
+ };
191
+
192
+ // src/api/files.api.ts
193
+ var FilesAPI = class {
194
+ constructor(axios2) {
195
+ this.axios = axios2;
196
+ }
197
+ /**
198
+ * POST /files - อัปโหลดไฟล์ใหม่
199
+ * Supports both authenticated and anonymous uploads
200
+ */
201
+ async upload(formData) {
202
+ const response = await this.axios.post("/files", formData, {
203
+ headers: {
204
+ "Content-Type": "multipart/form-data"
205
+ }
206
+ });
207
+ return response.data.data;
208
+ }
209
+ /**
210
+ * GET /files/:id - ดูข้อมูลไฟล์
211
+ * Public access (supports both authenticated and anonymous)
212
+ */
213
+ async getById(id) {
214
+ const response = await this.axios.get(`/files/${id}`);
215
+ return response.data.data;
216
+ }
217
+ /**
218
+ * GET /files/:id/content - ดึง file content (รูปภาพ, เอกสาร)
219
+ * Returns the actual file content or redirects to cloud storage URL
220
+ * Public access based on file.is_public flag
221
+ */
222
+ getContentUrl(id) {
223
+ const baseURL = this.axios.defaults.baseURL || "";
224
+ return `${baseURL}/files/${id}/content`;
225
+ }
226
+ /**
227
+ * PUT /files/:id - อัปเดตข้อมูลไฟล์
228
+ * Requires authentication
229
+ */
230
+ async update(id, updateData) {
231
+ const response = await this.axios.put(`/files/${id}`, updateData);
232
+ return response.data.data;
233
+ }
234
+ /**
235
+ * DELETE /files/:id - ลบไฟล์
236
+ * Requires authentication
237
+ */
238
+ async delete(id) {
239
+ const response = await this.axios.delete(`/files/${id}`);
240
+ return response.data.data;
241
+ }
242
+ /**
243
+ * POST /files/search - ค้นหาไฟล์แบบ advanced
244
+ * Public access (supports both authenticated and anonymous)
245
+ */
246
+ async search(searchParams) {
247
+ const response = await this.axios.post("/files/search", searchParams || {});
248
+ return response.data.data;
249
+ }
250
+ /**
251
+ * DELETE /files/bulk - ลบไฟล์หลายไฟล์
252
+ * Requires authentication
253
+ */
254
+ async bulkDelete(ids) {
255
+ const response = await this.axios.delete("/files/bulk", {
256
+ data: { ids }
257
+ });
258
+ return response.data.data;
259
+ }
260
+ };
261
+
262
+ // src/api/event-log.api.ts
263
+ var EventLogApi = class {
264
+ constructor(axios2) {
265
+ this.axios = axios2;
266
+ }
267
+ /**
268
+ * Log event to centralized event log system
269
+ */
270
+ async logEvent(eventData) {
271
+ const response = await this.axios.post("/event-logs", eventData);
272
+ return response.data.data;
273
+ }
274
+ /**
275
+ * Batch log multiple events (for performance)
276
+ */
277
+ async logEvents(events) {
278
+ const response = await this.axios.post("/event-logs/batch", {
279
+ events
280
+ });
281
+ return response.data.data;
282
+ }
283
+ };
284
+
285
+ // src/api/line.api.ts
286
+ var LineAPI = class {
287
+ constructor(axios2) {
288
+ this.axios = axios2;
289
+ }
290
+ /**
291
+ * ส่งข้อความ text ไปยัง user
292
+ *
293
+ * @example
294
+ * ```typescript
295
+ * const result = await authClient.line.sendTextMessage({
296
+ * userId: 'user-123',
297
+ * message: 'สวัสดีครับ! ยินดีต้อนรับ'
298
+ * });
299
+ * ```
300
+ */
301
+ async sendTextMessage(request) {
302
+ const response = await this.axios.post("/line/send-text", request);
303
+ return response.data;
304
+ }
305
+ /**
306
+ * ส่ง sticker ไปยัง user
307
+ *
308
+ * @example
309
+ * ```typescript
310
+ * const result = await authClient.line.sendSticker({
311
+ * userId: 'user-123',
312
+ * packageId: '11537',
313
+ * stickerId: '52002734'
314
+ * });
315
+ * ```
316
+ */
317
+ async sendSticker(request) {
318
+ const response = await this.axios.post("/line/send-sticker", request);
319
+ return response.data;
320
+ }
321
+ /**
322
+ * ส่งรูปภาพไปยัง user
323
+ *
324
+ * @example
325
+ * ```typescript
326
+ * const result = await authClient.line.sendImage({
327
+ * userId: 'user-123',
328
+ * originalContentUrl: 'https://example.com/image.jpg',
329
+ * previewImageUrl: 'https://example.com/preview.jpg'
330
+ * });
331
+ * ```
332
+ */
333
+ async sendImage(request) {
334
+ const response = await this.axios.post("/line/send-image", request);
335
+ return response.data;
336
+ }
337
+ /**
338
+ * ส่งหลายข้อความพร้อมกัน (สูงสุด 5 ข้อความ)
339
+ *
340
+ * @example
341
+ * ```typescript
342
+ * const result = await authClient.line.sendMessages({
343
+ * userId: 'user-123',
344
+ * messages: [
345
+ * { type: 'text', text: 'ข้อความแรก' },
346
+ * { type: 'sticker', packageId: '11537', stickerId: '52002734' },
347
+ * { type: 'text', text: 'ข้อความสุดท้าย' }
348
+ * ]
349
+ * });
350
+ * ```
351
+ */
352
+ async sendMessages(request) {
353
+ const response = await this.axios.post("/line/send-messages", request);
354
+ return response.data;
355
+ }
356
+ /**
357
+ * ส่ง notification แบบ high-level (มี title, icon และ action URL)
358
+ *
359
+ * @example
360
+ * ```typescript
361
+ * const result = await authClient.line.sendNotification({
362
+ * userId: 'user-123',
363
+ * title: 'งานใหม่ได้รับมอบหมาย',
364
+ * message: 'คุณได้รับมอบหมายงาน: ทำรายงานประจำเดือน',
365
+ * type: 'info',
366
+ * action_url: 'https://app.example.com/tasks/123',
367
+ * priority: 'high'
368
+ * });
369
+ * ```
370
+ */
371
+ async sendNotification(request) {
372
+ const response = await this.axios.post("/line/send-notification", request);
373
+ return response.data;
374
+ }
375
+ /**
376
+ * ตรวจสอบว่า user สามารถรับข้อความ LINE ได้หรือไม่
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * const result = await authClient.line.checkMessagingAvailability('user-123');
381
+ * if (result.data?.canReceiveMessages) {
382
+ * console.log('User can receive LINE messages');
383
+ * }
384
+ * ```
385
+ */
386
+ async checkMessagingAvailability(userId) {
387
+ const response = await this.axios.get(`/line/messaging-availability/${userId}`);
388
+ return response.data;
389
+ }
390
+ };
391
+
392
+ // src/api/todo.api.ts
393
+ var TodoAPI = class {
394
+ constructor(axios2) {
395
+ this.axios = axios2;
396
+ }
397
+ /**
398
+ * Create a new todo
399
+ *
400
+ * @example
401
+ * ```typescript
402
+ * const todo = await authClient.todo.create({
403
+ * title: "ซื้อของใช้ในบ้าน",
404
+ * priority: TodoPriority.NORMAL,
405
+ * user_id: "user123e4567-e89b-12d3-a456-426614174000",
406
+ * description: "ซื้อน้ำยาล้างจาน, กระดาษทิชชู่, แชมพู",
407
+ * due_date: new Date("2024-01-20T17:00:00Z"),
408
+ * category: "shopping",
409
+ * labels: ["บ้าน", "จำเป็น"],
410
+ * is_send_notification: true
411
+ * });
412
+ * ```
413
+ */
414
+ async create(todoData) {
415
+ const response = await this.axios.post("/todos", todoData);
416
+ return response.data.data;
417
+ }
418
+ };
419
+
420
+ // src/api/user.api.ts
421
+ var UserAPI = class {
422
+ constructor(axios2) {
423
+ this.axios = axios2;
424
+ }
425
+ /**
426
+ * Search users with pagination and filters
427
+ *
428
+ * @example
429
+ * ```typescript
430
+ * const result = await authClient.user.search({
431
+ * search: "สมชาย",
432
+ * page: 1,
433
+ * limit: 20,
434
+ * sort_by: "created_at",
435
+ * sort_order: "desc",
436
+ * advanced: {
437
+ * status: "active",
438
+ * department_id: "dept-123"
439
+ * }
440
+ * });
441
+ *
442
+ * // Access paginated data
443
+ * console.log(result.data); // User[]
444
+ * console.log(result.pagination.total); // Total count
445
+ * console.log(result.pagination.has_next); // Has next page
446
+ * ```
447
+ */
448
+ async search(params) {
449
+ const response = await this.axios.post("/users/search", params || {});
450
+ return response.data;
451
+ }
452
+ /**
453
+ * Get user by ID
454
+ *
455
+ * @example
456
+ * ```typescript
457
+ * const user = await authClient.user.get("user-123");
458
+ * ```
459
+ */
460
+ async get(userId) {
461
+ const response = await this.axios.get(`/users/${userId}`);
462
+ return response.data.data;
463
+ }
464
+ /**
465
+ * Create a new user
466
+ *
467
+ * @description ถ้าไม่ระบุ password ระบบจะ auto generate และส่ง reset password link ไปทางอีเมล
468
+ * ถ้าระบุ password ระบบจะใช้ password ที่ส่งมาและส่ง welcome email พร้อม login link
469
+ *
470
+ * @example
471
+ * ```typescript
472
+ * // กรณีที่มี password - ระบบจะส่ง welcome email พร้อม login link
473
+ * const newUser = await authClient.user.create({
474
+ * email: "user@example.com",
475
+ * first_name: "สมชาย",
476
+ * last_name: "ใจดี",
477
+ * password: "SecurePassword123!",
478
+ * code: "USR-2024-001",
479
+ * role_ids: ["role-123", "role-456"] // Optional: assign roles immediately
480
+ * });
481
+ * ```
482
+ *
483
+ * @example
484
+ * ```typescript
485
+ * // กรณีที่ไม่มี password - ระบบจะ auto generate และส่ง welcome email พร้อม reset password link
486
+ * const newUser = await authClient.user.create({
487
+ * email: "user@example.com",
488
+ * first_name: "สมชาย",
489
+ * last_name: "ใจดี",
490
+ * code: "USR-2024-002"
491
+ * });
492
+ * ```
493
+ */
494
+ async create(userData) {
495
+ const response = await this.axios.post("/users", userData);
496
+ return response.data.data;
497
+ }
498
+ /**
499
+ * Update user
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * const updatedUser = await authClient.user.update("user-123", {
504
+ * first_name: "สมชาย",
505
+ * last_name: "ใจดีมาก",
506
+ * phone_number: "+66812345678",
507
+ * role_ids: ["role-123", "role-456"] // Optional: replace all roles
508
+ * });
509
+ * ```
510
+ */
511
+ async update(userId, userData) {
512
+ const response = await this.axios.put(`/users/${userId}`, userData);
513
+ return response.data.data;
514
+ }
515
+ /**
516
+ * Delete user
517
+ *
518
+ * @example
519
+ * ```typescript
520
+ * await authClient.user.delete("user-123");
521
+ * ```
522
+ */
523
+ async delete(userId) {
524
+ await this.axios.delete(`/users/${userId}`);
525
+ }
526
+ // ==========================================================================
527
+ // Position Assignment
528
+ // ==========================================================================
529
+ /**
530
+ * Get user positions
531
+ *
532
+ * @description ดึงรายการตำแหน่งทั้งหมดของผู้ใช้
533
+ *
534
+ * @example
535
+ * ```typescript
536
+ * const positions = await authClient.user.getPositions("user-123");
537
+ * const primaryPosition = positions.find(p => p.is_primary);
538
+ * ```
539
+ */
540
+ async getPositions(userId) {
541
+ const response = await this.axios.get(`/users/${userId}/positions`);
542
+ return response.data.data || [];
543
+ }
544
+ /**
545
+ * Assign positions to user
546
+ *
547
+ * @description มอบหมายตำแหน่งให้ผู้ใช้ รองรับการมอบหมายหลายตำแหน่งพร้อมกัน
548
+ *
549
+ * @example
550
+ * ```typescript
551
+ * // Replace mode (default) - ทับตำแหน่งเดิมทั้งหมด
552
+ * const result = await authClient.user.assignPositions("user-123", {
553
+ * positions: [
554
+ * { position_id: "pos-001", is_primary: true },
555
+ * { position_id: "pos-002", is_primary: false }
556
+ * ],
557
+ * mode: "replace"
558
+ * });
559
+ *
560
+ * // Add mode - เพิ่มตำแหน่งใหม่โดยไม่ลบของเดิม
561
+ * const result = await authClient.user.assignPositions("user-123", {
562
+ * positions: [
563
+ * { position_id: "pos-003", is_primary: false }
564
+ * ],
565
+ * mode: "add"
566
+ * });
567
+ * ```
568
+ */
569
+ async assignPositions(userId, data) {
570
+ const response = await this.axios.post(`/users/${userId}/positions`, data);
571
+ return response.data.data;
572
+ }
573
+ /**
574
+ * Unassign positions from user
575
+ *
576
+ * @description ยกเลิกตำแหน่งจากผู้ใช้
577
+ *
578
+ * @example
579
+ * ```typescript
580
+ * const result = await authClient.user.unassignPositions("user-123", ["pos-001", "pos-002"]);
581
+ * ```
582
+ */
583
+ async unassignPositions(userId, positionIds) {
584
+ const response = await this.axios.delete(`/users/${userId}/positions`, {
585
+ data: { ids: positionIds }
586
+ });
587
+ return response.data.data;
588
+ }
589
+ // ==========================================================================
590
+ // Role Assignment
591
+ // ==========================================================================
592
+ /**
593
+ * Get user roles
594
+ *
595
+ * @description ดึงรายการบทบาททั้งหมดของผู้ใช้
596
+ *
597
+ * @example
598
+ * ```typescript
599
+ * const roles = await authClient.user.getRoles("user-123");
600
+ * console.log(roles.map(r => r.name)); // ["Admin", "Manager"]
601
+ * ```
602
+ */
603
+ async getRoles(userId) {
604
+ const response = await this.axios.get(`/users/${userId}/roles`);
605
+ return response.data.data || [];
606
+ }
607
+ /**
608
+ * Assign roles to user
609
+ *
610
+ * @description มอบหมายบทบาทให้ผู้ใช้ (แทนที่บทบาทเดิมทั้งหมด)
611
+ *
612
+ * @example
613
+ * ```typescript
614
+ * const result = await authClient.user.assignRoles("user-123", ["role-001", "role-002"]);
615
+ * ```
616
+ */
617
+ async assignRoles(userId, roleIds) {
618
+ const response = await this.axios.post(`/users/${userId}/roles`, {
619
+ ids: roleIds
620
+ });
621
+ return response.data.data;
622
+ }
623
+ /**
624
+ * Unassign roles from user
625
+ *
626
+ * @description ยกเลิกบทบาทจากผู้ใช้
627
+ *
628
+ * @example
629
+ * ```typescript
630
+ * const result = await authClient.user.unassignRoles("user-123", ["role-001"]);
631
+ * ```
632
+ */
633
+ async unassignRoles(userId, roleIds) {
634
+ const response = await this.axios.delete(`/users/${userId}/roles`, {
635
+ data: { ids: roleIds }
636
+ });
637
+ return response.data.data;
638
+ }
639
+ // ==========================================================================
640
+ // Sync Operations
641
+ // ==========================================================================
642
+ /**
643
+ * Sync users for external applications
644
+ *
645
+ * @description ดึงข้อมูลผู้ใช้แบบ paginated สำหรับ sync operations
646
+ * ใช้สำหรับ external applications ที่ต้องการ sync user data
647
+ * ต้องใช้ API Key authentication
648
+ *
649
+ * @example
650
+ * ```typescript
651
+ * // Sync all users (first page)
652
+ * const result = await authClient.user.sync({
653
+ * page: 1,
654
+ * page_size: 100
655
+ * });
656
+ *
657
+ * // Sync users updated after specific date
658
+ * const updatedUsers = await authClient.user.sync({
659
+ * page: 1,
660
+ * page_size: 100,
661
+ * updated_after: new Date('2024-01-01')
662
+ * });
663
+ *
664
+ * // Access paginated data
665
+ * console.log(result.data); // UserSyncResponse[]
666
+ * console.log(result.pagination.total); // Total count
667
+ * console.log(result.pagination.has_next); // Has next page
668
+ * ```
669
+ */
670
+ async sync(params) {
671
+ const queryParams = {};
672
+ if (params?.page !== void 0) {
673
+ queryParams.page = params.page.toString();
674
+ }
675
+ if (params?.page_size !== void 0) {
676
+ queryParams.page_size = params.page_size.toString();
677
+ }
678
+ if (params?.updated_after) {
679
+ const updatedAfter = params.updated_after instanceof Date ? params.updated_after.toISOString() : params.updated_after;
680
+ queryParams.updated_after = updatedAfter;
681
+ }
682
+ const queryString = new URLSearchParams(queryParams).toString();
683
+ const url = `/users/sync${queryString ? `?${queryString}` : ""}`;
684
+ const response = await this.axios.get(url);
685
+ return response.data;
686
+ }
687
+ };
688
+
689
+ // src/api/otp.api.ts
690
+ var OtpAPI = class {
691
+ constructor(axios2) {
692
+ this.axios = axios2;
693
+ }
694
+ /**
695
+ * Send OTP to recipient (SMS or Email)
696
+ *
697
+ * @example
698
+ * ```typescript
699
+ * // Send SMS OTP
700
+ * const result = await authClient.otp.sendOTP({
701
+ * method: 'sms',
702
+ * recipient: '0812345678',
703
+ * context: 'login'
704
+ * });
705
+ *
706
+ * console.log('OTP ID:', result.otp_id); // UUID
707
+ * console.log('Ref Code:', result.ref_code); // OTP-XXXXXX (for tracking)
708
+ * console.log('Expires at:', result.expires_at);
709
+ *
710
+ * // Send Email OTP
711
+ * const result = await authClient.otp.sendOTP({
712
+ * method: 'email',
713
+ * recipient: 'user@example.com',
714
+ * context: 'verification'
715
+ * });
716
+ * ```
717
+ */
718
+ async sendOTP(request) {
719
+ const response = await this.axios.post("/otp/send", request);
720
+ return response.data.data;
721
+ }
722
+ /**
723
+ * Verify OTP code
724
+ *
725
+ * @example
726
+ * ```typescript
727
+ * const result = await authClient.otp.verifyOTP({
728
+ * otp_id: '123e4567-e89b-12d3-a456-426614174000',
729
+ * code: '123456'
730
+ * });
731
+ *
732
+ * if (result.verified) {
733
+ * console.log('OTP verified successfully');
734
+ * }
735
+ * ```
736
+ */
737
+ async verifyOTP(request) {
738
+ const response = await this.axios.post("/otp/verify", request);
739
+ return response.data.data;
740
+ }
741
+ };
742
+
743
+ // src/api/email.api.ts
744
+ var EmailAPI = class {
745
+ constructor(axios2) {
746
+ this.axios = axios2;
747
+ }
748
+ /**
749
+ * Send email (auto-detect Template Mode or Raw HTML Mode)
750
+ *
751
+ * @param request - SendEmailRequest
752
+ * @returns SendEmailResponse
753
+ *
754
+ * @example
755
+ * ```typescript
756
+ * // Template Mode
757
+ * const result = await authClient.email.sendEmail({
758
+ * template_code: 'welcome_email',
759
+ * template_data: { userName: 'John' },
760
+ * recipient_email: 'user@example.com'
761
+ * });
762
+ *
763
+ * // Raw HTML Mode
764
+ * const result = await authClient.email.sendEmail({
765
+ * html_body: '<h1>Hello</h1>',
766
+ * subject: 'Welcome',
767
+ * recipient_email: 'user@example.com'
768
+ * });
769
+ * ```
770
+ */
771
+ async sendEmail(request) {
772
+ const response = await this.axios.post("/send", request);
773
+ return response.data.data;
774
+ }
775
+ /**
776
+ * Send email with template (Template Mode - convenience method)
777
+ *
778
+ * @param templateCode - Template code from database
779
+ * @param templateData - Template data for rendering
780
+ * @param recipient - Email address or user ID
781
+ * @param options - Additional options (cc, bcc, attachments, etc.)
782
+ * @returns SendEmailResponse
783
+ *
784
+ * @example
785
+ * ```typescript
786
+ * const result = await authClient.email.sendEmailWithTemplate(
787
+ * 'welcome_email',
788
+ * {
789
+ * userName: 'สมชาย ใจดี',
790
+ * activationLink: 'https://app.com/activate?token=xxx'
791
+ * },
792
+ * 'user@example.com',
793
+ * {
794
+ * recipient_name: 'สมชาย ใจดี',
795
+ * language: 'th',
796
+ * cc: ['manager@example.com'],
797
+ * attachments: [
798
+ * {
799
+ * filename: 'welcome.pdf',
800
+ * href: 'https://storage.azure.com/container/welcome.pdf' // URL จาก cloud storage
801
+ * }
802
+ * ]
803
+ * }
804
+ * );
805
+ * ```
806
+ */
807
+ async sendEmailWithTemplate(templateCode, templateData, recipient, options) {
808
+ const request = {
809
+ template_code: templateCode,
810
+ template_data: templateData,
811
+ ...options?.language && { language: options.language },
812
+ ...options?.subject && { subject: options.subject },
813
+ ...recipient.includes("@") ? { recipient_email: recipient } : { recipient_id: recipient },
814
+ ...options?.recipient_name && { recipient_name: options.recipient_name },
815
+ ...options?.cc && { cc: options.cc },
816
+ ...options?.bcc && { bcc: options.bcc },
817
+ ...options?.attachments && { attachments: options.attachments },
818
+ ...options?.priority && { priority: options.priority },
819
+ ...options?.scheduled_at && { scheduled_at: options.scheduled_at },
820
+ ...options?.source && { source: options.source },
821
+ ...options?.related_entity_id && { related_entity_id: options.related_entity_id },
822
+ ...options?.related_entity_type && { related_entity_type: options.related_entity_type }
823
+ };
824
+ return this.sendEmail(request);
825
+ }
826
+ /**
827
+ * Send email with raw HTML (Raw HTML Mode - convenience method)
828
+ *
829
+ * @param htmlBody - HTML content
830
+ * @param subject - Email subject
831
+ * @param recipient - Email address or user ID
832
+ * @param options - Additional options (text_body, cc, bcc, attachments, etc.)
833
+ * @returns SendEmailResponse
834
+ *
835
+ * @example
836
+ * ```typescript
837
+ * const result = await authClient.email.sendRawEmail(
838
+ * '<h1>ยินดีต้อนรับ</h1><p>ขอบคุณที่สมัครสมาชิก</p>',
839
+ * 'ยินดีต้อนรับสู่ระบบ',
840
+ * 'user@example.com',
841
+ * {
842
+ * recipient_name: 'สมชาย ใจดี',
843
+ * text_body: 'ยินดีต้อนรับ ขอบคุณที่สมัครสมาชิก',
844
+ * cc: ['manager@example.com'],
845
+ * bcc: ['archive@example.com'],
846
+ * attachments: [
847
+ * {
848
+ * filename: 'document.pdf',
849
+ * href: 'https://api.example.com/files/123e4567-e89b-12d3-a456-426614174000/content' // URL จาก File API
850
+ * }
851
+ * ]
852
+ * }
853
+ * );
854
+ * ```
855
+ */
856
+ async sendRawEmail(htmlBody, subject, recipient, options) {
857
+ const request = {
858
+ html_body: htmlBody,
859
+ subject,
860
+ ...recipient.includes("@") ? { recipient_email: recipient } : { recipient_id: recipient },
861
+ ...options?.recipient_name && { recipient_name: options.recipient_name },
862
+ ...options?.text_body && { text_body: options.text_body },
863
+ ...options?.cc && { cc: options.cc },
864
+ ...options?.bcc && { bcc: options.bcc },
865
+ ...options?.attachments && { attachments: options.attachments },
866
+ ...options?.priority && { priority: options.priority },
867
+ ...options?.scheduled_at && { scheduled_at: options.scheduled_at },
868
+ ...options?.source && { source: options.source },
869
+ ...options?.related_entity_id && { related_entity_id: options.related_entity_id },
870
+ ...options?.related_entity_type && { related_entity_type: options.related_entity_type }
871
+ };
872
+ return this.sendEmail(request);
873
+ }
874
+ };
875
+
876
+ // src/api/workflow.api.ts
877
+ var WorkflowAPI = class {
878
+ constructor(axios2) {
879
+ this.axios = axios2;
880
+ }
881
+ /**
882
+ * Get workflow instance by ID
883
+ *
884
+ * @example
885
+ * ```typescript
886
+ * const instance = await authClient.workflow.getInstance("wf-inst-123");
887
+ * ```
888
+ */
889
+ async getInstance(instanceId) {
890
+ const response = await this.axios.get(`/workflow-instances/${instanceId}`);
891
+ return response.data.data;
892
+ }
893
+ /**
894
+ * Create a new workflow instance
895
+ *
896
+ * @example
897
+ * ```typescript
898
+ * const instance = await authClient.workflow.createInstance({
899
+ * workflow_definition_id: "wf-def-123",
900
+ * document_id: "doc-123",
901
+ * document_type: "purchase_request",
902
+ * document_title: "ขอซื้อคอมพิวเตอร์",
903
+ * priority: "high",
904
+ * position_id: "pos-123",
905
+ * form_data: {
906
+ * amount: 150000,
907
+ * items: ["Laptop", "Monitor"]
908
+ * },
909
+ * user_id: "user-123"
910
+ * });
911
+ * ```
912
+ */
913
+ async createInstance(instanceData) {
914
+ const response = await this.axios.post("/workflow-instances", instanceData);
915
+ return response.data.data;
916
+ }
917
+ /**
918
+ * Update workflow instance
919
+ *
920
+ * @example
921
+ * ```typescript
922
+ * const updatedInstance = await authClient.workflow.updateInstance("wf-inst-123", {
923
+ * document_title: "ขอซื้อคอมพิวเตอร์ (แก้ไข)",
924
+ * priority: "urgent"
925
+ * });
926
+ * ```
927
+ */
928
+ async updateInstance(instanceId, instanceData) {
929
+ const response = await this.axios.put(
930
+ `/workflow-instances/${instanceId}`,
931
+ instanceData
932
+ );
933
+ return response.data.data;
934
+ }
935
+ /**
936
+ * Search workflow instances with pagination and filters
937
+ *
938
+ * @example
939
+ * ```typescript
940
+ * const result = await authClient.workflow.searchInstances({
941
+ * search: "ขอซื้อ",
942
+ * page: 1,
943
+ * limit: 20,
944
+ * sort_by: "created_at",
945
+ * sort_order: "desc",
946
+ * filters: {
947
+ * status: ["running", "pending"],
948
+ * priority: ["high", "urgent"]
949
+ * }
950
+ * });
951
+ *
952
+ * // Access paginated data
953
+ * console.log(result.data); // WorkflowInstance[]
954
+ * console.log(result.pagination.total); // Total count
955
+ * console.log(result.pagination.has_next); // Has next page
956
+ * ```
957
+ */
958
+ async searchInstances(params) {
959
+ const response = await this.axios.post(
960
+ "/workflow-instances/search",
961
+ params || {}
962
+ );
963
+ return response.data;
964
+ }
965
+ /**
966
+ * Get workflow task by ID
967
+ *
968
+ * @example
969
+ * ```typescript
970
+ * const task = await authClient.workflow.getTask("task-123");
971
+ * ```
972
+ */
973
+ async getTask(taskId) {
974
+ const response = await this.axios.get(`/workflow-tasks/${taskId}`);
975
+ return response.data.data;
976
+ }
977
+ /**
978
+ * Get user tasks with pagination and filters
979
+ *
980
+ * @example
981
+ * ```typescript
982
+ * const result = await authClient.workflow.getUserTasks({
983
+ * status: ["assigned", "in_progress"],
984
+ * priority: ["high"],
985
+ * page: 1,
986
+ * limit: 20
987
+ * });
988
+ *
989
+ * // Access paginated data
990
+ * console.log(result.data); // WorkflowTask[]
991
+ * console.log(result.pagination.total); // Total count
992
+ * ```
993
+ */
994
+ async getUserTasks(params) {
995
+ const queryParams = {};
996
+ if (params?.status) {
997
+ queryParams.status = params.status.join(",");
998
+ }
999
+ if (params?.priority) {
1000
+ queryParams.priority = params.priority.join(",");
1001
+ }
1002
+ if (params?.workflow_instance_id) {
1003
+ queryParams.workflow_instance_id = params.workflow_instance_id;
1004
+ }
1005
+ if (params?.assigned_to) {
1006
+ queryParams.assigned_to = params.assigned_to;
1007
+ }
1008
+ if (params?.page !== void 0) {
1009
+ queryParams.page = params.page.toString();
1010
+ }
1011
+ if (params?.limit !== void 0) {
1012
+ queryParams.limit = params.limit.toString();
1013
+ }
1014
+ if (params?.sort_by) {
1015
+ queryParams.sort_by = params.sort_by;
1016
+ }
1017
+ if (params?.sort_order) {
1018
+ queryParams.sort_order = params.sort_order;
1019
+ }
1020
+ const queryString = new URLSearchParams(queryParams).toString();
1021
+ const url = `/workflow-tasks${queryString ? `?${queryString}` : ""}`;
1022
+ const response = await this.axios.get(url);
1023
+ return response.data;
1024
+ }
1025
+ /**
1026
+ * Perform action on workflow task (approve, reject, delegate, escalate, etc.)
1027
+ *
1028
+ * @example
1029
+ * ```typescript
1030
+ * // Approve task
1031
+ * const result = await authClient.workflow.performTaskAction("task-123", {
1032
+ * action_key: "approve",
1033
+ * comments: "อนุมัติตามขั้นตอน"
1034
+ * });
1035
+ *
1036
+ * // Reject task
1037
+ * const result = await authClient.workflow.performTaskAction("task-123", {
1038
+ * action_key: "reject",
1039
+ * comments: "ไม่ผ่านตามเงื่อนไข",
1040
+ * reason: "งบประมาณไม่เพียงพอ"
1041
+ * });
1042
+ *
1043
+ * // Delegate task
1044
+ * const result = await authClient.workflow.performTaskAction("task-123", {
1045
+ * action_key: "delegate",
1046
+ * delegate_to_user_id: "user-456",
1047
+ * comments: "มอบหมายให้ผู้จัดการพิจารณา"
1048
+ * });
1049
+ * ```
1050
+ */
1051
+ async performTaskAction(taskId, actionData) {
1052
+ const response = await this.axios.post(`/workflow-tasks/${taskId}/actions`, actionData);
1053
+ return response.data.data;
1054
+ }
1055
+ /**
1056
+ * Get workflow definition by ID
1057
+ *
1058
+ * @example
1059
+ * ```typescript
1060
+ * const definition = await authClient.workflow.getDefinition("wf-def-123");
1061
+ * ```
1062
+ */
1063
+ async getDefinition(definitionId) {
1064
+ const response = await this.axios.get(`/workflow-definitions/${definitionId}`);
1065
+ return response.data.data;
1066
+ }
1067
+ /**
1068
+ * Search workflow definitions with pagination and filters
1069
+ *
1070
+ * @example
1071
+ * ```typescript
1072
+ * const result = await authClient.workflow.searchDefinitions({
1073
+ * search: "อนุมัติ",
1074
+ * page: 1,
1075
+ * limit: 20,
1076
+ * filters: {
1077
+ * status: ["active"]
1078
+ * }
1079
+ * });
1080
+ *
1081
+ * // Access paginated data
1082
+ * console.log(result.data); // WorkflowDefinition[]
1083
+ * console.log(result.pagination.total); // Total count
1084
+ * ```
1085
+ */
1086
+ async searchDefinitions(params) {
1087
+ const response = await this.axios.post(
1088
+ "/workflow-definitions/search",
1089
+ params || {}
1090
+ );
1091
+ return response.data;
1092
+ }
1093
+ };
1094
+
1095
+ // src/api/organization.api.ts
1096
+ var OrganizationAPI = class {
1097
+ constructor(axios2) {
1098
+ this.axios = axios2;
1099
+ }
1100
+ /**
1101
+ * Search organizations with pagination and filters
1102
+ */
1103
+ async search(params) {
1104
+ const response = await this.axios.post("/organizations/search", params || {});
1105
+ return response.data;
1106
+ }
1107
+ /**
1108
+ * Get organization by ID
1109
+ */
1110
+ async get(id) {
1111
+ const response = await this.axios.get(`/organizations/${id}`);
1112
+ return response.data.data;
1113
+ }
1114
+ /**
1115
+ * Find organization by code
1116
+ *
1117
+ * @description ค้นหาองค์กรด้วย code ที่ unique
1118
+ *
1119
+ * @example
1120
+ * ```typescript
1121
+ * const org = await authClient.organization.findByCode("WIN-CORP");
1122
+ * if (org) {
1123
+ * console.log(org.name); // "บริษัท วิน คอร์ปอเรชั่น จำกัด"
1124
+ * }
1125
+ * ```
1126
+ */
1127
+ async findByCode(code) {
1128
+ const response = await this.axios.get(`/organizations/code/${code}`);
1129
+ return response.data.data || null;
1130
+ }
1131
+ /**
1132
+ * Create a new organization
1133
+ */
1134
+ async create(data) {
1135
+ const response = await this.axios.post("/organizations", data);
1136
+ return response.data.data;
1137
+ }
1138
+ /**
1139
+ * Bulk create organizations (เร็วกว่า loop create ทีละรายการ)
1140
+ *
1141
+ * @description สร้างองค์กรหลายรายการในครั้งเดียว ต้องเรียง parent ก่อน child
1142
+ * หรือระบุ id ให้ parent เพื่อให้ child อ้างอิง parent_id ได้
1143
+ *
1144
+ * @example
1145
+ * ```typescript
1146
+ * const result = await authClient.organization.bulkCreate({
1147
+ * organizations: [
1148
+ * { name: "Group A", code: "GRP-A", type: "group", id: "uuid-1" },
1149
+ * { name: "Company 1", code: "CO-1", type: "company", parent_id: "uuid-1", id: "uuid-2" },
1150
+ * { name: "Dept IT", code: "IT", type: "department", parent_id: "uuid-2" },
1151
+ * ],
1152
+ * });
1153
+ * console.log(result.created); // 3
1154
+ * ```
1155
+ */
1156
+ async bulkCreate(data) {
1157
+ const response = await this.axios.post(
1158
+ "/organizations/bulk-create",
1159
+ data
1160
+ );
1161
+ return response.data.data;
1162
+ }
1163
+ /**
1164
+ * Update organization
1165
+ */
1166
+ async update(id, data) {
1167
+ const response = await this.axios.put(`/organizations/${id}`, data);
1168
+ return response.data.data;
1169
+ }
1170
+ /**
1171
+ * Delete organization
1172
+ */
1173
+ async delete(id) {
1174
+ const response = await this.axios.delete(`/organizations/${id}`);
1175
+ return !!response.data.success;
1176
+ }
1177
+ /**
1178
+ * Get organization users
1179
+ * @param includeDescendants If true, returns users from all descendant organizations recursively
1180
+ */
1181
+ async getUsers(id, includeDescendants = false) {
1182
+ const params = includeDescendants ? { includeDescendants: "true" } : {};
1183
+ const response = await this.axios.get(`/organizations/${id}/users`, { params });
1184
+ return response.data.data || [];
1185
+ }
1186
+ /**
1187
+ * Get ancestors (parent organizations at all levels)
1188
+ */
1189
+ async getAncestors(id, includeRoot = true) {
1190
+ const params = { includeRoot: String(includeRoot) };
1191
+ const response = await this.axios.get(`/organizations/${id}/ancestors`, { params });
1192
+ return response.data.data || [];
1193
+ }
1194
+ /**
1195
+ * Get immediate supervisor/parent organization
1196
+ */
1197
+ async getDirectSupervisor(id) {
1198
+ const response = await this.axios.get(`/organizations/${id}/supervisor`);
1199
+ return response.data.data || null;
1200
+ }
1201
+ /**
1202
+ * Get full path from root to organization
1203
+ */
1204
+ async getPath(id) {
1205
+ const response = await this.axios.get(`/organizations/${id}/path`);
1206
+ return response.data.data || [];
1207
+ }
1208
+ /**
1209
+ * Get reporting line (hierarchical and functional)
1210
+ */
1211
+ async getReportingLine(id) {
1212
+ const response = await this.axios.get(`/organizations/${id}/reporting-line`);
1213
+ return response.data.data;
1214
+ }
1215
+ /**
1216
+ * Get sibling organizations (same parent)
1217
+ */
1218
+ async getSiblings(id, includeSelf = false) {
1219
+ const params = { includeSelf: String(includeSelf) };
1220
+ const response = await this.axios.get(`/organizations/${id}/siblings`, { params });
1221
+ return response.data.data || [];
1222
+ }
1223
+ /**
1224
+ * Get organization level
1225
+ */
1226
+ async getLevel(id) {
1227
+ const response = await this.axios.get(`/organizations/${id}/level`);
1228
+ return response.data.data;
1229
+ }
1230
+ /**
1231
+ * Get lowest common ancestor of two organizations
1232
+ */
1233
+ async getCommonAncestor(orgA, orgB) {
1234
+ const params = { orgA, orgB };
1235
+ const response = await this.axios.get("/organizations/common-ancestor", {
1236
+ params
1237
+ });
1238
+ return response.data.data || null;
1239
+ }
1240
+ /**
1241
+ * Check if an organization is an ancestor of another
1242
+ */
1243
+ async isAncestorOf(ancestorId, descendantId) {
1244
+ const params = { ancestorId, descendantId };
1245
+ const response = await this.axios.get("/organizations/check-ancestor", { params });
1246
+ return !!response.data.data;
1247
+ }
1248
+ // ==========================================================================
1249
+ // Hierarchy Tree
1250
+ // ==========================================================================
1251
+ /**
1252
+ * Get organization hierarchy
1253
+ *
1254
+ * @description ดึง hierarchy tree ขององค์กรทั้งหมด หรือเริ่มจาก root ที่ระบุ
1255
+ *
1256
+ * @param rootId - Optional root organization ID. ถ้าไม่ระบุจะดึง hierarchy ทั้งหมด
1257
+ *
1258
+ * @example
1259
+ * ```typescript
1260
+ * // ดึง hierarchy ทั้งหมด
1261
+ * const hierarchy = await authClient.organization.getHierarchy();
1262
+ *
1263
+ * // ดึง hierarchy จาก root ที่ระบุ
1264
+ * const hierarchy = await authClient.organization.getHierarchy("org-root-123");
1265
+ * ```
1266
+ */
1267
+ async getHierarchy(rootId) {
1268
+ const params = rootId ? { rootId } : {};
1269
+ const response = await this.axios.get("/organizations/hierarchy", { params });
1270
+ return response.data.data || [];
1271
+ }
1272
+ /**
1273
+ * Get organization tree (with departments and positions)
1274
+ *
1275
+ * @description ดึงโครงสร้าง tree ขององค์กร รวม departments, positions และ user assignments
1276
+ *
1277
+ * @example
1278
+ * ```typescript
1279
+ * const tree = await authClient.organization.getTree("org-123");
1280
+ * console.log(tree.children); // departments & positions
1281
+ * console.log(tree.total_users); // จำนวนผู้ใช้ทั้งหมด
1282
+ * ```
1283
+ */
1284
+ async getTree(id) {
1285
+ const response = await this.axios.get(`/organizations/${id}/tree`);
1286
+ return response.data.data;
1287
+ }
1288
+ /**
1289
+ * Get direct children of organization
1290
+ *
1291
+ * @description ดึงองค์กรลูกตรง (direct children) ขององค์กรที่ระบุ
1292
+ *
1293
+ * @example
1294
+ * ```typescript
1295
+ * const children = await authClient.organization.getChildren("org-123");
1296
+ * ```
1297
+ */
1298
+ async getChildren(id) {
1299
+ const response = await this.axios.get(`/organizations/${id}/children`);
1300
+ return response.data.data || [];
1301
+ }
1302
+ /**
1303
+ * Get sub-organizations
1304
+ *
1305
+ * @description ดึง sub-organizations ขององค์กรที่ระบุ
1306
+ *
1307
+ * @example
1308
+ * ```typescript
1309
+ * const subOrgs = await authClient.organization.getSubOrganizations("org-123");
1310
+ * ```
1311
+ */
1312
+ async getSubOrganizations(id) {
1313
+ const response = await this.axios.get(`/organizations/${id}/sub-organizations`);
1314
+ return response.data.data || [];
1315
+ }
1316
+ /**
1317
+ * Get positions under organization
1318
+ *
1319
+ * @description ดึงรายการตำแหน่ง (position nodes) ทั้งหมดภายใต้องค์กรที่ระบุ
1320
+ *
1321
+ * @example
1322
+ * ```typescript
1323
+ * const positions = await authClient.organization.getPositions("org-123");
1324
+ * console.log(positions.map(p => p.name)); // ["Senior Developer", "Team Lead", ...]
1325
+ * ```
1326
+ */
1327
+ async getPositions(id) {
1328
+ const response = await this.axios.get(`/organizations/${id}/positions`);
1329
+ return response.data.data || [];
1330
+ }
1331
+ // ==========================================================================
1332
+ // Status Management
1333
+ // ==========================================================================
1334
+ /**
1335
+ * Activate organization
1336
+ *
1337
+ * @description เปิดใช้งานองค์กร
1338
+ *
1339
+ * @example
1340
+ * ```typescript
1341
+ * await authClient.organization.activate("org-123");
1342
+ * ```
1343
+ */
1344
+ async activate(id) {
1345
+ const response = await this.axios.patch(`/organizations/${id}/activate`);
1346
+ return !!response.data.data;
1347
+ }
1348
+ /**
1349
+ * Deactivate organization
1350
+ *
1351
+ * @description ปิดใช้งานองค์กร
1352
+ *
1353
+ * @example
1354
+ * ```typescript
1355
+ * await authClient.organization.deactivate("org-123");
1356
+ * ```
1357
+ */
1358
+ async deactivate(id) {
1359
+ const response = await this.axios.patch(`/organizations/${id}/deactivate`);
1360
+ return !!response.data.data;
1361
+ }
1362
+ // ==========================================================================
1363
+ // Bulk Operations
1364
+ // ==========================================================================
1365
+ /**
1366
+ * Bulk activate organizations
1367
+ *
1368
+ * @description เปิดใช้งานหลายองค์กรพร้อมกัน
1369
+ *
1370
+ * @example
1371
+ * ```typescript
1372
+ * const result = await authClient.organization.bulkActivate(["org-1", "org-2", "org-3"]);
1373
+ * console.log(result.success_count); // 3
1374
+ * ```
1375
+ */
1376
+ async bulkActivate(ids) {
1377
+ const response = await this.axios.post("/organizations/bulk-activate", {
1378
+ ids
1379
+ });
1380
+ return response.data.data;
1381
+ }
1382
+ /**
1383
+ * Bulk deactivate organizations
1384
+ *
1385
+ * @description ปิดใช้งานหลายองค์กรพร้อมกัน
1386
+ *
1387
+ * @example
1388
+ * ```typescript
1389
+ * const result = await authClient.organization.bulkDeactivate(["org-1", "org-2"]);
1390
+ * console.log(result.success_count); // 2
1391
+ * ```
1392
+ */
1393
+ async bulkDeactivate(ids) {
1394
+ const response = await this.axios.post("/organizations/bulk-deactivate", {
1395
+ ids
1396
+ });
1397
+ return response.data.data;
1398
+ }
1399
+ /**
1400
+ * Bulk delete organizations
1401
+ *
1402
+ * @description ลบหลายองค์กรพร้อมกัน
1403
+ *
1404
+ * @example
1405
+ * ```typescript
1406
+ * const result = await authClient.organization.bulkDelete(["org-1", "org-2"]);
1407
+ * console.log(result.success_count); // 2
1408
+ * ```
1409
+ */
1410
+ async bulkDelete(ids) {
1411
+ const response = await this.axios.post("/organizations/bulk-delete", {
1412
+ ids
1413
+ });
1414
+ return response.data.data;
1415
+ }
1416
+ /**
1417
+ * Clear all organization data
1418
+ *
1419
+ * @description ลบข้อมูลองค์กรทั้งหมด รวมถึง:
1420
+ * - user_position_assignment (เอาข้อมูล position ออกจาก user)
1421
+ * - organization_closure
1422
+ * - organization (company, department, position)
1423
+ * - Nullify organization/position references ใน workflow และ document tables
1424
+ *
1425
+ * รองรับทั้ง JWT และ API Key authentication (สำหรับเรียกจากระบบอื่น)
1426
+ *
1427
+ * @example
1428
+ * ```typescript
1429
+ * const result = await authClient.organization.clearAll();
1430
+ * console.log(result.organizations_deleted); // จำนวนองค์กรที่ลบ
1431
+ * console.log(result.user_position_assignments_deleted); // จำนวน position assignment ที่ลบ
1432
+ * ```
1433
+ */
1434
+ async clearAll() {
1435
+ const response = await this.axios.post("/organizations/clear-all");
1436
+ return response.data.data;
1437
+ }
1438
+ /**
1439
+ * Rebuild all organization data (รวมทุก fix ในครั้งเดียว)
1440
+ *
1441
+ * @description ใช้หลัง clear-all + create เพื่อให้ข้อมูลครบถ้วน:
1442
+ * 1. fix organization_id ตาม hierarchy
1443
+ * 2. reload organization_closure สำหรับทุก company
1444
+ * 3. reload report_to_position
1445
+ *
1446
+ * @example
1447
+ * ```typescript
1448
+ * await authClient.organization.clearAll();
1449
+ * // ... create organizations ...
1450
+ * const result = await authClient.organization.rebuildAll();
1451
+ * console.log(result.organization_ids_fixed, result.closure_companies_processed);
1452
+ * ```
1453
+ */
1454
+ async rebuildAll() {
1455
+ const response = await this.axios.post("/organizations/rebuild-all");
1456
+ return response.data.data;
1457
+ }
1458
+ // ==========================================================================
1459
+ // Hierarchy Operations
1460
+ // ==========================================================================
1461
+ /**
1462
+ * Duplicate organization (copy)
1463
+ *
1464
+ * @description คัดลอกองค์กรและ children ทั้งหมด สร้าง organization ใหม่พร้อม hierarchy fields และ closure records
1465
+ *
1466
+ * @example
1467
+ * ```typescript
1468
+ * const duplicated = await authClient.organization.duplicate("org-123");
1469
+ * console.log(duplicated.id); // new organization ID
1470
+ * ```
1471
+ */
1472
+ async duplicate(id) {
1473
+ const response = await this.axios.post(`/organizations/${id}/duplicate`);
1474
+ return response.data.data;
1475
+ }
1476
+ /**
1477
+ * Move organization to new parent
1478
+ *
1479
+ * @description ย้ายองค์กรไปอยู่ภายใต้ parent ใหม่ อัพเดท hierarchy fields และ closure table อัตโนมัติ
1480
+ * ส่ง `null` เพื่อย้ายไปเป็น root level
1481
+ *
1482
+ * @example
1483
+ * ```typescript
1484
+ * // ย้ายไปอยู่ภายใต้ parent ใหม่
1485
+ * await authClient.organization.move("org-123", { new_parent_id: "org-456" });
1486
+ *
1487
+ * // ย้ายไปเป็น root level
1488
+ * await authClient.organization.move("org-123", { new_parent_id: null });
1489
+ * ```
1490
+ */
1491
+ async move(id, data) {
1492
+ const response = await this.axios.patch(`/organizations/${id}/move`, data);
1493
+ return !!response.data.success;
1494
+ }
1495
+ };
1496
+
1497
+ // src/api/role.api.ts
1498
+ var RoleAPI = class {
1499
+ constructor(axios2) {
1500
+ this.axios = axios2;
1501
+ }
1502
+ // ==========================================================================
1503
+ // CRUD Operations
1504
+ // ==========================================================================
1505
+ /**
1506
+ * Search roles with pagination and filters
1507
+ *
1508
+ * @example
1509
+ * ```typescript
1510
+ * const result = await authClient.role.search({
1511
+ * search: "Admin",
1512
+ * page: 1,
1513
+ * limit: 20,
1514
+ * sort_by: "created_at",
1515
+ * sort_order: "desc"
1516
+ * });
1517
+ * ```
1518
+ */
1519
+ async search(params) {
1520
+ const response = await this.axios.post("/roles/search", params || {});
1521
+ return response.data;
1522
+ }
1523
+ /**
1524
+ * Get role by ID
1525
+ *
1526
+ * @example
1527
+ * ```typescript
1528
+ * const role = await authClient.role.get("role-123");
1529
+ * ```
1530
+ */
1531
+ async get(roleId) {
1532
+ const response = await this.axios.get(`/roles/${roleId}`);
1533
+ return response.data.data;
1534
+ }
1535
+ /**
1536
+ * Create a new role
1537
+ *
1538
+ * @example
1539
+ * ```typescript
1540
+ * const newRole = await authClient.role.create({
1541
+ * name: "ผู้ดูแลระบบ",
1542
+ * code: "ADMIN",
1543
+ * description: "บทบาทสำหรับผู้ดูแลระบบ"
1544
+ * });
1545
+ * ```
1546
+ */
1547
+ async create(data) {
1548
+ const response = await this.axios.post("/roles", data);
1549
+ return response.data.data;
1550
+ }
1551
+ /**
1552
+ * Update role
1553
+ *
1554
+ * @example
1555
+ * ```typescript
1556
+ * const updatedRole = await authClient.role.update("role-123", {
1557
+ * name: "ผู้ดูแลระบบหลัก",
1558
+ * description: "บทบาทสำหรับผู้ดูแลระบบหลัก"
1559
+ * });
1560
+ * ```
1561
+ */
1562
+ async update(roleId, data) {
1563
+ const response = await this.axios.put(`/roles/${roleId}`, data);
1564
+ return response.data.data;
1565
+ }
1566
+ /**
1567
+ * Clear all roles for current application (hard delete)
1568
+ *
1569
+ * @description ลบบทบาททั้งหมดตาม application_id จาก RequestContext (API key/context)
1570
+ * ใช้สำหรับ migrate - ไม่ใช้ DTO, ดึง application_id จาก context อัตโนมัติ
1571
+ *
1572
+ * @example
1573
+ * ```typescript
1574
+ * const result = await authClient.role.clear();
1575
+ * console.log(result.roles_deleted, result.role_permissions_deleted);
1576
+ * ```
1577
+ */
1578
+ async clear() {
1579
+ const response = await this.axios.post("/roles/clear");
1580
+ return response.data.data;
1581
+ }
1582
+ /**
1583
+ * Delete role
1584
+ *
1585
+ * @example
1586
+ * ```typescript
1587
+ * await authClient.role.delete("role-123");
1588
+ * ```
1589
+ */
1590
+ async delete(roleId) {
1591
+ const response = await this.axios.delete(`/roles/${roleId}`);
1592
+ return !!response.data.success;
1593
+ }
1594
+ // ==========================================================================
1595
+ // Status Management
1596
+ // ==========================================================================
1597
+ /**
1598
+ * Activate role
1599
+ *
1600
+ * @example
1601
+ * ```typescript
1602
+ * await authClient.role.activate("role-123");
1603
+ * ```
1604
+ */
1605
+ async activate(roleId) {
1606
+ const response = await this.axios.patch(`/roles/${roleId}/activate`);
1607
+ return !!response.data.data;
1608
+ }
1609
+ /**
1610
+ * Deactivate role
1611
+ *
1612
+ * @example
1613
+ * ```typescript
1614
+ * await authClient.role.deactivate("role-123");
1615
+ * ```
1616
+ */
1617
+ async deactivate(roleId) {
1618
+ const response = await this.axios.patch(`/roles/${roleId}/deactivate`);
1619
+ return !!response.data.data;
1620
+ }
1621
+ // ==========================================================================
1622
+ // User Assignment
1623
+ // ==========================================================================
1624
+ /**
1625
+ * Get role users
1626
+ *
1627
+ * @description ดึงรายการผู้ใช้ทั้งหมดที่มีบทบาทนี้
1628
+ *
1629
+ * @example
1630
+ * ```typescript
1631
+ * const users = await authClient.role.getUsers("role-123");
1632
+ * console.log(users.map(u => u.email));
1633
+ * ```
1634
+ */
1635
+ async getUsers(roleId) {
1636
+ const response = await this.axios.get(`/roles/${roleId}/users`);
1637
+ return response.data.data || [];
1638
+ }
1639
+ /**
1640
+ * Assign users to role
1641
+ *
1642
+ * @description มอบหมายผู้ใช้ให้บทบาท (เพิ่มเข้าไป ไม่ลบของเดิม)
1643
+ *
1644
+ * @example
1645
+ * ```typescript
1646
+ * await authClient.role.assignUsers("role-123", ["user-001", "user-002"]);
1647
+ * ```
1648
+ */
1649
+ async assignUsers(roleId, userIds) {
1650
+ const response = await this.axios.post(`/roles/${roleId}/users`, {
1651
+ ids: userIds
1652
+ });
1653
+ return !!response.data.success;
1654
+ }
1655
+ /**
1656
+ * Unassign users from role
1657
+ *
1658
+ * @description ยกเลิกผู้ใช้จากบทบาท
1659
+ *
1660
+ * @example
1661
+ * ```typescript
1662
+ * await authClient.role.unassignUsers("role-123", ["user-001"]);
1663
+ * ```
1664
+ */
1665
+ async unassignUsers(roleId, userIds) {
1666
+ const response = await this.axios.delete(`/roles/${roleId}/users`, {
1667
+ data: { ids: userIds }
1668
+ });
1669
+ return !!response.data.success;
1670
+ }
1671
+ // ==========================================================================
1672
+ // Permission Assignment
1673
+ // ==========================================================================
1674
+ /**
1675
+ * Get role permissions
1676
+ *
1677
+ * @description ดึงรายการสิทธิ์ทั้งหมดของบทบาท
1678
+ *
1679
+ * @example
1680
+ * ```typescript
1681
+ * const permissions = await authClient.role.getPermissions("role-123");
1682
+ * ```
1683
+ */
1684
+ async getPermissions(roleId) {
1685
+ const response = await this.axios.get(`/roles/${roleId}/permissions`);
1686
+ return response.data.data || [];
1687
+ }
1688
+ /**
1689
+ * Assign permissions to role
1690
+ *
1691
+ * @description มอบหมายสิทธิ์ให้บทบาท
1692
+ *
1693
+ * @example
1694
+ * ```typescript
1695
+ * await authClient.role.assignPermissions("role-123", ["perm-001", "perm-002"]);
1696
+ * ```
1697
+ */
1698
+ async assignPermissions(roleId, permissionIds) {
1699
+ const response = await this.axios.post(`/roles/${roleId}/permissions`, {
1700
+ ids: permissionIds
1701
+ });
1702
+ return !!response.data.success;
1703
+ }
1704
+ /**
1705
+ * Unassign permissions from role
1706
+ *
1707
+ * @description ยกเลิกสิทธิ์จากบทบาท
1708
+ *
1709
+ * @example
1710
+ * ```typescript
1711
+ * await authClient.role.unassignPermissions("role-123", ["perm-001"]);
1712
+ * ```
1713
+ */
1714
+ async unassignPermissions(roleId, permissionIds) {
1715
+ const response = await this.axios.delete(`/roles/${roleId}/permissions`, {
1716
+ data: { ids: permissionIds }
1717
+ });
1718
+ return !!response.data.success;
1719
+ }
1720
+ };
1721
+
1722
+ // src/api/permission.api.ts
1723
+ var PermissionAPI = class {
1724
+ constructor(axios2) {
1725
+ this.axios = axios2;
1726
+ }
1727
+ /**
1728
+ * Clear all permissions for current application (hard delete)
1729
+ *
1730
+ * @description ลบสิทธิ์ทั้งหมดตาม application_id จาก RequestContext (API key/context)
1731
+ * ใช้สำหรับ migrate - ไม่ใช้ DTO, ดึง application_id จาก context อัตโนมัติ
1732
+ *
1733
+ * @example
1734
+ * ```typescript
1735
+ * const result = await authClient.permission.clear();
1736
+ * console.log(result.permissions_deleted, result.role_permissions_deleted);
1737
+ * ```
1738
+ */
1739
+ async clear() {
1740
+ const response = await this.axios.post("/permissions/clear");
1741
+ return response.data.data;
1742
+ }
1743
+ /**
1744
+ * Search permissions with pagination and filters
1745
+ */
1746
+ async search(params) {
1747
+ const response = await this.axios.post("/permissions/search", params || {});
1748
+ return response.data;
1749
+ }
1750
+ /**
1751
+ * Get permission by ID
1752
+ */
1753
+ async get(id) {
1754
+ const response = await this.axios.get(`/permissions/${id}`);
1755
+ return response.data.data ?? null;
1756
+ }
1757
+ /**
1758
+ * Create a new permission
1759
+ */
1760
+ async create(data) {
1761
+ const response = await this.axios.post("/permissions", data);
1762
+ return response.data.data;
1763
+ }
1764
+ /**
1765
+ * Bulk create permissions ในครั้งเดียว
1766
+ *
1767
+ * @description สร้างสิทธิ์หลายรายการในครั้งเดียว ทุก permission ต้องมี category_id ที่มีอยู่แล้วในระบบ
1768
+ *
1769
+ * @example
1770
+ * ```typescript
1771
+ * const result = await authClient.permission.bulkCreate({
1772
+ * permissions: [
1773
+ * { category_id: "cat-uuid", name: "Create", key: "create", description: "..." },
1774
+ * { category_id: "cat-uuid", name: "Read", key: "read", description: "..." },
1775
+ * ],
1776
+ * });
1777
+ * console.log(result.created); // 2
1778
+ * ```
1779
+ */
1780
+ async bulkCreate(data) {
1781
+ const response = await this.axios.post("/permissions/bulk-create", data);
1782
+ return response.data.data;
1783
+ }
1784
+ /**
1785
+ * Update permission
1786
+ */
1787
+ async update(id, data) {
1788
+ const response = await this.axios.put(`/permissions/${id}`, data);
1789
+ return response.data.data;
1790
+ }
1791
+ /**
1792
+ * Delete permission
1793
+ */
1794
+ async delete(id) {
1795
+ const response = await this.axios.delete(`/permissions/${id}`);
1796
+ return !!response.data.success;
1797
+ }
1798
+ /**
1799
+ * Activate permission
1800
+ */
1801
+ async activate(id) {
1802
+ const response = await this.axios.patch(`/permissions/${id}/activate`);
1803
+ return !!response.data.data;
1804
+ }
1805
+ /**
1806
+ * Deactivate permission
1807
+ */
1808
+ async deactivate(id) {
1809
+ const response = await this.axios.patch(`/permissions/${id}/deactivate`);
1810
+ return !!response.data.data;
1811
+ }
1812
+ };
1813
+
1814
+ // src/api/permission-category.api.ts
1815
+ var PermissionCategoryAPI = class {
1816
+ constructor(axios2) {
1817
+ this.axios = axios2;
1818
+ }
1819
+ /**
1820
+ * Clear all permission categories for current application (hard delete)
1821
+ *
1822
+ * @description ลบหมวดหมู่สิทธิ์ทั้งหมดตาม application_id จาก RequestContext (API key/context)
1823
+ * ใช้สำหรับ migrate - ไม่ใช้ DTO, ดึง application_id จาก context อัตโนมัติ
1824
+ *
1825
+ * @example
1826
+ * ```typescript
1827
+ * const result = await authClient.permissionCategory.clear();
1828
+ * console.log(result.permission_categories_deleted, result.permissions_deleted);
1829
+ * ```
1830
+ */
1831
+ async clear() {
1832
+ const response = await this.axios.post(
1833
+ "/permission-categories/clear"
1834
+ );
1835
+ return response.data.data;
1836
+ }
1837
+ /**
1838
+ * Search permission categories with pagination and filters
1839
+ */
1840
+ async search(params) {
1841
+ const response = await this.axios.post(
1842
+ "/permission-categories/search",
1843
+ params || {}
1844
+ );
1845
+ return response.data;
1846
+ }
1847
+ /**
1848
+ * Get permission category by ID
1849
+ */
1850
+ async get(id) {
1851
+ const response = await this.axios.get(`/permission-categories/${id}`);
1852
+ return response.data.data;
1853
+ }
1854
+ /**
1855
+ * Create a new permission category (พร้อม permissions ได้)
1856
+ *
1857
+ * @note application_id ไม่ต้องส่งเมื่อเรียกจาก app context - API จะ inject อัตโนมัติ
1858
+ */
1859
+ async create(data) {
1860
+ const response = await this.axios.post("/permission-categories", data);
1861
+ return response.data.data;
1862
+ }
1863
+ /**
1864
+ * Bulk create permission categories พร้อม permissions ในครั้งเดียว
1865
+ *
1866
+ * @description สร้างหมวดหมู่สิทธิ์หลายรายการพร้อม permissions ในครั้งเดียว
1867
+ * ต้องเรียง parent ก่อน child หรือระบุ id ให้ parent เพื่อให้ child อ้างอิง parent_id ได้
1868
+ *
1869
+ * @note application_id ไม่ต้องส่ง - API จะ inject อัตโนมัติจาก API key หรือ RequestContextService
1870
+ *
1871
+ * @example
1872
+ * ```typescript
1873
+ * // เรียกจาก app context (API key) - application_id จะถูก inject อัตโนมัติ
1874
+ * const result = await authClient.permissionCategory.bulkCreate({
1875
+ * permission_categories: [
1876
+ * {
1877
+ * id: "cat-users",
1878
+ * key: "users",
1879
+ * name: "User Management",
1880
+ * resource: "users",
1881
+ * permissions: [
1882
+ * { name: "Create User", key: "create", description: "..." },
1883
+ * { name: "Read User", key: "read", description: "..." },
1884
+ * ],
1885
+ * },
1886
+ * {
1887
+ * key: "user_profile",
1888
+ * name: "User Profile",
1889
+ * parent_id: "cat-users",
1890
+ * permissions: [{ name: "Edit Profile", key: "edit", description: "..." }],
1891
+ * },
1892
+ * ],
1893
+ * });
1894
+ * console.log(result.created); // 2
1895
+ * ```
1896
+ */
1897
+ async bulkCreate(data) {
1898
+ const response = await this.axios.post(
1899
+ "/permission-categories/bulk-create",
1900
+ data
1901
+ );
1902
+ return response.data.data;
1903
+ }
1904
+ /**
1905
+ * Update permission category
1906
+ */
1907
+ async update(id, data) {
1908
+ const response = await this.axios.put(`/permission-categories/${id}`, data);
1909
+ return response.data.data;
1910
+ }
1911
+ /**
1912
+ * Delete permission category
1913
+ */
1914
+ async delete(id) {
1915
+ const response = await this.axios.delete(`/permission-categories/${id}`);
1916
+ return !!response.data.success;
1917
+ }
1918
+ };
1919
+
1920
+ // src/api/webhook.api.ts
1921
+ var WebhookAPI = class {
1922
+ constructor(axios2) {
1923
+ this.axios = axios2;
1924
+ }
1925
+ /**
1926
+ * ส่ง webhook request ผ่าน proxy endpoint
1927
+ *
1928
+ * @description
1929
+ * - ส่ง webhook request ไปยัง external URL ผ่านระบบ proxy
1930
+ * - ระบบจะสร้าง webhook_log และยิง webhook ออกไปให้
1931
+ * - รองรับ retry mechanism อัตโนมัติ
1932
+ * - ส่ง async: true เพื่อยิงทันทีและรับ result (http_status, response_body) ใน response
1933
+ *
1934
+ * @example
1935
+ * ```typescript
1936
+ * // ส่ง webhook request (โหมดปกติ - ได้ webhook_log_id กลับมา แล้วค่อย getStatus ตรวจสอบ)
1937
+ * const result = await authClient.webhook.proxy({
1938
+ * webhook_url: 'https://api.example.com/webhooks/users',
1939
+ * event_type: 'user.created',
1940
+ * payload: {
1941
+ * data: { id: 'user-123', email: 'user@example.com' },
1942
+ * object: 'event',
1943
+ * type: 'user.created'
1944
+ * },
1945
+ * headers: { 'Authorization': 'Bearer token' },
1946
+ * secret: 'webhook-secret',
1947
+ * timeout_ms: 30000,
1948
+ * max_retries: 3
1949
+ * });
1950
+ * console.log('Webhook Log ID:', result.webhook_log_id);
1951
+ *
1952
+ * // โหมด async: true - ยิงทันทีและได้ result กลับใน response (ไม่ต้อง getStatus)
1953
+ * const resultAsync = await authClient.webhook.proxy({
1954
+ * webhook_url: 'https://api.example.com/webhooks/users',
1955
+ * event_type: 'user.created',
1956
+ * payload: { data: { id: 'user-123' }, object: 'event', type: 'user.created' },
1957
+ * async: true
1958
+ * });
1959
+ * if (resultAsync.status === 'success') {
1960
+ * console.log('HTTP Status:', resultAsync.http_status);
1961
+ * console.log('Response Body:', resultAsync.response_body);
1962
+ * console.log('Execution Time:', resultAsync.execution_time_ms, 'ms');
1963
+ * } else {
1964
+ * console.error('Failed:', resultAsync.error_message);
1965
+ * }
1966
+ * ```
1967
+ */
1968
+ async proxy(request) {
1969
+ const response = await this.axios.post("/webhook-proxy", request);
1970
+ return response.data.data;
1971
+ }
1972
+ /**
1973
+ * ดึง webhook log detail ตาม ID
1974
+ *
1975
+ * @description
1976
+ * - ดึงข้อมูล webhook log ตาม ID ที่ส่งกลับมาจาก proxy()
1977
+ * - แสดง status, response, error message, และข้อมูลอื่นๆ
1978
+ * - สามารถดึงได้เฉพาะ webhook logs ของ application ที่ authenticate อยู่เท่านั้น
1979
+ *
1980
+ * @example
1981
+ * ```typescript
1982
+ * // ดึง webhook log detail
1983
+ * const log = await authClient.webhook.getStatus('log-123e4567-e89b-12d3-a456-426614174000');
1984
+ *
1985
+ * console.log('Status:', log.status); // 'success', 'failed', 'pending', 'retrying'
1986
+ * console.log('HTTP Status:', log.http_status); // 200, 404, 500, etc.
1987
+ * console.log('Response Body:', log.response_body);
1988
+ * console.log('Error:', log.error_message);
1989
+ * console.log('Execution Time:', log.execution_time_ms, 'ms');
1990
+ * console.log('Retry Count:', log.retry_count);
1991
+ *
1992
+ * // ตรวจสอบว่า webhook สำเร็จหรือไม่
1993
+ * if (log.status === 'success') {
1994
+ * console.log('Webhook delivered successfully!');
1995
+ * } else if (log.status === 'failed') {
1996
+ * console.error('Webhook failed:', log.error_message);
1997
+ * }
1998
+ * ```
1999
+ */
2000
+ async getStatus(webhookLogId) {
2001
+ const response = await this.axios.get(`/webhook-proxy/${webhookLogId}`);
2002
+ return response.data.data;
2003
+ }
2004
+ };
2005
+
2006
+ // src/portal-api-client.ts
2007
+ var PortalApiClient = class {
2008
+ constructor(config) {
2009
+ this.axios = import_axios.default.create({
2010
+ baseURL: config.apiUrl,
2011
+ timeout: config.timeout ?? 3e4,
2012
+ withCredentials: true
2013
+ });
2014
+ this.axios.interceptors.request.use((cfg) => {
2015
+ const token = config.getToken();
2016
+ if (token) cfg.headers.Authorization = `Bearer ${token}`;
2017
+ if (config.apiKey) cfg.headers["X-API-Key"] = config.apiKey;
2018
+ return cfg;
2019
+ });
2020
+ this.email = new EmailAPI(this.axios);
2021
+ this.eventLog = new EventLogApi(this.axios);
2022
+ this.files = new FilesAPI(this.axios);
2023
+ this.health = new HealthAPI(this.axios);
2024
+ this.line = new LineAPI(this.axios);
2025
+ this.organization = new OrganizationAPI(this.axios);
2026
+ this.otp = new OtpAPI(this.axios);
2027
+ this.permission = new PermissionAPI(this.axios);
2028
+ this.permissionCategory = new PermissionCategoryAPI(this.axios);
2029
+ this.role = new RoleAPI(this.axios);
2030
+ this.systemConfig = new SystemConfigAPI(this.axios);
2031
+ this.todo = new TodoAPI(this.axios);
2032
+ this.user = new UserAPI(this.axios);
2033
+ this.webhook = new WebhookAPI(this.axios);
2034
+ this.workflow = new WorkflowAPI(this.axios);
2035
+ }
2036
+ get(url, config) {
2037
+ return this.axios.get(url, config);
2038
+ }
2039
+ post(url, data, config) {
2040
+ return this.axios.post(url, data, config);
2041
+ }
2042
+ put(url, data, config) {
2043
+ return this.axios.put(url, data, config);
2044
+ }
2045
+ patch(url, data, config) {
2046
+ return this.axios.patch(url, data, config);
2047
+ }
2048
+ delete(url, config) {
2049
+ return this.axios.delete(url, config);
2050
+ }
2051
+ };
2052
+
2053
+ // ../../shared/src/enums/common.enums.ts
2054
+ var OrganizationType = /* @__PURE__ */ ((OrganizationType2) => {
2055
+ OrganizationType2["GROUP"] = "group";
2056
+ OrganizationType2["COMPANY"] = "company";
2057
+ OrganizationType2["BRANCH"] = "branch";
2058
+ OrganizationType2["DIVISION"] = "division";
2059
+ OrganizationType2["DEPARTMENT"] = "department";
2060
+ OrganizationType2["SECTION"] = "section";
2061
+ OrganizationType2["TEAM"] = "team";
2062
+ OrganizationType2["POSITION"] = "position";
2063
+ return OrganizationType2;
2064
+ })(OrganizationType || {});
2065
+
2066
+ // ../../shared/src/enums/event-log.enums.ts
2067
+ var EventSeverity = /* @__PURE__ */ ((EventSeverity2) => {
2068
+ EventSeverity2["DEBUG"] = "debug";
2069
+ EventSeverity2["INFO"] = "info";
2070
+ EventSeverity2["WARNING"] = "warning";
2071
+ EventSeverity2["ERROR"] = "error";
2072
+ EventSeverity2["CRITICAL"] = "critical";
2073
+ return EventSeverity2;
2074
+ })(EventSeverity || {});
2075
+ var EventOutcome = /* @__PURE__ */ ((EventOutcome2) => {
2076
+ EventOutcome2["SUCCESS"] = "success";
2077
+ EventOutcome2["FAILURE"] = "failure";
2078
+ EventOutcome2["PARTIAL"] = "partial";
2079
+ EventOutcome2["UNKNOWN"] = "unknown";
2080
+ return EventOutcome2;
2081
+ })(EventOutcome || {});
2082
+ var EventCategory = /* @__PURE__ */ ((EventCategory2) => {
2083
+ EventCategory2["AUTHENTICATION"] = "authentication";
2084
+ EventCategory2["AUTHORIZATION"] = "authorization";
2085
+ EventCategory2["DATA_ACCESS"] = "data_access";
2086
+ EventCategory2["SECURITY"] = "security";
2087
+ EventCategory2["BUSINESS"] = "business";
2088
+ EventCategory2["TECHNICAL"] = "technical";
2089
+ EventCategory2["COMPLIANCE"] = "compliance";
2090
+ EventCategory2["ISO27001_AUDIT"] = "iso27001_audit";
2091
+ return EventCategory2;
2092
+ })(EventCategory || {});
2093
+ var EventRiskLevel = /* @__PURE__ */ ((EventRiskLevel2) => {
2094
+ EventRiskLevel2["NONE"] = "none";
2095
+ EventRiskLevel2["LOW"] = "low";
2096
+ EventRiskLevel2["MEDIUM"] = "medium";
2097
+ EventRiskLevel2["HIGH"] = "high";
2098
+ EventRiskLevel2["CRITICAL"] = "critical";
2099
+ return EventRiskLevel2;
2100
+ })(EventRiskLevel || {});
2101
+ var ActorType = /* @__PURE__ */ ((ActorType2) => {
2102
+ ActorType2["USER"] = "user";
2103
+ ActorType2["SYSTEM"] = "system";
2104
+ ActorType2["SERVICE"] = "service";
2105
+ ActorType2["API_CLIENT"] = "api_client";
2106
+ ActorType2["SCHEDULER"] = "scheduler";
2107
+ ActorType2["WEBHOOK"] = "webhook";
2108
+ return ActorType2;
2109
+ })(ActorType || {});
2110
+
2111
+ // ../../shared/src/enums/todo.enums.ts
2112
+ var TodoPriority = /* @__PURE__ */ ((TodoPriority2) => {
2113
+ TodoPriority2["LOW"] = "low";
2114
+ TodoPriority2["NORMAL"] = "normal";
2115
+ TodoPriority2["HIGH"] = "high";
2116
+ return TodoPriority2;
2117
+ })(TodoPriority || {});
2118
+ // Annotate the CommonJS export names for ESM import in node:
2119
+ 0 && (module.exports = {
2120
+ ActorType,
2121
+ EmailAPI,
2122
+ EventCategory,
2123
+ EventLogApi,
2124
+ EventOutcome,
2125
+ EventRiskLevel,
2126
+ EventSeverity,
2127
+ FilesAPI,
2128
+ HealthAPI,
2129
+ LineAPI,
2130
+ OrganizationAPI,
2131
+ OrganizationType,
2132
+ OtpAPI,
2133
+ PermissionAPI,
2134
+ PermissionCategoryAPI,
2135
+ PortalApiClient,
2136
+ RoleAPI,
2137
+ SystemConfigAPI,
2138
+ TodoAPI,
2139
+ TodoPriority,
2140
+ UserAPI,
2141
+ WebhookAPI,
2142
+ WorkflowAPI
2143
+ });
2144
+ //# sourceMappingURL=index.js.map