feat(registration): 优化经销商注册流程并增加地址定位功能

- 修改导航栏标题从“邀请注册”为“注册成为会员”
- 修复重复提交问题并移除不必要的submitting状态
- 增加昵称和头像的必填验证提示
- 添加用户角色缺失时的默认角色写入机制
- 集成地图选点功能,支持经纬度获取和地址解析
- 实现微信地址导入功能,自动填充基本信息
- 增加定位权限检查和错误处理机制
- 添加.gitignore规则忽略备份文件夹src__bak
- 移除已废弃的银行卡和客户管理页面代码
- 优化表单验证规则和错误提示信息
- 实现经销商注册成功后自动跳转到“我的”页面
- 添加用户信息缓存刷新机制确保角色信息同步
```
This commit is contained in:
2026-03-01 12:35:41 +08:00
parent 945351be91
commit eee4644d06
296 changed files with 28845 additions and 6664 deletions

View File

@@ -1,6 +1,6 @@
import {useEffect, useState, useRef} from "react";
import {useRouter} from '@tarojs/taro'
import {Button, Loading, CellGroup, Input, TextArea, Form} from '@nutui/nutui-react-taro'
import {Button, Loading, CellGroup, Cell, Input, TextArea, Form} from '@nutui/nutui-react-taro'
import {Scan, ArrowRight} from '@nutui/icons-react-taro'
import Taro from '@tarojs/taro'
import {View} from '@tarojs/components'
@@ -9,6 +9,34 @@ import {ShopUserAddress} from "@/api/shop/shopUserAddress/model";
import {getShopUserAddress, listShopUserAddress, updateShopUserAddress, addShopUserAddress} from "@/api/shop/shopUserAddress";
import RegionData from '@/api/json/regions-data.json';
import FixedButton from "@/components/FixedButton";
import { parseLngLatFromText } from "@/utils/geofence";
type SelectedLocation = { lng: string; lat: string; name?: string; address?: string }
const isLocationDenied = (e: any) => {
const msg = String(e?.errMsg || e?.message || e || '')
return (
msg.includes('auth deny') ||
msg.includes('authorize') ||
msg.includes('permission') ||
msg.includes('denied') ||
msg.includes('scope.userLocation')
)
}
const isUserCancel = (e: any) => {
const msg = String(e?.errMsg || e?.message || e || '')
return msg.includes('cancel')
}
const hasValidLngLat = (addr?: Partial<ShopUserAddress> | null) => {
if (!addr) return false
const p = parseLngLatFromText(`${(addr as any)?.lng ?? ''},${(addr as any)?.lat ?? ''}`)
if (!p) return false
// Treat "0,0" as missing in this app (typically used as placeholder by backends).
if (p.lng === 0 && p.lat === 0) return false
return true
}
const AddUserAddress = () => {
const {params} = useRouter();
@@ -18,16 +46,72 @@ const AddUserAddress = () => {
const [visible, setVisible] = useState(false)
const [FormData, setFormData] = useState<ShopUserAddress>({})
const [inputText, setInputText] = useState<string>('')
const [selectedLocation, setSelectedLocation] = useState<SelectedLocation | null>(null)
const formRef = useRef<any>(null)
const wxDraftRef = useRef<Partial<ShopUserAddress> | null>(null)
const wxDraftPatchedRef = useRef(false)
// 判断是编辑还是新增模式
const isEditMode = !!params.id
const addressId = params.id ? Number(params.id) : undefined
const fromWx = params.fromWx === '1' || params.fromWx === 'true'
const skipDefaultCheck =
fromWx || params.skipDefaultCheck === '1' || params.skipDefaultCheck === 'true'
const reload = async () => {
// 整理地区数据
setRegionData()
// 新增模式:若存在“默认地址”但缺少经纬度,则强制引导到编辑页完善定位
// 目的:确保业务依赖默认地址坐标(选店/配送范围)时不会因为缺失坐标而失败
if (!isEditMode && !skipDefaultCheck) {
try {
const defaultList = await listShopUserAddress({ isDefault: true })
const defaultAddr = defaultList?.[0]
if (defaultAddr && !hasValidLngLat(defaultAddr)) {
await Taro.showModal({
title: '需要完善定位',
content: '默认收货地址缺少定位信息,请先进入编辑页面选择定位并保存后再继续。',
confirmText: '去完善',
showCancel: false
})
if (defaultAddr.id) {
Taro.navigateTo({ url: `/user/address/add?id=${defaultAddr.id}` })
} else {
Taro.navigateTo({ url: '/user/address/index' })
}
return
}
} catch (_e) {
// ignore: 新增页不阻塞渲染
}
}
// 微信地址导入:先用微信返回的字段预填表单,让用户手动选择定位后再保存
if (!isEditMode && fromWx && !wxDraftPatchedRef.current) {
try {
const draft = Taro.getStorageSync('WxAddressDraft')
if (draft) {
wxDraftPatchedRef.current = true
wxDraftRef.current = draft as any
Taro.removeStorageSync('WxAddressDraft')
setFormData(prev => ({
...prev,
...(draft as any)
}))
const p = String((draft as any)?.province || '').trim()
const c = String((draft as any)?.city || '').trim()
const r = String((draft as any)?.region || '').trim()
const regionText = [p, c, r].filter(Boolean).join(' ')
if (regionText) setText(regionText)
}
} catch (_e) {
// ignore
}
}
// 如果是编辑模式,加载地址数据
if (isEditMode && addressId) {
try {
@@ -35,6 +119,8 @@ const AddUserAddress = () => {
setFormData(address)
// 设置所在地区
setText(`${address.province} ${address.city} ${address.region}`)
// 回显已保存的经纬度(编辑模式)
if (hasValidLngLat(address)) setSelectedLocation({ lng: String(address.lng), lat: String(address.lat) })
} catch (error) {
console.error('加载地址失败:', error)
Taro.showToast({
@@ -210,15 +296,137 @@ const AddUserAddress = () => {
return null;
};
// 选择定位:打开地图让用户选点,保存经纬度到表单数据
const chooseGeoLocation = async () => {
const applyChosenLocation = (res: any) => {
if (!res) return
if (res.latitude === undefined || res.longitude === undefined) {
Taro.showToast({ title: '定位信息获取失败', icon: 'none' })
return
}
const next: SelectedLocation = {
lng: String(res.longitude),
lat: String(res.latitude),
name: res.name,
address: res.address
}
setSelectedLocation(next)
// 尝试从地图返回的 address 文本解析省市区best-effort
const regionResult = res?.provinceName || res?.cityName || res?.adName
? {
province: String(res.provinceName || ''),
city: String(res.cityName || ''),
region: String(res.adName || '')
}
: parseRegion(String(res.address || ''))
// 将地图选点的地址同步到“收货地址”(不额外拼接省市区字段,省市区由独立字段保存)
const nextDetailAddress = (() => {
const rawAddr = String(res.address || '').trim()
const name = String(res.name || '').trim()
const province = String(regionResult?.province || '').trim()
const city = String(regionResult?.city || '').trim()
const region = String(regionResult?.region || '').trim()
// 选择定位返回的 address 往往包含省市区,这里尽量剥离掉,避免和表单的省市区字段重复
let detail = rawAddr
for (const part of [province, city, region]) {
if (part) detail = detail.replace(part, '')
}
detail = detail.replace(/[,]+/g, ' ').replace(/\s+/g, ' ').trim()
const base = detail || rawAddr
if (!base && !name) return ''
if (!base) return name
if (!name) return base
return base.includes(name) ? base : `${base} ${name}`
})()
setFormData(prev => ({
...prev,
lng: next.lng,
lat: next.lat,
address: nextDetailAddress || prev.address,
province: regionResult?.province || prev.province,
city: regionResult?.city || prev.city,
region: regionResult?.region || prev.region
}))
if (regionResult?.province && regionResult?.city && regionResult?.region) {
setText(`${regionResult.province} ${regionResult.city} ${regionResult.region}`)
}
// 更新表单展示值Form initialValues 不会跟随 FormData 变化)
if (formRef.current) {
const patch: any = {}
if (nextDetailAddress) patch.address = nextDetailAddress
if (regionResult?.region) patch.region = regionResult.region
formRef.current.setFieldsValue(patch)
}
}
try {
const initLat = selectedLocation?.lat ? Number(selectedLocation.lat) : undefined
const initLng = selectedLocation?.lng ? Number(selectedLocation.lng) : undefined
const latitude = typeof initLat === 'number' && Number.isFinite(initLat) ? initLat : undefined
const longitude = typeof initLng === 'number' && Number.isFinite(initLng) ? initLng : undefined
const res = await Taro.chooseLocation({
latitude,
longitude
})
applyChosenLocation(res)
} catch (e: any) {
console.warn('选择定位失败:', e)
if (isUserCancel(e)) return
if (isLocationDenied(e)) {
try {
const modal = await Taro.showModal({
title: '需要定位权限',
content: '选择定位需要开启定位权限,请在设置中开启后重试。',
confirmText: '去设置'
})
if (modal.confirm) {
await Taro.openSetting()
// 权限可能刚被开启:重试一次
const res = await Taro.chooseLocation({})
applyChosenLocation(res)
}
} catch (_e) {
// ignore
}
return
}
try {
await Taro.showToast({ title: '打开地图失败,请重试', icon: 'none' })
} catch (_e) {
// ignore
}
}
}
// 提交表单
const submitSucceed = async (values: any) => {
const loc =
selectedLocation ||
(hasValidLngLat(FormData) ? { lng: String(FormData.lng), lat: String(FormData.lat) } : null)
if (!loc) {
Taro.showToast({ title: '请选择定位', icon: 'none' })
return
}
try {
// 准备提交的数据
const submitData = {
...values,
country: FormData.country,
province: FormData.province,
city: FormData.city,
region: FormData.region,
lng: loc.lng,
lat: loc.lat,
isDefault: true // 新增或编辑的地址都设为默认地址
};
@@ -271,13 +479,34 @@ const AddUserAddress = () => {
useEffect(() => {
// 动态设置页面标题
Taro.setNavigationBarTitle({
title: isEditMode ? '编辑收货地址' : '新增收货地址'
title: isEditMode ? '编辑收货地址' : (fromWx ? '完善收货地址' : '新增收货地址')
});
reload().then(() => {
setLoading(false)
})
}, [isEditMode]);
}, [fromWx, isEditMode]);
// NutUI Form 的 initialValues 在首次渲染后不再响应更新;微信导入时做一次 setFieldsValue 兜底回填。
useEffect(() => {
if (loading) return
if (isEditMode) return
const draft = wxDraftRef.current
if (!draft) return
if (!formRef.current?.setFieldsValue) return
try {
formRef.current.setFieldsValue({
name: (draft as any)?.name,
phone: (draft as any)?.phone,
address: (draft as any)?.address,
region: (draft as any)?.region
})
} catch (_e) {
// ignore
} finally {
wxDraftRef.current = null
}
}, [fromWx, isEditMode, loading])
if (loading) {
return <Loading className={'px-2'}></Loading>
@@ -324,10 +553,25 @@ const AddUserAddress = () => {
</CellGroup>
<View className={'bg-gray-100 h-3'}></View>
<CellGroup style={{padding: '4px 0'}}>
<Form.Item name="name" label="收货人" initialValue={FormData.name} required>
<Form.Item
name="name"
label="收货人"
initialValue={FormData.name}
rules={[{ required: true, message: '请输入收货人姓名' }]}
required
>
<Input placeholder="请输入收货人姓名" maxLength={10}/>
</Form.Item>
<Form.Item name="phone" label="手机号" initialValue={FormData.phone} required>
<Form.Item
name="phone"
label="手机号"
initialValue={FormData.phone}
rules={[
{ required: true, message: '请输入手机号' },
{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
]}
required
>
<Input placeholder="请输入手机号" maxLength={11}/>
</Form.Item>
<Form.Item
@@ -346,6 +590,27 @@ const AddUserAddress = () => {
<TextArea maxLength={50} placeholder="请输入详细收货地址"/>
</Form.Item>
</CellGroup>
<CellGroup>
<Cell
title="选择定位"
description={
selectedLocation?.address ||
(selectedLocation ? `经纬度:${selectedLocation.lng}, ${selectedLocation.lat}` : '用于计算是否超出配送范围')
}
extra={(
<div className={'flex items-center gap-2'}>
<div
className={'text-gray-900 text-sm'}
style={{maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}
>
{selectedLocation?.name || (selectedLocation ? '已选择' : '请选择')}
</div>
<ArrowRight className={'text-gray-400'}/>
</div>
)}
onClick={chooseGeoLocation}
/>
</CellGroup>
</Form>
<Address
@@ -365,7 +630,15 @@ const AddUserAddress = () => {
/>
{/* 底部浮动按钮 */}
<FixedButton text={isEditMode ? '更新地址' : '保存并使用'} onClick={() => submitSucceed} />
<FixedButton
text={isEditMode ? '更新地址' : '保存并使用'}
onClick={() => {
// 触发表单提交
if (formRef.current) {
formRef.current.submit();
}
}}
/>
</>
);
};

View File

@@ -1,4 +1,4 @@
export default definePageConfig({
navigationBarTitleText: '地址管理',
navigationBarTitleText: '配送管理',
navigationBarTextStyle: 'black'
})

View File

@@ -1,16 +1,58 @@
import {useState} from "react";
import Taro, {useDidShow} from '@tarojs/taro'
import {Button, Cell, CellGroup, Space, Empty, ConfigProvider, Divider} from '@nutui/nutui-react-taro'
import {Dongdong, ArrowRight, CheckNormal, Checked} from '@nutui/icons-react-taro'
import {Button, Cell, Space, Empty, ConfigProvider, Divider} from '@nutui/nutui-react-taro'
import {CheckNormal, Checked} from '@nutui/icons-react-taro'
import {View} from '@tarojs/components'
import {ShopUserAddress} from "@/api/shop/shopUserAddress/model";
import {listShopUserAddress, removeShopUserAddress, updateShopUserAddress} from "@/api/shop/shopUserAddress";
import FixedButton from "@/components/FixedButton";
import dayjs from "dayjs";
const Address = () => {
const [list, setList] = useState<ShopUserAddress[]>([])
const [address, setAddress] = useState<ShopUserAddress>()
const safeNavigateBack = async () => {
try {
const pages = (Taro as any).getCurrentPages?.() || []
if (Array.isArray(pages) && pages.length > 1) {
await Taro.navigateBack()
return true
}
} catch (_e) {
// ignore
}
return false
}
const parseTime = (raw?: unknown) => {
if (raw === undefined || raw === null || raw === '') return null;
// 兼容秒/毫秒时间戳
if (typeof raw === 'number' || (typeof raw === 'string' && /^\d+$/.test(raw))) {
const n = Number(raw);
return dayjs(Number.isFinite(n) ? (n < 1e12 ? n * 1000 : n) : raw as any);
}
return dayjs(raw as any);
}
const canModifyOncePerMonth = (item: ShopUserAddress) => {
const lastUpdate = parseTime(item.updateTime);
if (!lastUpdate || !lastUpdate.isValid()) return { ok: true as const };
// 若 updateTime 与 createTime 基本一致,则视为“未修改过”,不做限制
const createdAt = parseTime(item.createTime);
if (createdAt && createdAt.isValid() && Math.abs(lastUpdate.diff(createdAt, 'minute')) < 1) {
return { ok: true as const };
}
const nextAllowed = lastUpdate.add(1, 'month');
const now = dayjs();
if (now.isBefore(nextAllowed)) {
return { ok: false as const, nextAllowed: nextAllowed.format('YYYY-MM-DD HH:mm') };
}
return { ok: true as const };
}
const reload = () => {
listShopUserAddress({
userId: Taro.getStorageSync('UserId')
@@ -29,6 +71,8 @@ const Address = () => {
}
const onDefault = async (item: ShopUserAddress) => {
if (item.isDefault) return
if (address) {
await updateShopUserAddress({
...address,
@@ -36,14 +80,18 @@ const Address = () => {
})
}
await updateShopUserAddress({
id: item.id,
isDefault: true
...item,
isDefault: true,
})
Taro.showToast({
title: '设置成功',
icon: 'success'
});
reload();
// 设置默认地址通常是“选择地址”的动作:成功后返回上一页,体验更顺滑
setTimeout(async () => {
const backed = await safeNavigateBack()
if (!backed) reload()
}, 400)
}
const onDel = async (id?: number) => {
@@ -56,6 +104,12 @@ const Address = () => {
}
const selectAddress = async (item: ShopUserAddress) => {
if (item.isDefault) {
const backed = await safeNavigateBack()
if (!backed) reload()
return
}
if (address) {
await updateShopUserAddress({
...address,
@@ -63,11 +117,12 @@ const Address = () => {
})
}
await updateShopUserAddress({
id: item.id,
isDefault: true
...item,
isDefault: true,
})
setTimeout(() => {
Taro.navigateBack()
setTimeout(async () => {
const backed = await safeNavigateBack()
if (!backed) reload()
}, 500)
}
@@ -89,8 +144,8 @@ const Address = () => {
/>
<Space>
<Button onClick={() => Taro.navigateTo({url: '/user/address/add'})}></Button>
<Button type="success" fill="dashed"
onClick={() => Taro.navigateTo({url: '/user/address/wxAddress'})}></Button>
{/*<Button type="success" fill="dashed"*/}
{/* onClick={() => Taro.navigateTo({url: '/user/address/wxAddress'})}>获取微信地址</Button>*/}
</Space>
</div>
</ConfigProvider>
@@ -99,19 +154,19 @@ const Address = () => {
return (
<>
<CellGroup>
<Cell
onClick={() => Taro.navigateTo({url: '/user/address/wxAddress'})}
>
<div className={'flex justify-between items-center w-full'}>
<div className={'flex items-center gap-3'}>
<Dongdong className={'text-green-600'}/>
<div></div>
</div>
<ArrowRight className={'text-gray-400'}/>
</div>
</Cell>
</CellGroup>
{/*<CellGroup>*/}
{/* <Cell*/}
{/* onClick={() => Taro.navigateTo({url: '/user/address/wxAddress'})}*/}
{/* >*/}
{/* <div className={'flex justify-between items-center w-full'}>*/}
{/* <div className={'flex items-center gap-3'}>*/}
{/* <Dongdong className={'text-green-600'}/>*/}
{/* <div>获取微信地址</div>*/}
{/* </div>*/}
{/* <ArrowRight className={'text-gray-400'}/>*/}
{/* </div>*/}
{/* </Cell>*/}
{/*</CellGroup>*/}
{list.map((item, _) => (
<Cell.Group>
<Cell className={'flex flex-col gap-1'} onClick={() => selectAddress(item)}>
@@ -137,7 +192,17 @@ const Address = () => {
</View>
<Divider direction={'vertical'}/>
<View className={'text-gray-400'}
onClick={() => Taro.navigateTo({url: '/user/address/add?id=' + item.id})}>
onClick={() => {
const { ok, nextAllowed } = canModifyOncePerMonth(item);
if (!ok) {
Taro.showToast({
title: `一个月只能修改一次${nextAllowed ? '' + nextAllowed + ' 后可再次修改' : ''}`,
icon: 'none',
});
return;
}
Taro.navigateTo({url: '/user/address/add?id=' + item.id})
}}>
</View>
</>

View File

@@ -1,17 +1,17 @@
import {useEffect} from "react";
import Taro from '@tarojs/taro'
import {addShopUserAddress} from "@/api/shop/shopUserAddress";
const WxAddress = () => {
/**
* 从微信API获取用户收货地址
* 调用微信原生地址选择界面,获取成功后保存到服务器并刷新列表
* 调用微信原生地址选择界面,获取成功后跳转到“新增收货地址”页面,让用户选择定位后再保存
*/
const getWeChatAddress = () => {
Taro.chooseAddress()
.then(res => {
// 格式化微信返回的地址数据为后端所需格式
const addressData = {
.then(async res => {
// 仅填充微信地址信息,不要用“当前定位”覆盖经纬度(会造成经纬度与地址不匹配)。
// 选择后跳转到“新增/编辑收货地址”页面,让用户手动选择地图定位后再保存。
const addressDraft = {
name: res.userName,
phone: res.telNumber,
country: res.nationalCode || '中国',
@@ -19,38 +19,32 @@ const WxAddress = () => {
city: res.cityName,
region: res.countyName,
address: res.detailInfo,
postalCode: res.postalCode,
isDefault: false
isDefault: false,
}
console.log(res, 'addrs..')
// 调用保存地址的API假设存在该接口
addShopUserAddress(addressData)
.then((msg) => {
console.log(msg)
Taro.showToast({
title: `${msg}`,
icon: 'none'
})
setTimeout(() => {
// 保存成功后返回
Taro.navigateBack()
}, 1000)
})
.catch(error => {
console.error('保存地址失败:', error)
Taro.showToast({title: '保存地址失败', icon: 'error'})
})
Taro.setStorageSync('WxAddressDraft', addressDraft)
// 用 redirectTo 替换当前页面,避免保存后 navigateBack 回到空白的 wxAddress 页面。
await Taro.redirectTo({ url: '/user/address/add?fromWx=1&skipDefaultCheck=1' })
})
.catch(err => {
console.error('获取微信地址失败:', err)
// 用户取消选择地址:直接返回上一页
if (String(err?.errMsg || '').includes('cancel')) {
setTimeout(() => Taro.navigateBack(), 200)
return
}
// 处理用户拒绝授权的情况
if (err.errMsg.includes('auth deny')) {
if (String(err?.errMsg || '').includes('auth deny')) {
Taro.showModal({
title: '授权失败',
content: '请在设置中允许获取地址权限',
showCancel: false
})
setTimeout(() => Taro.navigateBack(), 300)
return
}
Taro.showToast({ title: '获取微信地址失败', icon: 'none' })
setTimeout(() => Taro.navigateBack(), 300)
})
}