添加首页加载skeleton

This commit is contained in:
2026-05-26 17:04:04 +08:00
parent 9680276b3f
commit 2f528c049f
10 changed files with 1329 additions and 410 deletions

View File

@@ -3,6 +3,7 @@ import { getCurrentUserId } from '@/utils/store.uts'
import { getCurrentUser } from '@/utils/store.uts'
import type { UserAddress } from '@/utils/supabaseService.uts'
import type { HomeServiceCatalogType } from '@/types/home-service.uts'
import type { DeliveryServiceRecordType } from '@/types/delivery.uts'
import {
getServiceOrderStatusText,
normalizeServiceOrderStatus,
@@ -38,6 +39,25 @@ function buildId(prefix: string): string {
return prefix + '-' + String(Date.now()) + '-' + String(Math.floor(Math.random() * 100000)).padStart(5, '0')
}
function buildHex(length: number): string {
const chars = '0123456789abcdef'
let result = ''
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
function buildUuidLike(): string {
const segment1 = buildHex(8)
const segment2 = buildHex(4)
const segment3 = '4' + buildHex(3)
const variants = '89ab'
const segment4 = variants.charAt(Math.floor(Math.random() * variants.length)) + buildHex(3)
const segment5 = buildHex(12)
return segment1 + '-' + segment2 + '-' + segment3 + '-' + segment4 + '-' + segment5
}
function buildOrderNo(): string {
const date = new Date()
const y = String(date.getFullYear())
@@ -144,6 +164,17 @@ function safeJsonField(source: any, key: string): string {
return JSON.stringify(value)
}
function safeFirstJsonField(source: any, keys: Array<string>): string {
const plain = JSON.parse(JSON.stringify(source)) as any
for (let i = 0; i < keys.length; i++) {
const value = plain[keys[i]]
if (value != null) {
return JSON.stringify(value)
}
}
return ''
}
function plainObject(source: any): any {
return JSON.parse(JSON.stringify(source)) as any
}
@@ -168,6 +199,171 @@ function readNumber(source: any, key: string): number {
return 0
}
function hasMissingColumnError(error: any, columnName: string): boolean {
if (error == null || columnName == '') {
return false
}
const errorText = JSON.stringify(error).toLowerCase()
return errorText.indexOf('could not find the') >= 0 && errorText.indexOf(columnName.toLowerCase()) >= 0
}
function shouldUseCareTaskPath(orderId: string): boolean {
return isUuidLike(orderId)
}
function isStaffActive(staff: any): boolean {
const plain = plainObject(staff)
if (plain['deleted_at'] != null && String(plain['deleted_at']) != '') {
return false
}
if (plain['is_active'] === false) {
return false
}
return readNumber(staff, 'status') == 1
}
function getStaffPriority(staff: any): number {
let score = 0
const onlineStatus = readString(staff, 'online_status')
if (onlineStatus == 'online') {
score += 30
} else if (onlineStatus == 'resting' || onlineStatus == '') {
score += 20
} else if (onlineStatus == 'busy') {
score += 10
}
if (readString(staff, 'uid') != '') {
score += 5
}
if (readString(staff, 'station_id') != '') {
score += 1
}
return score
}
async function getAutoAssignableStaff(): Promise<any | null> {
const staffResponse = await supa
.from('ml_delivery_staff')
.select('id, uid, station_id, nickname, phone, status, deleted_at, is_active, online_status, updated_at, created_at')
.eq('status', 1)
.execute()
if (staffResponse.error != null || staffResponse.data == null) {
return null
}
const rawStaffList = staffResponse.data as Array<any>
let selected: any = null
let bestScore = -1
let bestTime = ''
for (let i = 0; i < rawStaffList.length; i++) {
const staff = rawStaffList[i]
if (!isStaffActive(staff)) {
continue
}
const score = getStaffPriority(staff)
const timeMark = readFirstString(staff, ['updated_at', 'created_at'])
if (selected == null || score > bestScore || (score == bestScore && timeMark > bestTime)) {
selected = staff
bestScore = score
bestTime = timeMark
}
}
return selected
}
function buildEcServiceRequestPayload(params: CreateServiceOrderParams, userId: string, requestId: string, createdAt: string, appointmentTime: string | null, useAddressSnapshot: boolean): any {
const payload = {
id: requestId,
user_id: userId,
service_catalog_id: params.service.id,
service_name: params.service.name,
service_category: params.service.category,
elder_name: params.recipientName,
elder_phone: params.recipientPhone,
contact_name: params.contactName,
contact_phone: params.contactPhone,
scheduled_at: appointmentTime,
remark: params.remark,
status: 'ORDER_CREATED',
created_at: createdAt,
updated_at: createdAt
} as any
if (useAddressSnapshot) {
payload.address_snapshot = params.address as any
} else {
payload.address_snapshot_json = params.address as any
}
return payload
}
function buildEcServiceRequestPayloadWithoutAddress(params: CreateServiceOrderParams, userId: string, requestId: string, createdAt: string, appointmentTime: string | null): any {
return {
id: requestId,
user_id: userId,
service_catalog_id: params.service.id,
service_name: params.service.name,
service_category: params.service.category,
elder_name: params.recipientName,
elder_phone: params.recipientPhone,
contact_name: params.contactName,
contact_phone: params.contactPhone,
scheduled_at: appointmentTime,
remark: params.remark,
status: 'ORDER_CREATED',
created_at: createdAt,
updated_at: createdAt
} as any
}
function buildEcCareTaskPayload(params: CreateServiceOrderParams, userId: string, requestId: string, taskId: string, taskNo: string, createdAt: string, appointmentTime: string | null, useAddressSnapshot: boolean): any {
const payload = {
id: taskId,
task_no: taskNo,
request_id: requestId,
user_id: userId,
service_catalog_id: params.service.id,
service_name: params.service.name,
service_category: params.service.category,
service_snapshot_json: params.service as any,
elder_name: params.recipientName,
elder_phone: params.recipientPhone,
contact_name: params.contactName,
contact_phone: params.contactPhone,
scheduled_at: appointmentTime,
remark: params.remark,
status: 'ORDER_CREATED',
created_at: createdAt,
updated_at: createdAt
} as any
if (useAddressSnapshot) {
payload.address_snapshot = params.address as any
} else {
payload.address_snapshot_json = params.address as any
}
return payload
}
function buildEcCareTaskPayloadWithoutAddress(params: CreateServiceOrderParams, userId: string, requestId: string, taskId: string, taskNo: string, createdAt: string, appointmentTime: string | null): any {
return {
id: taskId,
task_no: taskNo,
request_id: requestId,
user_id: userId,
service_catalog_id: params.service.id,
service_name: params.service.name,
service_category: params.service.category,
service_snapshot_json: params.service as any,
elder_name: params.recipientName,
elder_phone: params.recipientPhone,
contact_name: params.contactName,
contact_phone: params.contactPhone,
scheduled_at: appointmentTime,
remark: params.remark,
status: 'ORDER_CREATED',
created_at: createdAt,
updated_at: createdAt
} as any
}
function parseTimeline(item: any): ServiceOrderTimelineItemType {
return {
id: readString(item, 'id'),
@@ -231,7 +427,7 @@ function parseEvidenceFile(item: any): ServiceEvidenceFileType {
}
function parseServiceOrder(item: any, logs: Array<ServiceOrderTimelineItemType>, review: ServiceReviewType | null): ServiceOrderType {
const addressSnapshot = safeJsonField(item, 'address_snapshot_json')
const addressSnapshot = safeFirstJsonField(item, ['address_snapshot_json', 'address_snapshot'])
const serviceSnapshot = safeJsonField(item, 'service_snapshot_json')
const addressObj = plainObject(safeParseObject(addressSnapshot))
const serviceObj = plainObject(safeParseObject(serviceSnapshot))
@@ -354,7 +550,7 @@ function readJsonObjectField(source: any, keys: Array<string>): any {
function mapCareTaskRowToLegacyOrderRow(item: any): any {
const serviceSnapshotValue = readJsonObjectField(item, ['service_snapshot_json'])
const addressSnapshotValue = readJsonObjectField(item, ['address_snapshot_json'])
const addressSnapshotValue = readJsonObjectField(item, ['address_snapshot', 'address_snapshot_json'])
let derivedStatus = readString(item, 'status')
if (readFirstString(item, ['accepted_by_family_at']) != '') {
derivedStatus = 'ACCEPTED'
@@ -478,6 +674,9 @@ function buildLegacyExecutionRecord(taskId: string, records: Array<any>): Servic
}
async function getCareTaskDetail(taskId: string): Promise<ServiceOrderType | null> {
if (!isUuidLike(taskId)) {
return null
}
const taskResponse = await supa.from('ec_care_tasks').select('*').eq('id', taskId).limit(1).execute()
if (taskResponse.error != null || taskResponse.data == null) {
return null
@@ -545,74 +744,54 @@ async function tryCreateCareTask(params: CreateServiceOrderParams): Promise<Serv
if (userId == '') {
return null
}
const requestId = buildId('sr')
const taskId = buildId('ct')
const requestId = buildUuidLike()
const taskId = buildUuidLike()
const taskNo = buildOrderNo()
const createdAt = nowIso()
const appointmentTime = normalizeAppointmentTime(params.appointmentTime)
const requestResponse = await supa.from('ec_service_requests').insert({
id: requestId,
user_id: userId,
service_catalog_id: params.service.id,
service_name: params.service.name,
service_category: params.service.category,
elder_name: params.recipientName,
elder_phone: params.recipientPhone,
contact_name: params.contactName,
contact_phone: params.contactPhone,
address_snapshot_json: params.address as any,
scheduled_at: appointmentTime,
remark: params.remark,
status: 'ORDER_CREATED',
created_at: createdAt,
updated_at: createdAt
}).execute()
let requestResponse = await supa.from('ec_service_requests').insert(
buildEcServiceRequestPayload(params, userId, requestId, createdAt, appointmentTime, true)
).execute()
if (requestResponse.error != null) {
requestResponse = await supa.from('ec_service_requests').insert(
buildEcServiceRequestPayload(params, userId, requestId, createdAt, appointmentTime, false)
).execute()
}
if (requestResponse.error != null) {
requestResponse = await supa.from('ec_service_requests').insert(
buildEcServiceRequestPayloadWithoutAddress(params, userId, requestId, createdAt, appointmentTime)
).execute()
}
if (requestResponse.error != null) {
return null
}
const taskResponse = await supa.from('ec_care_tasks').insert({
id: taskId,
task_no: taskNo,
request_id: requestId,
user_id: userId,
service_catalog_id: params.service.id,
service_name: params.service.name,
service_category: params.service.category,
service_snapshot_json: params.service as any,
address_snapshot_json: params.address as any,
elder_name: params.recipientName,
elder_phone: params.recipientPhone,
contact_name: params.contactName,
contact_phone: params.contactPhone,
scheduled_at: appointmentTime,
remark: params.remark,
status: 'ORDER_CREATED',
created_at: createdAt,
updated_at: createdAt
}).execute()
let taskResponse = await supa.from('ec_care_tasks').insert(
buildEcCareTaskPayload(params, userId, requestId, taskId, taskNo, createdAt, appointmentTime, true)
).execute()
if (taskResponse.error != null) {
taskResponse = await supa.from('ec_care_tasks').insert(
buildEcCareTaskPayload(params, userId, requestId, taskId, taskNo, createdAt, appointmentTime, false)
).execute()
}
if (taskResponse.error != null) {
taskResponse = await supa.from('ec_care_tasks').insert(
buildEcCareTaskPayloadWithoutAddress(params, userId, requestId, taskId, taskNo, createdAt, appointmentTime)
).execute()
}
if (taskResponse.error != null) {
return null
}
await insertWorkOrderEvent(taskId, '', 'ORDER_CREATED', userId, 'consumer', 'create_task', '创建服务申请')
const staffResponse = await supa
.from('ml_delivery_staff')
.select('id, uid, station_id, nickname, phone, status, deleted_at')
.eq('status', 1)
.order('created_at', { ascending: true })
.execute()
if (staffResponse.data != null) {
const rawStaffList = staffResponse.data as Array<any>
if (rawStaffList.length > 0) {
const staffObj = rawStaffList[0]
const assignedUserId = readFirstString(staffObj, ['uid', 'id'])
if (assignedUserId != '') {
await supa.from('ec_care_tasks').update({
status: 'ORDER_ASSIGNED',
assigned_to: assignedUserId,
updated_at: createdAt
}).eq('id', taskId).execute()
await insertWorkOrderEvent(taskId, 'ORDER_CREATED', 'ORDER_ASSIGNED', userId, 'system', 'assign_task', '系统已自动派单')
}
const assignedStaff = await getAutoAssignableStaff()
if (assignedStaff != null) {
const assignedUserId = readString(assignedStaff, 'uid')
if (assignedUserId != '') {
await supa.from('ec_care_tasks').update({
status: 'ORDER_ASSIGNED',
assigned_to: assignedUserId,
updated_at: createdAt
}).eq('id', taskId).execute()
await insertWorkOrderEvent(taskId, 'ORDER_CREATED', 'ORDER_ASSIGNED', userId, 'system', 'assign_task', '系统已自动派单')
}
}
return await getCareTaskDetail(taskId)
@@ -728,22 +907,15 @@ export async function createServiceOrder(params: CreateServiceOrderParams): Prom
return null
}
await insertLegacyStatusLog(orderId, '', 'created', userId, 'consumer', '创建服务订单')
const staffResponse = await supa
.from('ml_delivery_staff')
.select('id, station_id, nickname, phone, status, deleted_at')
.eq('status', 1)
.order('created_at', { ascending: true })
.execute()
if (staffResponse.data != null) {
const rawStaffList = staffResponse.data as any[]
if (rawStaffList.length > 0) {
const staffObj = plainObject(rawStaffList[0])
const staffObj = await getAutoAssignableStaff()
if (staffObj != null) {
const plainStaff = plainObject(staffObj)
const assignmentId = buildId('sa')
await supa.from('hss_service_assignments').insert({
id: assignmentId,
order_id: orderId,
staff_id: readString(staffObj, 'id'),
station_id: readString(staffObj, 'station_id') == '' ? null : readString(staffObj, 'station_id'),
staff_id: readString(plainStaff, 'id'),
station_id: readString(plainStaff, 'station_id') == '' ? null : readString(plainStaff, 'station_id'),
status: 'assigned',
assigned_at: now,
created_at: now,
@@ -752,11 +924,10 @@ export async function createServiceOrder(params: CreateServiceOrderParams): Prom
await supa.from('hss_service_orders').update({
status: 'assigned',
current_assignment_id: assignmentId,
current_staff_id: readString(staffObj, 'id'),
current_staff_id: readString(plainStaff, 'id'),
updated_at: now
}).eq('id', orderId).execute()
await insertLegacyStatusLog(orderId, 'created', 'assigned', userId, 'system', '系统已自动派单')
}
}
return await getLegacyServiceOrderDetail(orderId)
}
@@ -794,19 +965,94 @@ export async function listConsumerServiceOrders(): Promise<Array<ServiceOrderTyp
}
export async function getServiceOrderDetail(orderId: string): Promise<ServiceOrderType | null> {
const careTask = await getCareTaskDetail(orderId)
if (careTask != null) {
return careTask
if (shouldUseCareTaskPath(orderId)) {
const careTask = await getCareTaskDetail(orderId)
if (careTask != null) {
return careTask
}
}
return await getLegacyServiceOrderDetail(orderId)
}
export async function saveServiceRecord(orderId: string, record: DeliveryServiceRecordType): Promise<ServiceOrderType | null> {
const userId = getCurrentUserId()
if (userId == '') {
return null
}
const careTask = shouldUseCareTaskPath(orderId) ? await getCareTaskDetail(orderId) : null
if (careTask != null) {
const savedAt = nowIso()
const serviceContent = record.serviceContent.length > 0 ? record.serviceContent : record.serviceItems.map(item => item.name)
const serviceSummary = record.serviceSummary != '' ? record.serviceSummary : record.processNote
const healthMetrics = record.healthMetrics as any
const familyConfirmation = record.familyConfirmation as any
const insertResponse = await supa.from('ec_care_records').insert({
id: buildId('care-record'),
task_id: orderId,
record_type: 'service_record',
created_by: userId,
service_items_json: record.serviceItems as any,
service_content_json: serviceContent as any,
service_summary: serviceSummary,
process_note: record.processNote,
elder_status: record.elderStatus,
health_metrics_json: healthMetrics,
materials_used: record.materialsUsed,
abnormal_note: record.abnormalNote,
photos_json: record.photos as any,
staff_remark: record.staffRemark,
family_confirmation_json: familyConfirmation,
created_at: savedAt,
updated_at: savedAt
}).execute()
if (insertResponse.error != null) {
return null
}
const updateResponse = await supa.from('ec_care_tasks').update({
updated_at: savedAt
}).eq('id', orderId).execute()
if (updateResponse.error != null) {
return null
}
await insertWorkOrderEvent(orderId, careTask.status, careTask.status, userId, 'staff', 'save_service_record', serviceSummary == '' ? '服务记录已保存' : serviceSummary)
return await getCareTaskDetail(orderId)
}
const current = await getLegacyServiceOrderDetail(orderId)
if (current == null) {
return null
}
const savedAt = nowIso()
const serviceSummary = record.serviceSummary != '' ? record.serviceSummary : record.processNote
const saveResponse = await supa.from('hss_service_execution_records').insert({
id: buildId('ser'),
order_id: orderId,
checkin_time: current.executionRecord != null ? current.executionRecord.checkin_time : savedAt,
checkin_latitude: current.executionRecord != null ? current.executionRecord.checkin_latitude : 0,
checkin_longitude: current.executionRecord != null ? current.executionRecord.checkin_longitude : 0,
checkin_address: current.executionRecord != null ? current.executionRecord.checkin_address : '',
service_content_json: record.serviceContent.length > 0 ? record.serviceContent as any : record.serviceItems.map(item => item.name) as any,
service_summary: serviceSummary,
completion_images_json: record.photos as any,
signature_image: '',
signature_name: record.familyConfirmation.familyMember,
created_at: savedAt,
updated_at: savedAt
}).execute()
if (saveResponse.error != null) {
return null
}
await supa.from('hss_service_orders').update({
updated_at: savedAt
}).eq('id', orderId).execute()
return await getLegacyServiceOrderDetail(orderId)
}
export async function confirmServiceOrder(orderId: string, rating: number, content: string, tags: Array<string>): Promise<ServiceOrderType | null> {
const userId = getCurrentUserId()
if (userId == '') {
return null
}
const careTask = await getCareTaskDetail(orderId)
const careTask = shouldUseCareTaskPath(orderId) ? await getCareTaskDetail(orderId) : null
if (careTask != null) {
const acceptedAt = nowIso()
const updateResponse = await supa.from('ec_care_tasks').update({
@@ -870,7 +1116,7 @@ export async function rejectServiceOrderAcceptance(orderId: string, content: str
if (userId == '') {
return null
}
const careTask = await getCareTaskDetail(orderId)
const careTask = shouldUseCareTaskPath(orderId) ? await getCareTaskDetail(orderId) : null
if (careTask != null) {
const rejectedAt = nowIso()
const updateResponse = await supa.from('ec_care_tasks').update({
@@ -914,75 +1160,4 @@ export async function rejectServiceOrderAcceptance(orderId: string, content: str
export async function getCurrentConsumerUser() {
return await getCurrentUser()
}
export async function getOrdersByTab(tab: string): Promise<Array<ServiceOrderType>> {
const orders = await listConsumerServiceOrders()
if (tab == 'pending') {
return orders.filter((order) => {
return order.status != 'ACCEPTED' && order.status != 'COMPLETED' && order.status != 'CANCELLED'
})
}
if (tab == 'history') {
return orders.filter((order) => {
return order.status == 'ACCEPTED' || order.status == 'COMPLETED' || order.status == 'CANCELLED'
})
}
return orders.filter((order) => {
return order.status != 'ACCEPTED' && order.status != 'COMPLETED' && order.status != 'CANCELLED'
})
}
export async function getOrderDetail(orderId: string): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}
export async function getDashboard(): Promise<UTSJSONObject> {
const orders = await listConsumerServiceOrders()
let pendingCount = 0
let todayCount = 0
let completedCount = 0
for (let i = 0; i < orders.length; i++) {
const order = orders[i]
if (order.status == 'ACCEPTED' || order.status == 'COMPLETED' || order.status == 'CANCELLED') {
completedCount += 1
} else {
pendingCount += 1
todayCount += 1
}
}
return {
pendingCount,
todayCount,
completedCount,
totalCount: orders.length
} as UTSJSONObject
}
export async function acceptOrder(orderId: string): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}
export async function departOrder(orderId: string, _location: any): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}
export async function arriveOrder(orderId: string, _location: any): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}
export async function checkinOrder(orderId: string, _payload: any): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}
export async function startService(orderId: string): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}
export async function finishOrder(orderId: string): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}
export async function saveServiceRecord(orderId: string, _payload: any): Promise<ServiceOrderType | null> {
return await getServiceOrderDetail(orderId)
}