import type { AgentSettlementCycle } from "@/lib/agent-settlement-cycle"; export type SettlementPeriodPresetKey = "this_week" | "last_week" | "this_month"; /** `datetime-local` 控件取值格式 */ export function toDateTimeLocalValue(date: Date): string { const pad = (n: number) => String(n).padStart(2, "0"); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`; } function startOfDay(date: Date): Date { const d = new Date(date); d.setHours(0, 0, 0, 0); return d; } function endOfDay(date: Date): Date { const d = new Date(date); d.setHours(23, 59, 0, 0); return d; } /** 周一为一周起始(与产品文档「周结」一致) */ function startOfWeekMonday(date: Date): Date { const d = startOfDay(date); const day = d.getDay(); const diff = day === 0 ? -6 : 1 - day; d.setDate(d.getDate() + diff); return d; } function addDays(date: Date, days: number): Date { const d = new Date(date); d.setDate(d.getDate() + days); return d; } function startOfMonth(date: Date): Date { const d = startOfDay(date); d.setDate(1); return d; } function endOfMonth(date: Date): Date { const d = startOfDay(date); d.setMonth(d.getMonth() + 1); d.setDate(0); return endOfDay(d); } export function settlementPeriodPresetRange( key: SettlementPeriodPresetKey, now: Date = new Date(), ): { period_start: string; period_end: string } { switch (key) { case "this_week": { const start = startOfWeekMonday(now); const end = endOfDay(addDays(start, 6)); return { period_start: toDateTimeLocalValue(start), period_end: toDateTimeLocalValue(end), }; } case "last_week": { const thisStart = startOfWeekMonday(now); const start = addDays(thisStart, -7); const end = endOfDay(addDays(start, 6)); return { period_start: toDateTimeLocalValue(start), period_end: toDateTimeLocalValue(end), }; } case "this_month": { const start = startOfMonth(now); const end = endOfMonth(now); return { period_start: toDateTimeLocalValue(start), period_end: toDateTimeLocalValue(end), }; } } } /** 按代理结算周期推荐默认快捷开期(周结优先) */ export function defaultSettlementPeriodPreset( cycle: AgentSettlementCycle, ): SettlementPeriodPresetKey { if (cycle === "monthly") { return "this_month"; } return "this_week"; } export function formatSettlementPeriodSpan( periodStart: string | undefined, periodEnd: string | undefined, ): string { const start = periodStart?.slice(0, 10) ?? "—"; const end = periodEnd?.slice(0, 10) ?? "—"; return `${start} ~ ${end}`; }