From 11e26bebb6d8280100a333e5c2212de61ed75327 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:14:16 +0000 Subject: [PATCH 01/40] feat(ios): preserve renewal local dates in billing timezone --- apps/ios/ServerBee/Localizable.xcstrings | 30 +++++ apps/ios/ServerBee/Models/ServerConfig.swift | 35 ++++++ .../Models/UpdateServerRequest.swift | 27 +++- .../ios/ServerBee/Utilities/BillingDate.swift | 39 ++++++ .../ViewModels/EditServerViewModel.swift | 46 ++++++- .../Detail/ServerOverviewSection.swift | 3 +- .../Servers/Enrollment/EditServerSheet.swift | 9 ++ .../ios/ServerBeeTests/RenewalDateTests.swift | 115 ++++++++++++++++++ 8 files changed, 293 insertions(+), 11 deletions(-) create mode 100644 apps/ios/ServerBee/Utilities/BillingDate.swift create mode 100644 apps/ios/ServerBeeTests/RenewalDateTests.swift diff --git a/apps/ios/ServerBee/Localizable.xcstrings b/apps/ios/ServerBee/Localizable.xcstrings index 4a789d1e6..5d18ec9de 100644 --- a/apps/ios/ServerBee/Localizable.xcstrings +++ b/apps/ios/ServerBee/Localizable.xcstrings @@ -18721,6 +18721,36 @@ } } } + }, + "Billing timezone": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "账单时区" + } + } + } + }, + "Choose a valid billing timezone.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "请选择有效的账单时区。" + } + } + } + }, + "Valid through the selected date in the billing timezone.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "在账单时区内,有效期持续至所选日期结束。" + } + } + } } }, "version": "1.0" diff --git a/apps/ios/ServerBee/Models/ServerConfig.swift b/apps/ios/ServerBee/Models/ServerConfig.swift index e08905cc8..c1354ee9d 100644 --- a/apps/ios/ServerBee/Models/ServerConfig.swift +++ b/apps/ios/ServerBee/Models/ServerConfig.swift @@ -1,5 +1,25 @@ import Foundation +/// Server-owned renewal projection. Clients display the selected local date; +/// recurrence and deadline advancement remain on the server. +struct ServerRenewal: Decodable, Hashable, Sendable { + let enabled: Bool + let billingTimezone: String + let expiryDate: String? + let confirmedExpiredAt: String? + let deadlineOrigin: String + let occurrenceId: String? + + enum CodingKeys: String, CodingKey { + case enabled + case billingTimezone = "billing_timezone" + case expiryDate = "expiry_date" + case confirmedExpiredAt = "confirmed_expired_at" + case deadlineOrigin = "deadline_origin" + case occurrenceId = "occurrence_id" + } +} + /// Server group (`/api/server-groups`). Used to resolve `group_id` to a name. struct ServerGroup: Decodable, Identifiable, Hashable, Sendable { let id: String @@ -92,6 +112,7 @@ struct ServerConfig: Decodable, Identifiable, Hashable, Sendable { var billingCycle: String? var currency: String? var expiredAt: String? + var renewal: ServerRenewal? var trafficLimit: Int64? var trafficLimitType: String? var billingStartDay: Int? @@ -123,6 +144,7 @@ struct ServerConfig: Decodable, Identifiable, Hashable, Sendable { case publicRemark = "public_remark" case billingCycle = "billing_cycle" case expiredAt = "expired_at" + case renewal case trafficLimit = "traffic_limit" case trafficLimitType = "traffic_limit_type" case billingStartDay = "billing_start_day" @@ -157,4 +179,17 @@ struct ServerConfig: Decodable, Identifiable, Hashable, Sendable { guard let expiredAt else { return nil } return ISO8601DateFormatter.shared.date(from: expiredAt) } + + var expiryLocalDate: String? { + renewal?.expiryDate ?? expiredDate.flatMap { + BillingDate.string(from: $0, timezone: renewal?.billingTimezone ?? "UTC") + } + } + + var expiryDisplayDate: String? { + let timezone = renewal?.billingTimezone ?? "UTC" + guard let selectedDate = expiryLocalDate, + let date = BillingDate.date(from: selectedDate, timezone: timezone) else { return nil } + return BillingDate.display(from: date, timezone: timezone) + } } diff --git a/apps/ios/ServerBee/Models/UpdateServerRequest.swift b/apps/ios/ServerBee/Models/UpdateServerRequest.swift index 1b0296273..518f6702a 100644 --- a/apps/ios/ServerBee/Models/UpdateServerRequest.swift +++ b/apps/ios/ServerBee/Models/UpdateServerRequest.swift @@ -9,9 +9,9 @@ enum Tri: Sendable { case clear case set(Value) - func encode( - into container: inout KeyedEncodingContainer, - forKey key: UpdateServerRequest.CodingKeys + func encode( + into container: inout KeyedEncodingContainer, + forKey key: Key ) throws { switch self { case .unchanged: break @@ -21,6 +21,24 @@ enum Tri: Sendable { } } +/// Date-only renewal edits. Omission preserves the server's current anchor; +/// clearing is explicit and validation belongs to the server. +struct UpdateRenewalRequest: Encodable, Sendable { + var billingTimezone: Tri = .unchanged + var expiryDate: Tri = .unchanged + + enum CodingKeys: String, CodingKey { + case billingTimezone = "billing_timezone" + case expiryDate = "expiry_date" + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try billingTimezone.encode(into: &container, forKey: .billingTimezone) + try expiryDate.encode(into: &container, forKey: .expiryDate) + } +} + /// Body for `PUT /api/servers/{id}` (UpdateServerInput). Every field is optional: /// omit to leave unchanged. Plain fields use `encodeIfPresent`; nullable fields /// use `Tri` so they can be cleared (remark/public_remark cannot be NULL-cleared @@ -36,6 +54,7 @@ struct UpdateServerRequest: Encodable, Sendable { var billingCycle: Tri = .unchanged var currency: Tri = .unchanged var expiredAt: Tri = .unchanged + var renewal: UpdateRenewalRequest? var trafficLimit: Tri = .unchanged var trafficLimitType: Tri = .unchanged var billingStartDay: Tri = .unchanged @@ -46,6 +65,7 @@ struct UpdateServerRequest: Encodable, Sendable { case groupId = "group_id" case billingCycle = "billing_cycle" case expiredAt = "expired_at" + case renewal case trafficLimit = "traffic_limit" case trafficLimitType = "traffic_limit_type" case billingStartDay = "billing_start_day" @@ -63,6 +83,7 @@ struct UpdateServerRequest: Encodable, Sendable { try billingCycle.encode(into: &container, forKey: .billingCycle) try currency.encode(into: &container, forKey: .currency) try expiredAt.encode(into: &container, forKey: .expiredAt) + try container.encodeIfPresent(renewal, forKey: .renewal) try trafficLimit.encode(into: &container, forKey: .trafficLimit) try trafficLimitType.encode(into: &container, forKey: .trafficLimitType) try billingStartDay.encode(into: &container, forKey: .billingStartDay) diff --git a/apps/ios/ServerBee/Utilities/BillingDate.swift b/apps/ios/ServerBee/Utilities/BillingDate.swift new file mode 100644 index 000000000..aba219e33 --- /dev/null +++ b/apps/ios/ServerBee/Utilities/BillingDate.swift @@ -0,0 +1,39 @@ +import Foundation + +/// Converts the date picker's instant to/from the server's literal local date. +/// This never calculates a renewal boundary or advances a schedule. +enum BillingDate { + static func string(from date: Date, timezone: String) -> String? { + guard let formatter = formatter(timezone: timezone) else { return nil } + return formatter.string(from: date) + } + + static func date(from string: String, timezone: String) -> Date? { + guard let formatter = formatter(timezone: timezone), + let date = formatter.date(from: string), formatter.string(from: date) == string else { return nil } + // Noon gives the date picker a stable instant even where DST changes at midnight. + return formatter.calendar.date(bySettingHour: 12, minute: 0, second: 0, of: date) + } + + static func display(from date: Date, timezone: String) -> String { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .gregorian) + formatter.timeZone = TimeZone(identifier: timezone) ?? .gmt + formatter.dateStyle = .medium + formatter.timeStyle = .none + return formatter.string(from: date) + } + + private static func formatter(timezone: String) -> DateFormatter? { + guard let zone = TimeZone(identifier: timezone) else { return nil } + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = zone + formatter.calendar = calendar + formatter.timeZone = zone + formatter.dateFormat = "yyyy-MM-dd" + formatter.isLenient = false + return formatter + } +} diff --git a/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift b/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift index 8500526d8..327064eec 100644 --- a/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift @@ -20,6 +20,20 @@ final class EditServerViewModel { var billingStartDayText = "" var hasExpiry = false var expiryDate = Date() + var billingTimezone = "UTC" { + didSet { + guard oldValue != billingTimezone, + let date = BillingDate.string(from: expiryDate, timezone: oldValue), + let converted = BillingDate.date(from: date, timezone: billingTimezone) else { return } + expiryDate = converted + } + } + var expiryTimezone: TimeZone { TimeZone(identifier: billingTimezone) ?? .gmt } + var expiryCalendar: Calendar { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = expiryTimezone + return calendar + } var trafficLimitGiBText = "" var trafficLimitType = "" // "" = none @@ -27,6 +41,8 @@ final class EditServerViewModel { var isSaving = false var errorMessage: String? private var originalTags: [String] = [] + private var originalExpiryDate: String? + private var originalBillingTimezone = "UTC" static let gibibyte = 1_073_741_824.0 @@ -41,8 +57,12 @@ final class EditServerViewModel { currency = config.currency ?? "" billingCycle = config.billingCycle ?? "" billingStartDayText = config.billingStartDay.map(String.init) ?? "" - if let expiry = config.expiredDate { - hasExpiry = true + billingTimezone = config.renewal?.billingTimezone ?? "UTC" + originalBillingTimezone = billingTimezone + originalExpiryDate = config.renewal?.expiryDate + ?? config.expiredDate.flatMap { BillingDate.string(from: $0, timezone: billingTimezone) } + hasExpiry = originalExpiryDate != nil + if let date = originalExpiryDate, let expiry = BillingDate.date(from: date, timezone: billingTimezone) { expiryDate = expiry } if let limit = config.trafficLimit { @@ -73,11 +93,11 @@ final class EditServerViewModel { } } -private extension EditServerViewModel { +extension EditServerViewModel { /// Parse the comma/space-separated tag text, applying the server's rules so /// the user gets immediate feedback. Returns nil + sets errorMessage on a /// validation failure. - func parsedTags() -> [String]? { + private func parsedTags() -> [String]? { let raw = tagsText .split(whereSeparator: { $0 == "," || $0.isWhitespace }) .map { String($0) } @@ -112,7 +132,17 @@ private extension EditServerViewModel { request.trafficLimitType = trafficLimitType.isEmpty ? .clear : .set(trafficLimitType) request.price = tri(from: priceText, Double.init) request.billingStartDay = tri(from: billingStartDayText, Int.init) - request.expiredAt = hasExpiry ? .set(WireDate.string(from: expiryDate)) : .clear + let selectedDate = hasExpiry ? BillingDate.string(from: expiryDate, timezone: billingTimezone) : nil + let dateChanged = selectedDate != originalExpiryDate + let timezoneChanged = billingTimezone != originalBillingTimezone + if dateChanged || timezoneChanged { + var renewal = UpdateRenewalRequest() + if dateChanged { + if let selectedDate { renewal.expiryDate = .set(selectedDate) } else { renewal.expiryDate = .clear } + } + if timezoneChanged { renewal.billingTimezone = .set(billingTimezone) } + request.renewal = renewal + } if trafficLimitGiBText.trimmingCharacters(in: .whitespaces).isEmpty { request.trafficLimit = .clear } else if let gib = Double(trafficLimitGiBText) { @@ -122,7 +152,7 @@ private extension EditServerViewModel { } /// Empty text => clear; parseable => set; unparseable => leave unchanged. - func tri(from text: String, _ parse: (String) -> T?) -> Tri { + private func tri(from text: String, _ parse: (String) -> T?) -> Tri { let trimmed = text.trimmingCharacters(in: .whitespaces) if trimmed.isEmpty { return .clear } if let value = parse(trimmed) { return .set(value) } @@ -138,6 +168,10 @@ extension EditServerViewModel { errorMessage = String(localized: "Name is required.") return false } + guard TimeZone(identifier: billingTimezone) != nil else { + errorMessage = String(localized: "Choose a valid billing timezone.") + return false + } errorMessage = nil guard let tags = parsedTags() else { return false } diff --git a/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift b/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift index a3e16ade5..b1027c263 100644 --- a/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift +++ b/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift @@ -411,8 +411,7 @@ private extension ServerOverviewSection { @ViewBuilder var expiryText: some View { - if let expiry = config?.expiredDate { - let date = expiry.formatted(date: .abbreviated, time: .omitted) + if let expiry = config?.expiredDate, let date = config?.expiryDisplayDate { let isPast = expiry < Date() Text(isPast ? String(localized: "Expired \(date)") : String(localized: "Expires \(date)")) .font(.footnote.weight(isPast ? .semibold : .regular)) diff --git a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift index 5b06bce5f..0408ec72f 100644 --- a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift +++ b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift @@ -15,6 +15,7 @@ struct EditServerSheet: View { private static let currencies = ["USD", "EUR", "CNY", "JPY", "GBP"] private static let cycles = ["monthly", "quarterly", "yearly"] private static let trafficTypes = ["sum", "up", "down"] + private static let billingTimezones = ["UTC"] + TimeZone.knownTimeZoneIdentifiers.filter { $0 != "UTC" } var body: some View { NavigationStack { @@ -78,9 +79,17 @@ private extension EditServerSheet { } TextField(String(localized: "Billing day (1-28)"), text: $viewModel.billingStartDayText) .keyboardType(.numberPad) + Picker(String(localized: "Billing timezone"), selection: $viewModel.billingTimezone) { + ForEach(Self.billingTimezones, id: \.self) { Text(verbatim: $0).tag($0) } + } Toggle(String(localized: "Has expiry"), isOn: $viewModel.hasExpiry) if viewModel.hasExpiry { DatePicker(String(localized: "Expires"), selection: $viewModel.expiryDate, displayedComponents: .date) + .environment(\.timeZone, viewModel.expiryTimezone) + .environment(\.calendar, viewModel.expiryCalendar) + Text(String(localized: "Valid through the selected date in the billing timezone.")) + .font(.footnote) + .foregroundStyle(.secondary) } TextField(String(localized: "Traffic limit (GiB)"), text: $viewModel.trafficLimitGiBText) .keyboardType(.decimalPad) diff --git a/apps/ios/ServerBeeTests/RenewalDateTests.swift b/apps/ios/ServerBeeTests/RenewalDateTests.swift new file mode 100644 index 000000000..e44543cd0 --- /dev/null +++ b/apps/ios/ServerBeeTests/RenewalDateTests.swift @@ -0,0 +1,115 @@ +import XCTest +@testable import ServerBee + +final class RenewalDateTests: XCTestCase { + private func object(_ request: UpdateServerRequest) throws -> [String: Any] { + let data = try JSONEncoder.snakeCase.encode(request) + return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + func test_serverConfigDecodesSelectedDateAndBillingTimezone() throws { + let json = """ + {"id":"s1","name":"Server","renewal":{"enabled":false, + "billing_timezone":"America/Los_Angeles","expiry_date":"2026-03-08", + "confirmed_expired_at":"2026-03-09T06:59:59Z","deadline_origin":"confirmed", + "occurrence_id":"occurrence-1"}} + """ + let config = try JSONDecoder.snakeCase.decode(ServerConfig.self, from: Data(json.utf8)) + XCTAssertEqual(config.renewal?.expiryDate, "2026-03-08") + XCTAssertEqual(config.renewal?.billingTimezone, "America/Los_Angeles") + XCTAssertEqual(config.renewal?.confirmedExpiredAt, "2026-03-09T06:59:59Z") + XCTAssertEqual(config.renewal?.deadlineOrigin, "confirmed") + XCTAssertEqual(config.renewal?.occurrenceId, "occurrence-1") + XCTAssertEqual(config.renewal?.enabled, false) + } + + func test_renewalDateRequestDistinguishesOmitClearAndSet() throws { + XCTAssertNil(try object(UpdateServerRequest())["renewal"]) + var request = UpdateServerRequest() + request.renewal = UpdateRenewalRequest(expiryDate: .set("2026-03-08")) + var renewal = try XCTUnwrap(try object(request)["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["expiry_date"] as? String, "2026-03-08") + XCTAssertNil(renewal["billing_timezone"]) + XCTAssertNil(try object(request)["expired_at"]) + request.renewal = UpdateRenewalRequest(expiryDate: .clear) + renewal = try XCTUnwrap(try object(request)["renewal"] as? [String: Any]) + XCTAssertTrue(renewal["expiry_date"] is NSNull) + request.renewal = UpdateRenewalRequest(billingTimezone: .set("Asia/Tokyo")) + renewal = try XCTUnwrap(try object(request)["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["billing_timezone"] as? String, "Asia/Tokyo") + XCTAssertNil(renewal["expiry_date"]) + request.renewal = UpdateRenewalRequest(billingTimezone: .clear) + renewal = try XCTUnwrap(try object(request)["renewal"] as? [String: Any]) + XCTAssertTrue(renewal["billing_timezone"] is NSNull) + } + + @MainActor + func test_unchangedFullFormSavePreservesLegacyInstant() throws { + let config = try JSONDecoder.snakeCase.decode(ServerConfig.self, from: Data(""" + {"id":"s1","name":"Server","expired_at":"2026-03-08T00:30:00Z", + "renewal":{"enabled":false,"billing_timezone":"UTC","expiry_date":"2026-03-08", + "confirmed_expired_at":"2026-03-08T00:30:00Z","deadline_origin":"confirmed","occurrence_id":null}} + """.utf8)) + let model = EditServerViewModel() + model.prefill(from: config) + model.name = "Renamed" + model.billingCycle = "quarterly" + model.priceText = "12.50" + let request = try object(model.buildRequest()) + XCTAssertNil(request["expired_at"]) + XCTAssertNil(request["renewal"]) + XCTAssertEqual(request["billing_cycle"] as? String, "quarterly") + } + + @MainActor + func test_timezoneOnlyEditPreservesSelectedDateWithoutConfirmingIt() throws { + let config = try selectedConfig() + let model = EditServerViewModel() + model.prefill(from: config) + model.billingTimezone = "Asia/Tokyo" + XCTAssertEqual(BillingDate.string(from: model.expiryDate, timezone: "Asia/Tokyo"), "2026-03-08") + let request = try object(model.buildRequest()) + let renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["billing_timezone"] as? String, "Asia/Tokyo") + XCTAssertNil(renewal["expiry_date"]) + XCTAssertNil(request["expired_at"]) + } + + @MainActor + func test_changedDateSendsLiteralDateAndClearingSendsNull() throws { + let model = EditServerViewModel() + model.prefill(from: try selectedConfig()) + model.expiryDate = try XCTUnwrap(BillingDate.date(from: "2028-02-29", timezone: model.billingTimezone)) + var request = try object(model.buildRequest()) + var renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["expiry_date"] as? String, "2028-02-29") + XCTAssertNil(renewal["billing_timezone"]) + XCTAssertNil(request["expired_at"]) + model.hasExpiry = false + request = try object(model.buildRequest()) + renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertTrue(renewal["expiry_date"] is NSNull) + XCTAssertNil(request["expired_at"]) + } + + func test_datePickerInstantUsesBillingTimezoneAcrossDST() throws { + let date = try XCTUnwrap(BillingDate.date(from: "2026-03-08", timezone: "America/Los_Angeles")) + XCTAssertEqual(date.timeIntervalSince1970, 1_772_996_400) + XCTAssertEqual(BillingDate.string(from: date, timezone: "America/Los_Angeles"), "2026-03-08") + XCTAssertEqual(BillingDate.string(from: date, timezone: "Asia/Tokyo"), "2026-03-09") + XCTAssertNil(BillingDate.date(from: "2026-02-29", timezone: "UTC")) + } + + func test_selectedDateDisplayUsesStoredTimezoneAtUTCDateBoundary() throws { + let config = try selectedConfig() + XCTAssertEqual(config.expiryLocalDate, "2026-03-08") + } + + private func selectedConfig() throws -> ServerConfig { + try JSONDecoder.snakeCase.decode(ServerConfig.self, from: Data(""" + {"id":"s1","name":"Server","expired_at":"2026-03-09T06:59:59Z", + "renewal":{"enabled":true,"billing_timezone":"America/Los_Angeles","expiry_date":"2026-03-08", + "confirmed_expired_at":"2026-02-09T07:59:59Z","deadline_origin":"projected","occurrence_id":"o2"}} + """.utf8)) + } +} From da601d658e9346941bae87dd69b3804f8a7a722c Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:18:50 +0000 Subject: [PATCH 02/40] fix(ios): preserve billing dates through timezone transitions --- .../ios/ServerBee/Utilities/BillingDate.swift | 10 ++++++---- .../ViewModels/EditServerViewModel.swift | 6 ++++-- .../ios/ServerBeeTests/RenewalDateTests.swift | 20 +++++++++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/apps/ios/ServerBee/Utilities/BillingDate.swift b/apps/ios/ServerBee/Utilities/BillingDate.swift index aba219e33..66866e938 100644 --- a/apps/ios/ServerBee/Utilities/BillingDate.swift +++ b/apps/ios/ServerBee/Utilities/BillingDate.swift @@ -9,10 +9,12 @@ enum BillingDate { } static func date(from string: String, timezone: String) -> Date? { - guard let formatter = formatter(timezone: timezone), - let date = formatter.date(from: string), formatter.string(from: date) == string else { return nil } - // Noon gives the date picker a stable instant even where DST changes at midnight. - return formatter.calendar.date(bySettingHour: 12, minute: 0, second: 0, of: date) + guard let formatter = formatter(timezone: timezone) else { return nil } + // Parse at noon directly: some valid local dates have no midnight at DST start. + formatter.dateFormat = "yyyy-MM-dd HH:mm" + let noon = "\(string) 12:00" + guard let date = formatter.date(from: noon), formatter.string(from: date) == noon else { return nil } + return date } static func display(from date: Date, timezone: String) -> String { diff --git a/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift b/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift index 327064eec..5dc9a771a 100644 --- a/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift @@ -22,10 +22,11 @@ final class EditServerViewModel { var expiryDate = Date() var billingTimezone = "UTC" { didSet { - guard oldValue != billingTimezone, - let date = BillingDate.string(from: expiryDate, timezone: oldValue), + guard lastValidBillingTimezone != billingTimezone, + let date = BillingDate.string(from: expiryDate, timezone: lastValidBillingTimezone), let converted = BillingDate.date(from: date, timezone: billingTimezone) else { return } expiryDate = converted + lastValidBillingTimezone = billingTimezone } } var expiryTimezone: TimeZone { TimeZone(identifier: billingTimezone) ?? .gmt } @@ -43,6 +44,7 @@ final class EditServerViewModel { private var originalTags: [String] = [] private var originalExpiryDate: String? private var originalBillingTimezone = "UTC" + private var lastValidBillingTimezone = "UTC" static let gibibyte = 1_073_741_824.0 diff --git a/apps/ios/ServerBeeTests/RenewalDateTests.swift b/apps/ios/ServerBeeTests/RenewalDateTests.swift index e44543cd0..f9a3cc168 100644 --- a/apps/ios/ServerBeeTests/RenewalDateTests.swift +++ b/apps/ios/ServerBeeTests/RenewalDateTests.swift @@ -75,6 +75,19 @@ final class RenewalDateTests: XCTestCase { XCTAssertNil(request["expired_at"]) } + @MainActor + func test_timezoneEditThroughInvalidIntermediateValuePreservesSelectedDate() throws { + let model = EditServerViewModel() + model.prefill(from: try selectedConfig()) + model.billingTimezone = "Asia/" + model.billingTimezone = "Asia/Tokyo" + XCTAssertEqual(BillingDate.string(from: model.expiryDate, timezone: "Asia/Tokyo"), "2026-03-08") + let request = try object(model.buildRequest()) + let renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["billing_timezone"] as? String, "Asia/Tokyo") + XCTAssertNil(renewal["expiry_date"]) + } + @MainActor func test_changedDateSendsLiteralDateAndClearingSendsNull() throws { let model = EditServerViewModel() @@ -100,6 +113,13 @@ final class RenewalDateTests: XCTestCase { XCTAssertNil(BillingDate.date(from: "2026-02-29", timezone: "UTC")) } + func test_datePickerSupportsLocalDateWhoseMidnightDoesNotExist() throws { + let date = try XCTUnwrap(BillingDate.date(from: "2018-11-04", timezone: "America/Sao_Paulo")) + XCTAssertEqual(BillingDate.string(from: date, timezone: "America/Sao_Paulo"), "2018-11-04") + let utc = ISO8601DateFormatter.shared.date(from: "2018-11-04T14:00:00Z") + XCTAssertEqual(date, utc) + } + func test_selectedDateDisplayUsesStoredTimezoneAtUTCDateBoundary() throws { let config = try selectedConfig() XCTAssertEqual(config.expiryLocalDate, "2026-03-08") From 1a9d1aa1bf9447af9378575b44cec22894e23d37 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:20:10 +0000 Subject: [PATCH 03/40] feat(web): edit renewal dates in the billing timezone --- .../components/server/server-edit-dialog.tsx | 42 +++- .../server/server-edit-renewal.test.tsx | 212 ++++++++++++++++++ apps/web/src/locales/en/servers.json | 3 + apps/web/src/locales/zh/servers.json | 3 + 4 files changed, 257 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/components/server/server-edit-renewal.test.tsx diff --git a/apps/web/src/components/server/server-edit-dialog.tsx b/apps/web/src/components/server/server-edit-dialog.tsx index b8e00d1b9..c852d3260 100644 --- a/apps/web/src/components/server/server-edit-dialog.tsx +++ b/apps/web/src/components/server/server-edit-dialog.tsx @@ -1,7 +1,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import type { TFunction } from 'i18next' import { CalendarIcon, Check, ChevronsUpDown } from 'lucide-react' -import { type FormEvent, useMemo, useReducer, useState } from 'react' +import { type FormEvent, useId, useMemo, useReducer, useState } from 'react' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' import { Button } from '@/components/ui/button' @@ -87,6 +87,7 @@ export function ServerEditDialog({ server, open, onClose }: ServerEditDialogProp interface ServerEditState { billingCycle: string billingStartDay: string + billingTimezone: string countryCode: string currency: string expiredAt: string @@ -111,9 +112,10 @@ function serverEditStateFromServer(server: ServerResponse): ServerEditState { return { billingCycle: server.billing_cycle ?? '', billingStartDay: server.billing_start_day?.toString() ?? '', + billingTimezone: server.renewal?.billing_timezone ?? 'UTC', countryCode: server.geo_manual ? (server.country_code ?? '') : '', currency: server.currency ?? 'USD', - expiredAt: server.expired_at?.slice(0, 10) ?? '', + expiredAt: server.renewal ? (server.renewal.expiry_date ?? '') : (server.expired_at?.slice(0, 10) ?? ''), groupId: server.group_id ?? '', hidden: server.hidden, name: server.name, @@ -261,6 +263,11 @@ function ServerEditBillingFields({ state: ServerEditState t: TFunction }) { + const timezoneListId = useId() + const timezones = useMemo( + () => ['UTC', ...(typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') : [])], + [] + ) return (
@@ -332,6 +339,24 @@ function ServerEditBillingFields({ value={state.expiredAt} /> + + dispatch({ type: 'patch', value: { billingTimezone: e.target.value } })} + placeholder="America/New_York" + type="text" + value={state.billingTimezone} + /> + + {timezones.map((timezone) => ( + +

{t('edit_billing_timezone_hint')}

+
void; ser // override; otherwise we leave it blank and surface the auto-detected value as // a hint, so saving an untouched form never accidentally pins GeoIP. const initialCountryCode = server.geo_manual ? (server.country_code ?? '') : '' + const initialExpiryDate = serverEditStateFromServer(server).expiredAt + const initialBillingTimezone = server.renewal?.billing_timezone ?? 'UTC' const [state, dispatch] = useReducer(serverEditReducer, server, serverEditStateFromServer) const { data: groups } = useQuery({ @@ -414,6 +441,10 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser }) const buildPayload = (): UpdateServerInput => { + const renewal = { + ...(state.expiredAt !== initialExpiryDate && { expiry_date: state.expiredAt || null }), + ...(state.billingTimezone !== initialBillingTimezone && { billing_timezone: state.billingTimezone || null }) + } const payload: UpdateServerInput = { name: state.name, weight: state.weight, @@ -424,10 +455,10 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser price: state.price ? Number.parseFloat(state.price) : null, billing_cycle: state.billingCycle || null, currency: state.currency || null, - expired_at: state.expiredAt ? `${state.expiredAt}T00:00:00Z` : null, traffic_limit: state.trafficLimit ? Math.round(Number.parseFloat(state.trafficLimit) * 1024 ** 3) : null, traffic_limit_type: state.trafficLimitType || null, billing_start_day: state.billingStartDay ? Number.parseInt(state.billingStartDay, 10) : null, + ...(Object.keys(renewal).length > 0 && { renewal }), ...countryCodePatch(state.countryCode, initialCountryCode) } return payload @@ -671,6 +702,11 @@ function DatePickerField({ ariaLabel, onChange, value }: DatePickerFieldProps) { /> + {value && ( + + )}
) } diff --git a/apps/web/src/components/server/server-edit-renewal.test.tsx b/apps/web/src/components/server/server-edit-renewal.test.tsx new file mode 100644 index 000000000..789ac1419 --- /dev/null +++ b/apps/web/src/components/server/server-edit-renewal.test.tsx @@ -0,0 +1,212 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import i18next from 'i18next' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ServerResponse } from '@/lib/api-schema' +import { ServerEditDialog } from './server-edit-dialog' + +const apiBoundary = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn() })) +const MONTH_LABEL = /month/i +const MARCH_TENTH = /March 10.*2026/ +const YEAR_LABEL = /year/i +const CALENDAR_DATES = [ + { date: '2026-01-31', label: /January 31.*2026/, month: '0', year: '2026' }, + { date: '2024-02-29', label: /February 29.*2024/, month: '1', year: '2024' } +] + +// jsdom does not implement the browser animation boundary used by ScrollArea. +Element.prototype.getAnimations = () => [] + +vi.mock('@/lib/api-client', () => ({ api: apiBoundary })) +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })) + +const server = { + agent_authority: { outstanding_offer: null, status: 'claimed' }, + billing_cycle: 'monthly', + billing_start_day: null, + capabilities: 56, + created_at: '2026-04-18T00:00:00Z', + currency: 'USD', + expired_at: '2026-03-09T03:59:59Z', + features: [], + geo_manual: false, + group_id: null, + has_token: true, + hidden: false, + id: 'server-1', + name: 'New York Edge', + price: null, + protocol_version: 2, + public_remark: null, + remark: null, + renewal: { + billing_timezone: 'America/New_York', + confirmed_expired_at: '2026-02-09T04:59:59Z', + deadline_origin: 'projected', + enabled: false, + expiry_date: '2026-03-08', + occurrence_id: 'occurrence-1' + }, + traffic_limit: null, + traffic_limit_type: 'sum', + updated_at: '2026-04-18T00:00:00Z', + weight: 100 +} satisfies ServerResponse + +function renderEditor(value: ServerResponse = server) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + + ) +} + +beforeEach(() => { + apiBoundary.get.mockResolvedValue([]) + apiBoundary.put.mockResolvedValue(server) +}) + +afterEach(async () => { + cleanup() + await i18next.changeLanguage('en') + vi.clearAllMocks() +}) + +describe('server renewal date editing', () => { + it('displays the server-selected local expiry date instead of its UTC day', () => { + renderEditor() + + expect(screen.getByRole('button', { name: 'Expiration date' })).toHaveTextContent('2026-03-08') + }) + + it('preserves the existing deadline when saving an unrelated name change', async () => { + renderEditor() + fireEvent.change(screen.getByRole('textbox', { name: 'Name' }), { target: { value: 'Renamed Edge' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + const [path, payload] = apiBoundary.put.mock.calls[0] + expect(path).toBe('/api/servers/server-1') + expect(payload).toMatchObject({ name: 'Renamed Edge' }) + expect(payload).not.toHaveProperty('expired_at') + expect(payload).not.toHaveProperty('renewal') + }) + + it('submits an explicitly selected expiry as a local date without a UTC timestamp', async () => { + renderEditor() + fireEvent.click(screen.getByRole('button', { name: 'Expiration date' })) + fireEvent.change(await screen.findByRole('combobox', { name: MONTH_LABEL }), { target: { value: '2' } }) + fireEvent.click(screen.getByRole('button', { name: MARCH_TENTH })) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + const payload = apiBoundary.put.mock.calls[0][1] + expect(payload).toMatchObject({ renewal: { expiry_date: '2026-03-10' } }) + expect(payload).not.toHaveProperty('expired_at') + expect(payload.renewal).not.toHaveProperty('billing_timezone') + }) + + it('changes only the billing timezone without resubmitting or moving the selected date', async () => { + renderEditor() + const timezone = screen.getByLabelText('Billing timezone') + expect(timezone).toHaveValue('America/New_York') + fireEvent.change(timezone, { target: { value: 'Asia/Tokyo' } }) + expect(screen.getByRole('button', { name: 'Expiration date' })).toHaveTextContent('2026-03-08') + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + const payload = apiBoundary.put.mock.calls[0][1] + expect(payload.renewal).toEqual({ billing_timezone: 'Asia/Tokyo' }) + expect(payload).not.toHaveProperty('expired_at') + }) + + it('sends an explicit null when the operator clears the expiry date', async () => { + renderEditor() + fireEvent.click(screen.getByRole('button', { name: 'Clear expiration date' })) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1].renewal).toEqual({ expiry_date: null }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('expired_at') + }) + + it('keeps a legacy instant intact when the full form is saved unchanged', async () => { + const { renewal: _renewal, ...legacy } = server + renderEditor({ ...legacy, expired_at: '2026-03-08T12:34:56Z' }) + expect(screen.getByLabelText('Billing timezone')).toHaveValue('UTC') + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('expired_at') + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + }) + + it('keeps expiry confirmation untouched when only the cost interval changes', async () => { + renderEditor() + fireEvent.click(screen.getByText('Monthly')) + const interval = await screen.findByRole('option', { name: 'Quarterly' }) + fireEvent.mouseMove(interval) + fireEvent.click(interval) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).toMatchObject({ billing_cycle: 'quarterly' }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + }) + + it('omits renewal fields after the operator restores the original timezone', async () => { + renderEditor() + const timezone = screen.getByLabelText('Billing timezone') + fireEvent.change(timezone, { target: { value: 'Asia/Tokyo' } }) + fireEvent.change(timezone, { target: { value: 'America/New_York' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + }) + + it('submits date and timezone clearing together as explicit null values', async () => { + renderEditor() + fireEvent.click(screen.getByRole('button', { name: 'Clear expiration date' })) + fireEvent.change(screen.getByLabelText('Billing timezone'), { target: { value: '' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1].renewal).toEqual({ billing_timezone: null, expiry_date: null }) + }) + + it('leaves renewal confirmation untouched when only price changes', async () => { + renderEditor() + fireEvent.change(screen.getByRole('spinbutton', { name: 'Price' }), { target: { value: '12.50' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).toMatchObject({ price: 12.5 }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + }) + + it.each( + CALENDAR_DATES + )('encodes the selected calendar date $date without browser timezone conversion', async (date) => { + renderEditor() + fireEvent.click(screen.getByRole('button', { name: 'Expiration date' })) + fireEvent.change(await screen.findByRole('combobox', { name: MONTH_LABEL }), { target: { value: date.month } }) + fireEvent.change(screen.getByRole('combobox', { name: YEAR_LABEL }), { target: { value: date.year } }) + fireEvent.click(screen.getByRole('button', { name: date.label })) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1].renewal).toEqual({ expiry_date: date.date }) + }) + + it('localizes the date and billing timezone controls in Chinese', async () => { + await i18next.changeLanguage('zh') + renderEditor() + + expect(screen.getByRole('button', { name: '到期日期' })).toHaveTextContent('2026-03-08') + expect(screen.getByLabelText('账单时区')).toHaveValue('America/New_York') + expect(screen.getByText('请选择 IANA 时区。服务有效期包含此时区内所选到期日期的整天。')).toBeInTheDocument() + expect(screen.getByRole('button', { name: '清除到期日期' })).toBeInTheDocument() + }) +}) diff --git a/apps/web/src/locales/en/servers.json b/apps/web/src/locales/en/servers.json index 08126e3bd..e7611f5d4 100644 --- a/apps/web/src/locales/en/servers.json +++ b/apps/web/src/locales/en/servers.json @@ -272,6 +272,9 @@ "edit_cycle_yearly": "Yearly", "edit_expiration": "Expiration date", "edit_expiration_placeholder": "YYYY-MM-DD", + "edit_expiration_clear": "Clear expiration date", + "edit_billing_timezone": "Billing timezone", + "edit_billing_timezone_hint": "Use an IANA timezone. Service validity includes the entire selected expiry date in this timezone.", "edit_traffic_limit": "Traffic limit (GB)", "edit_unlimited": "Unlimited", "edit_limit_type": "Limit type", diff --git a/apps/web/src/locales/zh/servers.json b/apps/web/src/locales/zh/servers.json index 684fd6d0b..d915cd8f4 100644 --- a/apps/web/src/locales/zh/servers.json +++ b/apps/web/src/locales/zh/servers.json @@ -272,6 +272,9 @@ "edit_cycle_yearly": "年付", "edit_expiration": "到期日期", "edit_expiration_placeholder": "YYYY-MM-DD", + "edit_expiration_clear": "清除到期日期", + "edit_billing_timezone": "账单时区", + "edit_billing_timezone_hint": "请选择 IANA 时区。服务有效期包含此时区内所选到期日期的整天。", "edit_traffic_limit": "流量限制 (GB)", "edit_unlimited": "不限", "edit_limit_type": "限制类型", From fe4bfefa07c77bc8ec8e4ca908932d10abf6f3ec Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:22:21 +0000 Subject: [PATCH 04/40] feat(renewal): store billing calendar dates without changing legacy saves --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 4 + crates/server/src/dev_demo.rs | 1 + crates/server/src/entity/server.rs | 2 + .../m20261005_000086_renewal_dates.rs | 41 ++ crates/server/src/migration/mod.rs | 3 + crates/server/src/openapi.rs | 3 + crates/server/src/router/api/server.rs | 8 + crates/server/src/service/mod.rs | 2 + crates/server/src/service/renewal.rs | 200 +++++++++ crates/server/src/service/server.rs | 20 +- .../server/src/service/server_onboarding.rs | 28 +- .../server/tests/public_status_anonymous.rs | 1 + crates/server/tests/public_status_gating.rs | 1 + .../public_status_ip_quality_redaction.rs | 1 + .../server/tests/public_status_redaction.rs | 1 + .../public_status_redaction_authenticated.rs | 1 + crates/server/tests/public_status_scope.rs | 1 + crates/server/tests/renewal_dates.rs | 389 ++++++++++++++++++ 19 files changed, 702 insertions(+), 6 deletions(-) create mode 100644 crates/server/src/migration/m20261005_000086_renewal_dates.rs create mode 100644 crates/server/src/service/renewal.rs create mode 100644 crates/server/tests/renewal_dates.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e9b94a0fe..ccdc202e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -236,6 +236,7 @@ jobs: --test router_monitoring --test router_probes_extra --test router_security_rate + --test renewal_dates --test router_server_crud --test router_server_extra --test router_server_extra2 diff --git a/CHANGELOG.md b/CHANGELOG.md index f6bb1b77d..5d0bfc47d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Billing-calendar renewal dates** -- Web and native iOS administrators can edit a local expiry date in its stored IANA billing timezone. The Server preserves historical expiry instants on unchanged saves and applies the complete local expiry day to explicit date changes + ### Fixed - **IP Quality capability guidance matches Agent-owned permissions** -- A compact disabled notice opens a dialog explaining permanent configuration and temporary host-local grants instead of pointing to a nonexistent server-side toggle. Each command has a copy button with clipboard feedback. Manual checks use the Agent-reported capability, and an unavailable report is shown separately from a disabled capability diff --git a/crates/server/src/dev_demo.rs b/crates/server/src/dev_demo.rs index 71df379ea..c8a64336c 100644 --- a/crates/server/src/dev_demo.rs +++ b/crates/server/src/dev_demo.rs @@ -560,6 +560,7 @@ async fn seed_servers(db: &DatabaseConnection, now: chrono::DateTime) -> Re price: Set(Some(spec.price)), billing_cycle: Set(Some("monthly".to_string())), currency: Set(Some("USD".to_string())), + renewal_state: Set(None), expired_at: Set(None), traffic_limit: Set(Some((spec.mem_gib + spec.disk_gib / 10) * 100 * GIB)), traffic_limit_type: Set(Some("monthly".to_string())), diff --git a/crates/server/src/entity/server.rs b/crates/server/src/entity/server.rs index 6efc04469..89decbfa1 100644 --- a/crates/server/src/entity/server.rs +++ b/crates/server/src/entity/server.rs @@ -38,6 +38,8 @@ pub struct Model { pub billing_cycle: Option, pub currency: Option, pub expired_at: Option, + /// Internal renewal state; public projections never serialize this column. + pub renewal_state: Option, pub traffic_limit: Option, pub traffic_limit_type: Option, pub billing_start_day: Option, diff --git a/crates/server/src/migration/m20261005_000086_renewal_dates.rs b/crates/server/src/migration/m20261005_000086_renewal_dates.rs new file mode 100644 index 000000000..ff50e3a91 --- /dev/null +++ b/crates/server/src/migration/m20261005_000086_renewal_dates.rs @@ -0,0 +1,41 @@ +use chrono::{DateTime, Utc}; +use sea_orm_migration::prelude::*; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + let db = manager.get_connection(); + db.execute_unprepared("ALTER TABLE servers ADD COLUMN renewal_state TEXT") + .await?; + // Encode historical instants with the same RFC3339 representation used + // by the application, without rewriting the predecessor expiry column. + let backend = db.get_database_backend(); + for row in db + .query_all(sea_orm::Statement::from_string( + backend, + "SELECT id, expired_at FROM servers", + )) + .await? + { + let id: String = row.try_get("", "id")?; + let expiry: Option> = row.try_get("", "expired_at")?; + let state = + serde_json::json!({"billing_timezone":"UTC", "confirmed_expired_at":expiry}) + .to_string(); + db.execute(sea_orm::Statement::from_sql_and_values( + backend, + "UPDATE servers SET renewal_state = ? WHERE id = ?", + [state.into(), id.into()], + )) + .await?; + } + Ok(()) + } + + async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> { + Ok(()) + } +} diff --git a/crates/server/src/migration/mod.rs b/crates/server/src/migration/mod.rs index 02efb6da8..bd5550487 100644 --- a/crates/server/src/migration/mod.rs +++ b/crates/server/src/migration/mod.rs @@ -56,6 +56,8 @@ mod m20261003_000083_task_runs; mod m20261003_000084_alert_event_intents; mod m20261003_000085_security_event_admission; +mod m20261005_000086_renewal_dates; + pub struct Migrator; impl MigratorTrait for Migrator { @@ -115,6 +117,7 @@ impl MigratorTrait for Migrator { Box::new(m20261003_000083_task_runs::Migration), Box::new(m20261003_000084_alert_event_intents::Migration), Box::new(m20261003_000085_security_event_admission::Migration), + Box::new(m20261005_000086_renewal_dates::Migration), ] } } diff --git a/crates/server/src/openapi.rs b/crates/server/src/openapi.rs index 09e7c80d3..4f17ebb6b 100644 --- a/crates/server/src/openapi.rs +++ b/crates/server/src/openapi.rs @@ -290,6 +290,9 @@ impl Modify for SecurityAddon { crate::service::upgrade_release::LatestAgentVersionResponse, crate::router::api::agent::RegisterRequest, crate::router::api::agent::RegisterResponse, + crate::service::renewal::DeadlineOrigin, + crate::service::renewal::RenewalProjection, + crate::service::renewal::RenewalInput, // servers crate::router::api::server::ServerResponse, crate::router::api::server::TemporaryGrantDto, diff --git a/crates/server/src/router/api/server.rs b/crates/server/src/router/api/server.rs index 2618b904e..9f7a56940 100644 --- a/crates/server/src/router/api/server.rs +++ b/crates/server/src/router/api/server.rs @@ -125,6 +125,8 @@ pub struct ServerResponse { billing_cycle: Option, currency: Option, expired_at: Option>, + #[schema(required = false)] + renewal: crate::service::renewal::RenewalProjection, traffic_limit: Option, traffic_limit_type: Option, billing_start_day: Option, @@ -154,6 +156,7 @@ pub struct ServerResponse { #[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] pub struct CreateServerRequest { + pub renewal: Option, pub onboarding_request_id: String, pub name: String, #[serde(default)] @@ -301,7 +304,9 @@ fn build_server_response( let has_token = agent_authority.status == AgentAuthorityStatus::Claimed; let outstanding_enrollment = agent_authority.outstanding_offer.clone(); + let renewal = crate::service::renewal::RenewalState::from_server(&s).projection(s.expired_at); ServerResponse { + renewal, id: s.id, name: s.name, cpu_name: s.cpu_name, @@ -522,6 +527,7 @@ async fn create_server( billing_cycle: body.billing_cycle, billing_start_day: body.billing_start_day, expired_at: body.expired_at, + renewal: body.renewal, traffic_limit: body.traffic_limit, traffic_limit_type: body.traffic_limit_type, }, @@ -1564,6 +1570,7 @@ mod cleanup_tests { billing_cycle: None, currency: None, expired_at: None, + renewal_state: None, traffic_limit: None, traffic_limit_type: None, billing_start_day: None, @@ -1692,6 +1699,7 @@ mod delete_audit_tests { billing_cycle: None, currency: None, expired_at: None, + renewal_state: None, traffic_limit: None, traffic_limit_type: None, billing_start_day: None, diff --git a/crates/server/src/service/mod.rs b/crates/server/src/service/mod.rs index d7251b88b..675992585 100644 --- a/crates/server/src/service/mod.rs +++ b/crates/server/src/service/mod.rs @@ -56,3 +56,5 @@ pub mod mobile_recovery_grant; pub(crate) mod task_notification; pub(crate) mod alert_event_intents; + +pub mod renewal; diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs new file mode 100644 index 000000000..ce03ca118 --- /dev/null +++ b/crates/server/src/service/renewal.rs @@ -0,0 +1,200 @@ +//! Server-owned billing calendar contract. Clients submit dates, never UTC boundaries. +use crate::{entity::server, error::AppError}; +use chrono::{DateTime, Duration, NaiveDate, TimeZone, Utc}; +use chrono_tz::Tz; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct RenewalState { + pub billing_timezone: String, + pub confirmed_expired_at: Option>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum DeadlineOrigin { + Confirmed, + Projected, + Frozen, +} + +#[derive(Debug, Serialize, utoipa::ToSchema)] +pub struct RenewalProjection { + pub enabled: bool, + pub billing_timezone: String, + pub expiry_date: Option, + pub confirmed_expired_at: Option>, + pub deadline_origin: DeadlineOrigin, + pub occurrence_id: Option, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize, utoipa::ToSchema)] +pub struct RenewalInput { + #[serde( + default, + deserialize_with = "super::server::deserialize_optional_nullable" + )] + pub billing_timezone: Option>, + #[serde( + default, + deserialize_with = "super::server::deserialize_optional_nullable" + )] + pub expiry_date: Option>, +} + +impl RenewalState { + pub fn from_server(model: &server::Model) -> Self { + model + .renewal_state + .as_deref() + .and_then(|s| serde_json::from_str(s).ok()) + .unwrap_or_else(|| Self { + billing_timezone: "UTC".into(), + confirmed_expired_at: model.expired_at, + }) + } + pub fn projection(&self, deadline: Option>) -> RenewalProjection { + RenewalProjection { + enabled: false, + billing_timezone: self.billing_timezone.clone(), + expiry_date: selected_date(deadline, &self.billing_timezone).map(|d| d.to_string()), + confirmed_expired_at: self.confirmed_expired_at, + deadline_origin: DeadlineOrigin::Confirmed, + occurrence_id: None, + } + } +} + +pub fn selected_date(deadline: Option>, timezone: &str) -> Option { + let tz: Tz = timezone.parse().ok()?; + deadline.map(|instant| instant.with_timezone(&tz).date_naive()) +} + +pub fn date_boundary(date: NaiveDate, timezone: &str) -> Result, AppError> { + let tz: Tz = timezone.parse().map_err(|_| { + AppError::Validation("billing_timezone must be a valid IANA timezone".into()) + })?; + let start = date.and_hms_opt(0, 0, 0).unwrap(); + if !(0..1440).any(|minute| { + tz.from_local_datetime(&(start + Duration::minutes(minute))) + .earliest() + .is_some() + }) { + return Err(AppError::Validation( + "expiry_date does not exist in billing_timezone".into(), + )); + } + let next = date + .succ_opt() + .ok_or_else(|| AppError::Validation("expiry_date is out of range".into()))?; + // A few IANA zones transition at midnight. The boundary is the first instant + // of the following local date, choosing the earlier occurrence on overlap. + let midnight = next.and_hms_opt(0, 0, 0).unwrap(); + for minutes in 0..=1440 { + if let Some(boundary) = tz + .from_local_datetime(&(midnight + Duration::minutes(minutes))) + .earliest() + { + return Ok(boundary.with_timezone(&Utc) - Duration::nanoseconds(1)); + } + } + Err(AppError::Validation( + "expiry_date has no valid local boundary".into(), + )) +} + +pub fn apply_edit( + model: &server::Model, + input: Option<&RenewalInput>, + legacy: Option>>, +) -> Result<(RenewalState, Option>), AppError> { + apply_calendar( + RenewalState::from_server(model), + model.expired_at, + input, + legacy, + ) +} + +pub fn apply_initial( + input: Option<&RenewalInput>, + legacy: Option>, +) -> Result<(RenewalState, Option>), AppError> { + // Preserve old create payload instants. Calendar input uses the new contract. + apply_calendar( + RenewalState { + billing_timezone: "UTC".into(), + confirmed_expired_at: legacy, + }, + legacy, + input, + None, + ) +} + +fn apply_calendar( + mut state: RenewalState, + original: Option>, + input: Option<&RenewalInput>, + legacy: Option>>, +) -> Result<(RenewalState, Option>), AppError> { + let old_date = selected_date(original, &state.billing_timezone); + let mut deadline = original; + let timezone = input.and_then(|i| i.billing_timezone.as_ref()); + if let Some(zone) = timezone { + let zone = zone.as_deref().unwrap_or("UTC"); + zone.parse::().map_err(|_| { + AppError::Validation("billing_timezone must be a valid IANA timezone".into()) + })?; + if zone != state.billing_timezone { + state.billing_timezone = zone.into(); + deadline = old_date.map(|d| date_boundary(d, zone)).transpose()?; + } + } + let date = input.and_then(|i| i.expiry_date.as_ref()); + if date.is_some() && legacy.is_some() { + return Err(AppError::Validation( + "expiry_date and expired_at cannot be submitted together".into(), + )); + } + if let Some(value) = date { + let date = value + .as_deref() + .map(|s| { + let date = NaiveDate::parse_from_str(s, "%Y-%m-%d") + .map_err(|_| AppError::Validation("expiry_date must be YYYY-MM-DD".into()))?; + if date.to_string() != s { + return Err(AppError::Validation( + "expiry_date must be YYYY-MM-DD".into(), + )); + } + Ok(date) + }) + .transpose()?; + if date != old_date { + deadline = date + .map(|d| date_boundary(d, &state.billing_timezone)) + .transpose()?; + state.confirmed_expired_at = deadline; + } + } else if let Some(value) = legacy { + // Existing iOS repeats the original instant; old Web reconstructs UTC + // midnight from its date prefix. Neither is an operator date edit. + let unchanged = value == original + || matches!((value, original), (Some(new), Some(old)) if new.date_naive() == old.date_naive() && new.time() == chrono::NaiveTime::MIN); + if !unchanged { + let date = value.and_then(|instant| { + if instant.time() == chrono::NaiveTime::MIN { + Some(instant.date_naive()) + } else { + selected_date(Some(instant), &state.billing_timezone) + } + }); + deadline = date + .map(|d| date_boundary(d, &state.billing_timezone)) + .transpose()?; + state.confirmed_expired_at = deadline; + } + } + Ok((state, deadline)) +} diff --git a/crates/server/src/service/server.rs b/crates/server/src/service/server.rs index 1c36f9cb6..26ecc6481 100644 --- a/crates/server/src/service/server.rs +++ b/crates/server/src/service/server.rs @@ -9,7 +9,9 @@ use serverbee_common::types::SystemInfo; /// Deserialize a field that distinguishes between absent (None), explicit null (Some(None)), /// and a present value (Some(Some(v))). -fn deserialize_optional_nullable<'de, D, T>(deserializer: D) -> Result>, D::Error> +pub(super) fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> where D: Deserializer<'de>, T: Deserialize<'de>, @@ -21,6 +23,7 @@ where #[derive(Debug, Deserialize, utoipa::ToSchema)] pub struct UpdateServerInput { + pub renewal: Option, pub name: Option, #[serde(default, deserialize_with = "deserialize_optional_nullable")] pub group_id: Option>, @@ -81,7 +84,13 @@ impl ServerService { let model = Self::get_server(db, id).await?; Self::validate_update_input(&input)?; + let (renewal, deadline) = + super::renewal::apply_edit(&model, input.renewal.as_ref(), input.expired_at)?; let mut active: server::ActiveModel = model.into(); + active.renewal_state = Set(Some( + serde_json::to_string(&renewal).map_err(|e| AppError::Validation(e.to_string()))?, + )); + active.expired_at = Set(deadline); if let Some(name) = input.name { active.name = Set(name); @@ -125,9 +134,6 @@ impl ServerService { if let Some(currency) = input.currency { active.currency = Set(currency); } - if let Some(expired_at) = input.expired_at { - active.expired_at = Set(expired_at); - } if let Some(traffic_limit) = input.traffic_limit { active.traffic_limit = Set(traffic_limit); } @@ -390,6 +396,7 @@ mod tests { billing_cycle: None, currency: None, expired_at: None, + renewal: None, traffic_limit: None, traffic_limit_type: None, billing_start_day: None, @@ -758,7 +765,10 @@ mod tests { .expect("clear should update"); assert_eq!(cleared.country_code, None); assert_eq!(cleared.region, None); - assert!(!cleared.geo_manual, "manual override flag should be cleared"); + assert!( + !cleared.geo_manual, + "manual override flag should be cleared" + ); } #[tokio::test] diff --git a/crates/server/src/service/server_onboarding.rs b/crates/server/src/service/server_onboarding.rs index 84af96ec8..14faa8fd5 100644 --- a/crates/server/src/service/server_onboarding.rs +++ b/crates/server/src/service/server_onboarding.rs @@ -42,6 +42,7 @@ impl OnboardingRequestId { #[derive(Clone, Debug, Serialize)] pub struct ServerProfile { + pub renewal: Option, pub name: String, pub group_id: Option, pub tags: Vec, @@ -210,6 +211,7 @@ impl ServerOnboarding { price: Set(normalized.price), billing_cycle: Set(normalized.billing_cycle.clone()), currency: Set(normalized.currency.clone()), + renewal_state: Set(normalized.renewal_state.clone()), expired_at: Set(normalized.expired_at), traffic_limit: Set(normalized.traffic_limit), traffic_limit_type: Set(normalized.traffic_limit_type.clone()), @@ -279,6 +281,8 @@ impl ServerOnboarding { #[derive(Serialize)] struct NormalizedProfile { + #[serde(skip_serializing_if = "Option::is_none")] + renewal_state: Option, name: String, group_id: Option, tags: Vec, @@ -334,7 +338,28 @@ impl NormalizedProfile { )); } + if profile + .renewal + .as_ref() + .is_some_and(|input| input.expiry_date.is_some()) + && profile.expired_at.is_some() + { + return Err(OnboardingError::Validation( + "expiry_date and expired_at cannot be submitted together".into(), + )); + } + let (renewal, expired_at) = + super::renewal::apply_initial(profile.renewal.as_ref(), profile.expired_at) + .map_err(|e| OnboardingError::Validation(e.to_string()))?; + // Preserve the predecessor canonical hash for legacy onboarding retries. + let renewal_state = profile + .renewal + .as_ref() + .map(|_| serde_json::to_string(&renewal)) + .transpose() + .map_err(|e| OnboardingError::Validation(e.to_string()))?; Ok(Self { + renewal_state, name, group_id: normalize_optional(profile.group_id), tags: server_tag_service::validate_tags(&profile.tags) @@ -345,7 +370,7 @@ impl NormalizedProfile { currency: normalize_optional(profile.currency), billing_cycle: normalize_optional(profile.billing_cycle), billing_start_day: profile.billing_start_day, - expired_at: profile.expired_at, + expired_at, traffic_limit: profile.traffic_limit, traffic_limit_type: normalize_optional(profile.traffic_limit_type), }) @@ -433,6 +458,7 @@ mod tests { billing_cycle: None, billing_start_day: None, expired_at: None, + renewal: None, traffic_limit: None, traffic_limit_type: None, }, diff --git a/crates/server/tests/public_status_anonymous.rs b/crates/server/tests/public_status_anonymous.rs index 7a7e7a919..11883e2f4 100644 --- a/crates/server/tests/public_status_anonymous.rs +++ b/crates/server/tests/public_status_anonymous.rs @@ -138,6 +138,7 @@ pub(crate) async fn insert_server( billing_cycle: Set(None), currency: Set(None), expired_at: Set(None), + renewal_state: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), billing_start_day: Set(None), diff --git a/crates/server/tests/public_status_gating.rs b/crates/server/tests/public_status_gating.rs index ab376e123..7d87b2c82 100644 --- a/crates/server/tests/public_status_gating.rs +++ b/crates/server/tests/public_status_gating.rs @@ -106,6 +106,7 @@ async fn insert_minimal_server(db: &sea_orm::DatabaseConnection, id: &str) { billing_cycle: Set(None), currency: Set(None), expired_at: Set(None), + renewal_state: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), billing_start_day: Set(None), diff --git a/crates/server/tests/public_status_ip_quality_redaction.rs b/crates/server/tests/public_status_ip_quality_redaction.rs index f51348956..9ec2cfad6 100644 --- a/crates/server/tests/public_status_ip_quality_redaction.rs +++ b/crates/server/tests/public_status_ip_quality_redaction.rs @@ -139,6 +139,7 @@ async fn insert_minimal_server(db: &sea_orm::DatabaseConnection, id: &str) { billing_cycle: Set(None), currency: Set(None), expired_at: Set(None), + renewal_state: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), billing_start_day: Set(None), diff --git a/crates/server/tests/public_status_redaction.rs b/crates/server/tests/public_status_redaction.rs index 34b8dc8eb..6b9fb4a7c 100644 --- a/crates/server/tests/public_status_redaction.rs +++ b/crates/server/tests/public_status_redaction.rs @@ -129,6 +129,7 @@ async fn insert_server_with_ips( billing_cycle: Set(None), currency: Set(None), expired_at: Set(None), + renewal_state: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), billing_start_day: Set(None), diff --git a/crates/server/tests/public_status_redaction_authenticated.rs b/crates/server/tests/public_status_redaction_authenticated.rs index b8c2eabde..64d521cf9 100644 --- a/crates/server/tests/public_status_redaction_authenticated.rs +++ b/crates/server/tests/public_status_redaction_authenticated.rs @@ -127,6 +127,7 @@ async fn insert_server_with_ips( billing_cycle: Set(None), currency: Set(None), expired_at: Set(None), + renewal_state: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), billing_start_day: Set(None), diff --git a/crates/server/tests/public_status_scope.rs b/crates/server/tests/public_status_scope.rs index d752d34be..a99aacb10 100644 --- a/crates/server/tests/public_status_scope.rs +++ b/crates/server/tests/public_status_scope.rs @@ -116,6 +116,7 @@ async fn insert_server_with_hidden( billing_cycle: Set(None), currency: Set(None), expired_at: Set(None), + renewal_state: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), billing_start_day: Set(None), diff --git a/crates/server/tests/renewal_dates.rs b/crates/server/tests/renewal_dates.rs new file mode 100644 index 000000000..948cc37cc --- /dev/null +++ b/crates/server/tests/renewal_dates.rs @@ -0,0 +1,389 @@ +//! Billing-calendar edits through production HTTP with a real SQLite database. +mod common; +use common::{create_server, http_client, login_admin, start_test_server}; +use serde_json::{Value, json}; + +#[tokio::test] +async fn manual_date_uses_complete_day_in_stored_billing_timezone() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "calendar-host").await; + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json( + &json!({"renewal":{"expiry_date":"2026-03-08","billing_timezone":"America/New_York"}}), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + assert_eq!(body["data"]["expired_at"], "2026-03-09T03:59:59.999999999Z"); + assert_eq!(body["data"]["renewal"]["expiry_date"], "2026-03-08"); + assert_eq!( + body["data"]["renewal"]["billing_timezone"], + "America/New_York" + ); + assert_eq!(body["data"]["renewal"]["enabled"], false); + assert_eq!(body["data"]["renewal"]["deadline_origin"], "confirmed"); +} + +#[tokio::test] +async fn onboarding_calendar_is_atomic_and_idempotent() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let request = json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":"date-create","renewal":{"expiry_date":"2026-01-31","billing_timezone":"Asia/Tokyo"}}); + let body: Value = admin + .post(format!("{base}/api/servers")) + .json(&request) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let id = body["data"]["server_id"].as_str().unwrap(); + let detail: Value = admin + .get(format!("{base}/api/servers/{id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!( + detail["data"]["expired_at"], + "2026-01-31T14:59:59.999999999Z" + ); + assert_eq!(detail["data"]["renewal"]["expiry_date"], "2026-01-31"); + let replay: Value = admin + .post(format!("{base}/api/servers")) + .json(&request) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(replay["data"]["server_id"], id); +} + +/// Reopen the on-disk database and serve production routes with fresh AppState. +async fn serve_database(path: &std::path::Path) -> String { + use serverbee_server::{config::AppConfig, router::create_router, state::AppState}; + let db = sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display())) + .await + .unwrap(); + let mut config = AppConfig::default(); + config.auth.secure_cookie = false; + config.server.data_dir = path.parent().unwrap().to_str().unwrap().into(); + let state = AppState::new(db, config).await.unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve( + listener, + create_router(state).into_make_service_with_connect_info::(), + ) + .await + .unwrap(); + }); + base +} + +async fn predecessor_database() -> (tempfile::TempDir, std::path::PathBuf) { + use sea_orm::ConnectionTrait; + use sea_orm_migration::MigratorTrait; + use serverbee_server::{migration::Migrator, service::auth::AuthService}; + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("legacy.db"); + let db = sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display())) + .await + .unwrap(); + let steps = Migrator::migrations().len() as u32 - 1; + Migrator::up(&db, Some(steps)).await.unwrap(); + let user = AuthService::create_user(&db, "admin", "testpass", "admin") + .await + .unwrap(); + db.execute_unprepared("INSERT INTO servers (id, name, capabilities, protocol_version, expired_at, created_at, updated_at) VALUES ('legacy-host','legacy-host',56,1,'2026-04-18 17:42:13+00:00',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)").await.unwrap(); + db.execute(sea_orm::Statement::from_sql_and_values(sea_orm::DatabaseBackend::Sqlite, + "INSERT INTO server_onboarding_requests (id, actor_id, request_id, normalized_input_hash, server_id, created_at) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)", + ["legacy-request".into(), user.id.into(), "00000000-0000-4000-8000-000000000001".into(), "n9aQOl2YNKimgYTxqUR6lkxuN9Wj04TjkISmtiifE_M".into(), "legacy-host".into()])).await.unwrap(); + Migrator::up(&db, None).await.unwrap(); + db.close().await.unwrap(); + (tmp, path) +} + +#[tokio::test] +async fn predecessor_migration_and_real_legacy_full_forms_preserve_instant_after_reopen() { + let (_tmp, path) = predecessor_database().await; + let base = serve_database(&path).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let original: Value = admin + .get(format!("{base}/api/servers/legacy-host")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(original["data"]["expired_at"], "2026-04-18T17:42:13Z"); + assert_eq!(original["data"]["renewal"]["enabled"], false); + assert_eq!(original["data"]["renewal"]["billing_timezone"], "UTC"); + for payload in [ + json!({"name":"ios-save","price":12.0,"expired_at":"2026-04-18T17:42:13Z","billing_cycle":"monthly"}), + json!({"name":"web-save","price":13.0,"expired_at":"2026-04-18T00:00:00.000Z","billing_cycle":"monthly"}), + json!({"name":"new-save","renewal":{"expiry_date":"2026-04-18","billing_timezone":"UTC"}}), + ] { + let response = admin + .put(format!("{base}/api/servers/legacy-host")) + .json(&payload) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + assert_eq!(body["data"]["expired_at"], "2026-04-18T17:42:13Z"); + assert_eq!( + body["data"]["renewal"]["confirmed_expired_at"], + "2026-04-18T17:42:13Z" + ); + } + let reopened = serve_database(&path).await; + let admin = http_client(); + login_admin(&admin, &reopened).await; + let persisted: Value = admin + .get(format!("{reopened}/api/servers/legacy-host")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(persisted["data"]["expired_at"], "2026-04-18T17:42:13Z"); + assert_eq!(persisted["data"]["renewal"]["expiry_date"], "2026-04-18"); +} + +#[tokio::test] +async fn nonexistent_iana_calendar_date_is_rejected_atomically() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "unchanged-name").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"name":"must-not-persist","renewal":{"expiry_date":"2011-12-30","billing_timezone":"Pacific/Apia"}})) + .send().await.unwrap(); + assert_eq!( + response.status(), + 422, + "Apia skipped this complete calendar date" + ); + let detail: Value = admin + .get(format!("{base}/api/servers/{id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(detail["data"]["name"], "unchanged-name"); + assert_eq!(detail["data"]["expired_at"], Value::Null); +} + +#[tokio::test] +async fn invalid_calendar_inputs_cannot_partially_change_the_server() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "original").await; + for renewal in [ + json!({"expiry_date":"2026-02-30","billing_timezone":"UTC"}), + json!({"expiry_date":"2026-01-31","billing_timezone":"Mars/Olympus"}), + json!({"expiry_date":"2026-1-31"}), + ] { + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"name":"partial","renewal":renewal})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 422); + } + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"expiry_date":"2026-01-31"},"expired_at":"2026-01-31T00:00:00Z"})) + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + 422, + "simultaneous date contracts are ambiguous" + ); + let body: Value = admin + .get(format!("{base}/api/servers/{id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(body["data"]["name"], "original"); + assert_eq!(body["data"]["expired_at"], Value::Null); +} + +#[tokio::test] +async fn timezone_only_edit_keeps_the_calendar_date_and_operator_history() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "timezone-host").await; + let original: Value = admin + .put(format!("{base}/api/servers/{id}")) + .json( + &json!({"renewal":{"expiry_date":"2026-11-01","billing_timezone":"America/New_York"}}), + ) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!( + original["data"]["expired_at"], + "2026-11-02T04:59:59.999999999Z" + ); + let changed: Value = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"billing_timezone":"Asia/Tokyo"}})) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!( + changed["data"]["expired_at"], + "2026-11-01T14:59:59.999999999Z" + ); + assert_eq!(changed["data"]["renewal"]["expiry_date"], "2026-11-01"); + assert_eq!( + changed["data"]["renewal"]["confirmed_expired_at"], + original["data"]["expired_at"] + ); + let cleared: Value = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"expiry_date":null}})) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(cleared["data"]["expired_at"], Value::Null); + assert_eq!( + cleared["data"]["renewal"]["confirmed_expired_at"], + Value::Null + ); +} + +#[tokio::test] +async fn renewal_read_permissions_and_public_redaction_remain_unchanged() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "private-renewal").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"price":99.0,"renewal":{"expiry_date":"2028-02-29","billing_timezone":"Asia/Tokyo"}})).send().await.unwrap(); + assert_eq!(response.status(), 200); + let member = common::login_as_new_user(&admin, &base, "calendar-member", "member").await; + let detail: Value = member + .get(format!("{base}/api/servers/{id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(detail["data"]["renewal"]["expiry_date"], "2028-02-29"); + assert_eq!( + member + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"expiry_date":null}})) + .send() + .await + .unwrap() + .status(), + 403 + ); + assert_eq!( + admin + .put(format!("{base}/api/status-page")) + .json(&json!({"enabled":true,"server_ids":[id],"show_server_detail":true})) + .send() + .await + .unwrap() + .status(), + 200 + ); + let anonymous = http_client(); + for route in ["/api/status".into(), format!("/api/status/servers/{id}")] { + let response = anonymous + .get(format!("{base}{route}")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + let text = body.to_string(); + for private in [ + "renewal", + "expired_at", + "confirmed_expired_at", + "billing_timezone", + "price", + ] { + assert!( + !text.contains(&format!("\"{private}\"")), + "public response contains {private}: {body}" + ); + } + } +} + +#[tokio::test] +async fn legacy_web_changed_date_is_a_calendar_date_even_west_of_utc() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "legacy-change").await; + assert_eq!(admin.put(format!("{base}/api/servers/{id}")).json(&json!({"renewal":{"expiry_date":"2026-01-31","billing_timezone":"America/Los_Angeles"}})).send().await.unwrap().status(), 200); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"expired_at":"2026-02-28T00:00:00.000Z"})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + assert_eq!(body["data"]["renewal"]["expiry_date"], "2026-02-28"); + assert_eq!(body["data"]["expired_at"], "2026-03-01T07:59:59.999999999Z"); +} + +#[tokio::test] +async fn predecessor_onboarding_retry_keeps_its_original_request_identity() { + let (_tmp, path) = predecessor_database().await; + let base = serve_database(&path).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let response = admin.post(format!("{base}/api/servers")) + .json(&json!({"onboarding_request_id":"00000000-0000-4000-8000-000000000001","name":"legacy-host","expired_at":"2026-04-18T17:42:13Z"})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + assert_eq!(body["data"]["server_id"], "legacy-host"); + assert!(body["data"]["enrollment"].is_null()); +} From 5005a79cef5f604d620de56aaa986bebad22461e Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:28:20 +0000 Subject: [PATCH 05/40] feat(renewal): publish typed billing calendar contract --- apps/web/openapi.json | 86 +++++++++++++++++++ apps/web/src/lib/api-types.ts | 18 ++++ crates/server/src/service/alert.rs | 1 + crates/server/src/service/auth.rs | 3 + crates/server/src/service/cost.rs | 1 + crates/server/src/service/renewal.rs | 5 ++ .../server/src/service/server_onboarding.rs | 10 --- crates/server/src/service/task_scheduler.rs | 1 + crates/server/tests/renewal_dates.rs | 50 ++++++++++- 9 files changed, 164 insertions(+), 11 deletions(-) diff --git a/apps/web/openapi.json b/apps/web/openapi.json index 6f8d96548..dabf20a35 100644 --- a/apps/web/openapi.json +++ b/apps/web/openapi.json @@ -9945,6 +9945,16 @@ "null" ] }, + "renewal": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RenewalInput" + } + ] + }, "tags": { "type": "array", "items": { @@ -10250,6 +10260,14 @@ } ] }, + "DeadlineOrigin": { + "type": "string", + "enum": [ + "confirmed", + "projected", + "frozen" + ] + }, "DeleteRequest": { "type": "object", "required": [ @@ -12718,6 +12736,61 @@ } } }, + "RenewalInput": { + "type": "object", + "properties": { + "billing_timezone": { + "type": [ + "string", + "null" + ] + }, + "expiry_date": { + "type": [ + "string", + "null" + ] + } + } + }, + "RenewalProjection": { + "type": "object", + "required": [ + "enabled", + "billing_timezone", + "deadline_origin" + ], + "properties": { + "billing_timezone": { + "type": "string" + }, + "confirmed_expired_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "deadline_origin": { + "$ref": "#/components/schemas/DeadlineOrigin" + }, + "enabled": { + "type": "boolean" + }, + "expiry_date": { + "type": [ + "string", + "null" + ] + }, + "occurrence_id": { + "type": [ + "string", + "null" + ] + } + } + }, "ResourceValue": { "type": "object", "properties": { @@ -13695,6 +13768,9 @@ "null" ] }, + "renewal": { + "$ref": "#/components/schemas/RenewalProjection" + }, "swap_total": { "type": [ "integer", @@ -15384,6 +15460,16 @@ "null" ] }, + "renewal": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RenewalInput" + } + ] + }, "traffic_limit": { "type": [ "integer", diff --git a/apps/web/src/lib/api-types.ts b/apps/web/src/lib/api-types.ts index f6ce2f609..15f52a79d 100644 --- a/apps/web/src/lib/api-types.ts +++ b/apps/web/src/lib/api-types.ts @@ -2769,6 +2769,7 @@ export interface components { price?: number | null; public_remark?: string | null; remark?: string | null; + renewal?: null | components["schemas"]["RenewalInput"]; tags?: string[]; /** Format: int64 */ traffic_limit?: number | null; @@ -2851,6 +2852,8 @@ export interface components { DashboardWithWidgets: components["schemas"]["Model"] & { widgets: components["schemas"]["Model"][]; }; + /** @enum {string} */ + DeadlineOrigin: "confirmed" | "projected" | "frozen"; DeleteRequest: { path: string; recursive?: boolean; @@ -3563,6 +3566,19 @@ export interface components { RegisterResponse: { server_id: string; }; + RenewalInput: { + billing_timezone?: string | null; + expiry_date?: string | null; + }; + RenewalProjection: { + billing_timezone: string; + /** Format: date-time */ + confirmed_expired_at?: string | null; + deadline_origin: components["schemas"]["DeadlineOrigin"]; + enabled: boolean; + expiry_date?: string | null; + occurrence_id?: string | null; + }; ResourceValue: { /** Format: double */ cost_per_cpu_core?: number | null; @@ -3845,6 +3861,7 @@ export interface components { public_remark?: string | null; region?: string | null; remark?: string | null; + renewal?: components["schemas"]["RenewalProjection"]; /** Format: int64 */ swap_total?: number | null; /** @@ -4316,6 +4333,7 @@ export interface components { price?: number | null; public_remark?: string | null; remark?: string | null; + renewal?: null | components["schemas"]["RenewalInput"]; /** Format: int64 */ traffic_limit?: number | null; traffic_limit_type?: string | null; diff --git a/crates/server/src/service/alert.rs b/crates/server/src/service/alert.rs index 8bc8ecc34..050d3d1f0 100644 --- a/crates/server/src/service/alert.rs +++ b/crates/server/src/service/alert.rs @@ -3258,6 +3258,7 @@ mod tests { hidden: Set(false), capabilities: Set(0), protocol_version: Set(1), + renewal_state: Set(None), expired_at: Set(expired_at), created_at: Set(now), updated_at: Set(now), diff --git a/crates/server/src/service/auth.rs b/crates/server/src/service/auth.rs index 9841253ea..063daf062 100644 --- a/crates/server/src/service/auth.rs +++ b/crates/server/src/service/auth.rs @@ -1294,6 +1294,7 @@ mod tests { price: Set(None), billing_cycle: Set(None), currency: Set(None), + renewal_state: Set(None), expired_at: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), @@ -1358,6 +1359,7 @@ mod tests { price: Set(None), billing_cycle: Set(None), currency: Set(None), + renewal_state: Set(None), expired_at: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), @@ -1847,6 +1849,7 @@ mod tests { price: Set(None), billing_cycle: Set(None), currency: Set(None), + renewal_state: Set(None), expired_at: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), diff --git a/crates/server/src/service/cost.rs b/crates/server/src/service/cost.rs index f8fca01b1..ade685cfc 100644 --- a/crates/server/src/service/cost.rs +++ b/crates/server/src/service/cost.rs @@ -835,6 +835,7 @@ mod tests { price: Set(price), billing_cycle: Set(billing_cycle.map(str::to_string)), currency: Set(currency.map(str::to_string)), + renewal_state: Set(None), expired_at: Set(expired_at), traffic_limit: Set(Some(1024_i64.pow(4))), traffic_limit_type: Set(Some("sum".to_string())), diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs index ce03ca118..d1fd3ace9 100644 --- a/crates/server/src/service/renewal.rs +++ b/crates/server/src/service/renewal.rs @@ -120,6 +120,11 @@ pub fn apply_initial( input: Option<&RenewalInput>, legacy: Option>, ) -> Result<(RenewalState, Option>), AppError> { + if input.is_some_and(|input| input.expiry_date.is_some()) && legacy.is_some() { + return Err(AppError::Validation( + "expiry_date and expired_at cannot be submitted together".into(), + )); + } // Preserve old create payload instants. Calendar input uses the new contract. apply_calendar( RenewalState { diff --git a/crates/server/src/service/server_onboarding.rs b/crates/server/src/service/server_onboarding.rs index 14faa8fd5..16c5ab9f2 100644 --- a/crates/server/src/service/server_onboarding.rs +++ b/crates/server/src/service/server_onboarding.rs @@ -338,16 +338,6 @@ impl NormalizedProfile { )); } - if profile - .renewal - .as_ref() - .is_some_and(|input| input.expiry_date.is_some()) - && profile.expired_at.is_some() - { - return Err(OnboardingError::Validation( - "expiry_date and expired_at cannot be submitted together".into(), - )); - } let (renewal, expired_at) = super::renewal::apply_initial(profile.renewal.as_ref(), profile.expired_at) .map_err(|e| OnboardingError::Validation(e.to_string()))?; diff --git a/crates/server/src/service/task_scheduler.rs b/crates/server/src/service/task_scheduler.rs index 771675a56..0d261493a 100644 --- a/crates/server/src/service/task_scheduler.rs +++ b/crates/server/src/service/task_scheduler.rs @@ -1885,6 +1885,7 @@ mod tests { billing_cycle: Set(None), currency: Set(None), expired_at: Set(None), + renewal_state: Set(None), traffic_limit: Set(None), traffic_limit_type: Set(None), billing_start_day: Set(None), diff --git a/crates/server/tests/renewal_dates.rs b/crates/server/tests/renewal_dates.rs index 948cc37cc..7ad7053f8 100644 --- a/crates/server/tests/renewal_dates.rs +++ b/crates/server/tests/renewal_dates.rs @@ -102,8 +102,24 @@ async fn predecessor_database() -> (tempfile::TempDir, std::path::PathBuf) { let db = sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display())) .await .unwrap(); - let steps = Migrator::migrations().len() as u32 - 1; + let steps = Migrator::migrations() + .iter() + .position(|migration| migration.name() == "m20261005_000086_renewal_dates") + .expect("renewal migration remains registered") as u32; Migrator::up(&db, Some(steps)).await.unwrap(); + let columns = db + .query_all(sea_orm::Statement::from_string( + sea_orm::DatabaseBackend::Sqlite, + "PRAGMA table_info(servers)", + )) + .await + .unwrap(); + assert!( + !columns + .iter() + .any(|column| column.try_get::("", "name").unwrap() == "renewal_state"), + "fixture must predate renewal schema" + ); let user = AuthService::create_user(&db, "admin", "testpass", "admin") .await .unwrap(); @@ -387,3 +403,35 @@ async fn predecessor_onboarding_retry_keeps_its_original_request_identity() { assert_eq!(body["data"]["server_id"], "legacy-host"); assert!(body["data"]["enrollment"].is_null()); } + +#[tokio::test] +async fn invalid_or_ambiguous_onboarding_calendar_has_no_durable_side_effects() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + for fields in [ + json!({"renewal":{"expiry_date":"2026-02-30"}}), + json!({"renewal":{"expiry_date":"2026-01-31","billing_timezone":"not-a-timezone"}}), + json!({"renewal":{"expiry_date":"2026-01-31"},"expired_at":"2026-01-31T00:00:00Z"}), + ] { + let mut payload = fields; + payload["name"] = json!("invalid-create"); + payload["onboarding_request_id"] = json!(uuid::Uuid::new_v4().to_string()); + let response = admin + .post(format!("{base}/api/servers")) + .json(&payload) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 422); + } + let body: Value = admin + .get(format!("{base}/api/servers")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(body["data"], json!([])); +} From 4e3047a5f8c51b8b1893650a05dc8a470b629307 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:35:12 +0000 Subject: [PATCH 06/40] fix(web): preserve billing dates across browser timezones --- .../server/server-edit-dialog.test.tsx | 4 -- .../components/server/server-edit-dialog.tsx | 49 +++++-------------- .../server/server-edit-renewal.test.tsx | 39 ++++++++------- 3 files changed, 33 insertions(+), 59 deletions(-) diff --git a/apps/web/src/components/server/server-edit-dialog.test.tsx b/apps/web/src/components/server/server-edit-dialog.test.tsx index f5032fd9c..f7f48a90b 100644 --- a/apps/web/src/components/server/server-edit-dialog.test.tsx +++ b/apps/web/src/components/server/server-edit-dialog.test.tsx @@ -59,10 +59,6 @@ vi.mock('@/components/ui/button', () => ({ ) })) -vi.mock('@/components/ui/calendar', () => ({ - Calendar: () =>
-})) - vi.mock('@/components/ui/checkbox', () => ({ Checkbox: ({ checked, onCheckedChange }: { checked?: boolean; onCheckedChange?: (checked: boolean) => void }) => ( onCheckedChange?.(event.target.checked)} type="checkbox" /> diff --git a/apps/web/src/components/server/server-edit-dialog.tsx b/apps/web/src/components/server/server-edit-dialog.tsx index c852d3260..020834d57 100644 --- a/apps/web/src/components/server/server-edit-dialog.tsx +++ b/apps/web/src/components/server/server-edit-dialog.tsx @@ -1,11 +1,10 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import type { TFunction } from 'i18next' -import { CalendarIcon, Check, ChevronsUpDown } from 'lucide-react' +import { Check, ChevronsUpDown } from 'lucide-react' import { type FormEvent, useId, useMemo, useReducer, useState } from 'react' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' import { Button } from '@/components/ui/button' -import { Calendar } from '@/components/ui/calendar' import { Checkbox } from '@/components/ui/checkbox' import { Command, @@ -30,13 +29,6 @@ import { cn, countryCodeToFlag } from '@/lib/utils' const TAG_SPLIT_RE = /[\s,]+/ const TAG_VALID_RE = /^[A-Za-z0-9_.-]+$/ -function formatIsoDate(date: Date): string { - const year = date.getFullYear() - const month = String(date.getMonth() + 1).padStart(2, '0') - const day = String(date.getDate()).padStart(2, '0') - return `${year}-${month}-${day}` -} - function parseTagsInput(raw: string): { tags: string[]; error: string | null } { const parts = raw.split(TAG_SPLIT_RE).flatMap((t) => { const tag = t.trim() @@ -333,7 +325,7 @@ function ServerEditBillingFields({
- dispatch({ type: 'patch', value: { expiredAt } })} value={state.expiredAt} @@ -666,42 +658,23 @@ function CountryOverrideField({ ) } -interface DatePickerFieldProps { +interface ExpiryDateFieldProps { ariaLabel: string onChange: (value: string) => void value: string } -function DatePickerField({ ariaLabel, onChange, value }: DatePickerFieldProps) { +function ExpiryDateField({ ariaLabel, onChange, value }: ExpiryDateFieldProps) { const { t } = useTranslation('servers') - const selected = value ? new Date(`${value}T00:00:00`) : undefined return (
- - - } - > - - - {value || t('edit_expiration_placeholder', { defaultValue: 'YYYY-MM-DD' })} - - - - onChange(date ? formatIsoDate(date) : '')} - selected={selected} - /> - - + onChange(e.target.value)} + type="date" + value={value} + /> {value && (
@@ -72,7 +72,7 @@ function ConfiguredCostBar({ currency={currency} price={insights.price ?? server.price} /> - + {insights.cost_per_day != null && ( {t('cost_per_day', { @@ -140,13 +140,13 @@ function FallbackBillingBar({ server, serverId }: CostInsightBarProps) {
) } -function ExpiryStatus({ expiredAt }: { expiredAt?: string | null }) { +function ExpiryStatus({ expiredAt, renewal }: { expiredAt?: string | null; renewal?: ServerResponse['renewal'] }) { const { t } = useTranslation('servers') if (!expiredAt) { @@ -154,6 +154,8 @@ function ExpiryStatus({ expiredAt }: { expiredAt?: string | null }) { } const expiryDate = new Date(expiredAt) + const selectedDate = + renewal?.expiry_date ?? formatDateShort(expiryDate, { timeZone: renewal?.billing_timezone ?? 'UTC' }) const isExpired = expiryDate < new Date() const daysUntilExpiry = Math.ceil((expiryDate.getTime() - Date.now()) / 86_400_000) @@ -168,11 +170,12 @@ function ExpiryStatus({ expiredAt }: { expiredAt?: string | null }) { })() return ( - - {isExpired - ? `${t('detail_expired')} ${formatDateShort(expiryDate)}` - : `${t('detail_expires')} ${formatDateShort(expiryDate)}`} - {!isExpired && ` (${t('detail_expires_days', { count: daysUntilExpiry })})`} + + + {t('renewal_deadline')}: {isExpired ? t('detail_expired') : t('detail_expires')} {selectedDate} + {!isExpired && ` (${t('detail_expires_days', { count: daysUntilExpiry })})`} + + {t('renewal_cost_independent')} ) } diff --git a/apps/web/src/locales/en/servers.json b/apps/web/src/locales/en/servers.json index e7611f5d4..e2504dc1a 100644 --- a/apps/web/src/locales/en/servers.json +++ b/apps/web/src/locales/en/servers.json @@ -179,6 +179,8 @@ "detail_network_out": "Network out:", "detail_network_total": "Total:", "detail_expired": "Expired", + "renewal_deadline": "Renewal deadline", + "renewal_cost_independent": "Renewal deadline is separate from the cost estimation period.", "detail_expires": "Expires", "detail_expires_days": "{{count}}d", "detail_traffic": "Traffic:", diff --git a/apps/web/src/locales/zh/servers.json b/apps/web/src/locales/zh/servers.json index d915cd8f4..959b0ab71 100644 --- a/apps/web/src/locales/zh/servers.json +++ b/apps/web/src/locales/zh/servers.json @@ -179,6 +179,8 @@ "detail_network_out": "出站流量:", "detail_network_total": "总计:", "detail_expired": "已过期", + "renewal_deadline": "续费到期日", + "renewal_cost_independent": "续费到期日独立于费用估算周期。", "detail_expires": "到期", "detail_expires_days": "{{count}} 天", "detail_traffic": "流量:", From 8870323ab85f8bf50f83a0d3bc1a95bdd127dfc7 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:47:17 +0000 Subject: [PATCH 09/40] ci(ios): validate renewal integration before pull request --- .github/workflows/ci-ios.yml | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci-ios.yml b/.github/workflows/ci-ios.yml index 27d286ff6..b20bbbf37 100644 --- a/.github/workflows/ci-ios.yml +++ b/.github/workflows/ci-ios.yml @@ -2,7 +2,8 @@ name: CI iOS on: push: - branches: [main] + # Validate native changes on the renewal integration branch before its PR. + branches: [main, feat/renewal-tracking-integration] paths: - 'apps/ios/**' - 'tests/fixtures/push*-envelope-v1.json' @@ -99,3 +100,13 @@ jobs: action: test working-directory: apps/ios trust-plugins: true + verbosity: verbose + + - name: Preserve native test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: ios-native-tests-${{ github.sha }} + path: apps/ios/test.xcresult + if-no-files-found: error + retention-days: 1 From 5d5c372741d05e4580fe755a49091ada07cab1d3 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:48:21 +0000 Subject: [PATCH 10/40] feat(renewal): validate opt-in prerequisites atomically --- crates/server/src/service/renewal.rs | 33 +++++++++++++---- crates/server/src/service/server.rs | 2 +- .../server/src/service/server_onboarding.rs | 2 +- crates/server/tests/renewal_projection.rs | 35 +++++++++++++++++++ 4 files changed, 64 insertions(+), 8 deletions(-) create mode 100644 crates/server/tests/renewal_projection.rs diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs index c5bbaad59..9df45f20b 100644 --- a/crates/server/src/service/renewal.rs +++ b/crates/server/src/service/renewal.rs @@ -6,6 +6,8 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct RenewalState { + #[serde(default)] + pub enabled: bool, pub billing_timezone: String, pub confirmed_expired_at: Option>, } @@ -30,6 +32,7 @@ pub struct RenewalProjection { #[derive(Clone, Debug, Default, Deserialize, Serialize, utoipa::ToSchema)] pub struct RenewalInput { + pub enabled: Option, #[serde( default, deserialize_with = "super::server::deserialize_optional_nullable" @@ -49,13 +52,14 @@ impl RenewalState { .as_deref() .and_then(|s| serde_json::from_str(s).ok()) .unwrap_or_else(|| Self { + enabled: false, billing_timezone: "UTC".into(), confirmed_expired_at: model.expired_at, }) } pub fn projection(&self, deadline: Option>) -> RenewalProjection { RenewalProjection { - enabled: false, + enabled: self.enabled, billing_timezone: self.billing_timezone.clone(), expiry_date: selected_date(deadline, &self.billing_timezone).map(|d| d.to_string()), confirmed_expired_at: self.confirmed_expired_at, @@ -107,18 +111,22 @@ pub fn apply_edit( model: &server::Model, input: Option<&RenewalInput>, legacy: Option>>, + billing_cycle: Option<&str>, ) -> Result<(RenewalState, Option>), AppError> { - apply_calendar( + let result = apply_calendar( RenewalState::from_server(model), model.expired_at, input, legacy, - ) + )?; + validate_enabled(&result.0, result.1, billing_cycle)?; + Ok(result) } pub fn apply_initial( input: Option<&RenewalInput>, legacy: Option>, + billing_cycle: Option<&str>, ) -> Result<(RenewalState, Option>), AppError> { if input.is_some_and(|input| input.expiry_date.is_some()) && legacy.is_some() { return Err(AppError::Validation( @@ -126,15 +134,25 @@ pub fn apply_initial( )); } // Preserve old create payload instants. Calendar input uses the new contract. - apply_calendar( + let result = apply_calendar( RenewalState { - billing_timezone: "UTC".into(), + enabled: false, + billing_timezone: "UTC".into(), confirmed_expired_at: legacy, }, legacy, input, None, - ) + )?; + validate_enabled(&result.0, result.1, billing_cycle)?; + Ok(result) +} + +fn validate_enabled(state: &RenewalState, deadline: Option>, cycle: Option<&str>) -> Result<(), AppError> { + if state.enabled && (deadline.is_none() || !matches!(cycle, Some("monthly" | "quarterly" | "yearly"))) { + return Err(AppError::Validation("automatic renewal requires an expiry date and monthly, quarterly or yearly billing_cycle".into())); + } + Ok(()) } fn apply_calendar( @@ -210,5 +228,8 @@ fn apply_calendar( .map(|d| date_boundary(d, &state.billing_timezone)) .transpose()?; } + if let Some(enabled) = input.and_then(|i| i.enabled) { + state.enabled = enabled; + } Ok((state, deadline)) } diff --git a/crates/server/src/service/server.rs b/crates/server/src/service/server.rs index 26ecc6481..2c928b839 100644 --- a/crates/server/src/service/server.rs +++ b/crates/server/src/service/server.rs @@ -85,7 +85,7 @@ impl ServerService { Self::validate_update_input(&input)?; let (renewal, deadline) = - super::renewal::apply_edit(&model, input.renewal.as_ref(), input.expired_at)?; + super::renewal::apply_edit(&model, input.renewal.as_ref(), input.expired_at, input.billing_cycle.as_ref().map(|c| c.as_deref()).unwrap_or(model.billing_cycle.as_deref()))?; let mut active: server::ActiveModel = model.into(); active.renewal_state = Set(Some( serde_json::to_string(&renewal).map_err(|e| AppError::Validation(e.to_string()))?, diff --git a/crates/server/src/service/server_onboarding.rs b/crates/server/src/service/server_onboarding.rs index 16c5ab9f2..ee15aab3e 100644 --- a/crates/server/src/service/server_onboarding.rs +++ b/crates/server/src/service/server_onboarding.rs @@ -339,7 +339,7 @@ impl NormalizedProfile { } let (renewal, expired_at) = - super::renewal::apply_initial(profile.renewal.as_ref(), profile.expired_at) + super::renewal::apply_initial(profile.renewal.as_ref(), profile.expired_at, profile.billing_cycle.as_deref()) .map_err(|e| OnboardingError::Validation(e.to_string()))?; // Preserve the predecessor canonical hash for legacy onboarding retries. let renewal_state = profile diff --git a/crates/server/tests/renewal_projection.rs b/crates/server/tests/renewal_projection.rs new file mode 100644 index 000000000..6ee3f811d --- /dev/null +++ b/crates/server/tests/renewal_projection.rs @@ -0,0 +1,35 @@ +//! Opt-in renewal projection through authenticated HTTP and persistent SQLite. +mod common; +use common::{create_server, http_client, login_admin, start_test_server}; +use serde_json::{Value, json}; + +#[tokio::test] +async fn automatic_renewal_requires_complete_resulting_configuration_atomically() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "manual-host").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"name":"must-not-change","renewal":{"enabled":true}})) + .send().await.unwrap(); + assert_eq!(response.status(), 422, "enabled renewal must require date and interval"); + let body: Value = admin.get(format!("{base}/api/servers/{id}")) + .send().await.unwrap().json().await.unwrap(); + assert_eq!(body["data"]["name"], "manual-host"); + assert_eq!(body["data"]["renewal"]["enabled"], false); +} + +#[tokio::test] +async fn opt_in_projects_without_promoting_operator_history_to_payment_information() { + let (base, _tmp) = start_test_server().await; + let admin = http_client(); login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "expected-renewal").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","price":12.5,"currency":"USD","traffic_limit":1024,"billing_start_day":7,"renewal":{"enabled":true,"expiry_date":"2099-01-31","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + assert_eq!(body["data"]["renewal"]["deadline_origin"], "projected"); + assert_eq!(body["data"]["renewal"]["confirmed_expired_at"], "2099-02-01T04:59:59.999999999Z"); + assert!(body["data"]["renewal"]["occurrence_id"].as_str().is_some_and(|id| !id.is_empty())); +} From 038646534bc6076338d99febdf07e499a293918c Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:50:36 +0000 Subject: [PATCH 11/40] feat(ios): add automatic renewal controls and provenance --- apps/ios/ServerBee/Localizable.xcstrings | 140 ++++++++++++++++++ apps/ios/ServerBee/Models/ServerConfig.swift | 26 ++++ .../Models/UpdateServerRequest.swift | 5 +- .../ViewModels/EditServerViewModel.swift | 33 ++++- .../Detail/ServerOverviewSection.swift | 14 ++ .../Servers/Enrollment/EditServerSheet.swift | 50 ++++++- .../Views/Servers/ServerDetailView.swift | 1 + .../ios/ServerBeeTests/RenewalDateTests.swift | 113 +++++++++++++- 8 files changed, 374 insertions(+), 8 deletions(-) diff --git a/apps/ios/ServerBee/Localizable.xcstrings b/apps/ios/ServerBee/Localizable.xcstrings index 6ad3ca7d5..688bdde44 100644 --- a/apps/ios/ServerBee/Localizable.xcstrings +++ b/apps/ios/ServerBee/Localizable.xcstrings @@ -1,6 +1,146 @@ { "sourceLanguage": "en", "strings": { + "Renewal": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "续费" + } + } + } + }, + "Automatic renewal": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "自动续费" + } + } + } + }, + "Automatic renewal requires an expiry date.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "自动续费需要到期日期。" + } + } + } + }, + "Automatic renewal requires a monthly, quarterly, or yearly cycle.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "自动续费需要按月、季度或年计费。" + } + } + } + }, + "Advance the forecast after each renewal date. Turning this off freezes the current deadline.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "每个续费日期结束后推进预测日期。关闭此项将冻结当前期限。" + } + } + } + }, + "Automatic renewal advances a forecast after the expiry day ends. Provider renewal and payment remain your responsibility.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "自动续费在到期日结束后推进预测日期。服务商的续费和付款仍需您自行处理。" + } + } + } + }, + "Saved renewal deadline": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已保存的续费期限" + } + } + } + }, + "Last confirmed expiry": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "上次确认的到期日期" + } + } + } + }, + "Confirmed renewal deadline": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已确认的续费期限" + } + } + } + }, + "Projected renewal deadline": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "预测的续费期限" + } + } + } + }, + "Frozen renewal deadline": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已冻结的续费期限" + } + } + } + }, + "This deadline was recorded by an operator from provider information.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "此期限由管理员根据服务商信息记录。" + } + } + } + }, + "This deadline is a forecast. It does not confirm provider renewal or payment.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "此期限为预测日期,并不确认服务商已续费或收款。" + } + } + } + }, + "Automatic renewal is off. This forecast is frozen; it does not confirm provider renewal or payment.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "自动续费已关闭。此预测日期已冻结,并不确认服务商已续费或收款。" + } + } + } + }, "Selected session": { "localizations": { "zh-Hans": { diff --git a/apps/ios/ServerBee/Models/ServerConfig.swift b/apps/ios/ServerBee/Models/ServerConfig.swift index c1354ee9d..11b0177d2 100644 --- a/apps/ios/ServerBee/Models/ServerConfig.swift +++ b/apps/ios/ServerBee/Models/ServerConfig.swift @@ -20,6 +20,32 @@ struct ServerRenewal: Decodable, Hashable, Sendable { } } +extension ServerRenewal { + var deadlineOriginLabel: String? { + switch deadlineOrigin { + case "confirmed": String(localized: "Confirmed renewal deadline") + case "projected": String(localized: "Projected renewal deadline") + case "frozen": String(localized: "Frozen renewal deadline") + default: nil + } + } + + var deadlineExplanation: String? { + switch deadlineOrigin { + case "confirmed": String(localized: "This deadline was recorded by an operator from provider information.") + case "projected": String(localized: "This deadline is a forecast. It does not confirm provider renewal or payment.") + case "frozen": String(localized: "Automatic renewal is off. This forecast is frozen; it does not confirm provider renewal or payment.") + default: nil + } + } + + var confirmedDisplayDate: String? { + guard let confirmedExpiredAt, + let date = ISO8601DateFormatter.shared.date(from: confirmedExpiredAt) else { return nil } + return BillingDate.display(from: date, timezone: billingTimezone) + } +} + /// Server group (`/api/server-groups`). Used to resolve `group_id` to a name. struct ServerGroup: Decodable, Identifiable, Hashable, Sendable { let id: String diff --git a/apps/ios/ServerBee/Models/UpdateServerRequest.swift b/apps/ios/ServerBee/Models/UpdateServerRequest.swift index 518f6702a..fcb524ced 100644 --- a/apps/ios/ServerBee/Models/UpdateServerRequest.swift +++ b/apps/ios/ServerBee/Models/UpdateServerRequest.swift @@ -21,19 +21,22 @@ enum Tri: Sendable { } } -/// Date-only renewal edits. Omission preserves the server's current anchor; +/// Renewal edits. Omission preserves the server's current schedule; /// clearing is explicit and validation belongs to the server. struct UpdateRenewalRequest: Encodable, Sendable { + var enabled: Bool? var billingTimezone: Tri = .unchanged var expiryDate: Tri = .unchanged enum CodingKeys: String, CodingKey { + case enabled case billingTimezone = "billing_timezone" case expiryDate = "expiry_date" } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enabled, forKey: .enabled) try billingTimezone.encode(into: &container, forKey: .billingTimezone) try expiryDate.encode(into: &container, forKey: .expiryDate) } diff --git a/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift b/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift index 5dc9a771a..5b45aad3b 100644 --- a/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/EditServerViewModel.swift @@ -18,6 +18,8 @@ final class EditServerViewModel { var currency = "" // "" = none var billingCycle = "" // "" = none var billingStartDayText = "" + var automaticRenewal = false + private(set) var supportsAutomaticRenewal = false var hasExpiry = false var expiryDate = Date() var billingTimezone = "UTC" { @@ -42,6 +44,7 @@ final class EditServerViewModel { var isSaving = false var errorMessage: String? private var originalTags: [String] = [] + private var originalAutomaticRenewal = false private var originalExpiryDate: String? private var originalBillingTimezone = "UTC" private var lastValidBillingTimezone = "UTC" @@ -59,6 +62,9 @@ final class EditServerViewModel { currency = config.currency ?? "" billingCycle = config.billingCycle ?? "" billingStartDayText = config.billingStartDay.map(String.init) ?? "" + supportsAutomaticRenewal = config.renewal != nil + automaticRenewal = config.renewal?.enabled ?? false + originalAutomaticRenewal = automaticRenewal billingTimezone = config.renewal?.billingTimezone ?? "UTC" originalBillingTimezone = billingTimezone originalExpiryDate = config.renewal?.expiryDate @@ -121,6 +127,25 @@ extension EditServerViewModel { return result.sorted() } + /// Validation concerns the resulting form, so switching off and clearing + /// the deadline/interval in one save remains valid. Recurrence is server-owned. + var automaticRenewalPrerequisiteMessage: String? { + guard TimeZone(identifier: billingTimezone) != nil else { + return String(localized: "Choose a valid billing timezone.") + } + guard hasExpiry, BillingDate.string(from: expiryDate, timezone: billingTimezone) != nil else { + return String(localized: "Automatic renewal requires an expiry date.") + } + guard ["monthly", "quarterly", "yearly"].contains(billingCycle) else { + return String(localized: "Automatic renewal requires a monthly, quarterly, or yearly cycle.") + } + return nil + } + + var renewalValidationMessage: String? { + automaticRenewal ? automaticRenewalPrerequisiteMessage : nil + } + func buildRequest() -> UpdateServerRequest { var request = UpdateServerRequest() request.name = name.trimmingCharacters(in: .whitespaces) @@ -137,8 +162,10 @@ extension EditServerViewModel { let selectedDate = hasExpiry ? BillingDate.string(from: expiryDate, timezone: billingTimezone) : nil let dateChanged = selectedDate != originalExpiryDate let timezoneChanged = billingTimezone != originalBillingTimezone - if dateChanged || timezoneChanged { + let enabledChanged = supportsAutomaticRenewal && automaticRenewal != originalAutomaticRenewal + if dateChanged || timezoneChanged || enabledChanged { var renewal = UpdateRenewalRequest() + if enabledChanged { renewal.enabled = automaticRenewal } if dateChanged { if let selectedDate { renewal.expiryDate = .set(selectedDate) } else { renewal.expiryDate = .clear } } @@ -174,6 +201,10 @@ extension EditServerViewModel { errorMessage = String(localized: "Choose a valid billing timezone.") return false } + if let message = renewalValidationMessage { + errorMessage = message + return false + } errorMessage = nil guard let tags = parsedTags() else { return false } diff --git a/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift b/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift index b10b48230..ec92a156f 100644 --- a/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift +++ b/apps/ios/ServerBee/Views/Servers/Detail/ServerOverviewSection.swift @@ -387,6 +387,20 @@ private extension ServerOverviewSection { } else { expiryText } + if let renewal = config?.renewal { + if let label = renewal.deadlineOriginLabel { + Text(label).font(.footnote.weight(.semibold)) + .accessibilityIdentifier("renewal.detail.origin") + } + if let explanation = renewal.deadlineExplanation { + Text(explanation).font(.caption).foregroundStyle(.secondary) + } + if let date = renewal.confirmedDisplayDate { + LabeledContent(String(localized: "Last confirmed expiry"), value: date) + .font(.footnote) + } + Text(verbatim: renewal.billingTimezone).font(.caption).foregroundStyle(.secondary) + } ForEach(billingRows) { row in HStack(alignment: .firstTextBaseline, spacing: 12) { Text(row.label) diff --git a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift index c7c21effe..b5489511b 100644 --- a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift +++ b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift @@ -22,6 +22,7 @@ struct EditServerSheet: View { Form { basicSection billingSection + renewalSection if let error = viewModel.errorMessage { Section { Label(error, systemImage: "exclamationmark.triangle.fill").foregroundStyle(Color.serverOffline) @@ -45,6 +46,7 @@ private extension EditServerSheet { var basicSection: some View { Section { TextField(String(localized: "Name"), text: $viewModel.name) + .accessibilityIdentifier("server.name") Picker(String(localized: "Group"), selection: $viewModel.groupId) { Text(String(localized: "No group")).tag("") ForEach(viewModel.groups) { group in @@ -79,14 +81,29 @@ private extension EditServerSheet { } TextField(String(localized: "Billing day (1-28)"), text: $viewModel.billingStartDayText) .keyboardType(.numberPad) + TextField(String(localized: "Traffic limit (GiB)"), text: $viewModel.trafficLimitGiBText) + .keyboardType(.decimalPad) + Picker(String(localized: "Traffic type"), selection: $viewModel.trafficLimitType) { + Text(String(localized: "None")).tag("") + ForEach(Self.trafficTypes, id: \.self) { Text(Self.trafficTypeLabel($0)).tag($0) } + } + } + } + + @ViewBuilder + var renewalSection: some View { + Section(String(localized: "Renewal")) { Picker(String(localized: "Billing timezone"), selection: $viewModel.billingTimezone) { ForEach(Self.billingTimezones, id: \.self) { Text(verbatim: $0).tag($0) } } + .accessibilityIdentifier("renewal.timezone") Toggle(String(localized: "Has expiry"), isOn: $viewModel.hasExpiry) + .accessibilityIdentifier("renewal.hasExpiry") if viewModel.hasExpiry { DatePicker(String(localized: "Expires"), selection: $viewModel.expiryDate, displayedComponents: .date) .environment(\.timeZone, viewModel.expiryTimezone) .environment(\.calendar, viewModel.expiryCalendar) + .accessibilityIdentifier("renewal.expiry") Text(String(localized: "Valid through the selected date in the billing timezone.")) .font(.footnote) .foregroundStyle(.secondary) @@ -94,11 +111,33 @@ private extension EditServerSheet { Text(String(localized: "The renewal deadline is separate from the cost estimation period.")) .font(.footnote) .foregroundStyle(.secondary) - TextField(String(localized: "Traffic limit (GiB)"), text: $viewModel.trafficLimitGiBText) - .keyboardType(.decimalPad) - Picker(String(localized: "Traffic type"), selection: $viewModel.trafficLimitType) { - Text(String(localized: "None")).tag("") - ForEach(Self.trafficTypes, id: \.self) { Text(Self.trafficTypeLabel($0)).tag($0) } + if viewModel.supportsAutomaticRenewal { + Toggle(String(localized: "Automatic renewal"), isOn: $viewModel.automaticRenewal) + .disabled(!viewModel.automaticRenewal && viewModel.automaticRenewalPrerequisiteMessage != nil) + .accessibilityIdentifier("renewal.enabled") + .accessibilityHint(String(localized: "Advance the forecast after each renewal date. Turning this off freezes the current deadline.")) + if let message = viewModel.automaticRenewalPrerequisiteMessage { + Text(message) + .font(.footnote) + .foregroundStyle(.secondary) + .accessibilityIdentifier("renewal.prerequisites") + } + Text(String(localized: "Automatic renewal advances a forecast after the expiry day ends. Provider renewal and payment remain your responsibility.")) + .font(.footnote) + .foregroundStyle(.secondary) + if let renewal = config.renewal { + if let label = renewal.deadlineOriginLabel { + LabeledContent(String(localized: "Saved renewal deadline"), value: label) + .accessibilityIdentifier("renewal.origin") + } + if let explanation = renewal.deadlineExplanation { + Text(explanation).font(.footnote).foregroundStyle(.secondary) + } + if let date = renewal.confirmedDisplayDate { + LabeledContent(String(localized: "Last confirmed expiry"), value: date) + .accessibilityIdentifier("renewal.confirmed") + } + } } } } @@ -121,6 +160,7 @@ private extension EditServerSheet { } } .disabled(viewModel.name.trimmingCharacters(in: .whitespaces).isEmpty) + .accessibilityIdentifier("server.save") } } } diff --git a/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift b/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift index 1121bc287..c78a579bd 100644 --- a/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift +++ b/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift @@ -120,6 +120,7 @@ struct ServerDetailView: View { Button { showEdit = true } label: { Label(String(localized: "Edit server"), systemImage: "pencil") } + .accessibilityIdentifier("server.edit") } } } diff --git a/apps/ios/ServerBeeTests/RenewalDateTests.swift b/apps/ios/ServerBeeTests/RenewalDateTests.swift index f9a3cc168..6b471f3a5 100644 --- a/apps/ios/ServerBeeTests/RenewalDateTests.swift +++ b/apps/ios/ServerBeeTests/RenewalDateTests.swift @@ -23,6 +23,24 @@ final class RenewalDateTests: XCTestCase { XCTAssertEqual(config.renewal?.enabled, false) } + func test_deadlineDisplayUsesServerProvenance() throws { + for origin in ["confirmed", "projected", "frozen"] { + let config = try JSONDecoder.snakeCase.decode(ServerConfig.self, from: Data(""" + {"id":"s1","name":"Server","renewal":{"enabled":false, + "billing_timezone":"America/Los_Angeles","expiry_date":"2030-01-31", + "confirmed_expired_at":"2029-12-01T07:59:59Z","deadline_origin":"\(origin)"}} + """.utf8)) + let renewal = try XCTUnwrap(config.renewal) + XCTAssertNil(renewal.occurrenceId) + XCTAssertNotNil(renewal.deadlineOriginLabel) + XCTAssertNotNil(renewal.deadlineExplanation) + XCTAssertEqual(config.expiryLocalDate, "2030-01-31") + let confirmed = try XCTUnwrap(renewal.confirmedDisplayDate) + let expected = try XCTUnwrap(BillingDate.date(from: "2029-11-30", timezone: "America/Los_Angeles")) + XCTAssertEqual(confirmed, BillingDate.display(from: expected, timezone: "America/Los_Angeles")) + } + } + func test_renewalDateRequestDistinguishesOmitClearAndSet() throws { XCTAssertNil(try object(UpdateServerRequest())["renewal"]) var request = UpdateServerRequest() @@ -43,6 +61,21 @@ final class RenewalDateTests: XCTestCase { XCTAssertTrue(renewal["billing_timezone"] is NSNull) } + func test_enabledRequestOmitsOrEncodesFalse() throws { + var request = UpdateServerRequest() + request.renewal = UpdateRenewalRequest(enabled: true) + var renewal = try XCTUnwrap(try object(request)["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["enabled"] as? Bool, true) + XCTAssertNil(renewal["expiry_date"]) + request.renewal = UpdateRenewalRequest(enabled: false, expiryDate: .clear) + renewal = try XCTUnwrap(try object(request)["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["enabled"] as? Bool, false) + XCTAssertTrue(renewal["expiry_date"] is NSNull) + request.renewal = UpdateRenewalRequest(expiryDate: .set("2030-01-31")) + renewal = try XCTUnwrap(try object(request)["renewal"] as? [String: Any]) + XCTAssertNil(renewal["enabled"]) + } + @MainActor func test_unchangedFullFormSavePreservesLegacyInstant() throws { let config = try JSONDecoder.snakeCase.decode(ServerConfig.self, from: Data(""" @@ -61,6 +94,84 @@ final class RenewalDateTests: XCTestCase { XCTAssertEqual(request["billing_cycle"] as? String, "quarterly") } + @MainActor + func test_switchAndUnchangedSavesDoNotConfirm() throws { + let model = EditServerViewModel() + model.prefill(from: try selectedConfig()) + XCTAssertTrue(model.automaticRenewal) + XCTAssertNil(try object(model.buildRequest())["renewal"]) + model.automaticRenewal = false + let request = try object(model.buildRequest()) + let renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["enabled"] as? Bool, false) + XCTAssertNil(renewal["expiry_date"]) + XCTAssertNil(renewal["billing_timezone"]) + XCTAssertNil(request["expired_at"]) + model.automaticRenewal = true + XCTAssertNil(try object(model.buildRequest())["renewal"]) + } + + @MainActor + func test_enablingSendsOnlyChangedSwitchIntent() throws { + var config = try selectedConfig() + config.renewal = ServerRenewal( + enabled: false, billingTimezone: "America/Los_Angeles", expiryDate: "2026-03-08", + confirmedExpiredAt: "2026-03-09T06:59:59Z", deadlineOrigin: "confirmed", occurrenceId: "opaque-id" + ) + let model = EditServerViewModel() + model.prefill(from: config) + XCTAssertFalse(model.automaticRenewal) + XCTAssertNil(model.automaticRenewalPrerequisiteMessage) + model.automaticRenewal = true + XCTAssertNil(model.renewalValidationMessage) + let request = try object(model.buildRequest()) + let renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["enabled"] as? Bool, true) + XCTAssertNil(renewal["expiry_date"]) + XCTAssertNil(renewal["billing_timezone"]) + XCTAssertNil(request["expired_at"]) + } + + @MainActor + func test_prerequisitesAndDisableAndClear() throws { + let model = EditServerViewModel() + model.prefill(from: try selectedConfig()) + XCTAssertNil(model.renewalValidationMessage) + model.hasExpiry = false + XCTAssertNotNil(model.renewalValidationMessage) + model.hasExpiry = true + model.billingCycle = "" + XCTAssertNotNil(model.renewalValidationMessage) + model.billingCycle = "weekly" + XCTAssertNotNil(model.renewalValidationMessage) + model.billingCycle = "yearly" + model.billingTimezone = "Invalid/Zone" + XCTAssertNotNil(model.renewalValidationMessage) + model.billingTimezone = "America/Los_Angeles" + model.automaticRenewal = false + model.hasExpiry = false + model.billingCycle = "" + XCTAssertNil(model.renewalValidationMessage) + let request = try object(model.buildRequest()) + let renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["enabled"] as? Bool, false) + XCTAssertTrue(renewal["expiry_date"] is NSNull) + XCTAssertTrue(request["billing_cycle"] is NSNull) + } + + @MainActor + func test_oldServerUnchangedSaveHasNoRenewalIntent() throws { + let config = try JSONDecoder.snakeCase.decode(ServerConfig.self, from: Data(""" + {"id":"s1","name":"Server","expired_at":"2030-01-31T00:30:00Z"} + """.utf8)) + let model = EditServerViewModel() + model.prefill(from: config) + XCTAssertFalse(model.supportsAutomaticRenewal) + XCTAssertFalse(model.automaticRenewal) + XCTAssertNil(try object(model.buildRequest())["renewal"]) + XCTAssertNil(try object(model.buildRequest())["expired_at"]) + } + @MainActor func test_timezoneOnlyEditPreservesSelectedDateWithoutConfirmingIt() throws { let config = try selectedConfig() @@ -127,7 +238,7 @@ final class RenewalDateTests: XCTestCase { private func selectedConfig() throws -> ServerConfig { try JSONDecoder.snakeCase.decode(ServerConfig.self, from: Data(""" - {"id":"s1","name":"Server","expired_at":"2026-03-09T06:59:59Z", + {"id":"s1","name":"Server","billing_cycle":"monthly","expired_at":"2026-03-09T06:59:59Z", "renewal":{"enabled":true,"billing_timezone":"America/Los_Angeles","expiry_date":"2026-03-08", "confirmed_expired_at":"2026-02-09T07:59:59Z","deadline_origin":"projected","occurrence_id":"o2"}} """.utf8)) From 018b5d9e549a2ad77a541d4979197755b5f82400 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 18:54:20 +0000 Subject: [PATCH 12/40] feat(web): add automatic renewal controls and forecast provenance --- .../server/cost-insight-bar.test.tsx | 34 ++++++++ .../components/server/cost-insight-bar.tsx | 5 ++ .../server/renewal-deadline-info.tsx | 30 +++++++ .../components/server/server-edit-dialog.tsx | 56 +++++++++++- .../server/server-edit-renewal.test.tsx | 86 +++++++++++++++++++ apps/web/src/locales/en/servers.json | 9 +- apps/web/src/locales/zh/servers.json | 9 +- 7 files changed, 225 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/server/renewal-deadline-info.tsx diff --git a/apps/web/src/components/server/cost-insight-bar.test.tsx b/apps/web/src/components/server/cost-insight-bar.test.tsx index aaf312c3a..6d1a04f1d 100644 --- a/apps/web/src/components/server/cost-insight-bar.test.tsx +++ b/apps/web/src/components/server/cost-insight-bar.test.tsx @@ -39,4 +39,38 @@ describe('CostInsightBar renewal dates', () => { expect(screen.getByText(LOCAL_RENEWAL_DATE)).toBeInTheDocument() expect(screen.getByText(INDEPENDENT_PERIOD)).toBeInTheDocument() }) + + it('retains the frozen projected origin beside the current deadline and confirmed history', () => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render( + + + + ) + expect(screen.getByText('Frozen projected deadline')).toBeInTheDocument() + expect(screen.getByText('Last operator-confirmed expiry: 2/8/2026 (America/New_York)')).toBeInTheDocument() + expect( + screen.getByText( + 'Tracking advances the forecast after each expiry date ends. Disabling freezes the current deadline. This estimate does not confirm provider renewal or payment.' + ) + ).toBeInTheDocument() + }) }) diff --git a/apps/web/src/components/server/cost-insight-bar.tsx b/apps/web/src/components/server/cost-insight-bar.tsx index 50c4e2b21..635ed7c33 100644 --- a/apps/web/src/components/server/cost-insight-bar.tsx +++ b/apps/web/src/components/server/cost-insight-bar.tsx @@ -1,5 +1,6 @@ import { AlertTriangle, CreditCard } from 'lucide-react' import { useTranslation } from 'react-i18next' +import { RenewalDeadlineInfo } from '@/components/server/renewal-deadline-info' import { TrafficProgress } from '@/components/server/traffic-progress' import { useCostInsights } from '@/hooks/use-cost' import type { ResourceValue, ServerCostInsights, ServerResponse } from '@/lib/api-schema' @@ -175,6 +176,10 @@ function ExpiryStatus({ expiredAt, renewal }: { expiredAt?: string | null; renew {t('renewal_deadline')}: {isExpired ? t('detail_expired') : t('detail_expires')} {selectedDate} {!isExpired && ` (${t('detail_expires_days', { count: daysUntilExpiry })})`} + + {renewal && renewal.deadline_origin !== 'confirmed' && ( + {t('renewal_forecast_explanation')} + )} {t('renewal_cost_independent')}
) diff --git a/apps/web/src/components/server/renewal-deadline-info.tsx b/apps/web/src/components/server/renewal-deadline-info.tsx new file mode 100644 index 000000000..ab12780a1 --- /dev/null +++ b/apps/web/src/components/server/renewal-deadline-info.tsx @@ -0,0 +1,30 @@ +import { useTranslation } from 'react-i18next' +import type { ServerResponse } from '@/lib/api-schema' +import { formatDateShort } from '@/lib/format' + +export function RenewalDeadlineInfo({ renewal }: { renewal?: ServerResponse['renewal'] }) { + const { t } = useTranslation('servers') + if (!renewal) { + return null + } + + const originLabels = { + confirmed: 'renewal_origin_confirmed', + projected: 'renewal_origin_projected', + frozen: 'renewal_origin_frozen' + } as const + + return ( + + {t(originLabels[renewal.deadline_origin])} + {renewal.confirmed_expired_at && ( + + {t('renewal_confirmed_history', { + date: formatDateShort(renewal.confirmed_expired_at, { timeZone: renewal.billing_timezone }), + timezone: renewal.billing_timezone + })} + + )} + + ) +} diff --git a/apps/web/src/components/server/server-edit-dialog.tsx b/apps/web/src/components/server/server-edit-dialog.tsx index 020834d57..035655a77 100644 --- a/apps/web/src/components/server/server-edit-dialog.tsx +++ b/apps/web/src/components/server/server-edit-dialog.tsx @@ -4,6 +4,7 @@ import { Check, ChevronsUpDown } from 'lucide-react' import { type FormEvent, useId, useMemo, useReducer, useState } from 'react' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' +import { RenewalDeadlineInfo } from '@/components/server/renewal-deadline-info' import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' import { @@ -19,6 +20,7 @@ import { Dialog, DialogBody, DialogContent, DialogFooter, DialogHeader, DialogTi import { Input } from '@/components/ui/input' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { Switch } from '@/components/ui/switch' import { useServerTags, useUpdateServerTags } from '@/hooks/use-server-tags' import { api } from '@/lib/api-client' import type { ServerGroup, ServerResponse, UpdateServerInput } from '@/lib/api-schema' @@ -77,6 +79,7 @@ export function ServerEditDialog({ server, open, onClose }: ServerEditDialogProp } interface ServerEditState { + automaticRenewal: boolean billingCycle: string billingStartDay: string billingTimezone: string @@ -102,6 +105,7 @@ interface ServerEditAction { function serverEditStateFromServer(server: ServerResponse): ServerEditState { return { + automaticRenewal: server.renewal?.enabled ?? false, billingCycle: server.billing_cycle ?? '', billingStartDay: server.billing_start_day?.toString() ?? '', billingTimezone: server.renewal?.billing_timezone ?? 'UTC', @@ -248,14 +252,18 @@ function ServerEditBasicFields({ function ServerEditBillingFields({ dispatch, + server, state, t }: { dispatch: (action: ServerEditAction) => void + server: ServerResponse state: ServerEditState t: TFunction }) { const timezoneListId = useId() + const prerequisitesId = useId() + const hasPrerequisites = hasAutomaticRenewalPrerequisites(state) const timezones = useMemo( () => ['UTC', ...(typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') : [])], [] @@ -349,6 +357,29 @@ function ServerEditBillingFields({

{t('edit_billing_timezone_hint')}

+
+
+ {t('edit_automatic_renewal')} + dispatch({ type: 'patch', value: { automaticRenewal } })} + /> +
+

+ {t('edit_renewal_prerequisites')} +

+

{t('renewal_forecast_explanation')}

+ +

{t('renewal_cost_independent')}

+
void; ser const initialExpiryDate = serverEditStateFromServer(server).expiredAt const initialBillingTimezone = server.renewal?.billing_timezone ?? 'UTC' const [state, dispatch] = useReducer(serverEditReducer, server, serverEditStateFromServer) + const invalidAutomaticRenewal = state.automaticRenewal && !hasAutomaticRenewalPrerequisites(state) const { data: groups } = useQuery({ queryKey: ['server-groups'], @@ -434,6 +466,7 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser const buildPayload = (): UpdateServerInput => { const renewal = { + ...(state.automaticRenewal !== (server.renewal?.enabled ?? false) && { enabled: state.automaticRenewal }), ...(state.expiredAt !== initialExpiryDate && { expiry_date: state.expiredAt || null }), ...(state.billingTimezone !== initialBillingTimezone && { billing_timezone: state.billingTimezone || null }) } @@ -471,6 +504,9 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser const handleSubmit = async (e: FormEvent) => { e.preventDefault() + if (invalidAutomaticRenewal) { + return + } const parsed = parseTagsInput(tagsInput) if (parsed.error) { toast.error(t(parsed.error)) @@ -505,7 +541,7 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser t={t} tagsInput={tagsInput} /> - + {mutation.error && (
@@ -518,7 +554,7 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser - @@ -527,6 +563,22 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser ) } +function hasAutomaticRenewalPrerequisites(state: ServerEditState): boolean { + if (!(state.expiredAt && ['monthly', 'quarterly', 'yearly'].includes(state.billingCycle) && state.billingTimezone)) { + return false + } + try { + // Numeric UTC offsets are not IANA timezone identifiers. + if (state.billingTimezone.startsWith('+') || state.billingTimezone.startsWith('-')) { + return false + } + new Intl.DateTimeFormat('en', { timeZone: state.billingTimezone }).format() + return true + } catch { + return false + } +} + function Field({ label, children }: { children: React.ReactNode; label: string }) { return (
diff --git a/apps/web/src/components/server/server-edit-renewal.test.tsx b/apps/web/src/components/server/server-edit-renewal.test.tsx index 9ff0053ca..3b9ac0189 100644 --- a/apps/web/src/components/server/server-edit-renewal.test.tsx +++ b/apps/web/src/components/server/server-edit-renewal.test.tsx @@ -7,6 +7,13 @@ import { ServerEditDialog } from './server-edit-dialog' const apiBoundary = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn() })) const CALENDAR_DATES = [{ date: '2026-01-31' }, { date: '2024-02-29' }] +const MISSING_PREREQUISITES = [ + { label: 'date', billingCycle: 'monthly', date: null, timezone: 'America/New_York' }, + { label: 'interval', billingCycle: null, date: '2026-03-08', timezone: 'America/New_York' }, + { label: 'supported interval', billingCycle: 'weekly', date: '2026-03-08', timezone: 'America/New_York' }, + { label: 'valid timezone', billingCycle: 'monthly', date: '2026-03-08', timezone: 'Mars/Olympus' }, + { label: 'IANA timezone', billingCycle: 'monthly', date: '2026-03-08', timezone: '+01:00' } +] // jsdom does not implement the browser animation boundary used by ScrollArea. Element.prototype.getAnimations = () => [] @@ -68,6 +75,77 @@ afterEach(async () => { }) describe('server renewal date editing', () => { + it.each(MISSING_PREREQUISITES)('cannot opt in without a $label', (input) => { + renderEditor({ + ...server, + billing_cycle: input.billingCycle, + renewal: { ...server.renewal, expiry_date: input.date, billing_timezone: input.timezone } + }) + const automaticRenewal = screen.getByRole('switch', { name: 'Automatic renewal tracking' }) + expect(automaticRenewal).toHaveAttribute('aria-disabled', 'true') + fireEvent.click(automaticRenewal) + expect(automaticRenewal).not.toBeChecked() + expect(automaticRenewal).toHaveAccessibleDescription( + 'Choose an expiry date, a monthly, quarterly or yearly interval, and a valid IANA billing timezone.' + ) + }) + + it('omits renewal intent after restoring the original automatic setting', async () => { + renderEditor({ ...server, renewal: { ...server.renewal, enabled: true } }) + const automaticRenewal = screen.getByRole('switch', { name: 'Automatic renewal tracking' }) + fireEvent.click(automaticRenewal) + fireEvent.click(automaticRenewal) + fireEvent.change(screen.getByRole('spinbutton', { name: 'Price' }), { target: { value: '12.50' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + }) + + it('distinguishes the projected deadline from confirmed history and explains the forecast', () => { + renderEditor({ ...server, renewal: { ...server.renewal, enabled: true } }) + + expect(screen.getByText('Projected deadline')).toBeInTheDocument() + expect(screen.getByText('Last operator-confirmed expiry: 2/8/2026 (America/New_York)')).toBeInTheDocument() + expect( + screen.getByText( + 'Tracking advances the forecast after each expiry date ends. Disabling freezes the current deadline. This estimate does not confirm provider renewal or payment.' + ) + ).toBeInTheDocument() + expect(screen.getByText('Renewal deadline is separate from the cost estimation period.')).toBeInTheDocument() + }) + + it('blocks an enabled configuration with a cleared date until tracking is disabled', async () => { + renderEditor({ ...server, renewal: { ...server.renewal, enabled: true } }) + fireEvent.click(screen.getByRole('button', { name: 'Clear expiration date' })) + fireEvent.change(screen.getByLabelText('Billing timezone'), { target: { value: '' } }) + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled() + expect(screen.getByRole('alert')).toHaveTextContent( + 'Choose an expiry date, a monthly, quarterly or yearly interval, and a valid IANA billing timezone.' + ) + fireEvent.click(screen.getByRole('switch', { name: 'Automatic renewal tracking' })) + expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled() + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1].renewal).toEqual({ + enabled: false, + expiry_date: null, + billing_timezone: null + }) + }) + + it('opts in to automatic renewal without resubmitting the selected date or timezone', async () => { + renderEditor() + const automaticRenewal = screen.getByRole('switch', { name: 'Automatic renewal tracking' }) + expect(automaticRenewal).not.toBeChecked() + fireEvent.click(automaticRenewal) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1].renewal).toEqual({ enabled: true }) + }) + it('selects a billing date even when that date is skipped in the browser timezone', async () => { renderEditor({ ...server, @@ -213,5 +291,13 @@ describe('server renewal date editing', () => { expect(screen.getByLabelText('账单时区')).toHaveValue('America/New_York') expect(screen.getByText('请选择 IANA 时区。服务有效期包含此时区内所选到期日期的整天。')).toBeInTheDocument() expect(screen.getByRole('button', { name: '清除到期日期' })).toBeInTheDocument() + expect(screen.getByRole('switch', { name: '自动续费跟踪' })).not.toBeChecked() + expect(screen.getByText('预测到期日')).toBeInTheDocument() + expect(screen.getByText('请选择到期日期、月付/季付/年付周期和有效的 IANA 账单时区。')).toBeInTheDocument() + expect( + screen.getByText( + '跟踪会在每个到期日期结束后推进预测。关闭后将冻结当前到期日。该估算不代表服务商已续费或付款成功。' + ) + ).toBeInTheDocument() }) }) diff --git a/apps/web/src/locales/en/servers.json b/apps/web/src/locales/en/servers.json index e2504dc1a..dd56bb539 100644 --- a/apps/web/src/locales/en/servers.json +++ b/apps/web/src/locales/en/servers.json @@ -367,5 +367,12 @@ "upgrade_status_failed": "Upgrade failed", "upgrade_status_timeout": "Upgrade timed out", "upgrade_error_with_backup": "Backup saved at", - "upgrade_backup_path": "Backup location" + "upgrade_backup_path": "Backup location", + "edit_automatic_renewal": "Automatic renewal tracking", + "edit_renewal_prerequisites": "Choose an expiry date, a monthly, quarterly or yearly interval, and a valid IANA billing timezone.", + "renewal_origin_confirmed": "Operator-confirmed deadline", + "renewal_origin_projected": "Projected deadline", + "renewal_origin_frozen": "Frozen projected deadline", + "renewal_confirmed_history": "Last operator-confirmed expiry: {{date}} ({{timezone}})", + "renewal_forecast_explanation": "Tracking advances the forecast after each expiry date ends. Disabling freezes the current deadline. This estimate does not confirm provider renewal or payment." } diff --git a/apps/web/src/locales/zh/servers.json b/apps/web/src/locales/zh/servers.json index 959b0ab71..2635a4fce 100644 --- a/apps/web/src/locales/zh/servers.json +++ b/apps/web/src/locales/zh/servers.json @@ -367,5 +367,12 @@ "upgrade_status_failed": "升级失败", "upgrade_status_timeout": "升级超时", "upgrade_error_with_backup": "备份保存在", - "upgrade_backup_path": "备份位置" + "upgrade_backup_path": "备份位置", + "edit_automatic_renewal": "自动续费跟踪", + "edit_renewal_prerequisites": "请选择到期日期、月付/季付/年付周期和有效的 IANA 账单时区。", + "renewal_origin_confirmed": "操作员确认的到期日", + "renewal_origin_projected": "预测到期日", + "renewal_origin_frozen": "已冻结的预测到期日", + "renewal_confirmed_history": "上次操作员确认的到期日:{{date}}({{timezone}})", + "renewal_forecast_explanation": "跟踪会在每个到期日期结束后推进预测。关闭后将冻结当前到期日。该估算不代表服务商已续费或付款成功。" } From f562d46b962e9a10ea3a612057b4e28d17869bbf Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:00:15 +0000 Subject: [PATCH 13/40] feat(renewal): persist anchored forecasts and catch up offline schedules --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 2 + crates/server/src/router/api/server.rs | 14 +- crates/server/src/service/alert.rs | 92 ++++-- crates/server/src/service/mod.rs | 2 + crates/server/src/service/renewal.rs | 201 +++++++++++- crates/server/src/service/renewal_clock.rs | 13 + crates/server/src/service/server.rs | 32 +- .../server/src/service/server_onboarding.rs | 40 ++- crates/server/src/state.rs | 19 +- crates/server/src/task/alert_evaluator.rs | 46 ++- crates/server/tests/common/mod.rs | 13 +- crates/server/tests/renewal_projection.rs | 298 +++++++++++++++++- 13 files changed, 687 insertions(+), 86 deletions(-) create mode 100644 crates/server/src/service/renewal_clock.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ccdc202e8..260521b2b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -237,6 +237,7 @@ jobs: --test router_probes_extra --test router_security_rate --test renewal_dates + --test renewal_projection --test router_server_crud --test router_server_extra --test router_server_extra2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d0bfc47d..d94751648 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Opt-in automatic renewal tracking** -- Web and native iOS administrators can enable anchored monthly, quarterly or yearly expiry forecasts. The Server catches up after downtime while the Agent is offline, preserves confirmed expiry history and freezes the same projected deadline when tracking is disabled. Forecasts do not confirm provider renewal or payment + - **Billing-calendar renewal dates** -- Web and native iOS administrators can edit a local expiry date in its stored IANA billing timezone. The Server preserves historical expiry instants on unchanged saves and applies the complete local expiry day to explicit date changes ### Fixed diff --git a/crates/server/src/router/api/server.rs b/crates/server/src/router/api/server.rs index 9f7a56940..0bd3ab4ef 100644 --- a/crates/server/src/router/api/server.rs +++ b/crates/server/src/router/api/server.rs @@ -1052,7 +1052,8 @@ async fn update_server( // Capabilities are agent-owned and not writable here (the `capabilities` // field was removed from `UpdateServerInput`), so updating a server can no // longer change what the agent is allowed to do. - let server = ServerService::update_server(&state.db, &id, input).await?; + let server = + ServerService::update_server_at(&state.db, &id, input, state.renewal_clock.now()).await?; let authority = state .agent_authority @@ -1717,7 +1718,9 @@ mod delete_audit_tests { async fn delete_server_writes_audit_log() { let (db, _tmp) = setup_test_db().await; insert_server(&db, "srv-del", "Doomed").await; - let state = AppState::new(db.clone(), AppConfig::default()).await.unwrap(); + let state = AppState::new(db.clone(), AppConfig::default()) + .await + .unwrap(); let res = delete_server( State(state.clone()), @@ -1733,8 +1736,7 @@ mod delete_audit_tests { assert!( logs.iter().any(|l| l.action == "server_deleted" && l.user_id == "admin-1" - && l - .detail + && l.detail .as_deref() .is_some_and(|d| d.contains("srv-del") && d.contains("Doomed"))), "expected a server_deleted audit row, got: {logs:?}" @@ -1746,7 +1748,9 @@ mod delete_audit_tests { let (db, _tmp) = setup_test_db().await; insert_server(&db, "srv-a", "A").await; insert_server(&db, "srv-b", "B").await; - let state = AppState::new(db.clone(), AppConfig::default()).await.unwrap(); + let state = AppState::new(db.clone(), AppConfig::default()) + .await + .unwrap(); let res = batch_delete( State(state.clone()), diff --git a/crates/server/src/service/alert.rs b/crates/server/src/service/alert.rs index 050d3d1f0..bd3a1a9f9 100644 --- a/crates/server/src/service/alert.rs +++ b/crates/server/src/service/alert.rs @@ -36,8 +36,7 @@ pub const COVER_TYPE_ALL: &str = "all"; pub const COVER_TYPE_INCLUDE: &str = "include"; pub const COVER_TYPE_EXCLUDE: &str = "exclude"; /// All accepted `cover_type` values for alert_rule and block_list inputs. -pub const VALID_COVER_TYPES: &[&str] = - &[COVER_TYPE_ALL, COVER_TYPE_INCLUDE, COVER_TYPE_EXCLUDE]; +pub const VALID_COVER_TYPES: &[&str] = &[COVER_TYPE_ALL, COVER_TYPE_INCLUDE, COVER_TYPE_EXCLUDE]; /// `origin` discriminants for block_list rows. pub const ORIGIN_MANUAL: &str = "manual"; @@ -45,8 +44,7 @@ pub const ORIGIN_AUTO: &str = "auto"; /// Security rule types whose payload carries a `source_ip` and may attach a /// `block_source_ip` action. -pub const SOURCE_IP_RULE_TYPES: &[&str] = - &["ssh_brute_force_detected", "port_scan_detected"]; +pub const SOURCE_IP_RULE_TYPES: &[&str] = &["ssh_brute_force_detected", "port_scan_detected"]; // ── Alert Rule Types ── @@ -822,6 +820,16 @@ impl AlertService { config: &crate::config::AppConfig, agent_manager: &AgentManager, state_manager: &AlertStateManager, + ) -> Result<(), AppError> { + Self::evaluate_all_at(db, config, agent_manager, state_manager, Utc::now()).await + } + + pub async fn evaluate_all_at( + db: &DatabaseConnection, + config: &crate::config::AppConfig, + agent_manager: &AgentManager, + state_manager: &AlertStateManager, + now: chrono::DateTime, ) -> Result<(), AppError> { // Event-driven conditions cannot be re-polled. Replay captured intents // before ordinary rules, including the first tick after Server restart. @@ -855,7 +863,7 @@ impl AlertService { } if let Err(e) = - Self::evaluate_rule(db, config, agent_manager, state_manager, &rule).await + Self::evaluate_rule_at(db, config, agent_manager, state_manager, &rule, now).await { tracing::error!("Error evaluating alert rule '{}': {e}", rule.name); } @@ -863,12 +871,24 @@ impl AlertService { Ok(()) } + #[cfg(test)] async fn evaluate_rule( db: &DatabaseConnection, config: &crate::config::AppConfig, agent_manager: &AgentManager, state_manager: &AlertStateManager, rule: &alert_rule::Model, + ) -> Result<(), AppError> { + Self::evaluate_rule_at(db, config, agent_manager, state_manager, rule, Utc::now()).await + } + + async fn evaluate_rule_at( + db: &DatabaseConnection, + config: &crate::config::AppConfig, + agent_manager: &AgentManager, + state_manager: &AlertStateManager, + rule: &alert_rule::Model, + now: chrono::DateTime, ) -> Result<(), AppError> { let items: Vec = serde_json::from_str(&rule.rules_json).unwrap_or_default(); if items.is_empty() { @@ -878,7 +898,7 @@ impl AlertService { let servers = resolve_servers(db, &rule.cover_type, &rule.server_ids_json).await?; for srv in &servers { - let triggered = Self::check_server(db, agent_manager, &items, &srv.id).await; + let triggered = Self::check_server_at(db, agent_manager, &items, &srv.id, now).await; if triggered { // Skip alerting if the server is in a maintenance window @@ -906,11 +926,22 @@ impl AlertService { Ok(()) } + #[cfg(test)] async fn check_server( db: &DatabaseConnection, agent_manager: &AgentManager, items: &[AlertRuleItem], server_id: &str, + ) -> bool { + Self::check_server_at(db, agent_manager, items, server_id, Utc::now()).await + } + + async fn check_server_at( + db: &DatabaseConnection, + agent_manager: &AgentManager, + items: &[AlertRuleItem], + server_id: &str, + now: chrono::DateTime, ) -> bool { for item in items { let matched = match item.rule_type.as_str() { @@ -936,7 +967,7 @@ impl AlertService { } "expiration" => { // Check if server's expired_at is within N days (default 7) - check_expiration(db, server_id, item).await + check_expiration_at(db, server_id, item, now).await } "network_latency" => check_network_latency(db, server_id, item).await, "network_packet_loss" => check_network_packet_loss(db, server_id, item).await, @@ -1268,7 +1299,17 @@ async fn check_transfer_cycle( /// Check if a server's `expired_at` is within N days of now (or already expired). /// `item.duration` = days threshold (default 7). Triggers if expired_at is set and /// expires within that many days. +#[cfg(test)] async fn check_expiration(db: &DatabaseConnection, server_id: &str, item: &AlertRuleItem) -> bool { + check_expiration_at(db, server_id, item, Utc::now()).await +} + +async fn check_expiration_at( + db: &DatabaseConnection, + server_id: &str, + item: &AlertRuleItem, + now: chrono::DateTime, +) -> bool { let srv = server::Entity::find_by_id(server_id) .one(db) .await @@ -1281,7 +1322,7 @@ async fn check_expiration(db: &DatabaseConnection, server_id: &str, item: &Alert return false; }; let days_threshold = item.duration.unwrap_or(7) as i64; - let deadline = Utc::now() + Duration::days(days_threshold); + let deadline = now + Duration::days(days_threshold); expired_at <= deadline } @@ -1635,10 +1676,7 @@ mod tests { #[test] fn test_validate_rejects_multiple_security_items() { - let items = vec![ - item("ssh_brute_force_detected"), - item("ssh_new_ip_login"), - ]; + let items = vec![item("ssh_brute_force_detected"), item("ssh_new_ip_login")]; let err = validate_alert_rule_items(&items).expect_err("should reject multi-security"); assert!(matches!(err, AppError::BadRequest(_))); } @@ -1864,8 +1902,7 @@ mod tests { _ => break, } } - let _ = socket - .try_write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + let _ = socket.try_write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); let _ = tx.send(String::from_utf8_lossy(&buf).into_owned()); } }); @@ -1984,7 +2021,10 @@ mod tests { .expect("query states"); assert_eq!(rows.len(), 1, "no duplicate alert_state rows"); assert!(!rows[0].resolved, "re-armed row should be firing again"); - assert!(rows[0].resolved_at.is_none(), "resolved_at cleared on re-arm"); + assert!( + rows[0].resolved_at.is_none(), + "resolved_at cleared on re-arm" + ); assert_eq!(rows[0].count, 1, "count reset on re-arm"); } @@ -2620,10 +2660,12 @@ mod tests { async fn test_latest_record_time_picks_latest_and_none() { let (db, _tmp) = setup_test_db().await; // No records => None. - assert!(RecordService::latest_record_time(&db, "srv-1") - .await - .expect("query should succeed") - .is_none()); + assert!( + RecordService::latest_record_time(&db, "srv-1") + .await + .expect("query should succeed") + .is_none() + ); let older = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap(); let newer = Utc.with_ymd_and_hms(2026, 1, 1, 1, 0, 0).unwrap(); @@ -3104,15 +3146,9 @@ mod tests { let state_manager = AlertStateManager::new(); let config = crate::config::AppConfig::default(); - AlertService::check_event_rules( - &db, - &config, - &state_manager, - "srv-1", - "ssh_new_ip_login", - ) - .await - .expect("check_event_rules"); + AlertService::check_event_rules(&db, &config, &state_manager, "srv-1", "ssh_new_ip_login") + .await + .expect("check_event_rules"); assert!(!state_manager.is_triggered("rule-ip", "srv-1", "")); } diff --git a/crates/server/src/service/mod.rs b/crates/server/src/service/mod.rs index 675992585..029ab0f32 100644 --- a/crates/server/src/service/mod.rs +++ b/crates/server/src/service/mod.rs @@ -58,3 +58,5 @@ pub(crate) mod task_notification; pub(crate) mod alert_event_intents; pub mod renewal; + +pub mod renewal_clock; diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs index 9df45f20b..27d70834f 100644 --- a/crates/server/src/service/renewal.rs +++ b/crates/server/src/service/renewal.rs @@ -1,20 +1,31 @@ //! Server-owned billing calendar contract. Clients submit dates, never UTC boundaries. use crate::{entity::server, error::AppError}; -use chrono::{DateTime, Duration, NaiveDate, TimeZone, Utc}; +use chrono::{DateTime, Datelike, Duration, NaiveDate, TimeZone, Utc}; use chrono_tz::Tz; +use sea_orm::{ + ActiveModelTrait, ColumnTrait, DatabaseConnection, DatabaseTransaction, EntityTrait, + QueryFilter, Set, TransactionTrait, +}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct RenewalState { #[serde(default)] pub enabled: bool, + #[serde(default)] + pub deadline_origin: DeadlineOrigin, + #[serde(default)] + pub anchor_day: Option, + #[serde(default)] + pub occurrence_id: Option, pub billing_timezone: String, pub confirmed_expired_at: Option>, } -#[derive(Clone, Debug, Serialize, Deserialize, utoipa::ToSchema)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "snake_case")] pub enum DeadlineOrigin { + #[default] Confirmed, Projected, Frozen, @@ -53,18 +64,82 @@ impl RenewalState { .and_then(|s| serde_json::from_str(s).ok()) .unwrap_or_else(|| Self { enabled: false, + deadline_origin: DeadlineOrigin::Confirmed, + anchor_day: None, + occurrence_id: None, billing_timezone: "UTC".into(), confirmed_expired_at: model.expired_at, }) } + /// Catch up directly to the first unexpired occurrence, retaining the original day anchor. + /// No historical occurrence is admitted or represented as a payment. + pub fn advance( + &mut self, + deadline: &mut Option>, + cycle: Option<&str>, + now: DateTime, + ) -> Result { + if !self.enabled { + return Ok(false); + } + validate_enabled(self, *deadline, cycle)?; + let original = deadline.expect("enabled configuration was validated"); + let date = selected_date(Some(original), &self.billing_timezone) + .ok_or_else(|| AppError::Validation("invalid billing timezone".into()))?; + let anchor = *self.anchor_day.get_or_insert(date.day()); + if self.occurrence_id.is_none() { + self.occurrence_id = Some(uuid::Uuid::new_v4().to_string()); + } + if original >= now { + return Ok(false); + } + let interval: i32 = match cycle { + Some("monthly") => 1, + Some("quarterly") => 3, + Some("yearly") => 12, + _ => unreachable!(), + }; + let today = selected_date(Some(now), &self.billing_timezone).expect("validated timezone"); + let difference = + (today.year() - date.year()) * 12 + today.month() as i32 - date.month() as i32; + let mut periods = (difference / interval).max(1); + loop { + let month_index = date + .year() + .checked_mul(12) + .and_then(|year| year.checked_add(date.month0() as i32)) + .and_then(|month| month.checked_add(periods.checked_mul(interval)?)) + .ok_or_else(|| AppError::Validation("renewal date is out of range".into()))?; + let year = month_index.div_euclid(12); + let month = month_index.rem_euclid(12) as u32 + 1; + let mut day = anchor; + let candidate = loop { + if let Some(date) = NaiveDate::from_ymd_opt(year, month, day) { + break date; + } + day = day + .checked_sub(1) + .filter(|day| *day > 0) + .ok_or_else(|| AppError::Validation("renewal date is out of range".into()))?; + }; + let boundary = date_boundary(candidate, &self.billing_timezone)?; + if boundary >= now { + *deadline = Some(boundary); + self.deadline_origin = DeadlineOrigin::Projected; + self.occurrence_id = Some(uuid::Uuid::new_v4().to_string()); + return Ok(true); + } + periods += 1; + } + } pub fn projection(&self, deadline: Option>) -> RenewalProjection { RenewalProjection { enabled: self.enabled, billing_timezone: self.billing_timezone.clone(), expiry_date: selected_date(deadline, &self.billing_timezone).map(|d| d.to_string()), confirmed_expired_at: self.confirmed_expired_at, - deadline_origin: DeadlineOrigin::Confirmed, - occurrence_id: None, + deadline_origin: self.deadline_origin.clone(), + occurrence_id: self.occurrence_id.clone(), } } } @@ -112,15 +187,20 @@ pub fn apply_edit( input: Option<&RenewalInput>, legacy: Option>>, billing_cycle: Option<&str>, + now: DateTime, ) -> Result<(RenewalState, Option>), AppError> { - let result = apply_calendar( - RenewalState::from_server(model), - model.expired_at, - input, - legacy, - )?; + let previous = RenewalState::from_server(model); + let enabling = !previous.enabled && input.and_then(|i| i.enabled) == Some(true); + let result = apply_calendar(previous, model.expired_at, input, legacy)?; validate_enabled(&result.0, result.1, billing_cycle)?; - Ok(result) + let (mut state, mut deadline) = result; + if enabling { + deadline = selected_date(deadline, &state.billing_timezone) + .map(|date| date_boundary(date, &state.billing_timezone)) + .transpose()?; + } + state.advance(&mut deadline, billing_cycle, now)?; + Ok((state, deadline)) } pub fn apply_initial( @@ -137,7 +217,10 @@ pub fn apply_initial( let result = apply_calendar( RenewalState { enabled: false, - billing_timezone: "UTC".into(), + deadline_origin: DeadlineOrigin::Confirmed, + anchor_day: None, + occurrence_id: None, + billing_timezone: "UTC".into(), confirmed_expired_at: legacy, }, legacy, @@ -145,11 +228,24 @@ pub fn apply_initial( None, )?; validate_enabled(&result.0, result.1, billing_cycle)?; - Ok(result) + let (mut state, mut deadline) = result; + if state.enabled { + deadline = selected_date(deadline, &state.billing_timezone) + .map(|date| date_boundary(date, &state.billing_timezone)) + .transpose()?; + } + state.occurrence_id = None; + Ok((state, deadline)) } -fn validate_enabled(state: &RenewalState, deadline: Option>, cycle: Option<&str>) -> Result<(), AppError> { - if state.enabled && (deadline.is_none() || !matches!(cycle, Some("monthly" | "quarterly" | "yearly"))) { +fn validate_enabled( + state: &RenewalState, + deadline: Option>, + cycle: Option<&str>, +) -> Result<(), AppError> { + if state.enabled + && (deadline.is_none() || !matches!(cycle, Some("monthly" | "quarterly" | "yearly"))) + { return Err(AppError::Validation("automatic renewal requires an expiry date and monthly, quarterly or yearly billing_cycle".into())); } Ok(()) @@ -161,6 +257,12 @@ fn apply_calendar( input: Option<&RenewalInput>, legacy: Option>>, ) -> Result<(RenewalState, Option>), AppError> { + let resulting_enabled = input.and_then(|i| i.enabled).unwrap_or(state.enabled); + if resulting_enabled && input.is_some_and(|i| matches!(i.billing_timezone, Some(None))) { + return Err(AppError::Validation( + "automatic renewal requires a billing timezone".into(), + )); + } let old_date = selected_date(original, &state.billing_timezone); let mut deadline = original; let mut timezone_changed = false; @@ -228,8 +330,77 @@ fn apply_calendar( .map(|d| date_boundary(d, &state.billing_timezone)) .transpose()?; } + if date_replaced { + state.deadline_origin = DeadlineOrigin::Confirmed; + state.anchor_day = selected_date(deadline, &state.billing_timezone).map(|d| d.day()); + state.occurrence_id = deadline.map(|_| uuid::Uuid::new_v4().to_string()); + } if let Some(enabled) = input.and_then(|i| i.enabled) { state.enabled = enabled; } + if !state.enabled && state.deadline_origin == DeadlineOrigin::Projected { + state.deadline_origin = DeadlineOrigin::Frozen; + } + if state.enabled { + state.deadline_origin = DeadlineOrigin::Projected; + if state.anchor_day.is_none() { + state.anchor_day = selected_date(deadline, &state.billing_timezone).map(|d| d.day()); + } + if state.occurrence_id.is_none() { + state.occurrence_id = deadline.map(|_| uuid::Uuid::new_v4().to_string()); + } + } Ok((state, deadline)) } + +/// Reserve the SQLite writer before reading a schedule. CRUD, advancement and +/// reminder admission can share this transaction and cannot overwrite a newer snapshot. +pub async fn load_for_update( + tx: &DatabaseTransaction, + id: &str, +) -> Result { + server::Entity::update_many() + .col_expr( + server::Column::ExpiredAt, + sea_orm::prelude::Expr::col(server::Column::ExpiredAt).into(), + ) + .filter(server::Column::Id.eq(id)) + .exec(tx) + .await?; + server::Entity::find_by_id(id) + .one(tx) + .await? + .ok_or_else(|| AppError::NotFound("Server not found".into())) +} + +/// Production catch-up evaluates each server from a stable, freshly locked schedule. +pub async fn advance_all(db: &DatabaseConnection, now: DateTime) -> Result<(), AppError> { + let servers = server::Entity::find().all(db).await?; + for candidate in servers { + if !RenewalState::from_server(&candidate).enabled { + continue; + } + let tx = db.begin().await?; + let model = match load_for_update(&tx, &candidate.id).await { + Ok(model) => model, + Err(AppError::NotFound(_)) => { + tx.rollback().await?; + continue; + } + Err(error) => return Err(error), + }; + let mut state = RenewalState::from_server(&model); + let mut deadline = model.expired_at; + if state.advance(&mut deadline, model.billing_cycle.as_deref(), now)? { + let mut active: server::ActiveModel = model.into(); + active.expired_at = Set(deadline); + active.renewal_state = Set(Some( + serde_json::to_string(&state).map_err(|e| AppError::Internal(e.to_string()))?, + )); + active.updated_at = Set(now); + active.update(&tx).await?; + } + tx.commit().await?; + } + Ok(()) +} diff --git a/crates/server/src/service/renewal_clock.rs b/crates/server/src/service/renewal_clock.rs new file mode 100644 index 000000000..8fb0b67d9 --- /dev/null +++ b/crates/server/src/service/renewal_clock.rs @@ -0,0 +1,13 @@ +//! One time boundary for renewal lifecycle and expiration reminder evaluation. +use chrono::{DateTime, Utc}; + +pub trait RenewalClock: Send + Sync { + fn now(&self) -> DateTime; +} + +pub struct SystemRenewalClock; +impl RenewalClock for SystemRenewalClock { + fn now(&self) -> DateTime { + Utc::now() + } +} diff --git a/crates/server/src/service/server.rs b/crates/server/src/service/server.rs index 2c928b839..cce9528e2 100644 --- a/crates/server/src/service/server.rs +++ b/crates/server/src/service/server.rs @@ -81,11 +81,30 @@ impl ServerService { id: &str, input: UpdateServerInput, ) -> Result { - let model = Self::get_server(db, id).await?; - Self::validate_update_input(&input)?; + Self::update_server_at(db, id, input, Utc::now()).await + } - let (renewal, deadline) = - super::renewal::apply_edit(&model, input.renewal.as_ref(), input.expired_at, input.billing_cycle.as_ref().map(|c| c.as_deref()).unwrap_or(model.billing_cycle.as_deref()))?; + pub async fn update_server_at( + db: &DatabaseConnection, + id: &str, + input: UpdateServerInput, + now: chrono::DateTime, + ) -> Result { + Self::validate_update_input(&input)?; + let tx = db.begin().await?; + let model = super::renewal::load_for_update(&tx, id).await?; + + let (renewal, deadline) = super::renewal::apply_edit( + &model, + input.renewal.as_ref(), + input.expired_at, + input + .billing_cycle + .as_ref() + .map(|c| c.as_deref()) + .unwrap_or(model.billing_cycle.as_deref()), + now, + )?; let mut active: server::ActiveModel = model.into(); active.renewal_state = Set(Some( serde_json::to_string(&renewal).map_err(|e| AppError::Validation(e.to_string()))?, @@ -147,8 +166,9 @@ impl ServerService { // owned by the agent host (its config file) and the server only // mirrors what the agent reports — see `update_capabilities_mirror`. - active.updated_at = Set(Utc::now()); - let updated = active.update(db).await?; + active.updated_at = Set(now); + let updated = active.update(&tx).await?; + tx.commit().await?; Ok(updated) } diff --git a/crates/server/src/service/server_onboarding.rs b/crates/server/src/service/server_onboarding.rs index ee15aab3e..526054c0d 100644 --- a/crates/server/src/service/server_onboarding.rs +++ b/crates/server/src/service/server_onboarding.rs @@ -97,6 +97,7 @@ pub struct ServerOnboarding { db: DatabaseConnection, authority: Arc, max_servers: u32, + renewal_clock: Arc, request_locks: Arc>>>, } @@ -117,8 +118,23 @@ impl Drop for RequestLockCleanup { impl ServerOnboarding { pub fn new(db: DatabaseConnection, authority: Arc, max_servers: u32) -> Self { + Self::new_with_renewal_clock( + db, + authority, + max_servers, + Arc::new(super::renewal_clock::SystemRenewalClock), + ) + } + + pub fn new_with_renewal_clock( + db: DatabaseConnection, + authority: Arc, + max_servers: u32, + renewal_clock: Arc, + ) -> Self { Self { db, + renewal_clock, authority, max_servers, request_locks: Arc::new(DashMap::new()), @@ -182,7 +198,16 @@ impl ServerOnboarding { let server_id = ServerId::parse(Uuid::new_v4().to_string()) .map_err(|error| AppError::Internal(format!("generated invalid server id: {error}")))?; - let now = Utc::now(); + let now = self.renewal_clock.now(); + let mut deadline = normalized.expired_at; + let renewal_state = if let Some(serialized) = normalized.renewal_state.as_ref() { + let mut renewal: super::renewal::RenewalState = + serde_json::from_str(serialized).map_err(|e| AppError::Internal(e.to_string()))?; + renewal.advance(&mut deadline, normalized.billing_cycle.as_deref(), now)?; + Some(serde_json::to_string(&renewal).map_err(|e| AppError::Internal(e.to_string()))?) + } else { + None + }; let row = server::ActiveModel { id: Set(server_id.as_str().to_string()), token_hash: Set(None), @@ -211,8 +236,8 @@ impl ServerOnboarding { price: Set(normalized.price), billing_cycle: Set(normalized.billing_cycle.clone()), currency: Set(normalized.currency.clone()), - renewal_state: Set(normalized.renewal_state.clone()), - expired_at: Set(normalized.expired_at), + renewal_state: Set(renewal_state), + expired_at: Set(deadline), traffic_limit: Set(normalized.traffic_limit), traffic_limit_type: Set(normalized.traffic_limit_type.clone()), billing_start_day: Set(normalized.billing_start_day), @@ -338,9 +363,12 @@ impl NormalizedProfile { )); } - let (renewal, expired_at) = - super::renewal::apply_initial(profile.renewal.as_ref(), profile.expired_at, profile.billing_cycle.as_deref()) - .map_err(|e| OnboardingError::Validation(e.to_string()))?; + let (renewal, expired_at) = super::renewal::apply_initial( + profile.renewal.as_ref(), + profile.expired_at, + profile.billing_cycle.as_deref(), + ) + .map_err(|e| OnboardingError::Validation(e.to_string()))?; // Preserve the predecessor canonical hash for legacy onboarding retries. let renewal_state = profile .renewal diff --git a/crates/server/src/state.rs b/crates/server/src/state.rs index 599c41614..4b0926817 100644 --- a/crates/server/src/state.rs +++ b/crates/server/src/state.rs @@ -75,6 +75,7 @@ pub struct RateLimitEntry { pub struct AppState { pub db: DatabaseConnection, + pub renewal_clock: Arc, pub agent_manager: Arc, pub agent_authority: Arc, pub server_onboarding: Arc, @@ -189,13 +190,28 @@ impl AppState { } pub async fn new(db: DatabaseConnection, config: AppConfig) -> Result, AppError> { + Self::new_with_renewal_clock( + db, + config, + Arc::new(crate::service::renewal_clock::SystemRenewalClock), + ) + .await + } + + pub async fn new_with_renewal_clock( + db: DatabaseConnection, + config: AppConfig, + renewal_clock: Arc, + ) -> Result, AppError> { + crate::service::renewal::advance_all(&db, renewal_clock.now()).await?; let (browser_tx, _) = broadcast::channel(256); let agent_manager = Arc::new(AgentManager::new(browser_tx.clone())); let agent_authority = Arc::new(AgentAuthority::new(db.clone(), agent_manager.clone())); - let server_onboarding = Arc::new(ServerOnboarding::new( + let server_onboarding = Arc::new(ServerOnboarding::new_with_renewal_clock( db.clone(), agent_authority.clone(), config.auth.max_servers, + renewal_clock.clone(), )); let upgrade_tracker = UpgradeJobTracker::new(browser_tx.clone()); let upgrade_release_service = UpgradeReleaseService::new(&config.upgrade); @@ -263,6 +279,7 @@ impl AppState { crate::service::traceroute_enrich::TracerouteEnricher::new().with_asn(asn_arc.clone()); Ok(Arc::new(Self { db, + renewal_clock, agent_manager, agent_authority, server_onboarding, diff --git a/crates/server/src/task/alert_evaluator.rs b/crates/server/src/task/alert_evaluator.rs index ec942011f..a33af643c 100644 --- a/crates/server/src/task/alert_evaluator.rs +++ b/crates/server/src/task/alert_evaluator.rs @@ -1,8 +1,12 @@ use std::sync::Arc; +#[cfg(test)] use crate::config::AppConfig; +#[cfg(test)] use crate::service::agent_manager::AgentManager; -use crate::service::alert::{AlertService, AlertStateManager}; +use crate::service::alert::AlertService; +#[cfg(test)] +use crate::service::alert::AlertStateManager; use crate::state::AppState; /// Runs every 60 seconds to evaluate all enabled alert rules. @@ -14,19 +18,30 @@ pub async fn run(state: Arc) { loop { interval.tick().await; - evaluate_tick( - &state.db, - &state.config, - &state.agent_manager, - &state.alert_state_manager, - ) - .await; + if let Err(error) = evaluate_once(&state).await { + tracing::error!("Renewal/alert evaluation error: {error}"); + } } } +/// One production scheduler iteration, also used with a controlled renewal clock. +pub async fn evaluate_once(state: &AppState) -> Result<(), crate::error::AppError> { + let now = state.renewal_clock.now(); + crate::service::renewal::advance_all(&state.db, now).await?; + AlertService::evaluate_all_at( + &state.db, + &state.config, + &state.agent_manager, + &state.alert_state_manager, + now, + ) + .await +} + /// Performs the per-tick work of the alert evaluator: evaluate all enabled /// alert rules once and log any error. Extracted from the `run` loop so it can /// be exercised in isolation; behavior (work, ordering, logging) is unchanged. +#[cfg(test)] pub(crate) async fn evaluate_tick( db: &sea_orm::DatabaseConnection, config: &AppConfig, @@ -62,7 +77,12 @@ mod tests { let (browser_tx, _rx) = broadcast::channel::(16); let agent_manager = AgentManager::new(browser_tx.clone()); let state_manager = AlertStateManager::new(); - (agent_manager, state_manager, AppConfig::default(), browser_tx) + ( + agent_manager, + state_manager, + AppConfig::default(), + browser_tx, + ) } async fn insert_test_server(db: &sea_orm::DatabaseConnection, id: &str, name: &str) { @@ -139,13 +159,7 @@ mod tests { let (db, _tmp) = setup_test_db().await; insert_test_server(&db, "s1", "Srv").await; // A rule whose only item is the event-driven `ip_changed` type. - insert_alert_rule( - &db, - "r-event", - true, - r#"[{"rule_type":"ip_changed"}]"#, - ) - .await; + insert_alert_rule(&db, "r-event", true, r#"[{"rule_type":"ip_changed"}]"#).await; let (agent_manager, state_manager, config, _tx) = build_deps(); evaluate_tick(&db, &config, &agent_manager, &state_manager).await; diff --git a/crates/server/tests/common/mod.rs b/crates/server/tests/common/mod.rs index a2cca95b2..cc6541716 100644 --- a/crates/server/tests/common/mod.rs +++ b/crates/server/tests/common/mod.rs @@ -36,6 +36,17 @@ pub async fn start_test_server_with_state() -> (String, tempfile::TempDir, std:: /// Longer identity scenarios isolate their assertions from the separate rate tests. pub async fn start_test_server_with_login_limit( login_max: u32, +) -> (String, tempfile::TempDir, std::sync::Arc) { + start_test_server_with_renewal_clock( + login_max, + std::sync::Arc::new(serverbee_server::service::renewal_clock::SystemRenewalClock), + ) + .await +} + +pub async fn start_test_server_with_renewal_clock( + login_max: u32, + clock: std::sync::Arc, ) -> (String, tempfile::TempDir, std::sync::Arc) { let tmp = tempfile::tempdir().expect("Failed to create temp dir"); let data_dir = tmp.path().to_str().unwrap().to_string(); @@ -88,7 +99,7 @@ pub async fn start_test_server_with_login_limit( .await .expect("Failed to seed admin"); - let state = AppState::new(db, config) + let state = AppState::new_with_renewal_clock(db, config, clock) .await .expect("Failed to create AppState"); let security_recovery = state.security_service.start_recovery(); diff --git a/crates/server/tests/renewal_projection.rs b/crates/server/tests/renewal_projection.rs index 6ee3f811d..fbece141d 100644 --- a/crates/server/tests/renewal_projection.rs +++ b/crates/server/tests/renewal_projection.rs @@ -9,12 +9,25 @@ async fn automatic_renewal_requires_complete_resulting_configuration_atomically( let admin = http_client(); login_admin(&admin, &base).await; let id = create_server(&admin, &base, "manual-host").await; - let response = admin.put(format!("{base}/api/servers/{id}")) + let response = admin + .put(format!("{base}/api/servers/{id}")) .json(&json!({"name":"must-not-change","renewal":{"enabled":true}})) - .send().await.unwrap(); - assert_eq!(response.status(), 422, "enabled renewal must require date and interval"); - let body: Value = admin.get(format!("{base}/api/servers/{id}")) - .send().await.unwrap().json().await.unwrap(); + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + 422, + "enabled renewal must require date and interval" + ); + let body: Value = admin + .get(format!("{base}/api/servers/{id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); assert_eq!(body["data"]["name"], "manual-host"); assert_eq!(body["data"]["renewal"]["enabled"], false); } @@ -22,7 +35,8 @@ async fn automatic_renewal_requires_complete_resulting_configuration_atomically( #[tokio::test] async fn opt_in_projects_without_promoting_operator_history_to_payment_information() { let (base, _tmp) = start_test_server().await; - let admin = http_client(); login_admin(&admin, &base).await; + let admin = http_client(); + login_admin(&admin, &base).await; let id = create_server(&admin, &base, "expected-renewal").await; let response = admin.put(format!("{base}/api/servers/{id}")) .json(&json!({"billing_cycle":"monthly","price":12.5,"currency":"USD","traffic_limit":1024,"billing_start_day":7,"renewal":{"enabled":true,"expiry_date":"2099-01-31","billing_timezone":"America/New_York"}})) @@ -30,6 +44,274 @@ async fn opt_in_projects_without_promoting_operator_history_to_payment_informati assert_eq!(response.status(), 200); let body: Value = response.json().await.unwrap(); assert_eq!(body["data"]["renewal"]["deadline_origin"], "projected"); - assert_eq!(body["data"]["renewal"]["confirmed_expired_at"], "2099-02-01T04:59:59.999999999Z"); - assert!(body["data"]["renewal"]["occurrence_id"].as_str().is_some_and(|id| !id.is_empty())); + assert_eq!( + body["data"]["renewal"]["confirmed_expired_at"], + "2099-02-01T04:59:59.999999999Z" + ); + assert!( + body["data"]["renewal"]["occurrence_id"] + .as_str() + .is_some_and(|id| !id.is_empty()) + ); +} + +use chrono::{DateTime, Utc}; +use std::sync::{Arc, RwLock}; +struct ManualClock(RwLock>); +impl ManualClock { + fn at(value: &str) -> Arc { + Arc::new(Self(RwLock::new(instant(value)))) + } + fn set(&self, value: &str) { + *self.0.write().unwrap() = instant(value); + } +} +impl serverbee_server::service::renewal_clock::RenewalClock for ManualClock { + fn now(&self) -> DateTime { + *self.0.read().unwrap() + } +} +fn instant(value: &str) -> DateTime { + value.parse().unwrap() +} +async fn controlled_server( + clock: Arc, +) -> ( + String, + tempfile::TempDir, + Arc, +) { + common::start_test_server_with_renewal_clock(100, clock).await +} +async fn detail(admin: &reqwest::Client, base: &str, id: &str) -> Value { + let body: Value = admin + .get(format!("{base}/api/servers/{id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + body["data"].clone() +} + +#[tokio::test] +async fn enabling_overdue_month_end_catches_up_from_original_anchor() { + let clock = ManualClock::at("2026-03-01T05:00:00Z"); + let (base, _tmp, _state) = controlled_server(clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "offline-renewal").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","renewal":{"enabled":true,"expiry_date":"2026-01-31","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let model = detail(&admin, &base, &id).await; + assert_eq!(model["renewal"]["expiry_date"], "2026-03-31"); + assert_eq!(model["expired_at"], "2026-04-01T03:59:59.999999999Z"); + assert_eq!( + model["renewal"]["confirmed_expired_at"], + "2026-02-01T04:59:59.999999999Z" + ); +} + +#[tokio::test] +async fn scheduled_evaluation_advances_offline_month_end_and_restores_anchor_after_dst() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "offline-month-end").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","renewal":{"enabled":true,"expiry_date":"2026-01-31","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + clock.set("2026-02-01T05:00:00Z"); + // The production scheduler's first tick is immediate; no client opens a billing page. + let task = tokio::spawn(serverbee_server::task::alert_evaluator::run(state.clone())); + tokio::time::sleep(std::time::Duration::from_millis(150)).await; + task.abort(); + let model = detail(&admin, &base, &id).await; + assert_eq!(model["renewal"]["expiry_date"], "2026-02-28"); + assert_eq!(model["expired_at"], "2026-03-01T04:59:59.999999999Z"); +} + +async fn reopen( + tmp: &tempfile::TempDir, + clock: Arc, +) -> (String, Arc) { + use serverbee_server::{config::AppConfig, router::create_router, state::AppState}; + let db = sea_orm::Database::connect(format!( + "sqlite://{}?mode=rwc", + tmp.path().join("test.db").display() + )) + .await + .unwrap(); + let mut config = AppConfig::default(); + config.auth.secure_cookie = false; + config.server.data_dir = tmp.path().to_str().unwrap().into(); + let state = AppState::new_with_renewal_clock(db, config, clock) + .await + .unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let app = create_router(state.clone()); + tokio::spawn(async move { + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); + }); + (base, state) +} + +#[tokio::test] +async fn startup_reopens_persistent_schedule_and_catches_up_without_a_client_or_agent() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "restart-renewal").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","price":12.5,"currency":"USD","traffic_limit":1024,"billing_start_day":7,"renewal":{"enabled":true,"expiry_date":"2026-01-31","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + state.db.clone().close().await.unwrap(); + clock.set("2026-06-01T04:00:00Z"); + let (base, _restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let model = detail(&admin, &base, &id).await; + assert_eq!(model["renewal"]["expiry_date"], "2026-06-30"); + assert_eq!(model["expired_at"], "2026-07-01T03:59:59.999999999Z"); + assert_eq!( + model["renewal"]["confirmed_expired_at"], + "2026-02-01T04:59:59.999999999Z" + ); + assert_eq!(model["price"], 12.5); + assert_eq!(model["currency"], "USD"); + assert_eq!(model["billing_cycle"], "monthly"); + assert_eq!(model["traffic_limit"], 1024); + assert_eq!(model["billing_start_day"], 7); +} + +#[tokio::test] +async fn disabling_freezes_the_same_projected_deadline_and_occurrence_after_restart() { + let clock = ManualClock::at("2026-02-01T05:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "freeze-renewal").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","renewal":{"enabled":true,"expiry_date":"2026-01-31","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let before = detail(&admin, &base, &id).await; + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":false}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let frozen = detail(&admin, &base, &id).await; + assert_eq!(frozen["renewal"]["deadline_origin"], "frozen"); + assert_eq!(frozen["expired_at"], before["expired_at"]); + assert_eq!( + frozen["renewal"]["occurrence_id"], + before["renewal"]["occurrence_id"] + ); + assert_eq!( + frozen["renewal"]["confirmed_expired_at"], + before["renewal"]["confirmed_expired_at"] + ); + state.db.clone().close().await.unwrap(); + clock.set("2026-06-01T04:00:00Z"); + let (base, restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + serverbee_server::task::alert_evaluator::evaluate_once(&restarted) + .await + .unwrap(); + let persisted = detail(&admin, &base, &id).await; + assert_eq!(persisted["renewal"], frozen["renewal"]); + assert_eq!(persisted["expired_at"], frozen["expired_at"]); +} + +#[tokio::test] +async fn enabled_prerequisites_cannot_be_cleared_but_disabling_and_clearing_is_atomic() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, _tmp, _state) = controlled_server(clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "required-settings").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","renewal":{"enabled":true,"expiry_date":"2026-01-31","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let before = detail(&admin, &base, &id).await; + for invalid in [ + json!({"name":"must-not-change","renewal":{"expiry_date":null}}), + json!({"name":"must-not-change","billing_cycle":null}), + json!({"name":"must-not-change","renewal":{"billing_timezone":null}}), + json!({"name":"must-not-change","renewal":{"billing_timezone":"Mars/Olympus"}}), + ] { + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&invalid) + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + 422, + "required input cannot be cleared while enabled: {invalid}" + ); + let after = detail(&admin, &base, &id).await; + assert_eq!(after["name"], before["name"]); + assert_eq!(after["renewal"], before["renewal"]); + assert_eq!(after["expired_at"], before["expired_at"]); + assert_eq!(after["billing_cycle"], before["billing_cycle"]); + } + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":null,"renewal":{"enabled":false,"expiry_date":null,"billing_timezone":null}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let after = detail(&admin, &base, &id).await; + assert_eq!(after["renewal"]["enabled"], false); + assert!(after["expired_at"].is_null()); + assert!(after["billing_cycle"].is_null()); +} + +#[tokio::test] +async fn enabling_legacy_instant_keeps_entire_selected_day_and_confirmed_history() { + let clock = ManualClock::at("2026-01-31T18:00:00Z"); + let (base, _tmp, _state) = controlled_server(clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let body: Value = admin.post(format!("{base}/api/servers")) + .json(&json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":"legacy-calendar","billing_cycle":"monthly","expired_at":"2026-01-31T12:34:56Z"})) + .send().await.unwrap().json().await.unwrap(); + let id = body["data"]["server_id"].as_str().unwrap(); + let before = detail(&admin, &base, id).await; + assert_eq!(before["expired_at"], "2026-01-31T12:34:56Z"); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":true}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let after = detail(&admin, &base, id).await; + assert_eq!( + after["renewal"]["expiry_date"], "2026-01-31", + "today's full local date has not expired" + ); + assert_eq!(after["expired_at"], "2026-01-31T23:59:59.999999999Z"); + assert_eq!( + after["renewal"]["confirmed_expired_at"], + "2026-01-31T12:34:56Z" + ); } From 14089dc6058c2462fae2cfe0fee1894626c847e5 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:08:35 +0000 Subject: [PATCH 14/40] feat(renewal): align expiry advisories with shared renewal evaluation time --- crates/server/src/router/api/cost.rs | 15 +- crates/server/src/router/api/server.rs | 11 +- crates/server/src/service/alert.rs | 24 +- crates/server/src/service/cost.rs | 25 +- crates/server/tests/renewal_projection.rs | 399 +++++++++++++++++++++- 5 files changed, 445 insertions(+), 29 deletions(-) diff --git a/crates/server/src/router/api/cost.rs b/crates/server/src/router/api/cost.rs index 675b226d5..e335c4a32 100644 --- a/crates/server/src/router/api/cost.rs +++ b/crates/server/src/router/api/cost.rs @@ -26,7 +26,12 @@ pub fn read_router() -> Router> { pub async fn get_cost_overview( State(state): State>, ) -> Result>, AppError> { - ok(CostService::overview(&state.db, &state.agent_manager).await?) + ok(CostService::overview_with_expiry_time( + &state.db, + &state.agent_manager, + state.renewal_clock.now(), + ) + .await?) } #[utoipa::path( @@ -46,5 +51,11 @@ pub async fn get_server_cost_insights( State(state): State>, Path(id): Path, ) -> Result>, AppError> { - ok(CostService::server_insights(&state.db, &state.agent_manager, &id).await?) + ok(CostService::server_insights_with_expiry_time( + &state.db, + &state.agent_manager, + &id, + state.renewal_clock.now(), + ) + .await?) } diff --git a/crates/server/src/router/api/server.rs b/crates/server/src/router/api/server.rs index 0bd3ab4ef..c74e0d124 100644 --- a/crates/server/src/router/api/server.rs +++ b/crates/server/src/router/api/server.rs @@ -1718,9 +1718,7 @@ mod delete_audit_tests { async fn delete_server_writes_audit_log() { let (db, _tmp) = setup_test_db().await; insert_server(&db, "srv-del", "Doomed").await; - let state = AppState::new(db.clone(), AppConfig::default()) - .await - .unwrap(); + let state = AppState::new(db.clone(), AppConfig::default()).await.unwrap(); let res = delete_server( State(state.clone()), @@ -1736,7 +1734,8 @@ mod delete_audit_tests { assert!( logs.iter().any(|l| l.action == "server_deleted" && l.user_id == "admin-1" - && l.detail + && l + .detail .as_deref() .is_some_and(|d| d.contains("srv-del") && d.contains("Doomed"))), "expected a server_deleted audit row, got: {logs:?}" @@ -1748,9 +1747,7 @@ mod delete_audit_tests { let (db, _tmp) = setup_test_db().await; insert_server(&db, "srv-a", "A").await; insert_server(&db, "srv-b", "B").await; - let state = AppState::new(db.clone(), AppConfig::default()) - .await - .unwrap(); + let state = AppState::new(db.clone(), AppConfig::default()).await.unwrap(); let res = batch_delete( State(state.clone()), diff --git a/crates/server/src/service/alert.rs b/crates/server/src/service/alert.rs index bd3a1a9f9..5e8aefb3b 100644 --- a/crates/server/src/service/alert.rs +++ b/crates/server/src/service/alert.rs @@ -36,7 +36,8 @@ pub const COVER_TYPE_ALL: &str = "all"; pub const COVER_TYPE_INCLUDE: &str = "include"; pub const COVER_TYPE_EXCLUDE: &str = "exclude"; /// All accepted `cover_type` values for alert_rule and block_list inputs. -pub const VALID_COVER_TYPES: &[&str] = &[COVER_TYPE_ALL, COVER_TYPE_INCLUDE, COVER_TYPE_EXCLUDE]; +pub const VALID_COVER_TYPES: &[&str] = + &[COVER_TYPE_ALL, COVER_TYPE_INCLUDE, COVER_TYPE_EXCLUDE]; /// `origin` discriminants for block_list rows. pub const ORIGIN_MANUAL: &str = "manual"; @@ -44,7 +45,8 @@ pub const ORIGIN_AUTO: &str = "auto"; /// Security rule types whose payload carries a `source_ip` and may attach a /// `block_source_ip` action. -pub const SOURCE_IP_RULE_TYPES: &[&str] = &["ssh_brute_force_detected", "port_scan_detected"]; +pub const SOURCE_IP_RULE_TYPES: &[&str] = + &["ssh_brute_force_detected", "port_scan_detected"]; // ── Alert Rule Types ── @@ -1902,7 +1904,8 @@ mod tests { _ => break, } } - let _ = socket.try_write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + let _ = socket + .try_write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); let _ = tx.send(String::from_utf8_lossy(&buf).into_owned()); } }); @@ -2021,10 +2024,7 @@ mod tests { .expect("query states"); assert_eq!(rows.len(), 1, "no duplicate alert_state rows"); assert!(!rows[0].resolved, "re-armed row should be firing again"); - assert!( - rows[0].resolved_at.is_none(), - "resolved_at cleared on re-arm" - ); + assert!(rows[0].resolved_at.is_none(), "resolved_at cleared on re-arm"); assert_eq!(rows[0].count, 1, "count reset on re-arm"); } @@ -2660,12 +2660,10 @@ mod tests { async fn test_latest_record_time_picks_latest_and_none() { let (db, _tmp) = setup_test_db().await; // No records => None. - assert!( - RecordService::latest_record_time(&db, "srv-1") - .await - .expect("query should succeed") - .is_none() - ); + assert!(RecordService::latest_record_time(&db, "srv-1") + .await + .expect("query should succeed") + .is_none()); let older = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap(); let newer = Utc.with_ymd_and_hms(2026, 1, 1, 1, 0, 0).unwrap(); diff --git a/crates/server/src/service/cost.rs b/crates/server/src/service/cost.rs index ade685cfc..09fa906c4 100644 --- a/crates/server/src/service/cost.rs +++ b/crates/server/src/service/cost.rs @@ -165,9 +165,18 @@ impl CostService { pub async fn overview( db: &DatabaseConnection, agent_manager: &crate::service::agent_manager::AgentManager, + ) -> Result { + Self::overview_with_expiry_time(db, agent_manager, Utc::now()).await + } + + /// Only expiry advisories use renewal time; independent cost periods retain their clock. + pub async fn overview_with_expiry_time( + db: &DatabaseConnection, + agent_manager: &crate::service::agent_manager::AgentManager, + expiry_now: DateTime, ) -> Result { let servers = server::Entity::find().all(db).await?; - let computed = compute_costs(db, agent_manager, servers).await?; + let computed = compute_costs(db, agent_manager, servers, expiry_now).await?; Ok(CostOverviewResponse { currencies: currency_summaries(&computed), @@ -179,13 +188,22 @@ impl CostService { db: &DatabaseConnection, agent_manager: &crate::service::agent_manager::AgentManager, server_id: &str, + ) -> Result { + Self::server_insights_with_expiry_time(db, agent_manager, server_id, Utc::now()).await + } + + pub async fn server_insights_with_expiry_time( + db: &DatabaseConnection, + agent_manager: &crate::service::agent_manager::AgentManager, + server_id: &str, + expiry_now: DateTime, ) -> Result { let servers = server::Entity::find().all(db).await?; if !servers.iter().any(|server| server.id == server_id) { return Err(AppError::NotFound("Server not found".to_string())); } - let computed = compute_costs(db, agent_manager, servers).await?; + let computed = compute_costs(db, agent_manager, servers, expiry_now).await?; computed .iter() .find(|entry| entry.server.id == server_id) @@ -330,6 +348,7 @@ async fn compute_costs( db: &DatabaseConnection, agent_manager: &crate::service::agent_manager::AgentManager, servers: Vec, + expiry_now: DateTime, ) -> Result, AppError> { let now = Utc::now(); let today = now.date_naive(); @@ -397,7 +416,7 @@ async fn compute_costs( .collect::>(); for entry in &mut computed { - entry.advisories = compute_advisories(entry, now); + entry.advisories = compute_advisories(entry, expiry_now); } computed.sort_by(|left, right| { diff --git a/crates/server/tests/renewal_projection.rs b/crates/server/tests/renewal_projection.rs index fbece141d..aa436da5c 100644 --- a/crates/server/tests/renewal_projection.rs +++ b/crates/server/tests/renewal_projection.rs @@ -127,10 +127,10 @@ async fn scheduled_evaluation_advances_offline_month_end_and_restores_anchor_aft .send().await.unwrap(); assert_eq!(response.status(), 200); clock.set("2026-02-01T05:00:00Z"); - // The production scheduler's first tick is immediate; no client opens a billing page. - let task = tokio::spawn(serverbee_server::task::alert_evaluator::run(state.clone())); - tokio::time::sleep(std::time::Duration::from_millis(150)).await; - task.abort(); + // The scheduler invokes this same production iteration; time moves directly. + serverbee_server::task::alert_evaluator::evaluate_once(&state) + .await + .unwrap(); let model = detail(&admin, &base, &id).await; assert_eq!(model["renewal"]["expiry_date"], "2026-02-28"); assert_eq!(model["expired_at"], "2026-03-01T04:59:59.999999999Z"); @@ -315,3 +315,394 @@ async fn enabling_legacy_instant_keeps_entire_selected_day_and_confirmed_history "2026-01-31T12:34:56Z" ); } + +async fn configure( + admin: &reqwest::Client, + base: &str, + id: &str, + cycle: &str, + date: &str, + zone: &str, +) { + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":cycle,"renewal":{"enabled":true,"expiry_date":date,"billing_timezone":zone}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); +} +async fn tick(state: &serverbee_server::state::AppState) { + serverbee_server::task::alert_evaluator::evaluate_once(state) + .await + .unwrap(); +} + +#[tokio::test] +async fn current_local_date_remains_valid_until_its_last_nanosecond() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "full-local-day").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let original = detail(&admin, &base, &id).await; + for time in ["2026-02-01T04:59:59Z", "2026-02-01T04:59:59.999999999Z"] { + clock.set(time); + tick(&state).await; + let current = detail(&admin, &base, &id).await; + assert_eq!(current["renewal"], original["renewal"]); + assert_eq!(current["expired_at"], original["expired_at"]); + } + clock.set("2026-02-01T05:00:00Z"); + tick(&state).await; + assert_eq!( + detail(&admin, &base, &id).await["renewal"]["expiry_date"], + "2026-02-28" + ); + clock.set("2026-03-01T05:00:00Z"); + tick(&state).await; + let march = detail(&admin, &base, &id).await; + assert_eq!(march["renewal"]["expiry_date"], "2026-03-31"); + assert_eq!(march["expired_at"], "2026-04-01T03:59:59.999999999Z"); + assert_eq!( + march["renewal"]["confirmed_expired_at"], + original["renewal"]["confirmed_expired_at"] + ); +} + +#[tokio::test] +async fn quarterly_month_end_clamps_and_restores_the_original_day() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "quarterly-anchor").await; + configure( + &admin, + &base, + &id, + "quarterly", + "2026-01-31", + "America/New_York", + ) + .await; + clock.set("2026-02-01T05:00:00Z"); + tick(&state).await; + let april = detail(&admin, &base, &id).await; + assert_eq!(april["renewal"]["expiry_date"], "2026-04-30"); + assert_eq!(april["expired_at"], "2026-05-01T03:59:59.999999999Z"); + clock.set("2026-05-01T04:00:00Z"); + tick(&state).await; + let july = detail(&admin, &base, &id).await; + assert_eq!(july["renewal"]["expiry_date"], "2026-07-31"); + assert_eq!(july["expired_at"], "2026-08-01T03:59:59.999999999Z"); + assert_eq!( + july["renewal"]["confirmed_expired_at"], + "2026-02-01T04:59:59.999999999Z" + ); +} + +#[tokio::test] +async fn yearly_leap_day_returns_after_non_leap_years_and_persistent_reopen() { + let clock = ManualClock::at("2024-02-29T12:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "annual-leap-anchor").await; + configure( + &admin, + &base, + &id, + "yearly", + "2024-02-29", + "America/New_York", + ) + .await; + clock.set("2024-03-01T05:00:00Z"); + tick(&state).await; + let non_leap = detail(&admin, &base, &id).await; + assert_eq!(non_leap["renewal"]["expiry_date"], "2025-02-28"); + assert_eq!(non_leap["expired_at"], "2025-03-01T04:59:59.999999999Z"); + state.db.clone().close().await.unwrap(); + clock.set("2028-02-28T12:00:00Z"); + let (base, _restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let leap = detail(&admin, &base, &id).await; + assert_eq!(leap["renewal"]["expiry_date"], "2028-02-29"); + assert_eq!(leap["expired_at"], "2028-03-01T04:59:59.999999999Z"); + assert_eq!( + leap["renewal"]["confirmed_expired_at"], + "2024-03-01T04:59:59.999999999Z" + ); +} + +#[tokio::test] +async fn onboarding_validates_before_mutation_and_retries_keep_original_identity_across_time() { + let clock = ManualClock::at("2026-03-01T05:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + for invalid in [ + json!({"enabled":true,"expiry_date":"2026-01-31","billing_timezone":"UTC"}), + json!({"enabled":true,"billing_timezone":"UTC"}), + json!({"enabled":true,"expiry_date":"2026-01-31","billing_timezone":null}), + ] { + let response = admin.post(format!("{base}/api/servers")) + .json(&json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":"invalid-create","renewal":invalid})) + .send().await.unwrap(); + assert_eq!(response.status(), 422); + } + let body: Value = admin + .get(format!("{base}/api/servers")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert!( + body["data"].as_array().unwrap().is_empty(), + "invalid enabled onboarding creates no server" + ); + let request = json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":"valid-projected-create","billing_cycle":"monthly","renewal":{"enabled":true,"expiry_date":"2026-01-31","billing_timezone":"America/New_York"}}); + let response = admin + .post(format!("{base}/api/servers")) + .json(&request) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + let id = body["data"]["server_id"].as_str().unwrap(); + assert_eq!( + detail(&admin, &base, id).await["renewal"]["expiry_date"], + "2026-03-31" + ); + clock.set("2026-06-01T04:00:00Z"); + tick(&state).await; + let replay = admin + .post(format!("{base}/api/servers")) + .json(&request) + .send() + .await + .unwrap(); + assert_eq!( + replay.status(), + 200, + "runtime projection cannot change canonical onboarding identity" + ); + let replay: Value = replay.json().await.unwrap(); + assert_eq!(replay["data"]["server_id"], id); + let current = detail(&admin, &base, id).await; + assert_eq!(current["renewal"]["expiry_date"], "2026-06-30"); + assert_eq!( + current["renewal"]["confirmed_expired_at"], + "2026-02-01T04:59:59.999999999Z" + ); +} + +#[tokio::test] +async fn concurrent_http_metadata_edits_and_scheduler_ticks_keep_one_stable_schedule() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "before-rollover").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let original = detail(&admin, &base, &id).await; + clock.set("2026-02-01T05:00:00Z"); + let mut work = tokio::task::JoinSet::new(); + for _ in 0..8 { + let state = state.clone(); + work.spawn(async move { + tick(&state).await; + }); + } + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"name":"after-rollover","price":99.5})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + while let Some(result) = work.join_next().await { + result.unwrap(); + } + let current = detail(&admin, &base, &id).await; + assert_eq!(current["name"], "after-rollover"); + assert_eq!(current["price"], 99.5); + assert_eq!(current["renewal"]["expiry_date"], "2026-02-28"); + assert_eq!( + current["renewal"]["confirmed_expired_at"], + original["renewal"]["confirmed_expired_at"] + ); + assert_ne!( + current["renewal"]["occurrence_id"], + original["renewal"]["occurrence_id"] + ); + for _ in 0..3 { + tick(&state).await; + } + assert_eq!( + detail(&admin, &base, &id).await["renewal"], + current["renewal"] + ); + clock.set("2026-03-01T05:00:00Z"); + tick(&state).await; + assert_eq!( + detail(&admin, &base, &id).await["renewal"]["expiry_date"], + "2026-03-31" + ); +} + +#[tokio::test] +async fn ordinary_expiration_window_tracks_current_projection_without_historical_backlog() { + let clock = ManualClock::at("2026-02-01T05:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "current-reminder-target").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let response = admin.post(format!("{base}/api/alert-rules")) + .json(&json!({"name":"seven-day-renewal","trigger_mode":"once","cover_type":"include","server_ids":[id],"rules":[{"rule_type":"expiration","duration":7}]})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let rule: Value = response.json().await.unwrap(); + let rule_id = rule["data"]["id"].as_str().unwrap(); + tick(&state).await; + let events: Value = admin + .get(format!("{base}/api/alert-rules/{rule_id}/states")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert!( + events["data"].as_array().unwrap().is_empty(), + "historical January confirmation must not remain the reminder target" + ); + clock.set("2026-02-23T12:00:00Z"); + tick(&state).await; + let events: Value = admin + .get(format!("{base}/api/alert-rules/{rule_id}/states")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(events["data"].as_array().unwrap().len(), 1); + assert_eq!(events["data"][0]["server_id"], id); + assert_eq!(events["data"][0]["resolved"], false); +} + +#[tokio::test] +async fn cost_expiry_advisories_share_renewal_time_without_changing_independent_cost_periods() { + let clock = ManualClock::at("2026-02-01T05:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "forecast-cost-advisory").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"price":31.0,"currency":"USD","billing_start_day":7})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let cost: Value = admin + .get(format!("{base}/api/servers/{id}/cost-insights")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert!( + !cost["data"]["advisories"] + .as_array() + .unwrap() + .contains(&json!("expired_billing")), + "current February projection has not expired on February 1" + ); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":false}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + clock.set("2026-03-01T05:00:00Z"); + tick(&state).await; + let frozen_cost: Value = admin + .get(format!("{base}/api/servers/{id}/cost-insights")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert!( + frozen_cost["data"]["advisories"] + .as_array() + .unwrap() + .contains(&json!("expired_billing")) + ); + assert_eq!(cost["data"]["configured"], true); + for field in [ + "cycle_start", + "cycle_end", + "cycle_days", + "days_elapsed", + "days_remaining", + "cost_per_second", + "cost_per_hour", + "cost_per_day", + "cost_per_month_equivalent", + "cycle_cost_elapsed", + "cycle_cost_remaining", + "cycle_burn_percent", + ] { + assert!( + !cost["data"][field].is_null(), + "configured cost field {field} remains available" + ); + assert_eq!( + cost["data"][field], frozen_cost["data"][field], + "renewal time must not replace cost estimation calendar: {field}" + ); + } +} From 9f54824040b24bafcf090f420a7d80be88f6ced8 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:10:15 +0000 Subject: [PATCH 15/40] feat(renewal): publish typed automatic renewal input contract --- apps/web/openapi.json | 6 ++++++ apps/web/src/lib/api-types.ts | 1 + 2 files changed, 7 insertions(+) diff --git a/apps/web/openapi.json b/apps/web/openapi.json index dabf20a35..7e22d57ef 100644 --- a/apps/web/openapi.json +++ b/apps/web/openapi.json @@ -12745,6 +12745,12 @@ "null" ] }, + "enabled": { + "type": [ + "boolean", + "null" + ] + }, "expiry_date": { "type": [ "string", diff --git a/apps/web/src/lib/api-types.ts b/apps/web/src/lib/api-types.ts index 15f52a79d..b609e3afd 100644 --- a/apps/web/src/lib/api-types.ts +++ b/apps/web/src/lib/api-types.ts @@ -3568,6 +3568,7 @@ export interface components { }; RenewalInput: { billing_timezone?: string | null; + enabled?: boolean | null; expiry_date?: string | null; }; RenewalProjection: { From bb79ca1501d31a37ffd28791df0abb0bc4876c39 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:22:52 +0000 Subject: [PATCH 16/40] fix(web): hide automatic renewal controls for legacy servers --- .../components/server/server-edit-dialog.tsx | 46 ++++++++++--------- .../server/server-edit-renewal.test.tsx | 10 ++++ 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/apps/web/src/components/server/server-edit-dialog.tsx b/apps/web/src/components/server/server-edit-dialog.tsx index 035655a77..3d0957c43 100644 --- a/apps/web/src/components/server/server-edit-dialog.tsx +++ b/apps/web/src/components/server/server-edit-dialog.tsx @@ -357,29 +357,31 @@ function ServerEditBillingFields({

{t('edit_billing_timezone_hint')}

-
-
- {t('edit_automatic_renewal')} - dispatch({ type: 'patch', value: { automaticRenewal } })} - /> + {server.renewal && ( +
+
+ {t('edit_automatic_renewal')} + dispatch({ type: 'patch', value: { automaticRenewal } })} + /> +
+

+ {t('edit_renewal_prerequisites')} +

+

{t('renewal_forecast_explanation')}

+ +

{t('renewal_cost_independent')}

-

- {t('edit_renewal_prerequisites')} -

-

{t('renewal_forecast_explanation')}

- -

{t('renewal_cost_independent')}

-
+ )}
{ }) describe('server renewal date editing', () => { + it('preserves legacy-server saves without exposing an unsupported automatic switch', async () => { + renderEditor({ ...server, renewal: undefined }) + expect(screen.queryByRole('switch', { name: 'Automatic renewal tracking' })).not.toBeInTheDocument() + fireEvent.change(screen.getByRole('textbox', { name: 'Name' }), { target: { value: 'Legacy rename' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('expired_at') + }) + it.each(MISSING_PREREQUISITES)('cannot opt in without a $label', (input) => { renderEditor({ ...server, From 96a288ead4a8f7bc853ed1636ef44adebdf88a25 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:24:07 +0000 Subject: [PATCH 17/40] fix(renewal): skip unavailable dates and isolate invalid schedules --- crates/server/src/service/renewal.rs | 38 ++++++-- crates/server/tests/renewal_projection.rs | 111 ++++++++++++++++++++++ 2 files changed, 143 insertions(+), 6 deletions(-) diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs index 27d70834f..831667726 100644 --- a/crates/server/src/service/renewal.rs +++ b/crates/server/src/service/renewal.rs @@ -122,7 +122,13 @@ impl RenewalState { .filter(|day| *day > 0) .ok_or_else(|| AppError::Validation("renewal date is out of range".into()))?; }; - let boundary = date_boundary(candidate, &self.billing_timezone)?; + // A timezone may skip a whole anchored date. It cannot represent an + // occurrence; retain the anchor and examine the following period. + let Some(boundary) = representable_date_boundary(candidate, &self.billing_timezone)? + else { + periods += 1; + continue; + }; if boundary >= now { *deadline = Some(boundary); self.deadline_origin = DeadlineOrigin::Projected; @@ -150,6 +156,15 @@ pub fn selected_date(deadline: Option>, timezone: &str) -> Option< } pub fn date_boundary(date: NaiveDate, timezone: &str) -> Result, AppError> { + representable_date_boundary(date, timezone)?.ok_or_else(|| { + AppError::Validation("expiry_date does not exist in billing_timezone".into()) + }) +} + +fn representable_date_boundary( + date: NaiveDate, + timezone: &str, +) -> Result>, AppError> { let tz: Tz = timezone.parse().map_err(|_| { AppError::Validation("billing_timezone must be a valid IANA timezone".into()) })?; @@ -159,9 +174,7 @@ pub fn date_boundary(date: NaiveDate, timezone: &str) -> Result, A .earliest() .is_some() }) { - return Err(AppError::Validation( - "expiry_date does not exist in billing_timezone".into(), - )); + return Ok(None); } let next = date .succ_opt() @@ -174,7 +187,9 @@ pub fn date_boundary(date: NaiveDate, timezone: &str) -> Result, A .from_local_datetime(&(midnight + Duration::minutes(minutes))) .earliest() { - return Ok(boundary.with_timezone(&Utc) - Duration::nanoseconds(1)); + return Ok(Some( + boundary.with_timezone(&Utc) - Duration::nanoseconds(1), + )); } } Err(AppError::Validation( @@ -391,7 +406,18 @@ pub async fn advance_all(db: &DatabaseConnection, now: DateTime) -> Result< }; let mut state = RenewalState::from_server(&model); let mut deadline = model.expired_at; - if state.advance(&mut deadline, model.billing_cycle.as_deref(), now)? { + let advanced = match state.advance(&mut deadline, model.billing_cycle.as_deref(), now) { + Ok(advanced) => advanced, + Err(AppError::Validation(reason)) => { + // A damaged calendar configuration cannot stop healthy schedules. + // Database/transaction errors still propagate to the caller. + tracing::error!(server_id = %model.id, %reason, "Skipping invalid renewal schedule"); + tx.rollback().await?; + continue; + } + Err(error) => return Err(error), + }; + if advanced { let mut active: server::ActiveModel = model.into(); active.expired_at = Set(deadline); active.renewal_state = Set(Some( diff --git a/crates/server/tests/renewal_projection.rs b/crates/server/tests/renewal_projection.rs index aa436da5c..1af76a8c4 100644 --- a/crates/server/tests/renewal_projection.rs +++ b/crates/server/tests/renewal_projection.rs @@ -706,3 +706,114 @@ async fn cost_expiry_advisories_share_renewal_time_without_changing_independent_ ); } } + +#[tokio::test] +async fn automatic_projection_skips_nonexistent_anchored_days_and_recovers_after_restart() { + let clock = ManualClock::at("2011-12-31T00:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "apia-skipped-occurrence").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","renewal":{"enabled":true,"expiry_date":"2011-11-30","billing_timezone":"Pacific/Apia"}})) + .send().await.unwrap(); + assert_eq!( + response.status(), + 200, + "a nonexistent projected December 30 cannot block catch-up" + ); + let january = detail(&admin, &base, &id).await; + assert_eq!(january["renewal"]["expiry_date"], "2012-01-30"); + assert_eq!(january["expired_at"], "2012-01-30T09:59:59.999999999Z"); + assert_eq!( + january["renewal"]["confirmed_expired_at"], + "2011-12-01T09:59:59.999999999Z" + ); + // Persist an enabled pre-transition schedule, then genuinely close/reopen SQLite. + clock.set("2011-11-30T12:00:00Z"); + let before_jump = create_server(&admin, &base, "apia-startup-occurrence").await; + configure( + &admin, + &base, + &before_jump, + "monthly", + "2011-11-30", + "Pacific/Apia", + ) + .await; + state.db.clone().close().await.unwrap(); + clock.set("2011-12-31T00:00:00Z"); + let (base, restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let restored = detail(&admin, &base, &before_jump).await; + assert_eq!(restored["renewal"]["expiry_date"], "2012-01-30"); + assert_eq!(restored["expired_at"], "2012-01-30T09:59:59.999999999Z"); + tick(&restarted).await; + assert_eq!( + detail(&admin, &base, &before_jump).await["renewal"], + restored["renewal"] + ); +} + +#[tokio::test] +async fn invalid_persisted_schedule_does_not_block_other_forecasts_or_hide_database_failure() { + use sea_orm::{ConnectionTrait, DbBackend, Statement}; + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let invalid = create_server(&admin, &base, "damaged-schedule").await; + let healthy = create_server(&admin, &base, "healthy-schedule").await; + for id in [&invalid, &healthy] { + configure( + &admin, + &base, + id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + } + // Seed a durable invalid calendar record; all evaluation and persistence remain real. + let mut damaged = detail(&admin, &base, &invalid).await["renewal"].clone(); + damaged["billing_timezone"] = json!("Not/A_Real_Zone"); + damaged["anchor_day"] = json!(31); + state + .db + .execute(Statement::from_sql_and_values( + DbBackend::Sqlite, + "UPDATE servers SET renewal_state = ? WHERE id = ?", + [damaged.to_string().into(), invalid.clone().into()], + )) + .await + .unwrap(); + state.db.clone().close().await.unwrap(); + clock.set("2026-02-01T05:00:00Z"); + let (base, restarted) = reopen(&tmp, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + assert_eq!( + detail(&admin, &base, &healthy).await["renewal"]["expiry_date"], + "2026-02-28" + ); + assert_eq!( + detail(&admin, &base, &invalid).await["name"], + "damaged-schedule" + ); + clock.set("2026-03-01T05:00:00Z"); + tick(&restarted).await; + assert_eq!( + detail(&admin, &base, &healthy).await["renewal"]["expiry_date"], + "2026-03-31" + ); + restarted.db.clone().close().await.unwrap(); + assert!( + matches!( + serverbee_server::task::alert_evaluator::evaluate_once(&restarted).await, + Err(serverbee_server::error::AppError::Internal(_)) + ), + "database failures must remain visible" + ); +} From c01f6cefd491bbab1450751dda676bf42fc30e53 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:40:29 +0000 Subject: [PATCH 18/40] feat(ios): refresh renewal catalogs and superseded reminders --- apps/ios/ServerBee/ContentView.swift | 8 +- apps/ios/ServerBee/Localizable.xcstrings | 20 ++++ apps/ios/ServerBee/Models/AlertModels.swift | 13 ++- apps/ios/ServerBee/Models/ServerStatus.swift | 23 +++-- .../ServerBee/Models/WebSocketModels.swift | 6 ++ .../ServerBee/Services/WebSocketRouter.swift | 16 ++- .../ViewModels/AlertDetailViewModel.swift | 5 +- .../ViewModels/InsightsViewModel.swift | 18 +++- .../ViewModels/ServerDetailViewModel.swift | 4 +- .../ViewModels/ServerTrafficViewModel.swift | 15 +++ .../ViewModels/ServersViewModel.swift | 35 ++++++- .../Views/Alerts/AlertDetailView.swift | 11 ++- .../Views/Alerts/AlertEventCardView.swift | 4 +- .../Views/Alerts/AlertStatusBadge.swift | 13 +-- .../Views/Alerts/AlertsListView.swift | 2 +- .../Views/Insights/InsightsView.swift | 8 +- .../Servers/Detail/ServerTrafficSection.swift | 5 +- .../Views/Servers/ServerDetailView.swift | 12 ++- .../MobileAlertEventIdTests.swift | 16 +++ .../Services/WebSocketRouterTests.swift | 99 +++++++++++++++++++ .../ServersViewModelMergeTests.swift | 12 +++ 21 files changed, 300 insertions(+), 45 deletions(-) diff --git a/apps/ios/ServerBee/ContentView.swift b/apps/ios/ServerBee/ContentView.swift index 5a48bfaf9..3d761b018 100644 --- a/apps/ios/ServerBee/ContentView.swift +++ b/apps/ios/ServerBee/ContentView.swift @@ -133,9 +133,13 @@ struct ContentView: View { Task { await alertsViewModel.handleWSAlertEvent(apiClient: apiClient) } }, security: { broadcast in securityFeed?.ingest(broadcast) }, - upgrades: { msg in ContentView.applyUpgrade(msg, to: upgradeJobs) } + upgrades: { msg in ContentView.applyUpgrade(msg, to: upgradeJobs) }, + catalogRefresh: { ids in + await serversViewModel.refreshCatalog(serverIds: ids, apiClient: apiClient) + await alertsViewModel?.fetchEvents(apiClient: apiClient) + } ) - router.dispatch(message) + await router.dispatchAndRefresh(message) } } if let context = auth.captureContext() { diff --git a/apps/ios/ServerBee/Localizable.xcstrings b/apps/ios/ServerBee/Localizable.xcstrings index 688bdde44..145e9c20c 100644 --- a/apps/ios/ServerBee/Localizable.xcstrings +++ b/apps/ios/ServerBee/Localizable.xcstrings @@ -1,6 +1,26 @@ { "sourceLanguage": "en", "strings": { + "Superseded": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已被替代" + } + } + } + }, + "A newer renewal deadline superseded this reminder.": { + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "新的续费截止日期已替代此提醒。" + } + } + } + }, "Renewal": { "localizations": { "zh-Hans": { diff --git a/apps/ios/ServerBee/Models/AlertModels.swift b/apps/ios/ServerBee/Models/AlertModels.swift index d48314424..e9fb6e69b 100644 --- a/apps/ios/ServerBee/Models/AlertModels.swift +++ b/apps/ios/ServerBee/Models/AlertModels.swift @@ -3,11 +3,20 @@ import Foundation enum AlertStatus: String, Codable, Sendable { case firing case resolved + case superseded + + var label: String { + switch self { + case .firing: String(localized: "Firing") + case .resolved: String(localized: "Resolved") + case .superseded: String(localized: "Superseded") + } + } } /// One row of the alert-events list (`GET /api/alert-events`). Mirrors the /// server's `AlertEventResponse`. The list carries a complete alert key, -/// rule/server labels, a firing/resolved status, the relevant timestamp +/// rule/server labels, its current status, the relevant timestamp /// (`event_at`) and the trigger `count`. The richer fields (message, first/last /// timestamps, rule mode) live on the per-event detail DTO (`MobileAlertDetail`). struct MobileAlertEvent: Codable, Identifiable, Sendable { @@ -16,7 +25,7 @@ struct MobileAlertEvent: Codable, Identifiable, Sendable { let serverId: String let serverName: String let status: AlertStatus - /// `first_triggered_at` for firing, `resolved_at` for resolved. + /// `first_triggered_at` for firing/superseded, `resolved_at` for resolved. let eventAt: String let resolvedAt: String? let count: Int diff --git a/apps/ios/ServerBee/Models/ServerStatus.swift b/apps/ios/ServerBee/Models/ServerStatus.swift index 2ccb5860b..aa8963ded 100644 --- a/apps/ios/ServerBee/Models/ServerStatus.swift +++ b/apps/ios/ServerBee/Models/ServerStatus.swift @@ -238,19 +238,12 @@ extension ServerStatus { return ISO8601DateFormatter.shared.date(from: lastActiveAt) } - /// Merge non-nil fields from another status (used for WebSocket partial - /// updates AND for overlaying a live WS frame onto REST config). Fields that - /// are `nil` in `other` preserve the local value, so a metrics-only frame - /// never erases config fields like `ipv4`, `capabilities`, or billing. - mutating func merge(from other: ServerStatus) { + /// Preserve only runtime fields when replacing the authoritative REST catalog. + mutating func mergeLiveMetrics(from other: ServerStatus) { if let v = other.online { online = v } if let v = other.cpuUsage { cpuUsage = v } - if let v = other.cpuCores { cpuCores = v } - if let v = other.memoryTotal, v > 0 { memoryTotal = v } if let v = other.memoryUsed { memoryUsed = v } - if let v = other.swapTotal { swapTotal = v } if let v = other.swapUsed { swapUsed = v } - if let v = other.diskTotal, v > 0 { diskTotal = v } if let v = other.diskUsed { diskUsed = v } if let v = other.diskReadPerSec { diskReadPerSec = v } if let v = other.diskWritePerSec { diskWritePerSec = v } @@ -265,6 +258,18 @@ extension ServerStatus { if let v = other.tcpCount { tcpCount = v } if let v = other.udpCount { udpCount = v } if let v = other.uptime { uptime = v } + } + + /// Merge non-nil fields from another status (used for WebSocket partial + /// updates AND for overlaying a live WS frame onto REST config). Fields that + /// are `nil` in `other` preserve the local value, so a metrics-only frame + /// never erases config fields like `ipv4`, `capabilities`, or billing. + mutating func merge(from other: ServerStatus) { + mergeLiveMetrics(from: other) + if let v = other.cpuCores { cpuCores = v } + if let v = other.memoryTotal, v > 0 { memoryTotal = v } + if let v = other.swapTotal { swapTotal = v } + if let v = other.diskTotal, v > 0 { diskTotal = v } if let v = other.os { os = v } if let v = other.cpuName { cpuName = v } if let v = other.ipv4 { ipv4 = v } diff --git a/apps/ios/ServerBee/Models/WebSocketModels.swift b/apps/ios/ServerBee/Models/WebSocketModels.swift index d9ac735c0..90843d2d1 100644 --- a/apps/ios/ServerBee/Models/WebSocketModels.swift +++ b/apps/ios/ServerBee/Models/WebSocketModels.swift @@ -5,6 +5,8 @@ enum BrowserMessage: Sendable { case update(servers: [ServerStatus]) case serverOnline(serverId: String) case serverOffline(serverId: String) + /// Invalidate authenticated REST data; billing fields stay out of live metrics. + case serverCatalogChanged(serverIds: [String]) case agentAuthorityChanged(serverId: String, agentAuthority: AgentAuthorityState) case capabilitiesChanged(serverId: String, capabilities: Int, agentLocal: Int?, effective: Int?) case agentInfoUpdated(serverId: String, protocolVersion: Int) @@ -35,6 +37,7 @@ extension BrowserMessage: Decodable { case update case serverOnline = "server_online" case serverOffline = "server_offline" + case serverCatalogChanged = "server_catalog_changed" case agentAuthorityChanged = "agent_authority_changed" case capabilitiesChanged = "capabilities_changed" case agentInfoUpdated = "agent_info_updated" @@ -49,6 +52,7 @@ extension BrowserMessage: Decodable { case servers case upgrades case serverId = "server_id" + case serverIds = "server_ids" case capabilities case agentLocalCapabilities = "agent_local_capabilities" case effectiveCapabilities = "effective_capabilities" @@ -87,6 +91,8 @@ extension BrowserMessage: Decodable { case .serverOffline: let serverId = try container.decode(String.self, forKey: .serverId) self = .serverOffline(serverId: serverId) + case .serverCatalogChanged: + self = .serverCatalogChanged(serverIds: try container.decode([String].self, forKey: .serverIds)) case .agentAuthorityChanged: self = .agentAuthorityChanged( serverId: try container.decode(String.self, forKey: .serverId), diff --git a/apps/ios/ServerBee/Services/WebSocketRouter.swift b/apps/ios/ServerBee/Services/WebSocketRouter.swift index e825ac4bd..2d2767fe7 100644 --- a/apps/ios/ServerBee/Services/WebSocketRouter.swift +++ b/apps/ios/ServerBee/Services/WebSocketRouter.swift @@ -8,6 +8,20 @@ struct WebSocketRouter { let alerts: (BrowserMessage) -> Void var security: (SecurityEventBroadcast) -> Void = { _ in } var upgrades: (BrowserMessage) -> Void = { _ in } + var catalogRefresh: ([String]?) async -> Void = { _ in } + + /// Reconnects may miss catalog events, so a full sync also reloads REST data. + func dispatchAndRefresh(_ message: BrowserMessage) async { + dispatch(message) + switch message { + case .fullSync: + await catalogRefresh(nil) + case .serverCatalogChanged(let serverIds): + await catalogRefresh(serverIds) + default: + break + } + } func dispatch(_ message: BrowserMessage) { switch message { @@ -16,7 +30,7 @@ struct WebSocketRouter { servers(message) upgrades(message) case .update, .serverOnline, .serverOffline, .agentAuthorityChanged, - .capabilitiesChanged, .agentInfoUpdated: + .capabilitiesChanged, .agentInfoUpdated, .serverCatalogChanged: servers(message) case .alertEvent: alerts(message) diff --git a/apps/ios/ServerBee/ViewModels/AlertDetailViewModel.swift b/apps/ios/ServerBee/ViewModels/AlertDetailViewModel.swift index 46ea592f0..fa360085d 100644 --- a/apps/ios/ServerBee/ViewModels/AlertDetailViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/AlertDetailViewModel.swift @@ -13,8 +13,11 @@ final class AlertDetailViewModel { detail = nil errorMessage = nil do { - detail = try await apiClient.get("/api/alert-events/\(alertKey)") + let refreshed: MobileAlertDetail = try await apiClient.get("/api/alert-events/\(alertKey)") + guard !Task.isCancelled else { return } + detail = refreshed } catch { + guard !Task.isCancelled else { return } errorMessage = String(localized: "Alert not found") } } diff --git a/apps/ios/ServerBee/ViewModels/InsightsViewModel.swift b/apps/ios/ServerBee/ViewModels/InsightsViewModel.swift index 563804477..124db729d 100644 --- a/apps/ios/ServerBee/ViewModels/InsightsViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/InsightsViewModel.swift @@ -17,6 +17,12 @@ final class InsightsViewModel { var isLoading = false var hasLoaded = false + func refreshCost(apiClient: APIClient) async { + let refreshed: CostOverviewResponse? = try? await apiClient.get("/api/cost/overview") + guard !Task.isCancelled else { return } + costOverview = refreshed + } + func load(apiClient: APIClient) async { isLoading = true defer { isLoading = false; hasLoaded = true } @@ -26,11 +32,13 @@ final class InsightsViewModel { async let maints: [Maintenance]? = try? apiClient.get("/api/maintenances") async let securityStats: [StatsBucket]? = try? apiClient.get("/api/security/stats?group_by=event_type") - costOverview = await cost - monitors = (await mons ?? []).sorted { $0.name < $1.name } - incidents = (await incs ?? []).sorted { $0.createdAt > $1.createdAt } - maintenances = (await maints ?? []).sorted { $0.startAt > $1.startAt } - securityEventCount = (await securityStats).map { buckets in buckets.reduce(0) { $0 + $1.count } } + let (overview, loadedMonitors, loadedIncidents, loadedMaintenances, stats) = await (cost, mons, incs, maints, securityStats) + guard !Task.isCancelled else { return } + costOverview = overview + monitors = (loadedMonitors ?? []).sorted { $0.name < $1.name } + incidents = (loadedIncidents ?? []).sorted { $0.createdAt > $1.createdAt } + maintenances = (loadedMaintenances ?? []).sorted { $0.startAt > $1.startAt } + securityEventCount = stats.map { buckets in buckets.reduce(0) { $0 + $1.count } } } // MARK: - Derived diff --git a/apps/ios/ServerBee/ViewModels/ServerDetailViewModel.swift b/apps/ios/ServerBee/ViewModels/ServerDetailViewModel.swift index 8baa246e8..d6ec7b770 100644 --- a/apps/ios/ServerBee/ViewModels/ServerDetailViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/ServerDetailViewModel.swift @@ -31,7 +31,9 @@ final class ServerDetailViewModel { isLoadingConfig = true defer { isLoadingConfig = false } do { - config = try await apiClient.get("/api/servers/\(serverId)") + let refreshed: ServerConfig = try await apiClient.get("/api/servers/\(serverId)") + guard !Task.isCancelled else { return } + config = refreshed } catch { AppLog.viewModel.error("ServerConfig fetch failed: \(String(describing: error), privacy: .public)") } diff --git a/apps/ios/ServerBee/ViewModels/ServerTrafficViewModel.swift b/apps/ios/ServerBee/ViewModels/ServerTrafficViewModel.swift index 1245051c4..5f1bef057 100644 --- a/apps/ios/ServerBee/ViewModels/ServerTrafficViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/ServerTrafficViewModel.swift @@ -23,6 +23,20 @@ final class ServerTrafficViewModel { await reload(serverId: serverId, apiClient: apiClient) } + func refreshCost(serverId: String, apiClient: APIClient) async { + let refreshed = await fetchCost(serverId: serverId, apiClient: apiClient) + guard !Task.isCancelled else { return } + cost = refreshed + } + + func loadForCatalogRevision(serverId: String, apiClient: APIClient) async { + if hasLoaded { + await refreshCost(serverId: serverId, apiClient: apiClient) + } else { + await reload(serverId: serverId, apiClient: apiClient) + } + } + func reload(serverId: String, apiClient: APIClient) async { isLoading = true defer { @@ -36,6 +50,7 @@ final class ServerTrafficViewModel { async let uptimeResult = fetchUptime(serverId: serverId, apiClient: apiClient) let (t, c, u) = await (trafficResult, costResult, uptimeResult) + guard !Task.isCancelled else { return } traffic = t cost = c uptime = u diff --git a/apps/ios/ServerBee/ViewModels/ServersViewModel.swift b/apps/ios/ServerBee/ViewModels/ServersViewModel.swift index 69e2cccdc..a99e04fd5 100644 --- a/apps/ios/ServerBee/ViewModels/ServersViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/ServersViewModel.swift @@ -27,6 +27,28 @@ final class ServersViewModel { var isLoading = false var isRefreshing = false var errorMessage: String? + /// Drives authenticated detail and cost readers independently of live updates. + private(set) var catalogRevision = 0 + private var fullCatalogRevision = 0 + private var serverCatalogRevisions: [String: Int] = [:] + private var fetchGeneration = 0 + + func catalogRevision(for serverId: String) -> Int { + max(fullCatalogRevision, serverCatalogRevisions[serverId] ?? 0) + } + + /// Used for both server invalidations and successful local edits. A reconnect + /// passes nil because changes may have happened while the socket was closed. + func refreshCatalog(serverIds: [String]? = nil, apiClient: APIClient) async { + catalogRevision += 1 + if let serverIds { + for id in serverIds { serverCatalogRevisions[id] = catalogRevision } + } else { + fullCatalogRevision = catalogRevision + serverCatalogRevisions = [:] + } + await fetchServers(apiClient: apiClient) + } var filteredServers: [ServerStatus] { var result = servers @@ -102,16 +124,20 @@ final class ServersViewModel { } func fetchServers(apiClient: APIClient) async { + fetchGeneration += 1 + let generation = fetchGeneration isLoading = true - defer { isLoading = false } + defer { if generation == fetchGeneration { isLoading = false } } do { async let serversReq: [ServerStatus] = apiClient.get("/api/servers") async let groupsReq: [ServerGroup] = apiClient.get("/api/server-groups") let (config, groups) = try await (serversReq, groupsReq) + guard generation == fetchGeneration, !Task.isCancelled else { return } groupsByID = Dictionary(groups.map { ($0.id, $0.name) }, uniquingKeysWith: { a, _ in a }) applyConfig(config) errorMessage = nil } catch { + guard generation == fetchGeneration, !Task.isCancelled else { return } AppLog.viewModel.error("Servers fetch failed: \(String(describing: error), privacy: .public)") errorMessage = String( format: String(localized: "Failed to load servers: %@"), @@ -134,9 +160,10 @@ final class ServersViewModel { var byID = Dictionary(servers.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) var order = servers.map(\.id) for cfg in config { - if var existing = byID[cfg.id] { - existing.merge(from: cfg) - byID[cfg.id] = existing + if let existing = byID[cfg.id] { + var refreshed = cfg + refreshed.mergeLiveMetrics(from: existing) + byID[cfg.id] = refreshed } else { byID[cfg.id] = cfg order.append(cfg.id) diff --git a/apps/ios/ServerBee/Views/Alerts/AlertDetailView.swift b/apps/ios/ServerBee/Views/Alerts/AlertDetailView.swift index 19fb3355d..1fbe41beb 100644 --- a/apps/ios/ServerBee/Views/Alerts/AlertDetailView.swift +++ b/apps/ios/ServerBee/Views/Alerts/AlertDetailView.swift @@ -4,6 +4,7 @@ struct AlertDetailView: View { let alertKey: String @State private var viewModel = AlertDetailViewModel() @Environment(\.apiClient) private var apiClient + @Environment(ServersViewModel.self) private var serversViewModel @Environment(\.dismiss) private var dismiss @ScaledMetric(relativeTo: .headline) private var buttonHeight: CGFloat = 50 @@ -40,7 +41,7 @@ struct AlertDetailView: View { .background(Color(.systemGroupedBackground)) .navigationTitle(String(localized: "Alert Detail")) .navigationBarTitleDisplayMode(.inline) - .task { + .task(id: serversViewModel.catalogRevision) { await viewModel.fetchDetail(alertKey: alertKey, apiClient: apiClient) } } @@ -84,6 +85,8 @@ private extension AlertDetailView { if let resolvedAt = detail.resolvedAt { parts.append(String(localized: "resolved \(Formatters.formatRelativeTime(resolvedAt))")) } + case .superseded: + parts.append(String(localized: "A newer renewal deadline superseded this reminder.")) } return parts.joined(separator: " \u{00B7} ") } @@ -100,8 +103,10 @@ private extension AlertDetailView { .buttonStyle(.plain) rowDivider AlertInfoRow(label: String(localized: "First triggered"), value: AlertAbsoluteTime.string(from: detail.firstTriggeredAt)) - rowDivider - AlertInfoRow(label: String(localized: "Resolved at"), value: detail.resolvedAt.map(AlertAbsoluteTime.string(from:))) + if detail.status != .superseded { + rowDivider + AlertInfoRow(label: String(localized: "Resolved at"), value: detail.resolvedAt.map(AlertAbsoluteTime.string(from:))) + } rowDivider AlertInfoRow(label: String(localized: "Trigger count"), value: "\(detail.triggerCount)") rowDivider diff --git a/apps/ios/ServerBee/Views/Alerts/AlertEventCardView.swift b/apps/ios/ServerBee/Views/Alerts/AlertEventCardView.swift index c6d6416bf..b6599877b 100644 --- a/apps/ios/ServerBee/Views/Alerts/AlertEventCardView.swift +++ b/apps/ios/ServerBee/Views/Alerts/AlertEventCardView.swift @@ -34,9 +34,7 @@ struct AlertEventCardView: View { } private var accessibilityLabelText: String { - let status = event.status == .firing - ? String(localized: "Firing") - : String(localized: "Resolved") + let status = event.status.label let relative = Formatters.formatRelativeTime(event.eventAt) var parts = [status, event.ruleName, event.serverName, relative] if event.count > 1 { diff --git a/apps/ios/ServerBee/Views/Alerts/AlertStatusBadge.swift b/apps/ios/ServerBee/Views/Alerts/AlertStatusBadge.swift index cfba3f5bb..551e25385 100644 --- a/apps/ios/ServerBee/Views/Alerts/AlertStatusBadge.swift +++ b/apps/ios/ServerBee/Views/Alerts/AlertStatusBadge.swift @@ -1,18 +1,19 @@ import SwiftUI -/// Tinted "Firing" / "Resolved" capsule. Firing uses the alert colour; green is -/// reserved for the resolved (healthy) state. +/// Superseded renewal targets use a neutral color because advancement is no recovery. struct AlertStatusBadge: View { let status: AlertStatus private var label: String { - status == .firing - ? String(localized: "Firing") - : String(localized: "Resolved") + status.label } private var color: Color { - status == .firing ? .alertFiring : .serverOnline + switch status { + case .firing: .alertFiring + case .resolved: .serverOnline + case .superseded: .secondary + } } var body: some View { diff --git a/apps/ios/ServerBee/Views/Alerts/AlertsListView.swift b/apps/ios/ServerBee/Views/Alerts/AlertsListView.swift index 186dce88e..456328b10 100644 --- a/apps/ios/ServerBee/Views/Alerts/AlertsListView.swift +++ b/apps/ios/ServerBee/Views/Alerts/AlertsListView.swift @@ -68,7 +68,7 @@ private extension AlertsListView { var eventsList: some View { let visible = viewModel.events(matching: filter) let firing = visible.filter { $0.status == .firing } - let earlier = visible.filter { $0.status == .resolved } + let earlier = visible.filter { $0.status != .firing } return List { Section { filterPicker diff --git a/apps/ios/ServerBee/Views/Insights/InsightsView.swift b/apps/ios/ServerBee/Views/Insights/InsightsView.swift index 89d4c639d..4dc12f699 100644 --- a/apps/ios/ServerBee/Views/Insights/InsightsView.swift +++ b/apps/ios/ServerBee/Views/Insights/InsightsView.swift @@ -34,8 +34,12 @@ struct InsightsView: View { .navigationTitle(String(localized: "Insights")) .navigationBarTitleDisplayMode(.large) .refreshable { await viewModel.load(apiClient: apiClient) } - .task { - if !viewModel.hasLoaded { await viewModel.load(apiClient: apiClient) } + .task(id: serversViewModel.catalogRevision) { + if !viewModel.hasLoaded { + await viewModel.load(apiClient: apiClient) + } else { + await viewModel.refreshCost(apiClient: apiClient) + } #if DEBUG // Both the incident and maintenance sheets live on IncidentsView. if let token = UITestSupport.autoPresent, diff --git a/apps/ios/ServerBee/Views/Servers/Detail/ServerTrafficSection.swift b/apps/ios/ServerBee/Views/Servers/Detail/ServerTrafficSection.swift index 0bd05f0b9..c8207d65c 100644 --- a/apps/ios/ServerBee/Views/Servers/Detail/ServerTrafficSection.swift +++ b/apps/ios/ServerBee/Views/Servers/Detail/ServerTrafficSection.swift @@ -7,6 +7,7 @@ struct ServerTrafficSection: View { let config: ServerConfig? @Environment(\.apiClient) private var apiClient + @Environment(ServersViewModel.self) private var serversViewModel @State private var viewModel = ServerTrafficViewModel() var body: some View { @@ -19,8 +20,8 @@ struct ServerTrafficSection: View { .refreshable { await viewModel.reload(serverId: serverId, apiClient: apiClient) } - .task { - await viewModel.loadIfNeeded(serverId: serverId, apiClient: apiClient) + .task(id: serversViewModel.catalogRevision(for: serverId)) { + await viewModel.loadForCatalogRevision(serverId: serverId, apiClient: apiClient) } } diff --git a/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift b/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift index c78a579bd..62eda236b 100644 --- a/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift +++ b/apps/ios/ServerBee/Views/Servers/ServerDetailView.swift @@ -23,6 +23,9 @@ struct ServerDetailView: View { @State private var showEdit = false /// Section content is created one tick after the screen appears; see `body`. @State private var isContentReady = false + #if DEBUG + @State private var hasAutoPresentedEdit = false + #endif /// Allow constructing from a known live status (list navigation) or just an /// id (deep link / push). @@ -129,7 +132,7 @@ struct ServerDetailView: View { EditServerSheet(serverId: serverId, config: config, onSaved: reloadConfig) } } - .task { + .task(id: serversViewModel.catalogRevision(for: serverId)) { await viewModel.fetchConfig(serverId: serverId, apiClient: apiClient) #if DEBUG if let raw = UITestSupport.detailSection, @@ -154,12 +157,15 @@ struct ServerDetailView: View { #if DEBUG private func debugPresentEditIfReady() { - if UITestSupport.autoPresent == "edit-server", viewModel.config != nil { showEdit = true } + if !hasAutoPresentedEdit, UITestSupport.autoPresent == "edit-server", viewModel.config != nil { + hasAutoPresentedEdit = true + showEdit = true + } } #endif private func reloadConfig() { - Task { await viewModel.fetchConfig(serverId: serverId, apiClient: apiClient) } + Task { await serversViewModel.refreshCatalog(serverIds: [serverId], apiClient: apiClient) } } @ViewBuilder diff --git a/apps/ios/ServerBeeTests/MobileAlertEventIdTests.swift b/apps/ios/ServerBeeTests/MobileAlertEventIdTests.swift index 170331301..e0885755b 100644 --- a/apps/ios/ServerBeeTests/MobileAlertEventIdTests.swift +++ b/apps/ios/ServerBeeTests/MobileAlertEventIdTests.swift @@ -2,6 +2,22 @@ import XCTest @testable import ServerBee final class MobileAlertEventIdTests: XCTestCase { + @MainActor + func testSupersededRenewalIsVisibleWithoutRecovery() throws { + let json = """ + {"rule_id":"expiry","rule_name":"Renewal","server_id":"server","server_name":"Server","status":"superseded", + "event_at":"2026-03-01T00:00:00Z","resolved_at":null,"count":1,"alert_key":"prior-occurrence"} + """ + let event = try JSONDecoder.snakeCase.decode(MobileAlertEvent.self, from: Data(json.utf8)) + let model = AlertsViewModel() + model.events = [event] + XCTAssertEqual(event.status.label, String(localized: "Superseded")) + XCTAssertNil(event.resolvedAt) + XCTAssertEqual(model.firingCount, 0) + XCTAssertEqual(model.events(matching: .all).map(\.alertKey), ["prior-occurrence"]) + XCTAssertTrue(model.events(matching: .resolved).isEmpty) + } + private func make(status: AlertStatus, eventAt: String) -> MobileAlertEvent { MobileAlertEvent( ruleId: "rule-1", diff --git a/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift b/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift index 2c1cea44d..c770e8d8e 100644 --- a/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift +++ b/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift @@ -3,6 +3,105 @@ import XCTest @MainActor final class WebSocketRouterTests: XCTestCase { + override func setUp() async throws { URLProtocol.registerClass(AuthenticationURLProtocol.self) } + + override func tearDown() async throws { + AuthenticationURLProtocol.handler = nil + AuthenticationURLProtocol.cancelPending() + URLProtocol.unregisterClass(AuthenticationURLProtocol.self) + AuthManager().clearAuth() + } + + func test_catalogRefreshUpdatesAuthenticatedReaders() async throws { + let auth = AuthManager() + auth.setServerUrl("https://catalog.test") + auth.handleLoginResponse(MobileTokenResponse( + accessToken: "catalog-access", accessExpiresInSecs: 900, + refreshToken: "catalog-refresh", refreshExpiresInSecs: 3600, + tokenType: "Bearer", user: MobileUser(id: "reader", username: "reader", role: "member") + )) + let api = APIClient(authManager: auth) + let list = ServersViewModel() + let detail = ServerDetailViewModel() + let traffic = ServerTrafficViewModel() + let insights = InsightsViewModel() + list.handleWSMessage(.fullSync(servers: [ServerStatus(id: "renewing", name: "Old name", online: true, cpuUsage: 42)], upgrades: [])) + let log = AuthenticationRequestLog() + AuthenticationURLProtocol.handler = { request in + _ = log.append(request.request) + XCTAssertEqual(request.request.value(forHTTPHeaderField: "Authorization"), "Bearer catalog-access") + let body: String + switch request.request.url?.path { + case "/api/servers": body = #"{"data":[{"id":"renewing","name":"Current name"}]}"# + case "/api/server-groups": body = #"{"data":[]}"# + case "/api/servers/renewing": + body = """ + {"data":{"id":"renewing","name":"Current name","expired_at":"2026-04-01T03:59:59Z", + "renewal":{"enabled":true,"billing_timezone":"America/New_York","expiry_date":"2026-03-31", + "confirmed_expired_at":"2026-02-01T04:59:59Z","deadline_origin":"projected","occurrence_id":"march"}}} + """ + case "/api/servers/renewing/cost-insights": + body = #"{"data":{"server_id":"renewing","configured":true,"advisories":[]}}"# + case "/api/cost/overview": + body = #"{"data":{"currencies":[],"servers":[{"server_id":"renewing","name":"Current name","configured":true,"advisories":[]}]}}"# + default: + XCTFail("Unexpected refresh endpoint") + request.respond(404) + return + } + request.respond(200, data: Data(body.utf8)) + } + let router = WebSocketRouter( + servers: { list.handleWSMessage($0) }, alerts: { _ in }, + catalogRefresh: { await list.refreshCatalog(serverIds: $0, apiClient: api) } + ) + await router.dispatchAndRefresh(.serverCatalogChanged(serverIds: ["renewing"])) + XCTAssertGreaterThan(list.catalogRevision(for: "renewing"), 0) + XCTAssertEqual(list.catalogRevision(for: "unaffected"), 0) + XCTAssertEqual(list.servers.first?.name, "Current name") + XCTAssertEqual(list.servers.first?.cpuUsage, 42) + XCTAssertEqual(list.servers.first?.online, true) + + // These are the same awaitable loaders used by revision-driven view tasks. + await detail.fetchConfig(serverId: "renewing", apiClient: api) + await traffic.refreshCost(serverId: "renewing", apiClient: api) + await insights.refreshCost(apiClient: api) + XCTAssertEqual(detail.config?.renewal?.expiryDate, "2026-03-31") + XCTAssertEqual(detail.config?.renewal?.confirmedExpiredAt, "2026-02-01T04:59:59Z") + XCTAssertEqual(traffic.cost?.advisories, []) + XCTAssertEqual(insights.costOverview?.servers.first?.advisories, []) + XCTAssertEqual(Set(log.snapshot().compactMap { $0.url?.path }), Set([ + "/api/servers", "/api/server-groups", "/api/servers/renewing", + "/api/servers/renewing/cost-insights", "/api/cost/overview" + ])) + + await router.dispatchAndRefresh(.fullSync(servers: list.servers, upgrades: [])) + XCTAssertGreaterThan(list.catalogRevision(for: "unaffected"), 0, "Reconnect refreshes every cached private reader") + let revision = list.catalogRevision + await list.refreshCatalog(serverIds: ["renewing"], apiClient: api) + XCTAssertGreaterThan(list.catalogRevision, revision, "A local save refreshes the same readers without requiring a WS echo") + } + + func test_catalogChangeRefreshesOnlyPrivateReaders() async throws { + let message = try JSONDecoder.snakeCase.decode(BrowserMessage.self, from: Data( + #"{"type":"server_catalog_changed","server_ids":["renewing"]}"#.utf8 + )) + var refreshed: [[String]?] = [] + var servers: [BrowserMessage] = [] + let router = WebSocketRouter( + servers: { servers.append($0) }, alerts: { _ in }, + catalogRefresh: { refreshed.append($0) } + ) + await router.dispatchAndRefresh(message) + XCTAssertEqual(refreshed, [["renewing"]]) + XCTAssertEqual(servers.count, 1) + await router.dispatchAndRefresh(.update(servers: [])) + XCTAssertEqual(refreshed.count, 1, "Live updates must not refetch private billing data") + await router.dispatchAndRefresh(.fullSync(servers: [], upgrades: [])) + XCTAssertEqual(refreshed.count, 2) + XCTAssertNil(refreshed[1]) + } + func test_alertEvent_invokesAlertHandlerOnly() async { var servers: [BrowserMessage] = [] var alerts: [BrowserMessage] = [] diff --git a/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift b/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift index 110f05230..d2fa385bc 100644 --- a/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift +++ b/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift @@ -7,6 +7,18 @@ import XCTest /// and capabilities vanish the instant the first WS frame arrived. @MainActor final class ServersViewModelMergeTests: XCTestCase { + func test_catalogRefreshKeepsLiveStateAndAppliesEdits() { + let vm = ServersViewModel() + vm.applyConfig([config("1")]) + vm.handleWSMessage(.update(servers: [liveFrame("1", online: true, cpu: 42)])) + vm.applyConfig([ServerStatus(id: "1", name: "Renamed")]) + + XCTAssertEqual(vm.servers.first?.name, "Renamed") + XCTAssertNil(vm.servers.first?.ipv4) + XCTAssertEqual(vm.servers.first?.cpuUsage, 42) + XCTAssertEqual(vm.servers.first?.online, true) + } + private func config(_ id: String) -> ServerStatus { var s = ServerStatus( id: id, name: "srv-\(id)", online: nil, cpuUsage: nil, From d252d82682bdda295f5f3bb956b5e245badd66b7 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:41:57 +0000 Subject: [PATCH 19/40] feat(ios): retain renewal data in the private server catalog --- apps/ios/ServerBee/Models/ServerStatus.swift | 11 ++++++++++- .../Services/WebSocketRouterTests.swift | 17 ++++++++++++++++- .../ViewModels/ServersViewModelMergeTests.swift | 13 ++++++++++++- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/apps/ios/ServerBee/Models/ServerStatus.swift b/apps/ios/ServerBee/Models/ServerStatus.swift index aa8963ded..b4f6e87e9 100644 --- a/apps/ios/ServerBee/Models/ServerStatus.swift +++ b/apps/ios/ServerBee/Models/ServerStatus.swift @@ -60,6 +60,9 @@ struct ServerStatus: Decodable, Identifiable, Hashable, Sendable { var agentAuthority: AgentAuthorityState? /// Decoder compatibility for older Server payloads. var hasToken: Bool? + /// Authenticated REST catalog fields; live metric frames never own billing. + var expiredAt: String? + var renewal: ServerRenewal? /// ISO-8601 string. The WS frame sends `last_active` as a Unix **epoch /// second integer**; the decoder normalises both forms to a string here so /// view code keeps a single representation. @@ -112,6 +115,8 @@ struct ServerStatus: Decodable, Identifiable, Hashable, Sendable { case effectiveCapabilities = "effective_capabilities" case agentAuthority = "agent_authority" case hasToken = "has_token" + case expiredAt = "expired_at" + case renewal case lastActiveAt = "last_active_at" case lastActive = "last_active" } @@ -170,6 +175,8 @@ extension ServerStatus { effectiveCapabilities = try container.decodeIfPresent(Int.self, forKey: .effectiveCapabilities) agentAuthority = try container.decodeIfPresent(AgentAuthorityState.self, forKey: .agentAuthority) hasToken = try container.decodeIfPresent(Bool.self, forKey: .hasToken) + expiredAt = try container.decodeIfPresent(String.self, forKey: .expiredAt) + renewal = try container.decodeIfPresent(ServerRenewal.self, forKey: .renewal) // `last_active` is a Unix epoch integer over the WS, an ISO string over // REST (`last_active_at`). Normalise to an ISO string. Using `try?` so a @@ -258,6 +265,7 @@ extension ServerStatus { if let v = other.tcpCount { tcpCount = v } if let v = other.udpCount { udpCount = v } if let v = other.uptime { uptime = v } + if let v = other.lastActiveAt { lastActiveAt = v } } /// Merge non-nil fields from another status (used for WebSocket partial @@ -284,7 +292,8 @@ extension ServerStatus { if let v = other.effectiveCapabilities { effectiveCapabilities = v } if let v = other.agentAuthority { agentAuthority = v } if let v = other.hasToken { hasToken = v } - if let v = other.lastActiveAt { lastActiveAt = v } + if let v = other.expiredAt { expiredAt = v } + if let v = other.renewal { renewal = v } } } diff --git a/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift b/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift index c770e8d8e..8656a4c5d 100644 --- a/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift +++ b/apps/ios/ServerBeeTests/Services/WebSocketRouterTests.swift @@ -25,6 +25,13 @@ final class WebSocketRouterTests: XCTestCase { let detail = ServerDetailViewModel() let traffic = ServerTrafficViewModel() let insights = InsightsViewModel() + traffic.cost = try JSONDecoder.snakeCase.decode(ServerCostInsights.self, from: Data( + #"{"server_id":"renewing","configured":true,"advisories":["expired_billing"]}"#.utf8 + )) + insights.costOverview = try JSONDecoder.snakeCase.decode(CostOverviewResponse.self, from: Data( + #"{"currencies":[],"servers":[{"server_id":"renewing","name":"Old name","configured":true,"advisories":["expired_billing"]}]}"#.utf8 + )) + list.applyConfig([ServerStatus(id: "renewing", name: "Old name", expiredAt: "2026-03-01T04:59:59Z")]) list.handleWSMessage(.fullSync(servers: [ServerStatus(id: "renewing", name: "Old name", online: true, cpuUsage: 42)], upgrades: [])) let log = AuthenticationRequestLog() AuthenticationURLProtocol.handler = { request in @@ -32,7 +39,12 @@ final class WebSocketRouterTests: XCTestCase { XCTAssertEqual(request.request.value(forHTTPHeaderField: "Authorization"), "Bearer catalog-access") let body: String switch request.request.url?.path { - case "/api/servers": body = #"{"data":[{"id":"renewing","name":"Current name"}]}"# + case "/api/servers": + body = """ + {"data":[{"id":"renewing","name":"Current name","expired_at":"2026-04-01T03:59:59Z", + "renewal":{"enabled":true,"billing_timezone":"America/New_York","expiry_date":"2026-03-31", + "confirmed_expired_at":"2026-02-01T04:59:59Z","deadline_origin":"projected","occurrence_id":"march"}}]} + """ case "/api/server-groups": body = #"{"data":[]}"# case "/api/servers/renewing": body = """ @@ -61,6 +73,9 @@ final class WebSocketRouterTests: XCTestCase { XCTAssertEqual(list.servers.first?.name, "Current name") XCTAssertEqual(list.servers.first?.cpuUsage, 42) XCTAssertEqual(list.servers.first?.online, true) + XCTAssertEqual(list.servers.first?.expiredAt, "2026-04-01T03:59:59Z") + XCTAssertEqual(list.servers.first?.renewal?.occurrenceId, "march") + XCTAssertEqual(list.servers.first?.renewal?.expiryDate, "2026-03-31") // These are the same awaitable loaders used by revision-driven view tasks. await detail.fetchConfig(serverId: "renewing", apiClient: api) diff --git a/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift b/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift index d2fa385bc..8f81aee70 100644 --- a/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift +++ b/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift @@ -9,12 +9,23 @@ import XCTest final class ServersViewModelMergeTests: XCTestCase { func test_catalogRefreshKeepsLiveStateAndAppliesEdits() { let vm = ServersViewModel() - vm.applyConfig([config("1")]) + var original = config("1") + original.expiredAt = "2026-04-01T03:59:59Z" + original.renewal = ServerRenewal( + enabled: true, billingTimezone: "America/New_York", expiryDate: "2026-03-31", + confirmedExpiredAt: "2026-02-01T04:59:59Z", deadlineOrigin: "projected", occurrenceId: "march" + ) + vm.applyConfig([original]) vm.handleWSMessage(.update(servers: [liveFrame("1", online: true, cpu: 42)])) + XCTAssertEqual(vm.servers.first?.renewal?.expiryDate, "2026-03-31", "Live updates retain REST renewal metadata") + vm.handleWSMessage(.fullSync(servers: [liveFrame("1", online: true, cpu: 42)], upgrades: [])) + XCTAssertEqual(vm.servers.first?.expiredAt, "2026-04-01T03:59:59Z", "Full sync preserves billing until REST refresh") vm.applyConfig([ServerStatus(id: "1", name: "Renamed")]) XCTAssertEqual(vm.servers.first?.name, "Renamed") XCTAssertNil(vm.servers.first?.ipv4) + XCTAssertNil(vm.servers.first?.expiredAt) + XCTAssertNil(vm.servers.first?.renewal) XCTAssertEqual(vm.servers.first?.cpuUsage, 42) XCTAssertEqual(vm.servers.first?.online, true) } From 29fcdb66e9efaac5d45ed24d8148949ae38ff623 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:44:42 +0000 Subject: [PATCH 20/40] test(ios): add strict loopback renewal acceptance fixture --- tests/check-ios-renewal-harness.py | 161 +++++++++++++++++++ tests/check-ios-renewal-results.py | 124 +++++++++++++++ tests/fixtures/ios-renewal-http.py | 241 +++++++++++++++++++++++++++++ 3 files changed, 526 insertions(+) create mode 100644 tests/check-ios-renewal-harness.py create mode 100644 tests/check-ios-renewal-results.py create mode 100644 tests/fixtures/ios-renewal-http.py diff --git a/tests/check-ios-renewal-harness.py b/tests/check-ios-renewal-harness.py new file mode 100644 index 000000000..d51d56eec --- /dev/null +++ b/tests/check-ios-renewal-harness.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""Portable protocol/gate checks. These do not execute Swift or a Simulator.""" + +import importlib.util +import json +import subprocess +import sys +import tempfile +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("renewal_results", ROOT / "tests/check-ios-renewal-results.py") +results = importlib.util.module_from_spec(spec) +spec.loader.exec_module(results) + + +class FixtureProtocolTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="renewal-fixture-") + self.directory = Path(self.temp.name) + self.process = subprocess.Popen( + [sys.executable, str(ROOT / "tests/fixtures/ios-renewal-http.py"), + "--evidence-dir", self.temp.name], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + self.addCleanup(self.cleanup_fixture) + for _ in range(100): + if self.directory.joinpath("fixture-url.txt").exists(): + self.url = self.directory.joinpath("fixture-url.txt").read_text().strip() + return + if self.process.poll() is not None: + self.fail("fixture process exited before readiness") + time.sleep(0.02) + self.fail("fixture startup timed out") + + def cleanup_fixture(self): + self.process.terminate() + self.process.communicate(timeout=5) + self.temp.cleanup() + + def request(self, path, method="GET", body=None, marker=True, host=None): + headers = {"Content-Type": "application/json"} + if marker: + headers["Authorization"] = "Bearer fixture-renewal-access" + if host: + headers["Host"] = host + request = urllib.request.Request(self.url + path, method=method, headers=headers, + data=json.dumps(body).encode() if body is not None else None) + try: + response = urllib.request.urlopen(request, timeout=3) + except urllib.error.HTTPError as error: + response = error + with response: + return response.status, json.load(response) + + def reset(self, scenario): + status, state = self.request("/__test/reset", "POST", {"scenario": scenario}) + self.assertEqual(status, 200) + return state + + def save(self, renewal, name="Renewal UI fixture"): + body = {"name": name, "billing_cycle": "monthly"} + if renewal is not None: + body["renewal"] = renewal + return self.request("/api/servers/renewal-ui-server", "PUT", body) + + def test_three_scenarios_capture_changed_intent_and_fixed_wire_responses(self): + self.reset("timezone") + for path in ["/api/servers", "/api/servers/renewal-ui-server", "/api/server-groups", + "/api/servers/renewal-ui-server/tags", "/api/servers/renewal-ui-server/records?from=x&to=y&interval=raw", + "/api/alert-events?limit=100", "/api/mobile/push/settings"]: + self.assertEqual(self.request(path)[0], 200) + self.assertEqual(self.request("/api/ws/servers")[0], 426) + status, body = self.save({"billing_timezone": "UTC"}) + self.assertEqual(status, 200) + self.assertEqual(body["data"]["renewal"]["expiry_date"], "2026-01-31") + self.assertEqual(body["data"]["expired_at"], "2026-01-31T23:59:59.999999999Z") + self.reset("switch") + status, projected = self.save({"enabled": True}) + self.assertEqual(status, 200) + self.assertEqual(projected["data"]["renewal"]["expiry_date"], "2026-02-28") + status, frozen = self.save({"enabled": False}) + self.assertEqual(status, 200) + self.assertEqual(frozen["data"]["expired_at"], "2026-03-01T04:59:59.999999999Z") + self.assertEqual(frozen["data"]["renewal"]["deadline_origin"], "frozen") + self.assertEqual(frozen["data"]["renewal"]["occurrence_id"], projected["data"]["renewal"]["occurrence_id"]) + self.reset("manual") + status, manual = self.save({"expiry_date": "2026-02-15"}) + self.assertEqual(status, 200) + self.assertEqual(manual["data"]["expired_at"], "2026-02-16T04:59:59.999999999Z") + self.assertEqual(manual["data"]["renewal"]["confirmed_expired_at"], "2026-02-16T04:59:59.999999999Z") + self.assertEqual(self.save(None, "Renamed renewal fixture")[0], 200) + state = self.request("/__test/state")[1] + self.assertEqual(results.validate_fixture(state)["saveCount"], 5) + capture = self.directory.joinpath("fixture-requests.jsonl").read_text() + self.assertNotIn("fixture-renewal-access", capture) + self.assertNotIn("Authorization", capture) + + def test_explicit_date_resubmission_on_switch_save_is_rejected_and_error_survives_reset(self): + self.reset("switch") + self.assertEqual(self.save({"enabled": True, "expiry_date": "2026-01-31"})[0], 422) + state = self.reset("manual") + self.assertTrue(state["errors"]) + + def test_dual_legacy_and_local_date_is_rejected(self): + self.reset("manual") + status, _ = self.request("/api/servers/renewal-ui-server", "PUT", { + "billing_cycle": "monthly", "renewal": {"expiry_date": "2026-02-15"}, + "expired_at": "2026-02-15T00:00:00Z"}) + self.assertEqual(status, 422) + + def test_unknown_read_and_notification_write_fail_without_capturing_sensitive_body(self): + self.assertEqual(self.request("/api/not-a-route")[0], 422) + self.assertEqual(self.request("/api/mobile/push/encrypted-register", "POST", {"content_key": "must-not-capture"})[0], 422) + self.assertNotIn("must-not-capture", self.directory.joinpath("fixture-requests.jsonl").read_text()) + + def test_missing_marker_and_non_loopback_host_are_rejected(self): + self.assertEqual(self.request("/api/servers", marker=False)[0], 422) + self.assertEqual(self.request("/api/servers", host="example.com")[0], 422) + + +class ResultGateTests(unittest.TestCase): + def ui_documents(self): + summary = {"totalTestCount": 3, "passedTests": 3, "failedTests": 0, "skippedTests": 0} + tree = {"testNodes": [{"nodeType": "Test Suite", "name": "ServerBeeUITests", + "children": [{"nodeType": "Test Suite", "name": "RenewalBillingUITests", + "children": [{"nodeType": "Test Case", "name": name + "()", + "nodeIdentifier": "RenewalBillingUITests/" + name + "()", + "result": "Passed"} for name in sorted(results.UI_METHODS)]}]}]} + return summary, tree + + def test_supported_sample_schema_passes_all_three_named_cases(self): + summary, tree = self.ui_documents() + self.assertEqual(results.validate_results(summary, tree, "ui")["counts"]["passedTests"], 3) + + def test_zero_skip_missing_method_unknown_schema_cannot_pass(self): + summary, tree = self.ui_documents() + for changed in [{}, {**summary, "totalTestCount": 0}, {**summary, "skippedTests": 1}]: + with self.assertRaises(ValueError): + results.validate_results(changed, tree, "ui") + with self.assertRaises(ValueError): + results.validate_results(summary, {"unexpectedNodes": []}, "ui") + tree["testNodes"][0]["children"][0]["children"][0]["name"] = "testUnrelated()" + with self.assertRaises(ValueError): + results.validate_results(summary, tree, "ui") + + def test_successful_ui_counts_cannot_fill_unit_gate(self): + summary, tree = self.ui_documents() + with self.assertRaises(ValueError): + results.validate_results(summary, tree, "unit", ROOT / "apps/ios/ServerBeeTests/RenewalDateTests.swift") + + def test_incomplete_or_error_fixture_cannot_pass(self): + for state in [{}, {"errors": [], "completed": {}}, {"errors": ["unknown write"], "completed": {}}]: + with self.assertRaises(ValueError): + results.validate_fixture(state) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/check-ios-renewal-results.py b/tests/check-ios-renewal-results.py new file mode 100644 index 000000000..0307d5f2c --- /dev/null +++ b/tests/check-ios-renewal-results.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Fail-closed acceptance gate for Xcode 16 test-results JSON and fixture intent. + +The runner retains installed xcresulttool help and unmodified JSON. Unknown JSON +schemas fail this gate; sample JSON checks on Linux are not native test evidence. +""" + +import argparse +import json +import re +from pathlib import Path + +UI_METHODS = { + "testBillingDateAndTimezoneRemainIndependentOfDeviceTimezone", + "testAutomaticRenewalCanBeEnabledThenFrozenThroughControls", + "testManualDateEditUsesTheSelectedBillingCalendarDate", +} + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def test_cases(tree): + require(isinstance(tree, dict) and isinstance(tree.get("testNodes"), list), + "unsupported xcresult tests schema: expected testNodes list") + cases = [] + + def visit(node, ancestors): + require(isinstance(node, dict) and isinstance(node.get("nodeType"), str) + and isinstance(node.get("name"), str), "unsupported xcresult test node") + path = ancestors + [node["name"]] + if node["nodeType"] == "Test Case": + require(isinstance(node.get("result"), str), "test case lacks result") + identifier = node.get("nodeIdentifier") + require(isinstance(identifier, str) and identifier, "test case lacks nodeIdentifier") + cases.append({"identifier": identifier, "name": node["name"], + "path": "/".join(path), "result": node["result"]}) + children = node.get("children", []) + require(isinstance(children, list), "unsupported xcresult children schema") + for child in children: + visit(child, path) + + for node in tree["testNodes"]: + visit(node, []) + require(cases, "zero executed test cases") + return cases + + +def validate_results(summary, tree, kind, renewal_source=None): + keys = ["totalTestCount", "passedTests", "failedTests", "skippedTests"] + require(isinstance(summary, dict), "unsupported xcresult summary schema") + for key in keys: + require(type(summary.get(key)) is int, f"unsupported xcresult summary field {key}") + cases = test_cases(tree) + require(summary["totalTestCount"] == len(cases), "summary/tree test counts disagree") + require(summary["passedTests"] == len(cases) and summary["failedTests"] == 0 + and summary["skippedTests"] == 0, "failed, skipped or unexecuted native tests") + require(all(case["result"] == "Passed" for case in cases), "non-passing native test case") + identifiers = [case["identifier"] for case in cases] + require(len(set(identifiers)) == len(cases), "duplicate/retried test identifiers") + if kind == "ui": + require(len(cases) == 3, "UI bundle must execute exactly three acceptance methods") + for name in UI_METHODS: + matches = [case for case in cases if "RenewalBillingUITests" in case["path"] + and case["name"].removesuffix("()") == name] + require(len(matches) == 1, f"missing UI acceptance method {name}") + else: + require(len(cases) >= 463, "native unit bundle must retain at least 463 passing tests") + require(all("ServerBeeUITests" not in case["path"] for case in cases), + "UI success cannot fill a unit bundle count") + require(renewal_source is not None, "unit gate needs actual renewal test source") + expected = set(re.findall(r"func\s+(test\w+)\s*\(", renewal_source.read_text())) + require(len(expected) >= 15, "renewal unit source lost required methods") + actual = {case["name"].removesuffix("()") for case in cases + if "RenewalDateTests" in case["path"]} + require(expected == actual, "renewal unit methods differ from the checked-out source") + return {"kind": kind, "counts": {key: summary[key] for key in keys}, "cases": cases} + + +def validate_fixture(state): + require(isinstance(state, dict) and state.get("errors") == [], "fixture recorded protocol errors") + completed = state.get("completed") + require(isinstance(completed, dict) and set(completed) == {"timezone", "switch", "manual"}, + "fixture did not complete all three scenarios") + require([len(completed[key]) for key in ["timezone", "switch", "manual"]] == [1, 2, 2], + "fixture save counts differ") + expected = { + "timezone": [{"billing_timezone": "UTC"}], + "switch": [{"enabled": True}, {"enabled": False}], + "manual": [{"expiry_date": "2026-02-15"}, None], + } + for scenario, renewals in expected.items(): + for body, renewal in zip(completed[scenario], renewals): + require(isinstance(body, dict) and "expired_at" not in body, "legacy date intent captured") + if renewal is None: + require("renewal" not in body and body.get("name") == "Renamed renewal fixture", + "name-only save introduced renewal intent") + else: + require(body.get("renewal") == renewal, "captured renewal intent differs") + return {"scenarios": sorted(completed), "saveCount": 5, "errors": []} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--kind", choices=["unit", "ui"], required=True) + parser.add_argument("--summary", type=Path, required=True) + parser.add_argument("--tests", type=Path, required=True) + parser.add_argument("--renewal-source", type=Path) + parser.add_argument("--fixture-state", type=Path) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = validate_results(json.loads(args.summary.read_text()), json.loads(args.tests.read_text()), + args.kind, args.renewal_source) + if args.kind == "ui": + require(args.fixture_state is not None, "UI gate needs fixture evidence") + result["fixture"] = validate_fixture(json.loads(args.fixture_state.read_text())) + args.output.write_text(json.dumps(result, indent=2) + "\n") + print(f"{args.kind}: {result['counts']['passedTests']} passed, zero failed/skipped") + + +if __name__ == "__main__": + main() diff --git a/tests/fixtures/ios-renewal-http.py b/tests/fixtures/ios-renewal-http.py new file mode 100644 index 000000000..95b9e71c0 --- /dev/null +++ b/tests/fixtures/ios-renewal-http.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Local client-acceptance transport. No recurrence, database or provider model. + +Deadline literals: renewal_projection.rs enabling_overdue_month_end..., +scheduled_evaluation_advances_offline_month_end..., disabling_freezes...; +manual-date snapshot: renewal_edits.rs (see native UI evidence). +Opaque occurrence strings are fixture identities, never real Server credentials. +""" + +import argparse +import copy +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlsplit + +SERVER_ID = "renewal-ui-server" +ACCESS_MARKER = "fixture-renewal-access" +NY_JANUARY = "2026-02-01T04:59:59.999999999Z" +NY_FEBRUARY = "2026-03-01T04:59:59.999999999Z" +NY_MANUAL = "2026-02-16T04:59:59.999999999Z" + + +def snapshot(enabled=False, date="2026-01-31", deadline=NY_JANUARY, + origin="confirmed", confirmed=NY_JANUARY, occurrence="fixture-january"): + return { + "id": SERVER_ID, "name": "Renewal UI fixture", "billing_cycle": "monthly", + "price": 10, "currency": "USD", "weight": 0, "hidden": False, + "capabilities": 0, "agent_local_capabilities": 0, "effective_capabilities": 0, + "agent_authority": {"status": "claimed", "outstanding_offer": None}, + "expired_at": deadline, + "renewal": { + "enabled": enabled, "billing_timezone": "America/New_York", + "expiry_date": date, "confirmed_expired_at": confirmed, + "deadline_origin": origin, "occurrence_id": occurrence, + }, + } + + +CONFIRMED = snapshot() +PROJECTED = snapshot(True, "2026-02-28", NY_FEBRUARY, "projected", + occurrence="fixture-february") +FROZEN = copy.deepcopy(PROJECTED) +FROZEN["renewal"].update(enabled=False, deadline_origin="frozen") +TIMEZONE_SAVED = copy.deepcopy(CONFIRMED) +TIMEZONE_SAVED["expired_at"] = "2026-01-31T23:59:59.999999999Z" +TIMEZONE_SAVED["renewal"]["billing_timezone"] = "UTC" +MANUAL = snapshot(True, "2026-02-15", NY_MANUAL, "projected", NY_MANUAL, + "fixture-manual-february") +NAMED = copy.deepcopy(MANUAL) +NAMED["name"] = "Renamed renewal fixture" +SCENARIOS = { + "timezone": (CONFIRMED, [({"billing_timezone": "UTC"}, TIMEZONE_SAVED)]), + "switch": (CONFIRMED, [({"enabled": True}, PROJECTED), ({"enabled": False}, FROZEN)]), + "manual": (PROJECTED, [({"expiry_date": "2026-02-15"}, MANUAL), (None, NAMED)]), +} +PUSH_SETUP = { + "revision": 1, "registered": False, "delivery_available": False, + "security_allowed": False, "tasks_allowed": False, "test_available": False, + "task_failure_available": False, + "preferences": {"enabled": False, "alerts": False, "security": False, + "task_failure": False, "task_success": False}, +} + + +class Fixture: + def __init__(self, evidence): + self.evidence = evidence + self.lock = threading.RLock() + self.current = copy.deepcopy(CONFIRMED) + self.scenario = None + self.saves = [] + self.errors = [] + self.completed = {} + self.reads = {} + self.persist() + + def state(self): + return {"scenario": self.scenario, "server": self.current, + "saves": self.saves, "errors": self.errors, "completed": self.completed, + "reads": self.reads} + + def persist(self): + pending = self.evidence.joinpath("fixture-state.pending.json") + pending.write_text( + json.dumps(self.state(), indent=2) + "\n") + pending.replace(self.evidence.joinpath("fixture-state.json")) + + def capture(self, method, path, body, status): + # Deliberately never record headers, query values, access or refresh markers. + record = {"method": method, "path": path, "body": body, "status": status, + "scenario": self.scenario} + with self.evidence.joinpath("fixture-requests.jsonl").open("a") as stream: + stream.write(json.dumps(record) + "\n") + + def fail(self, message): + self.errors.append(message) + self.persist() + return 422, {"error": {"message": message}} + + def save(self, body): + if self.scenario not in SCENARIOS: + return self.fail("save without an active scenario") + steps = SCENARIOS[self.scenario][1] + index = len(self.saves) + if index >= len(steps): + return self.fail("unexpected additional save") + expected, result = steps[index] + if not isinstance(body, dict) or "expired_at" in body: + return self.fail("invalid body or legacy expired_at date intent") + if expected is None: + if "renewal" in body or body.get("name") != NAMED["name"]: + return self.fail("name-only save must omit renewal") + elif body.get("renewal") != expected: + return self.fail("renewal intent differs from the scenario contract") + if body.get("billing_cycle") != "monthly": + return self.fail("billing cycle must remain monthly") + allowed = {"name", "weight", "hidden", "remark", "public_remark", "group_id", + "currency", "billing_cycle", "traffic_limit_type", "price", + "billing_start_day", "traffic_limit", "renewal"} + if set(body) - allowed: + return self.fail("unrecognized server update fields") + self.saves.append(copy.deepcopy(body)) + self.current = copy.deepcopy(result) + if len(self.saves) == len(steps): + self.completed[self.scenario] = copy.deepcopy(self.saves) + self.persist() + return 200, {"data": self.current} + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def do_GET(self): + self.handle_request() + + def do_POST(self): + self.handle_request() + + def do_PUT(self): + self.handle_request() + + def do_DELETE(self): + self.handle_request() + + def do_PATCH(self): + self.handle_request() + + def do_OPTIONS(self): + self.handle_request() + + def do_HEAD(self): + self.handle_request() + + def handle_request(self): + fixture = self.server.fixture + with fixture.lock: + route = urlsplit(self.path) + path = route.path + body = None + try: + if route.scheme or route.netloc or "%" in path or ".." in path: + raise ValueError("non-local request target") + if self.headers.get("Host") != f"127.0.0.1:{self.server.server_port}": + raise ValueError("non-loopback host") + length = int(self.headers.get("Content-Length", "0")) + if length < 0 or length > 65536: + raise ValueError("invalid request length") + if length: + body = json.loads(self.rfile.read(length)) + if path.startswith("/api/"): + authorized = self.headers.get("Authorization") == f"Bearer {ACCESS_MARKER}" + if not authorized: + raise ValueError("application request lacks fixture marker") + status, reply = self.dispatch(path, body) + except (ValueError, TypeError, json.JSONDecodeError) as error: + status, reply = fixture.fail(str(error)) + # Unknown/provider writes may contain confidential bodies. Capture only + # the approved editor PUT and reset fields; never an auth/register body. + captured = body if path == f"/api/servers/{SERVER_ID}" and self.command == "PUT" else None + fixture.capture(self.command, path, captured, status) + encoded = json.dumps(reply).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def dispatch(self, path, body): + fixture = self.server.fixture + method = self.command + if method == "GET" and path == "/__test/state": + return 200, fixture.state() + if method == "POST" and path == "/__test/reset": + if not isinstance(body, dict) or body.get("scenario") not in SCENARIOS: + return fixture.fail("unknown reset scenario") + fixture.scenario = body["scenario"] + fixture.saves = [] + fixture.reads = {} + fixture.current = copy.deepcopy(SCENARIOS[fixture.scenario][0]) + # Errors and completed captures survive resets, so a failed earlier + # case cannot disappear from the final runner report. + fixture.persist() + return 200, fixture.state() + server_path = f"/api/servers/{SERVER_ID}" + if method == "PUT" and path == server_path: + return fixture.save(body) + if method == "GET": + fixture.reads[path] = fixture.reads.get(path, 0) + 1 + fixture.persist() + if path == "/api/servers": + return 200, {"data": [fixture.current]} + if path == server_path: + return 200, {"data": fixture.current} + if path in {"/api/server-groups", "/api/alert-events", + server_path + "/tags", server_path + "/records"}: + return 200, {"data": []} + if path == "/api/mobile/push/settings": + return 200, {"data": PUSH_SETUP} + if path == "/api/ws/servers": + # Intentional bounded unsupported local WS, not a live refresh proof. + return 426, {"error": {"message": "fixture has no live WebSocket"}} + return fixture.fail(f"unsupported fixture route: {method} {path}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--evidence-dir", type=Path, required=True) + args = parser.parse_args() + args.evidence_dir.mkdir(parents=True, exist_ok=True) + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.fixture = Fixture(args.evidence_dir) + args.evidence_dir.joinpath("fixture-url.txt").write_text( + f"http://127.0.0.1:{server.server_port}\n") + server.serve_forever() + + +if __name__ == "__main__": + main() From 3574b8591d70a2b4e4b56fc894dc5175401f4d56 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:45:09 +0000 Subject: [PATCH 21/40] test(ios): exercise renewal billing through native controls --- .../Servers/Enrollment/EditServerSheet.swift | 6 + .../RenewalBillingUITests.swift | 293 ++++++++++++++++++ apps/ios/project.yml | 25 ++ tests/check-push-secret-boundaries.py | 2 +- 4 files changed, 325 insertions(+), 1 deletion(-) create mode 100644 apps/ios/ServerBeeUITests/RenewalBillingUITests.swift diff --git a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift index b5489511b..1279429ac 100644 --- a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift +++ b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift @@ -93,6 +93,12 @@ private extension EditServerSheet { @ViewBuilder var renewalSection: some View { Section(String(localized: "Renewal")) { + #if DEBUG + if ProcessInfo.processInfo.environment["SB_UITEST_RENEWAL_CONTEXT"] == "1" { + Text(verbatim: TimeZone.current.identifier) + .accessibilityIdentifier("renewal.deviceTimezone") + } + #endif Picker(String(localized: "Billing timezone"), selection: $viewModel.billingTimezone) { ForEach(Self.billingTimezones, id: \.self) { Text(verbatim: $0).tag($0) } } diff --git a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift new file mode 100644 index 000000000..4d12d4fe8 --- /dev/null +++ b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift @@ -0,0 +1,293 @@ +import XCTest + +/// Real SwiftUI controls and production request encoding against a local HTTP +/// seam. Calendar recurrence and persistence are verified by Server HTTP tests. +@MainActor +final class RenewalBillingUITests: XCTestCase { + private let app = XCUIApplication() + private var fixtureURL: URL? + + func testBillingDateAndTimezoneRemainIndependentOfDeviceTimezone() async throws { + defer { screenshot("timezone-final"); app.terminate() } + try await launch(scenario: "timezone") + let deviceZone = reveal("renewal.deviceTimezone") + let zone = deviceZone.label + XCTAssertFalse(zone.isEmpty, "Missing actual application TimeZone.current readout") + XCTAssertNotEqual(zone, "America/New_York", "This acceptance requires a device/billing timezone mismatch") + let metadata = XCTAttachment(string: "Application TimeZone.current.identifier: \(zone)") + metadata.name = "actual-device-timezone" + metadata.lifetime = .keepAlways + add(metadata) + assertDate("Jan 31, 2026") + assertText("renewal.timezone", contains: "America/New_York") + screenshot("stored-january-date") + + reveal("renewal.timezone").tap() + let utc = app.buttons["UTC"].firstMatch + XCTAssertTrue(utc.waitForExistence(timeout: 5), app.debugDescription) + utc.tap() + assertText("renewal.timezone", contains: "UTC") + assertDate("Jan 31, 2026") + screenshot("utc-picker-selected-date-preserved") + try await save(expectedCount: 1) + let body = try await capturedSave(index: 0) + XCTAssertEqual(body["renewal"] as? [String: String], ["billing_timezone": "UTC"]) + XCTAssertNil(body["expired_at"]) + try await reopen(expectedOrigin: "Confirmed renewal deadline") + assertText("renewal.timezone", contains: "UTC") + assertDate("Jan 31, 2026") + screenshot("reopened-utc-date") + try await assertFixtureHealthy() + } + + func testAutomaticRenewalCanBeEnabledThenFrozenThroughControls() async throws { + defer { screenshot("switch-final"); app.terminate() } + try await launch(scenario: "switch") + assertSwitch(enabled: false) + assertDate("Jan 31, 2026") + reveal("renewal.enabled").tap() + assertSwitch(enabled: true) + screenshot("enable-selected") + try await save(expectedCount: 1) + let enabledBody = try await capturedSave(index: 0) + XCTAssertEqual(enabledBody["renewal"] as? [String: Bool], ["enabled": true]) + XCTAssertNil(enabledBody["expired_at"]) + try await reopen(expectedOrigin: "Projected renewal deadline") + assertSwitch(enabled: true) + assertDate("Feb 28, 2026") + assertExplanation("This deadline is a forecast. It does not confirm provider renewal or payment.") + screenshot("saved-projected-deadline") + let projected = try await fixtureState() + let projectedRenewal = try renewal(in: projected) + + reveal("renewal.enabled").tap() + assertSwitch(enabled: false) + try await save(expectedCount: 2) + let disabledBody = try await capturedSave(index: 1) + XCTAssertEqual(disabledBody["renewal"] as? [String: Bool], ["enabled": false]) + XCTAssertNil(disabledBody["expired_at"]) + try await reopen(expectedOrigin: "Frozen renewal deadline") + assertSwitch(enabled: false) + assertDate("Feb 28, 2026") + assertText("renewal.confirmed", contains: "Jan 31, 2026") + assertExplanation("Automatic renewal is off. This forecast is frozen; it does not confirm provider renewal or payment.") + let frozenRenewal = try renewal(in: await fixtureState()) + XCTAssertEqual(frozenRenewal["occurrence_id"] as? String, projectedRenewal["occurrence_id"] as? String) + XCTAssertEqual(frozenRenewal["confirmed_expired_at"] as? String, projectedRenewal["confirmed_expired_at"] as? String) + screenshot("saved-frozen-deadline-and-history") + try await assertFixtureHealthy() + } + + func testManualDateEditUsesTheSelectedBillingCalendarDate() async throws { + defer { screenshot("manual-final"); app.terminate() } + try await launch(scenario: "manual") + assertSwitch(enabled: true) + assertDate("Feb 28, 2026") + reveal("renewal.expiry").tap() + // Compact DatePicker opens Apple's calendar. Select an actual day cell, + // never a binding, view-model method or fixture date injection. + let fullDate = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "February 15")).firstMatch + let day = app.buttons["15"].firstMatch + let selectedDay: XCUIElement + if fullDate.waitForExistence(timeout: 3) { + selectedDay = fullDate + } else { + XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", "February 2026")).firstMatch.exists, + "Expected February calendar: \(app.debugDescription)") + XCTAssertTrue(day.waitForExistence(timeout: 3), app.debugDescription) + selectedDay = day + } + screenshot("manual-calendar-before-day-selection") + selectedDay.tap() + // The date popover can stay open after selection; tapping its production + // row label dismisses it without changing the chosen calendar date. + if app.buttons["15"].firstMatch.isHittable { + app.staticTexts["Expires"].firstMatch.tap() + } + assertDate("Feb 15, 2026") + screenshot("manual-february-fifteenth-selected") + try await save(expectedCount: 1) + let dateBody = try await capturedSave(index: 0) + XCTAssertEqual(dateBody["renewal"] as? [String: String], ["expiry_date": "2026-02-15"]) + XCTAssertNil(dateBody["expired_at"]) + try await reopen(expectedOrigin: "Projected renewal deadline") + assertDate("Feb 15, 2026") + assertText("renewal.timezone", contains: "America/New_York") + assertText("renewal.confirmed", contains: "Feb 15, 2026") + screenshot("manual-saved-projection-and-new-history") + + let name = reveal("server.name", scrollingDown: false) + name.tap() + if let value = name.value as? String { + name.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: value.count)) + } + name.typeText("Renamed renewal fixture") + try await save(expectedCount: 2) + let nameBody = try await capturedSave(index: 1) + XCTAssertEqual(nameBody["name"] as? String, "Renamed renewal fixture") + XCTAssertNil(nameBody["renewal"]) + XCTAssertNil(nameBody["expired_at"]) + try await reopen(expectedOrigin: "Projected renewal deadline") + assertDate("Feb 15, 2026") + assertText("renewal.confirmed", contains: "Feb 15, 2026") + assertText("renewal.timezone", contains: "America/New_York") + screenshot("name-only-save-preserves-date-and-origin") + try await assertFixtureHealthy() + } +} + +private extension RenewalBillingUITests { + enum FixtureError: Error { case invalidURL, invalidResponse, invalidState } + + func launch(scenario: String) async throws { + continueAfterFailure = false + let raw = ProcessInfo.processInfo.environment["SERVERBEE_RENEWAL_FIXTURE_URL"] ?? "" + guard let url = URL(string: raw), url.scheme == "http", url.host == "127.0.0.1", url.port != nil, + url.path.isEmpty, url.query == nil, url.user == nil else { throw FixtureError.invalidURL } + fixtureURL = url + _ = try await request("/__test/reset", body: ["scenario": scenario]) + app.launchArguments = ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"] + app.launchEnvironment = [ + "SB_UITEST_SERVER": raw, + "SB_UITEST_ACCESS": "fixture-renewal-access", + "SB_UITEST_REFRESH": "fixture-renewal-refresh", + "SB_UITEST_USERNAME": "fixture-admin", "SB_UITEST_USER_ID": "fixture-user", + "SB_UITEST_ROLE": "admin", "SB_UITEST_DEEPLINK": "server:renewal-ui-server", + "SB_UITEST_PRESENT": "edit-server", "SB_UITEST_RENEWAL_CONTEXT": "1" + ] + app.launch() + XCTAssertTrue(app.buttons["server.save"].waitForExistence(timeout: 20), app.debugDescription) + XCTAssertTrue(app.textFields["server.name"].waitForExistence(timeout: 5)) + // Groups/tags load asynchronously during form prefill. Wait for those + // real auxiliary reads before enabling save interactions. + for _ in 0..<50 { + let state = try await fixtureState() + let reads = state["reads"] as? [String: Int] ?? [:] + if reads["/api/server-groups", default: 0] > 0 && reads["/api/servers/renewal-ui-server/tags", default: 0] > 0 { + return + } + try await Task.sleep(for: .milliseconds(100)) + } + XCTFail("Editor groups/tags reads did not complete") + } + + func element(_ identifier: String) -> XCUIElement { + app.descendants(matching: .any).matching(identifier: identifier).firstMatch + } + + @discardableResult + func reveal(_ identifier: String, scrollingDown: Bool = true) -> XCUIElement { + let target = element(identifier) + for _ in 0..<14 { + if target.exists && target.isHittable { return target } + if scrollingDown { app.swipeUp() } else { app.swipeDown() } + } + XCTAssertTrue(target.exists && target.isHittable, "Control \(identifier): \(app.debugDescription)") + return target + } + + func assertText(_ identifier: String, contains text: String) { + let target = reveal(identifier) + let predicate = NSPredicate(format: "label CONTAINS %@ OR value CONTAINS %@", text, text) + let expectation = XCTNSPredicateExpectation(predicate: predicate, object: target) + if XCTWaiter.wait(for: [expectation], timeout: 5) != .completed { + XCTAssertTrue(target.descendants(matching: .any).matching(predicate).firstMatch.exists, + "Expected \(text) in \(target.debugDescription)") + } + } + + func assertDate(_ text: String) { + assertText("renewal.expiry", contains: text) + } + + func assertSwitch(enabled: Bool) { + let toggle = reveal("renewal.enabled") + XCTAssertEqual(toggle.value as? String, enabled ? "1" : "0", toggle.debugDescription) + } + + func assertExplanation(_ text: String) { + let target = app.staticTexts[text].firstMatch + for _ in 0..<8 { + if target.exists && target.isHittable { break } + app.swipeUp() + } + XCTAssertTrue(target.exists, app.debugDescription) + } + + func screenshot(_ name: String) { + let image = app.state == .runningForeground ? app.screenshot() : XCUIScreen.main.screenshot() + let attachment = XCTAttachment(screenshot: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } + + func save(expectedCount: Int) async throws { + app.buttons["server.save"].tap() + let edit = app.buttons["server.edit"] + XCTAssertTrue(edit.waitForExistence(timeout: 10), app.debugDescription) + waitUntilHittable(edit) + let state = try await fixtureState() + XCTAssertEqual((state["saves"] as? [[String: Any]])?.count, expectedCount) + XCTAssertFalse(app.buttons["server.save"].exists, "Editor must dismiss after a real save") + } + + func waitUntilHittable(_ target: XCUIElement) { + let ready = XCTNSPredicateExpectation(predicate: NSPredicate(format: "hittable == true"), object: target) + XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 10), .completed, app.debugDescription) + } + + func reopen(expectedOrigin: String) async throws { + // Await the detail's real post-save GET (not merely the PUT response). + // Opening the production toolbar immediately could observe old config. + let origin = app.staticTexts[expectedOrigin].firstMatch + for _ in 0..<10 { + if origin.exists { break } + app.swipeUp() + } + XCTAssertTrue(origin.waitForExistence(timeout: 10), app.debugDescription) + app.buttons["server.edit"].tap() + XCTAssertTrue(app.buttons["server.save"].waitForExistence(timeout: 10)) + assertText("renewal.origin", contains: expectedOrigin) + } + + func request(_ path: String, body: [String: String]? = nil) async throws -> [String: Any] { + guard let base = fixtureURL else { throw FixtureError.invalidURL } + var request = URLRequest(url: base.appendingPathComponent(path)) + request.timeoutInterval = 5 + if let body { + request.httpMethod = "POST" + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONSerialization.data(withJSONObject: body) + } + let (data, response) = try await URLSession.shared.data(for: request) + guard (response as? HTTPURLResponse)?.statusCode == 200, + let result = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw FixtureError.invalidResponse + } + return result + } + + func fixtureState() async throws -> [String: Any] { + try await request("/__test/state") + } + + func capturedSave(index: Int) async throws -> [String: Any] { + let state = try await fixtureState() + guard let saves = state["saves"] as? [[String: Any]], saves.indices.contains(index) else { + throw FixtureError.invalidState + } + return saves[index] + } + + func renewal(in state: [String: Any]) throws -> [String: Any] { + guard let server = state["server"] as? [String: Any], + let renewal = server["renewal"] as? [String: Any] else { throw FixtureError.invalidState } + return renewal + } + + func assertFixtureHealthy() async throws { + let state = try await fixtureState() + XCTAssertEqual(state["errors"] as? [String], [], "Unknown routes or invalid intent must fail acceptance") + } +} diff --git a/apps/ios/project.yml b/apps/ios/project.yml index e411df423..e532c4c64 100644 --- a/apps/ios/project.yml +++ b/apps/ios/project.yml @@ -98,6 +98,19 @@ targets: - "$(inherited)" - "-framework" - AppIntents + ServerBeeUITests: + type: bundle.ui-testing + platform: iOS + sources: + - path: ServerBeeUITests + dependencies: + - target: ServerBee + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: app.serverbee.uitests + GENERATE_INFOPLIST_FILE: YES + TEST_TARGET_NAME: ServerBee + SWIFT_STRICT_CONCURRENCY: complete schemes: ServerBee: build: @@ -108,3 +121,15 @@ schemes: targets: - ServerBeeTests gatherCoverageData: true + ServerBeeUI: + build: + targets: + ServerBee: [test] + ServerBeeUITests: [test] + test: + config: Debug + targets: + - name: ServerBeeUITests + parallelizable: false + randomExecutionOrder: false + deleteScreenshotsWhenEachTestSucceeds: false diff --git a/tests/check-push-secret-boundaries.py b/tests/check-push-secret-boundaries.py index ae108c4c6..448854812 100644 --- a/tests/check-push-secret-boundaries.py +++ b/tests/check-push-secret-boundaries.py @@ -26,7 +26,7 @@ def check_entitlements(): bundle_id = "app.serverbee" project = (IOS / "project.yml").read_text() assert re.findall(r"PRODUCT_BUNDLE_IDENTIFIER: (\S+)", project) == [ - bundle_id, bundle_id + ".notifications", bundle_id + ".tests" + bundle_id, bundle_id + ".notifications", bundle_id + ".tests", bundle_id + ".uitests" ] worker = (ROOT / "apps/push-relay/wrangler.jsonc").read_text() assert re.search(r'"APNS_TOPIC":\s*"([^"\n]+)"', worker)[1] == bundle_id From 14da0dad17e59823809deb5691f71fadb276d90e Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:45:09 +0000 Subject: [PATCH 22/40] ci(ios): retain serial Simulator renewal acceptance evidence --- .github/workflows/ci-ios.yml | 25 +++++- scripts/ios-renewal-ui-check.sh | 136 ++++++++++++++++++++++++++++++++ 2 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 scripts/ios-renewal-ui-check.sh diff --git a/.github/workflows/ci-ios.yml b/.github/workflows/ci-ios.yml index b20bbbf37..d33750de8 100644 --- a/.github/workflows/ci-ios.yml +++ b/.github/workflows/ci-ios.yml @@ -9,6 +9,9 @@ on: - 'tests/fixtures/push*-envelope-v1.json' - 'tests/check-push-secret-boundaries.py' - 'scripts/ios-install.sh' + - 'scripts/ios-renewal-ui-check.sh' + - 'tests/fixtures/ios-renewal-http.py' + - 'tests/check-ios-renewal-*.py' - 'crates/server/**' - 'apps/push-relay/**' - 'bun.lock' @@ -21,6 +24,9 @@ on: - 'tests/fixtures/push*-envelope-v1.json' - 'tests/check-push-secret-boundaries.py' - 'scripts/ios-install.sh' + - 'scripts/ios-renewal-ui-check.sh' + - 'tests/fixtures/ios-renewal-http.py' + - 'tests/check-ios-renewal-*.py' - 'crates/server/**' - 'apps/push-relay/**' - 'bun.lock' @@ -66,7 +72,6 @@ jobs: path: ${{ runner.temp }}/push-traces if-no-files-found: error retention-days: 1 - test: name: iOS Test needs: push-trace @@ -110,3 +115,21 @@ jobs: path: apps/ios/test.xcresult if-no-files-found: error retention-days: 1 + + - name: Validate native units and run renewal controls on installed Simulator + if: ${{ !cancelled() }} + timeout-minutes: 25 + env: + SERVERBEE_RENEWAL_EVIDENCE_DIR: ${{ runner.temp }}/serverbee-renewal-ui + RENEWAL_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + RENEWAL_PR_MERGE_SHA: ${{ github.event.pull_request.merge_commit_sha }} + run: bash ../../scripts/ios-renewal-ui-check.sh + + - name: Preserve renewal Simulator acceptance evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: ios-renewal-ui-${{ github.sha }} + path: ${{ runner.temp }}/serverbee-renewal-ui + if-no-files-found: error + retention-days: 7 diff --git a/scripts/ios-renewal-ui-check.sh b/scripts/ios-renewal-ui-check.sh new file mode 100644 index 000000000..08f1b026e --- /dev/null +++ b/scripts/ios-renewal-ui-check.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# Serial hosted Simulator acceptance after the existing ServerBee unit scheme. +set -euo pipefail + +RENEWAL_ROOT="$(git rev-parse --show-toplevel)" +RENEWAL_EVIDENCE_DIR="${SERVERBEE_RENEWAL_EVIDENCE_DIR:-${RUNNER_TEMP:-/tmp}/serverbee-renewal-ui}" +mkdir -p "$RENEWAL_EVIDENCE_DIR" +RENEWAL_FIXTURE_PID="" +cleanup() { + if [[ -n "$RENEWAL_FIXTURE_PID" ]]; then + kill "$RENEWAL_FIXTURE_PID" 2>/dev/null || true + wait "$RENEWAL_FIXTURE_PID" 2>/dev/null || true + fi +} +trap cleanup EXIT + +git -C "$RENEWAL_ROOT" rev-parse HEAD > "$RENEWAL_EVIDENCE_DIR/source-sha.txt" +git -C "$RENEWAL_ROOT" status --short > "$RENEWAL_EVIDENCE_DIR/source-status.txt" +python3 - "$RENEWAL_EVIDENCE_DIR" <<'PY' +import json, os, pathlib, platform +directory = pathlib.Path(__import__('sys').argv[1]) +keys = ['GITHUB_SHA', 'GITHUB_REF', 'GITHUB_EVENT_NAME', 'GITHUB_RUN_ID', + 'GITHUB_RUN_ATTEMPT', 'RENEWAL_PR_HEAD_SHA', 'RENEWAL_PR_MERGE_SHA'] +directory.joinpath('checkout-metadata.json').write_text(json.dumps({ + 'runner': platform.platform(), 'github': {key: os.environ.get(key) for key in keys}, + 'checkoutNote': 'push executes candidate head; pull_request executes the recorded merge ref', +}, indent=2) + '\n') +PY + +[[ "$(uname -s)" == Darwin ]] || { echo "Native Simulator acceptance requires macOS" >&2; exit 1; } +xcodebuild -version > "$RENEWAL_EVIDENCE_DIR/xcode-version.txt" +xcodegen --version > "$RENEWAL_EVIDENCE_DIR/xcodegen-version.txt" +xcodebuild -help > "$RENEWAL_EVIDENCE_DIR/xcodebuild-help.txt" 2>&1 +grep -q -- '-parallel-testing-enabled' "$RENEWAL_EVIDENCE_DIR/xcodebuild-help.txt" +grep -q -- '-resultBundlePath' "$RENEWAL_EVIDENCE_DIR/xcodebuild-help.txt" +xcrun xcresulttool help get test-results > "$RENEWAL_EVIDENCE_DIR/xcresulttool-help.txt" +xcrun xcresulttool help get test-results summary > "$RENEWAL_EVIDENCE_DIR/xcresulttool-summary-help.txt" +xcrun xcresulttool help get test-results tests > "$RENEWAL_EVIDENCE_DIR/xcresulttool-tests-help.txt" +xcrun xcresulttool help export attachments > "$RENEWAL_EVIDENCE_DIR/xcresulttool-attachments-help.txt" + +# Keep the original native unit suite independently nonzero, including all +# renewal model/request/view-model methods from this exact checkout. +RENEWAL_UNIT_RESULT="$RENEWAL_ROOT/apps/ios/test.xcresult" +test -d "$RENEWAL_UNIT_RESULT" +xcrun xcresulttool get test-results summary --path "$RENEWAL_UNIT_RESULT" > "$RENEWAL_EVIDENCE_DIR/unit-summary.json" +xcrun xcresulttool get test-results tests --path "$RENEWAL_UNIT_RESULT" > "$RENEWAL_EVIDENCE_DIR/unit-tests.json" +python3 "$RENEWAL_ROOT/tests/check-ios-renewal-results.py" --kind unit \ + --summary "$RENEWAL_EVIDENCE_DIR/unit-summary.json" --tests "$RENEWAL_EVIDENCE_DIR/unit-tests.json" \ + --renewal-source "$RENEWAL_ROOT/apps/ios/ServerBeeTests/RenewalDateTests.swift" \ + --output "$RENEWAL_EVIDENCE_DIR/unit-validated.json" + +xcrun simctl list devices available -j > "$RENEWAL_EVIDENCE_DIR/simulators.json" +xcrun simctl list runtimes -j > "$RENEWAL_EVIDENCE_DIR/runtimes.json" +python3 - "$RENEWAL_EVIDENCE_DIR" <<'PY' +import json, pathlib, sys +directory = pathlib.Path(sys.argv[1]) +devices = json.loads(directory.joinpath('simulators.json').read_text())['devices'] +runtimes = json.loads(directory.joinpath('runtimes.json').read_text())['runtimes'] +options = [] +for runtime in runtimes: + if not runtime.get('isAvailable') or not runtime['identifier'].startswith('com.apple.CoreSimulator.SimRuntime.iOS-'): + continue + version = tuple(int(part) for part in runtime['version'].split('.')) + if version < (17,): + continue + for device in devices.get(runtime['identifier'], []): + if device.get('isAvailable') and device['name'].startswith('iPhone'): + preferred = device['name'] == 'iPhone 16' and version == (18, 5) + options.append((preferred, version, device['name'], device, runtime)) +if not options: + raise SystemExit('No installed available iPhone Simulator with iOS >=17') +_, _, _, device, runtime = sorted(options, key=lambda entry: entry[:3], reverse=True)[0] +directory.joinpath('destination.json').write_text(json.dumps({'device': device, 'runtime': runtime}, indent=2) + '\n') +directory.joinpath('simulator-udid.txt').write_text(device['udid'] + '\n') +directory.joinpath('simulator-state.txt').write_text(device['state'] + '\n') +PY +RENEWAL_SIM_UDID="$(cat "$RENEWAL_EVIDENCE_DIR/simulator-udid.txt")" +if [[ "$(cat "$RENEWAL_EVIDENCE_DIR/simulator-state.txt")" != Booted ]]; then + xcrun simctl boot "$RENEWAL_SIM_UDID" +fi +python3 - "$RENEWAL_SIM_UDID" "$RENEWAL_EVIDENCE_DIR/simulator-boot.log" <<'PY' +import subprocess, sys +with open(sys.argv[2], 'w') as log: + subprocess.run(['xcrun', 'simctl', 'bootstatus', sys.argv[1], '-b'], stdout=log, + stderr=subprocess.STDOUT, timeout=180, check=True) +PY + +python3 "$RENEWAL_ROOT/tests/fixtures/ios-renewal-http.py" --evidence-dir "$RENEWAL_EVIDENCE_DIR" \ + > "$RENEWAL_EVIDENCE_DIR/fixture.log" 2>&1 & +RENEWAL_FIXTURE_PID=$! +python3 - "$RENEWAL_EVIDENCE_DIR" <<'PY' +import pathlib, sys, time, urllib.request +directory = pathlib.Path(sys.argv[1]) +for attempt in range(100): + try: + url = directory.joinpath('fixture-url.txt').read_text().strip() + with urllib.request.urlopen(url + '/__test/state', timeout=1) as response: + if response.status == 200: + break + except (OSError, ValueError): + time.sleep(0.1) +else: + raise SystemExit('Loopback renewal fixture did not become ready within 10 seconds') +PY +export TEST_RUNNER_SERVERBEE_RENEWAL_FIXTURE_URL="$(cat "$RENEWAL_EVIDENCE_DIR/fixture-url.txt")" +cd "$RENEWAL_ROOT/apps/ios" +# Regenerate with the installed XcodeGen after adding the new source bundle. +xcodegen generate > "$RENEWAL_EVIDENCE_DIR/xcodegen.log" 2>&1 +set +e +xcodebuild -project ServerBee.xcodeproj -scheme ServerBeeUI -configuration Debug \ + -destination "platform=iOS Simulator,id=$RENEWAL_SIM_UDID" \ + -parallel-testing-enabled NO -maximum-concurrent-test-simulator-destinations 1 \ + -resultBundlePath "$RENEWAL_EVIDENCE_DIR/RenewalUI.xcresult" \ + -skipPackagePluginValidation -only-testing:ServerBeeUITests/RenewalBillingUITests test \ + 2>&1 | tee "$RENEWAL_EVIDENCE_DIR/xcodebuild-ui.log" +RENEWAL_BUILD_STATUS=${PIPESTATUS[0]} +set -e +printf '%s\n' "$RENEWAL_BUILD_STATUS" > "$RENEWAL_EVIDENCE_DIR/xcodebuild-exit-status.txt" +if [[ -d "$RENEWAL_EVIDENCE_DIR/RenewalUI.xcresult" ]]; then + xcrun xcresulttool get test-results summary --path "$RENEWAL_EVIDENCE_DIR/RenewalUI.xcresult" > "$RENEWAL_EVIDENCE_DIR/ui-summary.json" + xcrun xcresulttool get test-results tests --path "$RENEWAL_EVIDENCE_DIR/RenewalUI.xcresult" > "$RENEWAL_EVIDENCE_DIR/ui-tests.json" + xcrun xcresulttool export attachments --path "$RENEWAL_EVIDENCE_DIR/RenewalUI.xcresult" \ + --output-path "$RENEWAL_EVIDENCE_DIR/screenshots" > "$RENEWAL_EVIDENCE_DIR/attachment-export.log" 2>&1 +fi +[[ "$RENEWAL_BUILD_STATUS" == 0 ]] || exit "$RENEWAL_BUILD_STATUS" +python3 "$RENEWAL_ROOT/tests/check-ios-renewal-results.py" --kind ui \ + --summary "$RENEWAL_EVIDENCE_DIR/ui-summary.json" --tests "$RENEWAL_EVIDENCE_DIR/ui-tests.json" \ + --fixture-state "$RENEWAL_EVIDENCE_DIR/fixture-state.json" \ + --output "$RENEWAL_EVIDENCE_DIR/ui-validated.json" +python3 - "$RENEWAL_EVIDENCE_DIR/screenshots" <<'PY' +import pathlib, sys +screenshots = list(pathlib.Path(sys.argv[1]).rglob('*.png')) +if len(screenshots) < 9: + raise SystemExit('Missing successful interaction screenshots (expected at least nine PNG attachments)') +print(f'Preserved {len(screenshots)} actual screenshot attachments') +PY From b7aa002a60b2a8d5b703544e7d9bf7bde73517c4 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:45:46 +0000 Subject: [PATCH 23/40] fix(ios): preserve websocket tags during catalog refresh --- .../ViewModels/ServersViewModel.swift | 4 ++++ .../ServersViewModelMergeTests.swift | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/apps/ios/ServerBee/ViewModels/ServersViewModel.swift b/apps/ios/ServerBee/ViewModels/ServersViewModel.swift index a99e04fd5..6ee7358b8 100644 --- a/apps/ios/ServerBee/ViewModels/ServersViewModel.swift +++ b/apps/ios/ServerBee/ViewModels/ServersViewModel.swift @@ -163,6 +163,10 @@ final class ServersViewModel { if let existing = byID[cfg.id] { var refreshed = cfg refreshed.mergeLiveMetrics(from: existing) + // These catalog fields are supplied by full sync/legacy payloads, + // and are absent from the authenticated ServerResponse DTO. + if cfg.tags == nil { refreshed.tags = existing.tags } + if cfg.groupName == nil { refreshed.groupName = existing.groupName } byID[cfg.id] = refreshed } else { byID[cfg.id] = cfg diff --git a/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift b/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift index 8f81aee70..cf4fa2d3c 100644 --- a/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift +++ b/apps/ios/ServerBeeTests/ViewModels/ServersViewModelMergeTests.swift @@ -7,6 +7,27 @@ import XCTest /// and capabilities vanish the instant the first WS frame arrived. @MainActor final class ServersViewModelMergeTests: XCTestCase { + func test_restRefreshPreservesWebSocketCatalogFields() throws { + let vm = ServersViewModel() + let fullSync = try JSONDecoder.snakeCase.decode(BrowserMessage.self, from: Data( + #"{"type":"full_sync","servers":[{"id":"1","name":"Original","online":true,"tags":["production"],"group_name":"Legacy group"}]}"#.utf8 + )) + vm.handleWSMessage(fullSync) + let rest = try JSONDecoder.snakeCase.decode([ServerStatus].self, from: Data( + #"[{"id":"1","name":"Renamed","ipv4":null,"group_id":null,"renewal":null,"expired_at":null}]"#.utf8 + )) + vm.applyConfig(rest) + XCTAssertEqual(vm.servers.first?.name, "Renamed") + XCTAssertEqual(vm.servers.first?.tags, ["production"]) + XCTAssertEqual(vm.servers.first?.groupName, "Legacy group") + XCTAssertEqual(vm.servers.first?.online, true) + XCTAssertNil(vm.servers.first?.groupId) + + // Explicit tag updates remain authoritative, including clearing all tags. + vm.applyConfig([ServerStatus(id: "1", name: "Renamed", tags: [])]) + XCTAssertEqual(vm.servers.first?.tags, []) + } + func test_catalogRefreshKeepsLiveStateAndAppliesEdits() { let vm = ServersViewModel() var original = config("1") From 4a9ee365fdb705577fdf892c3e9557e1068091f8 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:46:05 +0000 Subject: [PATCH 24/40] fix(ios): reject numeric fixture renewal switch intent --- tests/check-ios-renewal-harness.py | 4 ++++ tests/check-ios-renewal-results.py | 2 ++ tests/fixtures/ios-renewal-http.py | 2 ++ 3 files changed, 8 insertions(+) diff --git a/tests/check-ios-renewal-harness.py b/tests/check-ios-renewal-harness.py index d51d56eec..2d5b66d48 100644 --- a/tests/check-ios-renewal-harness.py +++ b/tests/check-ios-renewal-harness.py @@ -111,6 +111,10 @@ def test_dual_legacy_and_local_date_is_rejected(self): "expired_at": "2026-02-15T00:00:00Z"}) self.assertEqual(status, 422) + def test_numeric_switch_value_cannot_stand_in_for_boolean_intent(self): + self.reset("switch") + self.assertEqual(self.save({"enabled": 1})[0], 422) + def test_unknown_read_and_notification_write_fail_without_capturing_sensitive_body(self): self.assertEqual(self.request("/api/not-a-route")[0], 422) self.assertEqual(self.request("/api/mobile/push/encrypted-register", "POST", {"content_key": "must-not-capture"})[0], 422) diff --git a/tests/check-ios-renewal-results.py b/tests/check-ios-renewal-results.py index 0307d5f2c..26f54a51b 100644 --- a/tests/check-ios-renewal-results.py +++ b/tests/check-ios-renewal-results.py @@ -99,6 +99,8 @@ def validate_fixture(state): "name-only save introduced renewal intent") else: require(body.get("renewal") == renewal, "captured renewal intent differs") + if "enabled" in renewal: + require(type(body["renewal"]["enabled"]) is bool, "enabled intent must be a JSON boolean") return {"scenarios": sorted(completed), "saveCount": 5, "errors": []} diff --git a/tests/fixtures/ios-renewal-http.py b/tests/fixtures/ios-renewal-http.py index 95b9e71c0..f73ae9091 100644 --- a/tests/fixtures/ios-renewal-http.py +++ b/tests/fixtures/ios-renewal-http.py @@ -114,6 +114,8 @@ def save(self, body): return self.fail("name-only save must omit renewal") elif body.get("renewal") != expected: return self.fail("renewal intent differs from the scenario contract") + if expected and "enabled" in expected and type(body["renewal"]["enabled"]) is not bool: + return self.fail("enabled intent must be a JSON boolean") if body.get("billing_cycle") != "monthly": return self.fail("billing cycle must remain monthly") allowed = {"name", "weight", "hidden", "remark", "public_remark", "group_id", From f58dedeadb38b38d796fe06a022783c208d5f29f Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:46:15 +0000 Subject: [PATCH 25/40] feat(web): refresh renewal catalog and occurrence advisories --- .../dashboard/widgets/alert-list.tsx | 16 +- .../components/server/server-edit-dialog.tsx | 2 + .../src/hooks/use-servers-ws-renewal.test.tsx | 266 ++++++++++++++++++ apps/web/src/hooks/use-servers-ws.ts | 10 + apps/web/src/lib/server-catalog.ts | 26 +- apps/web/src/lib/server-cost-cache.ts | 13 + apps/web/src/locales/en/dashboard.json | 5 + apps/web/src/locales/en/settings.json | 1 + apps/web/src/locales/zh/dashboard.json | 5 + apps/web/src/locales/zh/settings.json | 1 + .../settings/alert-rules-list.test.tsx | 77 +++++ .../_authed/settings/alert-rules-list.tsx | 43 ++- 12 files changed, 444 insertions(+), 21 deletions(-) create mode 100644 apps/web/src/hooks/use-servers-ws-renewal.test.tsx create mode 100644 apps/web/src/lib/server-cost-cache.ts create mode 100644 apps/web/src/routes/_authed/settings/alert-rules-list.test.tsx diff --git a/apps/web/src/components/dashboard/widgets/alert-list.tsx b/apps/web/src/components/dashboard/widgets/alert-list.tsx index cb2ab0db0..582dfcef4 100644 --- a/apps/web/src/components/dashboard/widgets/alert-list.tsx +++ b/apps/web/src/components/dashboard/widgets/alert-list.tsx @@ -14,6 +14,7 @@ interface AlertListWidgetProps { } interface AlertEvent { + alert_key?: string count: number event_at: string resolved_at: string | null @@ -67,14 +68,25 @@ export function AlertListWidget({ config, servers }: AlertListWidgetProps) { {filtered.map((event) => { const isFiring = event.status === 'firing' + const isResolved = event.status === 'resolved' + const statusLabel = t(`widgets.alertList.status.${event.status}`, { defaultValue: event.status }) + let statusColor = 'bg-muted-foreground' + if (isFiring) { + statusColor = 'bg-red-500' + } else if (isResolved) { + statusColor = 'bg-green-500' + } const serverName = serverNameMap.get(event.server_id) ?? event.server_name return (
{event.rule_name} diff --git a/apps/web/src/components/server/server-edit-dialog.tsx b/apps/web/src/components/server/server-edit-dialog.tsx index 3d0957c43..a4b25b909 100644 --- a/apps/web/src/components/server/server-edit-dialog.tsx +++ b/apps/web/src/components/server/server-edit-dialog.tsx @@ -26,6 +26,7 @@ import { api } from '@/lib/api-client' import type { ServerGroup, ServerResponse, UpdateServerInput } from '@/lib/api-schema' import { buildCountryOptions, type CountryOption } from '@/lib/country-codes' import { projectServerCatalog } from '@/lib/server-catalog' +import { invalidateServerCosts } from '@/lib/server-cost-cache' import { cn, countryCodeToFlag } from '@/lib/utils' const TAG_SPLIT_RE = /[\s,]+/ @@ -463,6 +464,7 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser mutationFn: (payload: UpdateServerInput) => api.put(`/api/servers/${server.id}`, payload), onSuccess: (data) => { projectServerCatalog(queryClient, { kind: 'server_saved', server: data }) + invalidateServerCosts(queryClient, [data.id]) } }) diff --git a/apps/web/src/hooks/use-servers-ws-renewal.test.tsx b/apps/web/src/hooks/use-servers-ws-renewal.test.tsx new file mode 100644 index 000000000..3bc9ae8a8 --- /dev/null +++ b/apps/web/src/hooks/use-servers-ws-renewal.test.tsx @@ -0,0 +1,266 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react' +import type { ReactNode } from 'react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { AlertListWidget } from '@/components/dashboard/widgets/alert-list' +import { ServerEditDialog } from '@/components/server/server-edit-dialog' +import type { CostOverviewResponse, ServerCostInsights, ServerResponse } from '@/lib/api-schema' +import { useLiveServers, useServerDetail, useServerList } from '@/lib/server-catalog' +import { useCostInsights, useCostOverview } from './use-cost' +import { useServersWs } from './use-servers-ws' + +// Stub the network boundary; the hook, WsClient, catalog and cost hooks remain real. +class BrowserSocket { + static instances: BrowserSocket[] = [] + readonly url: string + onmessage: ((event: MessageEvent) => void) | null = null + close() { + this.onmessage = null + } + constructor(url: string) { + this.url = url + BrowserSocket.instances.push(this) + } + receive(message: unknown) { + this.onmessage?.(new MessageEvent('message', { data: JSON.stringify(message) })) + } +} + +const server: ServerResponse = { + agent_authority: { outstanding_offer: null, status: 'unclaimed' }, + capabilities: 0, + created_at: '2026-01-01T00:00:00Z', + expired_at: '2026-01-31T23:59:59Z', + features: [], + geo_manual: false, + has_token: false, + hidden: false, + id: 'srv-1', + name: 'Offline monthly server', + protocol_version: 2, + updated_at: '2026-01-01T00:00:00Z', + weight: 0 +} + +function setup() { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Number.POSITIVE_INFINITY } } + }) + let currentServer = server + let expired = true + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input, options) => { + const path = String(input) + let data: ServerResponse | ServerResponse[] | CostOverviewResponse | ServerCostInsights + if (path === '/api/servers/srv-1' && options?.method === 'PUT') { + currentServer = { ...server, expired_at: '2026-03-31T23:59:59Z' } + expired = false + data = currentServer + } else if (path === '/api/server-groups' || path === '/api/servers/srv-1/tags') { + data = [] + } else if (path === '/api/alert-events?limit=10') { + return Promise.resolve( + Response.json({ + data: [ + { + rule_id: 'rule-1', + rule_name: expired ? 'Prior occurrence' : 'Superseded occurrence', + server_id: 'srv-1', + server_name: server.name, + status: expired ? 'firing' : 'superseded', + event_at: '2026-01-31T00:00:00Z', + resolved_at: null, + count: 1 + } + ] + }) + ) + } else if (path === '/api/servers') { + data = [currentServer] + } else if (path === '/api/servers/srv-1') { + data = currentServer + } else if (path === '/api/cost/overview') { + data = { + currencies: [], + servers: [ + { server_id: 'srv-1', name: server.name, configured: true, advisories: expired ? ['expired_billing'] : [] } + ] + } + } else if (path.endsWith('/cost-insights')) { + data = { + server_id: path.split('/')[3], + configured: true, + advisories: expired ? ['expired_billing'] : [] + } + } else { + throw new Error(`Unexpected request: ${path}`) + } + return Promise.resolve(Response.json({ data })) + }) + vi.stubGlobal('WebSocket', BrowserSocket) + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ) + return { + queryClient, + fetchSpy, + wrapper, + advance() { + currentServer = { ...server, expired_at: '2026-02-28T23:59:59Z' } + expired = false + }, + receive(message: unknown) { + act(() => BrowserSocket.instances[0].receive(message)) + } + } +} + +afterEach(() => { + cleanup() + BrowserSocket.instances = [] + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('renewal catalog refresh through the browser WebSocket', () => { + it('refreshes current detail, list, dashboard and cost advisories after an affected catalog change', async () => { + const fixture = setup() + const { result } = renderHook( + () => { + useServersWs() + return { + list: useServerList(), + detail: useServerDetail('srv-1'), + dashboard: useLiveServers(), + overview: useCostOverview(), + insights: useCostInsights('srv-1'), + unrelated: useCostInsights('srv-2') + } + }, + { wrapper: fixture.wrapper } + ) + await waitFor(() => expect(result.current.insights.data?.advisories).toEqual(['expired_billing'])) + await waitFor(() => expect(result.current.detail.data?.expired_at).toBe('2026-01-31T23:59:59Z')) + await waitFor(() => expect(result.current.unrelated.data?.advisories).toEqual(['expired_billing'])) + + fixture.advance() + fixture.receive({ type: 'server_catalog_changed', server_ids: ['srv-1'] }) + + await waitFor(() => expect(result.current.detail.data?.expired_at).toBe('2026-02-28T23:59:59Z')) + await waitFor(() => expect(result.current.list.data?.[0].expired_at).toBe('2026-02-28T23:59:59Z')) + await waitFor(() => expect(result.current.overview.data?.servers[0].advisories).toEqual([])) + await waitFor(() => expect(result.current.insights.data?.advisories).toEqual([])) + expect(result.current.dashboard.data?.[0].name).toBe(server.name) + expect(result.current.dashboard.data?.[0]).not.toHaveProperty('expired_at') + expect(result.current.dashboard.data?.[0]).not.toHaveProperty('renewal') + expect(result.current.unrelated.data?.advisories).toEqual(['expired_billing']) + expect(fixture.fetchSpy.mock.calls.filter(([path]) => path === '/api/servers/srv-2/cost-insights')).toHaveLength(1) + }) + + it('refreshes REST deadlines and every cached cost advisory on a full sync after a missed catalog event', async () => { + const fixture = setup() + const { result } = renderHook( + () => { + useServersWs() + return { + list: useServerList(), + detail: useServerDetail('srv-1'), + overview: useCostOverview(), + insights: useCostInsights('srv-1'), + otherInsights: useCostInsights('srv-2') + } + }, + { wrapper: fixture.wrapper } + ) + await waitFor(() => expect(result.current.detail.data?.expired_at).toBe('2026-01-31T23:59:59Z')) + await waitFor(() => expect(result.current.otherInsights.data?.advisories).toEqual(['expired_billing'])) + + fixture.advance() + fixture.receive({ type: 'full_sync', servers: fixture.queryClient.getQueryData(['server-catalog', 'live']) }) + + await waitFor(() => expect(result.current.detail.data?.expired_at).toBe('2026-02-28T23:59:59Z')) + await waitFor(() => expect(result.current.overview.data?.servers[0].advisories).toEqual([])) + await waitFor(() => expect(result.current.insights.data?.advisories).toEqual([])) + await waitFor(() => expect(result.current.otherInsights.data?.advisories).toEqual([])) + expect(fixture.fetchSpy).toHaveBeenCalledWith('/api/servers', expect.any(Object)) + }) + + it('refreshes independently cached cost advisories after saving a manual date through the billing editor', async () => { + const fixture = setup() + Element.prototype.getAnimations = () => [] + const { result } = renderHook(() => ({ overview: useCostOverview(), insights: useCostInsights('srv-1') }), { + wrapper: fixture.wrapper + }) + await waitFor(() => expect(result.current.insights.data?.advisories).toEqual(['expired_billing'])) + await waitFor(() => expect(result.current.overview.data?.servers[0].advisories).toEqual(['expired_billing'])) + render(, { wrapper: fixture.wrapper }) + fireEvent.change(screen.getByLabelText('Expiration date'), { target: { value: '2026-03-31' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => + expect(fixture.fetchSpy).toHaveBeenCalledWith( + '/api/servers/srv-1', + expect.objectContaining({ + method: 'PUT', + body: expect.stringContaining('"expiry_date":"2026-03-31"') + }) + ) + ) + await waitFor(() => expect(result.current.overview.data?.servers[0].advisories).toEqual([])) + await waitFor(() => expect(result.current.insights.data?.advisories).toEqual([])) + }) + + it('refreshes dashboard alert occurrences when advancement supersedes the old target', async () => { + const fixture = setup() + renderHook(() => useServersWs(), { wrapper: fixture.wrapper }) + render(, { wrapper: fixture.wrapper }) + expect(await screen.findByText('Prior occurrence')).toBeInTheDocument() + + fixture.advance() + fixture.receive({ type: 'server_catalog_changed', server_ids: ['srv-1'] }) + + expect(await screen.findByText('Superseded occurrence')).toBeInTheDocument() + }) + + it('describes a superseded renewal occurrence without showing recovery', async () => { + const fixture = setup() + fixture.advance() + render(, { wrapper: fixture.wrapper }) + + expect(await screen.findByLabelText('Superseded by the next renewal deadline')).toBeInTheDocument() + expect(screen.queryByLabelText('Resolved')).not.toBeInTheDocument() + }) + + it('refreshes cost views opened after a reconnect even while their cached results were inactive and fresh', async () => { + const fixture = setup() + renderHook( + () => { + useServersWs() + return useServerList() + }, + { wrapper: fixture.wrapper } + ) + const costs = renderHook(() => ({ overview: useCostOverview(), insights: useCostInsights('srv-2') }), { + wrapper: fixture.wrapper + }) + await waitFor(() => expect(costs.result.current.insights.data?.advisories).toEqual(['expired_billing'])) + await waitFor(() => expect(costs.result.current.overview.data?.servers[0].advisories).toEqual(['expired_billing'])) + costs.unmount() + + fixture.advance() + fixture.receive({ type: 'full_sync', servers: fixture.queryClient.getQueryData(['server-catalog', 'live']) }) + const reopened = renderHook(() => ({ overview: useCostOverview(), insights: useCostInsights('srv-2') }), { + wrapper: fixture.wrapper + }) + + await waitFor(() => expect(reopened.result.current.insights.data?.advisories).toEqual([])) + await waitFor(() => expect(reopened.result.current.overview.data?.servers[0].advisories).toEqual([])) + }) + + it.each([null, 'srv-1', [], ['srv-1', null], [1], ['']])('ignores malformed catalog identifiers %j', (serverIds) => { + const fixture = setup() + renderHook(() => useServersWs(), { wrapper: fixture.wrapper }) + fixture.receive({ type: 'server_catalog_changed', server_ids: serverIds }) + + expect(fixture.fetchSpy).not.toHaveBeenCalled() + }) +}) diff --git a/apps/web/src/hooks/use-servers-ws.ts b/apps/web/src/hooks/use-servers-ws.ts index dedcdaea0..3682dc662 100644 --- a/apps/web/src/hooks/use-servers-ws.ts +++ b/apps/web/src/hooks/use-servers-ws.ts @@ -21,6 +21,7 @@ const MAX_SECURITY_EVENTS_IN_CACHE = 200 type WsMessage = | { type: 'full_sync'; servers: ServerMetrics[]; upgrades?: UpgradeJob[] } | { type: 'update'; servers: LiveMetrics[] } + | { type: 'server_catalog_changed'; server_ids: string[] } | { type: 'server_online'; server_id: string } | { type: 'server_offline'; server_id: string } | { @@ -402,6 +403,15 @@ export function handleWsMessage(raw: unknown, queryClient: QueryClient): void { return } switch (raw.type) { + case 'server_catalog_changed': + if ( + Array.isArray(raw.server_ids) && + raw.server_ids.length > 0 && + raw.server_ids.every((id) => typeof id === 'string' && id.length > 0) + ) { + projectServerCatalog(queryClient, { kind: 'catalog_changed', serverIds: raw.server_ids }) + } + break case 'traceroute_update': dispatchToSubscribers('traceroute_update', raw) break diff --git a/apps/web/src/lib/server-catalog.ts b/apps/web/src/lib/server-catalog.ts index 4ff01f93a..7fb93dfc4 100644 --- a/apps/web/src/lib/server-catalog.ts +++ b/apps/web/src/lib/server-catalog.ts @@ -1,6 +1,7 @@ import { type QueryClient, useQuery, useQueryClient } from '@tanstack/react-query' import { api } from '@/lib/api-client' import type { AgentAuthorityStateSummary, OutstandingEnrollmentSummary, ServerResponse } from '@/lib/api-schema' +import { invalidateServerCosts } from '@/lib/server-cost-cache' const LIVE_SERVERS_KEY = ['server-catalog', 'live'] as const const SERVER_LIST_KEY = ['server-catalog', 'list'] as const @@ -71,6 +72,7 @@ export type ServerCatalogEvent = | { kind: 'rest_snapshot'; servers: ServerResponse[] } | { kind: 'servers_removed'; serverIds: readonly string[] } | { kind: 'server_saved'; server: ServerResponse } + | { kind: 'catalog_changed'; serverIds: readonly string[] } | { authority: AgentAuthorityStateSummary; kind: 'agent_authority_changed'; serverId: string } | { kind: 'tags_changed'; serverId: string; tags: string[] } | { kind: 'ws_full_sync'; servers: ServerMetrics[] } @@ -326,9 +328,22 @@ function ensureLiveProjectionLifetime(queryClient: QueryClient): void { }) } +function invalidateAlertOccurrences(queryClient: QueryClient): void { + queryClient.invalidateQueries({ queryKey: ['alert-events'] }).catch(() => undefined) + queryClient.invalidateQueries({ queryKey: ['alert-rule-states'] }).catch(() => undefined) +} + export function projectServerCatalog(queryClient: QueryClient, event: ServerCatalogEvent): void { ensureLiveProjectionLifetime(queryClient) switch (event.kind) { + case 'catalog_changed': { + // Billing metadata is REST-owned. Fetch even when only the live dashboard + // is mounted, so static catalog data does not depend on an active list query. + refreshServerCatalog(queryClient).catch(() => undefined) + invalidateServerCosts(queryClient, event.serverIds) + invalidateAlertOccurrences(queryClient) + return + } case 'rest_snapshot': { const serverIds = new Set(event.servers.map((server) => server.id)) queryClient.setQueryData(LIVE_SERVERS_KEY, (current) => @@ -401,9 +416,6 @@ export function projectServerCatalog(queryClient: QueryClient, event: ServerCata case 'ws_full_sync': { const serverIds = new Set(event.servers.map((server) => server.id)) const fullSyncById = new Map(event.servers.map((server) => [server.id, server])) - const currentList = queryClient.getQueryData(SERVER_LIST_KEY) - const hasUnlistedServer = - currentList !== undefined && event.servers.some((server) => !currentList.some((row) => row.id === server.id)) queryClient.setQueryData(LIVE_SERVERS_KEY, (current) => mergeWsFullSync(current, event.servers)) queryClient.setQueryData(SERVER_LIST_KEY, (current) => current @@ -417,9 +429,11 @@ export function projectServerCatalog(queryClient: QueryClient, event: ServerCata for (const server of event.servers) { updateExistingDetail(queryClient, server.id, (current) => projectFullSyncServerToRest(current, server)) } - if (hasUnlistedServer) { - queryClient.invalidateQueries({ exact: true, queryKey: SERVER_LIST_KEY }).catch(() => undefined) - } + // Full sync omits private billing fields. Recover catalog changes missed + // while disconnected and the separately cached cost expiry advisories. + refreshServerCatalog(queryClient).catch(() => undefined) + invalidateServerCosts(queryClient) + invalidateAlertOccurrences(queryClient) return } case 'ws_update': { diff --git a/apps/web/src/lib/server-cost-cache.ts b/apps/web/src/lib/server-cost-cache.ts new file mode 100644 index 000000000..00049ba0b --- /dev/null +++ b/apps/web/src/lib/server-cost-cache.ts @@ -0,0 +1,13 @@ +import type { QueryClient } from '@tanstack/react-query' + +export function invalidateServerCosts(queryClient: QueryClient, serverIds?: readonly string[]): void { + queryClient.invalidateQueries({ queryKey: ['cost', 'overview'] }).catch(() => undefined) + queryClient + .invalidateQueries({ + predicate: ({ queryKey }) => + queryKey[0] === 'servers' && + queryKey[2] === 'cost-insights' && + (serverIds === undefined || serverIds.includes(queryKey[1] as string)) + }) + .catch(() => undefined) +} diff --git a/apps/web/src/locales/en/dashboard.json b/apps/web/src/locales/en/dashboard.json index 1107eb457..6803d81ff 100644 --- a/apps/web/src/locales/en/dashboard.json +++ b/apps/web/src/locales/en/dashboard.json @@ -140,6 +140,11 @@ }, "alertList": { "title": "Alerts", + "status": { + "firing": "Triggered", + "resolved": "Resolved", + "superseded": "Superseded by the next renewal deadline" + }, "empty": { "noEvents": "No alert events" } diff --git a/apps/web/src/locales/en/settings.json b/apps/web/src/locales/en/settings.json index 37e0b6d1f..76713d21a 100644 --- a/apps/web/src/locales/en/settings.json +++ b/apps/web/src/locales/en/settings.json @@ -149,6 +149,7 @@ "alerts.no_rules": "No alert rules configured", "alerts.states": "States", "alerts.resolved": "Resolved", + "alerts.superseded": "Superseded by the next renewal deadline", "alerts.triggered": "Triggered", "alerts.no_triggered": "No triggered states", "alerts.metric_cpu": "CPU %", diff --git a/apps/web/src/locales/zh/dashboard.json b/apps/web/src/locales/zh/dashboard.json index cd40b5a64..2c2906e59 100644 --- a/apps/web/src/locales/zh/dashboard.json +++ b/apps/web/src/locales/zh/dashboard.json @@ -139,6 +139,11 @@ } }, "alertList": { + "status": { + "firing": "已触发", + "resolved": "已恢复", + "superseded": "已由下一个续费到期日替代" + }, "title": "告警", "empty": { "noEvents": "暂无告警事件" diff --git a/apps/web/src/locales/zh/settings.json b/apps/web/src/locales/zh/settings.json index e215048b0..6a8113e5b 100644 --- a/apps/web/src/locales/zh/settings.json +++ b/apps/web/src/locales/zh/settings.json @@ -149,6 +149,7 @@ "alerts.no_rules": "暂无告警规则", "alerts.states": "状态", "alerts.resolved": "已恢复", + "alerts.superseded": "已由下一个续费到期日替代", "alerts.triggered": "已触发", "alerts.no_triggered": "暂无触发状态", "alerts.metric_cpu": "CPU %", diff --git a/apps/web/src/routes/_authed/settings/alert-rules-list.test.tsx b/apps/web/src/routes/_authed/settings/alert-rules-list.test.tsx new file mode 100644 index 000000000..b5840417a --- /dev/null +++ b/apps/web/src/routes/_authed/settings/alert-rules-list.test.tsx @@ -0,0 +1,77 @@ +import { cleanup, render, screen } from '@testing-library/react' +import i18next from 'i18next' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AlertRule, AlertStateResponse } from '@/lib/api-schema' +import { AlertRulesList } from './alert-rules-list' + +const SUPERSEDED_LABEL = /Superseded by the next renewal deadline/ +const RESOLVED_LABEL = /Resolved/ +const TRIGGERED_LABEL = /Triggered \(1x\)/ +const CHINESE_SUPERSEDED_LABEL = /已由下一个续费到期日替代/ + +const rule: AlertRule = { + id: 'renewal-rule', + name: 'Renewal reminder', + enabled: true, + rules_json: '[]', + cover_type: 'all', + trigger_mode: 'once', + created_at: '2026-01-01T00:00:00Z', + updated_at: '2026-01-01T00:00:00Z' +} + +function renderState(state: AlertStateResponse & { status?: string }) { + render( + + ) +} + +const state: AlertStateResponse = { + server_id: 'server-1', + server_name: 'Monthly server', + count: 1, + resolved: true, + resolved_at: null, + first_triggered_at: '2026-01-31T00:00:00Z', + last_notified_at: '2026-01-31T00:00:00Z' +} + +afterEach(async () => { + cleanup() + await i18next.changeLanguage('en') +}) + +describe('renewal alert state presentation', () => { + it('shows a superseded occurrence as a neutral deadline transition', () => { + renderState({ ...state, status: 'superseded' }) + + expect(screen.getByText(SUPERSEDED_LABEL)).toBeInTheDocument() + expect(screen.queryByText(RESOLVED_LABEL)).not.toBeInTheDocument() + }) + + it('preserves firing and resolved labels from older Server responses', () => { + renderState(state) + expect(screen.getByText(RESOLVED_LABEL)).toBeInTheDocument() + cleanup() + renderState({ ...state, resolved: false }) + expect(screen.getByText(TRIGGERED_LABEL)).toBeInTheDocument() + }) + + it('localizes the superseded occurrence in Chinese', async () => { + await i18next.changeLanguage('zh') + renderState({ ...state, status: 'superseded' }) + expect(screen.getByText(CHINESE_SUPERSEDED_LABEL)).toBeInTheDocument() + }) +}) diff --git a/apps/web/src/routes/_authed/settings/alert-rules-list.tsx b/apps/web/src/routes/_authed/settings/alert-rules-list.tsx index 3dcdefb17..b4e4746b9 100644 --- a/apps/web/src/routes/_authed/settings/alert-rules-list.tsx +++ b/apps/web/src/routes/_authed/settings/alert-rules-list.tsx @@ -197,19 +197,36 @@ function AlertRuleStates({ states }: { states: AlertStateResponse[] | undefined
{states && states.length > 0 ? (
- {states.map((state) => ( -
- - - {state.server_name} - - - {state.resolved ? t('alerts.resolved') : `${t('alerts.triggered')} (${state.count}x)`} - {' · '} - {formatDateTime(state.first_triggered_at)} - -
- ))} + {states.map((state) => { + // Older Servers only provide the resolved flag. + const status = + (state as AlertStateResponse & { status?: string }).status ?? (state.resolved ? 'resolved' : 'firing') + let statusColor = 'bg-muted-foreground' + let statusText = t('alerts.superseded') + if (status === 'firing') { + statusColor = 'bg-red-500' + statusText = `${t('alerts.triggered')} (${state.count}x)` + } else if (status === 'resolved') { + statusColor = 'bg-green-500' + statusText = t('alerts.resolved') + } + return ( +
+ + + {state.server_name} + + + {statusText} + {' · '} + {formatDateTime(state.first_triggered_at)} + +
+ ) + })}
) : (

{t('alerts.no_triggered')}

From b82e91ffa6c2da9610fbb81d8c33c1e5479f0ac2 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:47:42 +0000 Subject: [PATCH 26/40] fix(ci): select Xcode-supported renewal Simulator destinations --- scripts/ios-renewal-ui-check.sh | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/scripts/ios-renewal-ui-check.sh b/scripts/ios-renewal-ui-check.sh index 08f1b026e..feabf687a 100644 --- a/scripts/ios-renewal-ui-check.sh +++ b/scripts/ios-renewal-ui-check.sh @@ -49,6 +49,11 @@ python3 "$RENEWAL_ROOT/tests/check-ios-renewal-results.py" --kind unit \ --renewal-source "$RENEWAL_ROOT/apps/ios/ServerBeeTests/RenewalDateTests.swift" \ --output "$RENEWAL_EVIDENCE_DIR/unit-validated.json" +cd "$RENEWAL_ROOT/apps/ios" +# Regenerate with the installed XcodeGen after adding the new source bundle. +xcodegen generate > "$RENEWAL_EVIDENCE_DIR/xcodegen.log" 2>&1 +xcodebuild -showdestinations -project ServerBee.xcodeproj -scheme ServerBeeUI \ + -skipPackagePluginValidation > "$RENEWAL_EVIDENCE_DIR/xcode-destinations.txt" 2>&1 xcrun simctl list devices available -j > "$RENEWAL_EVIDENCE_DIR/simulators.json" xcrun simctl list runtimes -j > "$RENEWAL_EVIDENCE_DIR/runtimes.json" python3 - "$RENEWAL_EVIDENCE_DIR" <<'PY' @@ -56,6 +61,7 @@ import json, pathlib, sys directory = pathlib.Path(sys.argv[1]) devices = json.loads(directory.joinpath('simulators.json').read_text())['devices'] runtimes = json.loads(directory.joinpath('runtimes.json').read_text())['runtimes'] +destinations = directory.joinpath('xcode-destinations.txt').read_text().splitlines() options = [] for runtime in runtimes: if not runtime.get('isAvailable') or not runtime['identifier'].startswith('com.apple.CoreSimulator.SimRuntime.iOS-'): @@ -64,11 +70,13 @@ for runtime in runtimes: if version < (17,): continue for device in devices.get(runtime['identifier'], []): - if device.get('isAvailable') and device['name'].startswith('iPhone'): + compatible = any(device['udid'] in line and 'platform:iOS Simulator' in line + and 'error:' not in line for line in destinations) + if device.get('isAvailable') and device['name'].startswith('iPhone') and compatible: preferred = device['name'] == 'iPhone 16' and version == (18, 5) options.append((preferred, version, device['name'], device, runtime)) if not options: - raise SystemExit('No installed available iPhone Simulator with iOS >=17') + raise SystemExit('No installed iPhone Simulator with iOS >=17 supported by the selected Xcode scheme') _, _, _, device, runtime = sorted(options, key=lambda entry: entry[:3], reverse=True)[0] directory.joinpath('destination.json').write_text(json.dumps({'device': device, 'runtime': runtime}, indent=2) + '\n') directory.joinpath('simulator-udid.txt').write_text(device['udid'] + '\n') @@ -103,9 +111,6 @@ else: raise SystemExit('Loopback renewal fixture did not become ready within 10 seconds') PY export TEST_RUNNER_SERVERBEE_RENEWAL_FIXTURE_URL="$(cat "$RENEWAL_EVIDENCE_DIR/fixture-url.txt")" -cd "$RENEWAL_ROOT/apps/ios" -# Regenerate with the installed XcodeGen after adding the new source bundle. -xcodegen generate > "$RENEWAL_EVIDENCE_DIR/xcodegen.log" 2>&1 set +e xcodebuild -project ServerBee.xcodeproj -scheme ServerBeeUI -configuration Debug \ -destination "platform=iOS Simulator,id=$RENEWAL_SIM_UDID" \ From 4739b2a64df6bfc9df1a2e59b04f3f6a4da85b0a Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:48:23 +0000 Subject: [PATCH 27/40] test(renewal): cover billing edit intent and persistent anchors --- .github/workflows/ci.yml | 1 + .../ios/ServerBeeTests/RenewalDateTests.swift | 72 +++ .../server/server-edit-renewal.test.tsx | 48 ++ crates/server/tests/renewal_edits.rs | 520 ++++++++++++++++++ 4 files changed, 641 insertions(+) create mode 100644 crates/server/tests/renewal_edits.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 260521b2b..36b154bbe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -237,6 +237,7 @@ jobs: --test router_probes_extra --test router_security_rate --test renewal_dates + --test renewal_edits --test renewal_projection --test router_server_crud --test router_server_extra diff --git a/apps/ios/ServerBeeTests/RenewalDateTests.swift b/apps/ios/ServerBeeTests/RenewalDateTests.swift index 6b471f3a5..0bcaac576 100644 --- a/apps/ios/ServerBeeTests/RenewalDateTests.swift +++ b/apps/ios/ServerBeeTests/RenewalDateTests.swift @@ -244,3 +244,75 @@ final class RenewalDateTests: XCTestCase { """.utf8)) } } + +extension RenewalDateTests { + @MainActor + func test_intervalOnlyEditOfClampedProjectionDoesNotSendConfirmation() throws { + var config = try selectedConfig() + config.renewal = ServerRenewal( + enabled: true, billingTimezone: "America/Los_Angeles", expiryDate: "2026-02-28", + confirmedExpiredAt: "2026-02-01T07:59:59Z", deadlineOrigin: "projected", occurrenceId: "february" + ) + let model = EditServerViewModel() + model.prefill(from: config) + model.billingCycle = "quarterly" + let request = try object(model.buildRequest()) + XCTAssertEqual(request["billing_cycle"] as? String, "quarterly") + XCTAssertNil(request["renewal"]) + XCTAssertNil(request["expired_at"]) + } + + @MainActor + func test_restoringClampedDateAndTimezoneLeavesOnlyUnrelatedEditIntent() throws { + var config = try selectedConfig() + config.renewal = ServerRenewal( + enabled: true, billingTimezone: "America/Los_Angeles", expiryDate: "2026-02-28", + confirmedExpiredAt: "2026-02-01T07:59:59Z", deadlineOrigin: "projected", occurrenceId: "february" + ) + let model = EditServerViewModel() + model.prefill(from: config) + model.expiryDate = try XCTUnwrap(BillingDate.date(from: "2026-03-01", timezone: model.billingTimezone)) + model.expiryDate = try XCTUnwrap(BillingDate.date(from: "2026-02-28", timezone: model.billingTimezone)) + model.billingTimezone = "Asia/Tokyo" + model.billingTimezone = "America/Los_Angeles" + model.priceText = "15" + let request = try object(model.buildRequest()) + XCTAssertEqual(request["price"] as? Double, 15) + XCTAssertNil(request["renewal"]) + XCTAssertNil(request["expired_at"]) + } + + @MainActor + func test_dateCorrectionAndTimezoneEditEncodeBothChangedFields() throws { + let model = EditServerViewModel() + model.prefill(from: try selectedConfig()) + model.billingTimezone = "Asia/Tokyo" + model.expiryDate = try XCTUnwrap(BillingDate.date(from: "2028-02-29", timezone: model.billingTimezone)) + let request = try object(model.buildRequest()) + let renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["expiry_date"] as? String, "2028-02-29") + XCTAssertEqual(renewal["billing_timezone"] as? String, "Asia/Tokyo") + XCTAssertNil(renewal["enabled"]) + XCTAssertNil(request["expired_at"]) + } + + @MainActor + func test_frozenDeadlineRemainsUnconfirmedOnSaveAndUsesExistingDateCorrection() throws { + var config = try selectedConfig() + config.renewal = ServerRenewal( + enabled: false, billingTimezone: "America/Los_Angeles", expiryDate: "2026-02-28", + confirmedExpiredAt: "2026-02-01T07:59:59Z", deadlineOrigin: "frozen", occurrenceId: "february" + ) + let model = EditServerViewModel() + model.prefill(from: config) + XCTAssertFalse(model.automaticRenewal) + XCTAssertNil(try object(model.buildRequest())["renewal"]) + model.expiryDate = try XCTUnwrap(BillingDate.date(from: "2026-02-15", timezone: model.billingTimezone)) + let request = try object(model.buildRequest()) + let renewal = try XCTUnwrap(request["renewal"] as? [String: Any]) + XCTAssertEqual(renewal["expiry_date"] as? String, "2026-02-15") + XCTAssertNil(renewal["enabled"]) + XCTAssertNil(renewal["billing_timezone"]) + XCTAssertNil(request["expired_at"]) + } +} diff --git a/apps/web/src/components/server/server-edit-renewal.test.tsx b/apps/web/src/components/server/server-edit-renewal.test.tsx index 568069809..dfb8f7681 100644 --- a/apps/web/src/components/server/server-edit-renewal.test.tsx +++ b/apps/web/src/components/server/server-edit-renewal.test.tsx @@ -75,6 +75,54 @@ afterEach(async () => { }) describe('server renewal date editing', () => { + it('does not confirm a clamped projection after restoring its selected date', async () => { + renderEditor({ + ...server, + expired_at: '2026-03-01T04:59:59.999999999Z', + renewal: { ...server.renewal, enabled: true, expiry_date: '2026-02-28' } + }) + const selectedDate = screen.getByLabelText('Expiration date') + fireEvent.change(selectedDate, { target: { value: '2026-03-01' } }) + fireEvent.change(selectedDate, { target: { value: '2026-02-28' } }) + fireEvent.change(screen.getByRole('spinbutton', { name: 'Price' }), { target: { value: '15' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).toMatchObject({ price: 15, billing_cycle: 'monthly' }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('expired_at') + }) + + it('changes the interval of an active clamped projection without sending a date', async () => { + renderEditor({ ...server, renewal: { ...server.renewal, enabled: true, expiry_date: '2026-02-28' } }) + fireEvent.click(screen.getByText('Monthly')) + const interval = await screen.findByRole('option', { name: 'Quarterly' }) + fireEvent.mouseMove(interval) + fireEvent.click(interval) + expect(screen.getByLabelText('Expiration date')).toHaveValue('2026-02-28') + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).toMatchObject({ billing_cycle: 'quarterly' }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('expired_at') + }) + + it('corrects a frozen deadline and timezone using the existing billing form', async () => { + renderEditor({ ...server, renewal: { ...server.renewal, deadline_origin: 'frozen' } }) + expect(screen.getByText('Frozen projected deadline')).toBeInTheDocument() + fireEvent.change(screen.getByLabelText('Billing timezone'), { target: { value: 'Asia/Tokyo' } }) + fireEvent.change(screen.getByLabelText('Expiration date'), { target: { value: '2026-03-15' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1].renewal).toEqual({ + billing_timezone: 'Asia/Tokyo', + expiry_date: '2026-03-15' + }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('expired_at') + }) + it('preserves legacy-server saves without exposing an unsupported automatic switch', async () => { renderEditor({ ...server, renewal: undefined }) expect(screen.queryByRole('switch', { name: 'Automatic renewal tracking' })).not.toBeInTheDocument() diff --git a/crates/server/tests/renewal_edits.rs b/crates/server/tests/renewal_edits.rs new file mode 100644 index 000000000..23b882663 --- /dev/null +++ b/crates/server/tests/renewal_edits.rs @@ -0,0 +1,520 @@ +//! Billing edit intent through production HTTP, calendar evaluation and reopened SQLite. +mod common; +use common::{create_server, http_client, login_admin}; +use serde_json::{Value, json}; + +use chrono::{DateTime, Utc}; +use std::sync::{Arc, RwLock}; +struct ManualClock(RwLock>); +impl ManualClock { + fn at(value: &str) -> Arc { + Arc::new(Self(RwLock::new(instant(value)))) + } + fn set(&self, value: &str) { + *self.0.write().unwrap() = instant(value); + } +} +impl serverbee_server::service::renewal_clock::RenewalClock for ManualClock { + fn now(&self) -> DateTime { + *self.0.read().unwrap() + } +} +fn instant(value: &str) -> DateTime { + value.parse().unwrap() +} +async fn controlled_server( + clock: Arc, +) -> ( + String, + tempfile::TempDir, + Arc, +) { + common::start_test_server_with_renewal_clock(100, clock).await +} +async fn detail(admin: &reqwest::Client, base: &str, id: &str) -> Value { + let body: Value = admin + .get(format!("{base}/api/servers/{id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + body["data"].clone() +} + +async fn reopen( + tmp: &tempfile::TempDir, + clock: Arc, +) -> (String, Arc) { + use serverbee_server::{config::AppConfig, router::create_router, state::AppState}; + let db = sea_orm::Database::connect(format!( + "sqlite://{}?mode=rwc", + tmp.path().join("test.db").display() + )) + .await + .unwrap(); + let mut config = AppConfig::default(); + config.auth.secure_cookie = false; + config.server.data_dir = tmp.path().to_str().unwrap().into(); + let state = AppState::new_with_renewal_clock(db, config, clock) + .await + .unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let app = create_router(state.clone()); + tokio::spawn(async move { + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); + }); + (base, state) +} + +async fn configure( + admin: &reqwest::Client, + base: &str, + id: &str, + cycle: &str, + date: &str, + zone: &str, +) { + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":cycle,"renewal":{"enabled":true,"expiry_date":date,"billing_timezone":zone}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); +} +async fn tick(state: &serverbee_server::state::AppState) { + serverbee_server::task::alert_evaluator::evaluate_once(state) + .await + .unwrap(); +} + +#[tokio::test] +async fn interval_edit_after_clamped_month_retains_history_and_original_anchor_on_reopen() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "edited-quarterly-anchor").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + clock.set("2026-02-01T05:00:00Z"); + tick(&state).await; + let february = detail(&admin, &base, &id).await; + assert_eq!(february["renewal"]["expiry_date"], "2026-02-28"); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"quarterly"})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let edited = detail(&admin, &base, &id).await; + assert_eq!(edited["renewal"], february["renewal"]); + assert_eq!(edited["expired_at"], february["expired_at"]); + state.db.clone().close().await.unwrap(); + clock.set("2026-03-01T05:00:00Z"); + let (base, _restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let may = detail(&admin, &base, &id).await; + assert_eq!(may["billing_cycle"], "quarterly"); + assert_eq!(may["renewal"]["expiry_date"], "2026-05-31"); + assert_eq!(may["expired_at"], "2026-06-01T03:59:59.999999999Z"); + assert_eq!( + may["renewal"]["confirmed_expired_at"], + february["renewal"]["confirmed_expired_at"] + ); + assert_ne!( + may["renewal"]["occurrence_id"], + february["renewal"]["occurrence_id"] + ); +} + +#[tokio::test] +async fn actual_date_correction_confirms_provider_date_and_replaces_clamped_anchor() { + let clock = ManualClock::at("2026-01-31T12:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "corrected-provider-date").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + clock.set("2026-02-01T05:00:00Z"); + tick(&state).await; + let february = detail(&admin, &base, &id).await; + assert_eq!(february["renewal"]["expiry_date"], "2026-02-28"); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"expiry_date":"2026-02-15"}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let corrected = detail(&admin, &base, &id).await; + assert_eq!(corrected["renewal"]["expiry_date"], "2026-02-15"); + assert_eq!(corrected["expired_at"], "2026-02-16T04:59:59.999999999Z"); + assert_eq!( + corrected["renewal"]["confirmed_expired_at"], + "2026-02-16T04:59:59.999999999Z" + ); + assert_eq!(corrected["renewal"]["deadline_origin"], "projected"); + assert_eq!(corrected["renewal"]["enabled"], true); + assert_ne!( + corrected["renewal"]["occurrence_id"], + february["renewal"]["occurrence_id"] + ); + state.db.clone().close().await.unwrap(); + clock.set("2026-02-16T05:00:00Z"); + let (base, _restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let march = detail(&admin, &base, &id).await; + assert_eq!(march["renewal"]["expiry_date"], "2026-03-15"); + assert_eq!(march["expired_at"], "2026-03-16T03:59:59.999999999Z"); + assert_eq!( + march["renewal"]["confirmed_expired_at"], + corrected["renewal"]["confirmed_expired_at"] + ); +} + +#[tokio::test] +async fn past_date_correction_confirms_recorded_date_and_catches_up_with_new_anchor() { + let clock = ManualClock::at("2026-02-01T05:00:00Z"); + let (base, _tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "past-provider-correction").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let before = detail(&admin, &base, &id).await; + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"expiry_date":"2026-01-20"}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let corrected = detail(&admin, &base, &id).await; + assert_eq!( + corrected["renewal"]["confirmed_expired_at"], + "2026-01-21T04:59:59.999999999Z" + ); + assert_eq!(corrected["renewal"]["expiry_date"], "2026-02-20"); + assert_eq!(corrected["expired_at"], "2026-02-21T04:59:59.999999999Z"); + assert_ne!( + corrected["renewal"]["occurrence_id"], + before["renewal"]["occurrence_id"] + ); + clock.set("2026-02-21T05:00:00Z"); + tick(&state).await; + let march = detail(&admin, &base, &id).await; + assert_eq!(march["renewal"]["expiry_date"], "2026-03-20"); + assert_eq!(march["expired_at"], "2026-03-21T03:59:59.999999999Z"); + assert_eq!( + march["renewal"]["confirmed_expired_at"], + corrected["renewal"]["confirmed_expired_at"] + ); +} + +#[tokio::test] +async fn timezone_only_edit_preserves_local_projection_history_occurrence_and_anchor_through_dst() { + let clock = ManualClock::at("2026-02-01T05:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let clamped = create_server(&admin, &base, "timezone-clamped-date").await; + configure( + &admin, + &base, + &clamped, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let dst = create_server(&admin, &base, "timezone-dst-date").await; + configure( + &admin, + &base, + &dst, + "monthly", + "2026-02-08", + "America/New_York", + ) + .await; + clock.set("2026-02-09T05:00:00Z"); + tick(&state).await; + let mut histories = Vec::new(); + for (id, zone, date, boundary) in [ + ( + &clamped, + "Asia/Tokyo", + "2026-02-28", + "2026-02-28T14:59:59.999999999Z", + ), + ( + &dst, + "America/Los_Angeles", + "2026-03-08", + "2026-03-09T06:59:59.999999999Z", + ), + ] { + let before = detail(&admin, &base, id).await; + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"billing_timezone":zone}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let after = detail(&admin, &base, id).await; + assert_eq!(after["renewal"]["expiry_date"], date); + assert_eq!(after["expired_at"], boundary); + assert_eq!( + after["renewal"]["confirmed_expired_at"], + before["renewal"]["confirmed_expired_at"] + ); + assert_eq!( + after["renewal"]["occurrence_id"], + before["renewal"]["occurrence_id"] + ); + assert_eq!(after["renewal"]["deadline_origin"], "projected"); + histories.push(before["renewal"]["confirmed_expired_at"].clone()); + } + state.db.clone().close().await.unwrap(); + clock.set("2026-03-09T07:00:00Z"); + let (base, _restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let march = detail(&admin, &base, &clamped).await; + assert_eq!(march["renewal"]["expiry_date"], "2026-03-31"); + assert_eq!(march["expired_at"], "2026-03-31T14:59:59.999999999Z"); + assert_eq!(march["renewal"]["confirmed_expired_at"], histories[0]); + let april = detail(&admin, &base, &dst).await; + assert_eq!(april["renewal"]["expiry_date"], "2026-04-08"); + assert_eq!(april["expired_at"], "2026-04-09T06:59:59.999999999Z"); + assert_eq!(april["renewal"]["confirmed_expired_at"], histories[1]); +} + +#[tokio::test] +async fn actual_full_form_shapes_and_legacy_resubmissions_preserve_projected_anchor_on_reopen() { + let clock = ManualClock::at("2026-02-01T05:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "full-form-clamped-projection").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let before = detail(&admin, &base, &id).await; + // Actual Web and iOS editors submit these ordinary fields and omit unchanged + // renewal settings. Retain old clients' instant and UTC-prefix saves too. + let web = json!({"name":"web-save","weight":100,"hidden":false,"group_id":null, + "remark":"","public_remark":"","price":12.5,"billing_cycle":"monthly", + "currency":"USD","traffic_limit":1073741824_i64,"traffic_limit_type":"sum","billing_start_day":7}); + let mut ios = web.clone(); + ios["name"] = json!("ios-save"); + ios["price"] = json!(15.0); + let mut calendar_full_form = web.clone(); + calendar_full_form["renewal"] = + json!({"enabled":true,"expiry_date":"2026-02-28","billing_timezone":"America/New_York"}); + let mut legacy_ios = ios.clone(); + legacy_ios["expired_at"] = before["expired_at"].clone(); + let mut legacy_web = web.clone(); + legacy_web["expired_at"] = json!("2026-03-01T00:00:00.000Z"); + for payload in [web, ios, calendar_full_form, legacy_ios, legacy_web] { + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&payload) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let saved = detail(&admin, &base, &id).await; + assert_eq!(saved["renewal"], before["renewal"]); + assert_eq!(saved["expired_at"], before["expired_at"]); + for field in [ + "name", + "price", + "currency", + "traffic_limit", + "traffic_limit_type", + "billing_start_day", + ] { + assert_eq!( + saved[field], payload[field], + "ordinary field {field} still saves" + ); + } + } + state.db.clone().close().await.unwrap(); + clock.set("2026-03-01T05:00:00Z"); + let (base, _restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let march = detail(&admin, &base, &id).await; + assert_eq!(march["renewal"]["expiry_date"], "2026-03-31"); + assert_eq!(march["expired_at"], "2026-04-01T03:59:59.999999999Z"); + assert_eq!( + march["renewal"]["confirmed_expired_at"], + before["renewal"]["confirmed_expired_at"] + ); + assert_eq!(march["price"], 12.5); + assert_eq!(march["currency"], "USD"); + assert_eq!(march["traffic_limit"], 1073741824_i64); + assert_eq!(march["billing_start_day"], 7); +} + +#[tokio::test] +async fn interval_edit_of_non_leap_projection_keeps_leap_day_anchor_and_confirmation_on_reopen() { + let clock = ManualClock::at("2024-02-29T12:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "edited-leap-anchor").await; + configure( + &admin, + &base, + &id, + "yearly", + "2024-02-29", + "America/New_York", + ) + .await; + clock.set("2024-03-01T05:00:00Z"); + tick(&state).await; + let non_leap = detail(&admin, &base, &id).await; + assert_eq!(non_leap["renewal"]["expiry_date"], "2025-02-28"); + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"quarterly","renewal":{"enabled":true,"expiry_date":"2025-02-28","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + assert_eq!( + detail(&admin, &base, &id).await["renewal"], + non_leap["renewal"] + ); + state.db.clone().close().await.unwrap(); + clock.set("2025-03-01T05:00:00Z"); + let (base, _restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let may = detail(&admin, &base, &id).await; + assert_eq!(may["renewal"]["expiry_date"], "2025-05-29"); + assert_eq!(may["expired_at"], "2025-05-30T03:59:59.999999999Z"); + assert_eq!( + may["renewal"]["confirmed_expired_at"], + "2024-03-01T04:59:59.999999999Z" + ); +} + +#[tokio::test] +async fn frozen_timezone_edit_keeps_provenance_until_actual_date_correction_confirms_it() { + let clock = ManualClock::at("2026-02-01T05:00:00Z"); + let (base, tmp, state) = controlled_server(clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let id = create_server(&admin, &base, "manual-frozen-correction").await; + configure( + &admin, + &base, + &id, + "monthly", + "2026-01-31", + "America/New_York", + ) + .await; + let projected = detail(&admin, &base, &id).await; + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":false,"billing_timezone":"Asia/Tokyo"}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let frozen = detail(&admin, &base, &id).await; + assert_eq!(frozen["renewal"]["expiry_date"], "2026-02-28"); + assert_eq!(frozen["expired_at"], "2026-02-28T14:59:59.999999999Z"); + assert_eq!(frozen["renewal"]["deadline_origin"], "frozen"); + assert_eq!( + frozen["renewal"]["occurrence_id"], + projected["renewal"]["occurrence_id"] + ); + assert_eq!( + frozen["renewal"]["confirmed_expired_at"], + projected["renewal"]["confirmed_expired_at"] + ); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"expiry_date":"2026-02-15"}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let corrected = detail(&admin, &base, &id).await; + assert_eq!(corrected["renewal"]["deadline_origin"], "confirmed"); + assert_eq!(corrected["renewal"]["enabled"], false); + assert_eq!(corrected["expired_at"], "2026-02-15T14:59:59.999999999Z"); + assert_eq!( + corrected["renewal"]["confirmed_expired_at"], + corrected["expired_at"] + ); + assert_ne!( + corrected["renewal"]["occurrence_id"], + frozen["renewal"]["occurrence_id"] + ); + state.db.clone().close().await.unwrap(); + clock.set("2026-03-01T00:00:00Z"); + let (base, restarted) = reopen(&tmp, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + tick(&restarted).await; + assert_eq!( + detail(&admin, &base, &id).await["renewal"], + corrected["renewal"] + ); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":true}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let resumed = detail(&admin, &base, &id).await; + assert_eq!(resumed["renewal"]["expiry_date"], "2026-03-15"); + assert_eq!( + resumed["renewal"]["confirmed_expired_at"], + corrected["expired_at"] + ); +} From bd59b686f3a533e28478c82951e8ee648106a8e0 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:49:45 +0000 Subject: [PATCH 28/40] feat(renewal): admit once reminders for each projected occurrence --- .github/workflows/ci.yml | 1 + crates/server/src/service/alert.rs | 52 +++++++-- crates/server/src/service/mod.rs | 1 + .../server/src/service/renewal_reminders.rs | 107 ++++++++++++++++++ crates/server/tests/renewal_reminders.rs | 81 +++++++++++++ 5 files changed, 231 insertions(+), 11 deletions(-) create mode 100644 crates/server/src/service/renewal_reminders.rs create mode 100644 crates/server/tests/renewal_reminders.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 260521b2b..7cac8eca5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -238,6 +238,7 @@ jobs: --test router_security_rate --test renewal_dates --test renewal_projection + --test renewal_reminders --test router_server_crud --test router_server_extra --test router_server_extra2 diff --git a/crates/server/src/service/alert.rs b/crates/server/src/service/alert.rs index 5e8aefb3b..b40b9557d 100644 --- a/crates/server/src/service/alert.rs +++ b/crates/server/src/service/alert.rs @@ -36,8 +36,7 @@ pub const COVER_TYPE_ALL: &str = "all"; pub const COVER_TYPE_INCLUDE: &str = "include"; pub const COVER_TYPE_EXCLUDE: &str = "exclude"; /// All accepted `cover_type` values for alert_rule and block_list inputs. -pub const VALID_COVER_TYPES: &[&str] = - &[COVER_TYPE_ALL, COVER_TYPE_INCLUDE, COVER_TYPE_EXCLUDE]; +pub const VALID_COVER_TYPES: &[&str] = &[COVER_TYPE_ALL, COVER_TYPE_INCLUDE, COVER_TYPE_EXCLUDE]; /// `origin` discriminants for block_list rows. pub const ORIGIN_MANUAL: &str = "manual"; @@ -45,8 +44,7 @@ pub const ORIGIN_AUTO: &str = "auto"; /// Security rule types whose payload carries a `source_ip` and may attach a /// `block_source_ip` action. -pub const SOURCE_IP_RULE_TYPES: &[&str] = - &["ssh_brute_force_detected", "port_scan_detected"]; +pub const SOURCE_IP_RULE_TYPES: &[&str] = &["ssh_brute_force_detected", "port_scan_detected"]; // ── Alert Rule Types ── @@ -900,6 +898,34 @@ impl AlertService { let servers = resolve_servers(db, &rule.cover_type, &rule.server_ids_json).await?; for srv in &servers { + if items.iter().any(|item| item.rule_type == "expiration") + && !items + .iter() + .any(|item| EVENT_DRIVEN_RULE_TYPES.contains(&item.rule_type.as_str())) + { + let other: Vec<_> = items + .iter() + .filter(|item| item.rule_type != "expiration") + .cloned() + .collect(); + let matched = Self::check_server_at(db, agent_manager, &other, &srv.id, now).await; + if let Some(notify) = crate::service::renewal_reminders::evaluate( + db, + state_manager, + rule, + &srv.id, + &items, + matched, + now, + ) + .await? + { + if notify { + Self::notify_triggered(db, config, rule, &srv.id, &srv.name, now).await; + } + continue; + } + } let triggered = Self::check_server_at(db, agent_manager, &items, &srv.id, now).await; if triggered { @@ -1904,8 +1930,7 @@ mod tests { _ => break, } } - let _ = socket - .try_write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + let _ = socket.try_write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); let _ = tx.send(String::from_utf8_lossy(&buf).into_owned()); } }); @@ -2024,7 +2049,10 @@ mod tests { .expect("query states"); assert_eq!(rows.len(), 1, "no duplicate alert_state rows"); assert!(!rows[0].resolved, "re-armed row should be firing again"); - assert!(rows[0].resolved_at.is_none(), "resolved_at cleared on re-arm"); + assert!( + rows[0].resolved_at.is_none(), + "resolved_at cleared on re-arm" + ); assert_eq!(rows[0].count, 1, "count reset on re-arm"); } @@ -2660,10 +2688,12 @@ mod tests { async fn test_latest_record_time_picks_latest_and_none() { let (db, _tmp) = setup_test_db().await; // No records => None. - assert!(RecordService::latest_record_time(&db, "srv-1") - .await - .expect("query should succeed") - .is_none()); + assert!( + RecordService::latest_record_time(&db, "srv-1") + .await + .expect("query should succeed") + .is_none() + ); let older = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap(); let newer = Utc.with_ymd_and_hms(2026, 1, 1, 1, 0, 0).unwrap(); diff --git a/crates/server/src/service/mod.rs b/crates/server/src/service/mod.rs index 029ab0f32..b4393c67d 100644 --- a/crates/server/src/service/mod.rs +++ b/crates/server/src/service/mod.rs @@ -60,3 +60,4 @@ pub(crate) mod alert_event_intents; pub mod renewal; pub mod renewal_clock; +pub mod renewal_reminders; diff --git a/crates/server/src/service/renewal_reminders.rs b/crates/server/src/service/renewal_reminders.rs new file mode 100644 index 000000000..ff0e89388 --- /dev/null +++ b/crates/server/src/service/renewal_reminders.rs @@ -0,0 +1,107 @@ +//! Durable expiration admission for the current projected or frozen renewal occurrence. +use crate::{ + entity::{alert_rule, alert_state}, + error::AppError, + service::{ + alert::{AlertRuleItem, AlertStateManager, rule_covers_server}, + maintenance::MaintenanceService, + mobile_alert_push, + renewal::{self, DeadlineOrigin, RenewalState}, + }, +}; +use chrono::{DateTime, Duration, Utc}; +use sea_orm::{ + ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, Set, + TransactionTrait, +}; + +/// `None` leaves legacy confirmed-expiry rules on their existing alert path. +/// The writer reservation protects the selected deadline through queue admission. +pub(super) async fn evaluate( + db: &DatabaseConnection, + manager: &AlertStateManager, + rule: &alert_rule::Model, + server_id: &str, + items: &[AlertRuleItem], + other_conditions: bool, + now: DateTime, +) -> Result, AppError> { + let _admission = manager.admission_lock.lock().await; + let tx = db.begin().await?; + let model = renewal::load_for_update(&tx, server_id).await?; + let renewal = RenewalState::from_server(&model); + if renewal.deadline_origin == DeadlineOrigin::Confirmed { + tx.commit().await?; + return Ok(None); + } + let Some(occurrence) = renewal.occurrence_id else { + tx.commit().await?; + return Ok(None); + }; + let Some(rule) = alert_rule::Entity::find_by_id(&rule.id) + .one(&tx) + .await? + .filter(|rule| { + rule.enabled && rule_covers_server(&rule.cover_type, &rule.server_ids_json, server_id) + }) + else { + tx.commit().await?; + return Ok(Some(false)); + }; + let event_key = format!("renewal:{occurrence}"); + let matched = other_conditions + && items + .iter() + .filter(|item| item.rule_type == "expiration") + .all(|item| { + model.expired_at.is_some_and(|deadline| { + deadline <= now + Duration::days(item.duration.unwrap_or(7) as i64) + }) + }); + if !matched || MaintenanceService::is_in_maintenance_at(&tx, server_id, now).await? { + tx.commit().await?; + return Ok(Some(false)); + } + let existing = alert_state::Entity::find() + .filter(alert_state::Column::RuleId.eq(&rule.id)) + .filter(alert_state::Column::ServerId.eq(server_id)) + .filter(alert_state::Column::EventKey.eq(&event_key)) + .one(&tx) + .await?; + let should_notify = existing.as_ref().is_none_or(|state| { + rule.trigger_mode != "once" && now - state.last_notified_at >= Duration::minutes(5) + }); + if !should_notify { + tx.commit().await?; + return Ok(Some(false)); + } + let row = if let Some(previous) = existing { + let count = previous.count; + let mut active: alert_state::ActiveModel = previous.into(); + active.last_notified_at = Set(now); + active.count = Set(count.saturating_add(1)); + active.resolved = Set(false); + active.resolved_at = Set(None); + active.updated_at = Set(now); + active.update(&tx).await? + } else { + alert_state::ActiveModel { + rule_id: Set(rule.id.clone()), + server_id: Set(server_id.into()), + event_key: Set(event_key), + first_triggered_at: Set(now), + last_notified_at: Set(now), + count: Set(1), + resolved: Set(false), + resolved_at: Set(None), + updated_at: Set(now), + ..Default::default() + } + .insert(&tx) + .await? + }; + mobile_alert_push::enqueue(&tx, &rule, &row, &model.name).await?; + tx.commit().await?; + manager.publish_state(&row); + Ok(Some(true)) +} diff --git a/crates/server/tests/renewal_reminders.rs b/crates/server/tests/renewal_reminders.rs new file mode 100644 index 000000000..4c3012e55 --- /dev/null +++ b/crates/server/tests/renewal_reminders.rs @@ -0,0 +1,81 @@ +//! Renewal reminders through authenticated HTTP, real persistent SQLite and the production tick. +mod common; +use chrono::{DateTime, Utc}; +use common::{create_server, http_client, login_admin}; +use serde_json::{Value, json}; +use serverbee_server::{service::renewal_clock::RenewalClock, state::AppState}; +use std::sync::{Arc, RwLock}; + +struct ManualClock(RwLock>); +impl ManualClock { + fn at(value: &str) -> Arc { + Arc::new(Self(RwLock::new(value.parse().unwrap()))) + } + fn set(&self, value: &str) { + *self.0.write().unwrap() = value.parse().unwrap(); + } +} +impl RenewalClock for ManualClock { + fn now(&self) -> DateTime { + *self.0.read().unwrap() + } +} +async fn get(admin: &reqwest::Client, base: &str, path: &str) -> Value { + let response = admin + .get(format!("{base}/api/{path}")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + response.json::().await.unwrap()["data"].clone() +} +async fn configure(admin: &reqwest::Client, base: &str, days: u32) -> (String, String) { + let id = create_server(admin, base, "offline-renewal-reminder").await; + let response = admin.put(format!("{base}/api/servers/{id}")) + .json(&json!({"billing_cycle":"monthly","renewal":{"enabled":true,"expiry_date":"2026-10-31","billing_timezone":"America/New_York"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let response = admin.post(format!("{base}/api/alert-rules")) + .json(&json!({"name":"renewal reminder","rules":[{"rule_type":"expiration","duration":days}],"trigger_mode":"once","enabled":true,"cover_type":"include","server_ids":[id]})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + (id, body["data"]["id"].as_str().unwrap().to_string()) +} +async fn tick(state: &AppState) { + serverbee_server::task::alert_evaluator::evaluate_once(state) + .await + .unwrap(); +} +#[tokio::test] +async fn once_reminder_rearms_for_next_month_even_when_sixty_day_condition_stays_true() { + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (base, _tmp, state) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, rule) = configure(&admin, &base, 60).await; + tick(&state).await; + let first = get(&admin, &base, "alert-events").await; + assert_eq!(first.as_array().unwrap().len(), 1); + clock.set("2026-11-01T04:00:00Z"); + tick(&state).await; + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["expiry_date"], + "2026-11-30" + ); + let events = get(&admin, &base, "alert-events").await; + assert_eq!( + events.as_array().unwrap().len(), + 2, + "each current monthly occurrence must admit its own once reminder: {events}" + ); + assert_ne!(events[0]["alert_key"], events[1]["alert_key"]); + assert!( + events + .as_array() + .unwrap() + .iter() + .all(|event| event["rule_id"] == rule) + ); +} From dce2352b069d3df913071c987898d983e5e7f899 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:55:21 +0000 Subject: [PATCH 29/40] fix(web): reject stale renewal requests during catalog refresh --- .../src/hooks/use-servers-ws-renewal.test.tsx | 140 +++++++++++++++++- apps/web/src/lib/server-catalog.ts | 27 +++- apps/web/src/lib/server-cost-cache.ts | 20 ++- 3 files changed, 170 insertions(+), 17 deletions(-) diff --git a/apps/web/src/hooks/use-servers-ws-renewal.test.tsx b/apps/web/src/hooks/use-servers-ws-renewal.test.tsx index 3bc9ae8a8..ca55eb753 100644 --- a/apps/web/src/hooks/use-servers-ws-renewal.test.tsx +++ b/apps/web/src/hooks/use-servers-ws-renewal.test.tsx @@ -104,8 +104,8 @@ function setup() { queryClient, fetchSpy, wrapper, - advance() { - currentServer = { ...server, expired_at: '2026-02-28T23:59:59Z' } + advance(expiredAt = '2026-02-28T23:59:59Z') { + currentServer = { ...server, expired_at: expiredAt } expired = false }, receive(message: unknown) { @@ -122,6 +122,142 @@ afterEach(() => { }) describe('renewal catalog refresh through the browser WebSocket', () => { + it.each([ + 'server_catalog_changed', + 'full_sync' + ])('retains the newest deadline when %s arrives during an older catalog fetch', async (messageType) => { + const fixture = setup() + const { result } = renderHook( + () => { + useServersWs() + return { list: useServerList(), detail: useServerDetail('srv-1') } + }, + { wrapper: fixture.wrapper } + ) + await waitFor(() => expect(result.current.list.data?.[0].expired_at).toBe(server.expired_at)) + await waitFor(() => expect(result.current.detail.data?.expired_at).toBe(server.expired_at)) + + let release: (response: Response) => void = () => { + throw new Error('Deferred request not initialized') + } + const blocked = new Promise((resolve) => { + release = resolve + }) + fixture.fetchSpy.mockImplementationOnce(() => blocked) + fixture.advance() + fixture.receive({ type: 'server_catalog_changed', server_ids: ['srv-1'] }) + await waitFor(() => expect(fixture.fetchSpy.mock.calls.filter(([path]) => path === '/api/servers')).toHaveLength(2)) + + fixture.advance('2026-03-31T23:59:59Z') + fixture.receive( + messageType === 'full_sync' + ? { type: 'full_sync', servers: fixture.queryClient.getQueryData(['server-catalog', 'live']) } + : { type: 'server_catalog_changed', server_ids: ['srv-1'] } + ) + await act(async () => { + release(Response.json({ data: [{ ...server, expired_at: '2026-02-28T23:59:59Z' }] })) + await blocked + }) + + await waitFor(() => expect(result.current.list.data?.[0].expired_at).toBe('2026-03-31T23:59:59Z')) + await waitFor(() => expect(result.current.detail.data?.expired_at).toBe('2026-03-31T23:59:59Z')) + }) + + it('keeps an older pending detail request from overwriting a refreshed renewal deadline', async () => { + const fixture = setup() + let release: (response: Response) => void = () => { + throw new Error('Deferred request not initialized') + } + const blocked = new Promise((resolve) => { + release = resolve + }) + const network = fixture.fetchSpy.getMockImplementation() + let held = false + fixture.fetchSpy.mockImplementation((input, options) => { + if (String(input) === '/api/servers/srv-1' && !held) { + held = true + return blocked + } + if (!network) { + throw new Error('Fixture network not initialized') + } + return network(input, options) + }) + const { result } = renderHook( + () => { + useServersWs() + return { list: useServerList(), detail: useServerDetail('srv-1') } + }, + { wrapper: fixture.wrapper } + ) + await waitFor(() => expect(result.current.list.data?.[0].expired_at).toBe(server.expired_at)) + + fixture.advance() + fixture.receive({ type: 'server_catalog_changed', server_ids: ['srv-1'] }) + await waitFor(() => expect(result.current.list.data?.[0].expired_at).toBe('2026-02-28T23:59:59Z')) + await act(async () => { + release(Response.json({ data: server })) + await blocked + }) + + await waitFor(() => expect(result.current.detail.data?.expired_at).toBe('2026-02-28T23:59:59Z')) + expect(result.current.list.data?.[0].expired_at).toBe('2026-02-28T23:59:59Z') + }) + + it.each([ + '/api/servers/srv-1/cost-insights', + '/api/cost/overview' + ])('refreshes cost advisories when a catalog change arrives during the first %s request', async (path) => { + const fixture = setup() + let release: (response: Response) => void = () => { + throw new Error('Deferred request not initialized') + } + const blocked = new Promise((resolve) => { + release = resolve + }) + const network = fixture.fetchSpy.getMockImplementation() + let held = false + fixture.fetchSpy.mockImplementation((input, options) => { + if (String(input) === path && !held) { + held = true + return blocked + } + if (!network) { + throw new Error('Fixture network not initialized') + } + return network(input, options) + }) + const { result } = renderHook( + () => { + useServersWs() + return { insights: useCostInsights('srv-1'), overview: useCostOverview() } + }, + { wrapper: fixture.wrapper } + ) + await waitFor(() => expect(fixture.fetchSpy).toHaveBeenCalledWith(path, expect.any(Object))) + fixture.advance() + fixture.receive({ type: 'server_catalog_changed', server_ids: ['srv-1'] }) + await act(async () => { + release( + Response.json({ + data: + path === '/api/cost/overview' + ? { + currencies: [], + servers: [ + { server_id: 'srv-1', name: server.name, configured: true, advisories: ['expired_billing'] } + ] + } + : { server_id: 'srv-1', configured: true, advisories: ['expired_billing'] } + }) + ) + await blocked + }) + + await waitFor(() => expect(result.current.insights.data?.advisories).toEqual([])) + await waitFor(() => expect(result.current.overview.data?.servers[0].advisories).toEqual([])) + }) + it('refreshes current detail, list, dashboard and cost advisories after an affected catalog change', async () => { const fixture = setup() const { result } = renderHook( diff --git a/apps/web/src/lib/server-catalog.ts b/apps/web/src/lib/server-catalog.ts index 7fb93dfc4..ba266de72 100644 --- a/apps/web/src/lib/server-catalog.ts +++ b/apps/web/src/lib/server-catalog.ts @@ -7,6 +7,7 @@ const LIVE_SERVERS_KEY = ['server-catalog', 'live'] as const const SERVER_LIST_KEY = ['server-catalog', 'list'] as const const SERVER_DETAIL_PREFIX = ['server-catalog', 'detail'] as const const listRequestGenerations = new WeakMap() +const catalogRefreshGenerations = new WeakMap() type TemporaryGrant = NonNullable[number] @@ -560,16 +561,23 @@ export function useServerDetail(serverId: string, options: CatalogQueryOptions = export async function refreshServerCatalog(queryClient: QueryClient): Promise { const generation = nextListRequestGeneration(queryClient) - await queryClient.cancelQueries({ exact: true, queryKey: SERVER_LIST_KEY }) + catalogRefreshGenerations.set(queryClient, (catalogRefreshGenerations.get(queryClient) ?? 0) + 1) + await Promise.all([ + queryClient.cancelQueries({ exact: true, queryKey: SERVER_LIST_KEY }), + queryClient.cancelQueries({ queryKey: SERVER_DETAIL_PREFIX }) + ]) if (!isCurrentListRequest(queryClient, generation)) { return } try { - await queryClient.fetchQuery({ - queryFn: () => fetchAndProjectRestSnapshot(queryClient, generation), - queryKey: SERVER_LIST_KEY, - staleTime: 0 - }) + await Promise.all([ + queryClient.fetchQuery({ + queryFn: () => fetchAndProjectRestSnapshot(queryClient, generation), + queryKey: SERVER_LIST_KEY, + staleTime: 0 + }), + queryClient.invalidateQueries({ queryKey: SERVER_DETAIL_PREFIX }) + ]) } catch (error) { if (isCurrentListRequest(queryClient, generation)) { throw error @@ -599,8 +607,13 @@ async function fetchAndProjectRestSnapshot( } async function fetchAndProjectServerDetail(queryClient: QueryClient, serverId: string): Promise { + const generation = catalogRefreshGenerations.get(queryClient) const server = await api.get(`/api/servers/${serverId}`) - projectServerCatalog(queryClient, { kind: 'server_saved', server }) + // Cancellation stops React Query from accepting an obsolete request, but the + // HTTP boundary may still finish. Its catalog projection must also be fenced. + if (catalogRefreshGenerations.get(queryClient) === generation) { + projectServerCatalog(queryClient, { kind: 'server_saved', server }) + } return server } diff --git a/apps/web/src/lib/server-cost-cache.ts b/apps/web/src/lib/server-cost-cache.ts index 00049ba0b..78ab96bcc 100644 --- a/apps/web/src/lib/server-cost-cache.ts +++ b/apps/web/src/lib/server-cost-cache.ts @@ -1,13 +1,17 @@ -import type { QueryClient } from '@tanstack/react-query' +import type { QueryClient, QueryFilters } from '@tanstack/react-query' export function invalidateServerCosts(queryClient: QueryClient, serverIds?: readonly string[]): void { - queryClient.invalidateQueries({ queryKey: ['cost', 'overview'] }).catch(() => undefined) - queryClient - .invalidateQueries({ - predicate: ({ queryKey }) => - queryKey[0] === 'servers' && + const filters: QueryFilters = { + predicate: ({ queryKey }) => + (queryKey[0] === 'cost' && queryKey[1] === 'overview') || + (queryKey[0] === 'servers' && queryKey[2] === 'cost-insights' && - (serverIds === undefined || serverIds.includes(queryKey[1] as string)) - }) + (serverIds === undefined || serverIds.includes(queryKey[1] as string))) + } + // Invalidation alone reuses an initial pending request without cached data. + // Cancel it first so advisories are fetched after the catalog change. + queryClient + .cancelQueries(filters) + .then(() => queryClient.invalidateQueries(filters)) .catch(() => undefined) } From 72162918e55dd862cc697593443927ba47d1d0ce Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 19:57:16 +0000 Subject: [PATCH 30/40] feat(renewal): evaluate local reminders and silently supersede old targets --- crates/server/src/router/api/alert.rs | 10 +- crates/server/src/service/alert.rs | 16 +- crates/server/src/service/renewal.rs | 36 ++-- .../server/src/service/renewal_reminders.rs | 46 ++++- crates/server/tests/renewal_reminders.rs | 171 ++++++++++++++++++ 5 files changed, 248 insertions(+), 31 deletions(-) diff --git a/crates/server/src/router/api/alert.rs b/crates/server/src/router/api/alert.rs index a9dff2b37..cb401404e 100644 --- a/crates/server/src/router/api/alert.rs +++ b/crates/server/src/router/api/alert.rs @@ -251,12 +251,10 @@ pub async fn get_alert_event_detail( .map(|s| s.name) .unwrap_or_else(|| "Unknown".to_string()); - let status = if alert_state.resolved { - "resolved" - } else { - "firing" - }; - let message = if alert_state.resolved { + let status = crate::service::alert::alert_status(&alert_state); + let message = if status == "superseded" { + "Reminder target superseded by the current renewal deadline".to_string() + } else if alert_state.resolved { format!("Alert resolved after {} trigger(s)", alert_state.count) } else { format!("Alert firing — triggered {} time(s)", alert_state.count) diff --git a/crates/server/src/service/alert.rs b/crates/server/src/service/alert.rs index b40b9557d..8ebf0e965 100644 --- a/crates/server/src/service/alert.rs +++ b/crates/server/src/service/alert.rs @@ -233,6 +233,8 @@ pub struct UpdateAlertRule { #[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] pub struct AlertStateResponse { + #[schema(required = false)] + pub status: String, pub server_id: String, pub server_name: String, pub first_triggered_at: chrono::DateTime, @@ -718,6 +720,7 @@ impl AlertService { .unwrap_or_else(|| "Unknown".to_string()); result.push(AlertStateResponse { + status: alert_status(&state).into(), server_id: state.server_id, server_name, first_triggered_at: state.first_triggered_at, @@ -767,7 +770,7 @@ impl AlertService { let result = states .into_iter() .map(|s| { - let status = if s.resolved { "resolved" } else { "firing" }; + let status = alert_status(&s); let event_at = if s.resolved { s.resolved_at .map(|t| t.to_rfc3339()) @@ -1122,6 +1125,17 @@ impl AlertService { } } +/// Calendar supersession is retained for detail without claiming recovery. +pub fn alert_status(state: &alert_state::Model) -> &'static str { + if state.resolved && state.resolved_at.is_none() && state.event_key.starts_with("renewal:") { + "superseded" + } else if state.resolved { + "resolved" + } else { + "firing" + } +} + /// Versioned URL-safe identity binds the complete dimension and trigger cycle. /// An overwritten cycle must return unavailable rather than a newer alert. pub fn alert_detail_key(state: &alert_state::Model) -> String { diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs index 831667726..5f495dcba 100644 --- a/crates/server/src/service/renewal.rs +++ b/crates/server/src/service/renewal.rs @@ -389,6 +389,25 @@ pub async fn load_for_update( } /// Production catch-up evaluates each server from a stable, freshly locked schedule. +pub(super) async fn advance_locked( + tx: &DatabaseTransaction, + model: server::Model, + now: DateTime, +) -> Result<(server::Model, bool), AppError> { + let mut state = RenewalState::from_server(&model); + let mut deadline = model.expired_at; + if !state.advance(&mut deadline, model.billing_cycle.as_deref(), now)? { + return Ok((model, false)); + } + let mut active: server::ActiveModel = model.into(); + active.expired_at = Set(deadline); + active.renewal_state = Set(Some( + serde_json::to_string(&state).map_err(|e| AppError::Internal(e.to_string()))?, + )); + active.updated_at = Set(now); + Ok((active.update(tx).await?, true)) +} + pub async fn advance_all(db: &DatabaseConnection, now: DateTime) -> Result<(), AppError> { let servers = server::Entity::find().all(db).await?; for candidate in servers { @@ -404,27 +423,16 @@ pub async fn advance_all(db: &DatabaseConnection, now: DateTime) -> Result< } Err(error) => return Err(error), }; - let mut state = RenewalState::from_server(&model); - let mut deadline = model.expired_at; - let advanced = match state.advance(&mut deadline, model.billing_cycle.as_deref(), now) { - Ok(advanced) => advanced, + match advance_locked(&tx, model, now).await { + Ok(_) => {} Err(AppError::Validation(reason)) => { // A damaged calendar configuration cannot stop healthy schedules. // Database/transaction errors still propagate to the caller. - tracing::error!(server_id = %model.id, %reason, "Skipping invalid renewal schedule"); + tracing::error!(server_id = %candidate.id, %reason, "Skipping invalid renewal schedule"); tx.rollback().await?; continue; } Err(error) => return Err(error), - }; - if advanced { - let mut active: server::ActiveModel = model.into(); - active.expired_at = Set(deadline); - active.renewal_state = Set(Some( - serde_json::to_string(&state).map_err(|e| AppError::Internal(e.to_string()))?, - )); - active.updated_at = Set(now); - active.update(&tx).await?; } tx.commit().await?; } diff --git a/crates/server/src/service/renewal_reminders.rs b/crates/server/src/service/renewal_reminders.rs index ff0e89388..b6cda279b 100644 --- a/crates/server/src/service/renewal_reminders.rs +++ b/crates/server/src/service/renewal_reminders.rs @@ -1,4 +1,4 @@ -//! Durable expiration admission for the current projected or frozen renewal occurrence. +//! Durable expiration admission for the current renewal occurrence. use crate::{ entity::{alert_rule, alert_state}, error::AppError, @@ -6,7 +6,7 @@ use crate::{ alert::{AlertRuleItem, AlertStateManager, rule_covers_server}, maintenance::MaintenanceService, mobile_alert_push, - renewal::{self, DeadlineOrigin, RenewalState}, + renewal::{self, RenewalState}, }, }; use chrono::{DateTime, Duration, Utc}; @@ -15,7 +15,7 @@ use sea_orm::{ TransactionTrait, }; -/// `None` leaves legacy confirmed-expiry rules on their existing alert path. +/// `None` leaves legacy records without an occurrence on their existing alert path. /// The writer reservation protects the selected deadline through queue admission. pub(super) async fn evaluate( db: &DatabaseConnection, @@ -29,11 +29,8 @@ pub(super) async fn evaluate( let _admission = manager.admission_lock.lock().await; let tx = db.begin().await?; let model = renewal::load_for_update(&tx, server_id).await?; + let (model, _) = renewal::advance_locked(&tx, model, now).await?; let renewal = RenewalState::from_server(&model); - if renewal.deadline_origin == DeadlineOrigin::Confirmed { - tx.commit().await?; - return Ok(None); - } let Some(occurrence) = renewal.occurrence_id else { tx.commit().await?; return Ok(None); @@ -49,17 +46,40 @@ pub(super) async fn evaluate( return Ok(Some(false)); }; let event_key = format!("renewal:{occurrence}"); + let previous = alert_state::Entity::find() + .filter(alert_state::Column::RuleId.eq(&rule.id)) + .filter(alert_state::Column::ServerId.eq(server_id)) + .filter(alert_state::Column::EventKey.like("renewal:%")) + .filter(alert_state::Column::EventKey.ne(&event_key)) + .filter(alert_state::Column::Resolved.eq(false)) + .all(&tx) + .await?; + let mut archived = Vec::new(); + for previous in previous { + let mut active: alert_state::ActiveModel = previous.into(); + active.resolved = Set(true); + // No recovery occurred. Keep the original trigger cycle available for + // notification detail and mark this target as silently superseded. + active.resolved_at = Set(None); + active.updated_at = Set(now); + archived.push(active.update(&tx).await?); + } let matched = other_conditions && items .iter() .filter(|item| item.rule_type == "expiration") .all(|item| { - model.expired_at.is_some_and(|deadline| { - deadline <= now + Duration::days(item.duration.unwrap_or(7) as i64) - }) + renewal::selected_date(model.expired_at, &renewal.billing_timezone) + .zip(renewal::selected_date(Some(now), &renewal.billing_timezone)) + .is_some_and(|(date, today)| { + (date - today).num_days() <= i64::from(item.duration.unwrap_or(7)) + }) }); if !matched || MaintenanceService::is_in_maintenance_at(&tx, server_id, now).await? { tx.commit().await?; + for row in &archived { + manager.publish_state(row); + } return Ok(Some(false)); } let existing = alert_state::Entity::find() @@ -73,6 +93,9 @@ pub(super) async fn evaluate( }); if !should_notify { tx.commit().await?; + for row in &archived { + manager.publish_state(row); + } return Ok(Some(false)); } let row = if let Some(previous) = existing { @@ -102,6 +125,9 @@ pub(super) async fn evaluate( }; mobile_alert_push::enqueue(&tx, &rule, &row, &model.name).await?; tx.commit().await?; + for row in &archived { + manager.publish_state(row); + } manager.publish_state(&row); Ok(Some(true)) } diff --git a/crates/server/tests/renewal_reminders.rs b/crates/server/tests/renewal_reminders.rs index 4c3012e55..7fd1c2902 100644 --- a/crates/server/tests/renewal_reminders.rs +++ b/crates/server/tests/renewal_reminders.rs @@ -79,3 +79,174 @@ async fn once_reminder_rearms_for_next_month_even_when_sixty_day_condition_stays .all(|event| event["rule_id"] == rule) ); } + +#[tokio::test] +async fn explicit_confirmed_dates_each_admit_once_even_when_reminder_window_stays_true() { + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (base, _tmp, state) = common::start_test_server_with_renewal_clock(100, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, _) = configure(&admin, &base, 60).await; + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":false,"expiry_date":"2026-11-15"}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + tick(&state).await; + let first = get(&admin, &base, "alert-events").await; + assert_eq!(first.as_array().unwrap().len(), 1); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"expiry_date":"2026-11-30"}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + tick(&state).await; + let events = get(&admin, &base, "alert-events").await; + assert_eq!( + events.as_array().unwrap().len(), + 2, + "operator-confirmed current dates also carry independent renewal occurrences" + ); +} + +#[tokio::test] +async fn automatic_rollover_supersedes_previous_alert_without_a_recovery_claim() { + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (base, _tmp, state) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (_, rule) = configure(&admin, &base, 60).await; + tick(&state).await; + let before = get(&admin, &base, "alert-events").await; + let key = before[0]["alert_key"].as_str().unwrap().to_string(); + clock.set("2026-11-01T04:00:00Z"); + tick(&state).await; + let detail = get(&admin, &base, &format!("alert-events/{key}")).await; + assert_eq!( + detail["status"], "superseded", + "advancement is a new reminder target, never service recovery" + ); + assert!(detail["resolved_at"].is_null()); + assert!(!detail["message"].as_str().unwrap().contains("resolved")); + let states = get(&admin, &base, &format!("alert-rules/{rule}/states")).await; + assert_eq!( + states + .as_array() + .unwrap() + .iter() + .filter(|row| row["status"] == "superseded") + .count(), + 1 + ); +} + +#[tokio::test] +async fn zero_day_reminder_is_eligible_through_the_complete_local_expiry_date() { + let clock = ManualClock::at("2026-10-31T03:59:59Z"); + let (base, _tmp, state) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, _) = configure(&admin, &base, 0).await; + tick(&state).await; + assert!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .is_empty() + ); + clock.set("2026-10-31T04:00:00Z"); + tick(&state).await; + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1, + "zero-day is eligible at the beginning of the billing timezone's expiry date" + ); + clock.set("2026-11-01T03:59:59.999999999Z"); + tick(&state).await; + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["expiry_date"], + "2026-10-31" + ); + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1 + ); + clock.set("2026-11-01T04:00:00Z"); + tick(&state).await; + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["expiry_date"], + "2026-11-30" + ); + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1, + "rollover does not invent another reminder outside the new window" + ); + clock.set("2026-11-30T05:00:00Z"); + tick(&state).await; + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 2, + "the next local expiry date remains eligible after the DST change" + ); +} + +#[tokio::test] +async fn production_reminder_evaluation_catches_up_inside_its_admission_snapshot() { + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (base, _tmp, state) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, _) = configure(&admin, &base, 60).await; + clock.set("2027-07-13T12:00:00Z"); + // The same production alert entry point must select/advance/admit atomically, + // rather than relying on a separately committed, earlier scheduler read. + serverbee_server::service::alert::AlertService::evaluate_all_at( + &state.db, + &state.config, + &state.agent_manager, + &state.alert_state_manager, + clock.now(), + ) + .await + .unwrap(); + let model = get(&admin, &base, &format!("servers/{id}")).await; + assert_eq!( + model["renewal"]["expiry_date"], "2027-07-31", + "only the current anchored occurrence can be admitted after downtime" + ); + let events = get(&admin, &base, "alert-events").await; + assert_eq!( + events.as_array().unwrap().len(), + 1, + "no historical reminder backlog" + ); + assert_eq!( + model["renewal"]["confirmed_expired_at"], + "2026-11-01T03:59:59.999999999Z" + ); +} From d133d03980a3104471aee2eaf7df08759a85bdde Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 20:03:25 +0000 Subject: [PATCH 31/40] fix(web): preserve renewal edit intent during catalog updates --- .../components/server/server-edit-dialog.tsx | 18 +++-- .../server/server-edit-renewal.test.tsx | 81 ++++++++++++++++++- 2 files changed, 93 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/server/server-edit-dialog.tsx b/apps/web/src/components/server/server-edit-dialog.tsx index a4b25b909..9b14498ef 100644 --- a/apps/web/src/components/server/server-edit-dialog.tsx +++ b/apps/web/src/components/server/server-edit-dialog.tsx @@ -444,8 +444,14 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser // override; otherwise we leave it blank and surface the auto-detected value as // a hint, so saving an untouched form never accidentally pins GeoIP. const initialCountryCode = server.geo_manual ? (server.country_code ?? '') : '' - const initialExpiryDate = serverEditStateFromServer(server).expiredAt - const initialBillingTimezone = server.renewal?.billing_timezone ?? 'UTC' + // The draft belongs to the snapshot opened in this dialog. Catalog refreshes + // may advance the deadline while it stays open; they must not turn untouched + // draft fields into explicit renewal edits. + const [initialRenewal] = useState(() => ({ + expiryDate: serverEditStateFromServer(server).expiredAt, + billingTimezone: server.renewal?.billing_timezone ?? 'UTC', + enabled: server.renewal?.enabled ?? false + })) const [state, dispatch] = useReducer(serverEditReducer, server, serverEditStateFromServer) const invalidAutomaticRenewal = state.automaticRenewal && !hasAutomaticRenewalPrerequisites(state) @@ -470,9 +476,11 @@ function ServerEditDialogContent({ server, onClose }: { onClose: () => void; ser const buildPayload = (): UpdateServerInput => { const renewal = { - ...(state.automaticRenewal !== (server.renewal?.enabled ?? false) && { enabled: state.automaticRenewal }), - ...(state.expiredAt !== initialExpiryDate && { expiry_date: state.expiredAt || null }), - ...(state.billingTimezone !== initialBillingTimezone && { billing_timezone: state.billingTimezone || null }) + ...(state.automaticRenewal !== initialRenewal.enabled && { enabled: state.automaticRenewal }), + ...(state.expiredAt !== initialRenewal.expiryDate && { expiry_date: state.expiredAt || null }), + ...(state.billingTimezone !== initialRenewal.billingTimezone && { + billing_timezone: state.billingTimezone || null + }) } const payload: UpdateServerInput = { name: state.name, diff --git a/apps/web/src/components/server/server-edit-renewal.test.tsx b/apps/web/src/components/server/server-edit-renewal.test.tsx index dfb8f7681..56a9bdc57 100644 --- a/apps/web/src/components/server/server-edit-renewal.test.tsx +++ b/apps/web/src/components/server/server-edit-renewal.test.tsx @@ -56,11 +56,21 @@ const server = { function renderEditor(value: ServerResponse = server) { const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) - return render( + const view = render( ) + return { + ...view, + updateServer(updated: ServerResponse) { + view.rerender( + + + + ) + } + } } beforeEach(() => { @@ -75,6 +85,75 @@ afterEach(async () => { }) describe('server renewal date editing', () => { + it('does not confirm the previous deadline when the catalog advances while the editor stays open', async () => { + const original = { ...server, renewal: { ...server.renewal, enabled: true } } + const editor = renderEditor(original) + editor.updateServer({ + ...original, + expired_at: '2026-04-09T03:59:59Z', + renewal: { ...original.renewal, expiry_date: '2026-04-08', occurrence_id: 'occurrence-2' } + }) + fireEvent.change(screen.getByRole('textbox', { name: 'Name' }), { target: { value: 'Renamed after advancement' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).toMatchObject({ name: 'Renamed after advancement' }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('expired_at') + }) + + it('preserves explicit date, timezone and switch edits across a catalog refresh', async () => { + const original = { ...server, renewal: { ...server.renewal, enabled: true } } + const editor = renderEditor(original) + fireEvent.change(screen.getByLabelText('Expiration date'), { target: { value: '2026-03-10' } }) + fireEvent.change(screen.getByLabelText('Billing timezone'), { target: { value: 'Asia/Tokyo' } }) + fireEvent.click(screen.getByRole('switch', { name: 'Automatic renewal tracking' })) + editor.updateServer({ + ...original, + expired_at: '2026-04-09T03:59:59Z', + renewal: { ...original.renewal, expiry_date: '2026-04-08', occurrence_id: 'occurrence-2' } + }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1].renewal).toEqual({ + enabled: false, + expiry_date: '2026-03-10', + billing_timezone: 'Asia/Tokyo' + }) + }) + + it('omits restored renewal fields even when live props now have a different date, timezone and switch', async () => { + const original = { ...server, renewal: { ...server.renewal, enabled: true } } + const editor = renderEditor(original) + const date = screen.getByLabelText('Expiration date') + const timezone = screen.getByLabelText('Billing timezone') + const automatic = screen.getByRole('switch', { name: 'Automatic renewal tracking' }) + fireEvent.change(date, { target: { value: '2026-03-10' } }) + fireEvent.change(date, { target: { value: '2026-03-08' } }) + fireEvent.change(timezone, { target: { value: 'Asia/Tokyo' } }) + fireEvent.change(timezone, { target: { value: 'America/New_York' } }) + fireEvent.click(automatic) + fireEvent.click(automatic) + editor.updateServer({ + ...original, + expired_at: '2026-04-08T14:59:59Z', + renewal: { + ...original.renewal, + enabled: false, + billing_timezone: 'Asia/Tokyo', + expiry_date: '2026-04-08', + occurrence_id: 'occurrence-2' + } + }) + fireEvent.change(screen.getByRole('spinbutton', { name: 'Price' }), { target: { value: '15' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(apiBoundary.put).toHaveBeenCalled()) + expect(apiBoundary.put.mock.calls[0][1]).toMatchObject({ price: 15 }) + expect(apiBoundary.put.mock.calls[0][1]).not.toHaveProperty('renewal') + }) + it('does not confirm a clamped projection after restoring its selected date', async () => { renderEditor({ ...server, From 2510b8edb5859016cdd09cb7445d42ca770c7f93 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 20:13:46 +0000 Subject: [PATCH 32/40] feat(renewal): refresh committed occurrence alerts and retain exact history --- CHANGELOG.md | 2 + apps/docs/content/docs/en/alerts.mdx | 8 + apps/docs/content/docs/zh/alerts.mdx | 8 + crates/common/src/protocol.rs | 163 ++++++-- crates/server/src/router/api/server.rs | 16 +- crates/server/src/service/alert.rs | 42 +- crates/server/src/service/renewal.rs | 17 +- .../server/src/service/renewal_reminders.rs | 121 ++++-- crates/server/src/task/alert_evaluator.rs | 19 +- .../server/tests/mobile_push_integration.rs | 72 +++- crates/server/tests/renewal_reminders.rs | 390 ++++++++++++++++++ 11 files changed, 762 insertions(+), 96 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d94751648..5405c92e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Renewal reminders follow each current occurrence** -- Expiration rules in once mode admit one durable reminder per rule, server and renewal occurrence, including consecutive monthly deadlines inside the same reminder window. Automatic calendar advancement silently supersedes old targets, and authenticated Web and native iOS views refresh deadlines, alert history and cost advisories + - **Opt-in automatic renewal tracking** -- Web and native iOS administrators can enable anchored monthly, quarterly or yearly expiry forecasts. The Server catches up after downtime while the Agent is offline, preserves confirmed expiry history and freezes the same projected deadline when tracking is disabled. Forecasts do not confirm provider renewal or payment - **Billing-calendar renewal dates** -- Web and native iOS administrators can edit a local expiry date in its stored IANA billing timezone. The Server preserves historical expiry instants on unchanged saves and applies the complete local expiry day to explicit date changes diff --git a/apps/docs/content/docs/en/alerts.mdx b/apps/docs/content/docs/en/alerts.mdx index 541bfaf49..05e07e15c 100644 --- a/apps/docs/content/docs/en/alerts.mdx +++ b/apps/docs/content/docs/en/alerts.mdx @@ -175,6 +175,14 @@ Each alert rule specifies which servers it applies to: - Sends a notification only on the **first trigger**. - No further notifications are sent until the condition recovers and triggers again. +### Renewal Expiration Reminders + +For a server with a stored renewal occurrence, an expiration rule in `once` mode sends at most one reminder for each rule, server and occurrence. A new monthly deadline can therefore send its own reminder even when a 60-day window stays continuously true. Retries, Server restart and disabling automatic tracking do not resend the same occurrence. + +The threshold uses the stored billing timezone's local expiry date. A zero-day reminder remains eligible throughout that date. Automatic tracking catches up to the current deadline after downtime without sending a backlog for missed occurrences. Previous automatic targets appear as **Superseded** in alert history; advancement sends no recovery notification and does not confirm provider renewal, payment or service availability. An explicitly edited date or a condition that stops matching can still produce the normal recovery transition. + +Authenticated Web and native iOS views refetch the Server-owned deadline, alert history and cost advisories after catalog changes and reconnects. Clients do not calculate recurring deadlines. + ### State Persistence Trigger state is persisted to the `alert_states` table in SQLite and loaded into a hot cache on startup. As a result: diff --git a/apps/docs/content/docs/zh/alerts.mdx b/apps/docs/content/docs/zh/alerts.mdx index c97956329..70d4d2ebd 100644 --- a/apps/docs/content/docs/zh/alerts.mdx +++ b/apps/docs/content/docs/zh/alerts.mdx @@ -176,6 +176,14 @@ Alerts 页面为 `capability_grant_detected`(「临时授予能力」)提供 - 仅在**首次触发**时发送通知。 - 在条件恢复并再次触发之前,不会发送后续通知。 +### 续期到期提醒 + +对于已保存续期周期标识的服务器,`once` 到期规则按规则、服务器和当前续期周期最多发送一次提醒。因此,即使 60 天提醒窗口持续满足条件,新的每月到期日仍可发送自己的提醒。重试、Server 重启或关闭自动追踪不会重复提醒同一周期。 + +到期阈值使用已保存账单时区的本地到期日期。零天提醒在该日期全天有效。停机后,自动追踪直接推进到当前到期日,不补发错过周期的历史提醒。旧的自动目标在告警历史中显示为**已替代**;日历推进不会发送恢复通知,也不代表服务商已续期、已付款或服务已恢复。明确修改日期或告警条件不再满足时,仍可发生正常的恢复转换。 + +收到目录变更或重新连接后,已认证的 Web 与原生 iOS 页面会重新获取 Server 管理的到期日、告警历史和费用建议。客户端不计算周期到期日。 + ### 状态持久化 告警触发状态会持久化到 SQLite 的 `alert_states` 表,并在启动时加载到热缓存。因此: diff --git a/crates/common/src/protocol.rs b/crates/common/src/protocol.rs index 09092397a..644138c23 100644 --- a/crates/common/src/protocol.rs +++ b/crates/common/src/protocol.rs @@ -595,6 +595,10 @@ pub enum BrowserMessage { Update { servers: Vec, }, + /// Authenticated REST catalog invalidation; private billing stays off metric frames. + ServerCatalogChanged { + server_ids: Vec, + }, ServerOnline { server_id: String, }, @@ -1364,9 +1368,15 @@ mod tests { rtt2: Some(1.456), rtt3: Some(1.678), asn: None, - ips: vec![], total_sent: None, total_recv: None, - loss_pct: None, best_ms: None, worst_ms: None, avg_ms: None, - stddev_ms: None, jitter_ms: None, + ips: vec![], + total_sent: None, + total_recv: None, + loss_pct: None, + best_ms: None, + worst_ms: None, + avg_ms: None, + stddev_ms: None, + jitter_ms: None, }, TracerouteHop { hop: 2, @@ -1376,9 +1386,15 @@ mod tests { rtt2: None, rtt3: None, asn: None, - ips: vec![], total_sent: None, total_recv: None, - loss_pct: None, best_ms: None, worst_ms: None, avg_ms: None, - stddev_ms: None, jitter_ms: None, + ips: vec![], + total_sent: None, + total_recv: None, + loss_pct: None, + best_ms: None, + worst_ms: None, + avg_ms: None, + stddev_ms: None, + jitter_ms: None, }, ], completed: true, @@ -1874,13 +1890,22 @@ mod tests { round: 1, total_rounds: 5, hops: vec![TracerouteHop { - hop: 1, ip: None, hostname: Some("hop1.example".into()), - rtt1: None, rtt2: None, rtt3: None, asn: None, + hop: 1, + ip: None, + hostname: Some("hop1.example".into()), + rtt1: None, + rtt2: None, + rtt3: None, + asn: None, ips: vec!["10.0.0.1".into()], - total_sent: Some(1), total_recv: Some(1), + total_sent: Some(1), + total_recv: Some(1), loss_pct: Some(0.0), - best_ms: Some(1.0), worst_ms: Some(1.0), avg_ms: Some(1.0), - stddev_ms: Some(0.0), jitter_ms: Some(0.0), + best_ms: Some(1.0), + worst_ms: Some(1.0), + avg_ms: Some(1.0), + stddev_ms: Some(0.0), + jitter_ms: Some(0.0), }], completed: false, error: None, @@ -1890,7 +1915,11 @@ mod tests { assert!(json.contains("\"protocol\":\"tcp\"")); let parsed: BrowserMessage = serde_json::from_str(&json).unwrap(); match parsed { - BrowserMessage::TracerouteUpdate { protocol, started_at, .. } => { + BrowserMessage::TracerouteUpdate { + protocol, + started_at, + .. + } => { assert_eq!(protocol, RecordedProtocol::Tcp); assert_eq!(started_at, 1_716_500_000_000); } @@ -1907,13 +1936,22 @@ mod tests { round: 2, total_rounds: 5, hops: vec![TracerouteHop { - hop: 1, ip: None, hostname: None, - rtt1: None, rtt2: None, rtt3: None, asn: None, + hop: 1, + ip: None, + hostname: None, + rtt1: None, + rtt2: None, + rtt3: None, + asn: None, ips: vec!["10.0.0.1".into()], - total_sent: Some(2), total_recv: Some(2), + total_sent: Some(2), + total_recv: Some(2), loss_pct: Some(0.0), - best_ms: Some(1.0), worst_ms: Some(1.2), avg_ms: Some(1.1), - stddev_ms: Some(0.1), jitter_ms: Some(0.05), + best_ms: Some(1.0), + worst_ms: Some(1.2), + avg_ms: Some(1.1), + stddev_ms: Some(0.1), + jitter_ms: Some(0.05), }], completed: false, error: None, @@ -1922,7 +1960,13 @@ mod tests { assert!(json.contains("\"type\":\"traceroute_round_update\"")); let parsed: AgentMessage = serde_json::from_str(&json).unwrap(); match parsed { - AgentMessage::TracerouteRoundUpdate { round, total_rounds, completed, hops, .. } => { + AgentMessage::TracerouteRoundUpdate { + round, + total_rounds, + completed, + hops, + .. + } => { assert_eq!(round, 2); assert_eq!(total_rounds, 5); assert!(!completed); @@ -1946,7 +1990,9 @@ mod tests { let json = serde_json::to_string(&msg).unwrap(); let parsed: AgentMessage = serde_json::from_str(&json).unwrap(); match parsed { - AgentMessage::TracerouteRoundUpdate { completed, error, .. } => { + AgentMessage::TracerouteRoundUpdate { + completed, error, .. + } => { assert!(completed); assert!(error.as_deref().unwrap().contains("privileges")); } @@ -1966,7 +2012,9 @@ mod tests { assert!(json.contains("\"protocol\":\"udp\"")); let parsed: ServerMessage = serde_json::from_str(&json).unwrap(); match parsed { - ServerMessage::Traceroute { protocol, .. } => assert_eq!(protocol, Some(TraceProtocol::Udp)), + ServerMessage::Traceroute { protocol, .. } => { + assert_eq!(protocol, Some(TraceProtocol::Udp)) + } _ => panic!("Expected Traceroute"), } } @@ -1994,7 +2042,9 @@ mod tests { hop: 1, ip: None, hostname: Some("router.local".into()), - rtt1: None, rtt2: None, rtt3: None, + rtt1: None, + rtt2: None, + rtt3: None, asn: None, ips: vec!["10.0.0.1".into()], total_sent: Some(5), @@ -2022,26 +2072,41 @@ mod tests { hop: 2, ip: Some("8.8.8.8".into()), hostname: Some("dns.google".into()), - rtt1: Some(12.0), rtt2: Some(11.8), rtt3: Some(12.3), + rtt1: Some(12.0), + rtt2: Some(11.8), + rtt3: Some(12.3), asn: Some("AS15169".into()), ips: vec![], - total_sent: None, total_recv: None, + total_sent: None, + total_recv: None, loss_pct: None, - best_ms: None, worst_ms: None, avg_ms: None, - stddev_ms: None, jitter_ms: None, + best_ms: None, + worst_ms: None, + avg_ms: None, + stddev_ms: None, + jitter_ms: None, }; let json = serde_json::to_string(&hop).unwrap(); - assert!(!json.contains("\"ips\":"), "got: {json}"); + assert!(!json.contains("\"ips\":"), "got: {json}"); assert!(!json.contains("\"total_sent\""), "got: {json}"); - assert!(!json.contains("\"loss_pct\""), "got: {json}"); + assert!(!json.contains("\"loss_pct\""), "got: {json}"); assert!(json.contains("\"rtt1\":12.0")); } #[test] fn test_trace_protocol_serializes_lowercase() { - assert_eq!(serde_json::to_string(&TraceProtocol::Icmp).unwrap(), "\"icmp\""); - assert_eq!(serde_json::to_string(&TraceProtocol::Udp).unwrap(), "\"udp\""); - assert_eq!(serde_json::to_string(&TraceProtocol::Tcp).unwrap(), "\"tcp\""); + assert_eq!( + serde_json::to_string(&TraceProtocol::Icmp).unwrap(), + "\"icmp\"" + ); + assert_eq!( + serde_json::to_string(&TraceProtocol::Udp).unwrap(), + "\"udp\"" + ); + assert_eq!( + serde_json::to_string(&TraceProtocol::Tcp).unwrap(), + "\"tcp\"" + ); } #[test] @@ -2058,15 +2123,30 @@ mod tests { #[test] fn test_recorded_protocol_serializes_lowercase_including_legacy() { - assert_eq!(serde_json::to_string(&RecordedProtocol::Icmp).unwrap(), "\"icmp\""); - assert_eq!(serde_json::to_string(&RecordedProtocol::Legacy).unwrap(), "\"legacy\""); + assert_eq!( + serde_json::to_string(&RecordedProtocol::Icmp).unwrap(), + "\"icmp\"" + ); + assert_eq!( + serde_json::to_string(&RecordedProtocol::Legacy).unwrap(), + "\"legacy\"" + ); } #[test] fn test_recorded_protocol_from_trace_protocol() { - assert_eq!(RecordedProtocol::from(TraceProtocol::Icmp), RecordedProtocol::Icmp); - assert_eq!(RecordedProtocol::from(TraceProtocol::Udp), RecordedProtocol::Udp); - assert_eq!(RecordedProtocol::from(TraceProtocol::Tcp), RecordedProtocol::Tcp); + assert_eq!( + RecordedProtocol::from(TraceProtocol::Icmp), + RecordedProtocol::Icmp + ); + assert_eq!( + RecordedProtocol::from(TraceProtocol::Udp), + RecordedProtocol::Udp + ); + assert_eq!( + RecordedProtocol::from(TraceProtocol::Tcp), + RecordedProtocol::Tcp + ); } } @@ -2080,7 +2160,11 @@ mod capability_grant_protocol_tests { occurred_at: None, msg_id: "m1".into(), capabilities: 1 | 1852, - temporary: vec![TemporaryGrant { cap: "terminal".into(), granted_at: 10, expires_at: 1810 }], + temporary: vec![TemporaryGrant { + cap: "terminal".into(), + granted_at: 10, + expires_at: 1810, + }], changes: vec![CapabilityChangeEvent { cap: "terminal".into(), action: CapabilityChangeAction::Granted, @@ -2094,7 +2178,12 @@ mod capability_grant_protocol_tests { assert!(json.contains("\"action\":\"granted\"")); let back: AgentMessage = serde_json::from_str(&json).unwrap(); match back { - AgentMessage::CapabilitiesChanged { capabilities, temporary, changes, .. } => { + AgentMessage::CapabilitiesChanged { + capabilities, + temporary, + changes, + .. + } => { assert_eq!(capabilities, 1 | 1852); assert_eq!(temporary.len(), 1); assert_eq!(changes[0].action, CapabilityChangeAction::Granted); diff --git a/crates/server/src/router/api/server.rs b/crates/server/src/router/api/server.rs index c74e0d124..961ed1fbc 100644 --- a/crates/server/src/router/api/server.rs +++ b/crates/server/src/router/api/server.rs @@ -1054,6 +1054,11 @@ async fn update_server( // longer change what the agent is allowed to do. let server = ServerService::update_server_at(&state.db, &id, input, state.renewal_clock.now()).await?; + let _ = state.browser_tx.send( + serverbee_common::protocol::BrowserMessage::ServerCatalogChanged { + server_ids: vec![id.clone()], + }, + ); let authority = state .agent_authority @@ -1718,7 +1723,9 @@ mod delete_audit_tests { async fn delete_server_writes_audit_log() { let (db, _tmp) = setup_test_db().await; insert_server(&db, "srv-del", "Doomed").await; - let state = AppState::new(db.clone(), AppConfig::default()).await.unwrap(); + let state = AppState::new(db.clone(), AppConfig::default()) + .await + .unwrap(); let res = delete_server( State(state.clone()), @@ -1734,8 +1741,7 @@ mod delete_audit_tests { assert!( logs.iter().any(|l| l.action == "server_deleted" && l.user_id == "admin-1" - && l - .detail + && l.detail .as_deref() .is_some_and(|d| d.contains("srv-del") && d.contains("Doomed"))), "expected a server_deleted audit row, got: {logs:?}" @@ -1747,7 +1753,9 @@ mod delete_audit_tests { let (db, _tmp) = setup_test_db().await; insert_server(&db, "srv-a", "A").await; insert_server(&db, "srv-b", "B").await; - let state = AppState::new(db.clone(), AppConfig::default()).await.unwrap(); + let state = AppState::new(db.clone(), AppConfig::default()) + .await + .unwrap(); let res = batch_delete( State(state.clone()), diff --git a/crates/server/src/service/alert.rs b/crates/server/src/service/alert.rs index 8ebf0e965..00cf17f68 100644 --- a/crates/server/src/service/alert.rs +++ b/crates/server/src/service/alert.rs @@ -824,7 +824,9 @@ impl AlertService { agent_manager: &AgentManager, state_manager: &AlertStateManager, ) -> Result<(), AppError> { - Self::evaluate_all_at(db, config, agent_manager, state_manager, Utc::now()).await + Self::evaluate_all_at(db, config, agent_manager, state_manager, Utc::now()) + .await + .map(|_| ()) } pub async fn evaluate_all_at( @@ -833,7 +835,7 @@ impl AlertService { agent_manager: &AgentManager, state_manager: &AlertStateManager, now: chrono::DateTime, - ) -> Result<(), AppError> { + ) -> Result, AppError> { // Event-driven conditions cannot be re-polled. Replay captured intents // before ordinary rules, including the first tick after Server restart. crate::service::alert_event_intents::replay(db, config, state_manager).await?; @@ -842,6 +844,7 @@ impl AlertService { .all(db) .await?; + let mut changed = Vec::new(); for rule in rules { // A failed event admission reserves the dimension/cycle. Do not // overwrite it with a later periodic evaluation of a mixed rule. @@ -865,13 +868,13 @@ impl AlertService { continue; } - if let Err(e) = - Self::evaluate_rule_at(db, config, agent_manager, state_manager, &rule, now).await + match Self::evaluate_rule_at(db, config, agent_manager, state_manager, &rule, now).await { - tracing::error!("Error evaluating alert rule '{}': {e}", rule.name); + Ok(mut servers) => changed.append(&mut servers), + Err(e) => tracing::error!("Error evaluating alert rule '{}': {e}", rule.name), } } - Ok(()) + Ok(changed) } #[cfg(test)] @@ -882,7 +885,9 @@ impl AlertService { state_manager: &AlertStateManager, rule: &alert_rule::Model, ) -> Result<(), AppError> { - Self::evaluate_rule_at(db, config, agent_manager, state_manager, rule, Utc::now()).await + Self::evaluate_rule_at(db, config, agent_manager, state_manager, rule, Utc::now()) + .await + .map(|_| ()) } async fn evaluate_rule_at( @@ -892,14 +897,15 @@ impl AlertService { state_manager: &AlertStateManager, rule: &alert_rule::Model, now: chrono::DateTime, - ) -> Result<(), AppError> { + ) -> Result, AppError> { let items: Vec = serde_json::from_str(&rule.rules_json).unwrap_or_default(); if items.is_empty() { - return Ok(()); + return Ok(Vec::new()); } let servers = resolve_servers(db, &rule.cover_type, &rule.server_ids_json).await?; + let mut changed = Vec::new(); for srv in &servers { if items.iter().any(|item| item.rule_type == "expiration") && !items @@ -912,7 +918,7 @@ impl AlertService { .cloned() .collect(); let matched = Self::check_server_at(db, agent_manager, &other, &srv.id, now).await; - if let Some(notify) = crate::service::renewal_reminders::evaluate( + if let Some(outcome) = crate::service::renewal_reminders::evaluate( db, state_manager, rule, @@ -923,8 +929,18 @@ impl AlertService { ) .await? { - if notify { - Self::notify_triggered(db, config, rule, &srv.id, &srv.name, now).await; + if !matches!(outcome, crate::service::renewal_reminders::Outcome::Silent) { + changed.push(srv.id.clone()); + } + match outcome { + crate::service::renewal_reminders::Outcome::Triggered => { + Self::notify_triggered(db, config, rule, &srv.id, &srv.name, now).await + } + crate::service::renewal_reminders::Outcome::Resolved => { + Self::handle_resolved(db, config, rule, &srv.id, &srv.name).await + } + crate::service::renewal_reminders::Outcome::Silent + | crate::service::renewal_reminders::Outcome::Superseded => {} } continue; } @@ -954,7 +970,7 @@ impl AlertService { } } - Ok(()) + Ok(changed) } #[cfg(test)] diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs index 5f495dcba..63b2cb885 100644 --- a/crates/server/src/service/renewal.rs +++ b/crates/server/src/service/renewal.rs @@ -408,8 +408,12 @@ pub(super) async fn advance_locked( Ok((active.update(tx).await?, true)) } -pub async fn advance_all(db: &DatabaseConnection, now: DateTime) -> Result<(), AppError> { +pub async fn advance_all( + db: &DatabaseConnection, + now: DateTime, +) -> Result, AppError> { let servers = server::Entity::find().all(db).await?; + let mut changed = Vec::new(); for candidate in servers { if !RenewalState::from_server(&candidate).enabled { continue; @@ -423,8 +427,8 @@ pub async fn advance_all(db: &DatabaseConnection, now: DateTime) -> Result< } Err(error) => return Err(error), }; - match advance_locked(&tx, model, now).await { - Ok(_) => {} + let advanced = match advance_locked(&tx, model, now).await { + Ok((_, advanced)) => advanced, Err(AppError::Validation(reason)) => { // A damaged calendar configuration cannot stop healthy schedules. // Database/transaction errors still propagate to the caller. @@ -433,8 +437,11 @@ pub async fn advance_all(db: &DatabaseConnection, now: DateTime) -> Result< continue; } Err(error) => return Err(error), - } + }; tx.commit().await?; + if advanced { + changed.push(candidate.id); + } } - Ok(()) + Ok(changed) } diff --git a/crates/server/src/service/renewal_reminders.rs b/crates/server/src/service/renewal_reminders.rs index b6cda279b..4010b45a1 100644 --- a/crates/server/src/service/renewal_reminders.rs +++ b/crates/server/src/service/renewal_reminders.rs @@ -6,7 +6,7 @@ use crate::{ alert::{AlertRuleItem, AlertStateManager, rule_covers_server}, maintenance::MaintenanceService, mobile_alert_push, - renewal::{self, RenewalState}, + renewal::{self, DeadlineOrigin, RenewalState}, }, }; use chrono::{DateTime, Duration, Utc}; @@ -17,6 +17,13 @@ use sea_orm::{ /// `None` leaves legacy records without an occurrence on their existing alert path. /// The writer reservation protects the selected deadline through queue admission. +pub(super) enum Outcome { + Silent, + Triggered, + Resolved, + Superseded, +} + pub(super) async fn evaluate( db: &DatabaseConnection, manager: &AlertStateManager, @@ -25,16 +32,12 @@ pub(super) async fn evaluate( items: &[AlertRuleItem], other_conditions: bool, now: DateTime, -) -> Result, AppError> { +) -> Result, AppError> { let _admission = manager.admission_lock.lock().await; let tx = db.begin().await?; let model = renewal::load_for_update(&tx, server_id).await?; let (model, _) = renewal::advance_locked(&tx, model, now).await?; let renewal = RenewalState::from_server(&model); - let Some(occurrence) = renewal.occurrence_id else { - tx.commit().await?; - return Ok(None); - }; let Some(rule) = alert_rule::Entity::find_by_id(&rule.id) .one(&tx) .await? @@ -43,9 +46,55 @@ pub(super) async fn evaluate( }) else { tx.commit().await?; - return Ok(Some(false)); + return Ok(Some(Outcome::Silent)); + }; + let Some(occurrence) = renewal.occurrence_id else { + // Explicitly clearing a typed date recovers its retained occurrence. + // Legacy rows still use the existing empty-event dimension below. + let previous = if model.expired_at.is_none() { + alert_state::Entity::find() + .filter(alert_state::Column::RuleId.eq(&rule.id)) + .filter(alert_state::Column::ServerId.eq(server_id)) + .filter(alert_state::Column::EventKey.like("renewal:%")) + .filter(alert_state::Column::Resolved.eq(false)) + .all(&tx) + .await? + } else { + Vec::new() + }; + let mut recovered = Vec::new(); + for previous in previous { + let mut active: alert_state::ActiveModel = previous.into(); + active.resolved = Set(true); + active.resolved_at = Set(Some(now)); + active.updated_at = Set(now); + let row = active.update(&tx).await?; + mobile_alert_push::enqueue(&tx, &rule, &row, &model.name).await?; + recovered.push(row); + } + tx.commit().await?; + for row in &recovered { + manager.publish_state(row); + } + return Ok(if recovered.is_empty() { + None + } else { + Some(Outcome::Resolved) + }); }; let event_key = format!("renewal:{occurrence}"); + let matched = other_conditions + && items + .iter() + .filter(|item| item.rule_type == "expiration") + .all(|item| { + renewal::selected_date(model.expired_at, &renewal.billing_timezone) + .zip(renewal::selected_date(Some(now), &renewal.billing_timezone)) + .is_some_and(|(date, today)| { + (date - today).num_days() <= i64::from(item.duration.unwrap_or(7)) + }) + }); + let manual_recovery = renewal.deadline_origin == DeadlineOrigin::Confirmed && !matched; let previous = alert_state::Entity::find() .filter(alert_state::Column::RuleId.eq(&rule.id)) .filter(alert_state::Column::ServerId.eq(server_id)) @@ -60,27 +109,13 @@ pub(super) async fn evaluate( active.resolved = Set(true); // No recovery occurred. Keep the original trigger cycle available for // notification detail and mark this target as silently superseded. - active.resolved_at = Set(None); + active.resolved_at = Set(manual_recovery.then_some(now)); active.updated_at = Set(now); - archived.push(active.update(&tx).await?); - } - let matched = other_conditions - && items - .iter() - .filter(|item| item.rule_type == "expiration") - .all(|item| { - renewal::selected_date(model.expired_at, &renewal.billing_timezone) - .zip(renewal::selected_date(Some(now), &renewal.billing_timezone)) - .is_some_and(|(date, today)| { - (date - today).num_days() <= i64::from(item.duration.unwrap_or(7)) - }) - }); - if !matched || MaintenanceService::is_in_maintenance_at(&tx, server_id, now).await? { - tx.commit().await?; - for row in &archived { - manager.publish_state(row); + let row = active.update(&tx).await?; + if manual_recovery { + mobile_alert_push::enqueue(&tx, &rule, &row, &model.name).await?; } - return Ok(Some(false)); + archived.push(row); } let existing = alert_state::Entity::find() .filter(alert_state::Column::RuleId.eq(&rule.id)) @@ -88,6 +123,32 @@ pub(super) async fn evaluate( .filter(alert_state::Column::EventKey.eq(&event_key)) .one(&tx) .await?; + let mut recovered = manual_recovery && !archived.is_empty(); + if !matched { + if let Some(current) = existing.as_ref().filter(|state| !state.resolved) { + let mut active: alert_state::ActiveModel = current.clone().into(); + active.resolved = Set(true); + active.resolved_at = Set(Some(now)); + active.updated_at = Set(now); + let row = active.update(&tx).await?; + mobile_alert_push::enqueue(&tx, &rule, &row, &model.name).await?; + archived.push(row); + recovered = true; + } + } + if !matched || MaintenanceService::is_in_maintenance_at(&tx, server_id, now).await? { + tx.commit().await?; + for row in &archived { + manager.publish_state(row); + } + return Ok(Some(if recovered { + Outcome::Resolved + } else if archived.is_empty() { + Outcome::Silent + } else { + Outcome::Superseded + })); + } let should_notify = existing.as_ref().is_none_or(|state| { rule.trigger_mode != "once" && now - state.last_notified_at >= Duration::minutes(5) }); @@ -96,7 +157,11 @@ pub(super) async fn evaluate( for row in &archived { manager.publish_state(row); } - return Ok(Some(false)); + return Ok(Some(if archived.is_empty() { + Outcome::Silent + } else { + Outcome::Superseded + })); } let row = if let Some(previous) = existing { let count = previous.count; @@ -129,5 +194,5 @@ pub(super) async fn evaluate( manager.publish_state(row); } manager.publish_state(&row); - Ok(Some(true)) + Ok(Some(Outcome::Triggered)) } diff --git a/crates/server/src/task/alert_evaluator.rs b/crates/server/src/task/alert_evaluator.rs index a33af643c..b033d859a 100644 --- a/crates/server/src/task/alert_evaluator.rs +++ b/crates/server/src/task/alert_evaluator.rs @@ -27,15 +27,28 @@ pub async fn run(state: Arc) { /// One production scheduler iteration, also used with a controlled renewal clock. pub async fn evaluate_once(state: &AppState) -> Result<(), crate::error::AppError> { let now = state.renewal_clock.now(); - crate::service::renewal::advance_all(&state.db, now).await?; - AlertService::evaluate_all_at( + let mut changed = crate::service::renewal::advance_all(&state.db, now).await?; + let evaluated = AlertService::evaluate_all_at( &state.db, &state.config, &state.agent_manager, &state.alert_state_manager, now, ) - .await + .await; + if let Ok(servers) = &evaluated { + changed.extend(servers.iter().cloned()); + } + changed.sort(); + changed.dedup(); + if !changed.is_empty() { + let _ = state.browser_tx.send( + serverbee_common::protocol::BrowserMessage::ServerCatalogChanged { + server_ids: changed, + }, + ); + } + evaluated.map(|_| ()) } /// Performs the per-tick work of the alert evaluator: evaluate all enabled diff --git a/crates/server/tests/mobile_push_integration.rs b/crates/server/tests/mobile_push_integration.rs index fbc32b503..67bf5aa17 100644 --- a/crates/server/tests/mobile_push_integration.rs +++ b/crates/server/tests/mobile_push_integration.rs @@ -3050,30 +3050,90 @@ async fn alert_subscriptions_fan_out_trigger_recovery_without_group_and_open_exa assert_eq!(alert_jobs(&restarted).await.len(), 6); set_alert_expiration(&client, &base, admin, &server, true).await; evaluate_alerts(&restarted).await; + let previous = client + .get(format!("{base}/api/alert-events/{key}")) + .bearer_auth(admin) + .send() + .await + .unwrap(); + assert_eq!( + previous.status(), + 200, + "An admitted renewal occurrence retains its own durable detail" + ); + let previous = previous.json::().await.unwrap()["data"].clone(); + assert_eq!(previous["alert_key"], key); + assert_eq!( + previous["first_triggered_at"], detail["data"]["first_triggered_at"], + "The old key preserves its original trigger cycle" + ); + assert_eq!( + previous["status"], "resolved", + "An old key cannot open the new firing occurrence" + ); + assert!(!previous["resolved_at"].is_null()); + assert_eq!( + alert_jobs(&restarted).await.len(), + 9, + "Each new occurrence reaches the same three subscribed recipients" + ); + let current = client + .get(format!("{base}/api/alert-events")) + .bearer_auth(admin) + .send() + .await + .unwrap() + .json::() + .await + .unwrap(); + let current = current["data"] + .as_array() + .unwrap() + .iter() + .find(|event| event["status"] == "firing") + .unwrap(); + assert_ne!( + current["alert_key"], key, + "Each occurrence binds a distinct complete-cycle key" + ); + let current_key = current["alert_key"].as_str().unwrap().to_string(); + let current_detail = client + .get(format!("{base}/api/alert-events/{current_key}")) + .bearer_auth(admin) + .send() + .await + .unwrap(); + assert_eq!(current_detail.status(), 200); + let current_detail = current_detail.json::().await.unwrap()["data"].clone(); + assert_eq!(current_detail["alert_key"], current_key); + assert_eq!(current_detail["status"], "firing"); + assert_ne!( + current_detail["first_triggered_at"], + previous["first_triggered_at"] + ); assert_eq!( client - .get(format!("{base}/api/alert-events/{key}")) + .delete(format!("{base}/api/alert-rules/{rule}")) .bearer_auth(admin) .send() .await .unwrap() .status(), - 404, - "Old cycle cannot open the new cycle" + 200 ); assert_eq!( client - .delete(format!("{base}/api/alert-rules/{rule}")) + .get(format!("{base}/api/alert-events/{key}")) .bearer_auth(admin) .send() .await .unwrap() .status(), - 200 + 404 ); assert_eq!( client - .get(format!("{base}/api/alert-events/{key}")) + .get(format!("{base}/api/alert-events/{current_key}")) .bearer_auth(admin) .send() .await diff --git a/crates/server/tests/renewal_reminders.rs b/crates/server/tests/renewal_reminders.rs index 7fd1c2902..856b70e78 100644 --- a/crates/server/tests/renewal_reminders.rs +++ b/crates/server/tests/renewal_reminders.rs @@ -250,3 +250,393 @@ async fn production_reminder_evaluation_catches_up_inside_its_admission_snapshot "2026-11-01T03:59:59.999999999Z" ); } + +async fn reopen( + tmp: &tempfile::TempDir, + clock: Arc, + config: serverbee_server::config::AppConfig, +) -> (String, Arc) { + use sea_orm_migration::MigratorTrait; + use sqlx::{ + ConnectOptions as _, + sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous}, + }; + let options = SqliteConnectOptions::new() + .filename(tmp.path().join("test.db")) + .create_if_missing(true) + .journal_mode(SqliteJournalMode::Wal) + .synchronous(SqliteSynchronous::Normal) + .foreign_keys(true) + .busy_timeout(std::time::Duration::from_secs(5)) + .disable_statement_logging(); + let pool = SqlitePoolOptions::new() + .max_connections(5) + .connect_with(options) + .await + .unwrap(); + let db = sea_orm::SqlxSqliteConnector::from_sqlx_sqlite_pool(pool); + serverbee_server::migration::Migrator::up(&db, None) + .await + .unwrap(); + let state = AppState::new_with_renewal_clock(db, config, clock) + .await + .unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let router = serverbee_server::router::create_router(state.clone()); + tokio::spawn(async move { + axum::serve( + listener, + router.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); + }); + (base, state) +} + +#[tokio::test] +async fn retries_concurrent_owners_database_reopen_and_freeze_keep_one_admission_per_occurrence() { + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (base, tmp, state) = common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, _) = configure(&admin, &base, 60).await; + let (second_base, second) = reopen(&tmp, clock.clone(), state.config.clone()).await; + tokio::join!(tick(&state), tick(&second)); + tick(&state).await; + let first = get(&admin, &base, "alert-events").await; + assert_eq!(first.as_array().unwrap().len(), 1); + assert_eq!(first[0]["count"], 1); + clock.set("2026-11-01T04:00:00Z"); + tokio::join!(tick(&second), tick(&state)); + let model = get(&admin, &second_base, &format!("servers/{id}")).await; + let response = admin + .put(format!("{second_base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":false}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let frozen = get(&admin, &base, &format!("servers/{id}")).await; + assert_eq!( + model["renewal"]["occurrence_id"], + frozen["renewal"]["occurrence_id"] + ); + let (third_base, third) = reopen(&tmp, clock, state.config.clone()).await; + tokio::join!(tick(&third), tick(&state), tick(&second)); + let events = get(&admin, &third_base, "alert-events").await; + assert_eq!(events.as_array().unwrap().len(), 2); + assert!( + events + .as_array() + .unwrap() + .iter() + .all(|event| event["count"] == 1) + ); + assert!( + events + .as_array() + .unwrap() + .iter() + .any(|event| event["alert_key"] == first[0]["alert_key"]) + ); +} + +async fn register_encrypted_alerts(admin: &reqwest::Client, base: &str) { + let response = admin.post(format!("{base}/api/mobile/auth/login")) + .json(&json!({"username":"admin","password":"testpass","installation_id":"renewal-test-install","device_name":"isolated fixture"})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let body: Value = response.json().await.unwrap(); + let token = body["data"]["access_token"].as_str().unwrap(); + let response = admin.put(format!("{base}/api/mobile/push/settings")).bearer_auth(token) + .json(&json!({"expected_revision":0,"preferences":{"enabled":true,"alerts":true,"security":false,"task_success":false,"task_failure":false}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let response = admin.post(format!("{base}/api/mobile/push/encrypted-register")).bearer_auth(token) + .json(&json!({"expected_revision":1,"device_token":"a".repeat(64),"environment":"sandbox", + "content_key_id":"22222222-2222-4222-8222-222222222222","content_key":"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=","deployment_id":"https://serverbee.test"})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); +} +async fn jobs(state: &AppState) -> Vec { + use sea_orm::EntityTrait; + serverbee_server::entity::mobile_push_outbox::Entity::find() + .all(&state.db) + .await + .unwrap() +} +async fn admit_direct(state: &AppState, now: DateTime) { + serverbee_server::service::alert::AlertService::evaluate_all_at( + &state.db, + &state.config, + &state.agent_manager, + &state.alert_state_manager, + now, + ) + .await + .unwrap(); +} +#[tokio::test] +async fn encrypted_queue_fault_rolls_back_calendar_and_admission_then_retry_and_reopen_are_deduplicated() + { + use sea_orm::ConnectionTrait; + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (_base, tmp, initial) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let mut config = initial.config.clone(); + config.push_relay.url = "https://unused-fixture-relay.invalid".into(); + let (base, state) = reopen(&tmp, clock.clone(), config).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, _) = configure(&admin, &base, 60).await; + register_encrypted_alerts(&admin, &base).await; + state.db.execute_unprepared("CREATE TRIGGER renewal_queue_failure BEFORE INSERT ON mobile_push_outbox BEGIN SELECT RAISE(FAIL,'isolated admission fault'); END").await.unwrap(); + clock.set("2026-11-01T04:00:00Z"); + admit_direct(&state, clock.now()).await; + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["expiry_date"], + "2026-10-31", + "failed queue admission cannot commit the calendar snapshot" + ); + assert!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .is_empty() + ); + assert!(jobs(&state).await.is_empty()); + state + .db + .execute_unprepared("DROP TRIGGER renewal_queue_failure") + .await + .unwrap(); + admit_direct(&state, clock.now()).await; + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["expiry_date"], + "2026-11-30" + ); + let original = jobs(&state).await; + assert_eq!(original.len(), 1); + let envelope = original[0].envelope.as_ref().unwrap(); + for forbidden in [ + "offline-renewal-reminder", + "renewal reminder", + "server_id", + "content_key", + ] { + assert!(!envelope.contains(forbidden)); + } + let (next_base, next) = reopen(&tmp, clock.clone(), state.config.clone()).await; + tokio::join!( + admit_direct(&state, clock.now()), + admit_direct(&next, clock.now()) + ); + assert_eq!(jobs(&next).await, original); + assert_eq!( + get(&admin, &next_base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1 + ); +} + +#[tokio::test] +async fn authenticated_catalog_signal_refetches_current_deadline_after_advancement_and_edits() { + use futures_util::StreamExt; + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (base, _tmp, state) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, _) = configure(&admin, &base, 60).await; + let response = admin + .post(format!("{base}/api/auth/api-keys")) + .json(&json!({"name":"isolated catalog reader"})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let key: Value = response.json().await.unwrap(); + let ws_url = format!("{}/api/ws/servers", base.replace("http://", "ws://")); + assert!( + matches!(tokio_tungstenite::connect_async(&ws_url).await, Err(tokio_tungstenite::tungstenite::Error::Http(response)) if response.status() == 401) + ); + let mut request = ws_url.into_client_request().unwrap(); + request.headers_mut().insert( + "x-api-key", + key["data"]["key"].as_str().unwrap().parse().unwrap(), + ); + let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + let frame = socket.next().await.unwrap().unwrap(); + let full_sync: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_eq!(full_sync["type"], "full_sync"); + for server in full_sync["servers"].as_array().unwrap() { + for private in ["expired_at", "renewal", "price", "billing_cycle"] { + assert!(server.get(private).is_none()); + } + } + clock.set("2026-11-01T04:00:00Z"); + tick(&state).await; + let frame = tokio::time::timeout(std::time::Duration::from_secs(1), socket.next()) + .await + .expect("automatic advancement must invalidate authenticated REST catalog readers") + .unwrap() + .unwrap(); + let changed: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_eq!( + changed, + json!({"type":"server_catalog_changed","server_ids":[id]}) + ); + let detail = get(&admin, &base, &format!("servers/{id}")).await; + let list = get(&admin, &base, "servers").await; + assert_eq!(detail["renewal"]["expiry_date"], "2026-11-30"); + assert_eq!( + list.as_array() + .unwrap() + .iter() + .find(|row| row["id"] == id) + .unwrap()["expired_at"], + detail["expired_at"] + ); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":false,"expiry_date":"2026-12-31"}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let frame = tokio::time::timeout(std::time::Duration::from_secs(1), socket.next()) + .await + .expect("renewal edits must invalidate authenticated catalog readers") + .unwrap() + .unwrap(); + let changed: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_eq!( + changed, + json!({"type":"server_catalog_changed","server_ids":[id]}) + ); + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["expiry_date"], + "2026-12-31" + ); + tick(&state).await; + let frame = tokio::time::timeout(std::time::Duration::from_secs(1), socket.next()) + .await + .expect("committed reminder retargeting must refresh earlier cached alert occurrences") + .unwrap() + .unwrap(); + let changed: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_eq!( + changed, + json!({"type":"server_catalog_changed","server_ids":[id]}) + ); + let events = get(&admin, &base, "alert-events").await; + assert_eq!( + events + .as_array() + .unwrap() + .iter() + .filter(|row| row["status"] == "firing") + .count(), + 1 + ); + assert_eq!( + events + .as_array() + .unwrap() + .iter() + .filter(|row| row["status"] == "superseded") + .count(), + 1 + ); +} + +#[tokio::test] +async fn current_occurrence_resolves_when_expiration_condition_is_edited_false() { + let clock = ManualClock::at("2026-10-30T12:00:00Z"); + let (base, _tmp, state) = common::start_test_server_with_renewal_clock(100, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, rule) = configure(&admin, &base, 60).await; + tick(&state).await; + let events = get(&admin, &base, "alert-events").await; + let key = events[0]["alert_key"].as_str().unwrap(); + let occurrence = + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["occurrence_id"].clone(); + let response = admin + .put(format!("{base}/api/alert-rules/{rule}")) + .json(&json!({"rules":[{"rule_type":"expiration","duration":0}]})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + tick(&state).await; + let detail = get(&admin, &base, &format!("alert-events/{key}")).await; + assert_eq!( + detail["status"], "resolved", + "a false condition still recovers the current occurrence" + ); + assert!(detail["resolved_at"].is_string()); + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["occurrence_id"], + occurrence + ); + let response = admin + .put(format!("{base}/api/alert-rules/{rule}")) + .json(&json!({"rules":[{"rule_type":"expiration","duration":60}]})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + tick(&state).await; + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1, + "once remains consumed for the same occurrence" + ); +} + +#[tokio::test] +async fn explicitly_clearing_expiry_resolves_its_retained_occurrence() { + let clock = ManualClock::at("2026-10-31T12:00:00Z"); + let (base, _tmp, state) = common::start_test_server_with_renewal_clock(100, clock).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, _) = configure(&admin, &base, 60).await; + tick(&state).await; + let events = get(&admin, &base, "alert-events").await; + let key = events[0]["alert_key"].as_str().unwrap(); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":false,"expiry_date":null}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + tick(&state).await; + let detail = get(&admin, &base, &format!("alert-events/{key}")).await; + assert_eq!( + detail["status"], "resolved", + "an explicit cleared date cannot leave its old occurrence firing" + ); + assert!(detail["resolved_at"].is_string()); + assert!(get(&admin, &base, &format!("servers/{id}")).await["expired_at"].is_null()); + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1 + ); +} From 8dac94d4ed635af6b5dca85569d03110690d30d0 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 20:30:49 +0000 Subject: [PATCH 33/40] fix(renewal): preserve consumed legacy reminders and recovery cycles --- apps/web/openapi.json | 3 + apps/web/src/lib/api-types.ts | 1 + crates/common/src/protocol.rs | 159 +++---------- crates/server/src/router/api/server.rs | 10 +- crates/server/src/service/alert.rs | 9 + .../server/src/service/renewal_reminders.rs | 72 +++++- crates/server/src/service/server.rs | 32 +++ .../server/tests/mobile_push_integration.rs | 112 +++++++++- crates/server/tests/renewal_reminders.rs | 210 ++++++++++++++++++ 9 files changed, 473 insertions(+), 135 deletions(-) diff --git a/apps/web/openapi.json b/apps/web/openapi.json index 7e22d57ef..71c44d1cd 100644 --- a/apps/web/openapi.json +++ b/apps/web/openapi.json @@ -8674,6 +8674,9 @@ }, "server_name": { "type": "string" + }, + "status": { + "type": "string" } } }, diff --git a/apps/web/src/lib/api-types.ts b/apps/web/src/lib/api-types.ts index b609e3afd..f645b4668 100644 --- a/apps/web/src/lib/api-types.ts +++ b/apps/web/src/lib/api-types.ts @@ -2442,6 +2442,7 @@ export interface components { resolved_at?: string | null; server_id: string; server_name: string; + status?: string; }; ApiKeyResponse: { created_at: string; diff --git a/crates/common/src/protocol.rs b/crates/common/src/protocol.rs index 644138c23..a762c102a 100644 --- a/crates/common/src/protocol.rs +++ b/crates/common/src/protocol.rs @@ -1368,15 +1368,9 @@ mod tests { rtt2: Some(1.456), rtt3: Some(1.678), asn: None, - ips: vec![], - total_sent: None, - total_recv: None, - loss_pct: None, - best_ms: None, - worst_ms: None, - avg_ms: None, - stddev_ms: None, - jitter_ms: None, + ips: vec![], total_sent: None, total_recv: None, + loss_pct: None, best_ms: None, worst_ms: None, avg_ms: None, + stddev_ms: None, jitter_ms: None, }, TracerouteHop { hop: 2, @@ -1386,15 +1380,9 @@ mod tests { rtt2: None, rtt3: None, asn: None, - ips: vec![], - total_sent: None, - total_recv: None, - loss_pct: None, - best_ms: None, - worst_ms: None, - avg_ms: None, - stddev_ms: None, - jitter_ms: None, + ips: vec![], total_sent: None, total_recv: None, + loss_pct: None, best_ms: None, worst_ms: None, avg_ms: None, + stddev_ms: None, jitter_ms: None, }, ], completed: true, @@ -1890,22 +1878,13 @@ mod tests { round: 1, total_rounds: 5, hops: vec![TracerouteHop { - hop: 1, - ip: None, - hostname: Some("hop1.example".into()), - rtt1: None, - rtt2: None, - rtt3: None, - asn: None, + hop: 1, ip: None, hostname: Some("hop1.example".into()), + rtt1: None, rtt2: None, rtt3: None, asn: None, ips: vec!["10.0.0.1".into()], - total_sent: Some(1), - total_recv: Some(1), + total_sent: Some(1), total_recv: Some(1), loss_pct: Some(0.0), - best_ms: Some(1.0), - worst_ms: Some(1.0), - avg_ms: Some(1.0), - stddev_ms: Some(0.0), - jitter_ms: Some(0.0), + best_ms: Some(1.0), worst_ms: Some(1.0), avg_ms: Some(1.0), + stddev_ms: Some(0.0), jitter_ms: Some(0.0), }], completed: false, error: None, @@ -1915,11 +1894,7 @@ mod tests { assert!(json.contains("\"protocol\":\"tcp\"")); let parsed: BrowserMessage = serde_json::from_str(&json).unwrap(); match parsed { - BrowserMessage::TracerouteUpdate { - protocol, - started_at, - .. - } => { + BrowserMessage::TracerouteUpdate { protocol, started_at, .. } => { assert_eq!(protocol, RecordedProtocol::Tcp); assert_eq!(started_at, 1_716_500_000_000); } @@ -1936,22 +1911,13 @@ mod tests { round: 2, total_rounds: 5, hops: vec![TracerouteHop { - hop: 1, - ip: None, - hostname: None, - rtt1: None, - rtt2: None, - rtt3: None, - asn: None, + hop: 1, ip: None, hostname: None, + rtt1: None, rtt2: None, rtt3: None, asn: None, ips: vec!["10.0.0.1".into()], - total_sent: Some(2), - total_recv: Some(2), + total_sent: Some(2), total_recv: Some(2), loss_pct: Some(0.0), - best_ms: Some(1.0), - worst_ms: Some(1.2), - avg_ms: Some(1.1), - stddev_ms: Some(0.1), - jitter_ms: Some(0.05), + best_ms: Some(1.0), worst_ms: Some(1.2), avg_ms: Some(1.1), + stddev_ms: Some(0.1), jitter_ms: Some(0.05), }], completed: false, error: None, @@ -1960,13 +1926,7 @@ mod tests { assert!(json.contains("\"type\":\"traceroute_round_update\"")); let parsed: AgentMessage = serde_json::from_str(&json).unwrap(); match parsed { - AgentMessage::TracerouteRoundUpdate { - round, - total_rounds, - completed, - hops, - .. - } => { + AgentMessage::TracerouteRoundUpdate { round, total_rounds, completed, hops, .. } => { assert_eq!(round, 2); assert_eq!(total_rounds, 5); assert!(!completed); @@ -1990,9 +1950,7 @@ mod tests { let json = serde_json::to_string(&msg).unwrap(); let parsed: AgentMessage = serde_json::from_str(&json).unwrap(); match parsed { - AgentMessage::TracerouteRoundUpdate { - completed, error, .. - } => { + AgentMessage::TracerouteRoundUpdate { completed, error, .. } => { assert!(completed); assert!(error.as_deref().unwrap().contains("privileges")); } @@ -2012,9 +1970,7 @@ mod tests { assert!(json.contains("\"protocol\":\"udp\"")); let parsed: ServerMessage = serde_json::from_str(&json).unwrap(); match parsed { - ServerMessage::Traceroute { protocol, .. } => { - assert_eq!(protocol, Some(TraceProtocol::Udp)) - } + ServerMessage::Traceroute { protocol, .. } => assert_eq!(protocol, Some(TraceProtocol::Udp)), _ => panic!("Expected Traceroute"), } } @@ -2042,9 +1998,7 @@ mod tests { hop: 1, ip: None, hostname: Some("router.local".into()), - rtt1: None, - rtt2: None, - rtt3: None, + rtt1: None, rtt2: None, rtt3: None, asn: None, ips: vec!["10.0.0.1".into()], total_sent: Some(5), @@ -2072,41 +2026,26 @@ mod tests { hop: 2, ip: Some("8.8.8.8".into()), hostname: Some("dns.google".into()), - rtt1: Some(12.0), - rtt2: Some(11.8), - rtt3: Some(12.3), + rtt1: Some(12.0), rtt2: Some(11.8), rtt3: Some(12.3), asn: Some("AS15169".into()), ips: vec![], - total_sent: None, - total_recv: None, + total_sent: None, total_recv: None, loss_pct: None, - best_ms: None, - worst_ms: None, - avg_ms: None, - stddev_ms: None, - jitter_ms: None, + best_ms: None, worst_ms: None, avg_ms: None, + stddev_ms: None, jitter_ms: None, }; let json = serde_json::to_string(&hop).unwrap(); - assert!(!json.contains("\"ips\":"), "got: {json}"); + assert!(!json.contains("\"ips\":"), "got: {json}"); assert!(!json.contains("\"total_sent\""), "got: {json}"); - assert!(!json.contains("\"loss_pct\""), "got: {json}"); + assert!(!json.contains("\"loss_pct\""), "got: {json}"); assert!(json.contains("\"rtt1\":12.0")); } #[test] fn test_trace_protocol_serializes_lowercase() { - assert_eq!( - serde_json::to_string(&TraceProtocol::Icmp).unwrap(), - "\"icmp\"" - ); - assert_eq!( - serde_json::to_string(&TraceProtocol::Udp).unwrap(), - "\"udp\"" - ); - assert_eq!( - serde_json::to_string(&TraceProtocol::Tcp).unwrap(), - "\"tcp\"" - ); + assert_eq!(serde_json::to_string(&TraceProtocol::Icmp).unwrap(), "\"icmp\""); + assert_eq!(serde_json::to_string(&TraceProtocol::Udp).unwrap(), "\"udp\""); + assert_eq!(serde_json::to_string(&TraceProtocol::Tcp).unwrap(), "\"tcp\""); } #[test] @@ -2123,30 +2062,15 @@ mod tests { #[test] fn test_recorded_protocol_serializes_lowercase_including_legacy() { - assert_eq!( - serde_json::to_string(&RecordedProtocol::Icmp).unwrap(), - "\"icmp\"" - ); - assert_eq!( - serde_json::to_string(&RecordedProtocol::Legacy).unwrap(), - "\"legacy\"" - ); + assert_eq!(serde_json::to_string(&RecordedProtocol::Icmp).unwrap(), "\"icmp\""); + assert_eq!(serde_json::to_string(&RecordedProtocol::Legacy).unwrap(), "\"legacy\""); } #[test] fn test_recorded_protocol_from_trace_protocol() { - assert_eq!( - RecordedProtocol::from(TraceProtocol::Icmp), - RecordedProtocol::Icmp - ); - assert_eq!( - RecordedProtocol::from(TraceProtocol::Udp), - RecordedProtocol::Udp - ); - assert_eq!( - RecordedProtocol::from(TraceProtocol::Tcp), - RecordedProtocol::Tcp - ); + assert_eq!(RecordedProtocol::from(TraceProtocol::Icmp), RecordedProtocol::Icmp); + assert_eq!(RecordedProtocol::from(TraceProtocol::Udp), RecordedProtocol::Udp); + assert_eq!(RecordedProtocol::from(TraceProtocol::Tcp), RecordedProtocol::Tcp); } } @@ -2160,11 +2084,7 @@ mod capability_grant_protocol_tests { occurred_at: None, msg_id: "m1".into(), capabilities: 1 | 1852, - temporary: vec![TemporaryGrant { - cap: "terminal".into(), - granted_at: 10, - expires_at: 1810, - }], + temporary: vec![TemporaryGrant { cap: "terminal".into(), granted_at: 10, expires_at: 1810 }], changes: vec![CapabilityChangeEvent { cap: "terminal".into(), action: CapabilityChangeAction::Granted, @@ -2178,12 +2098,7 @@ mod capability_grant_protocol_tests { assert!(json.contains("\"action\":\"granted\"")); let back: AgentMessage = serde_json::from_str(&json).unwrap(); match back { - AgentMessage::CapabilitiesChanged { - capabilities, - temporary, - changes, - .. - } => { + AgentMessage::CapabilitiesChanged { capabilities, temporary, changes, .. } => { assert_eq!(capabilities, 1 | 1852); assert_eq!(temporary.len(), 1); assert_eq!(changes[0].action, CapabilityChangeAction::Granted); diff --git a/crates/server/src/router/api/server.rs b/crates/server/src/router/api/server.rs index 961ed1fbc..dc65d0d4b 100644 --- a/crates/server/src/router/api/server.rs +++ b/crates/server/src/router/api/server.rs @@ -1052,8 +1052,14 @@ async fn update_server( // Capabilities are agent-owned and not writable here (the `capabilities` // field was removed from `UpdateServerInput`), so updating a server can no // longer change what the agent is allowed to do. - let server = - ServerService::update_server_at(&state.db, &id, input, state.renewal_clock.now()).await?; + let server = ServerService::update_server_at_with_alerts( + &state.db, + &id, + input, + state.renewal_clock.now(), + &state.alert_state_manager, + ) + .await?; let _ = state.browser_tx.send( serverbee_common::protocol::BrowserMessage::ServerCatalogChanged { server_ids: vec![id.clone()], diff --git a/crates/server/src/service/alert.rs b/crates/server/src/service/alert.rs index 00cf17f68..a82d9ac70 100644 --- a/crates/server/src/service/alert.rs +++ b/crates/server/src/service/alert.rs @@ -411,6 +411,15 @@ impl AlertStateManager { // Publish synchronously after commit. Durable eligibility never relies on // this display cache, including after cancellation or process restart. + pub(super) fn publish_adopted_renewal(&self, state: &alert_state::Model) { + self.triggered.remove(&( + state.rule_id.clone(), + state.server_id.clone(), + String::new(), + )); + self.publish_state(state); + } + pub(super) fn publish_state(&self, state: &alert_state::Model) { let key = ( state.rule_id.clone(), diff --git a/crates/server/src/service/renewal_reminders.rs b/crates/server/src/service/renewal_reminders.rs index 4010b45a1..78101bc3c 100644 --- a/crates/server/src/service/renewal_reminders.rs +++ b/crates/server/src/service/renewal_reminders.rs @@ -24,6 +24,62 @@ pub(super) enum Outcome { Superseded, } +/// Enabling the same future legacy date changes representation, not its once admission. +/// Only pure expiration once rows are adopted; event-intent dimensions stay untouched. +pub(super) async fn adopt_legacy_once( + tx: &sea_orm::DatabaseTransaction, + model: &crate::entity::server::Model, + selected: &RenewalState, + deadline: Option>, + now: DateTime, +) -> Result, AppError> { + let previous = RenewalState::from_server(model); + let Some(occurrence) = selected.occurrence_id.as_ref() else { + return Ok(Vec::new()); + }; + let old_date = renewal::selected_date(model.expired_at, &previous.billing_timezone); + let new_date = renewal::selected_date(deadline, &selected.billing_timezone); + if previous.occurrence_id.is_some() + || previous.enabled + || !selected.enabled + || previous.billing_timezone != selected.billing_timezone + || old_date != new_date + || !new_date + .zip(renewal::selected_date( + Some(now), + &selected.billing_timezone, + )) + .is_some_and(|(date, today)| date >= today) + { + return Ok(Vec::new()); + } + let states = alert_state::Entity::find() + .filter(alert_state::Column::ServerId.eq(&model.id)) + .filter(alert_state::Column::EventKey.eq("")) + .all(tx) + .await?; + let mut adopted = Vec::new(); + for state in states { + let Some(rule) = alert_rule::Entity::find_by_id(&state.rule_id) + .one(tx) + .await? + else { + continue; + }; + let items: Vec = serde_json::from_str(&rule.rules_json).unwrap_or_default(); + if rule.trigger_mode != "once" + || items.is_empty() + || !items.iter().all(|item| item.rule_type == "expiration") + { + continue; + } + let mut active: alert_state::ActiveModel = state.into(); + active.event_key = Set(format!("renewal:{occurrence}")); + adopted.push(active.update(tx).await?); + } + Ok(adopted) +} + pub(super) async fn evaluate( db: &DatabaseConnection, manager: &AlertStateManager, @@ -150,13 +206,17 @@ pub(super) async fn evaluate( })); } let should_notify = existing.as_ref().is_none_or(|state| { - rule.trigger_mode != "once" && now - state.last_notified_at >= Duration::minutes(5) + rule.trigger_mode != "once" + && (state.resolved || now - state.last_notified_at >= Duration::minutes(5)) }); if !should_notify { tx.commit().await?; for row in &archived { manager.publish_state(row); } + if let Some(row) = &existing { + manager.publish_state(row); + } return Ok(Some(if archived.is_empty() { Outcome::Silent } else { @@ -165,9 +225,17 @@ pub(super) async fn evaluate( } let row = if let Some(previous) = existing { let count = previous.count; + let recovered = previous.resolved; let mut active: alert_state::ActiveModel = previous.into(); + if recovered { + active.first_triggered_at = Set(now); + } active.last_notified_at = Set(now); - active.count = Set(count.saturating_add(1)); + active.count = Set(if recovered { + 1 + } else { + count.saturating_add(1) + }); active.resolved = Set(false); active.resolved_at = Set(None); active.updated_at = Set(now); diff --git a/crates/server/src/service/server.rs b/crates/server/src/service/server.rs index cce9528e2..24426cfcc 100644 --- a/crates/server/src/service/server.rs +++ b/crates/server/src/service/server.rs @@ -90,6 +90,30 @@ impl ServerService { input: UpdateServerInput, now: chrono::DateTime, ) -> Result { + Self::update_server_inner(db, id, input, now, None).await + } + + pub async fn update_server_at_with_alerts( + db: &DatabaseConnection, + id: &str, + input: UpdateServerInput, + now: chrono::DateTime, + manager: &super::alert::AlertStateManager, + ) -> Result { + Self::update_server_inner(db, id, input, now, Some(manager)).await + } + + async fn update_server_inner( + db: &DatabaseConnection, + id: &str, + input: UpdateServerInput, + now: chrono::DateTime, + manager: Option<&super::alert::AlertStateManager>, + ) -> Result { + let _admission = match manager { + Some(manager) => Some(manager.admission_lock.lock().await), + None => None, + }; Self::validate_update_input(&input)?; let tx = db.begin().await?; let model = super::renewal::load_for_update(&tx, id).await?; @@ -105,6 +129,9 @@ impl ServerService { .unwrap_or(model.billing_cycle.as_deref()), now, )?; + let adopted = + super::renewal_reminders::adopt_legacy_once(&tx, &model, &renewal, deadline, now) + .await?; let mut active: server::ActiveModel = model.into(); active.renewal_state = Set(Some( serde_json::to_string(&renewal).map_err(|e| AppError::Validation(e.to_string()))?, @@ -169,6 +196,11 @@ impl ServerService { active.updated_at = Set(now); let updated = active.update(&tx).await?; tx.commit().await?; + if let Some(manager) = manager { + for row in &adopted { + manager.publish_adopted_renewal(row); + } + } Ok(updated) } diff --git a/crates/server/tests/mobile_push_integration.rs b/crates/server/tests/mobile_push_integration.rs index 67bf5aa17..c18f9a4c9 100644 --- a/crates/server/tests/mobile_push_integration.rs +++ b/crates/server/tests/mobile_push_integration.rs @@ -3472,6 +3472,35 @@ async fn persisted_alert_cycle( .expect("read durable alert state") } +/// Rollback expiration fixtures use the persisted complete occurrence dimension. +async fn expiration_dimension(state: &AppState, server: &str) -> String { + let model = serverbee_server::entity::server::Entity::find_by_id(server) + .one(&state.db) + .await + .unwrap() + .unwrap(); + serverbee_server::service::renewal::RenewalState::from_server(&model) + .occurrence_id + .map(|id| format!("renewal:{id}")) + .unwrap_or_default() +} + +async fn persisted_expiration_cycle( + state: &AppState, + rule: &str, + server: &str, + key: &str, +) -> Option { + use serverbee_server::entity::alert_state; + alert_state::Entity::find() + .filter(alert_state::Column::RuleId.eq(rule)) + .filter(alert_state::Column::ServerId.eq(server)) + .filter(alert_state::Column::EventKey.eq(key)) + .one(&state.db) + .await + .unwrap() +} + async fn attach_alert_webhook( client: &reqwest::Client, base: &str, @@ -3533,11 +3562,23 @@ async fn assert_alert_rollback( state: &AppState, rule: &str, server: &str, + dimension: &str, before: &Option, + states_before: &[serverbee_server::entity::alert_state::Model], jobs_before: &[serverbee_server::entity::mobile_push_outbox::Model], ) { + let all_states = serverbee_server::entity::alert_state::Entity::find() + .filter(serverbee_server::entity::alert_state::Column::RuleId.eq(rule)) + .filter(serverbee_server::entity::alert_state::Column::ServerId.eq(server)) + .all(&state.db) + .await + .unwrap(); + assert_eq!( + all_states, states_before, + "Failed admission cannot leak any unexpected dimension or mutate retained history" + ); assert_eq!( - &persisted_alert_cycle(state, rule, server).await, + &persisted_expiration_cycle(state, rule, server, dimension).await, before, "Failed transaction must not consume a transition or rearm" ); @@ -3547,13 +3588,29 @@ async fn assert_alert_rollback( "First recipient and durable alert state must roll back with the failed recipient/commit" ); assert_eq!( - state.alert_state_manager.is_triggered(rule, server, ""), + state + .alert_state_manager + .is_triggered(rule, server, dimension), before.as_ref().is_some_and(|cycle| !cycle.resolved) ); + let selected_dimension = expiration_dimension(state, server).await; + if selected_dimension != dimension { + assert!( + !state + .alert_state_manager + .is_triggered(rule, server, &selected_dimension) + ); + assert!( + persisted_expiration_cycle(state, rule, server, &selected_dimension) + .await + .is_none(), + "Failed admission must not create the new selected occurrence" + ); + } if let Some(cycle) = before.as_ref().filter(|cycle| !cycle.resolved) { let cached = state .alert_state_manager - .get_info(rule, server, "") + .get_info(rule, server, dimension) .expect("Firing cache survives failed recovery"); assert_eq!(cached.first_triggered_at, cycle.first_triggered_at); assert_eq!(cached.last_notified_at, cycle.last_notified_at); @@ -3577,6 +3634,7 @@ async fn exercise_alert_rollback_restart(phase: AlertRollbackPhase, fault: Alert .await; let (server, rule) = alert_http_fixture(&client, &base, admin, "once").await; let webhook = attach_alert_webhook(&client, &base, admin, &rule).await; + let dimension = expiration_dimension(&state, &server).await; match phase { AlertRollbackPhase::Trigger => {} AlertRollbackPhase::Recovery => { @@ -3590,14 +3648,34 @@ async fn exercise_alert_rollback_restart(phase: AlertRollbackPhase, fault: Alert set_alert_expiration(&client, &base, admin, &server, true).await; } } - let before = persisted_alert_cycle(&state, &rule, &server).await; + let before = persisted_expiration_cycle(&state, &rule, &server, &dimension).await; + match phase { + AlertRollbackPhase::Trigger => assert!(before.is_none()), + AlertRollbackPhase::Recovery => assert!(!before.as_ref().unwrap().resolved), + AlertRollbackPhase::Rearm => assert!(before.as_ref().unwrap().resolved), + } + let states_before = serverbee_server::entity::alert_state::Entity::find() + .filter(serverbee_server::entity::alert_state::Column::RuleId.eq(&rule)) + .filter(serverbee_server::entity::alert_state::Column::ServerId.eq(&server)) + .all(&state.db) + .await + .unwrap(); let jobs_before = alert_jobs(&state).await; let external_before = webhook.lock().await.len(); fault_alert_admission(&state, fault).await; // Repeat in the same process: a failed attempt cannot consume the hot cache. for _ in 0..2 { evaluate_alerts(&state).await; - assert_alert_rollback(&state, &rule, &server, &before, &jobs_before).await; + assert_alert_rollback( + &state, + &rule, + &server, + &dimension, + &before, + &states_before, + &jobs_before, + ) + .await; assert_eq!( webhook.lock().await.len(), external_before, @@ -3612,16 +3690,32 @@ async fn exercise_alert_rollback_restart(phase: AlertRollbackPhase, fault: Alert // production cache has loaded, before removing only the external fault. let restarted = reopen_alert_state(&state, &directory).await; evaluate_alerts(&restarted).await; - assert_alert_rollback(&restarted, &rule, &server, &before, &jobs_before).await; + assert_alert_rollback( + &restarted, + &rule, + &server, + &dimension, + &before, + &states_before, + &jobs_before, + ) + .await; restarted .db .execute_unprepared("DROP TRIGGER fail_alert_admission") .await .unwrap(); evaluate_alerts(&restarted).await; - let admitted_state = persisted_alert_cycle(&restarted, &rule, &server) - .await - .unwrap(); + let admitted_dimension = if matches!(phase, AlertRollbackPhase::Recovery) { + dimension.clone() + } else { + expiration_dimension(&restarted, &server).await + }; + let admitted_state = + persisted_expiration_cycle(&restarted, &rule, &server, &admitted_dimension) + .await + .unwrap(); + assert_eq!(admitted_state.event_key, admitted_dimension); let admitted_jobs = alert_jobs(&restarted).await; let new_jobs: Vec<_> = admitted_jobs .iter() diff --git a/crates/server/tests/renewal_reminders.rs b/crates/server/tests/renewal_reminders.rs index 856b70e78..d9c9794b2 100644 --- a/crates/server/tests/renewal_reminders.rs +++ b/crates/server/tests/renewal_reminders.rs @@ -640,3 +640,213 @@ async fn explicitly_clearing_expiry_resolves_its_retained_occurrence() { 1 ); } + +#[tokio::test] +async fn enabling_tracking_for_same_legacy_date_does_not_readmit_its_once_reminder() { + let clock = ManualClock::at("2026-10-15T12:00:00Z"); + use sea_orm::ConnectionTrait; + let (_base, tmp, initial) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let mut config = initial.config.clone(); + config.push_relay.url = "https://unused-fixture-relay.invalid".into(); + let (base, state) = reopen(&tmp, clock.clone(), config).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let response = admin.post(format!("{base}/api/servers")) + .json(&json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":"legacy expiry","billing_cycle":"monthly","expired_at":"2026-10-31T12:34:56Z"})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let id = response.json::().await.unwrap()["data"]["server_id"] + .as_str() + .unwrap() + .to_string(); + let before = get(&admin, &base, &format!("servers/{id}")).await; + assert!(before["renewal"]["occurrence_id"].is_null()); + let response = admin.post(format!("{base}/api/alert-rules")) + .json(&json!({"name":"legacy once","rules":[{"rule_type":"expiration","duration":60}],"trigger_mode":"once","enabled":true,"cover_type":"include","server_ids":[id]})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + register_encrypted_alerts(&admin, &base).await; + tick(&state).await; + let old = get(&admin, &base, "alert-events").await; + assert_eq!(old.as_array().unwrap().len(), 1); + let old_key = old[0]["alert_key"].as_str().unwrap(); + let original_detail = get(&admin, &base, &format!("alert-events/{old_key}")).await; + let original_jobs = jobs(&state).await; + assert_eq!(original_jobs.len(), 1); + let rule = old[0]["rule_id"].as_str().unwrap(); + state.db.execute_unprepared("CREATE TRIGGER renewal_adoption_failure BEFORE UPDATE ON alert_states WHEN NEW.event_key != OLD.event_key BEGIN SELECT RAISE(FAIL,'isolated adoption fault'); END").await.unwrap(); + let failed = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":true}})) + .send() + .await + .unwrap(); + assert_eq!(failed.status(), 500); + assert_eq!(get(&admin, &base, &format!("servers/{id}")).await, before); + assert_eq!( + get(&admin, &base, &format!("alert-events/{old_key}")).await, + original_detail + ); + assert!(state.alert_state_manager.is_triggered(rule, &id, "")); + assert_eq!(jobs(&state).await, original_jobs); + state + .db + .execute_unprepared("DROP TRIGGER renewal_adoption_failure") + .await + .unwrap(); + let response = admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":true}})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + tick(&state).await; + let enabled = get(&admin, &base, &format!("servers/{id}")).await; + assert_eq!(enabled["renewal"]["expiry_date"], "2026-10-31"); + assert_eq!( + enabled["renewal"]["confirmed_expired_at"], + before["expired_at"] + ); + let same = get(&admin, &base, "alert-events").await; + assert_eq!( + same.as_array().unwrap().len(), + 1, + "enabling tracking for the same selected date must not fabricate another once reminder" + ); + assert_eq!(same[0]["count"], 1); + + let old_key = old[0]["alert_key"].as_str().unwrap(); + let new_key = same[0]["alert_key"].as_str().unwrap(); + assert_ne!(old_key, new_key); + assert_eq!( + admin + .get(format!("{base}/api/alert-events/{old_key}")) + .send() + .await + .unwrap() + .status(), + 404, + "an adopted complete dimension overwrites the legacy key, which must never select another occurrence" + ); + let detail = get(&admin, &base, &format!("alert-events/{new_key}")).await; + assert_eq!(detail["alert_key"], new_key); + assert_eq!( + detail["first_triggered_at"], + original_detail["first_triggered_at"] + ); + let rule = same[0]["rule_id"].as_str().unwrap(); + assert!(!state.alert_state_manager.is_triggered(rule, &id, "")); + assert!(state.alert_state_manager.is_triggered( + rule, + &id, + &format!( + "renewal:{}", + enabled["renewal"]["occurrence_id"].as_str().unwrap() + ) + )); + + assert_eq!( + jobs(&state).await, + original_jobs, + "adoption never enqueues or reencrypts delivery" + ); + let (reopened_base, reopened) = reopen(&tmp, clock.clone(), state.config.clone()).await; + tick(&reopened).await; + assert_eq!(jobs(&reopened).await, original_jobs); + for enabled in [false, true] { + assert_eq!( + admin + .put(format!("{reopened_base}/api/servers/{id}")) + .json(&json!({"renewal":{"enabled":enabled}})) + .send() + .await + .unwrap() + .status(), + 200 + ); + tick(&reopened).await; + assert_eq!(jobs(&reopened).await, original_jobs); + } + clock.set("2026-11-01T00:00:00Z"); + tick(&state).await; + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 2, + "a different monthly date still admits its own reminder" + ); + assert_eq!( + jobs(&state).await.len(), + 2, + "only the next current occurrence adds a job, with no calendar recovery" + ); +} + +#[tokio::test] +async fn always_reminder_retriggers_after_real_recovery_within_debounce_window() { + let clock = ManualClock::at("2026-10-30T12:00:00Z"); + let (base, _tmp, state) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (_, rule) = configure(&admin, &base, 60).await; + assert_eq!( + admin + .put(format!("{base}/api/alert-rules/{rule}")) + .json(&json!({"trigger_mode":"always"})) + .send() + .await + .unwrap() + .status(), + 200 + ); + tick(&state).await; + let old = get(&admin, &base, "alert-events").await; + let old_key = old[0]["alert_key"].as_str().unwrap(); + for duration in [0, 60] { + clock.set(if duration == 0 { + "2026-10-30T12:00:15Z" + } else { + "2026-10-30T12:00:30Z" + }); + assert_eq!( + admin + .put(format!("{base}/api/alert-rules/{rule}")) + .json(&json!({"rules":[{"rule_type":"expiration","duration":duration}]})) + .send() + .await + .unwrap() + .status(), + 200 + ); + tick(&state).await; + } + let events = get(&admin, &base, "alert-events").await; + assert_eq!( + events[0]["status"], "firing", + "an always rule starts a new real trigger cycle after recovery" + ); + assert_eq!(events[0]["count"], 1); + assert_ne!(events[0]["alert_key"], old_key); + let detail = get( + &admin, + &base, + &format!("alert-events/{}", events[0]["alert_key"].as_str().unwrap()), + ) + .await; + assert_eq!(detail["first_triggered_at"], "2026-10-30T12:00:30+00:00"); + assert_eq!( + admin + .get(format!("{base}/api/alert-events/{old_key}")) + .send() + .await + .unwrap() + .status(), + 404 + ); +} From 88fc17f21a32d70caf92be5ba0456f88aaec1915 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 20:33:27 +0000 Subject: [PATCH 34/40] style(renewal): simplify recovered occurrence admission --- .../server/src/service/renewal_reminders.rs | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/crates/server/src/service/renewal_reminders.rs b/crates/server/src/service/renewal_reminders.rs index 78101bc3c..fbd9094e3 100644 --- a/crates/server/src/service/renewal_reminders.rs +++ b/crates/server/src/service/renewal_reminders.rs @@ -180,17 +180,15 @@ pub(super) async fn evaluate( .one(&tx) .await?; let mut recovered = manual_recovery && !archived.is_empty(); - if !matched { - if let Some(current) = existing.as_ref().filter(|state| !state.resolved) { - let mut active: alert_state::ActiveModel = current.clone().into(); - active.resolved = Set(true); - active.resolved_at = Set(Some(now)); - active.updated_at = Set(now); - let row = active.update(&tx).await?; - mobile_alert_push::enqueue(&tx, &rule, &row, &model.name).await?; - archived.push(row); - recovered = true; - } + if !matched && let Some(current) = existing.as_ref().filter(|state| !state.resolved) { + let mut active: alert_state::ActiveModel = current.clone().into(); + active.resolved = Set(true); + active.resolved_at = Set(Some(now)); + active.updated_at = Set(now); + let row = active.update(&tx).await?; + mobile_alert_push::enqueue(&tx, &rule, &row, &model.name).await?; + archived.push(row); + recovered = true; } if !matched || MaintenanceService::is_in_maintenance_at(&tx, server_id, now).await? { tx.commit().await?; From d100194ac633287264af5d2d723718c420cf114b Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 20:46:45 +0000 Subject: [PATCH 35/40] fix(renewal): preserve local day and committed rule admission --- crates/server/src/service/renewal.rs | 3 + .../server/src/service/renewal_reminders.rs | 34 +- crates/server/src/service/server.rs | 2 +- .../server/src/service/server_onboarding.rs | 8 + crates/server/tests/renewal_reminders.rs | 445 ++++++++++++++++++ 5 files changed, 474 insertions(+), 18 deletions(-) diff --git a/crates/server/src/service/renewal.rs b/crates/server/src/service/renewal.rs index 63b2cb885..990f6a338 100644 --- a/crates/server/src/service/renewal.rs +++ b/crates/server/src/service/renewal.rs @@ -344,6 +344,9 @@ fn apply_calendar( deadline = old_date .map(|d| date_boundary(d, &state.billing_timezone)) .transpose()?; + if state.occurrence_id.is_none() { + state.occurrence_id = deadline.map(|_| uuid::Uuid::new_v4().to_string()); + } } if date_replaced { state.deadline_origin = DeadlineOrigin::Confirmed; diff --git a/crates/server/src/service/renewal_reminders.rs b/crates/server/src/service/renewal_reminders.rs index fbd9094e3..2e78d7791 100644 --- a/crates/server/src/service/renewal_reminders.rs +++ b/crates/server/src/service/renewal_reminders.rs @@ -17,21 +17,21 @@ use sea_orm::{ /// `None` leaves legacy records without an occurrence on their existing alert path. /// The writer reservation protects the selected deadline through queue admission. -pub(super) enum Outcome { +#[doc(hidden)] +pub enum Outcome { Silent, Triggered, Resolved, Superseded, } -/// Enabling the same future legacy date changes representation, not its once admission. -/// Only pure expiration once rows are adopted; event-intent dimensions stay untouched. -pub(super) async fn adopt_legacy_once( +/// Normalizing the same legacy date changes representation, not its once admission. +/// Only pure expiration rows are adopted; event-intent dimensions stay untouched. +pub(super) async fn adopt_legacy_occurrence( tx: &sea_orm::DatabaseTransaction, model: &crate::entity::server::Model, selected: &RenewalState, deadline: Option>, - now: DateTime, ) -> Result, AppError> { let previous = RenewalState::from_server(model); let Some(occurrence) = selected.occurrence_id.as_ref() else { @@ -41,15 +41,8 @@ pub(super) async fn adopt_legacy_once( let new_date = renewal::selected_date(deadline, &selected.billing_timezone); if previous.occurrence_id.is_some() || previous.enabled - || !selected.enabled - || previous.billing_timezone != selected.billing_timezone + || old_date.is_none() || old_date != new_date - || !new_date - .zip(renewal::selected_date( - Some(now), - &selected.billing_timezone, - )) - .is_some_and(|(date, today)| date >= today) { return Ok(Vec::new()); } @@ -67,7 +60,7 @@ pub(super) async fn adopt_legacy_once( continue; }; let items: Vec = serde_json::from_str(&rule.rules_json).unwrap_or_default(); - if rule.trigger_mode != "once" + if !matches!(rule.trigger_mode.as_str(), "once" | "always") || items.is_empty() || !items.iter().all(|item| item.rule_type == "expiration") { @@ -80,7 +73,9 @@ pub(super) async fn adopt_legacy_once( Ok(adopted) } -pub(super) async fn evaluate( +/// Internal Server admission boundary; public visibility supports real-database integration checks. +#[doc(hidden)] +pub async fn evaluate( db: &DatabaseConnection, manager: &AlertStateManager, rule: &alert_rule::Model, @@ -97,8 +92,13 @@ pub(super) async fn evaluate( let Some(rule) = alert_rule::Entity::find_by_id(&rule.id) .one(&tx) .await? - .filter(|rule| { - rule.enabled && rule_covers_server(&rule.cover_type, &rule.server_ids_json, server_id) + .filter(|current| { + current.enabled + && rule_covers_server(¤t.cover_type, ¤t.server_ids_json, server_id) + // A concurrent rule edit invalidates the caller's condition snapshot. + && current.rules_json == rule.rules_json + && current.notification_group_id == rule.notification_group_id + && current.name == rule.name }) else { tx.commit().await?; diff --git a/crates/server/src/service/server.rs b/crates/server/src/service/server.rs index 24426cfcc..40f23c724 100644 --- a/crates/server/src/service/server.rs +++ b/crates/server/src/service/server.rs @@ -130,7 +130,7 @@ impl ServerService { now, )?; let adopted = - super::renewal_reminders::adopt_legacy_once(&tx, &model, &renewal, deadline, now) + super::renewal_reminders::adopt_legacy_occurrence(&tx, &model, &renewal, deadline) .await?; let mut active: server::ActiveModel = model.into(); active.renewal_state = Set(Some( diff --git a/crates/server/src/service/server_onboarding.rs b/crates/server/src/service/server_onboarding.rs index 526054c0d..81ce7d254 100644 --- a/crates/server/src/service/server_onboarding.rs +++ b/crates/server/src/service/server_onboarding.rs @@ -142,6 +142,9 @@ impl ServerOnboarding { } pub async fn onboard(&self, input: OnboardServer) -> Result { + let typed_calendar = input.profile.renewal.as_ref().is_some_and(|renewal| { + renewal.expiry_date.is_some() || renewal.billing_timezone.is_some() + }); let normalized = NormalizedProfile::from_input(input.profile)?; let input_hash = normalized.hash(input.offer_ttl)?; if input.actor_id.trim().is_empty() { @@ -203,6 +206,11 @@ impl ServerOnboarding { let renewal_state = if let Some(serialized) = normalized.renewal_state.as_ref() { let mut renewal: super::renewal::RenewalState = serde_json::from_str(serialized).map_err(|e| AppError::Internal(e.to_string()))?; + // Allocate after the canonical request hash and replay lookup, so + // a typed manual date owns a local-day occurrence without changing retries. + if typed_calendar && deadline.is_some() && renewal.occurrence_id.is_none() { + renewal.occurrence_id = Some(Uuid::new_v4().to_string()); + } renewal.advance(&mut deadline, normalized.billing_cycle.as_deref(), now)?; Some(serde_json::to_string(&renewal).map_err(|e| AppError::Internal(e.to_string()))?) } else { diff --git a/crates/server/tests/renewal_reminders.rs b/crates/server/tests/renewal_reminders.rs index d9c9794b2..708b799aa 100644 --- a/crates/server/tests/renewal_reminders.rs +++ b/crates/server/tests/renewal_reminders.rs @@ -850,3 +850,448 @@ async fn always_reminder_retriggers_after_real_recovery_within_debounce_window() 404 ); } + +#[tokio::test] +async fn captured_expiration_conditions_cannot_consume_once_after_committed_rule_edit() { + use sea_orm::EntityTrait; + use serverbee_server::service::{ + alert::AlertRuleItem, + renewal_reminders::{self, Outcome}, + }; + let clock = ManualClock::at("2026-10-30T12:00:00Z"); + let (base, _tmp, state) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, rule) = configure(&admin, &base, 60).await; + // Capture exactly the production caller's database rule/items before an edit. + let captured = serverbee_server::entity::alert_rule::Entity::find_by_id(&rule) + .one(&state.db) + .await + .unwrap() + .unwrap(); + let items: Vec = serde_json::from_str(&captured.rules_json).unwrap(); + for conditions in [ + json!([{"rule_type":"expiration","duration":0}]), + json!([{"rule_type":"expiration","duration":60},{"rule_type":"ip_changed"}]), + ] { + assert_eq!( + admin + .put(format!("{base}/api/alert-rules/{rule}")) + .json(&json!({"rules":conditions})) + .send() + .await + .unwrap() + .status(), + 200 + ); + // The production admission helper takes its real writer reservation and + // reads the committed rule. Empty non-expiration AND was true in the captured rule. + let outcome = renewal_reminders::evaluate( + &state.db, + &state.alert_state_manager, + &captured, + &id, + &items, + true, + clock.now(), + ) + .await + .unwrap(); + assert!( + matches!(outcome, Some(Outcome::Silent)), + "a stale condition snapshot must defer without consuming once" + ); + assert!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .is_empty() + ); + assert!(jobs(&state).await.is_empty()); + } +} + +#[tokio::test] +async fn typed_disabled_create_reminds_on_local_expiry_date_and_preserves_identity_on_replay() { + let clock = ManualClock::at("2026-10-31T03:59:59Z"); + let (base, tmp, state) = common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let input = json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":"manual local expiry", + "renewal":{"enabled":false,"expiry_date":"2026-10-31","billing_timezone":"America/New_York"}}); + let response = admin + .post(format!("{base}/api/servers")) + .json(&input) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let id = response.json::().await.unwrap()["data"]["server_id"] + .as_str() + .unwrap() + .to_string(); + assert_eq!(admin.post(format!("{base}/api/alert-rules")) + .json(&json!({"name":"zero-day manual expiry","rules":[{"rule_type":"expiration","duration":0}],"trigger_mode":"once","enabled":true,"cover_type":"include","server_ids":[id]})) + .send().await.unwrap().status(), 200); + tick(&state).await; + assert!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .is_empty() + ); + clock.set("2026-10-31T04:00:00Z"); + tick(&state).await; + assert_eq!( + get(&admin, &base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1, + "a typed manual create must admit zero-day at the start of its local expiry date" + ); + let selected = get(&admin, &base, &format!("servers/{id}")).await; + assert!(selected["renewal"]["occurrence_id"].is_string()); + let replay = admin + .post(format!("{base}/api/servers")) + .json(&input) + .send() + .await + .unwrap(); + assert_eq!( + replay.status(), + 200, + "occurrence allocation must not randomize normalized onboarding hash" + ); + let replay = replay.json::().await.unwrap(); + assert_eq!(replay["data"]["server_id"], id); + assert_eq!(replay["data"]["replayed"], true); + assert_eq!( + get(&admin, &base, &format!("servers/{id}")).await["renewal"]["occurrence_id"], + selected["renewal"]["occurrence_id"] + ); + clock.set("2026-11-01T03:59:59.999999999Z"); + let (reopened_base, reopened) = reopen(&tmp, clock, state.config.clone()).await; + tick(&reopened).await; + assert_eq!( + get(&admin, &reopened_base, "alert-events") + .await + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + get(&admin, &reopened_base, &format!("servers/{id}")).await["renewal"]["occurrence_id"], + selected["renewal"]["occurrence_id"] + ); +} + +#[tokio::test] +async fn legacy_timezone_normalization_uses_local_day_without_readmitting_consumed_once() { + let clock = ManualClock::at("2026-10-30T12:00:00Z"); + let (_base, tmp, initial) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let mut config = initial.config.clone(); + config.push_relay.url = "https://unused-fixture-relay.invalid".into(); + let (base, state) = reopen(&tmp, clock.clone(), config).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let response = admin.post(format!("{base}/api/servers")) + .json(&json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":"legacy timezone", + "expired_at":"2026-10-31T12:34:56Z"})).send().await.unwrap(); + assert_eq!(response.status(), 200); + let id = response.json::().await.unwrap()["data"]["server_id"] + .as_str() + .unwrap() + .to_string(); + for days in [60, 0] { + assert_eq!(admin.post(format!("{base}/api/alert-rules")) + .json(&json!({"name":format!("legacy {days} day reminder"),"rules":[{"rule_type":"expiration","duration":days}],"trigger_mode":"once","enabled":true,"cover_type":"include","server_ids":[id]})) + .send().await.unwrap().status(), 200); + } + register_encrypted_alerts(&admin, &base).await; + tick(&state).await; + let old = get(&admin, &base, "alert-events").await; + assert_eq!(old.as_array().unwrap().len(), 1); + let original_jobs = jobs(&state).await; + assert_eq!(original_jobs.len(), 1); + let old_rule = old[0]["rule_id"].as_str().unwrap(); + let old_key = old[0]["alert_key"].as_str().unwrap(); + let original = get(&admin, &base, &format!("alert-events/{old_key}")).await; + let legacy = get(&admin, &base, &format!("servers/{id}")).await; + clock.set("2026-10-31T04:00:00Z"); + assert_eq!( + admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":{"billing_timezone":"America/New_York"}})) + .send() + .await + .unwrap() + .status(), + 200 + ); + tick(&state).await; + let current = get(&admin, &base, &format!("servers/{id}")).await; + assert_eq!(current["renewal"]["enabled"], false); + assert_eq!(current["renewal"]["expiry_date"], "2026-10-31"); + assert_eq!( + current["renewal"]["confirmed_expired_at"], + legacy["expired_at"] + ); + assert_eq!( + current["renewal"]["expiry_date"], + legacy["renewal"]["expiry_date"] + ); + let events = get(&admin, &base, "alert-events").await; + assert_eq!( + events.as_array().unwrap().len(), + 2, + "timezone normalization admits the zero-day rule and preserves the already consumed 60-day rule" + ); + let adopted = events + .as_array() + .unwrap() + .iter() + .find(|event| event["rule_id"] == old_rule) + .unwrap(); + assert_eq!(adopted["count"], 1); + assert_ne!(adopted["alert_key"], old_key); + let key = adopted["alert_key"].as_str().unwrap(); + assert_eq!( + get(&admin, &base, &format!("alert-events/{key}")).await["first_triggered_at"], + original["first_triggered_at"] + ); + assert_eq!( + admin + .get(format!("{base}/api/alert-events/{old_key}")) + .send() + .await + .unwrap() + .status(), + 404 + ); + let adopted_jobs = jobs(&state).await; + assert_eq!(adopted_jobs.len(), 2); + assert!(adopted_jobs.iter().any(|job| job == &original_jobs[0])); + let (reopened_base, reopened) = reopen(&tmp, clock, state.config.clone()).await; + tick(&reopened).await; + assert_eq!(jobs(&reopened).await, adopted_jobs); + assert_eq!( + get(&admin, &reopened_base, &format!("servers/{id}")).await["renewal"]["occurrence_id"], + current["renewal"]["occurrence_id"] + ); +} + +#[tokio::test] +async fn captured_notification_group_cannot_consume_once_after_committed_channel_edit() { + use sea_orm::EntityTrait; + use serverbee_server::service::{ + alert::AlertRuleItem, + renewal_reminders::{self, Outcome}, + }; + let clock = ManualClock::at("2026-10-30T12:00:00Z"); + let (_base, tmp, initial) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let mut config = initial.config.clone(); + config.push_relay.url = "https://unused-fixture-relay.invalid".into(); + let (base, state) = reopen(&tmp, clock.clone(), config).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let (id, rule) = configure(&admin, &base, 60).await; + register_encrypted_alerts(&admin, &base).await; + let receipts = Arc::new(tokio::sync::Mutex::new(Vec::::new())); + let sink = receipts.clone(); + let app = axum::Router::new().route( + "/{destination}", + axum::routing::post( + move |axum::extract::Path(destination): axum::extract::Path, body: String| { + let sink = sink.clone(); + async move { + sink.lock().await.push(format!("{destination}:{body}")); + "ok" + } + }, + ), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let webhook = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let mut groups = Vec::new(); + for destination in ["old", "new"] { + let response = admin.post(format!("{base}/api/notifications")) + .json(&json!({"name":destination,"notify_type":"webhook","enabled":true, + "config_json":{"url":format!("{webhook}/{destination}"),"method":"POST","body_template":"{{event}}"}})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + let notification = response.json::().await.unwrap()["data"]["id"].clone(); + let response = admin + .post(format!("{base}/api/notification-groups")) + .json(&json!({"name":destination,"notification_ids":[notification]})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + groups.push(response.json::().await.unwrap()["data"]["id"].clone()); + } + assert_eq!( + admin + .put(format!("{base}/api/alert-rules/{rule}")) + .json(&json!({"notification_group_id":groups[0]})) + .send() + .await + .unwrap() + .status(), + 200 + ); + let captured = serverbee_server::entity::alert_rule::Entity::find_by_id(&rule) + .one(&state.db) + .await + .unwrap() + .unwrap(); + let items: Vec = serde_json::from_str(&captured.rules_json).unwrap(); + assert_eq!( + admin + .put(format!("{base}/api/alert-rules/{rule}")) + .json(&json!({"notification_group_id":groups[1]})) + .send() + .await + .unwrap() + .status(), + 200 + ); + let outcome = renewal_reminders::evaluate( + &state.db, + &state.alert_state_manager, + &captured, + &id, + &items, + true, + clock.now(), + ) + .await + .unwrap(); + assert!( + matches!(outcome, Some(Outcome::Silent)), + "stale external routing must not consume a differently routed current rule" + ); + assert!(jobs(&state).await.is_empty()); + assert!(receipts.lock().await.is_empty()); + tick(&state).await; + assert_eq!(jobs(&state).await.len(), 1); + assert_eq!(*receipts.lock().await, vec!["new:triggered"]); + tick(&state).await; + assert_eq!(jobs(&state).await.len(), 1); + assert_eq!(*receipts.lock().await, vec!["new:triggered"]); +} + +#[tokio::test] +async fn legacy_always_representation_changes_preserve_existing_five_minute_debounce() { + let now = Utc::now(); + let clock = ManualClock::at(&now.to_rfc3339()); + use sea_orm::EntityTrait; + let (_base, tmp, initial) = + common::start_test_server_with_renewal_clock(100, clock.clone()).await; + let mut config = initial.config.clone(); + config.push_relay.url = "https://unused-fixture-relay.invalid".into(); + let (base, state) = reopen(&tmp, clock.clone(), config).await; + let admin = http_client(); + login_admin(&admin, &base).await; + let date = (now + chrono::Duration::days(10)).date_naive().to_string(); + let mut ids = Vec::new(); + for name in ["enabled legacy always", "timezone legacy always"] { + let response = admin + .post(format!("{base}/api/servers")) + .json( + &json!({"onboarding_request_id":uuid::Uuid::new_v4().to_string(),"name":name, + "billing_cycle":"monthly","expired_at":format!("{date}T12:34:56Z")}), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let id = response.json::().await.unwrap()["data"]["server_id"] + .as_str() + .unwrap() + .to_string(); + assert_eq!(admin.post(format!("{base}/api/alert-rules")) + .json(&json!({"name":name,"rules":[{"rule_type":"expiration","duration":60}],"trigger_mode":"always","enabled":true,"cover_type":"include","server_ids":[id]})) + .send().await.unwrap().status(), 200); + ids.push(id); + } + register_encrypted_alerts(&admin, &base).await; + tick(&state).await; + let before = get(&admin, &base, "alert-events").await; + assert_eq!(before.as_array().unwrap().len(), 2); + let original_jobs = jobs(&state).await; + assert_eq!(original_jobs.len(), 2); + let original_states = serverbee_server::entity::alert_state::Entity::find() + .all(&state.db) + .await + .unwrap(); + clock.set(&(now + chrono::Duration::seconds(30)).to_rfc3339()); + for (id, input) in ids.iter().zip([ + json!({"enabled":true}), + json!({"billing_timezone":"America/New_York"}), + ]) { + assert_eq!( + admin + .put(format!("{base}/api/servers/{id}")) + .json(&json!({"renewal":input})) + .send() + .await + .unwrap() + .status(), + 200 + ); + } + let adopted_states = serverbee_server::entity::alert_state::Entity::find() + .all(&state.db) + .await + .unwrap(); + assert_eq!(adopted_states.len(), original_states.len()); + for original in &original_states { + let adopted = adopted_states + .iter() + .find(|state| state.id == original.id) + .unwrap(); + assert_eq!(adopted.first_triggered_at, original.first_triggered_at); + assert_eq!(adopted.last_notified_at, original.last_notified_at); + assert_eq!(adopted.count, original.count); + assert_eq!(adopted.resolved, original.resolved); + assert_eq!(adopted.resolved_at, original.resolved_at); + } + tick(&state).await; + let adopted = get(&admin, &base, "alert-events").await; + assert_eq!( + adopted.as_array().unwrap().len(), + 2, + "representation changes cannot bypass an always rule's existing debounce" + ); + assert!( + adopted + .as_array() + .unwrap() + .iter() + .all(|event| event["count"] == 1) + ); + assert_eq!(jobs(&state).await, original_jobs); + clock.set(&(now + chrono::Duration::minutes(6)).to_rfc3339()); + tick(&state).await; + let repeated = get(&admin, &base, "alert-events").await; + assert_eq!(repeated.as_array().unwrap().len(), 2); + assert!( + repeated + .as_array() + .unwrap() + .iter() + .all(|event| event["count"] == 2) + ); + assert_eq!(jobs(&state).await.len(), 4); +} From 90e75d8d01cf24bcc15089107e598bfcbbd46487 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 21:27:04 +0000 Subject: [PATCH 36/40] fix(ios): start renewal loopback fixture without reverse DNS --- .github/workflows/ci-ios.yml | 2 + scripts/ios-renewal-ui-check.sh | 18 ++----- tests/check-ios-renewal-harness.py | 87 ++++++++++++++++++++++++++++++ tests/check-ios-renewal-startup.py | 64 ++++++++++++++++++++++ tests/fixtures/ios-renewal-http.py | 20 ++++++- 5 files changed, 175 insertions(+), 16 deletions(-) create mode 100644 tests/check-ios-renewal-startup.py diff --git a/.github/workflows/ci-ios.yml b/.github/workflows/ci-ios.yml index d33750de8..bfcd0f107 100644 --- a/.github/workflows/ci-ios.yml +++ b/.github/workflows/ci-ios.yml @@ -45,6 +45,8 @@ jobs: - uses: actions/checkout@v4 - name: Check official app identity and Keychain group configuration run: python3 tests/check-push-secret-boundaries.py --static-only + - name: Validate renewal fixture startup and native result gates + run: python3 tests/check-ios-renewal-harness.py - uses: actions/setup-node@v4 with: node-version: 24 diff --git a/scripts/ios-renewal-ui-check.sh b/scripts/ios-renewal-ui-check.sh index feabf687a..6c64a5f31 100644 --- a/scripts/ios-renewal-ui-check.sh +++ b/scripts/ios-renewal-ui-check.sh @@ -93,23 +93,11 @@ with open(sys.argv[2], 'w') as log: stderr=subprocess.STDOUT, timeout=180, check=True) PY -python3 "$RENEWAL_ROOT/tests/fixtures/ios-renewal-http.py" --evidence-dir "$RENEWAL_EVIDENCE_DIR" \ +python3 -u "$RENEWAL_ROOT/tests/fixtures/ios-renewal-http.py" --evidence-dir "$RENEWAL_EVIDENCE_DIR" \ > "$RENEWAL_EVIDENCE_DIR/fixture.log" 2>&1 & RENEWAL_FIXTURE_PID=$! -python3 - "$RENEWAL_EVIDENCE_DIR" <<'PY' -import pathlib, sys, time, urllib.request -directory = pathlib.Path(sys.argv[1]) -for attempt in range(100): - try: - url = directory.joinpath('fixture-url.txt').read_text().strip() - with urllib.request.urlopen(url + '/__test/state', timeout=1) as response: - if response.status == 200: - break - except (OSError, ValueError): - time.sleep(0.1) -else: - raise SystemExit('Loopback renewal fixture did not become ready within 10 seconds') -PY +python3 "$RENEWAL_ROOT/tests/check-ios-renewal-startup.py" \ + --evidence-dir "$RENEWAL_EVIDENCE_DIR" --pid "$RENEWAL_FIXTURE_PID" export TEST_RUNNER_SERVERBEE_RENEWAL_FIXTURE_URL="$(cat "$RENEWAL_EVIDENCE_DIR/fixture-url.txt")" set +e xcodebuild -project ServerBee.xcodeproj -scheme ServerBeeUI -configuration Debug \ diff --git a/tests/check-ios-renewal-harness.py b/tests/check-ios-renewal-harness.py index 2d5b66d48..f1ff647fb 100644 --- a/tests/check-ios-renewal-harness.py +++ b/tests/check-ios-renewal-harness.py @@ -3,6 +3,7 @@ import importlib.util import json +import os import subprocess import sys import tempfile @@ -18,6 +19,78 @@ spec.loader.exec_module(results) +class FixtureStartupTests(unittest.TestCase): + def test_live_unready_process_reports_bounded_timeout(self): + with tempfile.TemporaryDirectory(prefix="renewal-startup-timeout-") as directory: + process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + try: + check = subprocess.run( + [sys.executable, str(ROOT / "tests/check-ios-renewal-startup.py"), + "--evidence-dir", directory, "--pid", str(process.pid), + "--timeout-seconds", "0.2"], capture_output=True, text=True, timeout=3) + self.assertNotEqual(check.returncode, 0) + report = json.loads((Path(directory) / "fixture-startup-check.json").read_text()) + self.assertEqual(report["outcome"], "timeout") + self.assertFalse(report["urlPublished"]) + self.assertTrue(report["processStatus"]) + self.assertGreaterEqual(report["elapsedSeconds"], 0.2) + self.assertLess(report["elapsedSeconds"], 1) + self.assertIn("did not become ready", check.stderr) + finally: + process.terminate() + process.wait(timeout=3) + + def test_exited_fixture_reports_process_failure_instead_of_waiting_for_timeout(self): + with tempfile.TemporaryDirectory(prefix="renewal-startup-exit-") as directory: + failed = subprocess.Popen([sys.executable, "-c", "raise SystemExit(7)"]) + failed.wait(timeout=2) + started = time.monotonic() + check = subprocess.run( + [sys.executable, str(ROOT / "tests/check-ios-renewal-startup.py"), + "--evidence-dir", directory, "--pid", str(failed.pid)], + capture_output=True, text=True, timeout=3) + self.assertNotEqual(check.returncode, 0) + report_file = Path(directory) / "fixture-startup-check.json" + self.assertTrue(report_file.exists(), "missing fixture startup process diagnostics") + report = json.loads(report_file.read_text()) + self.assertEqual(report["outcome"], "process-exited") + self.assertFalse(report["urlPublished"]) + self.assertLess(time.monotonic() - started, 2) + self.assertIn("process exited", check.stderr) + + def test_loopback_fixture_becomes_ready_without_reverse_dns(self): + # Resolver availability is an external startup dependency. Exercise the + # actual CLI, socket bind and HTTP state endpoint while that boundary + # cannot return; no fixture protocol or application behavior is mocked. + wrapper = """import runpy, socket, sys, time +def stalled_resolver(*args, **kwargs): + time.sleep(60) +socket.getfqdn = stalled_resolver +sys.argv = sys.argv[1:] +runpy.run_path(sys.argv[0], run_name='__main__') +""" + with tempfile.TemporaryDirectory(prefix="renewal-startup-") as directory: + process = subprocess.Popen( + [sys.executable, "-c", wrapper, + str(ROOT / "tests/fixtures/ios-renewal-http.py"), + "--evidence-dir", directory], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + url_file = Path(directory) / "fixture-url.txt" + deadline = time.monotonic() + 2 + while not url_file.exists() and time.monotonic() < deadline: + if process.poll() is not None: + self.fail("fixture exited before publishing readiness") + time.sleep(0.02) + self.assertTrue(url_file.exists(), + "Loopback renewal fixture did not become ready: reverse DNS stalled startup") + with urllib.request.urlopen(url_file.read_text().strip() + "/__test/state", timeout=1) as response: + self.assertEqual(response.status, 200) + self.assertEqual(json.load(response)["server"]["renewal"]["expiry_date"], "2026-01-31") + finally: + process.terminate() + process.communicate(timeout=5) + + class FixtureProtocolTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory(prefix="renewal-fixture-") @@ -40,6 +113,20 @@ def cleanup_fixture(self): self.process.communicate(timeout=5) self.temp.cleanup() + def test_ready_probe_preserves_success_evidence_using_only_loopback_transport(self): + # Proxies are a runner boundary, not part of this loopback fixture. + environment = {**os.environ, "http_proxy": "http://127.0.0.1:1", + "HTTP_PROXY": "http://127.0.0.1:1", "no_proxy": "", "NO_PROXY": ""} + check = subprocess.run( + [sys.executable, str(ROOT / "tests/check-ios-renewal-startup.py"), + "--evidence-dir", self.temp.name, "--pid", str(self.process.pid)], + env=environment, capture_output=True, text=True, timeout=3) + self.assertEqual(check.returncode, 0, check.stderr) + report = json.loads(self.directory.joinpath("fixture-startup-check.json").read_text()) + self.assertEqual(report["outcome"], "ready") + self.assertTrue(report["urlPublished"]) + self.assertGreaterEqual(report["attempts"], 1) + def request(self, path, method="GET", body=None, marker=True, host=None): headers = {"Content-Type": "application/json"} if marker: diff --git a/tests/check-ios-renewal-startup.py b/tests/check-ios-renewal-startup.py new file mode 100644 index 000000000..4018ccc0a --- /dev/null +++ b/tests/check-ios-renewal-startup.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Bounded real loopback readiness with preserved fixture process diagnostics.""" + +import argparse +import json +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--evidence-dir", type=Path, required=True) + parser.add_argument("--pid", type=int, required=True) + parser.add_argument("--timeout-seconds", type=float, default=10) + args = parser.parse_args() + if args.pid <= 0 or args.timeout_seconds <= 0: + parser.error("pid and timeout must be positive") + started = time.monotonic() + report = {"pid": args.pid, "timeoutSeconds": args.timeout_seconds, + "urlPublished": False, "attempts": 0, "lastProbeError": None} + outcome = "timeout" + while time.monotonic() - started < args.timeout_seconds: + # ps exposes an exited/zombie process on both hosted macOS and Linux; + # do not record command lines, environment variables or credentials. + process = subprocess.run(["ps", "-p", str(args.pid), "-o", "pid=", + "-o", "stat=", "-o", "etime="], + capture_output=True, text=True, timeout=1) + report["processStatus"] = process.stdout.strip() + fields = report["processStatus"].split() + if not fields or fields[1].startswith("Z"): + outcome = "process-exited" + break + report["attempts"] += 1 + try: + url = args.evidence_dir.joinpath("fixture-url.txt").read_text().strip() + report["urlPublished"] = True + # Readiness uses the same literal loopback transport as the UI. + # Never let runner proxy configuration redirect this local probe. + remaining = args.timeout_seconds - (time.monotonic() - started) + if remaining <= 0: + break + local_http = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with local_http.open(url + "/__test/state", timeout=min(1, remaining)) as response: + if response.status == 200: + outcome = "ready" + break + except (OSError, ValueError) as error: + report["lastProbeError"] = type(error).__name__ + time.sleep(min(0.1, max(0, args.timeout_seconds - (time.monotonic() - started)))) + report.update(outcome=outcome, elapsedSeconds=round(time.monotonic() - started, 3)) + args.evidence_dir.joinpath("fixture-startup-check.json").write_text( + json.dumps(report, indent=2) + "\n") + if outcome != "ready": + message = ("Loopback renewal fixture process exited before readiness" if outcome == "process-exited" + else f"Loopback renewal fixture did not become ready within {args.timeout_seconds:g} seconds") + print(message + "; see fixture-startup-check.json and fixture.log", file=sys.stderr) + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/tests/fixtures/ios-renewal-http.py b/tests/fixtures/ios-renewal-http.py index f73ae9091..6dfbf4e24 100644 --- a/tests/fixtures/ios-renewal-http.py +++ b/tests/fixtures/ios-renewal-http.py @@ -10,7 +10,10 @@ import argparse import copy import json +import socketserver +import sys import threading +import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import urlsplit @@ -227,15 +230,30 @@ def dispatch(self, path, body): return fixture.fail(f"unsupported fixture route: {method} {path}") +class LoopbackHTTPServer(ThreadingHTTPServer): + def server_bind(self): + # HTTPServer performs reverse DNS after bind. This numeric, IPv4-only + # local transport must not wait for the hosted runner's resolver. + socketserver.TCPServer.server_bind(self) + self.server_name, self.server_port = self.server_address[:2] + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--evidence-dir", type=Path, required=True) args = parser.parse_args() args.evidence_dir.mkdir(parents=True, exist_ok=True) - server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + def progress(stage): + print(f"[renewal-fixture {time.monotonic():.3f}] {stage}", file=sys.stderr, flush=True) + + progress("binding numeric IPv4 loopback socket") + server = LoopbackHTTPServer(("127.0.0.1", 0), Handler) + progress("socket bound; initializing fixture evidence") server.fixture = Fixture(args.evidence_dir) + progress("fixture initialized; publishing local URL") args.evidence_dir.joinpath("fixture-url.txt").write_text( f"http://127.0.0.1:{server.server_port}\n") + progress("URL published; serving loopback HTTP") server.serve_forever() From 66eeda12c75762475c0402b8709b87d5e5b88aac Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 22:04:41 +0000 Subject: [PATCH 37/40] fix(ios): isolate renewal UI sessions and tap native switches --- apps/ios/ServerBee/Services/AuthManager.swift | 4 +- .../ServerBee/Utilities/UITestSupport.swift | 15 +++++- .../PendingSessionRevocationTests.swift | 23 ++++++++ .../RenewalBillingUITests.swift | 23 +++++++- tests/check-ios-renewal-harness.py | 52 +++++++++++++++++++ tests/fixtures/ios-renewal-http.py | 34 +++++++++++- 6 files changed, 144 insertions(+), 7 deletions(-) diff --git a/apps/ios/ServerBee/Services/AuthManager.swift b/apps/ios/ServerBee/Services/AuthManager.swift index 06459f6ed..f0f2213d8 100644 --- a/apps/ios/ServerBee/Services/AuthManager.swift +++ b/apps/ios/ServerBee/Services/AuthManager.swift @@ -41,9 +41,7 @@ final class AuthManager { if let seed = UITestSupport.seed { setServerUrl(seed.serverUrl) if let installation = seed.installationId { try? KeychainService.saveString(installation, for: KeychainService.installationIdKey) } - handleLoginResponse(MobileTokenResponse(accessToken: seed.accessToken, accessExpiresInSecs: 900, - refreshToken: seed.refreshToken, refreshExpiresInSecs: 3600, tokenType: "Bearer", - user: MobileUser(id: seed.userId, username: seed.username, role: seed.role))) + handleLoginResponse(seed.tokenResponse) if UITestSupport.sessionRecovery, let context = captureContext() { do { try suspendSessionForRecovery(context: context) } catch { recoveryError = error.localizedDescription } } diff --git a/apps/ios/ServerBee/Utilities/UITestSupport.swift b/apps/ios/ServerBee/Utilities/UITestSupport.swift index 3875b8d52..7e12776f3 100644 --- a/apps/ios/ServerBee/Utilities/UITestSupport.swift +++ b/apps/ios/ServerBee/Utilities/UITestSupport.swift @@ -22,6 +22,17 @@ enum UITestSupport { /// the SAME id, so a seeded session survives access-token expiry instead /// of bouncing to the login screen. let installationId: String? + /// Complete out-of-band login metadata preserves the production + /// exact-session cleanup boundary across repeated Simulator launches. + let revocationToken: String? + let mobileSessionId: String? + + var tokenResponse: MobileTokenResponse { + MobileTokenResponse(accessToken: accessToken, accessExpiresInSecs: 900, + refreshToken: refreshToken, refreshExpiresInSecs: 3600, tokenType: "Bearer", + user: MobileUser(id: userId, username: username, role: role), + revocationToken: revocationToken, mobileSessionId: mobileSessionId) + } } static var seed: Seed? { @@ -39,7 +50,9 @@ enum UITestSupport { userId: env["SB_UITEST_USER_ID"] ?? "uitest", username: env["SB_UITEST_USERNAME"] ?? "admin", role: env["SB_UITEST_ROLE"] ?? "admin", - installationId: env["SB_UITEST_INSTALLATION_ID"] + installationId: env["SB_UITEST_INSTALLATION_ID"], + revocationToken: env["SB_UITEST_REVOCATION"], + mobileSessionId: env["SB_UITEST_MOBILE_SESSION_ID"] ) } diff --git a/apps/ios/ServerBeeTests/PendingSessionRevocationTests.swift b/apps/ios/ServerBeeTests/PendingSessionRevocationTests.swift index 4c71aa7c0..868081f8c 100644 --- a/apps/ios/ServerBeeTests/PendingSessionRevocationTests.swift +++ b/apps/ios/ServerBeeTests/PendingSessionRevocationTests.swift @@ -49,6 +49,29 @@ final class PendingSessionRevocationTests: XCTestCase { mobileSessionId: confirmed ? (name == "alice" ? "11111111-1111-4111-8111-111111111111" : "22222222-2222-4222-8222-222222222222") : nil)) } + #if DEBUG + func testUISeedReplacementRetainsOriginalProof() throws { + let seed = UITestSupport.Seed(serverUrl: "http://127.0.0.1:9527", + accessToken: "fixture-access", refreshToken: "fixture-refresh", + userId: "fixture-user", username: "fixture-admin", role: "admin", + installationId: "fixture-installation", revocationToken: "fixture-deletion", + mobileSessionId: "11111111-1111-4111-8111-111111111111") + let journal = MemorySessionRevocations() + let normal = MemoryAuthentication() + let auth = AuthManager(revocations: PendingSessionRevocations(storage: journal), authenticationStorage: normal, + cleanupSession: cleanupSession) + auth.handleLoginResponse(seed.tokenResponse, origin: seed.serverUrl, installationId: seed.installationId) + let original = try XCTUnwrap(normal.value) + XCTAssertEqual(original.confirmedDeletionProof, "fixture-deletion") + XCTAssertEqual(original.mobileSessionId, seed.mobileSessionId) + auth.handleLoginResponse(seed.tokenResponse, origin: seed.serverUrl, installationId: seed.installationId) + XCTAssertTrue(auth.isAuthenticated) + XCTAssertNil(auth.recoveryError) + XCTAssertEqual(journal.values, [try XCTUnwrap(original.revocation)]) + XCTAssertNotEqual(normal.value?.loginId, original.loginId) + } + #endif + func testOfflineLogoutRestartsSignedOutAndReplaysOnlyOriginalDeletionProof() async throws { let journal = MemorySessionRevocations() let normal = MemoryAuthentication() diff --git a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift index 4d12d4fe8..cdc570edd 100644 --- a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift +++ b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift @@ -45,7 +45,7 @@ final class RenewalBillingUITests: XCTestCase { try await launch(scenario: "switch") assertSwitch(enabled: false) assertDate("Jan 31, 2026") - reveal("renewal.enabled").tap() + tapRenewalSwitch() assertSwitch(enabled: true) screenshot("enable-selected") try await save(expectedCount: 1) @@ -60,7 +60,7 @@ final class RenewalBillingUITests: XCTestCase { let projected = try await fixtureState() let projectedRenewal = try renewal(in: projected) - reveal("renewal.enabled").tap() + tapRenewalSwitch() assertSwitch(enabled: false) try await save(expectedCount: 2) let disabledBody = try await capturedSave(index: 1) @@ -146,11 +146,20 @@ private extension RenewalBillingUITests { url.path.isEmpty, url.query == nil, url.user == nil else { throw FixtureError.invalidURL } fixtureURL = url _ = try await request("/__test/reset", body: ["scenario": scenario]) + let sessions = [ + "switch": "11111111-1111-4111-8111-111111111111", + "timezone": "22222222-2222-4222-8222-222222222222", + "manual": "33333333-3333-4333-8333-333333333333" + ] + guard let session = sessions[scenario] else { throw FixtureError.invalidState } app.launchArguments = ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"] app.launchEnvironment = [ "SB_UITEST_SERVER": raw, "SB_UITEST_ACCESS": "fixture-renewal-access", "SB_UITEST_REFRESH": "fixture-renewal-refresh", + "SB_UITEST_REVOCATION": "fixture-renewal-deletion", + "SB_UITEST_MOBILE_SESSION_ID": session, + "SB_UITEST_INSTALLATION_ID": "renewal-ui-installation-\(scenario)", "SB_UITEST_USERNAME": "fixture-admin", "SB_UITEST_USER_ID": "fixture-user", "SB_UITEST_ROLE": "admin", "SB_UITEST_DEEPLINK": "server:renewal-ui-server", "SB_UITEST_PRESENT": "edit-server", "SB_UITEST_RENEWAL_CONTEXT": "1" @@ -205,6 +214,16 @@ private extension RenewalBillingUITests { XCTAssertEqual(toggle.value as? String, enabled ? "1" : "0", toggle.debugDescription) } + func tapRenewalSwitch() { + // SwiftUI exposes both the full labelled row and its physical switch + // as Switch elements. A tap at the row center hits the label, whereas + // the actual control is the small trailing descendant switch. + let row = reveal("renewal.enabled") + let control = row.switches.firstMatch + XCTAssertTrue(control.exists && control.isHittable, row.debugDescription) + control.tap() + } + func assertExplanation(_ text: String) { let target = app.staticTexts[text].firstMatch for _ in 0..<8 { diff --git a/tests/check-ios-renewal-harness.py b/tests/check-ios-renewal-harness.py index f1ff647fb..1b735be58 100644 --- a/tests/check-ios-renewal-harness.py +++ b/tests/check-ios-renewal-harness.py @@ -185,6 +185,58 @@ def test_three_scenarios_capture_changed_intent_and_fixed_wire_responses(self): self.assertNotIn("fixture-renewal-access", capture) self.assertNotIn("Authorization", capture) + def test_refresh_uses_the_complete_synthetic_session_without_recording_credentials(self): + self.reset("switch") + status, reply = self.request("/api/mobile/auth/refresh", "POST", { + "refresh_token": "fixture-renewal-refresh", "installation_id": "renewal-ui-installation-switch" + }, marker=False) + self.assertEqual(status, 200) + self.assertEqual(reply["data"]["user"]["id"], "fixture-user") + self.assertEqual(reply["data"]["mobile_session_id"], "11111111-1111-4111-8111-111111111111") + self.assertEqual(reply["data"]["revocation_token"], "fixture-renewal-deletion") + capture = self.directory.joinpath("fixture-requests.jsonl").read_text() + for value in ["fixture-renewal-refresh", "fixture-renewal-deletion", "refresh_token"]: + self.assertNotIn(value, capture) + + def test_previous_session_cleanup_keeps_its_exact_installation_and_session_scope(self): + self.reset("timezone") + status, reply = self.request("/api/mobile/auth/revoke", "POST", { + "revocation_token": "fixture-renewal-deletion", + "installation_id": "renewal-ui-installation-switch", + "expected_session_id": "11111111-1111-4111-8111-111111111111" + }, marker=False) + self.assertEqual(status, 200) + self.assertEqual(reply, {"data": "ok"}) + self.assertEqual(self.request("/__test/state")[1]["scenario"], "timezone") + capture = self.directory.joinpath("fixture-requests.jsonl").read_text() + self.assertNotIn("fixture-renewal-deletion", capture) + self.assertNotIn("revocation_token", capture) + + def test_synthetic_auth_rejects_missing_or_crossed_identity_and_preserves_errors(self): + self.reset("switch") + for body in [{}, {"refresh_token": "arbitrary", "installation_id": "renewal-ui-installation-switch"}, + {"refresh_token": "fixture-renewal-refresh", "installation_id": "renewal-ui-installation-timezone"}]: + self.assertEqual(self.request("/api/mobile/auth/refresh", "POST", body, marker=False)[0], 422) + for body in [{"revocation_token": "arbitrary", "installation_id": "renewal-ui-installation-switch", + "expected_session_id": "11111111-1111-4111-8111-111111111111"}, + {"revocation_token": "fixture-renewal-deletion", "installation_id": "renewal-ui-installation-switch", + "expected_session_id": "22222222-2222-4222-8222-222222222222"}]: + self.assertEqual(self.request("/api/mobile/auth/revoke", "POST", body, marker=False)[0], 422) + self.assertEqual(len(self.reset("manual")["errors"]), 5) + + def test_refresh_response_tracks_each_isolated_synthetic_session(self): + expected = {"switch": "11111111-1111-4111-8111-111111111111", + "timezone": "22222222-2222-4222-8222-222222222222", + "manual": "33333333-3333-4333-8333-333333333333"} + for scenario, session in expected.items(): + self.reset(scenario) + status, reply = self.request("/api/mobile/auth/refresh", "POST", { + "refresh_token": "fixture-renewal-refresh", "installation_id": f"renewal-ui-installation-{scenario}" + }, marker=False) + self.assertEqual(status, 200) + self.assertEqual(reply["data"]["mobile_session_id"], session) + self.assertEqual(reply["data"]["revocation_token"], "fixture-renewal-deletion") + def test_explicit_date_resubmission_on_switch_save_is_rejected_and_error_survives_reset(self): self.reset("switch") self.assertEqual(self.save({"enabled": True, "expiry_date": "2026-01-31"})[0], 422) diff --git a/tests/fixtures/ios-renewal-http.py b/tests/fixtures/ios-renewal-http.py index 6dfbf4e24..11053553f 100644 --- a/tests/fixtures/ios-renewal-http.py +++ b/tests/fixtures/ios-renewal-http.py @@ -20,6 +20,13 @@ SERVER_ID = "renewal-ui-server" ACCESS_MARKER = "fixture-renewal-access" +REFRESH_MARKER = "fixture-renewal-refresh" +DELETION_MARKER = "fixture-renewal-deletion" +SESSION_IDS = { + "switch": "11111111-1111-4111-8111-111111111111", + "timezone": "22222222-2222-4222-8222-222222222222", + "manual": "33333333-3333-4333-8333-333333333333", +} NY_JANUARY = "2026-02-01T04:59:59.999999999Z" NY_FEBRUARY = "2026-03-01T04:59:59.999999999Z" NY_MANUAL = "2026-02-16T04:59:59.999999999Z" @@ -175,7 +182,7 @@ def handle_request(self): raise ValueError("invalid request length") if length: body = json.loads(self.rfile.read(length)) - if path.startswith("/api/"): + if path.startswith("/api/") and path not in {"/api/mobile/auth/refresh", "/api/mobile/auth/revoke"}: authorized = self.headers.get("Authorization") == f"Bearer {ACCESS_MARKER}" if not authorized: raise ValueError("application request lacks fixture marker") @@ -196,6 +203,31 @@ def handle_request(self): def dispatch(self, path, body): fixture = self.server.fixture method = self.command + if method == "POST" and path == "/api/mobile/auth/revoke": + # Replaying an older synthetic identity must keep its own target; + # replacement login does not authorize deleting the current one. + valid = [{"revocation_token": DELETION_MARKER, + "installation_id": f"renewal-ui-installation-{scenario}", + "expected_session_id": session} + for scenario, session in SESSION_IDS.items()] + if body not in valid: + return fixture.fail("invalid synthetic exact-session cleanup") + return 200, {"data": "ok"} + if method == "POST" and path == "/api/mobile/auth/refresh": + # Normal refresh authenticates by its captured body, not a bearer + # header. Keep this local client seam strict and per-scenario; never + # admit arbitrary authentication/provider traffic. + expected = {"refresh_token": REFRESH_MARKER, + "installation_id": f"renewal-ui-installation-{fixture.scenario}"} + if fixture.scenario not in SESSION_IDS or body != expected: + return fixture.fail("invalid synthetic refresh identity") + return 200, {"data": { + "access_token": ACCESS_MARKER, "access_expires_in_secs": 900, + "refresh_token": REFRESH_MARKER, "refresh_expires_in_secs": 3600, + "token_type": "Bearer", "revocation_token": DELETION_MARKER, + "mobile_session_id": SESSION_IDS[fixture.scenario], + "user": {"id": "fixture-user", "username": "fixture-admin", "role": "admin"}, + }} if method == "GET" and path == "/__test/state": return 200, fixture.state() if method == "POST" and path == "/__test/reset": From 7a35ce2ef23b7fa1bb92b44bb853d0656115dfb0 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 22:41:02 +0000 Subject: [PATCH 38/40] fix(ios): scroll timezone menu and dismiss renewal calendar --- .../RenewalBillingUITests.swift | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift index cdc570edd..a3fc5a3b2 100644 --- a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift +++ b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift @@ -24,7 +24,19 @@ final class RenewalBillingUITests: XCTestCase { reveal("renewal.timezone").tap() let utc = app.buttons["UTC"].firstMatch + // The native menu scrolls to the current selection, so UTC at the + // beginning of the IANA list is initially outside its lazy viewport. + // Retain the menu's indexed element before scrolling moves that + // selection out of view; swiping the app would hit a different layer. + let menu = try XCTUnwrap(app.collectionViews.allElementsBoundByIndex.last(where: { + $0.buttons["America/New_York"].exists + }), app.debugDescription) + for _ in 0..<14 { + if utc.exists && utc.isHittable { break } + menu.swipeDown(velocity: .fast) + } XCTAssertTrue(utc.waitForExistence(timeout: 5), app.debugDescription) + XCTAssertTrue(utc.isHittable, app.debugDescription) utc.tap() assertText("renewal.timezone", contains: "UTC") assertDate("Jan 31, 2026") @@ -99,10 +111,14 @@ final class RenewalBillingUITests: XCTestCase { } screenshot("manual-calendar-before-day-selection") selectedDay.tap() - // The date popover can stay open after selection; tapping its production - // row label dismisses it without changing the chosen calendar date. - if app.buttons["15"].firstMatch.isHittable { - app.staticTexts["Expires"].firstMatch.tap() + // UIKit labels the day Button with its full date; "15" is a child + // StaticText. If the calendar stays open, a real tap on the editor + // title outside that popover dismisses it without changing the date. + if selectedDay.exists { + let navigation = app.navigationBars["Edit Server"] + XCTAssertTrue(navigation.exists, app.debugDescription) + navigation.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap() + XCTAssertFalse(selectedDay.exists, "Calendar must dismiss after the outside tap: \(app.debugDescription)") } assertDate("Feb 15, 2026") screenshot("manual-february-fifteenth-selected") From 4d0f147c85874c84d0ab729bd51965cdd3c0c561 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Mon, 5 Oct 2026 23:23:40 +0000 Subject: [PATCH 39/40] fix(ios): drag across the visible timezone menu --- .../ServerBeeUITests/RenewalBillingUITests.swift | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift index a3fc5a3b2..90a6e1f09 100644 --- a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift +++ b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift @@ -33,7 +33,18 @@ final class RenewalBillingUITests: XCTestCase { }), app.debugDescription) for _ in 0..<14 { if utc.exists && utc.isHittable { break } - menu.swipeDown(velocity: .fast) + // The menu's accessibility frame extends beyond the window. + // Drag across its visible viewport instead of using XCTest's + // shorter default swipe, which stopped among the Africa entries. + let frame = menu.frame + let viewport = frame.intersection(app.windows.firstMatch.frame) + XCTAssertFalse(viewport.isEmpty, menu.debugDescription) + let origin = menu.coordinate(withNormalizedOffset: .zero) + let start = origin.withOffset(CGVector(dx: viewport.midX - frame.minX, + dy: viewport.minY + viewport.height * 0.1 - frame.minY)) + let end = origin.withOffset(CGVector(dx: viewport.midX - frame.minX, + dy: viewport.minY + viewport.height * 0.9 - frame.minY)) + start.press(forDuration: 0.05, thenDragTo: end) } XCTAssertTrue(utc.waitForExistence(timeout: 5), app.debugDescription) XCTAssertTrue(utc.isHittable, app.debugDescription) From d82ed7006b4ac070f6e3d01930e773c4e98532b4 Mon Sep 17 00:00:00 2001 From: ZingerLittleBee <6970999@gmail.com> Date: Tue, 6 Oct 2026 00:13:19 +0000 Subject: [PATCH 40/40] fix(ios): make billing timezone selection searchable --- apps/ios/ServerBee/Localizable.xcstrings | 17 ++++++++ .../Enrollment/BillingTimezoneSelector.swift | 41 +++++++++++++++++++ .../Servers/Enrollment/EditServerSheet.swift | 22 ++++++---- .../RenewalBillingUITests.swift | 30 ++++---------- 4 files changed, 81 insertions(+), 29 deletions(-) create mode 100644 apps/ios/ServerBee/Views/Servers/Enrollment/BillingTimezoneSelector.swift diff --git a/apps/ios/ServerBee/Localizable.xcstrings b/apps/ios/ServerBee/Localizable.xcstrings index 145e9c20c..b381df258 100644 --- a/apps/ios/ServerBee/Localizable.xcstrings +++ b/apps/ios/ServerBee/Localizable.xcstrings @@ -14690,6 +14690,23 @@ } } }, + "Search billing timezones": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Search billing timezones" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "搜索账单时区" + } + } + } + }, "Search name, IP, tag": { "extractionState": "manual", "localizations": { diff --git a/apps/ios/ServerBee/Views/Servers/Enrollment/BillingTimezoneSelector.swift b/apps/ios/ServerBee/Views/Servers/Enrollment/BillingTimezoneSelector.swift new file mode 100644 index 000000000..1556d5814 --- /dev/null +++ b/apps/ios/ServerBee/Views/Servers/Enrollment/BillingTimezoneSelector.swift @@ -0,0 +1,41 @@ +import SwiftUI + +/// Selects a literal IANA billing timezone without changing other editor fields. +struct BillingTimezoneSelector: View { + @Binding var selection: String + let timezones: [String] + + @Environment(\.dismiss) private var dismiss + @State private var query = "" + + private var filteredTimezones: [String] { + let search = query.trimmingCharacters(in: .whitespacesAndNewlines) + return search.isEmpty ? timezones : timezones.filter { $0.localizedCaseInsensitiveContains(search) } + } + + var body: some View { + List(filteredTimezones, id: \.self) { timezone in + Button { + selection = timezone + dismiss() + } label: { + HStack { + Text(verbatim: timezone).foregroundStyle(.primary) + Spacer() + if selection == timezone { + Image(systemName: "checkmark") + .foregroundStyle(Color.brandAccent) + .accessibilityHidden(true) + } + } + } + .accessibilityAddTraits(selection == timezone ? .isSelected : []) + } + .navigationTitle(String(localized: "Billing timezone")) + .navigationBarTitleDisplayMode(.inline) + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), + prompt: String(localized: "Search billing timezones")) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } +} diff --git a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift index 1279429ac..9618816a7 100644 --- a/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift +++ b/apps/ios/ServerBee/Views/Servers/Enrollment/EditServerSheet.swift @@ -32,11 +32,13 @@ struct EditServerSheet: View { .navigationTitle(String(localized: "Edit Server")) .navigationBarTitleDisplayMode(.inline) .toolbar { toolbarContent } - .task { - viewModel.prefill(from: config) - await viewModel.loadGroups(apiClient: apiClient) - await viewModel.loadTags(serverId: serverId, apiClient: apiClient) - } + } + // Returning from timezone selection must preserve unsaved edits; + // initialization belongs to the editor presentation, not its form. + .task { + viewModel.prefill(from: config) + await viewModel.loadGroups(apiClient: apiClient) + await viewModel.loadTags(serverId: serverId, apiClient: apiClient) } } } @@ -99,8 +101,14 @@ private extension EditServerSheet { .accessibilityIdentifier("renewal.deviceTimezone") } #endif - Picker(String(localized: "Billing timezone"), selection: $viewModel.billingTimezone) { - ForEach(Self.billingTimezones, id: \.self) { Text(verbatim: $0).tag($0) } + NavigationLink { + BillingTimezoneSelector(selection: $viewModel.billingTimezone, timezones: Self.billingTimezones) + } label: { + HStack { + Text(String(localized: "Billing timezone")) + Spacer() + Text(verbatim: viewModel.billingTimezone).foregroundStyle(.secondary) + } } .accessibilityIdentifier("renewal.timezone") Toggle(String(localized: "Has expiry"), isOn: $viewModel.hasExpiry) diff --git a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift index 90a6e1f09..de484e171 100644 --- a/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift +++ b/apps/ios/ServerBeeUITests/RenewalBillingUITests.swift @@ -23,32 +23,18 @@ final class RenewalBillingUITests: XCTestCase { screenshot("stored-january-date") reveal("renewal.timezone").tap() + XCTAssertTrue(app.navigationBars["Billing timezone"].waitForExistence(timeout: 5), app.debugDescription) + let search = app.searchFields.matching(NSPredicate(format: "placeholderValue == %@", "Search billing timezones")).firstMatch + XCTAssertTrue(search.waitForExistence(timeout: 5), app.debugDescription) + XCTAssertTrue(search.isHittable, search.debugDescription) + search.tap() + search.typeText("UTC") let utc = app.buttons["UTC"].firstMatch - // The native menu scrolls to the current selection, so UTC at the - // beginning of the IANA list is initially outside its lazy viewport. - // Retain the menu's indexed element before scrolling moves that - // selection out of view; swiping the app would hit a different layer. - let menu = try XCTUnwrap(app.collectionViews.allElementsBoundByIndex.last(where: { - $0.buttons["America/New_York"].exists - }), app.debugDescription) - for _ in 0..<14 { - if utc.exists && utc.isHittable { break } - // The menu's accessibility frame extends beyond the window. - // Drag across its visible viewport instead of using XCTest's - // shorter default swipe, which stopped among the Africa entries. - let frame = menu.frame - let viewport = frame.intersection(app.windows.firstMatch.frame) - XCTAssertFalse(viewport.isEmpty, menu.debugDescription) - let origin = menu.coordinate(withNormalizedOffset: .zero) - let start = origin.withOffset(CGVector(dx: viewport.midX - frame.minX, - dy: viewport.minY + viewport.height * 0.1 - frame.minY)) - let end = origin.withOffset(CGVector(dx: viewport.midX - frame.minX, - dy: viewport.minY + viewport.height * 0.9 - frame.minY)) - start.press(forDuration: 0.05, thenDragTo: end) - } XCTAssertTrue(utc.waitForExistence(timeout: 5), app.debugDescription) XCTAssertTrue(utc.isHittable, app.debugDescription) + screenshot("timezone-search-utc") utc.tap() + XCTAssertTrue(app.navigationBars["Edit Server"].waitForExistence(timeout: 5), app.debugDescription) assertText("renewal.timezone", contains: "UTC") assertDate("Jan 31, 2026") screenshot("utc-picker-selected-date-preserved")