TrackHelper.ts 4.04 KB
import { AxiosStatic } from "axios";
import dayjs from "dayjs";
import { TrackController } from "@/api/TrackController";

export interface TrackUser {
    id?: number | string;
    name?: string;
    fullName?: string;
    authorities?: string[];
    [k: string]: any;
}

export interface TrackBusinessKey {
    businessType: string;
    businessKey: string | number;
}

export type TrackParamType = "STRING" | "NUMBER" | "BOOLEAN" | "JSON";

export interface TrackParam {
    paramKey: string;
    paramValue: string;
    paramType?: TrackParamType;
}

export interface TrackEventOptions {
    eventCode: string;
    user?: TrackUser;
    duration?: number;
    remark?: string;
    businessKeys?: TrackBusinessKey[];
    params?: TrackParam[];
}

interface EditContext {
    reportId?: string | number;
    vehicleId?: string | number;
    workOrderId?: string | number;
    [k: string]: any;
}

export class TrackHelper {
    private static editStartTimestamp = 0;
    private static editContext: EditContext = {};

    static markEditStart() {
        TrackHelper.editStartTimestamp = dayjs().unix();
    }

    static getEditStartTimestamp(): number {
        return TrackHelper.editStartTimestamp;
    }

    static getEditDurationSeconds(): number {
        if (!TrackHelper.editStartTimestamp) return 0;
        const currentTimestamp = dayjs().unix();
        const startTimestamp = TrackHelper.editStartTimestamp;
        return Math.max(0, currentTimestamp - startTimestamp);
    }

    static clearEditStart() {
        TrackHelper.editStartTimestamp = 0;
    }

    static setEditContext(ctx: EditContext) {
        TrackHelper.editContext = { ...TrackHelper.editContext, ...ctx };
    }

    static getEditContext(): EditContext {
        return TrackHelper.editContext;
    }

    static clearEditContext() {
        TrackHelper.editContext = {};
    }

    private static toStringSafe(v: any): string {
        if (v === null || v === undefined) return "";
        return String(v);
    }

    private static buildUserParams(user?: TrackUser): TrackParam[] {
        const u = user || {};
        const roleName = Array.isArray(u.authorities)
            ? u.authorities.join(",")
            : TrackHelper.toStringSafe((u as any).roleName);
        return [
            { paramKey: "user_id", paramValue: TrackHelper.toStringSafe(u.id), paramType: "STRING" },
            { paramKey: "role_name", paramValue: roleName, paramType: "STRING" },
        ];
    }

    static send(axios: AxiosStatic, options: TrackEventOptions): Promise<any> {
        const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
        const params = [
            ...TrackHelper.buildUserParams(options.user),
            ...(options.params || []),
        ];
        const payload = {
            events: [
                {
                    eventCode: options.eventCode,
                    eventTime: now,
                    duration: options.duration || 0,
                    remark: options.remark || "",
                    businessKeys: options.businessKeys || [],
                    params,
                },
            ],
        };
        return TrackController.eventTrackingBatchSave(axios, payload).catch((err) => {
            console.warn("[track] event report failed", options.eventCode, err);
        });
    }

    /** 计算两个对象之间值不同的字段名列表(浅比较,按需可扩展) */
    static diffFieldNames(
        before: Record<string, any> = {},
        after: Record<string, any> = {},
    ): string[] {
        const keys = new Set([...Object.keys(before || {}), ...Object.keys(after || {})]);
        const changed: string[] = [];
        keys.forEach((key) => {
            const b = before?.[key];
            const a = after?.[key];
            if (TrackHelper.normalize(b) !== TrackHelper.normalize(a)) {
                changed.push(key);
            }
        });
        return changed;
    }

    static normalize(v: any): string {
        if (v === null || v === undefined) return "";
        if (typeof v === "object") return JSON.stringify(v);
        return String(v);
    }
}