Listing_SuggestPrice/backend/commands/sync_erp.ts

62 lines
2.3 KiB
TypeScript

import { BaseCommand, flags } from '@adonisjs/core/ace'
import type { CommandOptions } from '@adonisjs/core/types/ace'
import env from '#start/env'
/**
* Trigger đồng bộ sản phẩm từ ERP qua queue.
*
* node ace sync:erp # đẩy 1 job sync NGAY (worker xử lý)
* node ace sync:erp --schedule # tạo/cập nhật cron sync hằng ngày
* node ace sync:erp --unschedule # gỡ cron
* node ace sync:erp --schedule --pattern "0 3 * * *" --tz "Australia/Sydney"
*
* Lưu ý: việc upsert thực tế do worker `node ace queue:work` đảm nhận,
* command này chỉ đưa job vào hàng đợi.
*/
export default class SyncErp extends BaseCommand {
static commandName = 'sync:erp'
static description = 'Đồng bộ ERP: đẩy job sync ngay, hoặc tạo/gỡ cron hằng ngày'
static options: CommandOptions = { startApp: true }
@flags.boolean({ description: 'Tạo/cập nhật cron sync hằng ngày thay vì chạy ngay' })
declare schedule: boolean
@flags.boolean({ description: 'Gỡ cron sync hằng ngày' })
declare unschedule: boolean
@flags.string({ description: 'Cron pattern (mặc định lấy từ SYNC_CRON hoặc "0 2 * * *")' })
declare pattern: string
@flags.string({ description: 'Timezone cho cron (mặc định SYNC_TZ hoặc "Australia/Sydney")' })
declare tz: string
async run() {
const { upsertSyncScheduler, removeSyncScheduler, enqueueSync, closeQueues } = await import(
'#services/queue_service'
)
try {
if (this.unschedule) {
await removeSyncScheduler()
this.logger.success('Đã gỡ cron sync ERP hằng ngày')
return
}
if (this.schedule) {
const pattern = this.pattern ?? env.get('SYNC_CRON', '0 2 * * *')
const tz = this.tz ?? env.get('SYNC_TZ', 'Australia/Sydney')
await upsertSyncScheduler(pattern, tz, 'cron')
this.logger.success(`Đã đặt cron sync ERP: "${pattern}" (tz: ${tz})`)
return
}
// Mặc định: đẩy 1 job sync ngay.
const job = await enqueueSync('cli')
this.logger.success(`Đã đẩy job sync ERP #${job.id} vào queue. Worker sẽ xử lý.`)
} finally {
// Đóng kết nối Redis để command thoát sạch.
await closeQueues()
}
}
}