@redonvn/ahamove-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +247 -0
  2. package/dist/client.d.ts +75 -0
  3. package/dist/client.d.ts.map +1 -0
  4. package/dist/client.js +85 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/config.d.ts +19 -0
  7. package/dist/config.d.ts.map +1 -0
  8. package/dist/config.js +27 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/errors/ahamove-error.d.ts +64 -0
  11. package/dist/errors/ahamove-error.d.ts.map +1 -0
  12. package/dist/errors/ahamove-error.js +74 -0
  13. package/dist/errors/ahamove-error.js.map +1 -0
  14. package/dist/errors/error-codes.d.ts +60 -0
  15. package/dist/errors/error-codes.d.ts.map +1 -0
  16. package/dist/errors/error-codes.js +90 -0
  17. package/dist/errors/error-codes.js.map +1 -0
  18. package/dist/errors/index.d.ts +3 -0
  19. package/dist/errors/index.d.ts.map +1 -0
  20. package/dist/errors/index.js +19 -0
  21. package/dist/errors/index.js.map +1 -0
  22. package/dist/index.d.ts +7 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +23 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/services/account.service.d.ts +68 -0
  27. package/dist/services/account.service.d.ts.map +1 -0
  28. package/dist/services/account.service.js +112 -0
  29. package/dist/services/account.service.js.map +1 -0
  30. package/dist/services/index.d.ts +5 -0
  31. package/dist/services/index.d.ts.map +1 -0
  32. package/dist/services/index.js +21 -0
  33. package/dist/services/index.js.map +1 -0
  34. package/dist/services/master-data.service.d.ts +32 -0
  35. package/dist/services/master-data.service.d.ts.map +1 -0
  36. package/dist/services/master-data.service.js +63 -0
  37. package/dist/services/master-data.service.js.map +1 -0
  38. package/dist/services/order.service.d.ts +101 -0
  39. package/dist/services/order.service.d.ts.map +1 -0
  40. package/dist/services/order.service.js +222 -0
  41. package/dist/services/order.service.js.map +1 -0
  42. package/dist/services/webhook.service.d.ts +41 -0
  43. package/dist/services/webhook.service.d.ts.map +1 -0
  44. package/dist/services/webhook.service.js +77 -0
  45. package/dist/services/webhook.service.js.map +1 -0
  46. package/dist/types/account.d.ts +107 -0
  47. package/dist/types/account.d.ts.map +1 -0
  48. package/dist/types/account.js +3 -0
  49. package/dist/types/account.js.map +1 -0
  50. package/dist/types/common.d.ts +84 -0
  51. package/dist/types/common.d.ts.map +1 -0
  52. package/dist/types/common.js +3 -0
  53. package/dist/types/common.js.map +1 -0
  54. package/dist/types/estimate.d.ts +95 -0
  55. package/dist/types/estimate.d.ts.map +1 -0
  56. package/dist/types/estimate.js +3 -0
  57. package/dist/types/estimate.js.map +1 -0
  58. package/dist/types/index.d.ts +7 -0
  59. package/dist/types/index.d.ts.map +1 -0
  60. package/dist/types/index.js +23 -0
  61. package/dist/types/index.js.map +1 -0
  62. package/dist/types/master-data.d.ts +104 -0
  63. package/dist/types/master-data.d.ts.map +1 -0
  64. package/dist/types/master-data.js +3 -0
  65. package/dist/types/master-data.js.map +1 -0
  66. package/dist/types/order.d.ts +488 -0
  67. package/dist/types/order.d.ts.map +1 -0
  68. package/dist/types/order.js +3 -0
  69. package/dist/types/order.js.map +1 -0
  70. package/dist/types/webhook.d.ts +137 -0
  71. package/dist/types/webhook.d.ts.map +1 -0
  72. package/dist/types/webhook.js +3 -0
  73. package/dist/types/webhook.js.map +1 -0
  74. package/dist/utils/http.d.ts +50 -0
  75. package/dist/utils/http.d.ts.map +1 -0
  76. package/dist/utils/http.js +195 -0
  77. package/dist/utils/http.js.map +1 -0
  78. package/dist/utils/webhook-verifier.d.ts +19 -0
  79. package/dist/utils/webhook-verifier.d.ts.map +1 -0
  80. package/dist/utils/webhook-verifier.js +69 -0
  81. package/dist/utils/webhook-verifier.js.map +1 -0
  82. package/package.json +40 -0
