完善登录逻辑和个人资料完善
This commit is contained in:
@@ -30,6 +30,10 @@ function nowText(): string {
|
||||
return new Date().toISOString().replace('T', ' ').substring(0, 19)
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function buildId(prefix: string): string {
|
||||
return prefix + '-' + String(Date.now()) + '-' + String(Math.floor(Math.random() * 100000)).padStart(5, '0')
|
||||
}
|
||||
@@ -290,7 +294,7 @@ function parseServiceOrder(item: any, logs: Array<ServiceOrderTimelineItemType>,
|
||||
}
|
||||
}
|
||||
|
||||
async function insertStatusLog(orderId: string, fromStatus: string, toStatus: ServiceOrderStatus, operatorId: string, operatorRole: string, remark: string): Promise<void> {
|
||||
async function insertLegacyStatusLog(orderId: string, fromStatus: string, toStatus: ServiceOrderStatus, operatorId: string, operatorRole: string, remark: string): Promise<void> {
|
||||
await supa.from('hss_service_order_status_logs').insert({
|
||||
id: buildId('slog'),
|
||||
order_id: orderId,
|
||||
@@ -303,110 +307,318 @@ async function insertStatusLog(orderId: string, fromStatus: string, toStatus: Se
|
||||
}).execute()
|
||||
}
|
||||
|
||||
export function buildAddressSnapshot(address: UserAddress, latitude: number, longitude: number): ServiceOrderAddressSnapshotType {
|
||||
async function insertWorkOrderEvent(taskId: string, fromStatus: string, toStatus: string, actorId: string, actorRole: string, action: string, remark: string): Promise<void> {
|
||||
await supa.from('hc_work_order_events').insert({
|
||||
id: buildId('hc-event'),
|
||||
task_id: taskId,
|
||||
from_status: fromStatus == '' ? null : fromStatus,
|
||||
to_status: toStatus,
|
||||
actor_id: actorId == '' ? null : actorId,
|
||||
actor_role: actorRole,
|
||||
action,
|
||||
remark,
|
||||
created_at: nowIso()
|
||||
}).execute()
|
||||
}
|
||||
|
||||
function readFirstString(source: any, keys: Array<string>): string {
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const value = readString(source, keys[i])
|
||||
if (value != '') {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function readFirstNumber(source: any, keys: Array<string>): number {
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const value = readNumber(source, keys[i])
|
||||
if (value != 0) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
function readJsonObjectField(source: any, keys: Array<string>): any {
|
||||
const plain = plainObject(source)
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const value = plain[keys[i]]
|
||||
if (value != null) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function mapCareTaskRowToLegacyOrderRow(item: any): any {
|
||||
const serviceSnapshotValue = readJsonObjectField(item, ['service_snapshot_json'])
|
||||
const addressSnapshotValue = readJsonObjectField(item, ['address_snapshot_json'])
|
||||
let derivedStatus = readString(item, 'status')
|
||||
if (readFirstString(item, ['accepted_by_family_at']) != '') {
|
||||
derivedStatus = 'ACCEPTED'
|
||||
} else if (readFirstString(item, ['acceptance_pending_at']) != '') {
|
||||
derivedStatus = 'ACCEPTANCE_PENDING'
|
||||
} else if (readString(item, 'service_started_at') != '') {
|
||||
derivedStatus = 'ORDER_IN_SERVICE'
|
||||
} else if (readFirstString(item, ['checked_in_at']) != '') {
|
||||
derivedStatus = 'ORDER_CHECKED_IN'
|
||||
} else if (readString(item, 'departed_at') != '') {
|
||||
derivedStatus = 'departed'
|
||||
} else if (readString(item, 'accepted_at') != '') {
|
||||
derivedStatus = 'ORDER_ACCEPTED'
|
||||
} else if (readFirstString(item, ['assigned_to']) != '') {
|
||||
derivedStatus = 'ORDER_ASSIGNED'
|
||||
}
|
||||
const serviceSnapshot = serviceSnapshotValue != null ? serviceSnapshotValue : {
|
||||
serviceId: readFirstString(item, ['service_catalog_id', 'service_id']),
|
||||
serviceName: readString(item, 'service_name'),
|
||||
category: readFirstString(item, ['service_category', 'category']),
|
||||
price: readFirstNumber(item, ['service_price', 'price']),
|
||||
durationText: readFirstString(item, ['service_duration_text', 'duration_text']),
|
||||
summary: readFirstString(item, ['service_summary', 'summary']),
|
||||
tags: [] as Array<string>,
|
||||
suitableFor: readFirstString(item, ['suitable_for'])
|
||||
}
|
||||
return {
|
||||
addressId: address.id,
|
||||
contactName: address.recipient_name,
|
||||
contactPhone: address.phone,
|
||||
province: address.province,
|
||||
city: address.city,
|
||||
district: address.district,
|
||||
detailAddress: address.detail_address,
|
||||
fullAddress: address.province + address.city + address.district + ' ' + address.detail_address,
|
||||
latitude,
|
||||
longitude,
|
||||
coordinateType: 'gcj02',
|
||||
remark: address.label ?? ''
|
||||
id: readString(item, 'id'),
|
||||
order_no: readFirstString(item, ['task_no', 'order_no']),
|
||||
user_id: readFirstString(item, ['user_id', 'requester_user_id']),
|
||||
service_id: readFirstString(item, ['service_catalog_id', 'service_id']),
|
||||
service_name: readString(item, 'service_name'),
|
||||
service_snapshot_json: serviceSnapshot,
|
||||
service_address_id: readFirstString(item, ['service_address_id', 'address_id']),
|
||||
address_snapshot_json: addressSnapshotValue != null ? addressSnapshotValue : JSON.parse('{}'),
|
||||
recipient_name: readFirstString(item, ['elder_name', 'recipient_name']),
|
||||
recipient_phone: readFirstString(item, ['elder_phone', 'recipient_phone']),
|
||||
contact_name: readString(item, 'contact_name'),
|
||||
contact_phone: readString(item, 'contact_phone'),
|
||||
appointment_time: readFirstString(item, ['scheduled_at', 'appointment_time']),
|
||||
remark: readString(item, 'remark'),
|
||||
status: derivedStatus,
|
||||
current_assignment_id: readFirstString(item, ['assignment_id', 'current_assignment_id']),
|
||||
current_staff_id: readFirstString(item, ['assigned_to', 'current_staff_id']),
|
||||
accepted_at: readString(item, 'accepted_at'),
|
||||
departed_at: readString(item, 'departed_at'),
|
||||
arrived_at: readFirstString(item, ['checked_in_at', 'arrived_at']),
|
||||
service_started_at: readString(item, 'service_started_at'),
|
||||
completed_at: readFirstString(item, ['service_completed_at', 'completed_at']),
|
||||
pending_acceptance_at: readFirstString(item, ['acceptance_pending_at', 'pending_acceptance_at']),
|
||||
accepted_by_user_at: readFirstString(item, ['accepted_by_family_at', 'accepted_by_user_at']),
|
||||
reviewed_at: readString(item, 'reviewed_at'),
|
||||
created_at: readString(item, 'created_at'),
|
||||
updated_at: readString(item, 'updated_at')
|
||||
}
|
||||
}
|
||||
|
||||
export async function createServiceOrder(params: CreateServiceOrderParams): Promise<ServiceOrderType | null> {
|
||||
function mapWorkOrderEventToLegacyLog(item: any): any {
|
||||
return {
|
||||
id: readString(item, 'id'),
|
||||
order_id: readFirstString(item, ['task_id', 'order_id']),
|
||||
from_status: readString(item, 'from_status'),
|
||||
to_status: readFirstString(item, ['to_status', 'status']),
|
||||
operator_id: readFirstString(item, ['actor_id', 'operator_id']),
|
||||
operator_role: readFirstString(item, ['actor_role', 'operator_role']),
|
||||
remark: readString(item, 'remark'),
|
||||
created_at: readString(item, 'created_at')
|
||||
}
|
||||
}
|
||||
|
||||
function mapCareReviewRecordToLegacyReview(item: any): any {
|
||||
return {
|
||||
id: readString(item, 'id'),
|
||||
order_id: readFirstString(item, ['task_id', 'order_id']),
|
||||
user_id: readFirstString(item, ['created_by', 'user_id']),
|
||||
rating: readFirstNumber(item, ['rating']),
|
||||
tags_json: readJsonObjectField(item, ['tags_json']) != null ? readJsonObjectField(item, ['tags_json']) : [] as Array<string>,
|
||||
content: readFirstString(item, ['content', 'summary', 'remark']),
|
||||
created_at: readString(item, 'created_at')
|
||||
}
|
||||
}
|
||||
|
||||
function buildLegacyExecutionRecord(taskId: string, records: Array<any>): ServiceExecutionRecordType | null {
|
||||
if (records.length == 0) {
|
||||
return null
|
||||
}
|
||||
let checkinRecord: any = null
|
||||
let serviceRecord: any = null
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
const recordType = readFirstString(records[i], ['record_type', 'care_record_type'])
|
||||
if (recordType == 'review') {
|
||||
continue
|
||||
}
|
||||
if (recordType == 'checkin') {
|
||||
checkinRecord = records[i]
|
||||
continue
|
||||
}
|
||||
if (serviceRecord == null) {
|
||||
serviceRecord = records[i]
|
||||
}
|
||||
}
|
||||
const target = serviceRecord != null ? serviceRecord : (checkinRecord != null ? checkinRecord : records[0])
|
||||
return parseExecutionRecord({
|
||||
id: readString(target, 'id'),
|
||||
order_id: taskId,
|
||||
assignment_id: readFirstString(target, ['assignment_id']),
|
||||
checkin_time: checkinRecord != null ? readFirstString(checkinRecord, ['checked_in_at', 'checkin_time', 'started_at']) : readFirstString(target, ['checked_in_at', 'checkin_time']),
|
||||
checkin_latitude: checkinRecord != null ? readFirstNumber(checkinRecord, ['latitude', 'checkin_latitude']) : readFirstNumber(target, ['latitude', 'checkin_latitude']),
|
||||
checkin_longitude: checkinRecord != null ? readFirstNumber(checkinRecord, ['longitude', 'checkin_longitude']) : readFirstNumber(target, ['longitude', 'checkin_longitude']),
|
||||
checkin_address: checkinRecord != null ? readFirstString(checkinRecord, ['location_text', 'checkin_address', 'remark']) : readFirstString(target, ['location_text', 'checkin_address']),
|
||||
service_started_at: readFirstString(target, ['started_at', 'service_started_at']),
|
||||
service_finished_at: readFirstString(target, ['finished_at', 'service_finished_at']),
|
||||
actual_duration_minutes: readFirstNumber(target, ['duration_minutes', 'actual_duration_minutes']),
|
||||
service_items_json: readJsonObjectField(target, ['service_items_json']) != null ? readJsonObjectField(target, ['service_items_json']) : [] as Array<any>,
|
||||
summary: readFirstString(target, ['summary', 'content']),
|
||||
remark: readString(target, 'remark'),
|
||||
track_points_json: readJsonObjectField(target, ['track_points_json']) != null ? readJsonObjectField(target, ['track_points_json']) : [] as Array<any>,
|
||||
created_at: readString(target, 'created_at'),
|
||||
updated_at: readString(target, 'updated_at')
|
||||
})
|
||||
}
|
||||
|
||||
async function getCareTaskDetail(taskId: string): Promise<ServiceOrderType | 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
|
||||
}
|
||||
const taskRows = taskResponse.data as Array<any>
|
||||
if (taskRows.length == 0) {
|
||||
return null
|
||||
}
|
||||
const eventsResponse = await supa.from('hc_work_order_events').select('*').eq('task_id', taskId).order('created_at', { ascending: false }).execute()
|
||||
const recordsResponse = await supa.from('ec_care_records').select('*').eq('task_id', taskId).order('created_at', { ascending: false }).execute()
|
||||
const evidenceResponse = await supa.from('hc_evidence_files').select('*').eq('task_id', taskId).order('created_at', { ascending: false }).execute()
|
||||
const logs = [] as Array<ServiceOrderTimelineItemType>
|
||||
if (eventsResponse.data != null) {
|
||||
const rawEvents = eventsResponse.data as Array<any>
|
||||
for (let i = 0; i < rawEvents.length; i++) {
|
||||
logs.push(parseTimeline(mapWorkOrderEventToLegacyLog(rawEvents[i])))
|
||||
}
|
||||
}
|
||||
let review: ServiceReviewType | null = null
|
||||
const recordRows = recordsResponse.data != null ? recordsResponse.data as Array<any> : [] as Array<any>
|
||||
for (let i = 0; i < recordRows.length; i++) {
|
||||
const recordType = readFirstString(recordRows[i], ['record_type', 'care_record_type'])
|
||||
if (recordType == 'review') {
|
||||
review = parseReview(mapCareReviewRecordToLegacyReview(recordRows[i]))
|
||||
break
|
||||
}
|
||||
}
|
||||
const parsed = parseServiceOrder(mapCareTaskRowToLegacyOrderRow(taskRows[0]), logs, review)
|
||||
parsed.executionRecord = buildLegacyExecutionRecord(taskId, recordRows)
|
||||
if (evidenceResponse.data != null) {
|
||||
const rawEvidence = evidenceResponse.data as Array<any>
|
||||
const evidenceFiles = [] as Array<ServiceEvidenceFileType>
|
||||
for (let i = 0; i < rawEvidence.length; i++) {
|
||||
evidenceFiles.push(parseEvidenceFile({
|
||||
id: readString(rawEvidence[i], 'id'),
|
||||
order_id: taskId,
|
||||
execution_record_id: readFirstString(rawEvidence[i], ['care_record_id', 'execution_record_id']),
|
||||
phase: readString(rawEvidence[i], 'phase'),
|
||||
file_type: readString(rawEvidence[i], 'file_type'),
|
||||
storage_path: readString(rawEvidence[i], 'storage_path'),
|
||||
file_url: readString(rawEvidence[i], 'file_url'),
|
||||
latitude: readFirstNumber(rawEvidence[i], ['latitude']),
|
||||
longitude: readFirstNumber(rawEvidence[i], ['longitude']),
|
||||
captured_at: readString(rawEvidence[i], 'captured_at'),
|
||||
created_at: readString(rawEvidence[i], 'created_at')
|
||||
}))
|
||||
}
|
||||
parsed.evidenceFiles = evidenceFiles
|
||||
}
|
||||
if (parsed.currentStaffId != '') {
|
||||
const staffResponse = await supa.from('ml_delivery_staff').select('nickname, phone').eq('uid', parsed.currentStaffId).limit(1).execute()
|
||||
if (staffResponse.data != null) {
|
||||
const rawStaffList = staffResponse.data as Array<any>
|
||||
if (rawStaffList.length > 0) {
|
||||
parsed.staffName = readString(rawStaffList[0], 'nickname')
|
||||
parsed.staffPhone = readString(rawStaffList[0], 'phone')
|
||||
}
|
||||
}
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
async function tryCreateCareTask(params: CreateServiceOrderParams): Promise<ServiceOrderType | null> {
|
||||
const userId = getCurrentUserId()
|
||||
if (userId == '') {
|
||||
return null
|
||||
}
|
||||
const orderId = buildId('so')
|
||||
const orderNo = buildOrderNo()
|
||||
const now = new Date().toISOString()
|
||||
const requestId = buildId('sr')
|
||||
const taskId = buildId('ct')
|
||||
const taskNo = buildOrderNo()
|
||||
const createdAt = nowIso()
|
||||
const appointmentTime = normalizeAppointmentTime(params.appointmentTime)
|
||||
const response = await supa.from('hss_service_orders').insert({
|
||||
id: orderId,
|
||||
order_no: orderNo,
|
||||
const requestResponse = await supa.from('ec_service_requests').insert({
|
||||
id: requestId,
|
||||
user_id: userId,
|
||||
service_id: params.service.id,
|
||||
service_catalog_id: params.service.id,
|
||||
service_name: params.service.name,
|
||||
service_snapshot_json: params.service as any,
|
||||
service_address_id: normalizeUuidOrNull(params.address.addressId),
|
||||
address_snapshot_json: params.address as any,
|
||||
recipient_name: params.recipientName,
|
||||
recipient_phone: params.recipientPhone,
|
||||
service_category: params.service.category,
|
||||
elder_name: params.recipientName,
|
||||
elder_phone: params.recipientPhone,
|
||||
contact_name: params.contactName,
|
||||
contact_phone: params.contactPhone,
|
||||
appointment_time: appointmentTime,
|
||||
address_snapshot_json: params.address as any,
|
||||
scheduled_at: appointmentTime,
|
||||
remark: params.remark,
|
||||
status: 'created',
|
||||
created_at: now,
|
||||
updated_at: now
|
||||
status: 'ORDER_CREATED',
|
||||
created_at: createdAt,
|
||||
updated_at: createdAt
|
||||
}).execute()
|
||||
if (response.error != null) {
|
||||
console.error('createServiceOrder failed', response.error)
|
||||
if (requestResponse.error != null) {
|
||||
return null
|
||||
}
|
||||
await insertStatusLog(orderId, '', 'created', userId, 'consumer', '创建服务订单')
|
||||
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()
|
||||
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, station_id, nickname, phone, status, deleted_at')
|
||||
.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 any[]
|
||||
const rawStaffList = staffResponse.data as Array<any>
|
||||
if (rawStaffList.length > 0) {
|
||||
const staffObj = plainObject(rawStaffList[0])
|
||||
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'),
|
||||
status: 'assigned',
|
||||
assigned_at: now,
|
||||
created_at: now,
|
||||
updated_at: now
|
||||
}).execute()
|
||||
await supa.from('hss_service_orders').update({
|
||||
status: 'assigned',
|
||||
current_assignment_id: assignmentId,
|
||||
current_staff_id: readString(staffObj, 'id'),
|
||||
updated_at: now
|
||||
}).eq('id', orderId).execute()
|
||||
await insertStatusLog(orderId, 'created', 'assigned', userId, 'system', '系统已自动派单')
|
||||
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', '系统已自动派单')
|
||||
}
|
||||
}
|
||||
}
|
||||
return await getServiceOrderDetail(orderId)
|
||||
return await getCareTaskDetail(taskId)
|
||||
}
|
||||
|
||||
export async function listConsumerServiceOrders(): Promise<Array<ServiceOrderType>> {
|
||||
const userId = getCurrentUserId()
|
||||
if (userId == '') {
|
||||
return [] as Array<ServiceOrderType>
|
||||
}
|
||||
const response = await supa.from('hss_service_orders').select('*').eq('user_id', userId).order('created_at', { ascending: false }).execute()
|
||||
if (response.error != null || response.data == null) {
|
||||
return [] as Array<ServiceOrderType>
|
||||
}
|
||||
const list = response.data as any[]
|
||||
const result = [] as Array<ServiceOrderType>
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const parsed = await getServiceOrderDetail(JSON.parse(JSON.stringify(list[i]))['id'] as string)
|
||||
if (parsed != null) {
|
||||
result.push(parsed)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function getServiceOrderDetail(orderId: string): Promise<ServiceOrderType | null> {
|
||||
async function getLegacyServiceOrderDetail(orderId: string): Promise<ServiceOrderType | null> {
|
||||
const orderResponse = await supa.from('hss_service_orders').select('*').eq('id', orderId).limit(1).execute()
|
||||
if (orderResponse.error != null || orderResponse.data == null) {
|
||||
return null
|
||||
@@ -454,19 +666,173 @@ export async function getServiceOrderDetail(orderId: string): Promise<ServiceOrd
|
||||
const rawStaffList = staffResponse.data as any[]
|
||||
if (rawStaffList.length > 0) {
|
||||
const staffObj = plainObject(rawStaffList[0])
|
||||
parsed.staffName = readString(staffObj, 'nickname')
|
||||
parsed.staffPhone = readString(staffObj, 'phone')
|
||||
parsed.staffName = readString(staffObj, 'nickname')
|
||||
parsed.staffPhone = readString(staffObj, 'phone')
|
||||
}
|
||||
}
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function buildAddressSnapshot(address: UserAddress, latitude: number, longitude: number): ServiceOrderAddressSnapshotType {
|
||||
return {
|
||||
addressId: address.id,
|
||||
contactName: address.recipient_name,
|
||||
contactPhone: address.phone,
|
||||
province: address.province,
|
||||
city: address.city,
|
||||
district: address.district,
|
||||
detailAddress: address.detail_address,
|
||||
fullAddress: address.province + address.city + address.district + ' ' + address.detail_address,
|
||||
latitude,
|
||||
longitude,
|
||||
coordinateType: 'gcj02',
|
||||
remark: address.label ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
export async function createServiceOrder(params: CreateServiceOrderParams): Promise<ServiceOrderType | null> {
|
||||
const newTask = await tryCreateCareTask(params)
|
||||
if (newTask != null) {
|
||||
return newTask
|
||||
}
|
||||
const userId = getCurrentUserId()
|
||||
if (userId == '') {
|
||||
return null
|
||||
}
|
||||
const orderId = buildId('so')
|
||||
const orderNo = buildOrderNo()
|
||||
const now = new Date().toISOString()
|
||||
const appointmentTime = normalizeAppointmentTime(params.appointmentTime)
|
||||
const response = await supa.from('hss_service_orders').insert({
|
||||
id: orderId,
|
||||
order_no: orderNo,
|
||||
user_id: userId,
|
||||
service_id: params.service.id,
|
||||
service_name: params.service.name,
|
||||
service_snapshot_json: params.service as any,
|
||||
service_address_id: normalizeUuidOrNull(params.address.addressId),
|
||||
address_snapshot_json: params.address as any,
|
||||
recipient_name: params.recipientName,
|
||||
recipient_phone: params.recipientPhone,
|
||||
contact_name: params.contactName,
|
||||
contact_phone: params.contactPhone,
|
||||
appointment_time: appointmentTime,
|
||||
remark: params.remark,
|
||||
status: 'created',
|
||||
created_at: now,
|
||||
updated_at: now
|
||||
}).execute()
|
||||
if (response.error != null) {
|
||||
console.error('createServiceOrder failed', response.error)
|
||||
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 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'),
|
||||
status: 'assigned',
|
||||
assigned_at: now,
|
||||
created_at: now,
|
||||
updated_at: now
|
||||
}).execute()
|
||||
await supa.from('hss_service_orders').update({
|
||||
status: 'assigned',
|
||||
current_assignment_id: assignmentId,
|
||||
current_staff_id: readString(staffObj, 'id'),
|
||||
updated_at: now
|
||||
}).eq('id', orderId).execute()
|
||||
await insertLegacyStatusLog(orderId, 'created', 'assigned', userId, 'system', '系统已自动派单')
|
||||
}
|
||||
}
|
||||
return await getLegacyServiceOrderDetail(orderId)
|
||||
}
|
||||
|
||||
export async function listConsumerServiceOrders(): Promise<Array<ServiceOrderType>> {
|
||||
const userId = getCurrentUserId()
|
||||
if (userId == '') {
|
||||
return [] as Array<ServiceOrderType>
|
||||
}
|
||||
const careTaskResponse = await supa.from('ec_care_tasks').select('*').eq('user_id', userId).order('created_at', { ascending: false }).execute()
|
||||
if (careTaskResponse.error == null && careTaskResponse.data != null) {
|
||||
const rawTasks = careTaskResponse.data as Array<any>
|
||||
const taskResult = [] as Array<ServiceOrderType>
|
||||
for (let i = 0; i < rawTasks.length; i++) {
|
||||
const parsed = await getCareTaskDetail(readString(rawTasks[i], 'id'))
|
||||
if (parsed != null) {
|
||||
taskResult.push(parsed)
|
||||
}
|
||||
}
|
||||
return taskResult
|
||||
}
|
||||
const response = await supa.from('hss_service_orders').select('*').eq('user_id', userId).order('created_at', { ascending: false }).execute()
|
||||
if (response.error != null || response.data == null) {
|
||||
return [] as Array<ServiceOrderType>
|
||||
}
|
||||
const list = response.data as any[]
|
||||
const result = [] as Array<ServiceOrderType>
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const parsed = await getLegacyServiceOrderDetail(JSON.parse(JSON.stringify(list[i]))['id'] as string)
|
||||
if (parsed != null) {
|
||||
result.push(parsed)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function getServiceOrderDetail(orderId: string): Promise<ServiceOrderType | null> {
|
||||
const careTask = await getCareTaskDetail(orderId)
|
||||
if (careTask != null) {
|
||||
return careTask
|
||||
}
|
||||
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)
|
||||
if (careTask != null) {
|
||||
const acceptedAt = nowIso()
|
||||
const updateResponse = await supa.from('ec_care_tasks').update({
|
||||
status: 'ACCEPTED',
|
||||
accepted_by_family_at: acceptedAt,
|
||||
updated_at: acceptedAt
|
||||
}).eq('id', orderId).execute()
|
||||
if (updateResponse.error == null) {
|
||||
await insertWorkOrderEvent(orderId, 'ACCEPTANCE_PENDING', 'ACCEPTED', userId, 'consumer', 'accept_task', '用户确认验收')
|
||||
if (rating > 0 || content != '' || tags.length > 0) {
|
||||
await supa.from('ec_care_records').insert({
|
||||
id: buildId('care-review'),
|
||||
task_id: orderId,
|
||||
record_type: 'review',
|
||||
created_by: userId,
|
||||
rating,
|
||||
tags_json: tags as any,
|
||||
content,
|
||||
created_at: acceptedAt,
|
||||
updated_at: acceptedAt
|
||||
}).execute()
|
||||
await insertWorkOrderEvent(orderId, 'ACCEPTED', 'ACCEPTED', userId, 'consumer', 'submit_review', '用户提交评价')
|
||||
}
|
||||
return await getCareTaskDetail(orderId)
|
||||
}
|
||||
}
|
||||
const current = await getServiceOrderDetail(orderId)
|
||||
if (current == null) {
|
||||
return null
|
||||
@@ -480,7 +846,7 @@ export async function confirmServiceOrder(orderId: string, rating: number, conte
|
||||
if (updateResponse.error != null) {
|
||||
return null
|
||||
}
|
||||
await insertStatusLog(orderId, current.status, 'accepted_by_user', userId, 'consumer', '用户确认验收')
|
||||
await insertLegacyStatusLog(orderId, current.status, 'accepted_by_user', userId, 'consumer', '用户确认验收')
|
||||
await supa.from('hss_service_reviews').insert({
|
||||
id: buildId('srv'),
|
||||
order_id: orderId,
|
||||
@@ -495,8 +861,8 @@ export async function confirmServiceOrder(orderId: string, rating: number, conte
|
||||
reviewed_at: acceptedAt,
|
||||
updated_at: acceptedAt
|
||||
}).eq('id', orderId).execute()
|
||||
await insertStatusLog(orderId, 'accepted_by_user', 'reviewed', userId, 'consumer', '用户提交评价')
|
||||
return await getServiceOrderDetail(orderId)
|
||||
await insertLegacyStatusLog(orderId, 'accepted_by_user', 'reviewed', userId, 'consumer', '用户提交评价')
|
||||
return await getLegacyServiceOrderDetail(orderId)
|
||||
}
|
||||
|
||||
export async function rejectServiceOrderAcceptance(orderId: string, content: string): Promise<ServiceOrderType | null> {
|
||||
@@ -504,6 +870,33 @@ export async function rejectServiceOrderAcceptance(orderId: string, content: str
|
||||
if (userId == '') {
|
||||
return null
|
||||
}
|
||||
const careTask = await getCareTaskDetail(orderId)
|
||||
if (careTask != null) {
|
||||
const rejectedAt = nowIso()
|
||||
const updateResponse = await supa.from('ec_care_tasks').update({
|
||||
status: 'ACCEPTANCE_REJECTED',
|
||||
updated_at: rejectedAt
|
||||
}).eq('id', orderId).execute()
|
||||
if (updateResponse.error == null) {
|
||||
await supa.from('hc_work_order_exceptions').insert({
|
||||
id: buildId('hc-ex'),
|
||||
task_id: orderId,
|
||||
exception_type: 'acceptance_rejected',
|
||||
description: content == '' ? '用户退回整改' : content,
|
||||
occurred_at: rejectedAt,
|
||||
location_text: '',
|
||||
images_json: [] as Array<string>,
|
||||
need_platform_intervention: false,
|
||||
request_cancel_order: false,
|
||||
request_reschedule: false,
|
||||
created_by: userId,
|
||||
created_at: rejectedAt,
|
||||
updated_at: rejectedAt
|
||||
}).execute()
|
||||
await insertWorkOrderEvent(orderId, 'ACCEPTANCE_PENDING', 'ACCEPTANCE_REJECTED', userId, 'consumer', 'reject_acceptance', content == '' ? '用户退回整改' : content)
|
||||
return await getCareTaskDetail(orderId)
|
||||
}
|
||||
}
|
||||
const current = await getServiceOrderDetail(orderId)
|
||||
if (current == null) {
|
||||
return null
|
||||
@@ -515,10 +908,81 @@ export async function rejectServiceOrderAcceptance(orderId: string, content: str
|
||||
if (updateResponse.error != null) {
|
||||
return null
|
||||
}
|
||||
await insertStatusLog(orderId, current.status, 'exception', userId, 'consumer', content == '' ? '用户退回整改' : content)
|
||||
return await getServiceOrderDetail(orderId)
|
||||
await insertLegacyStatusLog(orderId, current.status, 'exception', userId, 'consumer', content == '' ? '用户退回整改' : content)
|
||||
return await getLegacyServiceOrderDetail(orderId)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user