gongxiangp2/lib/salary-market-intent.ts

68 lines
5.2 KiB
TypeScript

import { prisma } from './prisma'
import { SalaryError } from './personnel-salary'
import { artPointPersonResolver, parseArtPointRows, type ArtPointPerson } from './art-workflow-points'
import { DING_WORKFLOW_ALLOWED_PROCESS_CODES, DING_WORKFLOW_STARTED_AT_CUTOFF_ISO, normalizeDetailFormFields, normalizeWorkflowTasks } from './ding-workflow-sync'
import { performanceConversionWorkflowItems, readPerformanceConversionWindows } from './performance-conversion'
import { buildIntentRateWindowSummary, toShanghaiDateKey } from '@/components/department-dashboard/performance-conversion'
import { summarizeMarketIntent, type MarketIntentEvidence, type MarketIntentCandidate, type MarketIntentExclusion } from './salary-market-intent-contract'
const PRODUCTION_ACTIVITIES = new Set(['31cf_5b23', 'a9e1_5be0', 'de46_708d', '2f9e_36f0', 'b306_c849', 'f073_738b', '6864_5429', '162b_23ea', 'c9fe_a6b8'])
export function marketIntentParticipants(formFields: unknown, activeTasks: unknown, people: ArtPointPerson[]) {
const resolve = artPointPersonResolver(people), fields = normalizeDetailFormFields(formFields)
const ids = new Set<string>()
const add = (value: unknown): void => {
if (Array.isArray(value)) { value.forEach(add); return }
if (typeof value === 'string' && /^[\[{]/.test(value.trim())) {
try { add(JSON.parse(value)); return } catch { return }
}
const id = resolve(value); if (id) ids.add(id)
}
add(fields.plannerOwner)
for (const task of normalizeWorkflowTasks(activeTasks)) if (PRODUCTION_ACTIVITIES.has(task.activityId ?? '')) add(task.assigneeUserId)
for (const value of [fields.planningTaskStats, fields.graphicTaskStats, fields.imageTaskStats]) {
for (const row of parseArtPointRows(value)) for (const label of ['全案策划', '策划案负责人']) add(row[label])
}
return ids
}
/** Internal aggregator, only called after the salary service's current-DB permission check. */
export async function readSalaryMarketIntent(month: string, people: ArtPointPerson[], employeeIds: string[]) {
try { return await readMarketIntent(month, people, employeeIds) }
catch (error) {
if (error instanceof SalaryError) throw error
throw new SalaryError('经营数据暂时无法读取,未计算市场验证得分,请稍后重新加载。', 503, 'MARKET_INTENT_UNAVAILABLE')
}
}
async function readMarketIntent(month: string, people: ArtPointPerson[], employeeIds: string[]) {
const employeeSet = new Set(employeeIds)
if (!employeeSet.size) return new Map<string, MarketIntentEvidence>()
const rows = await prisma.dingWorkflowSnapshot.findMany({
where: { processCode: DING_WORKFLOW_ALLOWED_PROCESS_CODES[0], sourceCreatedAtRaw: { gte: DING_WORKFLOW_STARTED_AT_CUTOFF_ISO }, sourceFinishedAtRaw: { not: null } },
select: { processInstanceId: true, businessId: true, title: true, result: true, bizAction: true, status: true, processCode: true, brand: true, sourceFinishedAtRaw: true, formFields: true, activeTasks: true },
})
const candidates = rows.filter(row => row.sourceFinishedAtRaw && toShanghaiDateKey(row.sourceFinishedAtRaw)?.slice(0, 7) === month).flatMap(row => {
const participants = Array.from(marketIntentParticipants(row.formFields, row.activeTasks, people)).filter(id => employeeSet.has(id))
return participants.length ? performanceConversionWorkflowItems(row).map(workflow => ({ workflow, participants })) : []
})
let windows: Awaited<ReturnType<typeof readPerformanceConversionWindows>>
try { windows = await readPerformanceConversionWindows(candidates.map(item => item.workflow), { intentWindowOnly: true }) }
catch { throw new SalaryError('经营数据暂时无法读取,未计算市场验证得分,请稍后重新加载。', 503, 'MARKET_INTENT_UNAVAILABLE') }
const records = new Map<string, MarketIntentCandidate[]>()
for (const { workflow, participants } of candidates) {
const window = windows.get(workflow.key)!, summary = buildIntentRateWindowSummary(window.daily)
const reason: MarketIntentExclusion | null = !window.supported ? 'unsupported-platform' : window.daily.length < 15 ? 'immature-window'
: !window.sourceDaily.length ? 'no-source-data' : summary.sevenDayIntentRate === 0 ? 'zero-baseline'
: summary.intentRateChange === null || !Number.isFinite(summary.intentRateChange) ? 'invalid-intent' : null
// Calendar expansion creates synthetic zero days even when the source is empty.
// Only expose computable means backed by an available data source.
const nullableValue = (value: number | null) => window.supported && window.sourceDaily.length > 0 && value !== null && Number.isFinite(value) ? value : null
for (const id of participants) {
const list = records.get(id) ?? []
list.push({ key: workflow.key, workflowId: workflow.workflowId, approvalNumber: workflow.approvalNumber, productId: workflow.productId, brand: workflow.brand, completedAt: workflow.completedAt,
invalidReason: reason, intentRateChange: nullableValue(summary.intentRateChange), sevenDayIntentRate: nullableValue(summary.sevenDayIntentRate), fifteenDayIntentRate: nullableValue(summary.fifteenDayIntentRate) })
records.set(id, list)
}
}
return new Map(Array.from(employeeSet, id => [id, summarizeMarketIntent(month, records.get(id) ?? [])]))
}