feat(drone-dock): 新增独立套餐收款页并接入收款接口
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import Foundation
|
||||
|
||||
/// 张工的机巢套餐收款数据源;付款链接与收款记录不提供单笔支付状态查询。
|
||||
protocol DroneDockPaymentServing: Sendable {
|
||||
/// 获取当前景区可售套餐,无分页。
|
||||
@MainActor func projects(scenicID: Int) async throws -> [DroneDockProject]
|
||||
/// 获取指定套餐的付款链接;省略 price 时使用后端当前售价。
|
||||
@MainActor func payCode(scenicID: Int, projectID: Int, price: String?) async throws -> DroneDockPayCode
|
||||
/// 获取本人当前景区的收款记录,默认日期与每页数量由后端决定。
|
||||
@MainActor func receipts(scenicID: Int, projectID: Int?, page: Int) async throws -> DroneDockReceiptsResponse
|
||||
}
|
||||
|
||||
/// 机巢套餐、付款链接及真实收款记录接口,复用统一登录凭证和业务错误处理。
|
||||
@MainActor
|
||||
final class DroneDockPaymentAPI: DroneDockPaymentServing {
|
||||
private let client: APIClient
|
||||
private let prefix = "/api/yf-handset-app/photog/multi-plane"
|
||||
|
||||
/// 注入统一客户端,支持正式服务和隔离的网络测试。
|
||||
init(client: APIClient) { self.client = client }
|
||||
|
||||
/// 请求当前景区可售套餐;空数组表示无可售套餐。
|
||||
func projects(scenicID: Int) async throws -> [DroneDockProject] {
|
||||
try validateScenic(scenicID)
|
||||
let projects: [DroneDockProject] = try await client.send(APIRequest(
|
||||
method: .get, path: prefix + "/projects",
|
||||
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID))]
|
||||
))
|
||||
guard Set(projects.map(\.id)).count == projects.count else {
|
||||
throw APIError.decodeFailed("套餐 ID 重复")
|
||||
}
|
||||
return projects
|
||||
}
|
||||
|
||||
/// 由后端生成完整付款链接;客户端不自行拼接金额、备注或身份参数。
|
||||
func payCode(scenicID: Int, projectID: Int, price: String? = nil) async throws -> DroneDockPayCode {
|
||||
try validateScenic(scenicID)
|
||||
guard projectID > 0 else { throw APIError.networkFailed("请选择航拍套餐") }
|
||||
let normalized: String?
|
||||
if let price {
|
||||
guard let value = DroneDockPriceValidator.normalizedPrice(price) else {
|
||||
throw APIError.networkFailed(DroneDockPriceValidator.validationMessage(for: price)!)
|
||||
}
|
||||
normalized = value
|
||||
} else { normalized = nil }
|
||||
return try await client.send(APIRequest(
|
||||
method: .post, path: prefix + "/pay-code",
|
||||
body: PayCodeBody(scenicID: scenicID, projectID: projectID, price: normalized)
|
||||
))
|
||||
}
|
||||
|
||||
/// 按当前身份读取实际收款记录;不把查询结果解释成当前码已支付。
|
||||
func receipts(scenicID: Int, projectID: Int? = nil, page: Int = 1) async throws -> DroneDockReceiptsResponse {
|
||||
try validateScenic(scenicID)
|
||||
guard page > 0, projectID.map({ $0 > 0 }) ?? true else {
|
||||
throw APIError.networkFailed("收款记录查询参数无效")
|
||||
}
|
||||
var query = [URLQueryItem(name: "scenic_id", value: String(scenicID)),
|
||||
URLQueryItem(name: "page", value: String(page))]
|
||||
if let projectID { query.append(URLQueryItem(name: "project_id", value: String(projectID))) }
|
||||
return try await client.send(APIRequest(method: .get, path: prefix + "/receipts", queryItems: query))
|
||||
}
|
||||
|
||||
private func validateScenic(_ scenicID: Int) throws {
|
||||
guard scenicID > 0 else { throw APIError.networkFailed("请先选择景区") }
|
||||
}
|
||||
|
||||
/// 报价请求体;nil 价格通过 Encodable 省略,不发送空串或 null。
|
||||
private struct PayCodeBody: Encodable {
|
||||
let scenicID: Int
|
||||
let projectID: Int
|
||||
let price: String?
|
||||
|
||||
/// 业务接口请求字段。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case scenicID = "scenic_id", projectID = "project_id", price
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import Foundation
|
||||
|
||||
/// 张工提供的当前景区可售航拍套餐;价格与次数来自服务器配置。
|
||||
struct DroneDockProject: Decodable, Hashable, Sendable {
|
||||
/// 套餐稳定 ID。
|
||||
let id: Int
|
||||
/// 套餐名称。
|
||||
let name: String
|
||||
/// 当前默认售价,单位元。
|
||||
let price: Decimal
|
||||
/// 整个套餐共享的拍摄次数。
|
||||
let shootCount: Int
|
||||
|
||||
/// 套餐接口字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case id, name, price
|
||||
case shootCount = "shoot_count"
|
||||
}
|
||||
|
||||
/// 严格读取可售套餐,不为缺失价格或次数生成默认值。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
id = try container.paymentInteger(.id, minimum: 1)
|
||||
name = try container.decode(String.self, forKey: .name)
|
||||
price = try container.paymentMoney(.price)
|
||||
shootCount = try container.paymentInteger(.shootCount, minimum: 1)
|
||||
guard DroneDockPriceValidator.isValid(price) else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .price, in: container, debugDescription: "套餐价格超出报价范围")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 后端生成的可重复购买付款链接;不代表单笔交易或到账结果。
|
||||
struct DroneDockPayCode: Decodable, Equatable, Sendable {
|
||||
/// 报价所属套餐 ID。
|
||||
let projectID: Int
|
||||
/// 后端确认的套餐名称。
|
||||
let projectName: String
|
||||
/// 后端确认的成交报价,单位元。
|
||||
let price: Decimal
|
||||
/// 报价包含的拍摄次数。
|
||||
let shootCount: Int
|
||||
/// 收款归属的店铺工作人员 ID。
|
||||
let storeUserID: Int
|
||||
/// 收款归属的店铺 ID。
|
||||
let storeID: Int
|
||||
/// 用于绘制普通二维码的 HTTP(S) 付款链接。
|
||||
let payURL: String
|
||||
|
||||
/// 付款链接接口字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case price
|
||||
case projectID = "project_id", projectName = "project_name", shootCount = "shoot_count"
|
||||
case storeUserID = "store_user_id", storeID = "store_id", payURL = "pay_url"
|
||||
}
|
||||
|
||||
/// 验证身份、报价和链接格式;不接受缺失或不可扫码的付款地址。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
projectID = try container.paymentInteger(.projectID, minimum: 1)
|
||||
projectName = try container.decode(String.self, forKey: .projectName)
|
||||
price = try container.paymentMoney(.price)
|
||||
shootCount = try container.paymentInteger(.shootCount, minimum: 1)
|
||||
storeUserID = try container.paymentInteger(.storeUserID, minimum: 1)
|
||||
storeID = try container.paymentInteger(.storeID, minimum: 1)
|
||||
payURL = try container.decode(String.self, forKey: .payURL)
|
||||
guard DroneDockPriceValidator.isValid(price) else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .price, in: container, debugDescription: "付款报价超出范围")
|
||||
}
|
||||
guard payURL.rangeOfCharacter(from: .whitespacesAndNewlines.union(.controlCharacters)) == nil,
|
||||
let components = URLComponents(string: payURL),
|
||||
let scheme = components.scheme?.lowercased(), ["https", "http"].contains(scheme),
|
||||
let host = components.host, !host.isEmpty, components.url != nil,
|
||||
components.user == nil, components.password == nil else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .payURL, in: container, debugDescription: "付款链接必须是有效 HTTP(S) 地址")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 收款记录分页与筛选范围汇总,不能据此推断某次二维码的交易状态。
|
||||
struct DroneDockReceiptsResponse: Decodable, Equatable, Sendable {
|
||||
/// Laravel 格式的收款记录分页。
|
||||
let records: DroneDockReceiptPage
|
||||
/// 整个查询范围的收款汇总,与当前分页无关。
|
||||
let summary: DroneDockReceiptSummary
|
||||
}
|
||||
|
||||
/// 后端 records 分页对象;列表字段实际为 data。
|
||||
struct DroneDockReceiptPage: Decodable, Equatable, Sendable {
|
||||
/// 当前页,从 1 开始。
|
||||
let currentPage: Int
|
||||
/// 每页条数。
|
||||
let perPage: Int
|
||||
/// 整个查询范围的记录数量。
|
||||
let total: Int
|
||||
/// 最后一页页码。
|
||||
let lastPage: Int
|
||||
/// 当前页实际记录。
|
||||
let items: [DroneDockReceipt]
|
||||
|
||||
/// Laravel 分页字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case currentPage = "current_page", perPage = "per_page", total, lastPage = "last_page"
|
||||
case items = "data"
|
||||
}
|
||||
|
||||
/// 保留真实分页,不把缺失列表当成正常空记录。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
currentPage = try container.paymentInteger(.currentPage, minimum: 1)
|
||||
perPage = try container.paymentInteger(.perPage, minimum: 1)
|
||||
total = try container.paymentInteger(.total, minimum: 0)
|
||||
lastPage = try container.paymentInteger(.lastPage, minimum: 0)
|
||||
items = try container.decode([DroneDockReceipt].self, forKey: .items)
|
||||
guard Set(items.map(\.orderNumber)).count == items.count else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .items, in: container, debugDescription: "收款记录订单号重复")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 已付款、已完成或已退款的真实收款记录,现金与积分分别展示。
|
||||
struct DroneDockReceipt: Decodable, Hashable, Sendable {
|
||||
/// 真实订单号。
|
||||
let orderNumber: String
|
||||
/// 套餐 ID。
|
||||
let projectID: Int
|
||||
/// 购买时套餐名称。
|
||||
let projectName: String
|
||||
/// 后端订单状态原值。
|
||||
let orderStatus: Int
|
||||
/// 支付时间,Unix 秒。
|
||||
let payTime: TimeInterval
|
||||
/// 服务端脱敏后的付款人昵称。
|
||||
let payer: String
|
||||
/// 现金实收,单位元。
|
||||
let cashPaid: Decimal
|
||||
/// 成功现金退款,单位元。
|
||||
let cashRefund: Decimal
|
||||
/// 现金净收,单位元。
|
||||
let cashNet: Decimal
|
||||
/// 消费积分数量。
|
||||
let pointsPaid: Int
|
||||
/// 已退回积分数量。
|
||||
let pointsRefund: Int
|
||||
/// 净消费积分数量。
|
||||
let pointsNet: Int
|
||||
/// 积分抵扣金额,单位元。
|
||||
let pointAmount: Decimal
|
||||
|
||||
/// 收款记录接口字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderNumber = "order_number", projectID = "project_id", projectName = "project_name"
|
||||
case orderStatus = "order_status", payTime = "pay_time", payer
|
||||
case cashPaid = "cash_paid", cashRefund = "cash_refund", cashNet = "cash_net"
|
||||
case pointsPaid = "points_paid", pointsRefund = "points_refund", pointsNet = "points_net"
|
||||
case pointAmount = "point_amount"
|
||||
}
|
||||
|
||||
/// 解码实际支付与退款字段,零现金支付保留为真实零值。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
orderNumber = try container.decode(String.self, forKey: .orderNumber)
|
||||
guard !orderNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .orderNumber, in: container, debugDescription: "订单号不能为空")
|
||||
}
|
||||
projectID = try container.paymentInteger(.projectID, minimum: 1)
|
||||
projectName = try container.decode(String.self, forKey: .projectName)
|
||||
orderStatus = try container.paymentInteger(.orderStatus)
|
||||
payTime = TimeInterval(try container.paymentInteger(.payTime, minimum: 0))
|
||||
payer = try container.decode(String.self, forKey: .payer)
|
||||
cashPaid = try container.paymentMoney(.cashPaid)
|
||||
cashRefund = try container.paymentMoney(.cashRefund)
|
||||
cashNet = try container.paymentMoney(.cashNet)
|
||||
pointsPaid = try container.paymentInteger(.pointsPaid, minimum: 0)
|
||||
pointsRefund = try container.paymentInteger(.pointsRefund, minimum: 0)
|
||||
pointsNet = try container.paymentInteger(.pointsNet)
|
||||
pointAmount = try container.paymentMoney(.pointAmount)
|
||||
}
|
||||
}
|
||||
|
||||
/// 整个筛选区间的到账与退款汇总,不把现金、积分合并为一种支付金额。
|
||||
struct DroneDockReceiptSummary: Decodable, Equatable, Sendable {
|
||||
/// 收款记录总数量。
|
||||
let count: Int
|
||||
/// 现金实收总额。
|
||||
let cashPaid: Decimal
|
||||
/// 成功现金退款总额。
|
||||
let cashRefund: Decimal
|
||||
/// 现金净收总额。
|
||||
let cashNet: Decimal
|
||||
/// 消费积分总数。
|
||||
let pointsPaid: Int
|
||||
/// 退回积分总数。
|
||||
let pointsRefund: Int
|
||||
/// 净消费积分总数。
|
||||
let pointsNet: Int
|
||||
/// 积分抵扣总金额。
|
||||
let pointAmount: Decimal
|
||||
|
||||
/// 收款汇总接口字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case count
|
||||
case cashPaid = "cash_paid", cashRefund = "cash_refund", cashNet = "cash_net"
|
||||
case pointsPaid = "points_paid", pointsRefund = "points_refund", pointsNet = "points_net"
|
||||
case pointAmount = "point_amount"
|
||||
}
|
||||
|
||||
/// 严格读取汇总;金额缺失或 null 不以零替代。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
count = try container.paymentInteger(.count, minimum: 0)
|
||||
cashPaid = try container.paymentMoney(.cashPaid)
|
||||
cashRefund = try container.paymentMoney(.cashRefund)
|
||||
cashNet = try container.paymentMoney(.cashNet)
|
||||
pointsPaid = try container.paymentInteger(.pointsPaid, minimum: 0)
|
||||
pointsRefund = try container.paymentInteger(.pointsRefund, minimum: 0)
|
||||
pointsNet = try container.paymentInteger(.pointsNet)
|
||||
pointAmount = try container.paymentMoney(.pointAmount)
|
||||
}
|
||||
}
|
||||
|
||||
/// 套餐报价校验与规范化,使用十进制金额并遵循后端报价范围。
|
||||
enum DroneDockPriceValidator {
|
||||
/// 合法金额返回 nil,否则返回可展示的输入提示。
|
||||
static func validationMessage(for text: String) -> String? {
|
||||
normalizedPrice(text) == nil ? "请输入 0.01~99999.99 元的金额,最多保留两位小数" : nil
|
||||
}
|
||||
|
||||
/// 将合法输入转换为固定两位小数的元字符串;拒绝指数、符号及不完整小数。
|
||||
static func normalizedPrice(_ text: String) -> String? {
|
||||
let value = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard value.range(of: #"^[0-9]+(?:\.[0-9]{1,2})?$"#, options: .regularExpression) != nil,
|
||||
let amount = Decimal(string: value, locale: Locale(identifier: "en_US_POSIX")), isValid(amount) else { return nil }
|
||||
let string = NSDecimalNumber(decimal: amount).stringValue
|
||||
let parts = string.split(separator: ".", omittingEmptySubsequences: false)
|
||||
if parts.count == 1 { return string + ".00" }
|
||||
return string + String(repeating: "0", count: max(0, 2 - parts[1].count))
|
||||
}
|
||||
|
||||
/// 验证金额处于后端支持范围且不存在超过分的精度。
|
||||
static func isValid(_ amount: Decimal) -> Bool {
|
||||
guard !amount.isNaN, amount >= Decimal(string: "0.01")!, amount <= Decimal(string: "99999.99")! else { return false }
|
||||
var value = amount
|
||||
var rounded = Decimal()
|
||||
NSDecimalRound(&rounded, &value, 2, .plain)
|
||||
return amount == rounded
|
||||
}
|
||||
}
|
||||
|
||||
/// 机巢收款字段的局部解码规则,不改变其他业务的网络解码策略。
|
||||
private extension KeyedDecodingContainer {
|
||||
/// 兼容整数与整数字符串,拒绝小数、空值及越界数值。
|
||||
func paymentInteger(_ key: Key, minimum: Int? = nil) throws -> Int {
|
||||
let value: Int
|
||||
if let number = try? decode(Int.self, forKey: key) { value = number }
|
||||
else if let text = try? decode(String.self, forKey: key), let number = Int(text) { value = number }
|
||||
else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "需要整数或整数字符串") }
|
||||
if let minimum, value < minimum {
|
||||
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "整数低于允许范围")
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/// 兼容数字与金额字符串,拒绝非法文本和超过两位小数的金额。
|
||||
func paymentMoney(_ key: Key) throws -> Decimal {
|
||||
let value: Decimal
|
||||
if let text = try? decode(String.self, forKey: key) {
|
||||
guard text.range(of: #"^-?[0-9]+(?:\.[0-9]{1,2})?$"#, options: .regularExpression) != nil,
|
||||
let number = Decimal(string: text, locale: Locale(identifier: "en_US_POSIX")) else {
|
||||
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "需要最多两位小数的金额")
|
||||
}
|
||||
value = number
|
||||
} else { value = try decode(Decimal.self, forKey: key) }
|
||||
var source = value
|
||||
var rounded = Decimal()
|
||||
NSDecimalRound(&rounded, &source, 2, .plain)
|
||||
guard !value.isNaN, value == rounded else {
|
||||
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "金额精度或数值无效")
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import Foundation
|
||||
|
||||
/// 独立机巢套餐收款状态;不使用普通景区收款链接,也不模拟单笔支付成功。
|
||||
final class DroneDockPaymentViewModel {
|
||||
/// 当前页面所属账号、景区和门店。
|
||||
private(set) var context: DroneDockHomeContext
|
||||
/// 服务端当前可售套餐。
|
||||
private(set) var projects: [DroneDockProject] = []
|
||||
/// 当前已确认报价的付款链接;改价、换套餐或失败时立即清除。
|
||||
private(set) var payCode: DroneDockPayCode?
|
||||
/// 是否正在加载套餐列表。
|
||||
private(set) var isLoadingProjects = false
|
||||
/// 是否正在向后端生成付款链接。
|
||||
private(set) var isGenerating = false
|
||||
/// 套餐读取错误,与成功的空列表分开表达。
|
||||
private(set) var projectError: String?
|
||||
/// 报价生成错误,不携带可继续使用的旧二维码。
|
||||
private(set) var payCodeError: String?
|
||||
|
||||
private let service: any DroneDockPaymentServing
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private var scopeGeneration = 0
|
||||
private var projectGeneration = 0
|
||||
private var codeGeneration = 0
|
||||
private var pendingCode: PendingCode?
|
||||
|
||||
/// 相同在途报价用于拦截重复点击;不同套餐或金额允许替换前一次请求。
|
||||
private struct PendingCode: Equatable {
|
||||
let projectID: Int
|
||||
let price: String?
|
||||
}
|
||||
|
||||
/// 注入真实收款服务与最新会话;调用方在完成后主动刷新 UIKit 界面。
|
||||
init(context: DroneDockHomeContext, service: any DroneDockPaymentServing,
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.context = context
|
||||
self.service = service
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 加载可售套餐;切换登录、景区或门店时清除之前的套餐和付款链接。
|
||||
func loadProjects() async {
|
||||
let scope = scopeGeneration
|
||||
let requested = await currentContext()
|
||||
guard scope == scopeGeneration, !Task.isCancelled else { return }
|
||||
if !context.hasSameIdentity(as: requested) {
|
||||
invalidate()
|
||||
context = requested
|
||||
}
|
||||
guard !isLoadingProjects else { return }
|
||||
projectGeneration &+= 1
|
||||
let request = projectGeneration
|
||||
isLoadingProjects = true
|
||||
projectError = nil
|
||||
defer { if projectGeneration == request { isLoadingProjects = false } }
|
||||
guard requested.canLoad else {
|
||||
projects = []
|
||||
payCode = nil
|
||||
projectError = "请先登录并选择景区和门店"
|
||||
return
|
||||
}
|
||||
do {
|
||||
let result = try await service.projects(scenicID: requested.scenicID)
|
||||
guard await accepts(request, isCode: false, context: requested) else { return }
|
||||
guard Set(result.map(\.id)).count == result.count else {
|
||||
projects = []
|
||||
projectError = "接口返回的套餐重复,请重试"
|
||||
return
|
||||
}
|
||||
projects = result
|
||||
} catch {
|
||||
guard await accepts(request, isCode: false, context: requested) else { return }
|
||||
projects = []
|
||||
if error is CancellationError { return }
|
||||
projectError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 确认套餐或改价后重新生成;只接受所选套餐、当前门店及当前会话的响应。
|
||||
func generateCode(projectID: Int, price: String? = nil) async {
|
||||
let normalized = price.flatMap(DroneDockPriceValidator.normalizedPrice)
|
||||
let pending = PendingCode(projectID: projectID, price: normalized)
|
||||
if isGenerating, pendingCode == pending, price == nil || normalized != nil { return }
|
||||
codeGeneration &+= 1
|
||||
let request = codeGeneration
|
||||
payCode = nil
|
||||
payCodeError = nil
|
||||
pendingCode = pending
|
||||
isGenerating = true
|
||||
defer {
|
||||
if codeGeneration == request {
|
||||
isGenerating = false
|
||||
pendingCode = nil
|
||||
}
|
||||
}
|
||||
guard price == nil || normalized != nil else {
|
||||
payCodeError = DroneDockPriceValidator.validationMessage(for: price ?? "")
|
||||
return
|
||||
}
|
||||
let requested = await currentContext()
|
||||
guard codeGeneration == request, !Task.isCancelled else { return }
|
||||
guard context.hasSameIdentity(as: requested) else {
|
||||
rejectChangedContext(requested)
|
||||
return
|
||||
}
|
||||
guard requested.canLoad else {
|
||||
payCodeError = "请先登录并选择景区和门店"
|
||||
return
|
||||
}
|
||||
guard projectID > 0, projects.contains(where: { $0.id == projectID }) else {
|
||||
payCodeError = "请先选择当前可售的航拍套餐"
|
||||
return
|
||||
}
|
||||
do {
|
||||
let result = try await service.payCode(scenicID: requested.scenicID, projectID: projectID, price: normalized)
|
||||
guard await accepts(request, isCode: true, context: requested) else { return }
|
||||
guard result.projectID == projectID, result.storeID == requested.storeID else {
|
||||
payCodeError = "返回的套餐或收款门店与当前选择不一致,请重新生成"
|
||||
return
|
||||
}
|
||||
if let normalized, result.price != Decimal(string: normalized, locale: Locale(identifier: "en_US_POSIX")) {
|
||||
payCodeError = "返回的收款金额与本次报价不一致,请重新生成"
|
||||
return
|
||||
}
|
||||
payCode = result
|
||||
} catch {
|
||||
guard await accepts(request, isCode: true, context: requested) else { return }
|
||||
if error is CancellationError { return }
|
||||
payCodeError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 页面退出或会话失效时清除全部状态,并阻止任何在途请求回填旧二维码。
|
||||
func invalidate() {
|
||||
scopeGeneration &+= 1
|
||||
projectGeneration &+= 1
|
||||
codeGeneration &+= 1
|
||||
projects = []
|
||||
payCode = nil
|
||||
isLoadingProjects = false
|
||||
isGenerating = false
|
||||
projectError = nil
|
||||
payCodeError = nil
|
||||
pendingCode = nil
|
||||
}
|
||||
|
||||
private func accepts(_ request: Int, isCode: Bool, context requested: DroneDockHomeContext) async -> Bool {
|
||||
guard request == (isCode ? codeGeneration : projectGeneration), !Task.isCancelled else { return false }
|
||||
let latest = await currentContext()
|
||||
guard request == (isCode ? codeGeneration : projectGeneration), !Task.isCancelled else { return false }
|
||||
guard requested.hasSameIdentity(as: latest) else {
|
||||
rejectChangedContext(latest)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private func rejectChangedContext(_ latest: DroneDockHomeContext) {
|
||||
invalidate()
|
||||
context = latest
|
||||
projectError = "账号、景区或门店已变化,请重新加载套餐"
|
||||
payCodeError = "账号、景区或门店已变化,请重新选择套餐"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import Foundation
|
||||
|
||||
/// 套餐收款记录的分页状态,只展示当前账号与景区的真实收款数据。
|
||||
final class DroneDockReceiptsViewModel {
|
||||
/// 当前记录所属的账号、景区及门店范围。
|
||||
private(set) var context: DroneDockHomeContext
|
||||
/// 按后端顺序排列并以订单号去重的收款记录。
|
||||
private(set) var receipts: [DroneDockReceipt] = []
|
||||
/// 后端提供的完整查询范围汇总,不将已加载页自行相加。
|
||||
private(set) var summary: DroneDockReceiptSummary?
|
||||
/// 当前是否有有效的刷新或翻页请求。
|
||||
private(set) var isLoading = false
|
||||
/// 当前读取错误;翻页失败时仍保留已有记录。
|
||||
private(set) var errorMessage: String?
|
||||
/// 后端分页信息是否还有下一页。
|
||||
private(set) var hasMore = false
|
||||
|
||||
private let service: any DroneDockPaymentServing
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private let projectID: Int?
|
||||
private var currentPage = 0
|
||||
private var generation = 0
|
||||
|
||||
/// 注入只读收款服务和最新会话;可按当前选中的套餐过滤记录。
|
||||
init(context: DroneDockHomeContext, service: any DroneDockPaymentServing,
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext, projectID: Int? = nil) {
|
||||
self.context = context
|
||||
self.service = service
|
||||
self.currentContext = currentContext
|
||||
self.projectID = projectID
|
||||
}
|
||||
|
||||
/// 从第一页重新读取,新的刷新会使旧刷新和旧分页响应失效。
|
||||
func refresh() async {
|
||||
await request(page: 1, replacing: true)
|
||||
}
|
||||
|
||||
/// 读取下一页;失败后可以重试同一页,不清除已有成功结果。
|
||||
func loadMore() async {
|
||||
guard !isLoading, hasMore else { return }
|
||||
await request(page: currentPage + 1, replacing: false)
|
||||
}
|
||||
|
||||
/// 离开页面时清除数据,并阻止在途响应重新填充旧账号记录。
|
||||
func invalidate() {
|
||||
generation &+= 1
|
||||
clearRecords()
|
||||
isLoading = false
|
||||
errorMessage = nil
|
||||
}
|
||||
|
||||
private func request(page: Int, replacing: Bool) async {
|
||||
generation &+= 1
|
||||
let requestGeneration = generation
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
defer { if generation == requestGeneration { isLoading = false } }
|
||||
|
||||
let requestedContext = await currentContext()
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return }
|
||||
let changedIdentity = !context.hasSameIdentity(as: requestedContext)
|
||||
if changedIdentity { clearRecords() }
|
||||
context = requestedContext
|
||||
guard requestedContext.canLoad else {
|
||||
clearRecords()
|
||||
errorMessage = "请先登录并选择景区和门店"
|
||||
return
|
||||
}
|
||||
guard projectID.map({ $0 > 0 }) ?? true else {
|
||||
clearRecords()
|
||||
errorMessage = "套餐信息无效,请返回后重新选择"
|
||||
return
|
||||
}
|
||||
guard replacing || !changedIdentity else {
|
||||
errorMessage = "账号或景区已变化,请刷新收款记录"
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let response = try await service.receipts(scenicID: requestedContext.scenicID, projectID: projectID, page: page)
|
||||
guard await accepts(requestGeneration, context: requestedContext) else { return }
|
||||
guard response.records.currentPage == page else {
|
||||
if replacing { clearRecords() }
|
||||
errorMessage = "收款记录页码异常,请重试"
|
||||
return
|
||||
}
|
||||
receipts = merge(replacing ? [] : receipts, with: response.records.items)
|
||||
summary = response.summary
|
||||
currentPage = response.records.currentPage
|
||||
hasMore = currentPage < response.records.lastPage
|
||||
} catch {
|
||||
guard await accepts(requestGeneration, context: requestedContext) else { return }
|
||||
if replacing { clearRecords() }
|
||||
if error is CancellationError { return }
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func accepts(_ requestGeneration: Int, context requested: DroneDockHomeContext) async -> Bool {
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||
let latest = await currentContext()
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||
guard requested.hasSameIdentity(as: latest) else {
|
||||
generation &+= 1
|
||||
context = latest
|
||||
clearRecords()
|
||||
isLoading = false
|
||||
errorMessage = "账号或景区已变化,请刷新收款记录"
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private func clearRecords() {
|
||||
receipts = []
|
||||
summary = nil
|
||||
currentPage = 0
|
||||
hasMore = false
|
||||
}
|
||||
|
||||
/// 翻页可能再次返回前页订单;更新其值但维持首次出现的位置。
|
||||
private func merge(_ existing: [DroneDockReceipt], with incoming: [DroneDockReceipt]) -> [DroneDockReceipt] {
|
||||
var result = existing
|
||||
var positions: [String: Int] = [:]
|
||||
for (index, receipt) in result.enumerated() { positions[receipt.orderNumber] = index }
|
||||
for receipt in incoming {
|
||||
if let index = positions[receipt.orderNumber] {
|
||||
result[index] = receipt
|
||||
} else {
|
||||
positions[receipt.orderNumber] = result.count
|
||||
result.append(receipt)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user