Commit 189df30e by 张立顺

Merge branch 'release/venus-usedcar-h5/1.0.0' of 192.168.3.233:monorepo/venus in…

…to release/venus-usedcar-h5/1.0.0
2 parents 718e843d 5ff5714f
Pipeline #168 for 189df30e failed in 0 seconds
......@@ -118,7 +118,6 @@ function setupdate() {
.selectBut {
position: relative;
float: left;
width: calc(33.333% - 12px);
height: 36px;
margin-right: 6px;
margin-bottom: 12px;
......@@ -132,6 +131,8 @@ function setupdate() {
background: #f9f9f9;
border: 1px solid #f9f9f9;
border-radius: 6px;
padding: 0 16px;
min-width: 30%;
}
.pitchOn {
......
......@@ -47,9 +47,10 @@ async function onFileChange(ev: Event) {
const file = input.files?.[0];
input.value = "";
if (!file) return;
const fileSize = file.size / 1024 / 1024;
if (fileSize && fileSize > 5) {
return showToast(`文件大小不能超过5MB`);
const maxSize10MB = 10 * 1024 * 1024;
if (file.size > maxSize10MB) {
showToast("文件大小不能超过10MB");
return;
}
uploading.value = true;
try {
......
......@@ -48,16 +48,16 @@ async function onFileChange(ev: Event) {
const file = input.files?.[0];
input.value = "";
if (!file) return;
const fileSize = file.size / 1024 / 1024;
// 检查文件大小是否超过限制 10MB
if (props.item.interactionType == 'image_upload' && fileSize && fileSize > 5) {
return showToast(`文件大小不能超过5MB`);;
const maxSize10MB = 10 * 1024 * 1024;
const maxSize100MB = 100 * 1024 * 1024;
if (props.item.interactionType == 'image_upload' && file.size > maxSize10MB) {
showToast("文件大小不能超过10MB");
return;
}
// 检查文件大小是否超过限制 10MB
if (props.item.interactionType == 'video_upload' && fileSize && fileSize > 100) {
return showToast(`文件大小不能超过100MB`);
if (props.item.interactionType == 'video_upload' && file.size > maxSize100MB) {
showToast("文件大小不能超过100MB");
return;
}
uploading.value = true;
try {
const res = await uploadFile(file);
......
......@@ -8,6 +8,13 @@ import { showToast } from "vant";
import { CONFIG_CACHE_KEY, CONFIG_CENTER_URL, TOKEN_KEY } from "./constants";
const defaultBaseURL = import.meta.env.VITE_API_BASE_URL ?? "";
const APP_BASE_PATH = (() => {
const base = import.meta.env.BASE_URL ?? "/";
if (!base || base === "/") {
return "";
}
return base.endsWith("/") ? base.slice(0, -1) : base;
})();
let config: Record<string, unknown> = {};
let requestInstance: null | Request = null;
......@@ -53,7 +60,7 @@ function initRequestInstance(cfg: Record<string, unknown>): void {
case 401: {
showToast("登录已过期,请重新登录");
localStorage.removeItem(TOKEN_KEY);
window.location.href = "/login";
window.location.href = `${APP_BASE_PATH}/login`;
break;
}
......
......@@ -17,6 +17,8 @@ export interface SubTab {
}
export interface BigModule {
/** 大项完成标志:0 未完成,1 已完成(接口可能返回字符串) */
completedFlag?: 0 | 1 | string;
/** 是否存在二级分组 Tab;false 表示子节点直接为叶子(nodeType=3),不展示二级 Tab */
hasSecondaryTabs?: boolean;
key: number | string;
......
......@@ -4,29 +4,6 @@ import { showToast } from "vant";
import { getConfig } from "../config/center";
/**
* 已在 `handleResponse` 中提示过用户(或 1006 已跳转登录),页面 catch 中勿再套一层「保存失败」等通用文案。
*/
export class ApiHandledError extends Error {
constructor(message: string) {
super(message);
this.name = "ApiHandledError";
Object.setPrototypeOf(this, ApiHandledError.prototype);
}
}
/** 请求层已 toast / 已处理:避免业务页 catch 再 showToast 盖住接口 message */
export function isRequestFailureAlreadyHandled(error: unknown): boolean {
if (error instanceof ApiHandledError) {
return true;
}
if (axios.isAxiosError(error)) {
// 走 axios 错误拦截器时均已 showToast(含无 response 的 default 分支)
return true;
}
return false;
}
export interface ApiResponse<T = unknown> {
code?: number | string;
data: T;
......@@ -50,36 +27,51 @@ export interface RequestConfig {
}
const defaultBaseURL = import.meta.env.VITE_API_BASE_URL ?? "";
/** 业务成功码 */
const REQUEST_TIMEOUT = 15_000;
const HTTP_CODE_UNAUTHORIZED = 401;
const HTTP_CODE_FORBIDDEN = 403;
const HTTP_CODE_SERVER_ERROR = 500;
const BIZ_CODE_OK = 200;
/** 不统一 toast / 由调用方自行处理的业务码 */
const BIZ_CODES_NO_GLOBAL_TOAST = new Set([1000, 1002, 1003, 1010]);
/** 未登录或登录过期 */
const BIZ_CODE_UNAUTHORIZED = 1006;
const DEFAULT_EXPIRED_MESSAGE = "登录已过期,请重新登录";
const BIZ_CODES_NO_GLOBAL_TOAST = new Set([1000, 1002, 1003, 1010]);
function normalizeBizCode(code: unknown): null | number {
if (code === null || code === undefined || code === "") {
return null;
const APP_BASE_PATH = (() => {
const base = import.meta.env.BASE_URL ?? "/";
if (!base || base === "/") {
return "";
}
const n = Number(code);
return Number.isNaN(n) ? null : n;
}
return base.endsWith("/") ? base.slice(0, -1) : base;
})();
function redirectToLogin(message?: string) {
showToast(message || "登录已过期,请重新登录");
localStorage.removeItem(TOKEN_KEY);
window.location.href = "/login";
let axiosInstance: AxiosInstance | null = null;
let isRedirectingToLogin = false;
let loginNavigationInFlight: null | Promise<void> = null;
/**
* 已在请求层提示过用户(或 1006 已跳登录),业务页 catch 不要再追加通用失败文案。
*/
export class ApiHandledError extends Error {
constructor(message: string) {
super(message);
this.name = "ApiHandledError";
Object.setPrototypeOf(this, ApiHandledError.prototype);
}
}
let axiosInstance: AxiosInstance | null = null;
/** 请求层已 toast / 已处理:避免业务页 catch 再 showToast 盖住接口 message */
export function isRequestFailureAlreadyHandled(error: unknown): boolean {
if (error instanceof ApiHandledError) return true;
// 走 axios 错误拦截器时均已 showToast(含无 response 的 default 分支)
return axios.isAxiosError(error);
}
function getToken(): string {
const token = localStorage.getItem(TOKEN_KEY);
return token ? `Bearer ${token}` : "";
}
function resolveBaseURL(): string {
function resolveBaseUrl(): string {
const cfg = getConfig() as Record<string, unknown>;
const apiBaseUrl =
((cfg.apiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseURL ??
......@@ -93,20 +85,136 @@ function resolveBaseURL(): string {
return apiBaseUrl || defaultBaseURL || "/";
}
function getInstance(): AxiosInstance {
if (axiosInstance) return axiosInstance;
function normalizeBizCode(code: unknown): null | number {
if (code === null || code === undefined || code === "") return null;
const normalized = Number(code);
return Number.isNaN(normalized) ? null : normalized;
}
const baseURL = resolveBaseURL();
function normalizePathname(pathname: string): string {
if (!pathname) return "/";
if (pathname.length > 1 && pathname.endsWith("/")) {
return pathname.slice(0, -1);
}
return pathname;
}
function isAtLoginPath(): boolean {
return /\/login$/.test(normalizePathname(window.location.pathname));
}
function buildLoginUrlWithHostContext(): string {
const currentUrl = new URL(window.location.href);
const loginUrl = new URL(`${APP_BASE_PATH}/login`, window.location.origin);
const openType = currentUrl.searchParams.get("openType");
if (openType) {
loginUrl.searchParams.set("openType", openType);
}
return `${loginUrl.pathname}${loginUrl.search}`;
}
function getLoginRouteQueryFromCurrentUrl(): { openType?: string } {
const currentUrl = new URL(window.location.href);
const openType = currentUrl.searchParams.get("openType");
return openType ? { openType } : {};
}
function clearAuthState() {
localStorage.removeItem(TOKEN_KEY);
// 同步清理 Pinia,避免路由守卫继续判定为已登录。
void import("@/stores/modules/user")
.then(({ useUserStore }) => {
useUserStore().setToken("");
})
.catch(() => {
// Store 清理失败不阻塞登录跳转。
});
}
async function navigateToLogin() {
if (isAtLoginPath()) return;
try {
const { default: router } = await import("@/router");
await router.replace({
path: "/login",
query: getLoginRouteQueryFromCurrentUrl(),
});
} catch {
// 无法获取 router 时兜底硬跳,避免停留在非法态页面。
if (!isAtLoginPath()) {
window.location.replace(buildLoginUrlWithHostContext());
}
}
}
function ensureLoginRedirect(message: string) {
clearAuthState();
if (isAtLoginPath()) return;
if (!isRedirectingToLogin) {
isRedirectingToLogin = true;
showToast(message);
}
if (!loginNavigationInFlight) {
loginNavigationInFlight = navigateToLogin().finally(() => {
loginNavigationInFlight = null;
isRedirectingToLogin = false;
});
}
}
/** HTTP 层鉴权失败(401) */
function handleHttpUnauthorized() {
ensureLoginRedirect(DEFAULT_EXPIRED_MESSAGE);
}
/** 业务层鉴权失败(code=1006) */
function handleBizUnauthorized(message: string) {
ensureLoginRedirect(message);
}
function getHttpErrorMessage(error: unknown): string {
const err = error as {
message?: string;
response?: { data?: { message?: string } };
};
return err?.response?.data?.message || err?.message || "网络错误,请检查网络连接";
}
function handleHttpError(error: unknown) {
const err = error as { response?: { status?: number } };
const status = err?.response?.status;
const message = getHttpErrorMessage(error);
switch (status) {
case HTTP_CODE_FORBIDDEN: {
showToast("暂无权限");
break;
}
case HTTP_CODE_SERVER_ERROR: {
showToast(message || "服务器异常,请稍后重试");
break;
}
case HTTP_CODE_UNAUTHORIZED: {
handleHttpUnauthorized();
break;
}
default: {
showToast(message);
}
}
}
function isBizResponse<T>(data: ApiResponse<T> | T): data is ApiResponse<T> {
return typeof data === "object" && data !== null && ("code" in data || "success" in data);
}
function createAxiosInstance(): AxiosInstance {
const instance = axios.create({
baseURL,
timeout: 15_000,
headers: {
"Content-Type": "application/json",
},
baseURL: resolveBaseUrl(),
timeout: REQUEST_TIMEOUT,
headers: { "Content-Type": "application/json" },
});
// 请求拦截:自动附带 Token
instance.interceptors.request.use(
(config) => {
const token = getToken();
......@@ -121,42 +229,24 @@ function getInstance(): AxiosInstance {
(error) => Promise.reject(error)
);
// 响应拦截:统一处理 HTTP 状态码
instance.interceptors.response.use(
(response) => response,
(error) => {
const status = error?.response?.status as number | undefined;
const msg =
error?.response?.data?.message ||
error?.message ||
"网络错误,请检查网络连接";
switch (status) {
case 401: {
redirectToLogin();
break;
}
case 403: {
showToast("暂无权限");
break;
}
case 500: {
showToast("服务器异常,请稍后重试");
break;
}
default: {
showToast(msg);
}
}
handleHttpError(error);
return Promise.reject(error);
}
);
axiosInstance = instance;
return instance;
}
function getInstance(): AxiosInstance {
if (!axiosInstance) {
axiosInstance = createAxiosInstance();
}
return axiosInstance;
}
/** 统一处理响应,提取 data 或按业务码处理 */
async function handleResponse<T>(
promise: Promise<AxiosResponse<ApiResponse<T> | T>>
......@@ -164,35 +254,28 @@ async function handleResponse<T>(
const res = await promise;
const data = res.data as ApiResponse<T> | T;
// 兼容业务响应结构:{ code, success, message, data }
if (typeof data === "object" && data && ("code" in data || "success" in data)) {
const biz = data as ApiResponse<T>;
const codeNum = normalizeBizCode(biz.code);
// 约定:业务成功为 code === 200;未返回 code 时沿用 success 字段兼容旧接口
const isSuccess =
codeNum === BIZ_CODE_OK || (codeNum === null && biz.success === true);
if (isSuccess) {
return (biz.data ?? (data as unknown)) as T;
}
const errMsg = biz.message || biz.msg || "请求失败";
if (codeNum === BIZ_CODE_UNAUTHORIZED) {
redirectToLogin(errMsg);
throw new ApiHandledError(errMsg);
}
if (!isBizResponse(data)) {
// 非标准结构,直接返回 data
return data as T;
}
if (codeNum !== null && BIZ_CODES_NO_GLOBAL_TOAST.has(codeNum)) {
throw new Error(errMsg);
}
const codeNum = normalizeBizCode(data.code);
const isSuccess = codeNum === BIZ_CODE_OK || (codeNum === null && data.success === true);
if (isSuccess) {
return (data.data ?? (data as unknown)) as T;
}
showToast(errMsg);
const errMsg = data.message || data.msg || "请求失败";
if (codeNum === BIZ_CODE_UNAUTHORIZED) {
handleBizUnauthorized(errMsg);
throw new ApiHandledError(errMsg);
}
if (codeNum !== null && BIZ_CODES_NO_GLOBAL_TOAST.has(codeNum)) {
throw new Error(errMsg);
}
// 非标准结构,直接返回 data
return data as T;
showToast(errMsg);
throw new ApiHandledError(errMsg);
}
function get<T = unknown>(
......
......@@ -16,6 +16,7 @@ import {
getInspectionRootNodes,
getInspectionTemplateDefault,
} from "@api";
import { isRequestFailureAlreadyHandled } from "@utils/request";
import { showToast } from "vant";
/** 检测评分大项的固定 key(非接口返回,手动追加至大项末尾) */
......@@ -39,6 +40,11 @@ export function isSubTabMarkCompleted(sub: SubTab): boolean {
return isCompletedFlagFieldDone(sub.completedFlag);
}
/** 大项弹窗勾选:根据 rootNodes.completedFlag 判断是否完成 */
export function isBigModuleMarkCompleted(module: BigModule): boolean {
return isCompletedFlagFieldDone(module.completedFlag);
}
/** 二级子节点列表:总进度 = 列表长度,已完成 = 各节点 inspectionResultVO.completedFlag */
function computeSecondaryProgressFromList(list: InspectionNode[]): { done: number; total: number; } {
const nodes = Array.isArray(list) ? list : [];
......@@ -143,6 +149,48 @@ export function useInspectModules(route: RouteLocationNormalizedLoaded) {
const currentLeafNodes = computed(() => activeSubTab.value?.leafNodes ?? []);
/** 拉取 rootNodes 并刷新大项列表;保留已加载的大项二级缓存与当前选中项 */
async function refreshBigModulesFromRootNodes() {
if (taskId.value === "" || taskId.value === null || taskId.value === undefined) return;
const rootNodes = await getInspectionRootNodes(taskId.value);
if (!Array.isArray(rootNodes) || rootNodes.length === 0) return;
const oldModules = bigModules.value;
const oldByKey = new Map(oldModules.map((m) => [String(m.key), m]));
const scoreRoot = rootNodes.find((root) => String(root.id) === "-1");
const inspectionRoots = rootNodes.filter((root) => String(root.id) !== "-1");
const refreshedInspectionModules: BigModule[] = inspectionRoots.map((root) => {
const prev = oldByKey.get(String(root.id));
return {
key: root.id,
label: root.nodeName,
nodeId: root.id,
completedFlag: root.completedFlag as 0 | 1 | string | undefined,
subTabs: prev?.subTabs ?? [],
hasSecondaryTabs: prev?.hasSecondaryTabs,
secondaryProgress: prev?.secondaryProgress,
};
});
const prevScore = oldByKey.get(String(SCORE_BIG_KEY));
const scoreModule: BigModule = {
key: SCORE_BIG_KEY,
label: "检测评分",
completedFlag: scoreRoot?.completedFlag as 0 | 1 | string | undefined,
subTabs: prevScore?.subTabs ?? [],
hasSecondaryTabs: prevScore?.hasSecondaryTabs,
secondaryProgress: prevScore?.secondaryProgress,
};
bigModules.value = [...refreshedInspectionModules, scoreModule];
const activeExists = bigModules.value.some((m) => m.key === activeBigKey.value);
if (!activeExists) {
const firstMain = bigModules.value[0];
if (firstMain) activeBigKey.value = firstMain.key;
}
}
async function initializeInspection() {
try {
loading.value = true;
......@@ -155,23 +203,11 @@ export function useInspectModules(route: RouteLocationNormalizedLoaded) {
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;
await refreshBigModulesFromRootNodes();
const firstMain = bigModules.value[0];
if (firstMain) {
......@@ -180,7 +216,9 @@ export function useInspectModules(route: RouteLocationNormalizedLoaded) {
}
} catch (error) {
console.error("初始化检测页失败:", error);
showToast("加载检测模板失败");
if (!isRequestFailureAlreadyHandled(error)) {
showToast("加载检测模板失败");
}
} finally {
loading.value = false;
}
......@@ -254,7 +292,9 @@ export function useInspectModules(route: RouteLocationNormalizedLoaded) {
}
} catch (error) {
console.error("加载二级项失败:", error);
showToast("加载二级项失败");
if (!isRequestFailureAlreadyHandled(error)) {
showToast("加载二级项失败");
}
}
}
......@@ -327,7 +367,12 @@ export function useInspectModules(route: RouteLocationNormalizedLoaded) {
await advanceToNextMainInspectionModule();
}
function onOpenModulePicker() {
async function onOpenModulePicker() {
try {
await refreshBigModulesFromRootNodes();
} catch (error) {
console.error("刷新检测模块失败:", error);
}
showModulePicker.value = true;
}
......
......@@ -141,7 +141,14 @@
class="module-picker-item"
:class="{ selected: bigModule.key === pendingModuleKey }"
@click="setPendingModuleKey(bigModule.key)">
<span class="picker-label">{{ bigModule.label }}</span>
<span class="picker-label-wrap">
<span class="picker-label">{{ bigModule.label }}</span>
<van-icon v-if="isBigModuleMarkCompleted(bigModule)"
class="picker-done-icon"
color="#27CD5A"
name="checked"
size="14" />
</span>
<van-icon v-if="bigModule.key === pendingModuleKey"
color="#477ffe"
name="success"
......@@ -179,7 +186,7 @@ import { useRoute } from "vue-router";
import customizeForm from "@/components/CustomizeForm/Index.vue";
import ScoreForm from "./components/ScoreForm.vue";
import { isSubTabMarkCompleted, SCORE_BIG_KEY, useInspectModules } from "./composables/useInspectModules";
import { isBigModuleMarkCompleted, isSubTabMarkCompleted, SCORE_BIG_KEY, useInspectModules } from "./composables/useInspectModules";
import { useInspectSubmit } from "./composables/useInspectSubmit";
const route = useRoute();
......@@ -546,5 +553,16 @@ onMounted(() => {
font-size: $font-size-base;
color: $color-text-primary;
}
.picker-label-wrap {
display: inline-flex;
gap: 4px;
align-items: center;
}
.picker-done-icon {
flex-shrink: 0;
line-height: 1;
}
}
</style>
......@@ -4,6 +4,7 @@ import { useRouter } from "vue-router";
import { login, sendSmsCode } from "@/api/modules/user.ts";
import { LOGIN_REDIRECT_KEY } from "@/config/constants";
import { useUserStore } from "@/stores/modules/user.ts";
import { isRequestFailureAlreadyHandled } from "@/utils/request";
import { notifyHostToken } from "@/utils/webviewBridge";
import { showFailToast, showSuccessToast } from "vant";
......@@ -60,7 +61,9 @@ export function useLogin() {
}, 1000);
} catch (error) {
console.error("sendSmsCode error", error);
showFailToast("验证码发送失败,请稍后重试");
if (!isRequestFailureAlreadyHandled(error)) {
showFailToast("验证码发送失败,请稍后重试");
}
} finally {
// sending 仅表示接口请求中;倒计时阶段由 countdown 控制禁用态
sending.value = false;
......@@ -102,7 +105,9 @@ export function useLogin() {
router.replace(redirect);
} catch (error) {
console.error("login error", error);
showFailToast("登录失败,请稍后重试");
if (!isRequestFailureAlreadyHandled(error)) {
showFailToast("登录失败,请稍后重试");
}
} finally {
loggingIn.value = false;
}
......
......@@ -218,7 +218,7 @@ onMounted(() => {
</div>
<div class="tl-content">
<div class="tl-label">
预约施工时间
检测更新时间
</div>
<div class="tl-value">
{{ fmtTime(detail?.updateTime) }}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!