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
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import UIKit
|
||||
final class DroneDockHomeViewController: BaseViewController {
|
||||
/// 与演示数据源隔离的首页状态。
|
||||
let viewModel: DroneDockHomeViewModel
|
||||
private let paymentControllerFactory: (() -> UIViewController)?
|
||||
private var refreshTask: Task<Void, Never>?
|
||||
private var isRefreshing = false
|
||||
private var devicePage = 0
|
||||
@@ -27,8 +28,9 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
}
|
||||
|
||||
/// 注入可测试的数据源,不加载演示数据。
|
||||
init(viewModel: DroneDockHomeViewModel) {
|
||||
init(viewModel: DroneDockHomeViewModel, paymentControllerFactory: (() -> UIViewController)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.paymentControllerFactory = paymentControllerFactory
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
@@ -232,7 +234,10 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
showAlert(title: feature, message: "该功能暂未开放")
|
||||
}
|
||||
|
||||
@objc private func receiptTapped() { showUnavailable("套餐收款") }
|
||||
@objc private func receiptTapped() {
|
||||
let controller = paymentControllerFactory?() ?? DroneDockPaymentViewController()
|
||||
navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
@objc private func refreshTriggered() { refreshHome() }
|
||||
|
||||
#if DEBUG
|
||||
|
||||
@@ -0,0 +1,587 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 独立机巢套餐收款页,使用套餐付款链接并通过收款记录核对到账。
|
||||
final class DroneDockPaymentViewController: BaseViewController {
|
||||
/// 当前账号范围内的套餐与付款码状态。
|
||||
let viewModel: DroneDockPaymentViewModel
|
||||
private let service: any DroneDockPaymentServing
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private var requestTask: Task<Void, Never>?
|
||||
private var hasLoaded = false
|
||||
private var isLoadingProjectRequest = false
|
||||
private var isUpdatingCode = false
|
||||
private var requestedProjectID: Int?
|
||||
private var requestedPrice: String?
|
||||
private var renderedURL: String?
|
||||
private var amountDialog: PaymentSetAmountDialogView?
|
||||
private var amountDraft = ""
|
||||
private let scrollView = UIScrollView()
|
||||
private let content = UIStackView()
|
||||
private let scenicLabel = DroneDockStyle.label(size: 18, weight: .semibold)
|
||||
private let projectButton = UIButton(type: .system)
|
||||
private let projectNameLabel = DroneDockStyle.label("请选择", size: 14, weight: .medium, color: DroneDockStyle.primary)
|
||||
private let projectCountLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let amountLabel = DroneDockStyle.label(size: 26, weight: .semibold)
|
||||
private let qrImageView = UIImageView()
|
||||
private let qrContainer = UIView()
|
||||
private let placeholder = UIStackView()
|
||||
private let placeholderIcon = UIImageView(image: UIImage(systemName: "qrcode"))
|
||||
private let placeholderTitle = DroneDockStyle.label(size: 15, weight: .medium)
|
||||
private let placeholderDetail = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let retryButton = UIButton(type: .system)
|
||||
private let retryProjectsButton = UIButton(type: .system)
|
||||
private let spinner = UIActivityIndicatorView(style: .medium)
|
||||
private let paymentHint = DroneDockStyle.label("请游客扫码购买,到账后可在收款记录中核对", size: 11, color: DroneDockStyle.secondary)
|
||||
private let setAmountButton = UIButton(type: .system)
|
||||
private let saveButton = UIButton(type: .system)
|
||||
private let checkReceiptsButton = UIButton(type: .system)
|
||||
private let recordsButton = UIButton(type: .system)
|
||||
private let staffValue = DroneDockStyle.label(size: 13)
|
||||
private let scenicValue = DroneDockStyle.label(size: 13)
|
||||
private let voiceSwitch = UISwitch()
|
||||
|
||||
/// 使用当前会话和统一网络客户端进入真实套餐收款。
|
||||
convenience init() {
|
||||
let service = DroneDockPaymentAPI(client: NetworkServices.shared.apiClient)
|
||||
self.init(viewModel: DroneDockPaymentViewModel(context: Self.currentPaymentContext(), service: service,
|
||||
currentContext: { Self.currentPaymentContext() }),
|
||||
service: service, currentContext: { Self.currentPaymentContext() })
|
||||
}
|
||||
|
||||
/// 注入服务和身份来源,测试可完全隔离真实账户及网络。
|
||||
init(viewModel: DroneDockPaymentViewModel, service: any DroneDockPaymentServing,
|
||||
currentContext: (@MainActor @Sendable () -> DroneDockHomeContext)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.service = service
|
||||
let context = viewModel.context
|
||||
self.currentContext = currentContext ?? { context }
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit { requestTask?.cancel() }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "收款详情"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = DroneDockStyle.background
|
||||
scrollView.alwaysBounceVertical = true
|
||||
content.axis = .vertical
|
||||
content.spacing = 14
|
||||
view.addSubview(scrollView)
|
||||
scrollView.addSubview(content)
|
||||
content.addArrangedSubview(makePaymentCard())
|
||||
content.addArrangedSubview(makeInformationCard())
|
||||
configureButton(recordsButton, title: "收款记录", identifier: "drone.payment.records", action: #selector(recordsTapped))
|
||||
recordsButton.contentHorizontalAlignment = .leading
|
||||
var recordConfig = UIButton.Configuration.plain()
|
||||
recordConfig.title = "收款记录"
|
||||
recordConfig.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16)
|
||||
recordsButton.configuration = recordConfig
|
||||
recordsButton.tintColor = DroneDockStyle.text
|
||||
let recordsChevron = UIImageView(image: UIImage(systemName: "chevron.right"))
|
||||
recordsChevron.tintColor = DroneDockStyle.secondary
|
||||
recordsChevron.contentMode = .scaleAspectFit
|
||||
recordsButton.addSubview(recordsChevron)
|
||||
recordsChevron.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview().inset(16)
|
||||
make.centerY.equalToSuperview()
|
||||
make.width.equalTo(12)
|
||||
make.height.equalTo(16)
|
||||
}
|
||||
DroneDockStyle.applyCard(to: recordsButton)
|
||||
content.addArrangedSubview(recordsButton)
|
||||
let voice = UIStackView(arrangedSubviews: [DroneDockStyle.label("收款到账语音提醒", size: 14), UIView(), voiceSwitch])
|
||||
voice.alignment = .center
|
||||
voiceSwitch.onTintColor = DroneDockStyle.primary
|
||||
voiceSwitch.isOn = AppStore.shared.payment.isOpenReceiveVoice
|
||||
voiceSwitch.addTarget(self, action: #selector(voiceChanged), for: .valueChanged)
|
||||
content.addArrangedSubview(card(voice, insets: 16))
|
||||
let offline = UIStackView()
|
||||
offline.axis = .vertical
|
||||
offline.spacing = 12
|
||||
offline.addArrangedSubview(DroneDockStyle.label("线下收款", size: 16, weight: .semibold))
|
||||
let register = UIButton(type: .system)
|
||||
register.setTitle("去登记 ›", for: .normal)
|
||||
register.addTarget(self, action: #selector(offlineTapped), for: .touchUpInside)
|
||||
let offlineRow = UIStackView(arrangedSubviews: [DroneDockStyle.label("线下收款登记", size: 14), UIView(), register])
|
||||
offlineRow.alignment = .center
|
||||
offline.addArrangedSubview(offlineRow)
|
||||
content.addArrangedSubview(card(offline, insets: 16))
|
||||
applyState()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
scrollView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
|
||||
content.snp.makeConstraints { make in
|
||||
make.edges.equalTo(scrollView.contentLayoutGuide).inset(16)
|
||||
make.width.equalTo(scrollView.frameLayoutGuide).offset(-32)
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
if !hasLoaded || !viewModel.context.hasSameIdentity(as: currentContext()) {
|
||||
requestedProjectID = nil
|
||||
requestedPrice = nil
|
||||
loadProjects()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
// 底部弹层和记录页返回时保留已选套餐;离开收款流程才取消正在进行的请求。
|
||||
if isMovingFromParent || navigationController?.isBeingDismissed == true {
|
||||
requestTask?.cancel()
|
||||
viewModel.invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private func makePaymentCard() -> UIView {
|
||||
let stack = UIStackView()
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 16
|
||||
scenicLabel.textAlignment = .center
|
||||
stack.addArrangedSubview(scenicLabel)
|
||||
configureButton(projectButton, title: "", identifier: "drone.payment.projectPicker", action: #selector(selectProject))
|
||||
let projectCaption = DroneDockStyle.label("航拍套餐", size: 13, color: DroneDockStyle.secondary)
|
||||
let projectChevron = UIImageView(image: UIImage(systemName: "chevron.right"))
|
||||
projectChevron.tintColor = DroneDockStyle.secondary
|
||||
projectChevron.contentMode = .scaleAspectFit
|
||||
projectNameLabel.textAlignment = .right
|
||||
projectNameLabel.numberOfLines = 2
|
||||
projectCountLabel.textAlignment = .right
|
||||
let projectTitles = UIStackView(arrangedSubviews: [projectNameLabel, projectCountLabel])
|
||||
projectTitles.axis = .vertical
|
||||
projectTitles.alignment = .trailing
|
||||
projectTitles.spacing = 4
|
||||
projectTitles.isUserInteractionEnabled = false
|
||||
[projectCaption, projectChevron, projectTitles].forEach(projectButton.addSubview)
|
||||
projectCaption.snp.makeConstraints { make in make.leading.centerY.equalToSuperview() }
|
||||
projectChevron.snp.makeConstraints { make in
|
||||
make.trailing.centerY.equalToSuperview()
|
||||
make.size.equalTo(CGSize(width: 10, height: 14))
|
||||
}
|
||||
projectTitles.snp.makeConstraints { make in
|
||||
make.leading.greaterThanOrEqualTo(projectCaption.snp.trailing).offset(12)
|
||||
make.trailing.equalTo(projectChevron.snp.leading).offset(-10)
|
||||
make.centerY.equalToSuperview()
|
||||
make.top.greaterThanOrEqualToSuperview().offset(6)
|
||||
make.bottom.lessThanOrEqualToSuperview().offset(-6)
|
||||
}
|
||||
projectButton.snp.makeConstraints { $0.height.greaterThanOrEqualTo(54) }
|
||||
stack.addArrangedSubview(line())
|
||||
stack.addArrangedSubview(projectButton)
|
||||
stack.addArrangedSubview(line())
|
||||
amountLabel.textAlignment = .center
|
||||
amountLabel.accessibilityIdentifier = "drone.payment.amount"
|
||||
stack.addArrangedSubview(amountLabel)
|
||||
stack.addArrangedSubview(qrContainer)
|
||||
qrContainer.snp.makeConstraints { $0.height.equalTo(230) }
|
||||
qrImageView.contentMode = .scaleAspectFit
|
||||
qrImageView.accessibilityIdentifier = "drone.payment.qr"
|
||||
qrImageView.isAccessibilityElement = true
|
||||
qrImageView.accessibilityLabel = "套餐付款二维码"
|
||||
qrContainer.addSubview(qrImageView)
|
||||
qrImageView.snp.makeConstraints { make in make.center.equalToSuperview(); make.size.equalTo(220) }
|
||||
placeholder.axis = .vertical
|
||||
placeholder.alignment = .center
|
||||
placeholder.spacing = 12
|
||||
placeholderIcon.tintColor = DroneDockStyle.secondary.withAlphaComponent(0.65)
|
||||
placeholderIcon.contentMode = .scaleAspectFit
|
||||
placeholderIcon.snp.makeConstraints { $0.size.equalTo(40) }
|
||||
placeholderDetail.numberOfLines = 0
|
||||
placeholderDetail.textAlignment = .center
|
||||
placeholderTitle.numberOfLines = 0
|
||||
placeholderTitle.textAlignment = .center
|
||||
[placeholderIcon, spinner, placeholderTitle, placeholderDetail, retryButton, retryProjectsButton].forEach(placeholder.addArrangedSubview)
|
||||
qrContainer.addSubview(placeholder)
|
||||
placeholder.snp.makeConstraints { make in
|
||||
make.center.equalToSuperview()
|
||||
make.leading.trailing.equalToSuperview().inset(4)
|
||||
}
|
||||
configureButton(retryButton, title: "重新生成", identifier: "drone.payment.retryCode", action: #selector(retryCode))
|
||||
configureButton(retryProjectsButton, title: "重新加载套餐", identifier: "drone.payment.retryProjects", action: #selector(retryProjects))
|
||||
paymentHint.numberOfLines = 0
|
||||
paymentHint.textAlignment = .center
|
||||
stack.addArrangedSubview(paymentHint)
|
||||
configureButton(checkReceiptsButton, title: "刷新收款记录", identifier: "drone.payment.refreshReceipts", action: #selector(checkReceipts))
|
||||
stack.addArrangedSubview(checkReceiptsButton)
|
||||
configureButton(setAmountButton, title: "设置金额", identifier: "drone.payment.setAmount", action: #selector(setAmountTapped))
|
||||
configureButton(saveButton, title: "保存二维码", identifier: "drone.payment.saveQR", action: #selector(saveTapped))
|
||||
let actions = UIStackView(arrangedSubviews: [setAmountButton, saveButton])
|
||||
actions.distribution = .fillEqually
|
||||
actions.snp.makeConstraints { $0.height.equalTo(44) }
|
||||
stack.addArrangedSubview(actions)
|
||||
return card(stack, insets: 18)
|
||||
}
|
||||
|
||||
private func makeInformationCard() -> UIView {
|
||||
let stack = UIStackView()
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 14
|
||||
stack.addArrangedSubview(infoRow("景区名称", value: scenicValue))
|
||||
stack.addArrangedSubview(line())
|
||||
stack.addArrangedSubview(infoRow("收款方", value: DroneDockStyle.label("—", size: 13)))
|
||||
stack.addArrangedSubview(line())
|
||||
stack.addArrangedSubview(infoRow("员工 ID", value: staffValue))
|
||||
return card(stack, insets: 16)
|
||||
}
|
||||
|
||||
private func infoRow(_ title: String, value: UILabel) -> UIView {
|
||||
value.numberOfLines = 2
|
||||
value.textAlignment = .right
|
||||
let caption = DroneDockStyle.label(title, size: 13, color: DroneDockStyle.secondary)
|
||||
caption.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
let row = UIStackView(arrangedSubviews: [caption, UIView(), value])
|
||||
row.spacing = 12
|
||||
row.alignment = .center
|
||||
row.snp.makeConstraints { $0.height.greaterThanOrEqualTo(26) }
|
||||
return row
|
||||
}
|
||||
|
||||
private func card(_ child: UIView, insets: CGFloat) -> UIView {
|
||||
let view = UIView()
|
||||
DroneDockStyle.applyCard(to: view)
|
||||
view.addSubview(child)
|
||||
child.snp.makeConstraints { $0.edges.equalToSuperview().inset(insets) }
|
||||
return view
|
||||
}
|
||||
|
||||
private func line() -> UIView {
|
||||
let line = UIView()
|
||||
line.backgroundColor = DroneDockStyle.border
|
||||
line.snp.makeConstraints { $0.height.equalTo(0.5) }
|
||||
return line
|
||||
}
|
||||
|
||||
private func configureButton(_ button: UIButton, title: String, identifier: String, action: Selector) {
|
||||
button.setTitle(title, for: .normal)
|
||||
button.titleLabel?.font = .systemFont(ofSize: 14)
|
||||
button.tintColor = DroneDockStyle.primary
|
||||
button.accessibilityIdentifier = identifier
|
||||
button.addTarget(self, action: action, for: .touchUpInside)
|
||||
}
|
||||
|
||||
private func applyState() {
|
||||
guard isViewLoaded else { return }
|
||||
scenicLabel.text = viewModel.context.scenicName.isEmpty ? "当前景区" : viewModel.context.scenicName
|
||||
scenicValue.text = scenicLabel.text
|
||||
let code = viewModel.payCode
|
||||
let selected = viewModel.projects.first { $0.id == (code?.projectID ?? requestedProjectID) }
|
||||
let name = code?.projectName ?? selected?.name
|
||||
let count = code?.shootCount ?? selected?.shootCount
|
||||
projectNameLabel.text = name ?? "请选择"
|
||||
projectCountLabel.text = count.map { "含 \($0) 次拍摄" }
|
||||
projectCountLabel.isHidden = count == nil
|
||||
projectButton.accessibilityLabel = "航拍套餐," + (name ?? "请选择")
|
||||
projectButton.isEnabled = !isLoadingProjectRequest && !viewModel.isLoadingProjects && !isUpdatingCode
|
||||
amountLabel.isHidden = code == nil
|
||||
amountLabel.text = code.map { "本次收款 ¥\(Self.money($0.price))" }
|
||||
staffValue.text = code.map { String($0.storeUserID) } ?? "—"
|
||||
let busy = isUpdatingCode || viewModel.isGenerating || viewModel.isLoadingProjects || isLoadingProjectRequest
|
||||
if busy { spinner.startAnimating() } else { spinner.stopAnimating() }
|
||||
spinner.isHidden = !busy
|
||||
placeholderIcon.isHidden = busy
|
||||
retryButton.isHidden = viewModel.payCodeError == nil || busy || requestedProjectID == nil
|
||||
retryProjectsButton.isHidden = busy || (viewModel.projectError == nil && !viewModel.projects.isEmpty)
|
||||
if isUpdatingCode || viewModel.isGenerating {
|
||||
placeholderTitle.text = "正在生成收款码…"
|
||||
placeholderDetail.text = "请稍候"
|
||||
} else if viewModel.isLoadingProjects || isLoadingProjectRequest {
|
||||
placeholderTitle.text = "正在加载套餐…"
|
||||
placeholderDetail.text = "请稍候"
|
||||
} else if let error = viewModel.payCodeError ?? viewModel.projectError {
|
||||
placeholderTitle.text = viewModel.payCodeError != nil ? "收款码生成失败" : "套餐加载失败"
|
||||
placeholderDetail.text = error
|
||||
} else if viewModel.projects.isEmpty && hasLoaded {
|
||||
placeholderTitle.text = "暂无可售套餐"
|
||||
placeholderDetail.text = "请联系管理员配置航拍套餐"
|
||||
} else {
|
||||
placeholderTitle.text = "请选择航拍套餐"
|
||||
placeholderDetail.text = "选择后生成对应套餐收款码"
|
||||
}
|
||||
let url = busy ? nil : code?.payURL
|
||||
if url != renderedURL {
|
||||
renderedURL = url
|
||||
qrImageView.image = url.flatMap { QRCodeGenerator.generateStyledQRCode(content: $0, backgroundColor: .white, cornerRadius: 0) }
|
||||
}
|
||||
let hasCode = url != nil && qrImageView.image != nil
|
||||
qrImageView.isHidden = !hasCode
|
||||
placeholder.isHidden = hasCode
|
||||
if url != nil && !hasCode {
|
||||
placeholderTitle.text = "二维码暂时无法显示"
|
||||
placeholderDetail.text = "请重新生成"
|
||||
retryButton.isHidden = false
|
||||
}
|
||||
paymentHint.isHidden = !hasCode
|
||||
checkReceiptsButton.isHidden = !hasCode
|
||||
setAmountButton.isEnabled = hasCode
|
||||
saveButton.isEnabled = hasCode
|
||||
setAmountButton.alpha = hasCode ? 1 : 0.4
|
||||
saveButton.alpha = hasCode ? 1 : 0.4
|
||||
}
|
||||
|
||||
private func loadProjects() {
|
||||
requestTask?.cancel()
|
||||
isUpdatingCode = false
|
||||
isLoadingProjectRequest = true
|
||||
applyState()
|
||||
requestTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.loadProjects()
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isLoadingProjectRequest = false
|
||||
self.hasLoaded = true
|
||||
self.applyState()
|
||||
#if DEBUG
|
||||
if ProcessInfo.processInfo.arguments.contains("--dock-payment-probe"),
|
||||
self.viewModel.payCode == nil, let first = self.viewModel.projects.first {
|
||||
self.requestedProjectID = first.id
|
||||
self.requestedPrice = nil
|
||||
self.isUpdatingCode = true
|
||||
self.applyState()
|
||||
await self.viewModel.generateCode(projectID: first.id, price: nil)
|
||||
self.isUpdatingCode = false
|
||||
self.applyState()
|
||||
}
|
||||
await self.captureIfRequested()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
private func generateCode(projectID: Int, price: String?) {
|
||||
requestTask?.cancel()
|
||||
requestedProjectID = projectID
|
||||
requestedPrice = price
|
||||
isUpdatingCode = true
|
||||
applyState()
|
||||
requestTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.generateCode(projectID: projectID, price: price)
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isUpdatingCode = false
|
||||
self.applyState()
|
||||
#if DEBUG
|
||||
await self.captureIfRequested()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func selectProject() {
|
||||
guard !viewModel.projects.isEmpty else {
|
||||
if viewModel.projectError != nil { loadProjects() }
|
||||
else { showAlert(title: "暂无可售套餐", message: "请联系管理员配置航拍套餐") }
|
||||
return
|
||||
}
|
||||
let picker = DroneDockProjectPickerViewController(projects: viewModel.projects,
|
||||
selectedID: viewModel.payCode?.projectID ?? requestedProjectID,
|
||||
scenicName: viewModel.context.scenicName)
|
||||
picker.onConfirm = { [weak self] project in self?.generateCode(projectID: project.id, price: nil) }
|
||||
let navigation = UINavigationController(rootViewController: picker)
|
||||
if let sheet = navigation.sheetPresentationController {
|
||||
sheet.detents = [.medium(), .large()]
|
||||
sheet.prefersGrabberVisible = true
|
||||
}
|
||||
present(navigation, animated: true)
|
||||
}
|
||||
|
||||
@objc private func retryProjects() { loadProjects() }
|
||||
@objc private func retryCode() {
|
||||
guard let id = requestedProjectID else { return }
|
||||
generateCode(projectID: id, price: requestedPrice)
|
||||
}
|
||||
|
||||
@objc private func setAmountTapped() {
|
||||
guard let code = viewModel.payCode, !isUpdatingCode else { return }
|
||||
amountDraft = Self.money(code.price)
|
||||
let dialog = PaymentSetAmountDialogView()
|
||||
dialog.configureAmountOnly(accessibilityPrefix: "drone.payment.amount")
|
||||
dialog.apply(amount: amountDraft, remark: "")
|
||||
dialog.onAmountChange = { [weak self] value in self?.amountDraft = value }
|
||||
dialog.onCancel = { [weak self, weak dialog] in dialog?.dismiss(); self?.amountDialog = nil }
|
||||
dialog.onConfirm = { [weak self, weak dialog] in
|
||||
guard let self else { return }
|
||||
if let error = DroneDockPriceValidator.validationMessage(for: self.amountDraft) {
|
||||
self.showToast(error)
|
||||
return
|
||||
}
|
||||
guard let price = DroneDockPriceValidator.normalizedPrice(self.amountDraft) else { return }
|
||||
dialog?.dismiss()
|
||||
self.amountDialog = nil
|
||||
self.generateCode(projectID: code.projectID, price: price)
|
||||
}
|
||||
amountDialog = dialog
|
||||
dialog.show(in: view)
|
||||
}
|
||||
|
||||
@objc private func saveTapped() {
|
||||
guard let image = qrImageView.image, !qrImageView.isHidden else { return }
|
||||
Task { @MainActor [weak self] in
|
||||
let success = await PhotoLibrarySaver.saveImage(image)
|
||||
self?.showToast(success ? "保存成功" : "保存失败")
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func recordsTapped() { navigationController?.pushViewController(makeReceiptsController(), animated: true) }
|
||||
@objc private func checkReceipts() { navigationController?.pushViewController(makeReceiptsController(projectID: viewModel.payCode?.projectID), animated: true) }
|
||||
@objc private func voiceChanged() { AppStore.shared.payment.isOpenReceiveVoice = voiceSwitch.isOn }
|
||||
@objc private func offlineTapped() { navigationController?.pushViewController(OfflineCollectionRegistrationViewController(), animated: true) }
|
||||
|
||||
/// 进入真实收款记录;不将最近一条记录推断为本次二维码的支付结果。
|
||||
func makeReceiptsController(projectID: Int? = nil) -> DroneDockReceiptsViewController {
|
||||
DroneDockReceiptsViewController(viewModel: DroneDockReceiptsViewModel(context: viewModel.context, service: service,
|
||||
currentContext: currentContext, projectID: projectID))
|
||||
}
|
||||
|
||||
/// 用十进制两位金额展示,不用浮点参与报价计算。
|
||||
private static func money(_ value: Decimal) -> String {
|
||||
let formatter = NumberFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.numberStyle = .decimal
|
||||
formatter.usesGroupingSeparator = false
|
||||
formatter.minimumFractionDigits = 2
|
||||
formatter.maximumFractionDigits = 2
|
||||
return formatter.string(from: NSDecimalNumber(decimal: value)) ?? "—"
|
||||
}
|
||||
|
||||
/// 从当前登录会话读取身份,不改变账号、景区或门店。
|
||||
private static func currentPaymentContext() -> DroneDockHomeContext {
|
||||
let session = AppStore.shared.session
|
||||
return DroneDockHomeContext(userID: session.userId, accountType: session.accountType.rawValue,
|
||||
scenicID: session.currentScenicId, scenicName: session.currentScenicName,
|
||||
storeID: session.currentStoreId, photographerName: session.userName, token: session.token)
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 显式联调参数下只保存本应用窗口,不采集其他 App 或系统屏幕。
|
||||
private func captureIfRequested() async {
|
||||
guard ProcessInfo.processInfo.arguments.contains("--dock-payment-capture") else { return }
|
||||
try? await Task.sleep(nanoseconds: 400_000_000)
|
||||
guard !Task.isCancelled, let window = view.window else { return }
|
||||
window.layoutIfNeeded()
|
||||
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) }
|
||||
do {
|
||||
let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("DroneDockPaymentDiagnostics", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
try image.pngData()?.write(to: directory.appendingPathComponent("payment.png"), options: .atomic)
|
||||
print("[DroneDockPayment] App window screenshot saved")
|
||||
} catch { print("[DroneDockPayment] Screenshot failed: \(error.localizedDescription)") }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 套餐单选弹层,取消时保留原选择,确认后才向服务端请求付款链接。
|
||||
private final class DroneDockProjectPickerViewController: BaseViewController, UITableViewDelegate {
|
||||
/// 仅用户确认当前候选套餐后通知收款页。
|
||||
var onConfirm: ((DroneDockProject) -> Void)?
|
||||
private let projects: [DroneDockProject]
|
||||
private var selectedID: Int?
|
||||
private let scenicName: String
|
||||
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
|
||||
private var dataSource: UITableViewDiffableDataSource<Int, Int>!
|
||||
private let confirmButton = UIButton(type: .system)
|
||||
private let cancelButton = UIButton(type: .system)
|
||||
private let footer = UIView()
|
||||
|
||||
/// 冻结本次选择列表及原套餐,列表点击不产生收款请求。
|
||||
init(projects: [DroneDockProject], selectedID: Int?, scenicName: String) {
|
||||
self.projects = projects
|
||||
self.selectedID = selectedID
|
||||
self.scenicName = scenicName
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() { title = "选择航拍套餐" }
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = DroneDockStyle.background
|
||||
tableView.backgroundColor = .clear
|
||||
tableView.rowHeight = 78
|
||||
tableView.delegate = self
|
||||
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "project")
|
||||
let scenicHeader = DroneDockStyle.label(" " + scenicName, size: 13, color: DroneDockStyle.secondary)
|
||||
scenicHeader.frame = CGRect(x: 0, y: 0, width: 320, height: 36)
|
||||
tableView.tableHeaderView = scenicHeader
|
||||
view.addSubview(tableView)
|
||||
view.addSubview(footer)
|
||||
let note = DroneDockStyle.label("选择套餐后可调整成交价,拍摄次数不变。", size: 12, color: DroneDockStyle.secondary)
|
||||
note.numberOfLines = 0
|
||||
cancelButton.setTitle("取消", for: .normal)
|
||||
confirmButton.setTitle("确认套餐", for: .normal)
|
||||
cancelButton.accessibilityIdentifier = "drone.payment.cancelProject"
|
||||
confirmButton.accessibilityIdentifier = "drone.payment.confirmProject"
|
||||
cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
|
||||
confirmButton.addTarget(self, action: #selector(confirm), for: .touchUpInside)
|
||||
cancelButton.backgroundColor = .white
|
||||
confirmButton.backgroundColor = DroneDockStyle.primary
|
||||
confirmButton.setTitleColor(.white, for: .normal)
|
||||
[cancelButton, confirmButton].forEach { $0.layer.cornerRadius = 10 }
|
||||
let buttons = UIStackView(arrangedSubviews: [cancelButton, confirmButton])
|
||||
buttons.distribution = .fillEqually
|
||||
buttons.spacing = 12
|
||||
buttons.snp.makeConstraints { $0.height.equalTo(46) }
|
||||
let stack = UIStackView(arrangedSubviews: [note, buttons])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 16
|
||||
footer.addSubview(stack)
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(16) }
|
||||
dataSource = UITableViewDiffableDataSource<Int, Int>(tableView: tableView) { [weak self] table, path, id in
|
||||
guard let self, let project = self.projects.first(where: { $0.id == id }) else { return nil }
|
||||
let cell = table.dequeueReusableCell(withIdentifier: "project", for: path)
|
||||
var config = cell.defaultContentConfiguration()
|
||||
config.text = project.name
|
||||
config.secondaryText = "含 \(project.shootCount) 次拍摄 ¥\(NSDecimalNumber(decimal: project.price).stringValue)"
|
||||
config.textProperties.font = .systemFont(ofSize: 15, weight: .medium)
|
||||
config.secondaryTextProperties.color = DroneDockStyle.secondary
|
||||
cell.contentConfiguration = config
|
||||
cell.accessoryType = id == self.selectedID ? .checkmark : .none
|
||||
cell.tintColor = DroneDockStyle.primary
|
||||
cell.accessibilityIdentifier = "drone.payment.project.\(id)"
|
||||
return cell
|
||||
}
|
||||
applySelection()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
footer.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
|
||||
tableView.snp.makeConstraints { make in
|
||||
make.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||
make.bottom.equalTo(footer.snp.top)
|
||||
}
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
||||
selectedID = dataSource.itemIdentifier(for: indexPath)
|
||||
applySelection()
|
||||
}
|
||||
|
||||
private func applySelection() {
|
||||
confirmButton.isEnabled = selectedID != nil
|
||||
confirmButton.alpha = selectedID == nil ? 0.4 : 1
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Int>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(projects.map(\.id))
|
||||
let existing = Set(dataSource.snapshot().itemIdentifiers)
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||
dataSource.apply(snapshot, animatingDifferences: true)
|
||||
}
|
||||
|
||||
@objc private func cancel() { dismiss(animated: true) }
|
||||
@objc private func confirm() {
|
||||
guard let project = projects.first(where: { $0.id == selectedID }) else { return }
|
||||
let completion = onConfirm
|
||||
dismiss(animated: true) { completion?(project) }
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,17 @@ import UIKit
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
if (arguments.contains("--dock-payment-live") || arguments.contains("--dock-receipts-live")), AppStore.shared.session.isLoggedIn {
|
||||
let home = DroneDockHomeViewController()
|
||||
let payment = DroneDockPaymentViewController()
|
||||
let navigation = UINavigationController()
|
||||
if arguments.contains("--dock-receipts-live") {
|
||||
navigation.setViewControllers([home, payment, payment.makeReceiptsController()], animated: false)
|
||||
} else {
|
||||
navigation.setViewControllers([home, payment], animated: false)
|
||||
}
|
||||
return navigation
|
||||
}
|
||||
if arguments.contains("--dock-home-live"), AppStore.shared.session.isLoggedIn {
|
||||
return UINavigationController(rootViewController: DroneDockHomeViewController())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 真实套餐收款记录页,展示接口汇总与分页明细,不进入拍摄订单或演示流程。
|
||||
@MainActor
|
||||
final class DroneDockReceiptsViewController: BaseViewController {
|
||||
/// 当前页面的收款查询状态。
|
||||
let viewModel: DroneDockReceiptsViewModel
|
||||
private let tableView = UITableView(frame: .zero, style: .plain)
|
||||
private var dataSource: UITableViewDiffableDataSource<Section, Item>!
|
||||
private var loadTask: Task<Void, Never>?
|
||||
private var operation: LoadAction?
|
||||
|
||||
/// 汇总与收款记录使用独立分区,空态也由同一 Diffable 数据源管理。
|
||||
private enum Section: Hashable { case summary, receipts }
|
||||
/// 订单号作为列表的稳定身份,金额更新不生成重复记录。
|
||||
private enum Item: Hashable { case summary, receipt(String), message }
|
||||
/// 区分整页刷新与保留现有记录的分页请求。
|
||||
private enum LoadAction: Equatable { case refresh, more }
|
||||
|
||||
/// 注入当前景区及可选套餐范围的记录模型。
|
||||
init(viewModel: DroneDockReceiptsViewModel) {
|
||||
self.viewModel = viewModel
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit { loadTask?.cancel() }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "收款记录"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = DroneDockStyle.background
|
||||
tableView.backgroundColor = .clear
|
||||
tableView.separatorStyle = .none
|
||||
tableView.allowsSelection = false
|
||||
tableView.rowHeight = UITableView.automaticDimension
|
||||
tableView.estimatedRowHeight = 230
|
||||
tableView.sectionHeaderTopPadding = 0
|
||||
tableView.accessibilityIdentifier = "drone.receipts.list"
|
||||
tableView.register(DroneDockReceiptSummaryCell.self, forCellReuseIdentifier: "summary")
|
||||
tableView.register(DroneDockReceiptCell.self, forCellReuseIdentifier: "receipt")
|
||||
tableView.register(DroneDockReceiptsMessageCell.self, forCellReuseIdentifier: "message")
|
||||
let refresh = UIRefreshControl()
|
||||
refresh.tintColor = DroneDockStyle.primary
|
||||
refresh.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
|
||||
tableView.refreshControl = refresh
|
||||
view.addSubview(tableView)
|
||||
configureDataSource()
|
||||
applySnapshot(animated: false)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
tableView.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide)
|
||||
make.leading.trailing.bottom.equalToSuperview()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
load(.refresh)
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
loadTask?.cancel()
|
||||
operation = nil
|
||||
viewModel.invalidate()
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UITableViewDiffableDataSource<Section, Item>(tableView: tableView) { [weak self] table, path, item in
|
||||
guard let self else { return nil }
|
||||
switch item {
|
||||
case .summary:
|
||||
let cell = table.dequeueReusableCell(withIdentifier: "summary", for: path) as! DroneDockReceiptSummaryCell
|
||||
cell.apply(self.operation == .refresh ? nil : self.viewModel.summary)
|
||||
return cell
|
||||
case .receipt(let orderNumber):
|
||||
let cell = table.dequeueReusableCell(withIdentifier: "receipt", for: path) as! DroneDockReceiptCell
|
||||
if let receipt = self.viewModel.receipts.first(where: { $0.orderNumber == orderNumber }) {
|
||||
cell.apply(receipt)
|
||||
}
|
||||
return cell
|
||||
case .message:
|
||||
let cell = table.dequeueReusableCell(withIdentifier: "message", for: path) as! DroneDockReceiptsMessageCell
|
||||
let isLoading = self.operation != nil || self.viewModel.isLoading
|
||||
let error = self.viewModel.errorMessage
|
||||
if isLoading || (self.viewModel.summary == nil && error == nil) {
|
||||
cell.apply(title: "正在加载收款记录", detail: "正在获取最新数据", canRetry: false)
|
||||
} else if let error {
|
||||
cell.apply(title: "收款记录加载失败", detail: error, canRetry: true)
|
||||
} else {
|
||||
cell.apply(title: "暂无收款记录", detail: "近7天暂无收款数据", canRetry: false)
|
||||
}
|
||||
cell.onRetry = { [weak self] in self?.load(.refresh) }
|
||||
return cell
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func load(_ action: LoadAction) {
|
||||
if action == .more, operation != nil || !viewModel.hasMore { return }
|
||||
loadTask?.cancel()
|
||||
operation = action
|
||||
applySnapshot(animated: false)
|
||||
loadTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
if action == .refresh { await self.viewModel.refresh() }
|
||||
else { await self.viewModel.loadMore() }
|
||||
guard !Task.isCancelled else { return }
|
||||
self.operation = nil
|
||||
self.tableView.refreshControl?.endRefreshing()
|
||||
self.applySnapshot(animated: true) { [weak self] in
|
||||
#if DEBUG
|
||||
guard action == .refresh, self?.viewModel.errorMessage == nil else { return }
|
||||
Task { @MainActor [weak self] in await self?.captureIfRequested() }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
|
||||
guard dataSource != nil else { return }
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
snapshot.appendSections([.summary, .receipts])
|
||||
snapshot.appendItems([.summary], toSection: .summary)
|
||||
let records = operation == .refresh ? [] : viewModel.receipts.map { Item.receipt($0.orderNumber) }
|
||||
snapshot.appendItems(records.isEmpty ? [.message] : records, toSection: .receipts)
|
||||
let previous = Set(dataSource.snapshot().itemIdentifiers)
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
|
||||
updateFooter()
|
||||
dataSource.apply(snapshot, animatingDifferences: animated, completion: completion)
|
||||
}
|
||||
|
||||
private func updateFooter() {
|
||||
guard operation != .refresh, !viewModel.receipts.isEmpty else {
|
||||
tableView.tableFooterView = nil
|
||||
return
|
||||
}
|
||||
let footer = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 84))
|
||||
let label = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
label.numberOfLines = 2
|
||||
label.textAlignment = .center
|
||||
let button = UIButton(type: .system)
|
||||
button.tintColor = DroneDockStyle.primary
|
||||
button.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
|
||||
button.accessibilityIdentifier = "drone.receipts.loadMore"
|
||||
button.addTarget(self, action: #selector(loadMoreTriggered), for: .touchUpInside)
|
||||
if operation != nil {
|
||||
label.text = operation == .more ? "正在加载更多…" : "正在刷新…"
|
||||
button.isHidden = true
|
||||
} else if let error = viewModel.errorMessage {
|
||||
label.text = error
|
||||
button.setTitle("重试加载", for: .normal)
|
||||
} else if viewModel.hasMore {
|
||||
label.text = "已显示 \(viewModel.receipts.count) 条记录"
|
||||
button.setTitle("加载更多", for: .normal)
|
||||
} else {
|
||||
label.text = "已显示全部收款记录"
|
||||
button.isHidden = true
|
||||
}
|
||||
let stack = UIStackView(arrangedSubviews: [label, button])
|
||||
stack.axis = .vertical
|
||||
stack.alignment = .center
|
||||
stack.spacing = 4
|
||||
footer.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.centerY.equalToSuperview()
|
||||
make.leading.trailing.equalToSuperview().inset(24)
|
||||
}
|
||||
button.snp.makeConstraints { $0.height.equalTo(36).priority(999) }
|
||||
tableView.tableFooterView = footer
|
||||
}
|
||||
|
||||
@objc private func refreshTriggered() { load(.refresh) }
|
||||
@objc private func loadMoreTriggered() { load(.more) }
|
||||
|
||||
#if DEBUG
|
||||
/// 显式联调时保存当前 App 的记录页,待 Diffable 动画与屏幕提交后再截图。
|
||||
private func captureIfRequested() async {
|
||||
guard ProcessInfo.processInfo.arguments.contains("--dock-payment-capture") else { return }
|
||||
try? await Task.sleep(nanoseconds: 400_000_000)
|
||||
guard !Task.isCancelled, operation == nil, viewModel.summary != nil,
|
||||
navigationController?.topViewController === self,
|
||||
let window = view.window, window.windowScene?.activationState == .foregroundActive else { return }
|
||||
window.layoutIfNeeded()
|
||||
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
|
||||
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
|
||||
}
|
||||
do {
|
||||
let folder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("DroneDockPaymentDiagnostics", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
try image.pngData()?.write(to: folder.appendingPathComponent("receipts.png"), options: .atomic)
|
||||
print("[DroneDockPayment] Receipts window screenshot saved")
|
||||
} catch { print("[DroneDockPayment] Receipts screenshot failed: \(error.localizedDescription)") }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 顶部收款汇总卡;现金金额与积分始终使用分开的展示区域。
|
||||
@MainActor
|
||||
private final class DroneDockReceiptSummaryCell: UITableViewCell {
|
||||
private let card = UIView()
|
||||
private let stack = UIStackView()
|
||||
|
||||
/// 建立自适应高度的汇总卡片。
|
||||
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||
backgroundColor = .clear
|
||||
selectionStyle = .none
|
||||
DroneDockStyle.applyCard(to: card)
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 16
|
||||
contentView.addSubview(card)
|
||||
card.addSubview(stack)
|
||||
card.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 16, left: 16, bottom: 12, right: 16)) }
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(16) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 使用服务端完整汇总,尚未成功读取时保留未知占位。
|
||||
func apply(_ summary: DroneDockReceiptSummary?) {
|
||||
stack.arrangedSubviews.forEach { $0.removeFromSuperview() }
|
||||
let title = DroneDockStyle.label("近7天收款汇总", size: 16, weight: .semibold)
|
||||
let count = DroneDockStyle.label(summary.map { "共 \($0.count) 笔" } ?? "—", size: 12, color: DroneDockStyle.secondary)
|
||||
count.setContentHuggingPriority(.required, for: .horizontal)
|
||||
let heading = UIStackView(arrangedSubviews: [title, count])
|
||||
stack.addArrangedSubview(heading)
|
||||
stack.addArrangedSubview(DroneDockReceiptFormatting.cashColumns(
|
||||
paid: summary?.cashPaid, refund: summary?.cashRefund, net: summary?.cashNet, large: true))
|
||||
if let summary, summary.pointsPaid != 0 || summary.pointsRefund != 0 || summary.pointsNet != 0 || summary.pointAmount != 0 {
|
||||
stack.addArrangedSubview(DroneDockReceiptFormatting.pointsView(
|
||||
paid: summary.pointsPaid, refund: summary.pointsRefund, net: summary.pointsNet, amount: summary.pointAmount))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 单笔收款卡片,仅展示套餐与支付字段,不推测拍摄次数或订单业务状态。
|
||||
@MainActor
|
||||
private final class DroneDockReceiptCell: UITableViewCell {
|
||||
private let card = UIView()
|
||||
private let stack = UIStackView()
|
||||
|
||||
/// 建立白底卡片与适应多行名称的纵向内容。
|
||||
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||
backgroundColor = .clear
|
||||
selectionStyle = .none
|
||||
DroneDockStyle.applyCard(to: card)
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 12
|
||||
contentView.addSubview(card)
|
||||
card.addSubview(stack)
|
||||
card.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 16, bottom: 12, right: 16)) }
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(16) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 重建本笔内容,避免复用后残留上一笔积分或付款人信息。
|
||||
func apply(_ receipt: DroneDockReceipt) {
|
||||
accessibilityIdentifier = "drone.receipt.\(receipt.orderNumber)"
|
||||
stack.arrangedSubviews.forEach { $0.removeFromSuperview() }
|
||||
let name = DroneDockStyle.label(receipt.projectName.isEmpty ? "套餐名称未提供" : receipt.projectName, size: 16, weight: .semibold)
|
||||
name.numberOfLines = 0
|
||||
stack.addArrangedSubview(name)
|
||||
let payer = DroneDockStyle.label("付款人 \(receipt.payer.isEmpty ? "—" : receipt.payer)", size: 12, color: DroneDockStyle.secondary)
|
||||
payer.numberOfLines = 0
|
||||
stack.addArrangedSubview(payer)
|
||||
stack.addArrangedSubview(DroneDockReceiptFormatting.cashColumns(
|
||||
paid: receipt.cashPaid, refund: receipt.cashRefund, net: receipt.cashNet, large: false))
|
||||
if receipt.pointsPaid != 0 || receipt.pointsRefund != 0 || receipt.pointsNet != 0 || receipt.pointAmount != 0 {
|
||||
stack.addArrangedSubview(DroneDockReceiptFormatting.pointsView(
|
||||
paid: receipt.pointsPaid, refund: receipt.pointsRefund, net: receipt.pointsNet, amount: receipt.pointAmount))
|
||||
}
|
||||
let separator = UIView()
|
||||
separator.backgroundColor = DroneDockStyle.border
|
||||
separator.snp.makeConstraints { $0.height.equalTo(1 / UIScreen.main.scale) }
|
||||
stack.addArrangedSubview(separator)
|
||||
let time = DroneDockStyle.label("支付时间 \(DroneDockReceiptFormatting.time(receipt.payTime))", size: 12, color: DroneDockStyle.secondary)
|
||||
let order = DroneDockStyle.label("订单号 \(receipt.orderNumber)", size: 12, color: DroneDockStyle.secondary)
|
||||
time.numberOfLines = 0
|
||||
order.numberOfLines = 0
|
||||
stack.addArrangedSubview(time)
|
||||
stack.addArrangedSubview(order)
|
||||
}
|
||||
}
|
||||
|
||||
/// 收款记录的加载、空数据和失败重试提示。
|
||||
@MainActor
|
||||
private final class DroneDockReceiptsMessageCell: UITableViewCell {
|
||||
/// 用户请求重新读取第一页。
|
||||
var onRetry: (() -> Void)?
|
||||
private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium)
|
||||
private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
|
||||
private let retryButton = UIButton(type: .system)
|
||||
|
||||
/// 创建适合空记录列表的居中提示。
|
||||
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||
backgroundColor = .clear
|
||||
selectionStyle = .none
|
||||
titleLabel.textAlignment = .center
|
||||
titleLabel.numberOfLines = 0
|
||||
detailLabel.textAlignment = .center
|
||||
detailLabel.numberOfLines = 0
|
||||
retryButton.setTitle("重新加载", for: .normal)
|
||||
retryButton.tintColor = DroneDockStyle.primary
|
||||
retryButton.accessibilityIdentifier = "drone.receipts.retry"
|
||||
retryButton.addTarget(self, action: #selector(retryTapped), for: .touchUpInside)
|
||||
let icon = UIImageView(image: UIImage(systemName: "doc.text.magnifyingglass"))
|
||||
icon.tintColor = DroneDockStyle.secondary.withAlphaComponent(0.6)
|
||||
icon.contentMode = .scaleAspectFit
|
||||
icon.snp.makeConstraints { $0.size.equalTo(38) }
|
||||
let stack = UIStackView(arrangedSubviews: [icon, titleLabel, detailLabel, retryButton])
|
||||
stack.axis = .vertical
|
||||
stack.alignment = .center
|
||||
stack.spacing = 12
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.top.bottom.equalToSuperview().inset(48)
|
||||
make.leading.trailing.equalToSuperview().inset(24)
|
||||
}
|
||||
retryButton.snp.makeConstraints { $0.height.equalTo(36).priority(999) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 失败与成功空态分开表达,只有失败时提供重试动作。
|
||||
func apply(title: String, detail: String, canRetry: Bool) {
|
||||
titleLabel.text = title
|
||||
detailLabel.text = detail
|
||||
retryButton.isHidden = !canRetry
|
||||
}
|
||||
|
||||
@objc private func retryTapped() { onRetry?() }
|
||||
}
|
||||
|
||||
/// 收款记录的展示格式,不计算或混合现金与积分账目。
|
||||
@MainActor
|
||||
private enum DroneDockReceiptFormatting {
|
||||
/// 十进制金额按人民币展示两位小数,未知金额保留占位。
|
||||
static func money(_ amount: Decimal?) -> String {
|
||||
guard let amount else { return "—" }
|
||||
let formatter = NumberFormatter()
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.numberStyle = .decimal
|
||||
formatter.minimumFractionDigits = 2
|
||||
formatter.maximumFractionDigits = 2
|
||||
return formatter.string(from: NSDecimalNumber(decimal: amount)).map { "¥" + $0 } ?? "—"
|
||||
}
|
||||
|
||||
/// 后端支付时间是 Unix 秒,缺失的零值不展示为 1970 年。
|
||||
static func time(_ timestamp: TimeInterval) -> String {
|
||||
guard timestamp > 0 else { return "—" }
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
return formatter.string(from: Date(timeIntervalSince1970: timestamp))
|
||||
}
|
||||
|
||||
/// 三列明确区分现金实收、现金退款和现金净收。
|
||||
static func cashColumns(paid: Decimal?, refund: Decimal?, net: Decimal?, large: Bool) -> UIView {
|
||||
let values = [("现金实收", paid), ("现金退款", refund), ("现金净收", net)]
|
||||
let columns = values.map { title, amount in
|
||||
let value = DroneDockStyle.label(money(amount), size: large ? 20 : 17, weight: .semibold,
|
||||
color: title == "现金净收" ? DroneDockStyle.primary : DroneDockStyle.text)
|
||||
value.adjustsFontSizeToFitWidth = true
|
||||
value.minimumScaleFactor = 0.6
|
||||
let column = UIStackView(arrangedSubviews: [DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary), value])
|
||||
column.axis = .vertical
|
||||
column.spacing = 8
|
||||
return column
|
||||
}
|
||||
let row = UIStackView(arrangedSubviews: columns)
|
||||
row.distribution = .fillEqually
|
||||
row.spacing = 8
|
||||
return row
|
||||
}
|
||||
|
||||
/// 积分及其抵扣金额独立成行,绝不加到现金实收或净收中。
|
||||
static func pointsView(paid: Int, refund: Int, net: Int, amount: Decimal) -> UIView {
|
||||
let label = DroneDockStyle.label("积分实收 \(paid) · 积分退款 \(refund) · 积分净收 \(net)", size: 12, color: DroneDockStyle.secondary)
|
||||
label.numberOfLines = 0
|
||||
let stack = UIStackView(arrangedSubviews: [label])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 6
|
||||
if amount != 0 {
|
||||
let amountLabel = DroneDockStyle.label("积分抵扣金额 \(money(amount))", size: 12, color: DroneDockStyle.secondary)
|
||||
amountLabel.numberOfLines = 0
|
||||
stack.addArrangedSubview(amountLabel)
|
||||
}
|
||||
return stack
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,21 @@ final class PaymentSetAmountDialogView: KeyboardAvoidingDialogView {
|
||||
remarkCountLabel.text = "\(remark.count)/200"
|
||||
}
|
||||
|
||||
/// 套餐报价复用金额输入与键盘避让;接口不支持备注时隐藏对应区域。
|
||||
func configureAmountOnly(accessibilityPrefix: String) {
|
||||
remarkTitleLabel.isHidden = true
|
||||
remarkField.isHidden = true
|
||||
remarkCountLabel.isHidden = true
|
||||
buttonStack.snp.remakeConstraints { make in
|
||||
make.top.equalTo(amountContainer.snp.bottom).offset(AppSpacing.lg)
|
||||
make.leading.trailing.bottom.equalToSuperview().inset(AppSpacing.md)
|
||||
make.height.equalTo(44)
|
||||
}
|
||||
amountField.accessibilityIdentifier = accessibilityPrefix + ".input"
|
||||
confirmButton.accessibilityIdentifier = accessibilityPrefix + ".confirm"
|
||||
cancelButton.accessibilityIdentifier = accessibilityPrefix + ".cancel"
|
||||
}
|
||||
|
||||
func show(in parent: UIView) {
|
||||
frame = parent.bounds
|
||||
autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
|
||||
Reference in New Issue
Block a user