package/README.md ADDED
@@ -0,0 +1,247 @@
1
+ # @redonvn/ahamove-sdk
2
+
3
+ Bộ TypeScript SDK chính thức và chuẩn hóa dành cho **Ahamove On-Demand Delivery API v3**.
4
+
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ---
9
+
10
+ ## 🌟 Tính Năng Nổi Bật
11
+
12
+ - **Chuẩn hóa TypeScript 100%**: Mọi model dữ liệu, tham số đầu vào, phản hồi API, trạng thái đơn hàng đều có kiểu dữ liệu rõ ràng kèm chú thích JSDoc tiếng Việt chi tiết.
13
+ - **Hỗ trợ đầy đủ Ahamove API v3**:
14
+ - **Order APIs**: Ước tính cước phí (`estimateFee`), tạo đơn hàng (`create`), tra cứu chi tiết (`getDetail`, `getMultipleDetails`), tra cứu theo mã đối tác (`getByTrackingNumber`), hủy đơn (`cancel`, `cancelByTrackingNumber`), lấy link live tracking (`getTrackingLink`), đánh giá tài xế (`rateSupplier`), xem log webhook callback (`getCallbackLogs`).
15
+ - **Account APIs**: Đăng ký tài khoản (`register`), xác thực lấy Bearer token (`authenticateToken`), quản lý tài khoản con chi nhánh (`getChildAccounts`, `addChildAccount`, `activateChildAccount`, `removeChildAccount`), cập nhật hồ sơ (`updateProfile`).
16
+ - **Master Data APIs**: Danh sách tỉnh thành (`getCities`), danh sách dịch vụ giao hàng (`getServices`), thông số cấu hình và dịch vụ kèm theo (`getServiceDetail`).
17
+ - **Webhook Utilities**: Tiếp nhận, xác thực chữ ký (API Key, Bearer, Basic Auth) và phân luồng sự kiện theo trạng thái đơn hàng.
18
+ - **Tự động làm mới Token (Auto Refresh Token)**: Khi token hết hạn (lỗi `401 NOT_AUTHORIZED`), SDK tự động gọi API cấp lại token mới và retry request trong suốt.
19
+ - **Xử lý lỗi thông minh**: Chuẩn hóa mã lỗi Ahamove (`MISSING_PATH_INFO`, `INVALID_MAX_DISTANCE`, `NOT_ENOUGH_CREDIT`, `DUPLICATE_TRACKING_NUMBER`...) thành class `AhamoveApiError` với các helper predicate trực quan.
20
+ - **Hỗ trợ song song cả 2 môi trường**: Sandbox (`staging`) và Production (`production`).
21
+
22
+ ---
23
+
24
+ ## 📦 Cài Đặt
25
+
26
+ ```bash
27
+ npm install @redonvn/ahamove-sdk
28
+ # hoặc
29
+ pnpm add @redonvn/ahamove-sdk
30
+ # hoặc
31
+ yarn add @redonvn/ahamove-sdk
32
+ ```
33
+
34
+ ---
35
+
36
+ ## 🚀 Hướng Dẫn Sử Dụng Nhanh
37
+
38
+ ### 1. Khởi tạo Client
39
+
40
+ ```typescript
41
+ import { AhamoveClient } from '@redonvn/ahamove-sdk';
42
+
43
+ const ahamove = new AhamoveClient({
44
+ apiKey: process.env.AHAMOVE_API_KEY, // API Key do Ahamove cấp
45
+ mobile: process.env.AHAMOVE_MOBILE, // Số điện thoại đăng ký tài khoản
46
+ environment: 'staging', // 'staging' hoặc 'production'
47
+ autoRefreshToken: true, // Tự động cấp lại token khi hết hạn
48
+ });
49
+ ```
50
+
51
+ ---
52
+
53
+ ### 2. Ước Tính Cước Phí và Khoảng Cách
54
+
55
+ ```typescript
56
+ const estimates = await ahamove.orders.estimateFee({
57
+ path: [
58
+ {
59
+ lat: 10.769753,
60
+ lng: 106.663661,
61
+ address: '7/28 Thành Thái, Phường 14, Quận 10, TP.HCM',
62
+ },
63
+ {
64
+ lat: 10.801849,
65
+ lng: 106.714466,
66
+ address: '475A Điện Biên Phủ, Phường 25, Quận Bình Thạnh, TP.HCM',
67
+ name: 'Nguyễn Văn B',
68
+ mobile: '0912345678',
69
+ cod: 150000,
70
+ },
71
+ ],
72
+ services: [{ service_id: 'SGN-BIKE' }],
73
+ });
74
+
75
+ for (const item of estimates) {
76
+ console.log(`Dịch vụ: ${item.service_id}`);
77
+ console.log(`Khoảng cách: ${item.data.distance} km`);
78
+ console.log(`Thời gian dự kiến: ${item.data.duration} giây`);
79
+ console.log(`Tổng cước phí: ${item.data.total_fee.toLocaleString('vi-VN')} VND`);
80
+ }
81
+ ```
82
+
83
+ ---
84
+
85
+ ### 3. Tạo Đơn Hàng Giao Ngay
86
+
87
+ ```typescript
88
+ const newOrder = await ahamove.orders.create({
89
+ service_id: 'SGN-BIKE',
90
+ payment_method: 'CASH', // 'CASH' | 'CASH_BY_RECIPIENT' | 'BALANCE'
91
+ remarks: 'Hàng dễ vỡ xin nhẹ tay',
92
+ path: [
93
+ {
94
+ lat: 10.76975346,
95
+ lng: 106.6636615,
96
+ address: '7/28 Thành Thái, Phường 14, Quận 10, TP.HCM',
97
+ short_address: 'Thành Thái, Quận 10',
98
+ name: 'Người gửi',
99
+ mobile: '0901234567',
100
+ },
101
+ {
102
+ lat: 10.8018493,
103
+ lng: 106.714466,
104
+ address: '475A Điện Biên Phủ, Phường 25, Quận Bình Thạnh, TP.HCM',
105
+ short_address: 'Hutech Bình Thạnh',
106
+ name: 'Người nhận A',
107
+ mobile: '0912345678',
108
+ cod: 200000,
109
+ tracking_number: 'DH-2026-0001', // Mã đơn hàng nội bộ
110
+ remarks: 'Gọi trước khi giao 15p',
111
+ },
112
+ ],
113
+ requests: [
114
+ { _id: 'SGN-BIKE-TIP', num: 1 }, // Tip thêm cho tài xế
115
+ ],
116
+ });
117
+
118
+ console.log('Tạo đơn thành công!');
119
+ console.log('Mã đơn Ahamove:', newOrder.order_id);
120
+ console.log('Trạng thái:', newOrder.status);
121
+ console.log('Link theo dõi live:', newOrder.shared_link);
122
+ ```
123
+
124
+ ---
125
+
126
+ ### 4. Tra Cứu và Hủy Đơn Hàng
127
+
128
+ ```typescript
129
+ // Tra cứu chi tiết theo mã đơn Ahamove
130
+ const order = await ahamove.orders.getDetail('24ABCD');
131
+ console.log('Trạng thái đơn:', order.status);
132
+ console.log('Tài xế:', order.supplier_name, order.supplier_mobile);
133
+
134
+ // Lấy link theo dõi thời gian thực
135
+ const trackingLink = await ahamove.orders.getTrackingLink('24ABCD');
136
+
137
+ // Hủy đơn hàng (chỉ hủy được khi đơn chưa chuyển sang IN PROCESS)
138
+ await ahamove.orders.cancel('24ABCD', {
139
+ comment: 'Khách yêu cầu đổi lịch giao ngày mai',
140
+ });
141
+ ```
142
+
143
+ ---
144
+
145
+ ### 5. Xử Lý Webhook Callback
146
+
147
+ Ahamove sẽ bắn HTTP POST callback về server của Đối tác mỗi khi trạng thái đơn hàng thay đổi.
148
+
149
+ ```typescript
150
+ import express from 'express';
151
+ import { AhamoveClient, WebhookVerifier } from '@redonvn/ahamove-sdk';
152
+
153
+ const app = express();
154
+ app.use(express.json());
155
+
156
+ const ahamove = new AhamoveClient({ environment: 'production' });
157
+
158
+ app.post('/api/ahamove/webhook', async (req, res) => {
159
+ try {
160
+ // 1. Xác thực header và lấy payload chuẩn
161
+ const payload = ahamove.webhook.parseAndVerify(req.headers, req.body, {
162
+ authType: 'API_KEY', // 'API_KEY' | 'BEARER_TOKEN' | 'BASIC_AUTH'
163
+ apiKey: process.env.WEBHOOK_SECRET_KEY,
164
+ });
165
+
166
+ // 2. Phân luồng sự kiện đơn hàng
167
+ await ahamove.webhook.handleWebhook(payload, {
168
+ onAssigning: (data) => {
169
+ console.log(`Đơn ${data._id} đang tìm tài xế`);
170
+ },
171
+ onAccepted: (data) => {
172
+ console.log(`Tài xế ${data.supplier_name} (${data.supplier_mobile}) đã nhận đơn ${data._id}`);
173
+ },
174
+ onInProcess: (data) => {
175
+ console.log(`Tài xế đã lấy hàng tại điểm gửi cho đơn ${data._id}`);
176
+ },
177
+ onSubStatusChanged: (subStatus, data) => {
178
+ console.log(`Đơn ${data._id} cập nhật hành trình tài xế: ${subStatus}`);
179
+ },
180
+ onCompleted: (data) => {
181
+ console.log(`Đơn ${data._id} đã hoàn tất thành công!`);
182
+ },
183
+ onCancelled: (data) => {
184
+ console.log(`Đơn ${data._id} đã bị hủy bởi: ${data.cancel_by_user ? 'Khách' : 'Tài xế/Hệ thống'}`);
185
+ console.log(`Lý do: ${data.cancel_comment}`);
186
+ },
187
+ });
188
+
189
+ res.status(200).send('OK');
190
+ } catch (error) {
191
+ console.error('Lỗi webhook:', error);
192
+ res.status(400).json({ error: 'Invalid webhook request' });
193
+ }
194
+ });
195
+ ```
196
+
197
+ ---
198
+
199
+ ### 6. Bắt và Xử Lý Lỗi Chuẩn Hóa
200
+
201
+ ```typescript
202
+ import { AhamoveApiError, AhamoveErrorCode } from '@redonvn/ahamove-sdk';
203
+
204
+ try {
205
+ await ahamove.orders.create({ ... });
206
+ } catch (error) {
207
+ if (error instanceof AhamoveApiError) {
208
+ console.error('HTTP Status:', error.statusCode);
209
+ console.error('Error Code:', error.errorCode);
210
+ console.error('Mô tả:', error.description);
211
+
212
+ if (error.isInsufficientCredit()) {
213
+ // Xử lý nạp thêm tiền vào tài khoản trả trước
214
+ } else if (error.isDuplicateTrackingNumber()) {
215
+ // Xử lý sinh mã tracking_number mới
216
+ } else if (error.isInvalidDistance()) {
217
+ // Báo người dùng chọn phương tiện khác
218
+ }
219
+ }
220
+ }
221
+ ```
222
+
223
+ ---
224
+
225
+ ## 📋 Danh Mục Mã Lỗi Ahamove
226
+
227
+ | Mã Lỗi | Code | Diễn giải tiếng Việt |
228
+ | --- | --- | --- |
229
+ | `400` | `BAD_REQUEST` | Dữ liệu yêu cầu không hợp lệ hoặc sai định dạng |
230
+ | `400` | `MISSING_REQUIRED_INFO` | Thiếu thông tin bắt buộc trong yêu cầu |
231
+ | `400` | `MISSING_PATH_INFO` | Lộ trình đơn hàng cần tối thiểu 2 điểm dừng |
232
+ | `401` | `NOT_AUTHORIZED` | Token xác thực không hợp lệ hoặc đã hết hạn |
233
+ | `404` | `SERVICE_NOT_FOUND` | Mã dịch vụ không tồn tại hoặc không hỗ trợ khu vực |
234
+ | `404` | `ORDER_NOT_FOUND` | Không tìm thấy đơn hàng |
235
+ | `406` | `INVALID_MAX_DISTANCE` | Khoảng cách giao hàng vượt quá giới hạn dịch vụ |
236
+ | `406` | `INVALID_MAX_COD` | Tiền COD vượt quá hạn mức tối đa |
237
+ | `406` | `NOT_ENOUGH_CREDIT` | Số dư tài khoản không đủ thanh toán |
238
+ | `406` | `SERVICE_NOT_VALID_AT_PICKUP` | Dịch vụ không khả dụng tại điểm lấy hàng |
239
+ | `409` | `DUPLICATE_TRACKING_NUMBER` | Mã tracking_number đã tồn tại trong hệ thống |
240
+ | `409` | `ORDER_CANNOT_BE_CANCELLED` | Đơn hàng không thể hủy (đang giao hoặc đã xong) |
241
+ | `500` | `INTERNAL_SERVER_ERROR` | Lỗi hệ thống nội bộ máy chủ Ahamove |
242
+
243
+ ---
244
+
245
+ ## 📄 Bản Quyền
246
+
247
+ Phát triển bởi đội ngũ **Redon**. Giấy phép mã nguồn mở [MIT License](LICENSE).
@@ -0,0 +1,75 @@
1
+ import { AhamoveClientConfig } from './types/common';
2
+ import { OrderService } from './services/order.service';
3
+ import { AccountService } from './services/account.service';
4
+ import { MasterDataService } from './services/master-data.service';
5
+ import { WebhookService } from './services/webhook.service';
6
+ /**
7
+ * Client trung tâm để tương tác với Ahamove API v3
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { AhamoveClient } from '@redonvn/ahamove-sdk';
12
+ *
13
+ * const client = new AhamoveClient({
14
+ * apiKey: 'YOUR_API_KEY',
15
+ * mobile: '849xxxxxxxx',
16
+ * environment: 'staging',
17
+ * });
18
+ *
19
+ * // 1. Ước tính cước phí giao hàng
20
+ * const estimates = await client.orders.estimateFee({
21
+ * path: [
22
+ * { lat: 10.769753, lng: 106.663661, address: '7/28 Thành Thái, Q10, HCM' },
23
+ * { lat: 10.801849, lng: 106.714466, address: '475A Điện Biên Phủ, Bình Thạnh, HCM', name: 'Anh', mobile: '0912345678' }
24
+ * ]
25
+ * });
26
+ *
27
+ * // 2. Tạo đơn hàng giao ngay
28
+ * const order = await client.orders.create({
29
+ * service_id: 'SGN-BIKE',
30
+ * payment_method: 'CASH',
31
+ * path: [
32
+ * { lat: 10.769753, lng: 106.663661, address: '7/28 Thành Thái, Q10, HCM' },
33
+ * { lat: 10.801849, lng: 106.714466, address: '475A Điện Biên Phủ, Bình Thạnh, HCM', name: 'Anh', mobile: '0912345678', cod: 100000 }
34
+ * ]
35
+ * });
36
+ * console.log('Đơn hàng đã tạo:', order.order_id, 'Link tracking:', order.shared_link);
37
+ * ```
38
+ */
39
+ export declare class AhamoveClient {
40
+ private readonly config;
41
+ private readonly http;
42
+ /**
43
+ * Quản lý đơn hàng (Tạo đơn, ước tính phí, lấy chi tiết, hủy đơn, theo dõi lộ trình...)
44
+ */
45
+ readonly orders: OrderService;
46
+ /**
47
+ * Quản lý tài khoản (Đăng ký tài khoản, xác thực lấy token, quản lý tài khoản con...)
48
+ */
49
+ readonly accounts: AccountService;
50
+ /**
51
+ * Tra cứu danh mục dữ liệu (Thành phố hoạt động, danh sách dịch vụ, cấu hình dịch vụ...)
52
+ */
53
+ readonly masterData: MasterDataService;
54
+ /**
55
+ * Tiếp nhận, xác thực và xử lý Webhook callback từ Ahamove
56
+ */
57
+ readonly webhook: WebhookService;
58
+ constructor(config?: AhamoveClientConfig);
59
+ /**
60
+ * Cập nhật Bearer Token thủ công cho Client
61
+ */
62
+ setToken(token: string): void;
63
+ /**
64
+ * Lấy Bearer Token hiện tại
65
+ */
66
+ getToken(): string | undefined;
67
+ /**
68
+ * Xác thực và tự động cập nhật Bearer Token cho Client
69
+ *
70
+ * @param mobile Số điện thoại tài khoản (mặc định lấy từ cấu hình khi khởi tạo)
71
+ * @returns Chuỗi token mới nhận được
72
+ */
73
+ authenticate(mobile?: string): Promise<string>;
74
+ }
75
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,aAAa;IAuBZ,OAAO,CAAC,QAAQ,CAAC,MAAM;IAtBnC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAa;IAElC;;OAEG;IACH,SAAgB,MAAM,EAAE,YAAY,CAAC;IAErC;;OAEG;IACH,SAAgB,QAAQ,EAAE,cAAc,CAAC;IAEzC;;OAEG;IACH,SAAgB,UAAU,EAAE,iBAAiB,CAAC;IAE9C;;OAEG;IACH,SAAgB,OAAO,EAAE,cAAc,CAAC;gBAEX,MAAM,GAAE,mBAAwB;IAmB7D;;OAEG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAKpC;;OAEG;IACI,QAAQ,IAAI,MAAM,GAAG,SAAS;IAIrC;;;;;OAKG;IACU,YAAY,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAI5D"}
package/dist/client.js ADDED
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AhamoveClient = void 0;
4
+ const http_1 = require("./utils/http");
5
+ const order_service_1 = require("./services/order.service");
6
+ const account_service_1 = require("./services/account.service");
7
+ const master_data_service_1 = require("./services/master-data.service");
8
+ const webhook_service_1 = require("./services/webhook.service");
9
+ /**
10
+ * Client trung tâm để tương tác với Ahamove API v3
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { AhamoveClient } from '@redonvn/ahamove-sdk';
15
+ *
16
+ * const client = new AhamoveClient({
17
+ * apiKey: 'YOUR_API_KEY',
18
+ * mobile: '849xxxxxxxx',
19
+ * environment: 'staging',
20
+ * });
21
+ *
22
+ * // 1. Ước tính cước phí giao hàng
23
+ * const estimates = await client.orders.estimateFee({
24
+ * path: [
25
+ * { lat: 10.769753, lng: 106.663661, address: '7/28 Thành Thái, Q10, HCM' },
26
+ * { lat: 10.801849, lng: 106.714466, address: '475A Điện Biên Phủ, Bình Thạnh, HCM', name: 'Anh', mobile: '0912345678' }
27
+ * ]
28
+ * });
29
+ *
30
+ * // 2. Tạo đơn hàng giao ngay
31
+ * const order = await client.orders.create({
32
+ * service_id: 'SGN-BIKE',
33
+ * payment_method: 'CASH',
34
+ * path: [
35
+ * { lat: 10.769753, lng: 106.663661, address: '7/28 Thành Thái, Q10, HCM' },
36
+ * { lat: 10.801849, lng: 106.714466, address: '475A Điện Biên Phủ, Bình Thạnh, HCM', name: 'Anh', mobile: '0912345678', cod: 100000 }
37
+ * ]
38
+ * });
39
+ * console.log('Đơn hàng đã tạo:', order.order_id, 'Link tracking:', order.shared_link);
40
+ * ```
41
+ */
42
+ class AhamoveClient {
43
+ constructor(config = {}) {
44
+ this.config = config;
45
+ this.http = new http_1.HttpClient(config);
46
+ this.accounts = new account_service_1.AccountService(this.http, config);
47
+ this.orders = new order_service_1.OrderService(this.http);
48
+ this.masterData = new master_data_service_1.MasterDataService(this.http);
49
+ this.webhook = new webhook_service_1.WebhookService();
50
+ // Thiết lập cơ chế tự động refresh token khi token hết hạn
51
+ this.http.setRefreshTokenHandler(async () => {
52
+ if (this.config.apiKey && this.config.mobile) {
53
+ this.config.logger?.('info', 'Đang tự động xác thực lấy token mới từ Ahamove...');
54
+ const res = await this.accounts.authenticateToken();
55
+ return res.token;
56
+ }
57
+ return null;
58
+ });
59
+ }
60
+ /**
61
+ * Cập nhật Bearer Token thủ công cho Client
62
+ */
63
+ setToken(token) {
64
+ this.http.setToken(token);
65
+ this.config.token = token;
66
+ }
67
+ /**
68
+ * Lấy Bearer Token hiện tại
69
+ */
70
+ getToken() {
71
+ return this.http.getToken();
72
+ }
73
+ /**
74
+ * Xác thực và tự động cập nhật Bearer Token cho Client
75
+ *
76
+ * @param mobile Số điện thoại tài khoản (mặc định lấy từ cấu hình khi khởi tạo)
77
+ * @returns Chuỗi token mới nhận được
78
+ */
79
+ async authenticate(mobile) {
80
+ const res = await this.accounts.authenticateToken(mobile ? { mobile } : undefined);
81
+ return res.token;
82
+ }
83
+ }
84
+ exports.AhamoveClient = AhamoveClient;
85
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AACA,uCAA0C;AAC1C,4DAAwD;AACxD,gEAA4D;AAC5D,wEAAmE;AACnE,gEAA4D;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAa,aAAa;IAuBxB,YAA6B,SAA8B,EAAE;QAAhC,WAAM,GAAN,MAAM,CAA0B;QAC3D,IAAI,CAAC,IAAI,GAAG,IAAI,iBAAU,CAAC,MAAM,CAAC,CAAC;QAEnC,IAAI,CAAC,QAAQ,GAAG,IAAI,gCAAc,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM,GAAG,IAAI,4BAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1C,IAAI,CAAC,UAAU,GAAG,IAAI,uCAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnD,IAAI,CAAC,OAAO,GAAG,IAAI,gCAAc,EAAE,CAAC;QAEpC,2DAA2D;QAC3D,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,KAAK,IAAI,EAAE;YAC1C,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;gBAC7C,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,mDAAmD,CAAC,CAAC;gBAClF,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,iBAAiB,EAAE,CAAC;gBACpD,OAAO,GAAG,CAAC,KAAK,CAAC;YACnB,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,QAAQ,CAAC,KAAa;QAC3B,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;IAC5B,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;IAC9B,CAAC;IAED;;;;;OAKG;IACI,KAAK,CAAC,YAAY,CAAC,MAAe;QACvC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QACnF,OAAO,GAAG,CAAC,KAAK,CAAC;IACnB,CAAC;CACF;AAnED,sCAmEC"}
@@ -0,0 +1,19 @@
1
+ import { AhamoveEnvironment } from './types/common';
2
+ /**
3
+ * Danh sách Base URL máy chủ API Ahamove theo từng môi trường
4
+ */
5
+ export declare const AHAMOVE_API_HOSTS: Record<AhamoveEnvironment, string>;
6
+ /**
7
+ * Cổng quản trị Partner Portal
8
+ */
9
+ export declare const AHAMOVE_PARTNER_PORTALS: Record<AhamoveEnvironment, string>;
10
+ /**
11
+ * Cấu hình mặc định cho Client
12
+ */
13
+ export declare const DEFAULT_CONFIG: {
14
+ environment: AhamoveEnvironment;
15
+ timeout: number;
16
+ retries: number;
17
+ autoRefreshToken: boolean;
18
+ };
19
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,kBAAkB,EAAE,MAAM,CAGhE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,uBAAuB,EAAE,MAAM,CAAC,kBAAkB,EAAE,MAAM,CAGtE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc;iBACC,kBAAkB;;;;CAI7C,CAAC"}
package/dist/config.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_CONFIG = exports.AHAMOVE_PARTNER_PORTALS = exports.AHAMOVE_API_HOSTS = void 0;
4
+ /**
5
+ * Danh sách Base URL máy chủ API Ahamove theo từng môi trường
6
+ */
7
+ exports.AHAMOVE_API_HOSTS = {
8
+ staging: 'https://partner-apistg.ahamove.com',
9
+ production: 'https://partner-api.ahamove.com',
10
+ };
11
+ /**
12
+ * Cổng quản trị Partner Portal
13
+ */
14
+ exports.AHAMOVE_PARTNER_PORTALS = {
15
+ staging: 'https://partnerstg.ahamove.com/v2/records',
16
+ production: 'https://partner.ahamove.com/v2/records',
17
+ };
18
+ /**
19
+ * Cấu hình mặc định cho Client
20
+ */
21
+ exports.DEFAULT_CONFIG = {
22
+ environment: 'staging',
23
+ timeout: 30000,
24
+ retries: 2,
25
+ autoRefreshToken: true,
26
+ };
27
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":";;;AAEA;;GAEG;AACU,QAAA,iBAAiB,GAAuC;IACnE,OAAO,EAAE,oCAAoC;IAC7C,UAAU,EAAE,iCAAiC;CAC9C,CAAC;AAEF;;GAEG;AACU,QAAA,uBAAuB,GAAuC;IACzE,OAAO,EAAE,2CAA2C;IACpD,UAAU,EAAE,wCAAwC;CACrD,CAAC;AAEF;;GAEG;AACU,QAAA,cAAc,GAAG;IAC5B,WAAW,EAAE,SAA+B;IAC5C,OAAO,EAAE,KAAK;IACd,OAAO,EAAE,CAAC;IACV,gBAAgB,EAAE,IAAI;CACvB,CAAC"}
@@ -0,0 +1,64 @@
1
+ import { AhamoveErrorCode } from './error-codes';
2
+ /**
3
+ * Lớp biểu diễn lỗi chuẩn hóa từ Ahamove API
4
+ */
5
+ export declare class AhamoveApiError extends Error {
6
+ /**
7
+ * Mã trạng thái HTTP (ví dụ: 400, 401, 404, 406, 409, 500)
8
+ */
9
+ readonly statusCode: number;
10
+ /**
11
+ * Mã lỗi logic từ Ahamove (ví dụ: `MISSING_REQUIRED_INFO`, `NOT_AUTHORIZED`, `NOT_ENOUGH_CREDIT`)
12
+ */
13
+ readonly errorCode: AhamoveErrorCode | string;
14
+ /**
15
+ * Diễn giải chi tiết ý nghĩa lỗi bằng tiếng Việt
16
+ */
17
+ readonly description: string;
18
+ /**
19
+ * Phản hồi gốc nhận được từ máy chủ Ahamove (nếu có)
20
+ */
21
+ readonly rawResponse?: unknown;
22
+ constructor(options: {
23
+ message?: string;
24
+ statusCode: number;
25
+ errorCode?: AhamoveErrorCode | string;
26
+ rawResponse?: unknown;
27
+ });
28
+ /**
29
+ * Kiểm tra lỗi có phải do token không hợp lệ hoặc hết hạn (401 NOT_AUTHORIZED) hay không
30
+ */
31
+ isUnauthorized(): boolean;
32
+ /**
33
+ * Kiểm tra lỗi có phải do không đủ số dư tài khoản trả trước để tạo đơn hay không
34
+ */
35
+ isInsufficientCredit(): boolean;
36
+ /**
37
+ * Kiểm tra lỗi có phải do khoảng cách vượt quá giới hạn dịch vụ hay không
38
+ */
39
+ isInvalidDistance(): boolean;
40
+ /**
41
+ * Kiểm tra lỗi có phải do trùng mã đơn nội bộ tracking_number hay không
42
+ */
43
+ isDuplicateTrackingNumber(): boolean;
44
+ /**
45
+ * Kiểm tra lỗi có phải do đơn hàng không thể hủy (đã lấy hàng hoặc đã hoàn thành)
46
+ */
47
+ isOrderCannotBeCancelled(): boolean;
48
+ /**
49
+ * Kiểm tra lỗi thiếu trường thông tin bắt buộc
50
+ */
51
+ isMissingRequiredInfo(): boolean;
52
+ /**
53
+ * Chuyển đổi lỗi thành object JSON thân thiện
54
+ */
55
+ toJSON(): {
56
+ name: string;
57
+ statusCode: number;
58
+ errorCode: string;
59
+ message: string;
60
+ description: string;
61
+ rawResponse: unknown;
62
+ };
63
+ }
64
+ //# sourceMappingURL=ahamove-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ahamove-error.d.ts","sourceRoot":"","sources":["../../src/errors/ahamove-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEzE;;GAEG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC;;OAEG;IACH,SAAgB,UAAU,EAAE,MAAM,CAAC;IAEnC;;OAEG;IACH,SAAgB,SAAS,EAAE,gBAAgB,GAAG,MAAM,CAAC;IAErD;;OAEG;IACH,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC;;OAEG;IACH,SAAgB,WAAW,CAAC,EAAE,OAAO,CAAC;gBAE1B,OAAO,EAAE;QACnB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,MAAM,CAAC;QACnB,SAAS,CAAC,EAAE,gBAAgB,GAAG,MAAM,CAAC;QACtC,WAAW,CAAC,EAAE,OAAO,CAAC;KACvB;IAgBD;;OAEG;IACI,cAAc,IAAI,OAAO;IAIhC;;OAEG;IACI,oBAAoB,IAAI,OAAO;IAItC;;OAEG;IACI,iBAAiB,IAAI,OAAO;IAOnC;;OAEG;IACI,yBAAyB,IAAI,OAAO;IAI3C;;OAEG;IACI,wBAAwB,IAAI,OAAO;IAI1C;;OAEG;IACI,qBAAqB,IAAI,OAAO;IAIvC;;OAEG;IACI,MAAM;;;;;;;;CAUd"}
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AhamoveApiError = void 0;
4
+ const error_codes_1 = require("./error-codes");
5
+ /**
6
+ * Lớp biểu diễn lỗi chuẩn hóa từ Ahamove API
7
+ */
8
+ class AhamoveApiError extends Error {
9
+ constructor(options) {
10
+ const code = options.errorCode || error_codes_1.AhamoveErrorCode.UNKNOWN_ERROR;
11
+ const defaultDesc = error_codes_1.AHAMOVE_ERROR_MESSAGES[code] || 'Lỗi xử lý API từ Ahamove';
12
+ const finalMessage = options.message || defaultDesc;
13
+ super(`[AhamoveApiError ${options.statusCode}:${code}] ${finalMessage}`);
14
+ this.name = 'AhamoveApiError';
15
+ this.statusCode = options.statusCode;
16
+ this.errorCode = code;
17
+ this.description = defaultDesc;
18
+ this.rawResponse = options.rawResponse;
19
+ // Giữ nguyên prototype chain cho instanceof
20
+ Object.setPrototypeOf(this, AhamoveApiError.prototype);
21
+ }
22
+ /**
23
+ * Kiểm tra lỗi có phải do token không hợp lệ hoặc hết hạn (401 NOT_AUTHORIZED) hay không
24
+ */
25
+ isUnauthorized() {
26
+ return this.statusCode === 401 || this.errorCode === error_codes_1.AhamoveErrorCode.NOT_AUTHORIZED;
27
+ }
28
+ /**
29
+ * Kiểm tra lỗi có phải do không đủ số dư tài khoản trả trước để tạo đơn hay không
30
+ */
31
+ isInsufficientCredit() {
32
+ return this.errorCode === error_codes_1.AhamoveErrorCode.NOT_ENOUGH_CREDIT;
33
+ }
34
+ /**
35
+ * Kiểm tra lỗi có phải do khoảng cách vượt quá giới hạn dịch vụ hay không
36
+ */
37
+ isInvalidDistance() {
38
+ return (this.errorCode === error_codes_1.AhamoveErrorCode.INVALID_MAX_DISTANCE ||
39
+ this.errorCode === error_codes_1.AhamoveErrorCode.INVALID_MIN_DISTANCE);
40
+ }
41
+ /**
42
+ * Kiểm tra lỗi có phải do trùng mã đơn nội bộ tracking_number hay không
43
+ */
44
+ isDuplicateTrackingNumber() {
45
+ return this.errorCode === error_codes_1.AhamoveErrorCode.DUPLICATE_TRACKING_NUMBER;
46
+ }
47
+ /**
48
+ * Kiểm tra lỗi có phải do đơn hàng không thể hủy (đã lấy hàng hoặc đã hoàn thành)
49
+ */
50
+ isOrderCannotBeCancelled() {
51
+ return this.errorCode === error_codes_1.AhamoveErrorCode.ORDER_CANNOT_BE_CANCELLED;
52
+ }
53
+ /**
54
+ * Kiểm tra lỗi thiếu trường thông tin bắt buộc
55
+ */
56
+ isMissingRequiredInfo() {
57
+ return this.errorCode === error_codes_1.AhamoveErrorCode.MISSING_REQUIRED_INFO;
58
+ }
59
+ /**
60
+ * Chuyển đổi lỗi thành object JSON thân thiện
61
+ */
62
+ toJSON() {
63
+ return {
64
+ name: this.name,
65
+ statusCode: this.statusCode,
66
+ errorCode: this.errorCode,
67
+ message: this.message,
68
+ description: this.description,
69
+ rawResponse: this.rawResponse,
70
+ };
71
+ }
72
+ }
73
+ exports.AhamoveApiError = AhamoveApiError;
74
+ //# sourceMappingURL=ahamove-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ahamove-error.js","sourceRoot":"","sources":["../../src/errors/ahamove-error.ts"],"names":[],"mappings":";;;AAAA,+CAAyE;AAEzE;;GAEG;AACH,MAAa,eAAgB,SAAQ,KAAK;IAqBxC,YAAY,OAKX;QACC,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,IAAI,8BAAgB,CAAC,aAAa,CAAC;QACjE,MAAM,WAAW,GAAI,oCAAiD,CAAC,IAAI,CAAC,IAAI,0BAA0B,CAAC;QAC3G,MAAM,YAAY,GAAG,OAAO,CAAC,OAAO,IAAI,WAAW,CAAC;QAEpD,KAAK,CAAC,oBAAoB,OAAO,CAAC,UAAU,IAAI,IAAI,KAAK,YAAY,EAAE,CAAC,CAAC;QACzE,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QAEvC,4CAA4C;QAC5C,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,eAAe,CAAC,SAAS,CAAC,CAAC;IACzD,CAAC;IAED;;OAEG;IACI,cAAc;QACnB,OAAO,IAAI,CAAC,UAAU,KAAK,GAAG,IAAI,IAAI,CAAC,SAAS,KAAK,8BAAgB,CAAC,cAAc,CAAC;IACvF,CAAC;IAED;;OAEG;IACI,oBAAoB;QACzB,OAAO,IAAI,CAAC,SAAS,KAAK,8BAAgB,CAAC,iBAAiB,CAAC;IAC/D,CAAC;IAED;;OAEG;IACI,iBAAiB;QACtB,OAAO,CACL,IAAI,CAAC,SAAS,KAAK,8BAAgB,CAAC,oBAAoB;YACxD,IAAI,CAAC,SAAS,KAAK,8BAAgB,CAAC,oBAAoB,CACzD,CAAC;IACJ,CAAC;IAED;;OAEG;IACI,yBAAyB;QAC9B,OAAO,IAAI,CAAC,SAAS,KAAK,8BAAgB,CAAC,yBAAyB,CAAC;IACvE,CAAC;IAED;;OAEG;IACI,wBAAwB;QAC7B,OAAO,IAAI,CAAC,SAAS,KAAK,8BAAgB,CAAC,yBAAyB,CAAC;IACvE,CAAC;IAED;;OAEG;IACI,qBAAqB;QAC1B,OAAO,IAAI,CAAC,SAAS,KAAK,8BAAgB,CAAC,qBAAqB,CAAC;IACnE,CAAC;IAED;;OAEG;IACI,MAAM;QACX,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,WAAW,EAAE,IAAI,CAAC,WAAW;SAC9B,CAAC;IACJ,CAAC;CACF;AApGD,0CAoGC"}