163 lines
4.7 KiB
TypeScript

import sql from 'mssql'
import {
buildEmployeeDirectorySyncPayload,
type EmployeeDirectorySourceRows,
} from '../src/lib/hr-sync/employee-directory-source'
type CliOptions = {
dryRun: boolean
}
type QueryResult = {
recordset?: Array<Record<string, unknown>>
}
function parseCliOptions(argv: string[]): CliOptions {
return {
dryRun: argv.includes('--dry-run'),
}
}
function env(name: string, options?: { fallbackNames?: string[]; defaultValue?: string; required?: boolean }): string {
const names = [name, ...(options?.fallbackNames ?? [])]
for (const item of names) {
const value = process.env[item]?.trim()
if (value) {
return value
}
}
if (options?.defaultValue !== undefined) {
return options.defaultValue
}
if (options?.required) {
throw new Error(`missing env: ${name}`)
}
return ''
}
function getSqlServerConfig(): sql.config {
return {
server: env('HR_SQLSERVER_HOST', { required: true }),
port: Number(env('HR_SQLSERVER_PORT', { defaultValue: '1433' })),
database: env('HR_SQLSERVER_DATABASE', { required: true }),
user: env('HR_SQLSERVER_USERNAME', { fallbackNames: ['HR_SQLSERVER_USER'], required: true }),
password: env('HR_SQLSERVER_PASSWORD', { required: true }),
options: {
encrypt: env('HR_SQLSERVER_ENCRYPT', { defaultValue: 'false' }) === 'true',
trustServerCertificate: env('HR_SQLSERVER_TRUST_SERVER_CERTIFICATE', { defaultValue: 'true' }) !== 'false',
},
pool: {
max: Number(env('HR_SQLSERVER_POOL_MAX', { defaultValue: '3' })),
min: 0,
idleTimeoutMillis: Number(env('HR_SQLSERVER_IDLE_TIMEOUT_MS', { defaultValue: '30000' })),
},
requestTimeout: Number(env('HR_SQLSERVER_REQUEST_TIMEOUT_MS', { defaultValue: '60000' })),
connectionTimeout: Number(env('HR_SQLSERVER_CONNECTION_TIMEOUT_MS', { defaultValue: '15000' })),
}
}
function getSourceQueries() {
return {
departments: env('HR_SQLSERVER_DEPARTMENT_QUERY', {
defaultValue: 'select * from dbo.hr_groups',
}),
employees: env('HR_SQLSERVER_EMPLOYEE_FULL_QUERY', {
fallbackNames: ['HR_SQLSERVER_EMPLOYEES_QUERY'],
defaultValue: 'select * from dbo.hr_employee',
}),
dimissions: env('HR_SQLSERVER_DIMISSION_QUERY', {
defaultValue: 'select * from dbo.hr_employee_dimission',
}),
}
}
async function fetchRows(pool: sql.ConnectionPool, queryText: string): Promise<Array<Record<string, unknown>>> {
const result = (await pool.request().query(queryText)) as QueryResult
return result.recordset ?? []
}
async function fetchSourceRows(): Promise<EmployeeDirectorySourceRows> {
const pool = await sql.connect(getSqlServerConfig())
const queries = getSourceQueries()
try {
const [departments, employees, dimissions] = await Promise.all([
fetchRows(pool, queries.departments),
fetchRows(pool, queries.employees),
fetchRows(pool, queries.dimissions),
])
return { departments, employees, dimissions }
} finally {
await pool.close()
}
}
async function postPayload(payload: unknown) {
const endpoint = env('HR_SYNC_ENDPOINT', { required: true })
const secret = env('HR_SYNC_SECRET', { fallbackNames: ['INTERNAL_SYNC_SECRET'], required: true })
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-internal-sync-secret': secret,
},
body: JSON.stringify(payload),
})
const text = await response.text()
let body: unknown = text
try {
body = JSON.parse(text) as unknown
} catch {
// Keep the raw body for error reporting.
}
if (!response.ok) {
throw new Error(`HR sync endpoint failed: ${response.status} ${response.statusText} ${text.slice(0, 1000)}`)
}
return body
}
async function main() {
const options = parseCliOptions(process.argv.slice(2))
const startedAt = new Date()
console.log(`[${startedAt.toISOString()}] start employee directory sync`)
const sourceRows = await fetchSourceRows()
const payload = buildEmployeeDirectorySyncPayload(sourceRows)
const sourceSummary = {
source: {
departments: sourceRows.departments.length,
employees: sourceRows.employees.length,
dimissions: sourceRows.dimissions.length,
},
payload: {
departments: payload.departments.length,
employees: payload.employees.length,
dimissions: payload.dimissions.length,
},
}
console.log(JSON.stringify(sourceSummary, null, 2))
if (options.dryRun) {
console.log('dry run: skipped posting payload')
return
}
const result = await postPayload(payload)
console.log(JSON.stringify(result, null, 2))
}
main().catch((error) => {
console.error(`employee directory sync failed: ${error instanceof Error ? error.message : String(error)}`)
process.exitCode = 1
})