koombiyo-delivery-sdk 0.0.0-stage → 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.
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
- # Temporary Holding Version
1
+ # koombiyo-delivery-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Unofficial, fully-typed TypeScript SDK for the **Koombiyo Delivery Clients' API (v2)**: order creation, waybill tracking, proof of delivery, pickups and return management.
4
+
5
+ - Zero runtime dependencies (uses the built-in `fetch`, Node ≥ 18, works in modern runtimes too)
6
+ - ESM + CJS builds with bundled `.d.ts`
7
+ - Automatic login, token refresh (with rotation) and one-shot retry on `401`
8
+ - Typed errors, async-iterator pagination, PDF endpoints returning `Uint8Array`
9
+ - Webhook receiver helpers (framework-agnostic)
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install koombiyo-sdk
15
+ ```
16
+
17
+ ## Quick start
18
+
19
+ ```ts
20
+ import { KoombiyoClient } from 'koombiyo-delivery-sdk';
21
+
22
+ const koombiyo = new KoombiyoClient({
23
+ apiKey: process.env.KOOMBIYO_API_KEY!,
24
+ password: process.env.KOOMBIYO_PASSWORD!,
25
+ });
26
+
27
+ const { waybills } = await koombiyo.orders.activeWaybills();
28
+
29
+ await koombiyo.orders.add({
30
+ waybillId: waybills[0]!.waybillId,
31
+ orderNumber: 'ORD-99812',
32
+ customerName: 'Nimal Silva',
33
+ customerPhone: '0712345678',
34
+ customerAddress: 'No. 45, Temple Road',
35
+ customerDistrictId: 10,
36
+ description: 'Clothes',
37
+ codAmount: 2500,
38
+ productValue: 2500,
39
+ });
40
+
41
+ await koombiyo.logout(); // revoke the session when your job is done
42
+ ```
43
+
44
+ You never call `login` yourself: the first request logs in, and an expired access token is refreshed transparently.
45
+
46
+ ## Configuration
47
+
48
+ | Option | Default | Description |
49
+ | --- | --- | --- |
50
+ | `apiKey`, `password` | – | Credentials from the client portal (required) |
51
+ | `baseUrl` | `https://client.koombiyodelivery.lk/clientapi/v2` | Override for staging/proxies |
52
+ | `timeoutMs` | `30000` | Per-request timeout |
53
+ | `fetch` | global `fetch` | Custom implementation (tests, proxies) |
54
+ | `tokenStore` | in-memory | Implement `TokenStore` to persist tokens (Redis, DB, file…) |
55
+ | `notFoundAsEmpty` | `true` | Turn "nothing found" 404s on list endpoints into empty results |
56
+
57
+ ## API map
58
+
59
+ | Resource | Methods → endpoint |
60
+ | --- | --- |
61
+ | `auth` | `login()` `refresh()` `logout()` `tokens()` |
62
+ | `dashboard` | `get()` → `/dashboard` |
63
+ | `locations` | `districts()` `cities({districtId, cityName?})` (served from bundled JSON, no API call) |
64
+ | `deliveryRates` | `list()` `iterate()` → `/delivery_rates` |
65
+ | `orders` | `add` `addBulk` `addExchange` `delete` `activeWaybills` `list` `iterate` `details` `timeline` `customerSuccessRate` `exchangeBagWaybills` `requestWaybills` `requestExchangeBags` |
66
+ | `pickups` | `add` `list` `iterate` |
67
+ | `notifications` | `list` `iterate` |
68
+ | `pod` | `single(waybillId, format)` `bulk(ids, format)` `day({date, format})` → PDF bytes |
69
+ | `returns` | `orders` `iterateOrders` `pending` `markReceived` `markManyReceived` `notes` `noteItems` `markNoteReceived` |
70
+ | `webhooks` | `test(targetUrl, payload)` |
71
+
72
+ Request fields are written in **camelCase** (`waybillId`, `codAmount`…) and converted to the API's snake_case (`waybill_id`, `cod_amount`…) just before sending. Response fields (and webhook payloads) are converted the other way: `delivery_rates` → `deliveryRates`, `total_count` → `totalCount`. Error bodies (`KoombiyoApiError.body`) are kept raw. Ids/amounts may be passed as `string | number` (numbers are stringified for you) and date filters accept `'YYYY-MM-DD'` or a `Date`.
73
+
74
+ ### Pagination
75
+
76
+ ```ts
77
+ for await (const order of koombiyo.orders.iterate({ fromDate: '2026-08-01', pageSize: 100 })) {
78
+ console.log(order);
79
+ }
80
+ ```
81
+
82
+ ### PDFs
83
+
84
+ ```ts
85
+ import { writeFile } from 'node:fs/promises';
86
+ await writeFile('waybills.pdf', await koombiyo.pod.bulk(['102938475', '102938476'], 'A6'));
87
+ ```
88
+
89
+ ### Response row types
90
+
91
+ Rows whose shape the docs don't describe are typed `UnknownRecord`. Pass your own type through the generic:
92
+
93
+ ```ts
94
+ interface MyOrder { waybillId: string; currentStatus: number }
95
+ const { orders } = await koombiyo.orders.list<MyOrder>({ limit: 20 });
96
+ ```
97
+
98
+ ## Errors
99
+
100
+ All errors extend `KoombiyoError`.
101
+
102
+ | Class | When |
103
+ | --- | --- |
104
+ | `KoombiyoApiError` | any non-2xx (`status`, `endpoint`, parsed `body`) |
105
+ | `KoombiyoAuthenticationError` | 401 (after the automatic refresh/re-login also failed) |
106
+ | `KoombiyoNotFoundError` | 404 |
107
+ | `KoombiyoBusinessRuleError` | 2xx response whose message says it was **not** done (pickup 3 PM cut-off) |
108
+ | `KoombiyoValidationError` | caught client-side before sending (empty bulk lists, exchange bags < 10) |
109
+ | `KoombiyoNetworkError` / `KoombiyoTimeoutError` | transport failures |
110
+
111
+ ```ts
112
+ try {
113
+ await koombiyo.pickups.add({ vehicleType: 'Bike', pickupQty: 5, pickupAddress: '…' });
114
+ } catch (e) {
115
+ if (e instanceof KoombiyoBusinessRuleError) console.warn(e.message); // "…before 3.00 pm…"
116
+ else throw e;
117
+ }
118
+ ```
119
+
120
+ Partial success: `orders.addBulk` and `returns.markManyReceived` return HTTP 201 even when some items fail – always inspect the returned `message` (`"X added, Y failed"`).
121
+
122
+ ## Webhooks (Koombiyo → your server)
123
+
124
+ Koombiyo POSTs a status update on every waybill status change and retries any non-200 reply, so **handlers must be idempotent**.
125
+
126
+ ```ts
127
+ import { handleWebhook, webhookEventKey } from 'koombiyo-sdk';
128
+
129
+ app.post('/api/webhook', async (req, res) => {
130
+ const result = await handleWebhook(req.body, async (event) => {
131
+ if (await alreadyProcessed(webhookEventKey(event))) return;
132
+ await updateOrder(event.waybillId, event.status, event.reason);
133
+ });
134
+ res.status(result.status).json(result.body); // 200 ok · 400 bad payload · 500 handler threw → retry
135
+ });
136
+ ```
137
+
138
+ `koombiyo.webhooks.test(url, payload)` makes Koombiyo call your URL and reports what it answered. A full `node:http` receiver is in [`examples/webhook-server.ts`](examples/webhook-server.ts).
139
+
140
+ > The documentation describes no signature or secret on webhook calls. Use an unguessable URL path and/or IP allow-listing.
141
+
142
+ ## Business rules from the docs
143
+
144
+ Exposed as `LIMITS`: COD between LKR 100 and 500 000 (enforced by the server) · minimum 10 exchange bags · pickup requests only before 15:00 and one per day · orders can only be deleted while pending (status 1). Known status ids: `OrderStatus.PENDING = 1`, `PENDING_RETURN = 9`, `RETURN_RECEIVED = 15`.
145
+
146
+ ## Assumptions & gaps in the documentation
147
+
148
+ The PDF is precise about endpoints and request fields but thin on response bodies, so this SDK makes a few careful choices. Please verify against the live API and adjust if needed:
149
+
150
+ 1. **Token field names** aren't specified. The SDK accepts `access_token` / `accessToken` / `token` and `refresh_token` / `refreshToken`, at the top level or under `data` / `tokens` / `result` (see `extractTokens` in `src/core/session.ts`).
151
+ 2. **Row shapes** (orders, timeline, notifications, pickups, dashboard rows…) are undocumented → `UnknownRecord`, overridable via generics.
152
+ 3. **POD `CUSTOM` format** is listed in the description but absent from the 400 error text – it may be rejected.
153
+ 4. **`/active_waybills`** says it "supports pagination and keyword search" but documents no parameters, so none are exposed.
154
+ 5. **`/request_exchange_bags`** documents barcode/POD success messages; the SDK just returns whatever `message` arrives.
155
+ 6. **Login location mismatch** (HTTP 400) hints that credentials may be tied to an IP/location – call from the registered environment.
156
+
157
+ ## Development
158
+
159
+ ```bash
160
+ npm install
161
+ npm run typecheck
162
+ npm test
163
+ npm run build
164
+ ```
165
+
166
+ ```
167
+ src/
168
+ ├── client.ts # KoombiyoClient – wires everything together
169
+ ├── index.ts # public exports
170
+ ├── core/ # config, transport (fetch/timeouts), session (tokens), api-client (auth + retry), errors, utils
171
+ ├── resources/ # one class per API section
172
+ ├── types/ # request/response types per API section
173
+ └── webhooks/ # inbound webhook parsing + handler
174
+ tests/ # vitest, fetch mocked
175
+ examples/ # quickstart + webhook server
176
+ ```
177
+
178
+ Not affiliated with Koombiyo Delivery. Questions about the API itself: system@koombiyodelivery.com.