-
Notifications
You must be signed in to change notification settings - Fork 0
OUT-3276: backfill script to update product info in mapping table #203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
150 changes: 150 additions & 0 deletions
150
src/cmd/backfillProductInfo/backfillProductInfo.service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| import { MAX_PRODUCT_LIST_LIMIT } from '@/app/api/core/constants/limit' | ||
| import APIError from '@/app/api/core/exceptions/api' | ||
| import { BaseService } from '@/app/api/core/services/base.service' | ||
| import { withRetry } from '@/app/api/core/utils/withRetry' | ||
| import { AuthService } from '@/app/api/quickbooks/auth/auth.service' | ||
| import { ProductService } from '@/app/api/quickbooks/product/product.service' | ||
| import { | ||
| QBProductSelectSchemaType, | ||
| QBProductSync, | ||
| } from '@/db/schema/qbProductSync' | ||
| import { StatusableError } from '@/type/CopilotApiError' | ||
| import { CopilotAPI } from '@/utils/copilotAPI' | ||
| import IntuitAPI from '@/utils/intuitAPI' | ||
| import { eq, isNotNull } from 'drizzle-orm' | ||
| import { convert } from 'html-to-text' | ||
| import httpStatus from 'http-status' | ||
|
|
||
| export class BackfillProductInfoService extends BaseService { | ||
| async _backfillProductInfoForPortal() { | ||
| try { | ||
| console.info( | ||
| `BackfillProductInfoService#backfillProductInfoForPortal :: Backfilling product info for portal: ${this.user.workspaceId}`, | ||
| ) | ||
|
|
||
| // 1. get all mapped products from our mapping table | ||
| const productService = new ProductService(this.user) | ||
| const mappedProducts: QBProductSelectSchemaType[] = | ||
| await productService.getAll(isNotNull(QBProductSync.qbItemId)) | ||
| const mappedAssemblyProductIds = [ | ||
| ...new Set(mappedProducts.map((product) => product.productId)), | ||
| ] | ||
|
|
||
| if (mappedAssemblyProductIds.length === 0) { | ||
| console.info( | ||
| `No mapped product found for portal: ${this.user.workspaceId}`, | ||
| ) | ||
| return | ||
| } | ||
|
|
||
| // 2. get all products from assembly | ||
| const copilotApi = new CopilotAPI(this.user.token) | ||
| const assemblyProducts = ( | ||
| await copilotApi.getProducts( | ||
| undefined, | ||
| undefined, | ||
| MAX_PRODUCT_LIST_LIMIT, | ||
| ) | ||
| )?.data | ||
|
|
||
| if (!assemblyProducts) { | ||
| console.info('No product found in assembly') | ||
| return | ||
| } | ||
|
|
||
| const filteredAssemblyProducts = assemblyProducts.filter((product) => | ||
| mappedAssemblyProductIds.includes(product.id), | ||
| ) | ||
|
|
||
| const authService = new AuthService(this.user) | ||
| const qbTokenInfo = await authService.getQBPortalConnection( | ||
| this.user.workspaceId, | ||
| ) | ||
|
|
||
| if (!qbTokenInfo.accessToken || !qbTokenInfo.refreshToken) { | ||
| console.info( | ||
| `No access token found for portal: ${this.user.workspaceId}`, | ||
| ) | ||
| return | ||
| } | ||
|
|
||
| const intuitApi = new IntuitAPI(qbTokenInfo) | ||
| const allQbItems = await intuitApi.getAllItems(MAX_PRODUCT_LIST_LIMIT, [ | ||
| 'Id', | ||
| 'Name', | ||
| 'UnitPrice', | ||
| 'Description', | ||
| 'SyncToken', | ||
| ]) | ||
|
|
||
| // 3. update the product info in our mapping table | ||
| for (const mappedProduct of mappedProducts) { | ||
| if (!mappedProduct.qbItemId) { | ||
| console.info(`Qb item id not found for product ${mappedProduct.name}`) | ||
| continue | ||
| } | ||
|
|
||
| const assemblyProduct = filteredAssemblyProducts.find( | ||
| (item) => item.id === mappedProduct.productId, | ||
| ) | ||
|
|
||
| if (!assemblyProduct) { | ||
| console.info( | ||
| `Copilot product not found for product ${mappedProduct.name} ${mappedProduct.productId}`, | ||
| ) | ||
| continue | ||
| } | ||
|
|
||
| // 4. get item from QB | ||
| const qbItem = allQbItems?.find( | ||
| (item) => item.Id === mappedProduct.qbItemId, | ||
| ) | ||
| if (!qbItem) { | ||
| console.info( | ||
| `Item not found in Quickbooks for product with assembly ID ${mappedProduct.productId}`, | ||
| ) | ||
| } | ||
|
|
||
| console.info( | ||
| `\nUpdating item info in mapping table for product with QB id ${mappedProduct.qbItemId}. Product map id ${mappedProduct.id}`, | ||
| ) | ||
|
|
||
| const payload = { | ||
| name: qbItem?.Name || null, | ||
| copilotName: assemblyProduct.name, | ||
| description: assemblyProduct.description | ||
| ? convert(assemblyProduct.description) | ||
| : '', | ||
| ...(qbItem?.SyncToken && { qbSyncToken: qbItem.SyncToken }), | ||
| } | ||
| await productService.updateQBProduct( | ||
| payload, | ||
| eq(QBProductSync.id, mappedProduct.id), | ||
| ) | ||
| } | ||
| } catch (error: unknown) { | ||
| if (error instanceof APIError) { | ||
| throw error | ||
| } | ||
| const AssemnblyError = error as StatusableError // no | ||
| const status = AssemnblyError.status || httpStatus.BAD_REQUEST | ||
| if (status === httpStatus.FORBIDDEN) { | ||
| console.info( | ||
| `Assembly sdk returns forbidden for the portal ${this.user.workspaceId}`, | ||
| ) | ||
| return | ||
| } | ||
| throw error | ||
| } | ||
| } | ||
|
|
||
| private wrapWithRetry<Args extends unknown[], R>( | ||
| fn: (...args: Args) => Promise<R>, | ||
| ): (...args: Args) => Promise<R> { | ||
| return (...args: Args): Promise<R> => withRetry(fn.bind(this), args) | ||
| } | ||
|
|
||
| backfillProductInfoForPortal = this.wrapWithRetry( | ||
| this._backfillProductInfoForPortal, | ||
| ) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import APIError from '@/app/api/core/exceptions/api' | ||
| import User from '@/app/api/core/models/User.model' | ||
| import { BackfillProductInfoService } from '@/cmd/backfillProductInfo/backfillProductInfo.service' | ||
| import { copilotAPIKey } from '@/config' | ||
| import { PortalConnectionWithSettingType } from '@/db/schema/qbPortalConnections' | ||
| import { getAllActivePortalConnections } from '@/db/service/token.service' | ||
| import { CopilotAPI } from '@/utils/copilotAPI' | ||
| import { encodePayload } from '@/utils/crypto' | ||
| import CustomLogger from '@/utils/logger' | ||
|
|
||
| /** | ||
| * This script is used to backfill product info in our mapping table | ||
| */ | ||
|
|
||
| // command to run the script: `yarn run cmd:backfill-product-info` | ||
| ;(async function run() { | ||
| try { | ||
| console.info('BackfillProductInfo#initiateProcess') | ||
| const activeConnections = await getAllActivePortalConnections() | ||
|
|
||
| if (!activeConnections.length) { | ||
| console.info('No active connection found') | ||
| return | ||
| } | ||
|
|
||
| for (const connection of activeConnections) { | ||
| if (!connection.setting?.syncFlag || !connection.setting?.isEnabled) { | ||
| console.info( | ||
| 'Skipping connection: ' + JSON.stringify(connection.portalId), | ||
| ) | ||
| continue | ||
| } | ||
|
|
||
| console.info( | ||
| `\n\n\n ########### Processing for PORTAL: ${connection.portalId} #############`, | ||
| ) | ||
|
|
||
| await initiateProcess(connection) | ||
| } | ||
|
|
||
| console.info('\n Backfilled product info to mapping table successfully 🎉') | ||
| process.exit(0) | ||
| } catch (error) { | ||
| console.error(error) | ||
| process.exit(1) | ||
| } | ||
| })() | ||
|
|
||
| async function initiateProcess(connection: PortalConnectionWithSettingType) { | ||
| // generate token for the portal | ||
| console.info('Generating token for the portal') | ||
| const payload = { | ||
| workspaceId: connection.portalId, | ||
| } | ||
| const token = encodePayload(copilotAPIKey, payload) | ||
|
|
||
| const copilot = new CopilotAPI(token) | ||
| const tokenPayload = await copilot.getTokenPayload() | ||
| CustomLogger.info({ | ||
| obj: { copilotApiCronToken: token, tokenPayload }, | ||
| message: | ||
| 'backfillProductInfo#initiateProcess | Copilot API token and payload', | ||
| }) | ||
| if (!tokenPayload) throw new APIError(500, 'Encoded token is not valid') // this should trigger p-retry and re-run the function | ||
|
|
||
| const user = new User(token, tokenPayload) | ||
| const syncMissedService = new BackfillProductInfoService(user) | ||
| await syncMissedService.backfillProductInfoForPortal() | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If possible let's make filteredAssemblyProducts a Map.