完成consumer端同步

This commit is contained in:
2026-05-14 15:28:09 +08:00
parent 612fb3d360
commit 0ffbc53902
197 changed files with 92657 additions and 7564 deletions

View File

@@ -9,7 +9,7 @@
</view>
<!-- 地址列表 -->
<scroll-view class="address-list" scroll-y>
<scroll-view class="address-list" direction="vertical">
<!-- 地址为空 -->
<view v-if="addressList.length === 0" class="empty-address">
<text class="empty-icon">📍</text>
@@ -68,7 +68,7 @@
<text class="form-close" @click="cancelNewAddress">×</text>
</view>
<scroll-view class="form-content" scroll-y>
<scroll-view class="form-content" direction="vertical">
<view class="form-item">
<text class="form-label">收货人</text>
<input class="form-input" v-model="newAddress.recipient_name"
@@ -133,7 +133,7 @@
<script setup lang="uts">
import { ref, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import supa from '@/components/supadb/aksupainstance.uts'
import { supabaseService, type UserAddress, type AddAddressParams } from '@/utils/supabaseService.uts'
type AddressType = {
id: string
@@ -149,10 +149,20 @@ type AddressType = {
created_at: string
}
type NewAddressForm = {
recipient_name: string
phone: string
province: string
city: string
district: string
detail: string
is_default: boolean
}
const addressList = ref<Array<AddressType>>([])
const fromSelect = ref<boolean>(false)
const showNewAddressForm = ref<boolean>(false)
const newAddress = ref<any>({
const newAddress = ref<NewAddressForm>({
recipient_name: '',
phone: '',
province: '',
@@ -163,394 +173,31 @@ const newAddress = ref<any>({
})
const smartAddressInput = ref<string>('')
onLoad((options: any) => {
const optObj = (options instanceof UTSJSONObject) ? (options as UTSJSONObject) : (JSON.parse(JSON.stringify(options ?? {})) as UTSJSONObject)
const flag = optObj.getString('fromSelect') ?? ''
fromSelect.value = (flag == '1' || flag == 'true')
})
// 生命周期
onMounted(() => {
loadAddresses()
// 监听地址更新事件从checkout页面或其他页面
uni.$on('addressUpdated', (updatedAddressList: any) => {
addressList.value = updatedAddressList
})
})
// 组件卸载时移除事件监听
onUnmounted(() => {
uni.$off('addressUpdated')
})
// 加载地址列表
const loadAddresses = async () => {
const userId = getCurrentUserId()
if (!userId) {
uni.showToast({
title: '请先登录',
icon: 'none'
})
uni.navigateTo({
url: '/pages/user/login'
})
return
}
try {
const { data, error } = await supa
.from('user_addresses')
.select('*')
.eq('user_id', userId)
.order('is_default', { ascending: false })
.order('created_at', { ascending: false })
if (error !== null) {
console.error('加载地址失败:', error)
return
}
addressList.value = data ?? []
} catch (err) {
console.error('加载地址异常:', err)
function mapAddress(item: UserAddress): AddressType {
return {
id: item.id,
user_id: item.user_id,
recipient_name: item.recipient_name ?? '',
phone: item.phone ?? '',
province: item.province ?? '',
city: item.city ?? '',
district: item.district ?? '',
detail: item.detail_address ?? '',
postal_code: item.postal_code ?? null,
is_default: item.is_default,
created_at: item.created_at ?? ''
}
}
// 获取当前用户ID
const getCurrentUserId = (): string | null => {
const userStore = uni.getStorageSync('userInfo')
if (userStore instanceof UTSJSONObject) {
return userStore.getString('id')
}
const obj = JSON.parse(JSON.stringify(userStore ?? {})) as UTSJSONObject
return obj.getString('id')
function getCurrentUserId(): string {
return supabaseService.getCurrentUserId() ?? ''
}
// 获取完整地址
const getFullAddress = (address: AddressType): string => {
function getFullAddress(address: AddressType): string {
return `${address.province}${address.city}${address.district}${address.detail}`
}
// 选择地址
const selectAddress = (address: AddressType) => {
if (fromSelect.value) {
try {
uni.setStorageSync('selectedAddress', JSON.stringify(address))
} catch (e) {}
uni.$emit('addressSelected', address)
uni.navigateBack()
}
}
// 编辑地址
const editAddress = (address: AddressType) => {
uni.navigateTo({
url: `/pages/mall/consumer/address-edit?id=${address.id}`
})
}
// 删除地址
const deleteAddress = (address: AddressType) => {
uni.showModal({
title: '删除地址',
content: '确定要删除这个收货地址吗?',
success: async (res) => {
if (res.confirm) {
try {
// 如果是默认地址,删除前检查是否还有其他地址
if (address.is_default && addressList.value.length > 1) {
uni.showModal({
title: '提示',
content: '删除默认地址后,系统会自动设置第一个地址为默认地址',
success: async (confirmRes) => {
if (confirmRes.confirm) {
await performDelete(address)
}
}
})
} else {
await performDelete(address)
}
} catch (err) {
console.error('删除地址异常:', err)
}
}
}
})
}
// 执行删除
const performDelete = async (address: AddressType) => {
try {
const { error } = await supa
.from('user_addresses')
.delete()
.eq('id', address.id)
if (error !== null) {
console.error('删除地址失败:', error)
uni.showToast({
title: '删除失败',
icon: 'none'
})
return
}
// 从列表中移除
const index = addressList.value.findIndex(item => item.id === address.id)
if (index !== -1) {
addressList.value.splice(index, 1)
}
// 如果是默认地址被删除,设置第一个地址为默认
if (address.is_default && addressList.value.length > 0) {
const newDefault = addressList.value[0]
await setAsDefault(newDefault)
}
uni.showToast({
title: '删除成功',
icon: 'success'
})
} catch (err) {
console.error('执行删除异常:', err)
}
}
// 设为默认地址
const setDefaultAddress = async (address: AddressType) => {
try {
const userId = getCurrentUserId()
if (!userId) return
// 1. 取消当前所有默认地址
const { error: updateError } = await supa
.from('user_addresses')
.update({ is_default: false })
.eq('user_id', userId)
.eq('is_default', true)
if (updateError !== null) {
console.error('取消默认地址失败:', updateError)
return
}
// 2. 设置新的默认地址
const { error: setError } = await supa
.from('user_addresses')
.update({ is_default: true })
.eq('id', address.id)
if (setError !== null) {
console.error('设置默认地址失败:', setError)
return
}
// 更新本地数据
addressList.value.forEach(item => {
item.is_default = item.id === address.id
})
uni.showToast({
title: '已设为默认地址',
icon: 'success'
})
} catch (err) {
console.error('设置默认地址异常:', err)
}
}
// 设置地址为默认(内部方法)
const setAsDefault = async (address: AddressType) => {
try {
const { error } = await supa
.from('user_addresses')
.update({ is_default: true })
.eq('id', address.id)
if (error !== null) {
console.error('设置默认地址失败:', error)
return
}
address.is_default = true
} catch (err) {
console.error('设置默认地址异常:', err)
}
}
// 解析智能地址
const parseSmartAddress = () => {
const input = smartAddressInput.value.trim()
if (!input) return
// 重置表单
newAddress.value.recipient_name = ''
newAddress.value.phone = ''
newAddress.value.province = ''
newAddress.value.city = ''
newAddress.value.district = ''
newAddress.value.detail = ''
// 尝试匹配手机号码11位数字
const phoneRegex = /(1[3-9]\d{9})/g
const phoneMatches = input.match(phoneRegex)
if (phoneMatches && phoneMatches.length > 0) {
newAddress.value.phone = phoneMatches[0]
}
// 尝试匹配收件人姓名中文姓名2-4个汉字
const nameRegex = /([\u4e00-\u9fa5]{2,4})/g
const nameMatches = input.match(nameRegex)
if (nameMatches && nameMatches.length > 0) {
// 取第一个匹配的中文姓名作为收件人
newAddress.value.recipient_name = nameMatches[0]
}
// 提取地址部分(移除姓名和手机号)
let addressText = input
if (newAddress.value.recipient_name) {
addressText = addressText.replace(newAddress.value.recipient_name, '')
}
if (newAddress.value.phone) {
addressText = addressText.replace(newAddress.value.phone, '')
}
// 清理地址文本(移除多余的空格和标点)
addressText = addressText.replace(/[,;\s]+/g, ' ').trim()
// 地址解析逻辑
const patterns = [
// 匹配格式:省市区详细地址
/^(.*?省)?(.*?市)?(.*?[区县])?(.*)$/,
// 匹配格式:省市详细地址
/^(.*?省)?(.*?市)?(.*)$/
]
for (const pattern of patterns) {
const match = addressText.match(pattern)
if (match) {
const [, province, city, district, detail] = match
if (province) newAddress.value.province = province.replace('省', '').trim()
if (city) newAddress.value.city = city.replace('市', '').trim()
if (district) newAddress.value.district = district.trim()
if (detail) newAddress.value.detail = detail.trim()
// 如果详细地址为空,但还有剩余内容,则作为详细地址
if (!newAddress.value.detail && district && detail) {
newAddress.value.detail = detail.trim()
}
break
}
}
// 如果没有匹配到模式,尝试简单分割
if (!newAddress.value.province && !newAddress.value.city && !newAddress.value.district) {
// 尝试按常见分隔符分割
const parts = addressText.split(/[省市县区]/)
if (parts.length >= 2) {
newAddress.value.province = parts[0] || ''
newAddress.value.city = parts[1] || ''
newAddress.value.detail = parts.slice(2).join('').trim() || addressText
} else {
newAddress.value.detail = addressText
}
}
// 如果地址部分为空,但还有剩余文本,则作为详细地址
if (!newAddress.value.detail && addressText.trim()) {
newAddress.value.detail = addressText.trim()
}
}
// 保存新地址
const saveNewAddress = async () => {
// 验证表单
if (!newAddress.value.recipient_name || !newAddress.value.phone || !newAddress.value.detail) {
uni.showToast({
title: '请填写完整信息',
icon: 'none'
})
return
}
const userId = getCurrentUserId()
if (!userId) {
uni.showToast({
title: '请先登录',
icon: 'none'
})
return
}
try {
const { data, error } = await supa
.from('user_addresses')
.insert({
user_id: userId,
recipient_name: newAddress.value.recipient_name,
phone: newAddress.value.phone,
province: newAddress.value.province,
city: newAddress.value.city,
district: newAddress.value.district,
detail: newAddress.value.detail,
is_default: newAddress.value.is_default,
created_at: new Date().toISOString()
})
.select()
.single()
if (error !== null) {
console.error('保存地址失败:', error)
uni.showToast({
title: '保存失败',
icon: 'none'
})
return
}
// 如果是默认地址,取消其他默认地址
if (newAddress.value.is_default) {
addressList.value.forEach(addr => {
addr.is_default = false
})
// 更新数据库中的其他地址
await supa
.from('user_addresses')
.update({ is_default: false })
.eq('user_id', userId)
.neq('id', data.id)
}
// 添加到列表
addressList.value.unshift(data)
// 发布地址更新事件让checkout页面也能获取到
uni.$emit('addressUpdated', addressList.value)
// 重置表单
resetNewAddressForm()
uni.showToast({
title: '地址保存成功',
icon: 'success'
})
} catch (err) {
console.error('保存地址异常:', err)
uni.showToast({
title: '保存失败',
icon: 'none'
})
}
}
// 重置新建地址表单
const resetNewAddressForm = () => {
function resetNewAddressForm(): void {
showNewAddressForm.value = false
newAddress.value = {
recipient_name: '',
@@ -564,17 +211,275 @@ const resetNewAddressForm = () => {
smartAddressInput.value = ''
}
// 取消新建地址
const cancelNewAddress = () => {
function cancelNewAddress(): void {
resetNewAddressForm()
}
function selectAddress(address: AddressType): void {
if (fromSelect.value) {
try {
uni.setStorageSync('selectedAddress', JSON.stringify(address))
} catch (e) {}
uni.$emit('addressSelected', address)
uni.navigateBack()
}
}
function editAddress(address: AddressType): void {
uni.navigateTo({
url: `/pages/mall/consumer/address-edit?id=${address.id}`
})
}
async function loadAddresses(): Promise<void> {
const userId = getCurrentUserId()
if (userId === '') {
uni.showToast({
title: '请先登录',
icon: 'none'
})
uni.navigateTo({
url: '/pages/user/login'
})
return
}
try {
const items = await supabaseService.getAddresses()
const nextList: AddressType[] = []
for (let i = 0; i < items.length; i++) {
nextList.push(mapAddress(items[i]))
}
addressList.value = nextList
} catch (err) {
console.error('加载地址异常:', err)
addressList.value = []
}
}
async function doDeleteAddress(address: AddressType): Promise<void> {
const success = await supabaseService.deleteAddress(address.id)
if (!success) {
uni.showToast({
title: '删除失败',
icon: 'none'
})
return
}
await loadAddresses()
if (address.is_default && addressList.value.length > 0) {
await supabaseService.setDefaultAddress(addressList.value[0].id)
await loadAddresses()
}
uni.showToast({
title: '删除成功',
icon: 'success'
})
}
function confirmDeleteAddress(address: AddressType): void {
doDeleteAddress(address)
}
function deleteAddress(address: AddressType): void {
uni.showModal({
title: '删除地址',
content: '确定要删除这个收货地址吗?',
success: (res) => {
if (!res.confirm) return
if (address.is_default && addressList.value.length > 1) {
uni.showModal({
title: '提示',
content: '删除默认地址后,系统会自动设置第一个地址为默认地址',
success: (confirmRes) => {
if (confirmRes.confirm) {
confirmDeleteAddress(address)
}
}
})
return
}
confirmDeleteAddress(address)
}
})
}
async function setDefaultAddress(address: AddressType): Promise<void> {
const success = await supabaseService.setDefaultAddress(address.id)
if (!success) {
uni.showToast({
title: '设置失败',
icon: 'none'
})
return
}
await loadAddresses()
uni.showToast({
title: '已设为默认地址',
icon: 'success'
})
}
function parseSmartAddress(): void {
const input = smartAddressInput.value.trim()
if (input === '') return
newAddress.value.recipient_name = ''
newAddress.value.phone = ''
newAddress.value.province = ''
newAddress.value.city = ''
newAddress.value.district = ''
newAddress.value.detail = ''
const phoneRegex = /(1[3-9]\d{9})/g
const phoneMatches = input.match(phoneRegex)
if (phoneMatches != null && phoneMatches.length > 0) {
newAddress.value.phone = phoneMatches[0] ?? ''
}
const nameRegex = /([\u4e00-\u9fa5]{2,4})/g
const nameMatches = input.match(nameRegex)
if (nameMatches != null && nameMatches.length > 0) {
newAddress.value.recipient_name = nameMatches[0] ?? ''
}
let addressText = input
if (newAddress.value.recipient_name !== '') {
addressText = addressText.replace(newAddress.value.recipient_name, '')
}
if (newAddress.value.phone !== '') {
addressText = addressText.replace(newAddress.value.phone, '')
}
addressText = addressText.replace(/[,;\s]+/g, ' ').trim()
const patterns = [
/^(.*?省)?(.*?市)?(.*?[区县])?(.*)$/,
/^(.*?省)?(.*?市)?(.*)$/
]
for (let i = 0; i < patterns.length; i++) {
const match = addressText.match(patterns[i])
if (match != null) {
const province = match.length > 1 ? (match[1] ?? '') : ''
const city = match.length > 2 ? (match[2] ?? '') : ''
const district = match.length > 3 ? (match[3] ?? '') : ''
const detail = match.length > 4 ? (match[4] ?? '') : ''
if (province !== '') newAddress.value.province = province.replace('省', '').trim()
if (city !== '') newAddress.value.city = city.replace('市', '').trim()
if (district !== '') newAddress.value.district = district.trim()
if (detail !== '') newAddress.value.detail = detail.trim()
if (newAddress.value.detail === '' && district !== '' && detail !== '') {
newAddress.value.detail = detail.trim()
}
break
}
}
if (newAddress.value.province === '' && newAddress.value.city === '' && newAddress.value.district === '') {
const parts = addressText.split(/[省市县区]/)
if (parts.length >= 2) {
newAddress.value.province = parts[0] ?? ''
newAddress.value.city = parts[1] ?? ''
const detailCandidate = parts.slice(2).join('').trim()
newAddress.value.detail = detailCandidate !== '' ? detailCandidate : addressText
} else {
newAddress.value.detail = addressText
}
}
if (newAddress.value.detail === '' && addressText.trim() !== '') {
newAddress.value.detail = addressText.trim()
}
}
async function saveNewAddress(): Promise<void> {
if (newAddress.value.recipient_name === '' || newAddress.value.phone === '' || newAddress.value.detail === '') {
uni.showToast({
title: '请填写完整信息',
icon: 'none'
})
return
}
const userId = getCurrentUserId()
if (userId === '') {
uni.showToast({
title: '请先登录',
icon: 'none'
})
return
}
const payload: AddAddressParams = {
recipient_name: newAddress.value.recipient_name,
phone: newAddress.value.phone,
province: newAddress.value.province,
city: newAddress.value.city,
district: newAddress.value.district,
detail_address: newAddress.value.detail,
is_default: newAddress.value.is_default
}
try {
const success = await supabaseService.addAddress(payload)
if (!success) {
uni.showToast({
title: '保存失败',
icon: 'none'
})
return
}
await loadAddresses()
uni.$emit('addressUpdated', addressList.value)
resetNewAddressForm()
uni.showToast({
title: '地址保存成功',
icon: 'success'
})
} catch (err) {
console.error('保存地址异常:', err)
uni.showToast({
title: '保存失败',
icon: 'none'
})
}
}
onLoad((options) => {
const optObj = (options instanceof UTSJSONObject) ? (options as UTSJSONObject) : (JSON.parse(JSON.stringify(options ?? {})) as UTSJSONObject)
const flag = optObj.getString('fromSelect') ?? ''
fromSelect.value = (flag == '1' || flag == 'true')
})
// 生命周期
function handleAddressUpdated(): void {
loadAddresses()
}
onMounted(() => {
loadAddresses()
// 监听地址更新事件从checkout页面或其他页面
uni.$on('addressUpdated', handleAddressUpdated)
})
// 组件卸载时移除事件监听
onUnmounted(() => {
uni.$off('addressUpdated')
})
</script>
<style scoped>
.address-page {
display: flex;
flex-direction: column;
height: 100vh;
height: 100%;
background-color: #f5f5f5;
}
@@ -765,7 +670,7 @@ const cancelNewAddress = () => {
background-color: #ffffff;
width: 90%;
max-width: 500px;
max-height: 80vh;
max-height: 80%;
border-radius: 12px;
display: flex;
flex-direction: column;
@@ -794,7 +699,7 @@ const cancelNewAddress = () => {
.form-content {
flex: 1;
padding: 15px;
max-height: 50vh;
max-height: 50%;
}
.form-item {