forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdraft-service.ts
More file actions
337 lines (315 loc) · 8.84 KB
/
Copy pathdraft-service.ts
File metadata and controls
337 lines (315 loc) · 8.84 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import axios from 'axios';
import { API_URL } from '@env';
import AsyncStorage from '@react-native-async-storage/async-storage';
import type {
DraftInvoice,
CreateDraftDto,
UpdateDraftDto,
DraftListResponse,
DiscardDraftResponse,
LocalDraft,
} from '../types/draft.types';
const DRAFT_STORAGE_KEY = '@invoisio_local_drafts';
/**
* DraftService handles all draft-related API operations on mobile
* Provides methods for creating, updating, retrieving, and managing invoice drafts
* with offline support
*/
export class DraftService {
private static readonly BASE_PATH = '/invoices/draft';
/**
* Create a new draft invoice
* @param token - Access token for authentication
* @param dto - Draft creation data
* @returns The created draft
*/
static async createDraft(
token: string,
dto: CreateDraftDto,
): Promise<DraftInvoice> {
const response = await axios.post(
`${API_URL}${this.BASE_PATH}`,
dto,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
return response.data as DraftInvoice;
}
/**
* Get all drafts for the authenticated merchant
* @param token - Access token for authentication
* @param page - Page number (1-indexed)
* @param limit - Items per page
* @returns Paginated draft list
*/
static async getDrafts(
token: string,
page = 1,
limit = 20,
): Promise<DraftListResponse> {
const params = new URLSearchParams({
page: String(page),
limit: String(limit),
}).toString();
const response = await axios.get(
`${API_URL}${this.BASE_PATH}?${params}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
return response.data as DraftListResponse;
}
/**
* Get a specific draft by ID
* @param token - Access token for authentication
* @param id - Draft UUID
* @returns The draft data
*/
static async getDraft(token: string, id: string): Promise<DraftInvoice> {
const response = await axios.get(
`${API_URL}${this.BASE_PATH}/${id}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
return response.data as DraftInvoice;
}
/**
* Update a draft (full update)
* @param token - Access token for authentication
* @param id - Draft UUID
* @param updates - Draft update data
* @returns Updated draft
*/
static async updateDraft(
token: string,
id: string,
updates: UpdateDraftDto,
): Promise<DraftInvoice> {
const response = await axios.patch(
`${API_URL}${this.BASE_PATH}/${id}`,
updates,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
return response.data as DraftInvoice;
}
/**
* Auto-save a draft (optimized for frequent calls)
* @param token - Access token for authentication
* @param id - Draft UUID
* @param updates - Draft update data
* @returns Updated draft
*/
static async autoSaveDraft(
token: string,
id: string,
updates: UpdateDraftDto,
): Promise<DraftInvoice> {
const response = await axios.patch(
`${API_URL}${this.BASE_PATH}/${id}/autosave`,
{
...updates,
autoSave: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
return response.data as DraftInvoice;
}
/**
* Convert a draft to a real invoice
* @param token - Access token for authentication
* @param id - Draft UUID
* @returns The converted invoice
*/
static async convertDraftToInvoice(token: string, id: string): Promise<unknown> {
const response = await axios.post(
`${API_URL}${this.BASE_PATH}/${id}/convert`,
{},
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
return response.data;
}
/**
* Discard/delete a draft
* @param token - Access token for authentication
* @param id - Draft UUID
* @returns Discard confirmation
*/
static async discardDraft(token: string, id: string): Promise<DiscardDraftResponse> {
const response = await axios.delete(
`${API_URL}${this.BASE_PATH}/${id}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
return response.data as DiscardDraftResponse;
}
/**
* Check if a draft has all required fields to be converted to an invoice
* @param draft - Draft invoice data
* @returns Boolean indicating if draft is complete
*/
static isDraftComplete(draft: Partial<DraftInvoice>): boolean {
return !!(draft.clientName?.trim() &&
draft.clientEmail?.trim() &&
draft.amount &&
draft.amount > 0 &&
draft.assetCode);
}
/**
* Get the completion percentage of a draft
* @param draft - Draft invoice data
* @returns Completion percentage (0-100)
*/
static getCompletionPercentage(draft: Partial<DraftInvoice>): number {
const fields = [
{ key: 'invoiceNumber', weight: 1 },
{ key: 'clientName', weight: 1 },
{ key: 'clientEmail', weight: 1 },
{ key: 'description', weight: 0.5 },
{ key: 'amount', weight: 1 },
{ key: 'assetCode', weight: 1 },
{ key: 'dueDate', weight: 0.5 },
];
let totalWeight = 0;
let filledWeight = 0;
for (const field of fields) {
totalWeight += field.weight;
const value = draft[field.key as keyof typeof draft];
if (value !== undefined && value !== null && value !== '') {
filledWeight += field.weight;
}
}
return Math.round((filledWeight / totalWeight) * 100);
}
/**
* Save draft locally for offline support
* @param draft - Draft data to save locally
*/
static async saveLocalDraft(draft: LocalDraft): Promise<void> {
try {
const stored = await AsyncStorage.getItem(DRAFT_STORAGE_KEY);
let drafts: LocalDraft[] = stored ? JSON.parse(stored) : [];
const index = drafts.findIndex((d) => d.id === draft.id);
if (index >= 0) {
drafts[index] = draft;
} else {
drafts.push(draft);
}
await AsyncStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(drafts));
} catch (error) {
console.error('Failed to save local draft:', error);
}
}
/**
* Get local drafts
* @returns Array of local drafts
*/
static async getLocalDrafts(): Promise<LocalDraft[]> {
try {
const stored = await AsyncStorage.getItem(DRAFT_STORAGE_KEY);
return stored ? JSON.parse(stored) : [];
} catch (error) {
console.error('Failed to get local drafts:', error);
return [];
}
}
/**
* Get a specific local draft by ID
* @param id - Draft UUID
* @returns Local draft or null if not found
*/
static async getLocalDraft(id: string): Promise<LocalDraft | null> {
const drafts = await this.getLocalDrafts();
return drafts.find((d) => d.id === id) || null;
}
/**
* Delete local draft
* @param id - Draft UUID
*/
static async deleteLocalDraft(id: string): Promise<void> {
try {
const drafts = await this.getLocalDrafts();
const filtered = drafts.filter((d) => d.id !== id);
await AsyncStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(filtered));
} catch (error) {
console.error('Failed to delete local draft:', error);
}
}
/**
* Sync local drafts with server
* @param token - Access token for authentication
*/
static async syncLocalDrafts(token: string): Promise<void> {
try {
const drafts = await this.getLocalDrafts();
const unsynced = drafts.filter((d) => !d.isSynced);
for (const localDraft of unsynced) {
try {
if (localDraft.pendingUpdates) {
// Update existing draft
await this.autoSaveDraft(
token,
localDraft.id,
localDraft.pendingUpdates,
);
} else if (localDraft.data) {
// Create new draft
const created = await this.createDraft(
token,
localDraft.data as CreateDraftDto,
);
localDraft.id = created.id;
}
localDraft.isSynced = true;
await this.saveLocalDraft(localDraft);
} catch (error) {
console.error('Failed to sync draft:', error);
}
}
} catch (error) {
console.error('Failed to sync local drafts:', error);
}
}
/**
* Get sync status
*/
static async getSyncStatus(): Promise<{ total: number; unsynced: number }> {
const drafts = await this.getLocalDrafts();
return {
total: drafts.length,
unsynced: drafts.filter((d) => !d.isSynced).length,
};
}
/**
* Clear all local drafts
*/
static async clearLocalDrafts(): Promise<void> {
try {
await AsyncStorage.removeItem(DRAFT_STORAGE_KEY);
} catch (error) {
console.error('Failed to clear local drafts:', error);
}
}
}