Commit 1b491e8a by chenwq1

feat: 添加检测报告模块及相关功能

- 新增 `inspect-report` 模块,包含页面、模板和记录的 API 接口。
- 更新请求封装,基于 axios 实现统一的请求处理。
- 修改 README.md,更新构建工具和适配信息,移除不再使用的 postcss-px-to-viewport。
- 优化 CustomizeForm 组件,支持新的检测报告数据结构。
- 更新路由配置,添加工单详情页面的重定向逻辑。
1 parent 9d47e966
Pipeline #108 for 1b491e8a failed in 0 seconds
Showing 22 changed files with 743 additions and 221 deletions
...@@ -7,15 +7,16 @@ ...@@ -7,15 +7,16 @@
- **框架**: Vue 3、Vue Router、Pinia - **框架**: Vue 3、Vue Router、Pinia
- **UI**: Vant 4(按需引入) - **UI**: Vant 4(按需引入)
- **工具**: VueUse、dayjs、glsk-toolkit - **工具**: VueUse、dayjs、glsk-toolkit
- **构建**: Vite、TypeScript、SCSS、postcss-px-to-viewport(375 设计稿) - **构建**: Vite、TypeScript、SCSS、Tailwind CSS
- **适配**: `lib-flexible` + `postcss-pxtorem`(设计稿以 375 宽为基准,`rootValue` 与 `flexible` 中基准字号一致)
## 已完成的配置 ## 已完成的配置
- **环境变量**: `.env` / `.env.development` / `.env.production`,支持 `VITE_APP_TITLE`、`VITE_API_BASE_URL`、`VITE_APP_ENV` - **环境变量**: `.env` / `.env.development` / `.env.production`,支持 `VITE_APP_TITLE`、`VITE_API_BASE_URL`、`VITE_APP_ENV`
- **路径别名**: `@`、`@assets`、`@views`、`@components`、`@stores`、`@utils`、`@api`、`@composables` - **路径别名**: `@`、`@assets`、`@views`、`@components`、`@stores`、`@utils`、`@api`、`@composables`
- **自动导入**: vue / vue-router / pinia / @vueuse/core;Vant 组件与 `src/components`、`src/layouts` 自动注册 - **自动导入**: vue / vue-router / pinia / @vueuse/core;Vant 组件与 `src/components`、`src/layouts` 自动注册
- **配置中心**: 远程拉取配置(`venus-usedcar-config`),本地缓存,动态设置 API baseURL;集成 glsk-toolkit Request,请求拦截器统一注入 `Authorization`,401/403/500 统一 Toast 提示 - **配置中心**: 远程拉取配置(`venus-usedcar-config`),本地缓存,动态设置 API baseURL;集成 glsk-toolkit Request 实例(与业务请求层并行时可统一收敛)
- **请求封装**: `src/utils/request.ts` 基于配置中心 Request 实例,提供 `get`/`post`,统一解析 `code === 200 | 0` 的 `data`,类型 `ApiResponse<T>`、`PageData<T>` - **请求封装**: `src/utils/request.ts` 基于 axios,提供 `get`/`post`,统一解析业务 `code === 200` 的 `data`,类型 `ApiResponse<T>`、`PageData<T>`
- **开发代理**: `/api` 代理到 `VITE_API_BASE_URL`,端口 8082 - **开发代理**: `/api` 代理到 `VITE_API_BASE_URL`,端口 8082
## 已完成的功能 ## 已完成的功能
......
export * from "./page";
export * from "./template";
export * from "./record";
import { post } from "@utils/request";
export interface InspectReportPageParams {
size: number;
page: number;
keyword?: string;
}
export interface PageSort {
empty: boolean;
sorted: boolean;
unsorted: boolean;
}
export interface InspectReportPageData<T> {
size: number;
number: number;
totalElements: number;
last: boolean;
totalPages: number;
sort: PageSort;
first: boolean;
numberOfElements: number;
content: T[];
}
export interface InspectReportVehicleCover {
uid?: string | number;
name?: string;
status?: string;
url?: string;
filePath?: string;
thumbPath?: string | null;
thumbUrl?: string | null;
size?: number;
lastModified?: number;
lastModifiedDate?: string;
[key: string]: unknown;
}
export interface InspectReportVehicleBaseInfo {
carBrandId?: number;
carBrand?: string;
carChildsBrandId?: number;
carChildsBrandName?: string;
carSeriesId?: number;
carSeriesName?: string;
carTypeId?: number;
carTypeName?: string;
mileage?: number;
vin?: string;
engineNumber?: string;
licensePlate?: string;
sourceNo?: string;
tags?: string[];
guidePrice?: number;
[key: string]: unknown;
}
export interface InspectReportVehicle {
createTime?: string;
updateTime?: string;
updateBy?: string;
createBy?: string;
vehicleId?: number;
baseInfo?: InspectReportVehicleBaseInfo;
coreSpecs?: Record<string, unknown>;
ownership?: Record<string, unknown>;
licenseInfo?: Record<string, unknown>;
historyCondition?: Record<string, unknown>;
evaluationTransaction?: Record<string, unknown>;
custodianInfo?: Record<string, unknown>;
ownerInfo?: Record<string, unknown>;
venue?: Record<string, unknown>;
area?: Record<string, unknown>;
parkingSpace?: string;
cover?: InspectReportVehicleCover;
albums?: InspectReportVehicleCover[];
[key: string]: unknown;
}
export interface InspectReportItem {
id: number;
reportNo: string;
woId: string;
vehicle?: InspectReportVehicle;
score?: number;
scoreLevel?: string;
bindStatus?: number;
h5Url?: string;
createTime?: string;
updateTime?: string;
[key: string]: unknown;
}
export type InspectReportPageResult = InspectReportPageData<InspectReportItem>;
export function getInspectReportPage(params: InspectReportPageParams) {
return post<InspectReportPageResult>("/rest/inspect/report/page", params);
}
import { post } from "@utils/request";
export interface LeafNodeValue {
valueText: string;
valueKey: string;
interactionType: string;
valueSeq: number;
remark: string;
}
export interface LeafNodeRecord {
nodeId: number;
nodeName: string;
resultStatus: number;
remark: string;
data: LeafNodeValue[];
}
export interface InspectionRecordSaveParams {
taskId: number | string;
/** 大项 nodeId */
locationModule: number | string;
/** 二级项 nodeId;无二级分组时为 null */
locationSubModule: number | string | null;
/** true = 保存并跳下一步,false = 仅保存 */
nextFlag: boolean;
leafNodes: LeafNodeRecord[];
}
/**
* 保存/下一步
*/
export function saveInspectionRecord(params: InspectionRecordSaveParams) {
return post<void>("/rest/inspectionRecord/save", params);
}
/**
* POST `/rest/inspectionRecord/completeInspection` 请求体
*/
export interface CompleteInspectionParams {
taskId: number | string;
exteriorScore: number;
exteriorComment: string;
skeletonLevel: string;
skeletonComment: string;
interiorLevel: string;
interiorComment: string;
overallScore: number;
overallComment: string;
}
/** `completeInspection` 成功时 `data`:有未完成项时带首项节点信息(多为大项 rootNodeId) */
export interface CompleteInspectionResultData {
firstUncompletedNodeId?: null | number | string;
firstUncompletedNodeName?: null | string;
}
/**
* 完成检测(提交检测评分)
*/
export function completeInspection(params: CompleteInspectionParams) {
return post<CompleteInspectionResultData>("/rest/inspectionRecord/completeInspection", params);
}
import { get, post } from "@utils/request"; import { get, post } from "@utils/request";
export interface InspectReportPageParams {
size: number;
page: number;
keyword?: string;
}
export interface PageSort {
empty: boolean;
sorted: boolean;
unsorted: boolean;
}
export interface InspectReportPageData<T> {
size: number;
number: number;
totalElements: number;
last: boolean;
totalPages: number;
sort: PageSort;
first: boolean;
numberOfElements: number;
content: T[];
}
export interface InspectReportVehicleCover {
uid?: string | number;
name?: string;
status?: string;
url?: string;
filePath?: string;
thumbPath?: string | null;
thumbUrl?: string | null;
size?: number;
lastModified?: number;
lastModifiedDate?: string;
// 后端字段较多,允许拓展
[key: string]: unknown;
}
export interface InspectReportVehicleBaseInfo {
carBrandId?: number;
carBrand?: string;
carChildsBrandId?: number;
carChildsBrandName?: string;
carSeriesId?: number;
carSeriesName?: string;
carTypeId?: number;
carTypeName?: string;
mileage?: number;
vin?: string;
engineNumber?: string;
licensePlate?: string;
sourceNo?: string;
tags?: string[];
guidePrice?: number;
[key: string]: unknown;
}
export interface InspectReportVehicle {
createTime?: string;
updateTime?: string;
updateBy?: string;
createBy?: string;
vehicleId?: number;
baseInfo?: InspectReportVehicleBaseInfo;
coreSpecs?: Record<string, unknown>;
ownership?: Record<string, unknown>;
licenseInfo?: Record<string, unknown>;
historyCondition?: Record<string, unknown>;
evaluationTransaction?: Record<string, unknown>;
custodianInfo?: Record<string, unknown>;
ownerInfo?: Record<string, unknown>;
venue?: Record<string, unknown>;
area?: Record<string, unknown>;
parkingSpace?: string;
cover?: InspectReportVehicleCover;
albums?: InspectReportVehicleCover[];
[key: string]: unknown;
}
export interface InspectReportItem {
id: number;
reportNo: string;
woId: string;
vehicle?: InspectReportVehicle;
score?: number;
scoreLevel?: string;
bindStatus?: number;
h5Url?: string;
createTime?: string;
updateTime?: string;
[key: string]: unknown;
}
export type InspectReportPageResult = InspectReportPageData<InspectReportItem>;
export function getInspectReportPage(params: InspectReportPageParams) {
return post<InspectReportPageResult>("/rest/inspect/report/page", params);
}
// 检测模板相关接口
/** 检测结果单项值(与落库结构对齐) */ /** 检测结果单项值(与落库结构对齐) */
export interface InspectionValueItem { export interface InspectionValueItem {
id?: number; id?: number;
...@@ -165,13 +63,6 @@ export interface InspectionNode { ...@@ -165,13 +63,6 @@ export interface InspectionNode {
[key: string]: unknown; [key: string]: unknown;
} }
export interface InspectionNodeResponse {
code: string;
data: InspectionNode[];
success: boolean;
message: string;
}
/** /**
* 获取检测模板根节点(大项) * 获取检测模板根节点(大项)
* @param taskId 检测工单ID * @param taskId 检测工单ID
...@@ -412,82 +303,3 @@ export function applyResolvedInitialValuesToLeafNodes( ...@@ -412,82 +303,3 @@ export function applyResolvedInitialValuesToLeafNodes(
return merged; return merged;
}); });
} }
// ===== 检测记录保存 =====
export interface LeafNodeValue {
valueText: string;
valueKey: string;
interactionType: string;
valueSeq: number;
remark: string;
}
export interface LeafNodeRecord {
nodeId: number;
nodeName: string;
resultStatus: number;
remark: string;
data: LeafNodeValue[];
}
export interface InspectionRecordSaveParams {
taskId: number | string;
/** 大项 nodeId */
locationModule: number | string;
/** 二级项 nodeId;无二级分组时为 null */
locationSubModule: number | string | null;
/** true = 保存并跳下一步,false = 仅保存 */
nextFlag: boolean;
leafNodes: LeafNodeRecord[];
}
/**
* 保存/下一步
*/
export function saveInspectionRecord(params: InspectionRecordSaveParams) {
return post<void>("/rest/inspectionRecord/save", params);
}
// ===== 完成检测(检测评分提交)=====
/**
* POST `/rest/inspectionRecord/completeInspection` 请求体
* @example
* {
* "taskId": 0,
* "exteriorScore": 0,
* "exteriorComment": "",
* "skeletonLevel": "",
* "skeletonComment": "",
* "interiorLevel": "",
* "interiorComment": "",
* "overallScore": 0,
* "overallComment": ""
* }
*/
export interface CompleteInspectionParams {
taskId: number | string;
exteriorScore: number;
exteriorComment: string;
skeletonLevel: string;
skeletonComment: string;
interiorLevel: string;
interiorComment: string;
overallScore: number;
overallComment: string;
}
/** `completeInspection` 成功时 `data`:有未完成项时带首项节点信息(多为大项 rootNodeId) */
export interface CompleteInspectionResultData {
firstUncompletedNodeId?: null | number | string;
firstUncompletedNodeName?: null | string;
}
/**
* 完成检测(提交检测评分)
*/
export function completeInspection(params: CompleteInspectionParams) {
return post<CompleteInspectionResultData>("/rest/inspectionRecord/completeInspection", params);
}
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from "vue"; import { ref, watch } from "vue";
import type { InspectionNode } from "@api";
import type { CustomizeFormValidateResult } from "@/types/views/car-detail"; import type { CustomizeFormValidateResult } from "@/types/views/car-detail";
import selectDatePicker from "@/components/customizeForm/selectDatePicker.vue"; import selectDatePicker from "@/components/CustomizeForm/selectDatePicker.vue";
import selectDropdown from "@/components/customizeForm/selectDropdown.vue"; import selectDropdown from "@/components/CustomizeForm/selectDropdown.vue";
import buttonSelect from "@/components/customizeForm/buttonSelect.vue"; import buttonSelect from "@/components/CustomizeForm/buttonSelect.vue";
import radioSelect from "@/components/customizeForm/radioSelect.vue"; import radioSelect from "@/components/CustomizeForm/radioSelect.vue";
import customizeUploadFile from "@/components/customizeForm/customizeUploadFile.vue"; import customizeUploadFile from "@/components/CustomizeForm/customizeUploadFile.vue";
// 获取父组件传递数据 // 获取父组件传递数据
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
leafNodes?: []; leafNodes?: InspectionNode[];
bigModuleLabel?: string; bigModuleLabel?: string;
subTabLabel?: string; subTabLabel?: string;
allowNoStructure?: boolean; allowNoStructure?: boolean;
...@@ -21,7 +22,14 @@ const props = withDefaults( ...@@ -21,7 +22,14 @@ const props = withDefaults(
allowNoStructure: false, allowNoStructure: false,
}); });
const columnsList = ref([]); type InspectionColumnRow = InspectionNode & {
value?: string | number;
valueKey?: string;
valueText?: string;
};
/** 叶子列(含展示用 value 等扩展字段) */
const columnsList = ref<InspectionColumnRow[]>([]);
const resultStatus = ref(false); const resultStatus = ref(false);
const form = ref({}); const form = ref({});
const rules = ref({}); const rules = ref({});
...@@ -31,7 +39,10 @@ const pageLoading = ref(false); ...@@ -31,7 +39,10 @@ const pageLoading = ref(false);
watch(() => props.leafNodes, (nodes) => { watch(() => props.leafNodes, (nodes) => {
pageLoading.value = true; pageLoading.value = true;
columnsList.value = (nodes || []).map((item: any) => ({ ...item, value: getValueText(item), })); columnsList.value = (nodes || []).map((item) => ({
...item,
value: getValueText(item),
})) as InspectionColumnRow[];
console.log('watchLeafNodes', columnsList.value); console.log('watchLeafNodes', columnsList.value);
setTimeout(() => { setTimeout(() => {
pageLoading.value = false; pageLoading.value = false;
...@@ -55,9 +66,15 @@ function getValueText(item: any) { ...@@ -55,9 +66,15 @@ function getValueText(item: any) {
// 提交数据 // 提交数据
function setSubmitData() { function setSubmitData() {
let returnData: never[] = []; const returnData: {
nodeId: number;
nodeName: string;
resultStatus: number;
remark: string;
data: Record<string, unknown>[];
}[] = [];
columnsList.value.forEach((item: any) => { columnsList.value.forEach((item: any) => {
let dataList: never[] = []; const dataList: Record<string, unknown>[] = [];
const inputList = ['text_input', 'textarea_input', 'number_input', 'date_picker']; const inputList = ['text_input', 'textarea_input', 'number_input', 'date_picker'];
const dropdownList = ['dropdown', 'radio_button_select']; const dropdownList = ['dropdown', 'radio_button_select'];
if (inputList.includes(item.interactionType) && item.value != null && item.value !== "") { if (inputList.includes(item.interactionType) && item.value != null && item.value !== "") {
......
...@@ -5,9 +5,7 @@ ...@@ -5,9 +5,7 @@
import { Defaults, Request } from "glsk-toolkit"; import { Defaults, Request } from "glsk-toolkit";
import { showToast } from "vant"; import { showToast } from "vant";
import { CONFIG_CACHE_KEY, CONFIG_CENTER_URL } from "./constants"; import { CONFIG_CACHE_KEY, CONFIG_CENTER_URL, TOKEN_KEY } from "./constants";
const TOKEN_KEY = "venus_usedcar_token";
const defaultBaseURL = import.meta.env.VITE_API_BASE_URL ?? ""; const defaultBaseURL = import.meta.env.VITE_API_BASE_URL ?? "";
let config: Record<string, unknown> = {}; let config: Record<string, unknown> = {};
......
/** /**
* 配置中心常量 * 应用级常量(配置中心、鉴权存储 key 等)
*/ */
/** 二手车 H5 配置请求 URL */ /** 二手车 H5 配置请求 URL */
export const CONFIG_CENTER_URL = export const CONFIG_CENTER_URL =
"https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-usedcar-config&env=develop"; "https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-usedcar-config&env=develop";
/** 配置缓存 key */ /** 配置缓存 key */
export const CONFIG_CACHE_KEY = "venus_usedcar_config"; export const CONFIG_CACHE_KEY = "venus_usedcar_config";
/** localStorage:登录 token(存裸 token,请求头由封装层加 Bearer) */
export const TOKEN_KEY = "venus_usedcar_token";
/** sessionStorage:未登录时记录目标路径,登录成功后回跳 */
export const LOGIN_REDIRECT_KEY = "venus_usedcar_login_redirect";
...@@ -4,4 +4,9 @@ export { ...@@ -4,4 +4,9 @@ export {
getConfig, getConfig,
getRequestApi, getRequestApi,
} from "./center.ts"; } from "./center.ts";
export { CONFIG_CACHE_KEY, CONFIG_CENTER_URL } from "./constants.ts"; export {
CONFIG_CACHE_KEY,
CONFIG_CENTER_URL,
LOGIN_REDIRECT_KEY,
TOKEN_KEY,
} from "./constants.ts";
...@@ -2,10 +2,13 @@ import { createRouter, createWebHistory } from "vue-router"; ...@@ -2,10 +2,13 @@ import { createRouter, createWebHistory } from "vue-router";
import { closeToast, showLoadingToast } from "vant"; import { closeToast, showLoadingToast } from "vant";
import { LOGIN_REDIRECT_KEY } from "@/config/constants";
import routes from "./routes.ts"; import routes from "./routes.ts";
import { useUserStore } from "@stores/modules/user.ts"; import { useUserStore } from "@stores/modules/user.ts";
const LOGIN_REDIRECT_KEY = "venus_usedcar_login_redirect"; const ROUTE_LOADING_DELAY_MS = 200;
let routeLoadingTimer: ReturnType<typeof setTimeout> | undefined;
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
...@@ -24,12 +27,22 @@ const WHITE_LIST: string[] = ["/login"]; ...@@ -24,12 +27,22 @@ const WHITE_LIST: string[] = ["/login"];
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
const userStore = useUserStore(); const userStore = useUserStore();
if (routeLoadingTimer !== undefined) {
clearTimeout(routeLoadingTimer);
routeLoadingTimer = undefined;
}
if (!to.meta.hideRouteLoading) {
routeLoadingTimer = window.setTimeout(() => {
routeLoadingTimer = undefined;
showLoadingToast({ showLoadingToast({
message: "加载中...", message: "加载中...",
forbidClick: true, forbidClick: true,
duration: 0, duration: 0,
loadingType: "spinner", loadingType: "spinner",
}); });
}, ROUTE_LOADING_DELAY_MS);
}
if (to.meta.title) { if (to.meta.title) {
document.title = `${to.meta.title} - ${import.meta.env.VITE_APP_TITLE}`; document.title = `${to.meta.title} - ${import.meta.env.VITE_APP_TITLE}`;
...@@ -61,6 +74,10 @@ router.beforeEach((to, from, next) => { ...@@ -61,6 +74,10 @@ router.beforeEach((to, from, next) => {
}); });
router.afterEach(() => { router.afterEach(() => {
if (routeLoadingTimer !== undefined) {
clearTimeout(routeLoadingTimer);
routeLoadingTimer = undefined;
}
closeToast(); closeToast();
}); });
......
...@@ -17,6 +17,7 @@ const routes: RouteRecordRaw[] = [ ...@@ -17,6 +17,7 @@ const routes: RouteRecordRaw[] = [
meta: { meta: {
title: "登录", title: "登录",
showTabBar: false, showTabBar: false,
hideRouteLoading: true,
}, },
}, },
{ {
...@@ -68,15 +69,22 @@ const routes: RouteRecordRaw[] = [ ...@@ -68,15 +69,22 @@ const routes: RouteRecordRaw[] = [
}, },
}, },
{ {
path: "word-order-detail/:id", path: "work-order-detail/:id",
name: "WorkOrderDetail", name: "WorkOrderDetail",
component: () => import("@views/word-order-detail/index.vue"), component: () => import("@views/work-order-detail/index.vue"),
meta: { meta: {
title: "工单详情", title: "工单详情",
keepAlive: false, keepAlive: false,
showTabBar: false, showTabBar: false,
}, },
}, },
{
path: "word-order-detail/:id",
redirect: (to) => ({
name: "WorkOrderDetail",
params: { id: to.params.id },
}),
},
], ],
}, },
{ {
...@@ -85,6 +93,7 @@ const routes: RouteRecordRaw[] = [ ...@@ -85,6 +93,7 @@ const routes: RouteRecordRaw[] = [
component: () => import("@views/404/index.vue"), component: () => import("@views/404/index.vue"),
meta: { meta: {
title: "页面不存在", title: "页面不存在",
hideRouteLoading: true,
}, },
}, },
]; ];
......
...@@ -2,12 +2,9 @@ import { defineStore } from "pinia"; ...@@ -2,12 +2,9 @@ import { defineStore } from "pinia";
import { ref, computed } from "vue"; import { ref, computed } from "vue";
import { logout as requestAuthLogout } from "@/api/modules/user"; import { logout as requestAuthLogout } from "@/api/modules/user";
import { LOGIN_REDIRECT_KEY, TOKEN_KEY } from "@/config/constants";
import { notifyHostLogout } from "@/utils/webviewBridge"; import { notifyHostLogout } from "@/utils/webviewBridge";
const TOKEN_KEY = "venus_usedcar_token";
/** 与 `router/index.ts`、登录页一致,登出时清掉避免沿用旧回跳地址 */
const LOGIN_REDIRECT_KEY = "venus_usedcar_login_redirect";
export interface UserInfo { export interface UserInfo {
id: number; id: number;
nickname: string; nickname: string;
......
...@@ -6,6 +6,8 @@ declare module "vue-router" { ...@@ -6,6 +6,8 @@ declare module "vue-router" {
keepAlive?: boolean; keepAlive?: boolean;
showTabBar?: boolean; showTabBar?: boolean;
requiresAuth?: boolean; requiresAuth?: boolean;
/** 为 true 时不展示全局路由 Loading、不参与延迟 Toast */
hideRouteLoading?: boolean;
} }
} }
......
import axios, { AxiosInstance, AxiosResponse } from "axios"; import axios, { AxiosInstance, AxiosResponse } from "axios";
import { showToast } from "vant"; import { showToast } from "vant";
import { TOKEN_KEY } from "@/config/constants";
import { getConfig } from "../config/center"; import { getConfig } from "../config/center";
/** /**
...@@ -48,7 +49,6 @@ export interface RequestConfig { ...@@ -48,7 +49,6 @@ export interface RequestConfig {
[key: string]: unknown; [key: string]: unknown;
} }
const TOKEN_KEY = "venus_usedcar_token";
const defaultBaseURL = import.meta.env.VITE_API_BASE_URL ?? ""; const defaultBaseURL = import.meta.env.VITE_API_BASE_URL ?? "";
/** 业务成功码 */ /** 业务成功码 */
......
import type { RouteLocationNormalizedLoaded } from "vue-router";
import type { BigModule } from "@/types/views/car-detail";
import type { CompleteInspectionResultData, InspectionResultVO, InspectionTemplateDefaultData } from "@api";
import {
applyResolvedInitialValuesToLeafNodes,
getInspectionChildren,
getInspectionRootNodes,
getInspectionTemplateDefault,
} from "@api";
import { computed, ref } from "vue";
import { showToast } from "vant";
/** 检测评分大项的固定 key(非接口返回,手动追加至大项末尾) */
export const SCORE_BIG_KEY = "__score_big__";
/** 与接口一致:0 / "0" 未完成,1 / "1" 已完成 */
export function isInspectionVoCompleted(vo: InspectionResultVO | undefined): boolean {
return vo?.completedFlag === 1 || String(vo?.completedFlag ?? "") === "1";
}
/** `completedFlag` 字段可能是数字或字符串,进度与 Tab 勾选统一用此判断 */
export function isCompletedFlagFieldDone(flag: unknown): boolean {
return flag === 1 || String(flag ?? "") === "1";
}
/** 提交评分返回里是否仍有未完成项(`firstUncompletedNodeId` 有有效值) */
export function hasCompleteInspectionUncompletedHint(data: CompleteInspectionResultData | undefined): boolean {
if (!data) return false;
const id = data.firstUncompletedNodeId;
if (id === undefined || id === null) return false;
if (typeof id === "string" && id.trim() === "") return false;
return true;
}
export function useInspectModules(route: RouteLocationNormalizedLoaded) {
const taskId = ref<number | string>("");
const bigModules = ref<BigModule[]>([]);
const activeBigKey = ref<number | string>("");
const showModulePicker = ref(false);
const loading = ref(false);
const activeSubKey = ref<number | string>("");
const activeBigModule = computed(
() =>
bigModules.value.find((module) => module.key === activeBigKey.value) ?? bigModules.value[0]
);
const isSubtabInspectionView = computed(
() => !loading.value && bigModules.value.length > 0 && activeBigKey.value !== SCORE_BIG_KEY
);
const showInspectionProgressBar = computed(
() =>
activeBigKey.value !== SCORE_BIG_KEY && activeBigModule.value?.hasSecondaryTabs !== false
);
const mainInspectionBigModules = computed(() =>
bigModules.value.filter((module) => module.key !== SCORE_BIG_KEY)
);
const flattenedMainSubTabs = computed(() =>
mainInspectionBigModules.value.flatMap((module) => module.subTabs)
);
const progressTotal = computed(() => flattenedMainSubTabs.value.length);
const progressDone = computed(() =>
flattenedMainSubTabs.value.filter((subTab) => isCompletedFlagFieldDone(subTab.completedFlag)).length
);
const remainingSubTabCount = computed(() => progressTotal.value - progressDone.value);
const activeSubTab = computed(
() =>
activeBigModule.value?.subTabs.find((subTab) => subTab.key === activeSubKey.value) ??
activeBigModule.value?.subTabs[0]
);
const currentLeafNodes = computed(() => activeSubTab.value?.leafNodes ?? []);
async function initializeInspection() {
try {
loading.value = true;
const rawId = route.query.id ?? route.params.id;
const routeTaskId = Array.isArray(rawId) ? rawId[0] : rawId;
if (routeTaskId === undefined || routeTaskId === null || routeTaskId === "") {
showToast("缺少检测工单ID");
return;
}
taskId.value = routeTaskId;
const rootNodes = await getInspectionRootNodes(taskId.value);
if (!rootNodes || rootNodes.length === 0) {
showToast("暂无检测模板数据");
return;
}
const assembledBigModules: BigModule[] = [
...rootNodes.map((root) => ({
key: root.id,
label: root.nodeName,
nodeId: root.id,
subTabs: [],
})),
{ key: SCORE_BIG_KEY, label: "检测评分", subTabs: [] },
];
bigModules.value = assembledBigModules;
const firstMain = bigModules.value[0];
if (firstMain) {
activeBigKey.value = firstMain.key;
await loadSubTabsForBigModule(firstMain.key);
}
} catch (error) {
console.error("初始化检测页失败:", error);
showToast("加载检测模板失败");
} finally {
loading.value = false;
}
}
async function loadSubTabsForBigModule(
bigModuleKey: number | string,
syncSelection = true,
force = false
) {
if (bigModuleKey === SCORE_BIG_KEY) return;
try {
const targetBigModule = bigModules.value.find((module) => module.key === bigModuleKey);
if (!targetBigModule) return;
if (!force && targetBigModule.subTabs.length > 0) {
if (syncSelection) {
activeSubKey.value = targetBigModule.subTabs[0]!.key;
}
return;
}
const childLevelNodes = await getInspectionChildren(bigModuleKey, taskId.value);
const list = Array.isArray(childLevelNodes) ? childLevelNodes : [];
const firstChild = list[0];
const isDirectLeafChildren = firstChild !== undefined && firstChild.nodeType === 3;
let templateDefaultData: InspectionTemplateDefaultData | null = null;
try {
templateDefaultData = await getInspectionTemplateDefault(taskId.value);
} catch (error) {
console.error("获取模板默认值失败:", error);
}
if (isDirectLeafChildren) {
targetBigModule.hasSecondaryTabs = false;
const leafNodes = applyResolvedInitialValuesToLeafNodes(list, templateDefaultData);
const allDone = list.every((n) => isInspectionVoCompleted(n.inspectionResultVO));
targetBigModule.subTabs = [
{
key: "__flat_leaf__",
label: targetBigModule.label,
nodeId: targetBigModule.nodeId,
leafNodes,
completedFlag: allDone ? 1 : 0,
},
];
} else {
targetBigModule.hasSecondaryTabs = true;
targetBigModule.subTabs = list.map((node) => ({
key: node.id,
label: node.nodeName,
nodeId: node.id,
leafNodes: applyResolvedInitialValuesToLeafNodes(node.childrenNodes, templateDefaultData),
completedFlag: isInspectionVoCompleted(node.inspectionResultVO) ? 1 : 0,
}));
}
if (targetBigModule.subTabs.length > 0 && syncSelection) {
activeSubKey.value = targetBigModule.subTabs[0]!.key;
}
} catch (error) {
console.error("加载二级项失败:", error);
showToast("加载二级项失败");
}
}
async function switchToUncompletedInspectionNode(nodeId: number | string): Promise<boolean> {
const idStr = String(nodeId);
const mains = mainInspectionBigModules.value;
const rootHit = mains.find(
(m) => String(m.key) === idStr || String(m.nodeId ?? "") === idStr
);
if (rootHit) {
activeBigKey.value = rootHit.key;
await loadSubTabsForBigModule(rootHit.key, true, true);
activeSubKey.value = rootHit.subTabs[0]?.key ?? "";
return true;
}
for (const m of mains) {
await loadSubTabsForBigModule(m.key, false, true);
const sub = m.subTabs.find(
(s) => String(s.key) === idStr || String(s.nodeId ?? "") === idStr
);
if (sub) {
activeBigKey.value = m.key;
activeSubKey.value = sub.key;
return true;
}
}
return false;
}
function advanceInspectionStep() {
const activeModule = activeBigModule.value;
if (!activeModule) return;
const subTabsOfActive = activeModule.subTabs;
const activeSubIndex = subTabsOfActive.findIndex((subTab) => subTab.key === activeSubKey.value);
if (activeSubIndex < subTabsOfActive.length - 1) {
activeSubKey.value = subTabsOfActive[activeSubIndex + 1]!.key;
return;
}
const mains = mainInspectionBigModules.value;
const activeMainIndex = mains.findIndex((module) => module.key === activeBigKey.value);
if (activeMainIndex < mains.length - 1) {
const nextMain = mains[activeMainIndex + 1]!;
activeBigKey.value = nextMain.key;
loadSubTabsForBigModule(nextMain.key, true, true).then(() => {
activeSubKey.value = nextMain.subTabs[0]?.key ?? "";
});
} else {
activeBigKey.value = SCORE_BIG_KEY;
activeSubKey.value = "";
}
}
function onOpenModulePicker() {
showModulePicker.value = true;
}
return {
SCORE_BIG_KEY,
taskId,
bigModules,
activeBigKey,
activeSubKey,
showModulePicker,
loading,
activeBigModule,
isSubtabInspectionView,
showInspectionProgressBar,
mainInspectionBigModules,
progressTotal,
progressDone,
remainingSubTabCount,
activeSubTab,
currentLeafNodes,
initializeInspection,
loadSubTabsForBigModule,
switchToUncompletedInspectionNode,
advanceInspectionStep,
onOpenModulePicker,
};
}
export type InspectModulesReturn = ReturnType<typeof useInspectModules>;
import type { BigModule, CustomizeFormValidateNode, CustomizeFormValidateResult } from "@/types/views/car-detail";
import type { LeafNodeRecord } from "@api";
import customizeForm from "@/components/CustomizeForm/Index.vue";
import {
completeInspection,
saveInspectionRecord,
} from "@api";
import { isRequestFailureAlreadyHandled } from "@utils/request";
import { ref, type Ref } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import ScoreForm from "../components/ScoreForm.vue";
import {
hasCompleteInspectionUncompletedHint,
SCORE_BIG_KEY,
type InspectModulesReturn,
} from "./useInspectModules";
function buildInspectionSavePayload(
modules: InspectModulesReturn,
leafNodes: LeafNodeRecord[],
nextFlag: boolean
) {
const { taskId, activeBigModule, activeSubTab } = modules;
const hasSecondaryTabs = activeBigModule.value?.hasSecondaryTabs === true;
return {
taskId: taskId.value,
locationModule: activeBigModule.value?.nodeId ?? 0,
locationSubModule: hasSecondaryTabs ? (activeSubTab.value?.nodeId ?? 0) : null,
nextFlag,
leafNodes,
};
}
function leafRecordFromValidateNode(raw: CustomizeFormValidateNode): LeafNodeRecord {
return {
data: (raw.data ?? []).map((item) => ({
interactionType: item.interactionType ?? "",
remark: item.remark ?? "",
valueKey: item.valueKey ?? "",
valueSeq: item.valueSeq ?? 0,
valueText: item.valueText ?? "",
})),
nodeId: Number(raw.nodeId),
nodeName: String(raw.nodeName ?? ""),
remark: String(raw.remark ?? ""),
resultStatus: Number(raw.resultStatus),
};
}
export function useInspectSubmit(
modules: InspectModulesReturn,
customizeFormRef: Ref<InstanceType<typeof customizeForm> | null>,
inspectionScoreFormRef: Ref<InstanceType<typeof ScoreForm> | null>
) {
const router = useRouter();
const submitting = ref(false);
async function saveCurrentLeafInspectionRecord(nextFlag: boolean): Promise<boolean> {
const saved = (await customizeFormRef.value?.saveData?.()) as CustomizeFormValidateResult | undefined;
const rows = saved?.data;
if (!rows?.length) return false;
const leafNodes = rows.map((row) => leafRecordFromValidateNode(row));
await saveInspectionRecord(buildInspectionSavePayload(modules, leafNodes, nextFlag));
return true;
}
async function persistCurrentSubTabSilently() {
if (modules.activeBigKey.value === SCORE_BIG_KEY) return;
try {
await saveCurrentLeafInspectionRecord(false);
} catch {
/* 静默失败,不阻断切换 */
}
}
async function onSelectBigModule(selectedBigModule: BigModule) {
modules.showModulePicker.value = false;
if (selectedBigModule.key === modules.activeBigKey.value) return;
await persistCurrentSubTabSilently();
modules.activeBigKey.value = selectedBigModule.key;
modules.activeSubKey.value = "";
if (selectedBigModule.key !== SCORE_BIG_KEY) {
await modules.loadSubTabsForBigModule(selectedBigModule.key, true, true);
}
}
async function onSelectSubTab(subTabKey: number | string) {
if (subTabKey === modules.activeSubKey.value) return;
await persistCurrentSubTabSilently();
const bigKey = modules.activeBigKey.value;
if (bigKey !== SCORE_BIG_KEY) {
await modules.loadSubTabsForBigModule(bigKey, false, true);
}
modules.activeSubKey.value = subTabKey;
}
async function onNext() {
if (submitting.value) return;
try {
submitting.value = true;
const res = (await customizeFormRef.value?.validate?.()) as CustomizeFormValidateResult | undefined;
if (!res?.success) {
showToast(res?.message ?? "校验失败");
return;
}
const savedOk = await saveCurrentLeafInspectionRecord(true);
if (!savedOk) {
showToast("未获取到表单数据");
return;
}
if (modules.activeBigKey.value !== SCORE_BIG_KEY) {
await modules.loadSubTabsForBigModule(modules.activeBigKey.value, false, true);
}
modules.advanceInspectionStep();
} catch (error) {
if (!isRequestFailureAlreadyHandled(error)) {
showToast("保存失败,请重试");
}
} finally {
submitting.value = false;
}
}
function onBack() {
router.back();
}
async function onPrev() {
if (submitting.value) return;
try {
submitting.value = true;
if (modules.activeBigKey.value === SCORE_BIG_KEY) {
const mains = modules.mainInspectionBigModules.value;
const lastMain = mains[mains.length - 1];
if (lastMain) {
modules.activeBigKey.value = lastMain.key;
await modules.loadSubTabsForBigModule(lastMain.key, true, true);
modules.activeSubKey.value = lastMain.subTabs[lastMain.subTabs.length - 1]?.key ?? "";
}
return;
}
await saveCurrentLeafInspectionRecord(false);
const subTabsOfActive = modules.activeBigModule.value?.subTabs ?? [];
const activeSubIndex = subTabsOfActive.findIndex(
(subTab) => subTab.key === modules.activeSubKey.value
);
if (activeSubIndex > 0) {
const prevSubKey = subTabsOfActive[activeSubIndex - 1]!.key;
await modules.loadSubTabsForBigModule(modules.activeBigKey.value, false, true);
modules.activeSubKey.value = prevSubKey;
} else {
const mains = modules.mainInspectionBigModules.value;
const activeMainIndex = mains.findIndex((m) => m.key === modules.activeBigKey.value);
if (activeMainIndex > 0) {
const previousMain = mains[activeMainIndex - 1]!;
modules.activeBigKey.value = previousMain.key;
await modules.loadSubTabsForBigModule(previousMain.key, true, true);
modules.activeSubKey.value =
previousMain.subTabs[previousMain.subTabs.length - 1]?.key ?? "";
}
}
} catch (error) {
if (!isRequestFailureAlreadyHandled(error)) {
showToast("保存失败,请重试");
}
} finally {
submitting.value = false;
}
}
async function onSubmitScore() {
if (!inspectionScoreFormRef.value?.validate()) return;
if (submitting.value) return;
try {
submitting.value = true;
const result = await completeInspection(
inspectionScoreFormRef.value.getCompleteInspectionPayload(modules.taskId.value)
);
if (result && hasCompleteInspectionUncompletedHint(result)) {
const name = result.firstUncompletedNodeName;
const nid = result.firstUncompletedNodeId;
showToast(
name ? `检测未完成,请先完成「${name}」` : "检测未完成,请先完成未填项"
);
const switched =
nid !== undefined && nid !== null && (await modules.switchToUncompletedInspectionNode(nid));
if (!switched) {
showToast("未找到对应检测模块,请手动切换大项");
}
return;
}
showToast("评分已提交");
} catch (error) {
if (!isRequestFailureAlreadyHandled(error)) {
showToast("提交失败,请重试");
}
} finally {
submitting.value = false;
}
}
return {
submitting,
onSelectBigModule,
onSelectSubTab,
onNext,
onPrev,
onSubmitScore,
onBack,
};
}
...@@ -4,7 +4,7 @@ import type { ReportItem } from "@/types/views/car-list"; ...@@ -4,7 +4,7 @@ import type { ReportItem } from "@/types/views/car-list";
import { computed, onActivated, ref, watch } from "vue"; import { computed, onActivated, ref, watch } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import { getInspectReportPage } from "@/api/modules/inspect-report.ts"; import { getInspectReportPage } from "@/api/modules/inspect-report";
import PageTop from "@/components/PageTop.vue"; import PageTop from "@/components/PageTop.vue";
const router = useRouter(); const router = useRouter();
......
...@@ -7,7 +7,7 @@ import { login, sendSmsCode } from "@/api/modules/user.ts"; ...@@ -7,7 +7,7 @@ import { login, sendSmsCode } from "@/api/modules/user.ts";
import { useUserStore } from "@/stores/modules/user.ts"; import { useUserStore } from "@/stores/modules/user.ts";
import { notifyHostToken } from "@/utils/webviewBridge"; import { notifyHostToken } from "@/utils/webviewBridge";
const LOGIN_REDIRECT_KEY = "venus_usedcar_login_redirect"; import { LOGIN_REDIRECT_KEY } from "@/config/constants";
export function useLogin() { export function useLogin() {
const router = useRouter(); const router = useRouter();
......
...@@ -6,7 +6,7 @@ import type { ...@@ -6,7 +6,7 @@ import type {
WorkOrderBaseInfo, WorkOrderBaseInfo,
WorkOrderDetailRemote, WorkOrderDetailRemote,
WorkOrderVehicle, WorkOrderVehicle,
} from "@/types/views/word-order-detail"; } from "@/types/views/work-order-detail";
import type { WorkOrderStatus } from "@/types/views/work-order-common"; import type { WorkOrderStatus } from "@/types/views/work-order-common";
import { computed, onMounted, ref } from "vue"; import { computed, onMounted, ref } from "vue";
...@@ -65,6 +65,12 @@ function continueCheck():void { ...@@ -65,6 +65,12 @@ function continueCheck():void {
const id = route.params.id as string; const id = route.params.id as string;
router.push({ name: "CarDetail", params: { id } }); router.push({ name: "CarDetail", params: { id } });
} }
/** 检测项目项点击:当前与「编辑工单」一致进入车辆检测页 */
function onNodeClick(_n: NodeVO) {
continueCheck();
}
const onBack=()=>{ const onBack=()=>{
router.back(); router.back();
}; };
......
...@@ -7,9 +7,6 @@ import Components from "unplugin-vue-components/vite"; ...@@ -7,9 +7,6 @@ import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers"; import { VantResolver } from "unplugin-vue-components/resolvers";
import { defineConfig, loadEnv } from "vite"; import { defineConfig, loadEnv } from "vite";
// @ts-expect-error - no types provided
import pxToViewport from "postcss-px-to-viewport-8-plugin";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename); const __dirname = dirname(__filename);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!