Commit bc9adb68 by chenwq

Merge branch 'v1.0.0' of http://192.168.3.233:8090/app/sales-assist-mobile into v1.0.0

2 parents 89880107 9ff2af17
...@@ -20,7 +20,7 @@ export default { ...@@ -20,7 +20,7 @@ export default {
// updateResolutionConfig(); // updateResolutionConfig();
// 连接(自动登录) // 连接(自动登录)
// #ifdef APP // #ifdef APP
ws.connect(); // ws.connect();
// #endif // #endif
}, },
onShow () { onShow () {
......
/**
* 新系统认证 API
* 鉴权方式: Bearer Token
*/
import { request } from "@/api/modules/http/http.uts";
/**
* 用户登录
* POST /api/auth/login
* @param data { account: string, password: string }
* @returns { token, userId, username, realName, phone, roleName, stores }
*/
export function login(data: UTSJSONObject): Promise<any> {
return request("/auth/login", data);
}
/**
* 展业素材 API
* GET /api/contents
*/
import { request } from "@/api/modules/http/http.uts";
/**
* 获取已发布的展业素材列表
* @param params { storeId?: number, pageNum?: number, pageSize?: number }
*/
export function getContents(params: UTSJSONObject = {} as UTSJSONObject): Promise<any> {
return request("/contents", params, "GET");
}
/**
* 新系统环境配置(仅包含新系统所需)
* 0: ip 本地 1: dev 开发 2: test 测试 3: prod 生产 4: beta 预发布
*/
const TARGET_OPTIONS = ["ip", "dev", "test", "prod", "beta"];
const TARGET_INDEX = 1;
function pickEnv(map: UTSJSONObject): string {
const target = TARGET_OPTIONS[TARGET_INDEX] ?? "dev";
const val = map[target];
if (val != null) return `${val}`;
const fallback = map["dev"];
return fallback != null ? `${fallback}` : "";
}
/** 新系统后端服务地址 */
const baseUrlMap: UTSJSONObject = {
ip: "http://192.168.1.122:8292",
dev: "http://yjy.dev.glsx.com.cn/sa",
test: "http://yjy.test.glsx.com.cn/sa",
beta: "http://yjy.beta.glsx.com.cn/sa",
prod: "http://yjy.glsx.com.cn/sa",
pet: "http://yjy.test.glsx.com.cn/sa"
};
export const baseUrl: string = pickEnv(baseUrlMap);
/**
* 新系统 HTTP 请求客户端
* - Base: baseUrl(env.uts 按环境选取)
* - 公共路径前缀: /api
* - 鉴权: Bearer Token(自动从 storage.sessionId 注入)
* - 数据格式: JSON
* - 401 自动跳转登录页
*/
import { baseUrl } from "./env.uts";
import { storage } from "@/utils/storage.uts";
/** 401 时清理会话并跳转登录页 */
function redirectLogin(reject: (e: any) => void): void {
storage.set("sessionId", "", 0);
storage.set("userInfo", {} as UTSJSONObject, 0);
uni.hideLoading();
const pages = getCurrentPages();
if (pages.length > 0) {
const currentPage = pages[pages.length - 1];
if (currentPage.route != "pages/common/login/index") {
uni.reLaunch({ url: "/pages/common/login/index" });
}
}
reject("登录已过期,请重新登录");
}
/**
* 新系统统一请求函数
* @param path 接口路径,自动拼接 `${baseUrl}/api` + path,如 `/auth/login`
* @param data 请求体(POST)或查询参数(GET)
* @param method HTTP 方法,默认 POST
* @returns 响应 data 字段(code===0 时)
*/
export function request(
path: string,
data: UTSJSONObject = {} as UTSJSONObject,
method: "GET" | "POST" = "POST"
): Promise<any> {
console.log("🚀 ~ request ~ data:", data)
return new Promise((resolve, reject) => {
uni.getNetworkType({
success: (netRes) => {
if (netRes.networkType == "none") {
uni.hideLoading();
uni.showToast({ title: "网络异常", icon: "none" });
reject("网络异常");
return;
}
// Bearer Token 鉴权
const token = storage.get("sessionId");
const header: UTSJSONObject = { "Content-Type": "application/json" };
if (token != null && `${token}` !== "") {
header.Authorization = `Bearer ${token}`;
}
const fullUrl = `${baseUrl}/api${path}`;
console.log("🚀 ~ request ~ fullUrl:", fullUrl)
uni.request({
url: fullUrl,
data,
method,
header,
dataType: "json",
timeout: 30_000,
success: (response) => {
const statusCode = response.statusCode;
const resData = response.data;
// HTTP 层错误
if (resData == null || statusCode < 200 || statusCode >= 300) {
uni.hideLoading();
// 401 → 登录过期
if (statusCode == 401) {
redirectLogin(reject);
return;
}
const errMsg = resData == null
? "获取数据失败,请重试"
: `服务器错误(${statusCode})`;
console.log("🚀 ~ request ~ errMsg:", errMsg)
uni.showToast({ title: errMsg, icon: "none" });
reject(errMsg);
return;
}
// 业务层解析
const obj = resData as UTSJSONObject;
const code = obj["code"];
// 兼容数字 0 和字符串 "0"
if (code !== 0 && `${code}` !== "0") {
const msg = obj["message"] != null ? `${obj["message"]}` : "请求失败";
uni.showToast({ title: msg, icon: "none" });
reject(msg);
return;
}
// code === 0,返回 data 字段
const payload = obj["data"];
resolve(payload != null ? (payload as any) : ({} as UTSJSONObject));
},
fail: (error) => {
console.log("🚀 ~ request ~ error:", error)
uni.hideLoading();
const msg = error != null && error.errMsg != null
? `${error.errMsg}`
: "网络请求失败";
uni.showToast({ title: msg, icon: "none" });
reject(msg);
}
});
},
fail: () => {
reject("获取网络状态失败");
}
});
});
}
/**
* 接待记录 API
* GET /api/receptions
*/
import { request } from "@/api/modules/http/http.uts";
/**
* 获取接待列表
* @param params { storeId?: number, status?: number, pageNum?: number }
*/
export function getReceptions(params: UTSJSONObject = {} as UTSJSONObject): Promise<any> {
return request("/receptions", params, "GET");
}
...@@ -179,13 +179,11 @@ class Request { ...@@ -179,13 +179,11 @@ class Request {
const dataObj = resData as UTSJSONObject; const dataObj = resData as UTSJSONObject;
// 须先于 returnAll 分支:saveRecCustomer / confirm 等均 returnAll=true,否则 401 永远不会走 restore // 须先于 returnAll 分支:saveRecCustomer / confirm 等均 returnAll=true,否则 401 永远不会走 restore
const code = dataObj.code; const code = dataObj.code;
// ✅ 已迁移到新系统登录,旧接口 401 不再尝试 restore/redirect,仅静默失败
if (`${code}` == "401") { if (`${code}` == "401") {
const currentSessionId = storage.get("sessionId") as string | null; const errMsg = "旧接口认证失败(已迁移至新系统)";
if (currentSessionId != null && currentSessionId != "") { uni.hideLoading();
this.restoreShukeLogin(resolve, reject, urlPath, requestBody, method, returnAll, `${currentSessionId}`); reject(errMsg);
} else {
this.redirectShukeToLogin(reject);
}
return; return;
} }
if (returnAll) { if (returnAll) {
......
...@@ -36,10 +36,9 @@ ...@@ -36,10 +36,9 @@
<script setup lang="uts"> <script setup lang="uts">
import { type Ref, computed, onMounted, ref } from "vue"; import { type Ref, computed, onMounted, ref } from "vue";
import { getList } from "@/api/receiption.uts"; import { getReceptions } from "@/api/modules/receptions.uts";
import { useOrientation } from "@/services/adapter/hooks/index.uts"; import { useOrientation } from "@/services/adapter/hooks/index.uts";
import { getStr } from "@/pages/receptionCenter/types/reception-center-helpers.uts"; import { getStr } from "@/pages/receptionCenter/types/reception-center-helpers.uts";
import { formatReceptionDateTime, getReceptionResultBadgeBgClass } from "@/pages/receptionCenter/lists/reception-list-helpers.uts";
type ReceptionCardItem = { type ReceptionCardItem = {
customerName: string; customerName: string;
...@@ -67,16 +66,24 @@ const cardList = ref<ReceptionCardItem[]>([]); ...@@ -67,16 +66,24 @@ const cardList = ref<ReceptionCardItem[]>([]);
const loading = ref(true); const loading = ref(true);
function buildCardItem(row: UTSJSONObject): ReceptionCardItem { function buildCardItem(row: UTSJSONObject): ReceptionCardItem {
const result = getStr(row, 'result'); const status = row["status"];
const resultText = result != '' ? result : '进行中'; const statusName = getStr(row, 'statusName');
const carType = getStr(row, 'carType'); const resultText = statusName != '' ? statusName : '进行中';
const carTypeText = carType != '' ? carType : '未填写车型'; // 新接口:brand + carSeries 拼接
const brand = getStr(row, 'brand');
const series = getStr(row, 'carSeries');
let carTypeText = '';
if (brand != '') {
carTypeText = series != '' ? `${brand} ${series}` : brand;
} else {
carTypeText = '未填写车型';
}
return { return {
customerName: getStr(row, 'customerName'), customerName: getStr(row, 'customerName'),
resultText: resultText, resultText: resultText,
badgeBgClass: getReceptionResultBadgeBgClass(result), badgeBgClass: status == 1 ? 'rrl-badge--active' : 'rrl-badge--done',
carTypeText: carTypeText, carTypeText: carTypeText,
timeText: formatReceptionDateTime(row, 'start'), timeText: getStr(row, 'startTime'),
rawData: row rawData: row
} as ReceptionCardItem; } as ReceptionCardItem;
} }
...@@ -86,17 +93,29 @@ async function fetchRecentList(): Promise<void> { ...@@ -86,17 +93,29 @@ async function fetchRecentList(): Promise<void> {
try { try {
const params = { const params = {
pageNum: 1, pageNum: 1,
pageSize: props.limit, status: 1
orderFinishFlag: "1"
} as UTSJSONObject; } as UTSJSONObject;
const resp = await getList(params); const resp = await getReceptions(params);
const respObj = resp as UTSJSONObject; // 新接口 request() 已提取 data 层,返回直接是数组
const rows = (respObj.data as UTSJSONObject)?.rows as UTSJSONObject[] | null; let data: any[] = [];
const data = rows != null ? rows : ([] as UTSJSONObject[]); if (resp != null) {
if (Array.isArray(resp)) {
data = resp as any[];
} else {
// 兼容:如果返回的是对象,尝试取 list 字段
const obj = resp as UTSJSONObject;
const list = obj["list"];
if (list != null && Array.isArray(list)) {
data = list as any[];
}
}
}
const limit = props.limit;
const count = data.length < limit ? data.length : limit;
const items: ReceptionCardItem[] = []; const items: ReceptionCardItem[] = [];
let i = 0; let i = 0;
while (i < data.length) { while (i < count) {
items.push(buildCardItem(data[i])); items.push(buildCardItem(data[i] as UTSJSONObject));
i++; i++;
} }
cardList.value = items; cardList.value = items;
......
<template> <template>
<view class="content-left"> <view class="content-left">
<view class="module-box box-class"> <list-view class="module-box" :show-scrollbar="false">
<!-- ✅ 性能优化:骨架屏 + 异步加载 --> <!-- ✅ 性能优化:骨架屏 + 异步加载 -->
<ProductIntroSkeleton v-if="!logic.loadComplete.value" /> <list-item v-if="!logic.loadComplete.value">
<view v-else class="content-box"> <ProductIntroSkeleton />
<ProductIntroSwiper </list-item>
:load-complete="logic.loadComplete.value" <list-item v-else>
:swiper-list="boutiqueIntroSwiperList" <ProductIntroGrid
:modules="introModulesForHomeFrame" :modules="introModulesForHomeFrame"
:eyebrow="boutiqueIntroEyebrowText" eyebrow="展业素材"
empty-title="暂无数据" empty-title="暂无数据"
:empty-text="boutiqueIntroEmptyText" :empty-text="boutiqueIntroEmptyText"
:show-switch-product="true" @item-tap="onIntroSlideTap" />
@slide-tap="onIntroSlideTap" </list-item>
@switch-product="onIntroSwitchProduct" /> </list-view>
</view>
</view>
<view class="recent-list-wrapper"> <view class="recent-list-wrapper">
<RecentReceptionList /> <RecentReceptionList />
</view> </view>
<CenterPopup :list="padBusinessTypePopupItems"
title="请选择接待类型"
:visible="showPadBusinessTypePopup"
:selected-type-code="boutiquePadSelectedTypeCode"
@choose="onChoosePadBusinessType"
@update:visible="onPadBusinessTypePopupVisible" />
<PackageDetailPopup ref="packageRef" @close="closePackageDetail"> <PackageDetailPopup ref="packageRef" @close="closePackageDetail">
<view class="package-detail-box"> <view class="package-detail-box">
<view class="package-box"> <view class="package-box">
...@@ -55,14 +46,11 @@ ...@@ -55,14 +46,11 @@
import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts"; import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
import { useBoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts"; import { useBoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
import { ComponentPublicInstance, computed, nextTick, onMounted, onShow, ref } from "vue"; import { ComponentPublicInstance, computed, onMounted, onShow, ref } from "vue";
import CenterPopup from "@/components/CenterPopup.uvue";
import PackageDetailPopup from "@/pages/boutique/components/PackageDetailPopup.uvue"; import PackageDetailPopup from "@/pages/boutique/components/PackageDetailPopup.uvue";
import ProductIntroSwiper from "@/components/ProductIntroSwiper.uvue"; import ProductIntroGrid from "@/components/ProductIntroGrid.uvue";
import ProductIntroSkeleton from "@/components/Skeleton/ProductIntroSkeleton.uvue"; import ProductIntroSkeleton from "@/components/Skeleton/ProductIntroSkeleton.uvue";
// ✅ 从 uview-unix 模块导入 UnSwiperItem 类型
import type { UnSwiperItem } from "@/uni_modules/uview-unix";
import RecentReceptionList from "@/components/RecentReceptionList.uvue"; import RecentReceptionList from "@/components/RecentReceptionList.uvue";
...@@ -103,54 +91,12 @@ const introModulesForHomeFrame = computed((): any[] => { ...@@ -103,54 +91,12 @@ const introModulesForHomeFrame = computed((): any[] => {
return logic.introCarouselItems.value; return logic.introCarouselItems.value;
}); });
function bannerUrlForItem(item: any): string {
const u = logic.getPkg(item, "bannerImg") as string;
if (u != null && u !== "") {
return u;
}
const m = logic.getPkg(item, "materialUrl") as string;
return m != null && m !== "" ? m : "";
}
const boutiqueIntroSwiperList = computed((): UnSwiperItem[] => {
const list = logic.introCarouselItems.value;
const out: UnSwiperItem[] = [];
for (let i = 0; i < list.length; i++) {
const url = bannerUrlForItem(list[i]);
// ✅ 使用 uview-unix 导出的 UnSwiperItem 类型
out.push({
url: url
} as UnSwiperItem);
}
return out;
});
const boutiqueIntroEmptyText = computed((): string => { const boutiqueIntroEmptyText = computed((): string => {
const t = logic.swiperNoDataObject["text"]; const t = logic.swiperNoDataObject["text"];
return t != null ? `${t}` : "暂无数据"; return t != null ? `${t}` : "暂无数据";
}); });
/** 产品介绍区 eyebrow:当前 Pad 业务类型名(切换后随 logic 更新) */
const boutiqueIntroEyebrowText = computed((): string => {
const n = logic.padSelectedTypeName.value;
if (n != null && n !== "") {
return n;
}
return "产品介绍";
});
const boutiquePadSelectedTypeCode = computed((): string => {
return logic.padSelectedTypeCode.value;
});
const padBusinessTypePopupItems = computed((): any[] => {
const list = logic.businessTypePopupList.value;
return list != null ? list : ([] as any[]);
});
const packageRef = ref(null); const packageRef = ref(null);
/** 切换产品:受控弹层(与 CenterPopup `visible` + `update:visible` 用法一致) */
const showPadBusinessTypePopup = ref<boolean>(false);
function callExposedMethod(comp: any, methodName: string): void { function callExposedMethod(comp: any, methodName: string): void {
if (comp == null) return; if (comp == null) return;
...@@ -170,24 +116,6 @@ function onIntroSlideTap(index: number): void { ...@@ -170,24 +116,6 @@ function onIntroSlideTap(index: number): void {
toDetail(index); toDetail(index);
} }
async function onIntroSwitchProduct(): Promise<void> {
const ok = await logic.preparePadBusinessTypePicker();
if (!ok) {
uni.showToast({ title: "暂无可选类型", icon: "none" });
return;
}
await nextTick();
showPadBusinessTypePopup.value = true;
}
function onPadBusinessTypePopupVisible(value: boolean): void {
showPadBusinessTypePopup.value = value;
}
async function onChoosePadBusinessType(index: number): Promise<void> {
await logic.applyPadBusinessTypeAtIndex(index);
}
function closePackageDetail(): void { function closePackageDetail(): void {
logic.chooseItem.value = {}; logic.chooseItem.value = {};
} }
...@@ -205,11 +133,16 @@ function closePackageDetail(): void { ...@@ -205,11 +133,16 @@ function closePackageDetail(): void {
.module-box { .module-box {
flex-shrink: 0; flex-shrink: 0;
height: var(--module-box-height, 420px); height: var(--module-box-height, 360px);
width: 100%;
}
.module-box .content-box {
width: 100%;
} }
.recent-list-wrapper { .recent-list-wrapper {
flex: 1; flex-shrink: 0;
min-height: 0; min-height: 0;
overflow: hidden; overflow: hidden;
margin-top: var(--l-spacing-sm, 8px); margin-top: var(--l-spacing-sm, 8px);
......
...@@ -102,9 +102,8 @@ ...@@ -102,9 +102,8 @@
<script setup lang="uts"> <script setup lang="uts">
import { onUnmounted, ref } from "vue"; import { onUnmounted, ref } from "vue";
import { apiShukeLoginInit, apiShukeStoreList } from "@/api/user-api.uts"; import { login as loginApi } from "@/api/modules/auth.uts";
import { switchTabSelectStoreWithStoresPayload } from "@/utils/shukeSelectStoreNav.uts"; import { switchTabSelectStoreWithStoresPayload } from "@/utils/shukeSelectStoreNav.uts";
import { encryptLoginPassword } from "@/utils/crypto.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import pageVars from './styles/index.vars' import pageVars from './styles/index.vars'
import { toStr, toObj, isEmptyStr, isNotEmptyStr, type AnyArrOrNull, type AnyOrNull, type ObjOrNull } from "@/utils/common.uts"; import { toStr, toObj, isEmptyStr, isNotEmptyStr, type AnyArrOrNull, type AnyOrNull, type ObjOrNull } from "@/utils/common.uts";
...@@ -115,8 +114,8 @@ type UniApiFail = { ...@@ -115,8 +114,8 @@ type UniApiFail = {
errMsg: string; errMsg: string;
}; };
const username = ref<string>("陈玲"); const username = ref<string>("admin");
const password = ref<string>("550747"); const password = ref<string>("admin123");
const showPassword = ref<boolean>(false); const showPassword = ref<boolean>(false);
const noSignIn = ref<boolean>(true); const noSignIn = ref<boolean>(true);
const readingStatus = ref<boolean>(true); const readingStatus = ref<boolean>(true);
...@@ -229,7 +228,6 @@ const openUserAgreement = (): void => { ...@@ -229,7 +228,6 @@ const openUserAgreement = (): void => {
const doLogin = async (): Promise<void> => { const doLogin = async (): Promise<void> => {
const u = username.value.trim(); const u = username.value.trim();
const p = password.value.trim(); const p = password.value.trim();
const remember = noSignIn.value;
const agreed = readingStatus.value; const agreed = readingStatus.value;
try { try {
if (u === "") { if (u === "") {
...@@ -245,89 +243,96 @@ const doLogin = async (): Promise<void> => { ...@@ -245,89 +243,96 @@ const doLogin = async (): Promise<void> => {
throw new Error("请您阅读并同意《隐私协议》"); throw new Error("请您阅读并同意《隐私协议》");
} }
const enc = encryptLoginPassword(p);
if (enc == null || enc === "") {
throw new Error("密码加密失败,请重试");
}
// uni.showLoading({
// title: "加载中",
// mask: true
// });
isLogging.value = true; isLogging.value = true;
const loginInRes = await apiShukeLoginInit(toObj({ // ✅ 新系统登录:POST /api/auth/login
username: u, const loginData = await loginApi({
password: enc account: u,
})); password: p
} as UTSJSONObject);
if (loginInRes == null) { if (loginData == null) {
throw new Error("登录失败"); throw new Error("登录失败");
} }
const codeRaw = loginInRes["code"] as number | StrOrNull; const data = toObj(loginData);
const msgAny = loginInRes["msg"] != null ? loginInRes["msg"] : loginInRes["message"]; const token = toStr(data["token"]);
const msgStr = msgAny != null ? `${msgAny}` : ""; if (isEmptyStr(token)) {
throw new Error("登录失败:未获取到 token");
if (codeRaw != null && `${codeRaw}` === "500") {
throw new Error(msgStr !== "" ? msgStr : "登录失败");
} }
const data = toObj(loginInRes["data"]); // ✅ 存储 sessionId(JWT token)
if (data == null) { storage.set("sessionId", token, 0);
throw new Error(msgStr !== "" ? msgStr : "登录失败");
// ✅ 从 data.user 提取用户信息(实际响应结构)
const userObj = toObj(data["user"]);
const userId = userObj["id"];
const usernameVal = toStr(userObj["username"]);
const displayName = toStr(userObj["displayName"]);
const phone = toStr(userObj["phone"]);
const accountNo = toStr(userObj["accountNo"]);
const staffId = toStr(userObj["staffId"]);
const tenantId = userObj["tenantId"];
const currentStoreId = toStr(userObj["currentStoreId"]);
const userInfo = {
userId: userId,
id: userId,
username: usernameVal,
accountNo: accountNo,
displayName: displayName,
phone: phone,
staffId: staffId,
tenantId: tenantId,
currentStoreId: currentStoreId,
shopMerchantId: userId != null ? `${userId}` : "",
shopMerchantName: displayName
} as UTSJSONObject;
storage.set("userInfo", userInfo, 0);
// ✅ 解析门店列表(兼容 Array 与 JSON 字符串两种形态)
let stores: any[] | null = null;
const storesRaw = data["stores"];
if (storesRaw != null) {
if (Array.isArray(storesRaw)) {
stores = storesRaw as any[];
} else if (typeof storesRaw === "string") {
try {
const parsed = JSON.parse(storesRaw as string);
if (Array.isArray(parsed)) {
stores = parsed as any[];
} }
} catch (_e) {}
const accessToken = toStr(data["access_token"]);
const spInfo = toObj(data["spInfo"]);
const spCode = spInfo != null ? (toStr(spInfo["spCode"])) : null;
if (isNotEmptyStr(accessToken)) {
// ✅ 性能优化:异步存储,避免阻塞主线程
storage.set("sessionId", accessToken, 0);
} }
const storeListRes = await apiShukeStoreList({
spCode: spCode != null ? spCode : ""
} as UTSJSONObject);
if (storeListRes == null) {
throw new Error("获取门店列表失败");
} }
const storeCodeRaw = storeListRes["code"] as number | StrOrNull;
if (storeCodeRaw != null && `${storeCodeRaw}` === "500") {
const sm = storeListRes["msg"] != null ? `${storeListRes["msg"]}` : "获取门店列表失败";
throw new Error(sm);
}
const storeData = toObj(storeListRes["data"]);
const stores = storeData != null ? (storeData["stores"] as AnyArrOrNull) : null;
if (stores == null || stores.length == 0) { if (stores == null || stores.length == 0) {
throw new Error("暂无门店信息,请联系管理员"); throw new Error("暂无门店信息,请联系管理员");
} }
const spCodeStr = spCode != null ? spCode : ""; // ✅ 存储门店列表(最多 20 个) TODO 后续正式环境要去掉这个截断
const loginPayload = { const storesToUse = stores.slice(0, 20);
username: u, storage.set("pendingShukeStores", storesToUse, 0);
password: enc,
spCode: spCodeStr, if (storesToUse.length == 1) {
noSignIn: remember // 单门店:直接保存门店信息并进入首页
} as UTSJSONObject; const store = storesToUse[0] as UTSJSONObject;
const storeId = toStr(store["storeId"]);
// ✅ 性能优化:异步批量存储,避免阻塞主线程 const storeName = toStr(store["storeName"]);
storage.setAsync("loginForm", loginPayload, 0); const storeCode = toStr(store["storeCode"]);
storage.setAsync("shukeLastConfirmForm", loginPayload, 0); storage.set("storeInfo", {
storage.setAsync("shukeSpCode", spCodeStr, 0); storeId: storeId,
storage.setAsync("pendingShukeStores", stores, 0); storeName: storeName,
storeCode: storeCode
// ✅ 性能优化:立即跳转,不使用 setTimeout } as UTSJSONObject, 0);
switchTabSelectStoreWithStoresPayload(stores); uni.switchTab({ url: "/pages/index/index" });
} else {
// 多门店:跳转选店页
switchTabSelectStoreWithStoresPayload(storesToUse);
}
} catch (error) { } catch (error) {
const msg = error != null ? `${error}` : "操作失败"; const msg = error != null ? `${error}` : "操作失败";
showError(msg); showError(msg);
// uni.hideLoading();
// isLogging.value = false;
} }
}; };
......
...@@ -71,10 +71,9 @@ ...@@ -71,10 +71,9 @@
<script setup lang="uts"> <script setup lang="uts">
import { ref, computed } from "vue"; import { ref, computed } from "vue";
import { apiShukeConfirmStore, apiShukeSaveLogin } from "@/api/user-api.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import { hideNativeTabBar } from "@/utils/tabBarShell.uts"; import { hideNativeTabBar } from "@/utils/tabBarShell.uts";
import { EMPTY_OBJECT, toStr, toObj, isEmptyStr, isNotEmptyStr, toBool, type AnyOrNull, type ObjOrNull, type StrOrNull, type AnyArrOrNull } from "@/utils/common.uts"; import { toStr, toObj, isEmptyStr, isNotEmptyStr, type AnyOrNull, type ObjOrNull, type StrOrNull, type AnyArrOrNull } from "@/utils/common.uts";
import pageVars from "@/pages/common/login/styles/index.vars"; import pageVars from "@/pages/common/login/styles/index.vars";
import SkeletonCard from "./SkeletonCard.uvue"; import SkeletonCard from "./SkeletonCard.uvue";
import { useColumnLayout } from "@/services/adapter/hooks"; import { useColumnLayout } from "@/services/adapter/hooks";
...@@ -91,6 +90,7 @@ const errorVisible = ref<boolean>(false); ...@@ -91,6 +90,7 @@ const errorVisible = ref<boolean>(false);
const errorMessage = ref<string>(""); const errorMessage = ref<string>("");
const pressedIndex = ref<number>(-1); const pressedIndex = ref<number>(-1);
const isLoading = ref<boolean>(true); // 添加加载状态 const isLoading = ref<boolean>(true); // 添加加载状态
const selectedStore = ref<any | null>(null);
/** ✅ 性能优化:使用动态列数 Hook(禁用自动更新,避免横竖屏 ANR) */ /** ✅ 性能优化:使用动态列数 Hook(禁用自动更新,避免横竖屏 ANR) */
const { columnCount, cssVars: columnCssVars } = useColumnLayout(false); const { columnCount, cssVars: columnCssVars } = useColumnLayout(false);
...@@ -183,40 +183,43 @@ const showError = (msg: string): void => { ...@@ -183,40 +183,43 @@ const showError = (msg: string): void => {
errorVisible.value = true; errorVisible.value = true;
}; };
/** 与 `loginForm` 同结构;选店成功后 `loginForm` 会删,切换门店仍要靠 confirm 接口,故保留一份(退出/切换账号时清) */ /** ✅ 新系统:登录已返回 token,选店只需保存门店信息并跳转 */
const SHUKE_LAST_CONFIRM_FORM_KEY = "shukeLastConfirmForm"; function completeStoreSelection(): void {
const store = selectedStore.value;
function hasValidLoginCredentials(form: UTSJSONObject): boolean { if (store == null) return;
const u = toStr(form["username"]); const storeObj = toObj(store);
const p = toStr(form["password"]); const storeId = toStr(storeObj["storeId"]);
const sp = toStr(form["spCode"]); const storeName = toStr(storeObj["storeName"]);
return isNotEmptyStr(u) && isNotEmptyStr(p) && isNotEmptyStr(sp); const storeCode = toStr(storeObj["storeCode"]);
}
// 保存门店信息(storeId 为主标识)
/** ✅ 性能优化:缓存 loginForm,避免重复读取 Storage */ storage.set("storeInfo", {
let cachedLoginForm: ObjOrNull = null; storeId: storeId,
let cachedLoginFormTime: number = 0; storeName: storeName,
const LOGIN_FORM_CACHE_TTL = 5000; // 5秒缓存 storeCode: storeCode
} as UTSJSONObject, 0);
function readLoginFormForSelectStore(): UTSJSONObject {
const now = Date.now(); // 补全 userInfo 的商户字段
// 如果缓存有效,直接返回 const profile = storage.parse("userInfo");
const cached = cachedLoginForm; let merchantId = toStr(profile["shopMerchantId"]);
if (cached != null && (now - cachedLoginFormTime) < LOGIN_FORM_CACHE_TTL) { if (merchantId === "") {
return cached; merchantId = toStr(storeObj["merchantId"]);
} }
if (merchantId === "" && storeCode !== "") {
const primary = storage.parse("loginForm"); merchantId = storeCode;
if (hasValidLoginCredentials(primary)) { }
cachedLoginForm = primary; profile["shopMerchantId"] = merchantId;
cachedLoginFormTime = now; if (toStr(profile["shopMerchantName"]) === "") {
return primary; profile["shopMerchantName"] = storeName !== "" ? storeName : "门店";
} }
storage.set("userInfo", profile, 0);
// 清理临时数据
storage.remove("loginForm");
storage.remove("pendingShukeStores");
const fallback = storage.parse(SHUKE_LAST_CONFIRM_FORM_KEY); // 跳转首页
cachedLoginForm = fallback; uni.switchTab({ url: "/pages/index/index" });
cachedLoginFormTime = now;
return fallback;
} }
/** ✅ 性能优化:同步处理门店数据(用于小数据量) */ /** ✅ 性能优化:同步处理门店数据(用于小数据量) */
...@@ -344,171 +347,6 @@ function readStoreListFromStorage(key: string): any[] { ...@@ -344,171 +347,6 @@ function readStoreListFromStorage(key: string): any[] {
return []; return [];
} }
/** ✅ 性能优化:提取商户 ID(支持多字段回退) */
function extractMerchantId(obj: ObjOrNull, fallback: string = ""): string {
if (obj == null) return fallback;
const fields = ["shopMerchantId", "merchantId"];
for (let i = 0; i < fields.length; i++) {
const val = obj[fields[i]] as string | number | null;
if (val != null) {
const str = `${val}`;
if (str !== "") return str;
}
}
return fallback;
}
/** ✅ 性能优化:提取商户名称(支持多字段回退) */
function extractMerchantName(obj: ObjOrNull, fallback: string = ""): string {
if (obj == null) return fallback;
const fields = ["shopMerchantName", "merchantName"];
for (let i = 0; i < fields.length; i++) {
const val = toStr(obj[fields[i]]);
if (isNotEmptyStr(val)) return val;
}
return fallback;
}
/** ✅ 性能优化:补全商户信息(避免重复逻辑) */
function enrichProfile(profile: UTSJSONObject, userObj: ObjOrNull, storeObj: ObjOrNull, storeCode: string, storeName: string): void {
// 补全 shopMerchantId
let merchantId = extractMerchantId(profile);
if (merchantId === "") {
merchantId = userObj != null ? extractMerchantId(userObj) : "";
}
if (merchantId === "") {
merchantId = storeObj != null ? extractMerchantId(storeObj) : "";
}
if (merchantId === "" && storeCode !== "") {
merchantId = storeCode;
}
profile["shopMerchantId"] = merchantId;
// 补全 shopMerchantName
let merchantName = extractMerchantName(profile);
if (merchantName === "") {
merchantName = userObj != null ? extractMerchantName(userObj) : "";
}
if (merchantName === "") {
merchantName = storeName !== "" ? storeName : "门店";
}
profile["shopMerchantName"] = merchantName;
}
/** 与 simgle_app `confirmLoginStore` 一致:请求体必须含 loginForm 内 username、password(加密)、spCode */
const confirmOne = async (store: AnyOrNull): Promise<void> => {
const loginFormRaw = readLoginFormForSelectStore();
if (hasValidLoginCredentials(loginFormRaw) != true) {
showError("登录信息已失效,请重新登录");
return;
}
const username = toStr(loginFormRaw["username"]);
const password = toStr(loginFormRaw["password"]);
const spCode = toStr(loginFormRaw["spCode"]);
const noSignIn = toBool(loginFormRaw["noSignIn"]);
const storeCode = getStoreCode(store);
if (isEmptyStr(username) || isEmptyStr(password) || isEmptyStr(spCode) || storeCode === "") {
showError("参数异常");
return;
}
// ✅ 性能优化:立即显示 loading,不使用 setTimeout
uni.showLoading({ title: "加载中", mask: true });
try {
const res = await apiShukeConfirmStore({
username,
password,
spCode,
storeCode
} as UTSJSONObject);
const resCode = toStr(res["code"]);
if (`${resCode}` === "500") {
let msg = toStr(res["msg"]);
if (isEmptyStr(msg)) {
msg = toStr(res["message"]);
}
if (isEmptyStr(msg)) {
msg = "确认门店失败";
}
showError(msg);
return;
}
const data = toObj(res["data"]);
if (data == null) {
showError("确认门店失败");
return;
}
let token = toStr(data["token"]);
if (isEmptyStr(token)) {
token = toStr(data["sessionId"]);
}
if (isEmptyStr(token)) {
token = toStr(data["access_token"]);
}
if (isEmptyStr(token)) {
showError("登录失败:未获取到 token");
return;
}
// ✅ 性能优化:异步存储,避免阻塞
asyncStorageSet("sessionId", token);
const loginUser = toObj(data["loginUser"]);
const userObj = toObj(data["user"]);
if (loginUser == null && userObj == null) {
showError("确认门店失败:未返回用户信息");
return;
}
const profile = loginUser != null ? loginUser : userObj;
const storeObj = toObj(store);
const storeName = getStoreName(store);
// ✅ 性能优化:使用统一函数补全商户信息
enrichProfile(profile, userObj, storeObj, storeCode, storeName);
// ✅ 性能优化:关键数据异步存储,避免阻塞(移除重复的 sessionId)
asyncStorageSet("userInfo", profile);
asyncStorageSet(
"storeInfo",
toObj({
storeCode,
storeName
})
);
if (noSignIn == true) {
asyncStorageSet("noSignInUuid", username);
// ✅ 性能优化:不等待 saveLogin 完成,直接继续
apiShukeSaveLogin(EMPTY_OBJECT).catch((e) => {
console.log("saveLoginInfo", e);
});
}
if (isNotEmptyStr(spCode)) {
asyncStorageSet("shukeSpCode", spCode);
}
/** 供再次进入选店页调 confirm(与 simgle 侧栏「切换」一致:不依赖未持久化的 loginForm) */
asyncStorageSet(
SHUKE_LAST_CONFIRM_FORM_KEY,
toObj({
username,
password,
spCode,
noSignIn: noSignIn == true
})
);
// ✅ 性能优化:异步删除,避免阻塞主线程
storage.removeAsync("loginForm");
storage.removeAsync("pendingShukeStores");
// ✅ 性能优化:先隐藏 loading,再跳转
uni.hideLoading();
// ✅ 立即跳转,不使用 setTimeout
uni.switchTab({ url: "/pages/index/index" });
} catch (e) {
showError(`${e}`);
} finally {
uni.hideLoading();
}
};
const onSelect = (item: AnyOrNull): void => { const onSelect = (item: AnyOrNull): void => {
if (item == null) { if (item == null) {
showError("门店数据异常"); showError("门店数据异常");
...@@ -520,9 +358,10 @@ const onSelect = (item: AnyOrNull): void => { ...@@ -520,9 +358,10 @@ const onSelect = (item: AnyOrNull): void => {
return; return;
} }
selectedStoreCode.value = code; selectedStoreCode.value = code;
selectedStore.value = item;
// confirmOne 内部会立即显示 loading // ✅ 新系统:登录已返回 token,直接保存门店信息并跳转
confirmOne(item); completeStoreSelection();
}; };
function parseStoresFromOptions(options: ObjOrNull): AnyArrOrNull { function parseStoresFromOptions(options: ObjOrNull): AnyArrOrNull {
...@@ -578,15 +417,11 @@ async function loadStoresData(options: ObjOrNull): Promise<void> { ...@@ -578,15 +417,11 @@ async function loadStoresData(options: ObjOrNull): Promise<void> {
} }
/** 与 simgle_app 一致:多店进页不拦;仅「单店自动 confirm」必须有凭据 */ /** 与 simgle_app 一致:多店进页不拦;仅「单店自动 confirm」必须有凭据 */
if (stores.value.length == 1) { if (stores.value.length == 1) {
const cred = readLoginFormForSelectStore();
if (hasValidLoginCredentials(cred) != true) {
showError("缺少登录凭据,请重新登录后再选店");
return;
}
const only = stores.value[0]; const only = stores.value[0];
selectedStoreCode.value = getStoreCodeField(only); selectedStoreCode.value = getStoreCodeField(only);
// ✅ 立即执行 confirm selectedStore.value = only;
confirmOne(only); // ✅ 单门店自动选择
completeStoreSelection();
return; return;
} }
} }
......
...@@ -25,14 +25,14 @@ import BoutiqueHomePanel from "@/pages/boutique/components/BoutiqueHomePanel.uvu ...@@ -25,14 +25,14 @@ import BoutiqueHomePanel from "@/pages/boutique/components/BoutiqueHomePanel.uvu
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow: hidden; overflow: hidden;
padding: var(--content-tabbar-gap, 12px); // padding: var(--content-tabbar-gap, 12px);
} }
.right-content-box { .right-content-box {
flex: 1; flex: 1;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
margin-top: var(--l-spacing-md); // margin-top: var(--l-spacing-md);
overflow: hidden; overflow: hidden;
} }
</style> </style>
...@@ -39,7 +39,7 @@ export default { ...@@ -39,7 +39,7 @@ export default {
portrait: { portrait: {
// 竖屏布局 - 产品介绍占 60% // 竖屏布局 - 产品介绍占 60%
// 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) - TabBar(60px) ≈ 屏幕高度 - 152px // 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) - TabBar(60px) ≈ 屏幕高度 - 152px
'--module-box-height': '420px', '--module-box-height': '350px',
'--swiper-height': 'calc(var(--module-box-height) - 40px)', // 轮播图高度 = module-box - 头部(40px) '--swiper-height': 'calc(var(--module-box-height) - 40px)', // 轮播图高度 = module-box - 头部(40px)
// Entrance 图标尺寸(竖屏) // Entrance 图标尺寸(竖屏)
'--entrance-icon-size': '52px', '--entrance-icon-size': '52px',
...@@ -52,7 +52,7 @@ export default { ...@@ -52,7 +52,7 @@ export default {
landscape: { landscape: {
// 横屏布局 - 产品介绍占 65% // 横屏布局 - 产品介绍占 65%
// 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) ≈ 屏幕高度 - 92px (TabBar在左侧,不影响高度) // 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) ≈ 屏幕高度 - 92px (TabBar在左侧,不影响高度)
'--module-box-height': '440px', '--module-box-height': '400px',
'--swiper-height': 'calc(var(--module-box-height) - 40px)', // 轮播图高度 = module-box - 头部(40px) '--swiper-height': 'calc(var(--module-box-height) - 40px)', // 轮播图高度 = module-box - 头部(40px)
// Entrance 图标尺寸(横屏) // Entrance 图标尺寸(横屏)
'--entrance-icon-size': '56px', '--entrance-icon-size': '56px',
...@@ -69,7 +69,7 @@ export default { ...@@ -69,7 +69,7 @@ export default {
// 大屏平板横屏 (1174x768) - 产品介绍占 65% // 大屏平板横屏 (1174x768) - 产品介绍占 65%
// 可用高度 = 768 - 44(状态栏) - 54(标题) ≈ 670px // 可用高度 = 768 - 44(状态栏) - 54(标题) ≈ 670px
'landscape-1174x768': { 'landscape-1174x768': {
'--module-box-height': '360px', '--module-box-height': '420px',
'--swiper-height': 'calc(var(--module-box-height) - 40px)', // 320px '--swiper-height': 'calc(var(--module-box-height) - 40px)', // 320px
'--common-title-height': '54px', '--common-title-height': '54px',
'--entrance-icon-size': '64px', '--entrance-icon-size': '64px',
...@@ -117,7 +117,7 @@ export default { ...@@ -117,7 +117,7 @@ export default {
// 大屏平板竖屏 (768x1174) - 产品介绍占 65% // 大屏平板竖屏 (768x1174) - 产品介绍占 65%
// 可用高度 = 1174 - 44(状态栏) - 54(标题) - 70(TabBar) ≈ 1006px // 可用高度 = 1174 - 44(状态栏) - 54(标题) - 70(TabBar) ≈ 1006px
'portrait-768x1174': { 'portrait-768x1174': {
'--module-box-height': '550px', '--module-box-height': '450px',
'--swiper-height': 'calc(var(--module-box-height) - 40px)', // 510px '--swiper-height': 'calc(var(--module-box-height) - 40px)', // 510px
'--common-title-height': '54px', '--common-title-height': '54px',
'--entrance-icon-size': '64px', '--entrance-icon-size': '64px',
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
width: 100%; width: 100%;
flex: 1; /* ✅ 通过 flex 自动填充父容器剩余空间 */ flex: 1; /* ✅ 通过 flex 自动填充父容器剩余空间 */
background-color: var(--person-bg-page, #f8fafc); background-color: var(--person-bg-page, #f8fafc);
padding: var(--person-page-padding, 0px); /* ✅ 通过 CSS 变量控制 */ // padding: var(--person-page-padding, 0px); /* ✅ 通过 CSS 变量控制 */
box-sizing: border-box; box-sizing: border-box;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!