client.ts
10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// vibe_erp typed REST client.
//
// **Why a thin wrapper instead of a generated client.** The framework
// already serves a real OpenAPI spec at /v3/api-docs and could feed
// openapi-typescript or openapi-generator-cli — but every code
// generator pulls a chain of npm/Java toolchain steps into the build
// and generates ~thousands of lines of churn for every backend tweak.
// A hand-written client over `fetch` keeps the SPA bundle small,
// auditable, and dependency-free, and v1 of the SPA only needs the
// few dozen calls listed below. Codegen can return when (a) the
// API surface is too large to maintain by hand or (b) external
// integrators want a typed client they can reuse — neither is true
// in v1.0.
//
// **Auth.** Every call goes through `apiFetch`, which reads the
// access token from localStorage and adds an `Authorization: Bearer
// <token>` header. A 401 response triggers a hard logout (clears
// the token + redirects to /login via the auth context) — not a
// silent refresh, because v1 keeps the refresh story simple.
// Refreshing on 401 is a v1.x improvement.
//
// **Errors.** A non-2xx response throws an `ApiError` carrying the
// status, message, and the parsed JSON body if any. Pages catch
// this and render the message inline. Network failures throw the
// underlying TypeError, also caught by the page boundary.
import type {
Item,
JournalEntry,
Location,
MetaInfo,
Partner,
PurchaseOrder,
Role,
SalesOrder,
ShopFloorEntry,
StockBalance,
StockMovement,
TokenPair,
Uom,
User,
WorkOrder,
} from '@/types/api'
const TOKEN_KEY = 'vibeerp.accessToken'
export function getAccessToken(): string | null {
return localStorage.getItem(TOKEN_KEY)
}
export function setAccessToken(token: string | null): void {
if (token === null) {
localStorage.removeItem(TOKEN_KEY)
} else {
localStorage.setItem(TOKEN_KEY, token)
}
}
export class ApiError extends Error {
constructor(
message: string,
public readonly status: number,
public readonly body: unknown,
) {
super(message)
this.name = 'ApiError'
}
}
// One-time-set callback that the auth context registers so the
// client can trigger a logout on 401 without a circular import.
let onUnauthorized: (() => void) | null = null
export function registerUnauthorizedHandler(handler: () => void) {
onUnauthorized = handler
}
async function apiFetch<T>(
path: string,
init: RequestInit = {},
expectJson = true,
): Promise<T> {
const headers = new Headers(init.headers)
headers.set('Accept', 'application/json')
if (init.body && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json')
}
const token = getAccessToken()
if (token) headers.set('Authorization', `Bearer ${token}`)
const res = await fetch(path, { ...init, headers })
if (res.status === 401) {
if (onUnauthorized) onUnauthorized()
throw new ApiError('Not authenticated', 401, null)
}
if (!res.ok) {
let body: unknown = null
let message = `${res.status} ${res.statusText}`
try {
const text = await res.text()
if (text) {
try {
body = JSON.parse(text)
const m = (body as { message?: unknown }).message
if (typeof m === 'string') message = m
} catch {
body = text
message = text
}
}
} catch {
// ignore body parse errors
}
throw new ApiError(message, res.status, body)
}
if (!expectJson || res.status === 204) {
return undefined as T
}
return (await res.json()) as T
}
// ─── Public unauthenticated calls ────────────────────────────────────
export const meta = {
info: () => apiFetch<MetaInfo>('/api/v1/_meta/info'),
}
export const auth = {
login: (username: string, password: string) =>
apiFetch<TokenPair>('/api/v1/auth/login', {
method: 'POST',
body: JSON.stringify({ username, password }),
}),
}
// ─── Identity ────────────────────────────────────────────────────────
export const identity = {
listUsers: () => apiFetch<User[]>('/api/v1/identity/users'),
getUser: (id: string) => apiFetch<User>(`/api/v1/identity/users/${id}`),
createUser: (body: {
username: string; displayName: string; email?: string | null
}) => apiFetch<User>('/api/v1/identity/users', { method: 'POST', body: JSON.stringify(body) }),
listRoles: () => apiFetch<Role[]>('/api/v1/identity/roles'),
createRole: (body: {
code: string; name: string; description?: string | null
}) => apiFetch<Role>('/api/v1/identity/roles', { method: 'POST', body: JSON.stringify(body) }),
getUserRoles: (userId: string) => apiFetch<string[]>(`/api/v1/identity/users/${userId}/roles`),
assignRole: (userId: string, roleCode: string) =>
apiFetch<void>(`/api/v1/identity/users/${userId}/roles/${roleCode}`, { method: 'POST' }, false),
revokeRole: (userId: string, roleCode: string) =>
apiFetch<void>(`/api/v1/identity/users/${userId}/roles/${roleCode}`, { method: 'DELETE' }, false),
}
// ─── Catalog ─────────────────────────────────────────────────────────
export const catalog = {
listItems: () => apiFetch<Item[]>('/api/v1/catalog/items'),
getItem: (id: string) => apiFetch<Item>(`/api/v1/catalog/items/${id}`),
createItem: (body: {
code: string; name: string; description?: string | null;
itemType: string; baseUomCode: string; active?: boolean
}) => apiFetch<Item>('/api/v1/catalog/items', { method: 'POST', body: JSON.stringify(body) }),
listUoms: () => apiFetch<Uom[]>('/api/v1/catalog/uoms'),
}
// ─── Partners ────────────────────────────────────────────────────────
export const partners = {
list: () => apiFetch<Partner[]>('/api/v1/partners/partners'),
get: (id: string) => apiFetch<Partner>(`/api/v1/partners/partners/${id}`),
create: (body: {
code: string; name: string; type: string;
email?: string | null; phone?: string | null;
taxId?: string | null; website?: string | null
}) => apiFetch<Partner>('/api/v1/partners/partners', { method: 'POST', body: JSON.stringify(body) }),
}
// ─── Inventory ───────────────────────────────────────────────────────
export const inventory = {
listLocations: () => apiFetch<Location[]>('/api/v1/inventory/locations'),
listBalances: () => apiFetch<StockBalance[]>('/api/v1/inventory/balances'),
listMovements: () => apiFetch<StockMovement[]>('/api/v1/inventory/movements'),
}
// ─── Sales orders ────────────────────────────────────────────────────
export const salesOrders = {
list: () => apiFetch<SalesOrder[]>('/api/v1/orders/sales-orders'),
get: (id: string) => apiFetch<SalesOrder>(`/api/v1/orders/sales-orders/${id}`),
create: (body: {
code: string
partnerCode: string
orderDate: string
currencyCode: string
lines: { lineNo: number; itemCode: string; quantity: number; unitPrice: number; currencyCode: string }[]
}) =>
apiFetch<SalesOrder>('/api/v1/orders/sales-orders', {
method: 'POST',
body: JSON.stringify(body),
}),
confirm: (id: string) =>
apiFetch<SalesOrder>(`/api/v1/orders/sales-orders/${id}/confirm`, {
method: 'POST',
}),
cancel: (id: string) =>
apiFetch<SalesOrder>(`/api/v1/orders/sales-orders/${id}/cancel`, {
method: 'POST',
}),
ship: (id: string, shippingLocationCode: string) =>
apiFetch<SalesOrder>(`/api/v1/orders/sales-orders/${id}/ship`, {
method: 'POST',
body: JSON.stringify({ shippingLocationCode }),
}),
}
// ─── Purchase orders ─────────────────────────────────────────────────
export const purchaseOrders = {
list: () => apiFetch<PurchaseOrder[]>('/api/v1/orders/purchase-orders'),
get: (id: string) => apiFetch<PurchaseOrder>(`/api/v1/orders/purchase-orders/${id}`),
create: (body: {
code: string; partnerCode: string; orderDate: string;
expectedDate?: string | null; currencyCode: string;
lines: { lineNo: number; itemCode: string; quantity: number; unitPrice: number; currencyCode: string }[]
}) => apiFetch<PurchaseOrder>('/api/v1/orders/purchase-orders', { method: 'POST', body: JSON.stringify(body) }),
confirm: (id: string) =>
apiFetch<PurchaseOrder>(`/api/v1/orders/purchase-orders/${id}/confirm`, {
method: 'POST',
}),
cancel: (id: string) =>
apiFetch<PurchaseOrder>(`/api/v1/orders/purchase-orders/${id}/cancel`, {
method: 'POST',
}),
receive: (id: string, receivingLocationCode: string) =>
apiFetch<PurchaseOrder>(`/api/v1/orders/purchase-orders/${id}/receive`, {
method: 'POST',
body: JSON.stringify({ receivingLocationCode }),
}),
}
// ─── Production ──────────────────────────────────────────────────────
export const production = {
listWorkOrders: () => apiFetch<WorkOrder[]>('/api/v1/production/work-orders'),
getWorkOrder: (id: string) =>
apiFetch<WorkOrder>(`/api/v1/production/work-orders/${id}`),
createWorkOrder: (body: {
code: string; outputItemCode: string; outputQuantity: number;
dueDate?: string | null; sourceSalesOrderCode?: string | null;
inputs?: { lineNo: number; itemCode: string; quantityPerUnit: number; sourceLocationCode: string }[];
operations?: { lineNo: number; operationCode: string; workCenter: string; standardMinutes: number }[];
}) => apiFetch<WorkOrder>('/api/v1/production/work-orders', { method: 'POST', body: JSON.stringify(body) }),
startWorkOrder: (id: string) =>
apiFetch<WorkOrder>(`/api/v1/production/work-orders/${id}/start`, {
method: 'POST',
}),
completeWorkOrder: (id: string, outputLocationCode: string) =>
apiFetch<WorkOrder>(`/api/v1/production/work-orders/${id}/complete`, {
method: 'POST',
body: JSON.stringify({ outputLocationCode }),
}),
cancelWorkOrder: (id: string) =>
apiFetch<WorkOrder>(`/api/v1/production/work-orders/${id}/cancel`, {
method: 'POST',
}),
shopFloor: () =>
apiFetch<ShopFloorEntry[]>('/api/v1/production/work-orders/shop-floor'),
}
// ─── Finance ─────────────────────────────────────────────────────────
export const finance = {
listJournalEntries: () =>
apiFetch<JournalEntry[]>('/api/v1/finance/journal-entries'),
}