gongxiangp2/lib/salary-market-intent.ts

108 lines
6.6 KiB
TypeScript

import { SalaryError } from './personnel-salary'
import { prepareSalaryWorkflow, readSalaryWorkflowSnapshots, type SalaryWorkflowSnapshot } from './salary-workflow-source'
import { artPointPersonResolver, parseArtPointRows, type ArtPointPerson } from './art-workflow-points'
import { DING_WORKFLOW_NEW_PRODUCT_DEMAND_TYPE, 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[]) {
return resolveMarketParticipants(normalizeDetailFormFields(formFields), normalizeWorkflowTasks(activeTasks), artPointPersonResolver(people))
}
function resolveMarketParticipants(
fields: ReturnType<typeof normalizeDetailFormFields>, tasks: ReturnType<typeof normalizeWorkflowTasks>,
resolve: ReturnType<typeof artPointPersonResolver>,
) {
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 tasks) 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[]) {
return (await readSalaryMarketIntentBatch([month], people, employeeIds)).get(month)!
}
const marketUnavailable = () => new SalaryError('经营数据暂时无法读取,未计算市场验证得分,请稍后重新加载。', 503, 'MARKET_INTENT_UNAVAILABLE')
type MarketFailure = (month: string, error: SalaryError) => void
/** Merge both months' product windows into the existing batched source reader. */
export async function readSalaryMarketIntentBatch(
months: string[], people: ArtPointPerson[], employeeIds: string[],
snapshots?: SalaryWorkflowSnapshot[], onFailure?: MarketFailure, signal?: AbortSignal,
) {
try { return await readMarketIntentBatch(months, people, employeeIds, snapshots, onFailure, signal) }
catch (error) {
if (error instanceof SalaryError) throw error
throw marketUnavailable()
}
}
async function readMarketIntentBatch(
months: string[], people: ArtPointPerson[], employeeIds: string[],
snapshots?: SalaryWorkflowSnapshot[], onFailure?: MarketFailure, signal?: AbortSignal,
) {
const employeeSet = new Set(employeeIds), monthSet = new Set(months)
const byMonth = new Map(Array.from(monthSet, month => [month, new Map<string, MarketIntentEvidence>()]))
if (!employeeSet.size) return byMonth
const rows = await (snapshots ?? readSalaryWorkflowSnapshots())
const resolve = artPointPersonResolver(people)
const candidates = rows.flatMap(row => {
const month = row.sourceFinishedAtRaw ? toShanghaiDateKey(row.sourceFinishedAtRaw)?.slice(0, 7) : undefined
if (!month || !monthSet.has(month)) return []
const items = performanceConversionWorkflowItems(row)
if (!items.length) return []
const { input } = prepareSalaryWorkflow(row)
const participants = Array.from(resolveMarketParticipants(input.formFields, input.tasks, resolve)).filter(id => employeeSet.has(id))
return participants.length ? items.map(workflow => ({ workflow, participants, month, demandType: input.formFields.demandType })) : []
})
const failedMonths = new Set<string>()
const monthByKey = new Map(candidates.map(item => [item.workflow.key, item.month]))
const windows = await readPerformanceConversionWindows(candidates.map(item => item.workflow), {
intentWindowOnly: true,
signal,
...(onFailure ? {
onWindowFailure(keys) {
for (const key of keys) {
const month = monthByKey.get(key)!
if (!failedMonths.has(month)) onFailure(month, marketUnavailable())
failedMonths.add(month)
}
},
} : {}),
})
const recordsByMonth = new Map(Array.from(monthSet, month => [month, new Map<string, MarketIntentCandidate[]>()]))
for (const { workflow, participants, month, demandType } of candidates) {
if (failedMonths.has(month)) continue
const records = recordsByMonth.get(month)!
const window = windows.get(workflow.key)!, summary = buildIntentRateWindowSummary(window.daily)
const reason: MarketIntentExclusion | null = demandType === DING_WORKFLOW_NEW_PRODUCT_DEMAND_TYPE ? 'new-product'
: !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,
demandType, invalidReason: reason, intentRateChange: nullableValue(summary.intentRateChange), sevenDayIntentRate: nullableValue(summary.sevenDayIntentRate), fifteenDayIntentRate: nullableValue(summary.fifteenDayIntentRate) })
records.set(id, list)
}
}
for (const month of Array.from(monthSet)) byMonth.set(month, new Map(Array.from(employeeSet, id => [id, summarizeMarketIntent(month, recordsByMonth.get(month)!.get(id) ?? [])])))
return byMonth
}