gongxiangp2/lib/performance-salary-workflows.ts

136 lines
8.0 KiB
TypeScript

import { SalaryError } from './personnel-salary'
import { prepareSalaryWorkflow, readSalaryWorkflowSnapshots, type SalaryWorkflowSnapshot } from './salary-workflow-source'
import { readArtPointConfiguration, readArtPointDeductions, readArtPointOvertimeExemptions } from './art-workflow-point-configuration'
import { assessDingWorkflowDeliveryBatch } from './ding-workflow-delivery'
import { applyDeliveryExemption, deliveryExemptWorkflowKeys } from './workflow-delivery-exemptions'
import {
DING_WORKFLOW_ALLOWED_PROCESS_CODES,
getShanghaiMonthRangeForValue, isDingWorkflowApprovedCompletion, isDingWorkflowDeliveryAssessmentInRange,
} from './ding-workflow-sync'
import {
artPointPersonResolver, assessArtWorkflowPoints, calculateArtWorkflowPoints, independentArtAdjustmentDate,
isRejectedArtPointWorkflow, parseArtPointRows, type ArtPointPerson,
} from './art-workflow-points'
const ART_PRODUCTION = new Set(['31cf_5b23', 'a9e1_5be0', 'de46_708d', '2f9e_36f0', 'b306_c849', 'f073_738b', '6864_5429', '162b_23ea', 'c9fe_a6b8'])
const CONTENT_PRODUCTION = new Set(['编导', '拍摄', '摄像', '剪辑', '修图', '布局拍摄', '后期制作'])
export async function readSalaryWorkflowMetrics(sourceMonth: string, people: ArtPointPerson[]) {
return (await readSalaryWorkflowMetricsBatch([sourceMonth], people)).get(sourceMonth)!
}
type WorkflowMetricOptions = {
delivery: boolean
pointsMonths: string[]
overtimeExemptions?: Awaited<ReturnType<typeof readArtPointOvertimeExemptions>>
}
/** One workflow/configuration read and one SLA assessment for every requested month. */
export async function readSalaryWorkflowMetricsBatch(
sourceMonths: string[], people: ArtPointPerson[], snapshots?: SalaryWorkflowSnapshot[] | Promise<SalaryWorkflowSnapshot[]>,
options?: WorkflowMetricOptions,
) {
const pointMonths = new Set(options?.pointsMonths ?? sourceMonths)
const configuration = () => {
if (!options) return readArtPointConfiguration()
return Promise.all([
options.overtimeExemptions ?? readArtPointOvertimeExemptions(),
pointMonths.size ? readArtPointDeductions() : [],
]).then(([overtimeExemptions, deductions]) => ({ overtimeExemptions, deductions }))
}
const [rows, config] = await Promise.all([
snapshots ?? readSalaryWorkflowSnapshots(),
configuration(),
])
const readDelivery = options?.delivery ?? true
const workflows = rows.map(prepareSalaryWorkflow)
// Keep the delivery population and queue calculation; only override a judged overtime result.
const candidates = readDelivery ? workflows.filter(({ row }) => row.status.trim().toUpperCase() !== 'COMPLETED'
|| isDingWorkflowApprovedCompletion(row.status, row.result, row.bizAction)) : []
const exemptKeys = deliveryExemptWorkflowKeys(config)
const assessments = assessDingWorkflowDeliveryBatch(candidates.map(({ input }) => input)).map((assessment, index) => {
const { row } = candidates[index]
return applyDeliveryExemption(assessment, row.businessId || row.processInstanceId, exemptKeys)
})
const byDingId = new Map(people.filter(person => person.dingtalkUserId).map(person => [person.dingtalkUserId, person.id]))
const resolve = artPointPersonResolver(people)
const artRows = pointMonths.size ? workflows.filter(({ input }) => input.processCode === DING_WORKFLOW_ALLOWED_PROCESS_CODES[0]) : []
const workflowKeys = new Set(artRows.map(({ row }) => row.businessId || row.processInstanceId))
const pointRanges = Array.from(pointMonths, month => ({ month, ...getShanghaiMonthRangeForValue(month) }))
const pointsByMonth = new Map<string, Array<(typeof artRows)[number] & { assessment: ReturnType<typeof assessArtWorkflowPoints> }>>()
for (const workflow of artRows) {
const { input } = workflow
const assessment = assessArtWorkflowPoints(input.tasks, input.formFields)
const finishedAt = assessment.finishedAt ? Date.parse(assessment.finishedAt) : NaN
const range = pointRanges.find(item => finishedAt >= item.start.getTime() && finishedAt < item.end.getTime())
if (!range) continue
const list = pointsByMonth.get(range.month) ?? []
list.push({ ...workflow, assessment })
pointsByMonth.set(range.month, list)
}
const byMonth = new Map<string, SalaryWorkflowMetrics>()
for (const sourceMonth of Array.from(new Set(sourceMonths))) {
const range = getShanghaiMonthRangeForValue(sourceMonth)
const points = new Map<string, number>()
const delivery = new Map<string, { onTime: number; total: number }>()
candidates.forEach(({ row, input }, index) => {
const assessment = assessments[index]
if (!isDingWorkflowApprovedCompletion(row.status, row.result, row.bizAction) || !isDingWorkflowDeliveryAssessmentInRange(assessment, range)) return
const art = input.processCode === DING_WORKFLOW_ALLOWED_PROCESS_CODES[0]
const owners = new Set(input.tasks.filter(task => art
? ART_PRODUCTION.has(task.activityId || '')
: CONTENT_PRODUCTION.has(task.nodeName)).flatMap(task => {
const id = byDingId.get(task.assigneeUserId); return id ? [id] : []
}))
if (art) {
const graphicRows = parseArtPointRows(input.formFields.graphicTaskStats)
const imageRows = parseArtPointRows(input.formFields.imageTaskStats)
for (const stat of [...graphicRows, ...imageRows]) {
const id = resolve(stat['全案策划']); if (id) owners.add(id)
}
}
owners.forEach(id => {
const counts = delivery.get(id) ?? { onTime: 0, total: 0 }; counts.total++; if (assessment.status === 'on_time') counts.onTime++; delivery.set(id, counts)
})
})
// Points follow the source dashboard's review-month filter, independently of final completion/SLA availability.
const pointRows = pointsByMonth.get(sourceMonth) ?? []
if (pointRows.some(({ input }) => !Object.prototype.hasOwnProperty.call(input.formFields, 'plannerOwner'))) {
throw new SalaryError('流程积分正在同步,请稍后重新加载。', 503, 'WORKFLOW_POINTS_SYNCING')
}
const selectedWorkflowKeys = new Set<string>()
const scoredWorkflowKeys = new Set<string>()
for (const { row, input, assessment } of pointRows) {
const workflowKey = row.businessId || row.processInstanceId
selectedWorkflowKeys.add(workflowKey)
if (isRejectedArtPointWorkflow(row.status, row.result)) continue
const plannerId = resolve(input.formFields.plannerOwner)
const scores = calculateArtWorkflowPoints({
workflowKey, plannerId, planningRows: parseArtPointRows(input.formFields.planningTaskStats),
graphicRows: parseArtPointRows(input.formFields.graphicTaskStats), imageRows: parseArtPointRows(input.formFields.imageTaskStats), assessment,
}, people, config, resolve)
scores.forEach((score, id) => { points.set(id, (points.get(id) ?? 0) + score) })
scoredWorkflowKeys.add(workflowKey)
}
// Known workflows use their selected review month; unknown keys use their encoded date.
// Adjustments already applied to contributions must not be counted a second time.
for (const item of pointMonths.has(sourceMonth) ? config.deductions : []) {
const date = independentArtAdjustmentDate(item.workflowKey)
if (item.enabled === false || !date || scoredWorkflowKeys.has(item.workflowKey)) continue
if (workflowKeys.has(item.workflowKey) ? !selectedWorkflowKeys.has(item.workflowKey) : date.slice(0, 7) !== sourceMonth) continue
const id = resolve(item.name)
if (id) points.set(id, (points.get(id) ?? 0) + (item.type === 'add' ? 1 : -1) * Math.round((item.points ?? 0) * 100) / 100)
}
points.forEach((score, id) => points.set(id, Math.round(score * 100) / 100))
byMonth.set(sourceMonth, { sourceMonth, points, deliveryCounts: delivery, onTimeRates: new Map(Array.from(delivery).map(([id, counts]) => [id, counts.onTime / counts.total * 100])) })
}
return byMonth
}
export type SalaryWorkflowMetrics = {
sourceMonth: string
points: Map<string, number>
deliveryCounts: Map<string, { onTime: number; total: number }>
onTimeRates: Map<string, number>
}