|
|
// 云函数completeOrder
|
|
|
const cloud = require('wx-server-sdk')
|
|
|
|
|
|
// 初始化cloud
|
|
|
cloud.init({
|
|
|
env: 'cloud1-4gczmwok7cacf142' // 使用您的云环境ID
|
|
|
})
|
|
|
const db = cloud.database()
|
|
|
|
|
|
exports.main = async (event, context) => {
|
|
|
const wxContext = cloud.getWXContext()
|
|
|
const openid = wxContext.OPENID
|
|
|
|
|
|
// 获取请求参数
|
|
|
const { orderId, comment, rating } = event
|
|
|
|
|
|
if (!orderId) {
|
|
|
return {
|
|
|
success: false,
|
|
|
message: '参数错误:未提供订单ID'
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 使用事务处理
|
|
|
const transaction = await db.startTransaction()
|
|
|
|
|
|
try {
|
|
|
// 获取订单信息
|
|
|
const orderResult = await transaction.collection('orders').doc(orderId).get()
|
|
|
const order = orderResult.data
|
|
|
|
|
|
if (!order) {
|
|
|
await transaction.rollback()
|
|
|
return {
|
|
|
success: false,
|
|
|
message: '订单不存在'
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 验证操作权限(只有买家/接单方可以完成订单)
|
|
|
if (order.buyerOpenid !== openid) {
|
|
|
await transaction.rollback()
|
|
|
return {
|
|
|
success: false,
|
|
|
message: '无权操作此订单'
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 判断订单状态是否为进行中
|
|
|
if (order.status !== 'processing') {
|
|
|
await transaction.rollback()
|
|
|
return {
|
|
|
success: false,
|
|
|
message: '只有进行中的订单可以被完成'
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 更新订单状态
|
|
|
await transaction.collection('orders').doc(orderId).update({
|
|
|
data: {
|
|
|
status: 'completed',
|
|
|
comment: comment || '',
|
|
|
rating: rating || 5,
|
|
|
completeTime: db.serverDate(),
|
|
|
updateTime: db.serverDate()
|
|
|
}
|
|
|
})
|
|
|
|
|
|
// 更新任务或商品状态
|
|
|
let targetCollection = ''
|
|
|
if (order.type === 'secondhand') {
|
|
|
targetCollection = 'secondhand_goods'
|
|
|
}
|
|
|
|
|
|
if (targetCollection) {
|
|
|
await transaction.collection(targetCollection).doc(order.itemId).update({
|
|
|
data: {
|
|
|
status: 'completed',
|
|
|
updateTime: db.serverDate()
|
|
|
}
|
|
|
})
|
|
|
}
|
|
|
|
|
|
// 更新用户信息(增加完成数量)
|
|
|
if (order.type === 'secondhand') {
|
|
|
await transaction.collection('users').where({
|
|
|
openid: openid
|
|
|
}).update({
|
|
|
data: {
|
|
|
secondhandCount: db.command.inc(1)
|
|
|
}
|
|
|
})
|
|
|
}
|
|
|
|
|
|
// 提交事务
|
|
|
await transaction.commit()
|
|
|
|
|
|
return {
|
|
|
success: true,
|
|
|
message: '订单完成成功'
|
|
|
}
|
|
|
} catch (error) {
|
|
|
// 回滚事务
|
|
|
await transaction.rollback()
|
|
|
|
|
|
return {
|
|
|
success: false,
|
|
|
message: '订单完成失败',
|
|
|
error: error.message
|
|
|
}
|
|
|
}
|
|
|
}
|