-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.service.ts
More file actions
545 lines (489 loc) · 16.7 KB
/
Copy pathsync.service.ts
File metadata and controls
545 lines (489 loc) · 16.7 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import { BaseService } from '@/app/api/core/services/base.service'
import { SyncLogService } from '@/app/api/quickbooks/syncLog/syncLog.service'
import { InvoiceService } from '@/app/api/quickbooks/invoice/invoice.service'
import { AuthService } from '@/app/api/quickbooks/auth/auth.service'
import IntuitAPI, { IntuitAPITokensType } from '@/utils/intuitAPI'
import { CopilotAPI } from '@/utils/copilotAPI'
import {
FailedRecordCategoryType,
EntityType,
EventType,
LogStatus,
} from '@/app/api/core/types/log'
import User from '@/app/api/core/models/User.model'
import { PaymentService } from '@/app/api/quickbooks/payment/payment.service'
import dayjs from 'dayjs'
import { ProductService } from '@/app/api/quickbooks/product/product.service'
import CustomLogger from '@/utils/logger'
import { QBSyncLog, QBSyncLogSelectSchemaType } from '@/db/schema/qbSyncLogs'
import { z } from 'zod'
import { and, eq, inArray, max } from 'drizzle-orm'
import { WhereClause } from '@/type/common'
import { TokenService } from '@/app/api/quickbooks/token/token.service'
import { QBPortalConnection } from '@/db/schema/qbPortalConnections'
import { MAX_ATTEMPTS } from '@/constant/sync'
import { captureMessage } from '@sentry/nextjs'
import { AccountTypeObj } from '@/constant/qbConnection'
export const runtime = 'nodejs'
export class SyncService extends BaseService {
private invoiceService: InvoiceService
private syncLogService: SyncLogService
constructor(user: User) {
super(user)
this.invoiceService = new InvoiceService(user)
this.syncLogService = new SyncLogService(user)
}
private async processInvoiceCreate(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
) {
const copilotApi = new CopilotAPI(this.user.token)
try {
// get invoice from Copilot API
const invoice = await copilotApi.getInvoice(record.copilotId)
if (!invoice) {
await this.syncLogService.deleteQBSyncLog(record.id)
return
}
// start re-sync process
await this.invoiceService.webhookInvoiceCreated(
{ data: invoice },
qbTokenInfo,
)
} catch (error: unknown) {
CustomLogger.error({
message: 'SyncService#processInvoiceCreate',
obj: { error, invoiceNumber: record.invoiceNumber },
})
}
}
private async processInvoicePaid(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
) {
const copilotApi = new CopilotAPI(this.user.token)
try {
// get invoice from Copilot API
const invoice = await copilotApi.getInvoice(record.copilotId)
if (!invoice) {
await this.syncLogService.deleteQBSyncLog(record.id)
return
}
// start re-sync process
await this.invoiceService.webhookInvoicePaid(
{ data: invoice },
qbTokenInfo,
)
} catch (error: unknown) {
CustomLogger.error({
message: 'SyncService#processInvoicePaid',
obj: { error, invoiceNumber: record.invoiceNumber },
})
}
}
private async processInvoiceVoided(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
) {
try {
const invNumber = z.string().parse(record.invoiceNumber)
const invoiceSync =
await this.invoiceService.getInvoiceByNumber(invNumber)
if (!invoiceSync) {
CustomLogger.info({
message: 'SyncService#processInvoiceVoided | No invoice found',
obj: { invoiceNumber: record.invoiceNumber },
})
await this.syncLogService.deleteQBSyncLog(record.id)
return
}
if (!invoiceSync.customer) {
CustomLogger.info({
message: 'SyncService#processInvoiceVoided | No customer found',
obj: { invoiceNumber: record.invoiceNumber },
})
return
}
const invoice = {
id: record.copilotId,
number: invNumber,
total: record.amount ? parseFloat(record.amount) / 100 : 0, // assuming amount is in cents
clientId: invoiceSync.customer.clientId || '',
companyId: invoiceSync.customer.companyId || '',
}
await this.invoiceService.webhookInvoiceVoided(invoice, qbTokenInfo)
} catch (error: unknown) {
CustomLogger.error({
message: 'SyncService#processInvoiceVoided',
obj: { error, invoiceNumber: record.invoiceNumber },
})
}
}
private async processInvoiceDeleted(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
) {
try {
const invNumber = z.string().parse(record.invoiceNumber)
const invoiceSync =
await this.invoiceService.getInvoiceByNumber(invNumber)
if (!invoiceSync) {
CustomLogger.info({
message: 'SyncService#processInvoiceDeleted | No invoice found',
obj: { invoiceNumber: record.invoiceNumber },
})
await this.syncLogService.deleteQBSyncLog(record.id)
return
}
if (!invoiceSync.customer) {
CustomLogger.info({
message: 'SyncService#processInvoiceDeleted | No customer found',
obj: { invoiceNumber: record.invoiceNumber },
})
return
}
const invoice = {
id: record.copilotId,
number: invNumber,
total: record.amount ? parseFloat(record.amount) / 100 : 0, // assuming amount is in cents
clientId: invoiceSync.customer.clientId || '',
companyId: invoiceSync.customer.companyId || '',
}
await this.invoiceService.handleInvoiceDeleted(invoice, qbTokenInfo)
} catch (error: unknown) {
CustomLogger.error({
message: 'SyncService#processInvoiceDeleted',
obj: { error, invoiceNumber: record.invoiceNumber },
})
}
}
private async processInvoiceSync(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
eventType: EventType,
) {
CustomLogger.info({
message: 'SyncService#processInvoiceSync',
obj: { eventType },
})
switch (eventType) {
case EventType.CREATED:
await this.processInvoiceCreate(record, qbTokenInfo)
break
case EventType.PAID:
await this.processInvoicePaid(record, qbTokenInfo)
break
case EventType.VOIDED:
await this.processInvoiceVoided(record, qbTokenInfo)
break
case EventType.DELETED:
await this.processInvoiceDeleted(record, qbTokenInfo)
break
default:
CustomLogger.error({
message: 'SyncLogService#processInvoiceSync | Unknown event type',
obj: { eventType },
})
break
}
}
private async processPaymentSucceededSync(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
) {
try {
CustomLogger.info({
message: 'syncService#processPaymentSucceededSync | records: ',
obj: record,
})
const intuitApi = new IntuitAPI(qbTokenInfo)
const tokenService = new TokenService(this.user)
const assetAccountRef = await tokenService.checkAndUpdateAccountStatus(
AccountTypeObj.Asset,
qbTokenInfo.intuitRealmId,
intuitApi,
qbTokenInfo.assetAccountRef,
)
const expenseAccountRef = await tokenService.checkAndUpdateAccountStatus(
AccountTypeObj.Expense,
qbTokenInfo.intuitRealmId,
intuitApi,
qbTokenInfo.expenseAccountRef,
)
const expensePayload = {
PaymentType: 'Cash' as const,
AccountRef: {
value: z.string().parse(assetAccountRef),
},
DocNumber: record.invoiceNumber || '',
TxnDate: dayjs(record.createdAt).format('YYYY-MM-DD'), // the date format for due date follows XML Schema standard (YYYY-MM-DD). For more info: https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/purchase#the-purchase-object
Line: [
{
DetailType: 'AccountBasedExpenseLineDetail' as const,
Amount: parseFloat(z.string().parse(record.feeAmount)) / 100, // fee amount is required for payment/expense creation
AccountBasedExpenseLineDetail: {
AccountRef: {
value: z.string().parse(expenseAccountRef),
},
},
},
],
}
const paymentService = new PaymentService(this.user)
await paymentService.createExpenseForAbsorbedFees(
expensePayload,
intuitApi,
record.copilotId,
)
} catch (error: unknown) {
CustomLogger.error({
message: 'SyncService#processPaymentSucceededSync',
obj: { error },
})
}
}
private async processProductCreate(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
) {
const productService = new ProductService(this.user)
const copilotApi = new CopilotAPI(this.user.token)
const priceResponse = await copilotApi.getPrice(
z.string().parse(record.copilotPriceId),
)
if (!priceResponse) {
await this.syncLogService.deleteQBSyncLog(record.id)
return
}
try {
await productService.webhookPriceCreated(
{ data: priceResponse },
qbTokenInfo,
)
} catch (error: unknown) {
CustomLogger.error({
message:
'SyncService#processProductCreate | Error while creating product',
obj: { error, copilotId: record.copilotId },
})
}
}
private async processProductUpdate(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
) {
const productService = new ProductService(this.user)
const copilotApi = new CopilotAPI(this.user.token)
try {
const product = await copilotApi.getProduct(record.copilotId)
if (!product) {
await this.syncLogService.deleteQBSyncLog(record.id)
return
}
await productService.webhookProductUpdated({ data: product }, qbTokenInfo)
} catch (error: unknown) {
CustomLogger.error({
message:
'SyncService#processProductUpdate | Error while updating product',
obj: { error },
})
}
}
private async processProductSync(
record: QBSyncLogSelectSchemaType,
qbTokenInfo: IntuitAPITokensType,
eventType: EventType,
) {
CustomLogger.info({
message: 'SyncService#processProductSync | Processing product sync',
obj: { eventType },
})
switch (eventType) {
case EventType.CREATED:
return await this.processProductCreate(record, qbTokenInfo)
case EventType.UPDATED:
return await this.processProductUpdate(record, qbTokenInfo)
default:
CustomLogger.error({
message: 'SyncService#processProductSync | Unknown product type',
obj: { eventType },
})
return
}
}
async intiateSync(logs: QBSyncLogSelectSchemaType[]) {
CustomLogger.info({
message: 'SyncService#intiateSync | Initiating re-sync',
})
const authService = new AuthService(this.user)
const qbTokenInfo = await authService.getQBPortalConnection(
this.user.workspaceId,
)
CustomLogger.info({
obj: { qbTokenInfo, user: this.user },
message: 'SyncService#intiateSync | QB Token Info and User',
})
for (const log of logs) {
// check and update attempt for failed logs
const resyncAttemtps = await this.checkAndUpdateAttempt(log)
if (resyncAttemtps.maxAttempts) {
continue
}
switch (log.entityType) {
case EntityType.INVOICE:
CustomLogger.info({
message: 'SyncService#intiateSync | Invoice re-sync started',
})
await this.processInvoiceSync(log, qbTokenInfo, log.eventType)
break
case EntityType.PAYMENT:
if (log.eventType === EventType.SUCCEEDED) {
CustomLogger.info({
message: 'SyncService#intiateSync | Payment re-sync started',
})
await this.processPaymentSucceededSync(log, qbTokenInfo)
}
break
case EntityType.PRODUCT:
CustomLogger.info({
message: 'SyncService#intiateSync | Product re-sync started',
})
await this.processProductSync(log, qbTokenInfo, log.eventType)
break
default:
CustomLogger.error({
message: 'SyncService#intiateSync | Unknown entity type',
obj: { entityType: log.entityType },
})
break
}
}
}
async syncFailedRecords({
includeDeleted = false,
}: { includeDeleted?: boolean } = {}) {
try {
CustomLogger.info({
message: 'SyncService#syncFailedRecords | Start re-sync process',
obj: { workspaceId: this.user.workspaceId },
})
// 1. get all failed sync logs group by the entity type
const failedSyncLogs =
await this.syncLogService.getAllFailedLogsForWorkspace(includeDeleted)
if (failedSyncLogs.length === 0) {
CustomLogger.info({
message:
'SyncService#syncFailedRecords | No failed sync logs found for portal',
obj: { workspaceId: this.user.workspaceId },
})
return
}
CustomLogger.info({
message: `Failed sync logs for portal: ${this.user.workspaceId}.`,
obj: { failedSyncLogs },
})
// 2. for each log, perform the sync based on the event type and also update the sync log status to success after successful sync
await this.intiateSync(failedSyncLogs)
CustomLogger.info({
message: 'SyncService#syncFailedRecords | Re-sync process completed',
obj: { workspaceId: this.user.workspaceId },
})
} catch (error: unknown) {
CustomLogger.error({
message: 'SyncService#syncFailedRecords',
obj: { error },
})
throw error
}
}
async checkAndSuspendAccount() {
CustomLogger.info({
message: `SyncService#checkAndSuspendAccount`,
obj: { workspaceId: this.user.workspaceId },
})
const record = await this.syncLogService.getOne(
and(
eq(QBSyncLog.portalId, this.user.workspaceId),
inArray(QBSyncLog.category, [
FailedRecordCategoryType.ACCOUNT,
FailedRecordCategoryType.AUTH,
]),
) as WhereClause,
'asc',
)
if (!record) return { suspended: false }
const sumDate = dayjs(record.createdAt).add(2, 'weeks')
if (dayjs().isAfter(sumDate)) {
CustomLogger.info({
message:
'SyncService#checkAndSuspendAccount | Date is over 2 weeks. Suspending the account...',
obj: { workspaceId: this.user.workspaceId },
})
// TODO: notify IU about the account suspension
await this.db.transaction(async (tx) => {
this.setTransaction(tx)
const tokenService = new TokenService(this.user)
const suspendAccount = tokenService.updateQBPortalConnection(
{
isSuspended: true,
},
eq(QBPortalConnection.portalId, this.user.workspaceId),
['id'],
)
const deleteLogs = this.syncLogService.updateQBSyncLog(
{
deletedAt: new Date(),
},
and(
eq(QBSyncLog.portalId, this.user.workspaceId),
eq(QBSyncLog.status, LogStatus.FAILED),
) as WhereClause,
)
await Promise.all([suspendAccount, deleteLogs])
this.unsetTransaction()
})
CustomLogger.info({
message: `SyncService#checkAndSuspendAccount | Suspended the account. Portal Id: ${this.user.workspaceId}`,
obj: { workspaceId: this.user.workspaceId },
})
return { suspended: true }
}
return { suspended: false }
}
async checkAndUpdateAttempt(log: QBSyncLogSelectSchemaType) {
if (log.attempt >= MAX_ATTEMPTS) {
CustomLogger.info({
message: `SyncService#checkAndUpdateAttempt | Reached max attempts. Not syncing the record with assembly id: ${log.copilotId}`,
obj: { workspaceId: this.user.workspaceId },
})
return { maxAttempts: true }
}
const attempt = log.attempt + 1
await this.syncLogService.updateQBSyncLog(
{
attempt,
},
eq(QBSyncLog.id, log.id),
)
// report to sentry if any records has exceeded max retry count
if (attempt == MAX_ATTEMPTS) {
captureMessage(
`SyncService#intiateSync | Records exceeded max retry count. Portal Id: ${this.user.workspaceId}.`,
{
tags: {
key: 'exceedMaxAttempts', // can be used to search like "key:exceedMaxAttempts"
},
extra: {
LogId: log.id, // shown in "Additional Data" section in Sentry
},
level: 'error',
},
)
}
CustomLogger.info({
message: `SyncService#checkAndUpdateAttempt | Attempt: ${attempt}`,
obj: { workspaceId: this.user.workspaceId },
})
return { maxAttempts: false }
}
}