diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3cd620b..bde1739 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,20 +32,18 @@ jobs: xcodebuild -project Sweep.xcodeproj -scheme Sweep -configuration Release \ -sdk iphoneos -destination 'generic/platform=iOS' -derivedDataPath build \ CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO build | tee build.log - - name: Package unsigned IPA + - name: Package IPA for AltStore signing run: | - mkdir -p dist/Payload - cp -R build/Build/Products/Release-iphoneos/Sweep.app dist/Payload/ - cd dist - /usr/bin/zip -qr Sweep-0.2.1-unsigned.ipa Payload - shasum -a 256 Sweep-0.2.1-unsigned.ipa > SHA256.txt + python3 Tools/package_ipa.py --app build/Build/Products/Release-iphoneos/Sweep.app \ + --output dist/Sweep-0.6.0-AltStore.ipa - name: Upload phone-test beta uses: actions/upload-artifact@v4 with: - name: Sweep-0.2.1-beta-unsigned + name: Sweep-0.6.0-AltStore path: | - dist/Sweep-0.2.1-unsigned.ipa + dist/Sweep-0.6.0-AltStore.ipa dist/SHA256.txt + dist/SIGNING-METADATA.json retention-days: 14 - name: Build and validate Bill shortcut run: | diff --git a/.github/workflows/feature-validation.yml b/.github/workflows/feature-validation.yml new file mode 100644 index 0000000..896502c --- /dev/null +++ b/.github/workflows/feature-validation.yml @@ -0,0 +1,117 @@ +name: Validate Sweep delivery workflows +on: + pull_request: + branches: [master] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: sweep-feature-${{ github.ref }} + cancel-in-progress: true +jobs: + validate: + runs-on: macos-15-intel + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Select Xcode + run: sudo xcode-select -s /Applications/Xcode_16.4.app/Contents/Developer + - name: Test ledger compatibility, durable share queue and QR amounts + run: swift test + - name: Generate project + run: | + brew install xcodegen + xcodegen generate + - name: Build app and embedded Share Extension + run: | + set -o pipefail + xcodebuild -project Sweep.xcodeproj -scheme Sweep -configuration Release \ + -sdk iphoneos -destination 'generic/platform=iOS' -derivedDataPath build \ + CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO build | tee build.log + test -d build/Build/Products/Release-iphoneos/Sweep.app/PlugIns/SweepShare.appex + - name: Package IPA with verifiable App Group metadata for AltStore + run: | + python3 Tools/package_ipa.py --app build/Build/Products/Release-iphoneos/Sweep.app \ + --output dist/Sweep-0.6.0-AltStore.ipa + - name: Upload app for AltStore signing + uses: actions/upload-artifact@v4 + with: + name: Sweep-0.6.0-AltStore + path: | + dist/Sweep-0.6.0-AltStore.ipa + dist/SHA256.txt + dist/SIGNING-METADATA.json + retention-days: 14 + - name: Upload device build log + if: failure() + uses: actions/upload-artifact@v4 + with: + name: Sweep-device-build-log + path: build.log + if-no-files-found: ignore + ui: + name: Simulator intake regression checks + needs: validate + runs-on: macos-15-intel + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Select Xcode + run: sudo xcode-select -s /Applications/Xcode_16.4.app/Contents/Developer + - name: Generate project + run: | + brew install xcodegen + xcodegen generate + - name: Verify shared image confirmation after presentation + run: | + set -o pipefail + SIMULATOR_ID=$(xcrun simctl list devices available -j | python3 -c 'import json,sys; d=json.load(sys.stdin); print(next(x["udid"] for runtime,items in d["devices"].items() if "iOS-18-5" in runtime for x in items if x["name"] == "iPhone 16"))') + xcrun simctl boot "$SIMULATOR_ID" || true + xcrun simctl bootstatus "$SIMULATOR_ID" -b + xcodebuild -project Sweep.xcodeproj -scheme Sweep -configuration Debug \ + -destination "platform=iOS Simulator,id=$SIMULATOR_ID" -derivedDataPath build-simulator \ + -resultBundlePath build-share-ui.xcresult CODE_SIGNING_ALLOWED=NO \ + -parallel-testing-enabled NO \ + -test-timeouts-enabled YES -default-test-execution-time-allowance 180 -maximum-test-execution-time-allowance 300 \ + -only-testing:SweepUITests/SweepUITests/testSharedImageReviewImportQRSetupAndRelaunch test | tee share-test.log + - name: Verify remaining delivery screens and new tools + run: | + set -o pipefail + SIMULATOR_ID=$(xcrun simctl list devices available -j | python3 -c 'import json,sys; d=json.load(sys.stdin); print(next(x["udid"] for runtime,items in d["devices"].items() if "iOS-18-5" in runtime for x in items if x["name"] == "iPhone 16"))') + xcodebuild -project Sweep.xcodeproj -scheme Sweep -configuration Debug \ + -destination "platform=iOS Simulator,id=$SIMULATOR_ID" -derivedDataPath build-simulator \ + -resultBundlePath build-ui.xcresult CODE_SIGNING_ALLOWED=NO \ + -parallel-testing-enabled NO \ + -test-timeouts-enabled YES -default-test-execution-time-allowance 180 -maximum-test-execution-time-allowance 300 \ + -only-testing:SweepUITests/SweepUITests/testBillPreviewOCRImportAndRelaunch \ + -only-testing:SweepUITests/SweepUITests/testRecordedTransferStillDisplaysQRCode \ + -only-testing:SweepUITests/SweepUITests/testReportImageSelectionAndCompactTransferCaption \ + -only-testing:SweepUITests/SweepUITests/testReconciliationEmptyMonthHasNoFiguresFromAnotherMonth \ + -only-testing:SweepUITests/SweepUITests/testIntakeHasOnlyPhotoAndCameraSourcesAtLargeTextSize \ + -only-testing:SweepUITests/SweepUITests/testApprovedCashWorkflowAndNewTools \ + -only-testing:SweepUITests/SweepUITests/testUpdate02CompactContactsAndPlaces \ + -only-testing:SweepUITests/SweepUITests/testUpdate02AttendanceCalendarSavesAndPersists test-without-building | tee simulator-test.log + - name: Export screenshots + if: always() + run: | + if [ -d build-share-ui.xcresult ]; then + xcrun xcresulttool export attachments --path build-share-ui.xcresult --output-path ui-share-screenshots || true + fi + if [ -d build-ui.xcresult ]; then + xcrun xcresulttool export attachments --path build-ui.xcresult --output-path ui-screenshots || true + fi + - uses: actions/upload-artifact@v4 + if: always() + with: + name: Sweep-feature-validation-evidence + path: | + build.log + share-test.log + simulator-test.log + ui-share-screenshots/ + ui-screenshots/ + if-no-files-found: ignore diff --git a/Design/AppIcon-Source.jpeg b/Design/AppIcon-Source.jpeg new file mode 100644 index 0000000..0bcc136 Binary files /dev/null and b/Design/AppIcon-Source.jpeg differ diff --git a/Package.swift b/Package.swift index 763f446..37d3b04 100644 --- a/Package.swift +++ b/Package.swift @@ -7,7 +7,7 @@ let package = Package( products: [.library(name: "SweepCore", targets: ["SweepCore"])], targets: [ .target(name: "SweepCore", path: "Sweep", - exclude: ["App", "Services", "Views", "Info.plist", "PrivacyInfo.xcprivacy", "Assets.xcassets"], + exclude: ["App", "Services", "Views", "Info.plist", "PrivacyInfo.xcprivacy", "Assets.xcassets", "Sweep.entitlements"], sources: ["Core", "Imaging"]), .testTarget(name: "SweepCoreTests", dependencies: ["SweepCore"], path: "Tests") ] diff --git a/README.md b/README.md index 6bd33d6..8e41c4b 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ xcodebuild -project Sweep.xcodeproj -scheme Sweep -configuration Release \ CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO build ``` -GitHub Actions **Build Sweep IPA** chạy kiểm thử core và build app arm64. Artifact chứa **IPA chưa ký**, cần ký/cài qua công cụ sideload. Chưa tự phát hành lên nguồn AltStore; chỉ thêm sau khi thử trên máy thật. +GitHub Actions **Build Sweep IPA** chạy kiểm thử core và build app arm64. Bản Sweep 0.4.0 (7) đã có trong [nguồn AltStore chung với StikDebug VN](https://raw.githubusercontent.com/Sentechtipsvn/Stikdebug-VN/main/altstore/altstore.json). IPA giữ Share Extension và metadata App Groups; AltStore vẫn cần ký lại để cài trên iPhone. Kiểm thử mới bao gồm công theo ngày ký, chống lặp, tiền thực tế, đối soát CK, lịch sử bất biến, SQLite mở lại, nhập schema Bill, CSV, sao lưu/ảnh lỗi và điều hướng trên simulator. Các bài kiểm thử công cụ ảnh: nhóm trùng theo hash/byte, bỏ tài nguyên không hỗ trợ, gợi ý giữ ảnh yêu thích, ngăn xóa hết nhóm, không đếm lặp ID, đường dẫn/symlink thoát thư mục, ảnh nén đúng kích thước/chiều xoay/bỏ GPS/giữ đầu vào và từ chối tệp lỗi. Chúng không thay thế kiểm thử PhotoKit/quyền/xóa/iCloud trên iPhone. diff --git a/Releases/0.4.0/SHA256.txt b/Releases/0.4.0/SHA256.txt new file mode 100644 index 0000000..252ef69 --- /dev/null +++ b/Releases/0.4.0/SHA256.txt @@ -0,0 +1 @@ +25b01fcd19cc66d84792e9a72d779a14a9526523eb2058477154f75cc92754ef Sweep-0.4.0-AltStore.ipa diff --git a/Releases/0.4.0/Sweep-0.4.0-AltStore.ipa b/Releases/0.4.0/Sweep-0.4.0-AltStore.ipa new file mode 100644 index 0000000..d38abae Binary files /dev/null and b/Releases/0.4.0/Sweep-0.4.0-AltStore.ipa differ diff --git a/Releases/0.4.0/manifest.json b/Releases/0.4.0/manifest.json new file mode 100644 index 0000000..02e4c6f --- /dev/null +++ b/Releases/0.4.0/manifest.json @@ -0,0 +1,11 @@ +{ + "version": "0.4.0", + "build": "7", + "size": 1296709, + "sha256": "25b01fcd19cc66d84792e9a72d779a14a9526523eb2058477154f75cc92754ef", + "appBundleIdentifier": "com.sentechtipsvn.sweep", + "extensionBundleIdentifier": "com.sentechtipsvn.sweep.share", + "sourceCommit": "b1ad9da4c92c160d6dca7d32b8f12029222f60c3", + "validationWorkflow": "https://github.com/Sentechtipsvn/Sweep/actions/runs/43525588962", + "signing": "Ad-hoc App Group metadata; AltStore must re-sign the app and retained Share Extension." +} diff --git a/Sweep/App/DeliveryTestSupport.swift b/Sweep/App/DeliveryTestSupport.swift index 7a8b7c6..d6f07a6 100644 --- a/Sweep/App/DeliveryTestSupport.swift +++ b/Sweep/App/DeliveryTestSupport.swift @@ -2,6 +2,14 @@ import UIKit extension DeliveryStore { + func installUpdate02UITestFixture() { + guard ledger.contacts?.isEmpty != false else { return } + _ = change { ledger in + try ledger.saveContact(DeliveryContact(name: "Liên hệ thử 01", phone: "0900000001", zalo: "", aliases: "TEL", role: "Bán hàng")) + try ledger.saveContact(DeliveryContact(name: "Liên hệ thử 02", phone: "0900000002", zalo: "", aliases: "", role: "Tài xế")) + try ledger.savePlace(DeliveryPlace(customer: "Điểm giao thử", phone: "0900000003", address: "Địa chỉ thử nghiệm", kind: "Khách hàng")) + } + } func installUITestFixture() { guard ProcessInfo.processInfo.arguments.contains("--delivery-ui-testing"), ledger.orders.isEmpty else { return } do { @@ -20,6 +28,39 @@ extension DeliveryStore { } extension DeliveryStore { + func installMonthlyUITestFixture() { + guard ProcessInfo.processInfo.arguments.contains("--delivery-ui-testing"), let order = ledger.orders.first, order.settlement == nil else { return } + _ = change { ledger in + try ledger.sign(order.id, at: Date()) + try ledger.settle(order.id, value: Settlement(outcome: .delivered, mode: .mixed, cash: 665_000, bank: 1_500_000, note: "", at: Date(), route: .transferNow)) + try ledger.handover(500_000, at: Date(), note: "UI test monthly remittance") + } + } + + func installQRUITestFixture() { + guard ProcessInfo.processInfo.arguments.contains("--delivery-ui-testing"), let order = ledger.orders.first else { return } + _ = change { ledger in + // Official VietQR documentation's public example; never part of a Release build. + ledger.settings.vietQR = VietQRAccount(bankID: "ICB", accountNumber: "113366668888", accountName: "PUBLIC DEMO ACCOUNT") + try ledger.sign(order.id, at: Date()) + try ledger.settle(order.id, value: Settlement(outcome: .delivered, mode: .bank, cash: 0, bank: order.total, note: "UI test: recorded transfer", at: Date(), route: .transferNow)) + } + } + + func installSharedUITestFixture() async throws { + guard ProcessInfo.processInfo.arguments.contains("--delivery-ui-testing") else { return } + let marker = root.appendingPathComponent("shared-fixture-sent") + guard !FileManager.default.fileExists(atPath: marker.path) else { return } + try Data().write(to: marker) + do { + let source = try billUITestResult().candidates[0].image + guard let image = UIImage(contentsOfFile: source.path) else { throw DeliveryError.invalid("Không mở được ảnh mẫu UI.") } + let received = try await SharedInvoiceLoader.load(from: NSItemProvider(item: image, typeIdentifier: "public.image")) + defer { try? FileManager.default.removeItem(at: received) } + _ = try SharedInvoiceInbox.live().add(received) + } catch { try? FileManager.default.removeItem(at: marker); throw error } + } + func billUITestResult() throws -> BillImportResult { let image = UIGraphicsImageRenderer(size: CGSize(width: 1400, height: 800)).image { context in UIColor.white.setFill(); context.fill(CGRect(x: 0, y: 0, width: 1400, height: 800)) diff --git a/Sweep/App/SweepApp.swift b/Sweep/App/SweepApp.swift index 99d6357..b02586b 100644 --- a/Sweep/App/SweepApp.swift +++ b/Sweep/App/SweepApp.swift @@ -4,26 +4,39 @@ import SwiftUI struct SweepApp: App { @StateObject private var library = PhotoStore() @StateObject private var delivery = DeliveryStore() + @StateObject private var router = SweepRouter() + @StateObject private var renewal = RenewalManager() + @Environment(\.scenePhase) private var scenePhase var body: some Scene { WindowGroup { - TabView { - OrdersView().tabItem { Label("Đơn hàng", systemImage: "shippingbox") } + TabView(selection: $router.tab) { + OrdersView().tabItem { Label("Đơn hàng", systemImage: "shippingbox") }.tag(0) NavigationStack { ReconciliationView() } - .tabItem { Label("Đối soát", systemImage: "checklist") } - NavigationStack { HomeView() } - .tabItem { Label("Công cụ", systemImage: "sparkles") } - NavigationStack { SettingsView() } - .tabItem { Label("Cài đặt", systemImage: "gearshape") } + .tabItem { Label("Lịch sử", systemImage: "clock.arrow.circlepath") }.tag(1) + NavigationStack(path: $router.tools) { HomeView().navigationDestination(for: String.self) { _ in PayrollView() } } + .tabItem { Label("Công cụ", systemImage: "sparkles") }.tag(2) + NavigationStack(path: $router.settings) { SettingsView().navigationDestination(for: String.self) { _ in RenewalView() } } + .tabItem { Label("Cài đặt", systemImage: "gearshape") }.tag(3) } - .tint(.green) + .tint(SweepStyle.blue) .environmentObject(library) .environmentObject(delivery) + .environmentObject(router) + .environmentObject(renewal) + .onOpenURL { router.open($0) } + .onReceive(NotificationCenter.default.publisher(for: .sweepInboxReceived)) { _ in router.tab = 0 } + .onReceive(NotificationCenter.default.publisher(for: .sweepRenewalSelected)) { _ in router.tab = 3; router.settings = ["renewal"] } + .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await renewal.refresh() } } } .background(DeliveryFeedback(store: delivery).frame(width: 0, height: 0)) .task { #if DEBUG if ProcessInfo.processInfo.arguments.contains("--seed-delivery") { delivery.installUITestFixture() } + if ProcessInfo.processInfo.arguments.contains("--qr-ui-testing") { delivery.installQRUITestFixture() } + if ProcessInfo.processInfo.arguments.contains("--monthly-ui-testing") { delivery.installMonthlyUITestFixture() } + if ProcessInfo.processInfo.arguments.contains("--update02-ui-testing") { delivery.installUpdate02UITestFixture() } #endif if library.canRead { library.reload() } + await renewal.refresh() } } } diff --git a/Sweep/App/SweepRouting.swift b/Sweep/App/SweepRouting.swift new file mode 100644 index 0000000..f9ec830 --- /dev/null +++ b/Sweep/App/SweepRouting.swift @@ -0,0 +1,59 @@ +import SwiftUI +import AppIntents + +extension Notification.Name { + static let sweepInboxReceived = Notification.Name("SweepInboxReceived") + static let sweepRenewalSelected = Notification.Name("SweepRenewalSelected") +} +@MainActor +final class SweepRouter: ObservableObject { + @Published var tab = 0 + @Published var tools: [String] = [] + @Published var settings: [String] = [] + @Published var orderID: UUID? + func open(_ url: URL) { + guard url.scheme == "sweep", url.user == nil, url.password == nil, + let host = url.host, url.query == nil, url.fragment == nil else { return } + switch host { + case "attendance", "payroll": + guard url.path.isEmpty else { return }; tab = 2; tools = ["payroll"] + case "renewal": + guard url.path.isEmpty else { return }; tab = 3; settings = ["renewal"] + case "order": + guard let id = UUID(uuidString: String(url.path.dropFirst())), url.path.split(separator: "/").count == 1 else { return } + orderID = id; tab = 0 + default: break + } + } +} +struct ReceiveSweepInvoice: AppIntent { + static var title: LocalizedStringResource = "Nhận phiếu Sweep" + static var description = IntentDescription("Nhận ảnh chia sẻ và mở Sweep để kiểm tra, đọc và nhập đơn.") + static var openAppWhenRun = true + @Parameter(title: "Ảnh phiếu") var image: IntentFile + func perform() async throws -> some IntentResult { + let bytes = image.data + guard !bytes.isEmpty, bytes.count <= 80 * 1024 * 1024 else { throw DeliveryError.invalid("Chọn một ảnh phiếu tối đa 80 MB.") } + _ = try await Task.detached(priority: .userInitiated) { + let url = try IncomingInvoiceImage.copy(data: bytes) + defer { try? FileManager.default.removeItem(at: url) } + return try SharedInvoiceInbox.live().add(url) + }.value + await MainActor.run { NotificationCenter.default.post(name: .sweepInboxReceived, object: nil) } + return .result() + } +} +struct SweepShortcutGuide: View { + var body: some View { + List { + Section("Nhận ảnh và mở Sweep") { + Text("Trong Phím tắt, tạo phím tắt “Nhận phiếu Sweep”, bật Hiển thị trong bảng chia sẻ và nhận đầu vào là Hình ảnh.") + Text("Thêm tác vụ “Nhận phiếu Sweep” của ứng dụng Sweep, chọn Ảnh phiếu = Đầu vào phím tắt.") + Text("Trong Zalo hoặc Ảnh: Chia sẻ → Nhận phiếu Sweep. App nhận ảnh vào hàng đợi rồi mở trang kiểm tra đơn.") + } + Section { + Text("Cần thử trên iPhone với phiên bản Zalo đang dùng. Đây là đường Phím tắt; biểu tượng Sweep trong bảng chia sẻ vẫn là tiện ích nhận ảnh, không tự bật app chính.").font(.footnote).foregroundStyle(.secondary) + } + }.navigationTitle("Nhận ảnh bằng Phím tắt").navigationBarTitleDisplayMode(.inline) + } +} diff --git a/Sweep/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/Sweep/Assets.xcassets/AppIcon.appiconset/AppIcon.png index f3a5023..38469b6 100644 Binary files a/Sweep/Assets.xcassets/AppIcon.appiconset/AppIcon.png and b/Sweep/Assets.xcassets/AppIcon.appiconset/AppIcon.png differ diff --git a/Sweep/Assets.xcassets/tool-cleanup.imageset/Contents.json b/Sweep/Assets.xcassets/tool-cleanup.imageset/Contents.json new file mode 100644 index 0000000..ae4d23e --- /dev/null +++ b/Sweep/Assets.xcassets/tool-cleanup.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "icon.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} diff --git a/Sweep/Assets.xcassets/tool-cleanup.imageset/icon.svg b/Sweep/Assets.xcassets/tool-cleanup.imageset/icon.svg new file mode 100644 index 0000000..0f3af7d --- /dev/null +++ b/Sweep/Assets.xcassets/tool-cleanup.imageset/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Sweep/Assets.xcassets/tool-compress.imageset/Contents.json b/Sweep/Assets.xcassets/tool-compress.imageset/Contents.json new file mode 100644 index 0000000..ae4d23e --- /dev/null +++ b/Sweep/Assets.xcassets/tool-compress.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "icon.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} diff --git a/Sweep/Assets.xcassets/tool-compress.imageset/icon.svg b/Sweep/Assets.xcassets/tool-compress.imageset/icon.svg new file mode 100644 index 0000000..d142099 --- /dev/null +++ b/Sweep/Assets.xcassets/tool-compress.imageset/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Sweep/Assets.xcassets/tool-contacts.imageset/Contents.json b/Sweep/Assets.xcassets/tool-contacts.imageset/Contents.json new file mode 100644 index 0000000..ae4d23e --- /dev/null +++ b/Sweep/Assets.xcassets/tool-contacts.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "icon.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} diff --git a/Sweep/Assets.xcassets/tool-contacts.imageset/icon.svg b/Sweep/Assets.xcassets/tool-contacts.imageset/icon.svg new file mode 100644 index 0000000..13fcca6 --- /dev/null +++ b/Sweep/Assets.xcassets/tool-contacts.imageset/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Sweep/Assets.xcassets/tool-duplicates.imageset/Contents.json b/Sweep/Assets.xcassets/tool-duplicates.imageset/Contents.json new file mode 100644 index 0000000..ae4d23e --- /dev/null +++ b/Sweep/Assets.xcassets/tool-duplicates.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "icon.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} diff --git a/Sweep/Assets.xcassets/tool-duplicates.imageset/icon.svg b/Sweep/Assets.xcassets/tool-duplicates.imageset/icon.svg new file mode 100644 index 0000000..c2f2efc --- /dev/null +++ b/Sweep/Assets.xcassets/tool-duplicates.imageset/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Sweep/Assets.xcassets/tool-files.imageset/Contents.json b/Sweep/Assets.xcassets/tool-files.imageset/Contents.json new file mode 100644 index 0000000..ae4d23e --- /dev/null +++ b/Sweep/Assets.xcassets/tool-files.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "icon.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} diff --git a/Sweep/Assets.xcassets/tool-files.imageset/icon.svg b/Sweep/Assets.xcassets/tool-files.imageset/icon.svg new file mode 100644 index 0000000..85cc5db --- /dev/null +++ b/Sweep/Assets.xcassets/tool-files.imageset/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Sweep/Assets.xcassets/tool-payroll.imageset/Contents.json b/Sweep/Assets.xcassets/tool-payroll.imageset/Contents.json new file mode 100644 index 0000000..1613617 --- /dev/null +++ b/Sweep/Assets.xcassets/tool-payroll.imageset/Contents.json @@ -0,0 +1 @@ +{"images":[{"filename":"icon.svg","idiom":"universal"}],"info":{"author":"xcode","version":1},"properties":{"preserves-vector-representation":true}} diff --git a/Sweep/Assets.xcassets/tool-payroll.imageset/icon.svg b/Sweep/Assets.xcassets/tool-payroll.imageset/icon.svg new file mode 100644 index 0000000..1242acb --- /dev/null +++ b/Sweep/Assets.xcassets/tool-payroll.imageset/icon.svg @@ -0,0 +1 @@ + diff --git a/Sweep/Assets.xcassets/tool-places.imageset/Contents.json b/Sweep/Assets.xcassets/tool-places.imageset/Contents.json new file mode 100644 index 0000000..ae4d23e --- /dev/null +++ b/Sweep/Assets.xcassets/tool-places.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "icon.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} diff --git a/Sweep/Assets.xcassets/tool-places.imageset/icon.svg b/Sweep/Assets.xcassets/tool-places.imageset/icon.svg new file mode 100644 index 0000000..1020743 --- /dev/null +++ b/Sweep/Assets.xcassets/tool-places.imageset/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Sweep/Assets.xcassets/tool-screenshots.imageset/Contents.json b/Sweep/Assets.xcassets/tool-screenshots.imageset/Contents.json new file mode 100644 index 0000000..ae4d23e --- /dev/null +++ b/Sweep/Assets.xcassets/tool-screenshots.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "icon.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} diff --git a/Sweep/Assets.xcassets/tool-screenshots.imageset/icon.svg b/Sweep/Assets.xcassets/tool-screenshots.imageset/icon.svg new file mode 100644 index 0000000..f01b632 --- /dev/null +++ b/Sweep/Assets.xcassets/tool-screenshots.imageset/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Sweep/Core/AppGroupConfiguration.swift b/Sweep/Core/AppGroupConfiguration.swift new file mode 100644 index 0000000..ede3677 --- /dev/null +++ b/Sweep/Core/AppGroupConfiguration.swift @@ -0,0 +1,17 @@ +import Foundation + +enum AppGroupConfiguration { + /// AltStore rewrites provisioning groups and publishes the new IDs in each bundle's Info.plist. + /// A custom build setting is not rewritten by AltStore and must only be the fallback. + static func identifiers(in info: [String: Any]) -> [String] { + let values: [String] + if let injected = info["ALTAppGroups"] { + values = injected as? [String] ?? [] + } else { + values = (info["SweepAppGroupIdentifier"] as? String).map { [$0] } ?? [] + } + return Array(Set(values.filter { + $0.count <= 255 && $0.range(of: #"^group\.[A-Za-z0-9][A-Za-z0-9._-]*$"#, options: .regularExpression) != nil + })).sorted() + } +} diff --git a/Sweep/Core/DeliveryDirections.swift b/Sweep/Core/DeliveryDirections.swift new file mode 100644 index 0000000..192c979 --- /dev/null +++ b/Sweep/Core/DeliveryDirections.swift @@ -0,0 +1,14 @@ +import Foundation + +enum DeliveryDirections { + static func googleMaps(address: String, native: Bool = true) -> URL? { + let destination = address.trimmingCharacters(in: .whitespacesAndNewlines) + guard !destination.isEmpty else { return nil } + var parts = URLComponents(string: native ? "comgooglemaps://" : "https://www.google.com/maps/dir/")! + parts.queryItems = native + ? [URLQueryItem(name: "daddr", value: destination), URLQueryItem(name: "directionsmode", value: "driving")] + : [URLQueryItem(name: "api", value: "1"), URLQueryItem(name: "destination", value: destination), URLQueryItem(name: "travelmode", value: "driving"), URLQueryItem(name: "dir_action", value: "navigate")] + parts.percentEncodedQuery = parts.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") + return parts.url + } +} diff --git a/Sweep/Core/DeliveryDirectory.swift b/Sweep/Core/DeliveryDirectory.swift new file mode 100644 index 0000000..c7fe70a --- /dev/null +++ b/Sweep/Core/DeliveryDirectory.swift @@ -0,0 +1,61 @@ +import Foundation + +struct DeliveryContact: Codable, Identifiable, Equatable { + var id = UUID() + var name: String + var phone: String + var zalo: String + var aliases: String + var role: String + func matches(_ seller: String) -> Bool { + let key = seller.trimmingCharacters(in: .whitespacesAndNewlines) + guard !key.isEmpty else { return false } + return ([name] + aliases.components(separatedBy: ",")).contains { $0.trimmingCharacters(in: .whitespacesAndNewlines).folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "vi_VN")) == key.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "vi_VN")) } + } +} +struct DeliveryPlace: Codable, Identifiable, Equatable { + var id = UUID() + var customer: String + var phone: String + var address: String + var kind: String + var latitude: Double? + var longitude: Double? + var destination: String { + if let lat = latitude, let lon = longitude { return "\(lat),\(lon)" } + return address + } + static func key(customer: String, address: String, kind: String, phone: String = "") -> String { + var number = phone.filter(\.isNumber) + if number.hasPrefix("84"), number.count == 11 { number = "0" + String(number.dropFirst(2)) } + return [customer, address, kind, number].map { $0.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "vi_VN")).split(whereSeparator: \.isWhitespace).joined(separator: " ") }.joined(separator: "|") + } + var key: String { Self.key(customer: customer, address: address, kind: kind, phone: phone) } +} +extension DeliveryLedger { + mutating func saveContact(_ value: DeliveryContact) throws { + guard !value.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw DeliveryError.invalid("Nhập tên liên hệ.") } + if !value.zalo.isEmpty { + let unchanged = (contacts ?? []).contains { $0.id == value.id && $0.zalo == value.zalo } + guard unchanged || ContactLinks.zalo(value.zalo) != nil else { throw DeliveryError.invalid("Chỉ nhận liên kết HTTPS thuộc zalo.me hoặc qr.zalo.me.") } + } + var list = contacts ?? [] + if let i = list.firstIndex(where: { $0.id == value.id }) { list[i] = value } else { list.append(value) } + contacts = list; record("Lưu liên hệ", value.name) + } + mutating func savePlace(_ value: DeliveryPlace) throws { + guard !value.customer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, !value.address.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw DeliveryError.invalid("Nhập tên và địa chỉ.") } + if let lat = value.latitude { guard lat.isFinite && (-90...90).contains(lat) else { throw DeliveryError.invalid("Vĩ độ không hợp lệ.") } } + if let lon = value.longitude { guard lon.isFinite && (-180...180).contains(lon) else { throw DeliveryError.invalid("Kinh độ không hợp lệ.") } } + guard (value.latitude == nil) == (value.longitude == nil) else { throw DeliveryError.invalid("Nhập đủ tọa độ.") } + var list = places ?? [] + if let i = list.firstIndex(where: { $0.id == value.id || $0.key == value.key }) { var copy = value; copy.id = list[i].id; list[i] = copy } else { list.append(value) } + places = list; record("Lưu vị trí", value.customer) + } + func hasPlace(for order: DeliveryOrder) -> Bool { + if order.settlement?.route == .freight { + return (places ?? []).contains { $0.id == order.freightPlaceID && $0.kind == "Chành xe" } + } + return (places ?? []).contains { $0.key == DeliveryPlace.key(customer: order.customer, address: order.address, kind: "Khách hàng", phone: order.phone) } + } +} diff --git a/Sweep/Core/DeliveryModels.swift b/Sweep/Core/DeliveryModels.swift index e91a440..3bf4ca8 100644 --- a/Sweep/Core/DeliveryModels.swift +++ b/Sweep/Core/DeliveryModels.swift @@ -32,8 +32,11 @@ enum DeliveryOutcome: String, Codable, CaseIterable { enum PaymentMode: String, Codable, CaseIterable { case none = "Chưa thu", cash = "Tiền mặt", bank = "Chuyển khoản ngay", deferred = "Chuyển khoản sau", mixed = "CK + tiền mặt" } +enum DeliveryRoute: String, Codable, CaseIterable { + case cashFull = "Tiền mặt đủ", transferNow = "Chuyển khoản ngay", transferLater = "Chuyển khoản sau", freight = "Giao chành" +} enum EvidenceRole: String, Codable, CaseIterable { - case invoice = "Phiếu nội bộ", signature = "Phiếu khách ký", transfer = "Ảnh giao dịch", companyQR = "QR công ty" + case invoice = "Phiếu nội bộ", signature = "Phiếu khách ký", transfer = "Ảnh giao dịch", companyQR = "QR công ty", freightSignature = "Phiếu nhà xe ký", goods = "Ảnh hàng đã gửi" } struct DeliveryEvidence: Codable, Identifiable, Equatable { var id = UUID() @@ -68,9 +71,19 @@ struct Settlement: Codable, Identifiable, Equatable { var bank: Int64 var note: String var at: Date + var route: DeliveryRoute? = nil func validate(total: Int64) throws { try VND.check(total); try VND.check(cash); try VND.check(bank) guard cash + bank <= total else { throw DeliveryError.invalid("Tiền ghi nhận vượt tổng đơn. Kiểm tra khoản thừa trước khi lưu.") } + if let route { + guard outcome == .delivered else { throw DeliveryError.invalid("Chỉ chốt nhánh giao khi đã giao hàng.") } + switch route { + case .cashFull: guard cash == total && bank == 0 && mode == .cash else { throw DeliveryError.invalid("Thu đủ tiền mặt phải khớp tổng đơn.") } + case .transferNow: guard bank > 0 && cash + bank <= total else { throw DeliveryError.invalid("Nhập khoản chuyển thực nhận.") } + case .transferLater: guard bank == 0 && cash < total else { throw DeliveryError.invalid("CK sau phải còn khoản chưa thu.") } + case .freight: guard cash == 0 && bank == 0 else { throw DeliveryError.invalid("Giao chành bàn giao tiền cho bán hàng theo dõi.") } + } + } switch mode { case .none, .deferred: guard cash == 0 && bank == 0 else { throw DeliveryError.invalid("Chưa thu / CK sau phải có hai khoản bằng 0. Chọn đúng hình thức nếu đã nhận tiền.") } @@ -100,12 +113,15 @@ struct DeliveryReport: Codable, Identifiable, Equatable { var text: String var evidenceIDs: [UUID] var preparedAt = Date() + var contentKey: String? = nil } struct DeliveryReportDraft: Codable, Identifiable, Equatable { var id = UUID() + var evidenceIDs: [UUID]? = nil var revision: Int var text: String var at = Date() + var contentKey: String? = nil } struct ReportAcknowledgement: Codable, Identifiable, Equatable { var id = UUID() @@ -124,6 +140,9 @@ struct DeliveryOrder: Codable, Identifiable, Equatable { var sourceID: String? var sourceCreatedAt: Date? var sourceSnapshot: String? + var salesperson: String? = nil + var locationPromptedAt: Date? = nil + var freightPlaceID: UUID? = nil var reviewNote = "" var note = "" var revision = 1 @@ -148,19 +167,95 @@ struct DeliveryOrder: Codable, Identifiable, Equatable { var remaining: Int64 { total - cash - bank } var verifiedBank: Int64 { bankChecks.last(where: { $0.settlementID == settlement?.id })?.amount ?? 0 } var activeAssignments: [SignedAssignment] { assignments.filter { a in !reversals.contains { $0.assignmentID == a.id } } } + var reportContentKey: String { + // Bank verification, contact/location edits and unselected photos do not invalidate a sent report. + let fields = [code, customer, String(total), outcome.rawValue, settlement?.mode.rawValue ?? "", + String(cash), String(bank), settlement?.route?.rawValue ?? "", settlement?.note ?? ""] + return (try? String(data: DeliveryCoding.encode(fields), encoding: .utf8)) ?? "" + } var reportSent: Bool { - guard let report = reports.last, report.revision == revision else { return false } - return reportAcks.contains { $0.reportID == report.id } + guard let report = reports.last else { return false } + if let draft = currentReportDraft, draft.at > report.preparedAt, + draft.text != report.text || (draft.evidenceIDs != nil && draft.evidenceIDs != report.evidenceIDs) { return false } + let current = report.contentKey.map { $0 == reportContentKey } ?? (report.revision == revision) + return current && Set(report.evidenceIDs).isSubset(of: Set(activeEvidence.map(\.id))) && reportAcks.contains { $0.reportID == report.id } + } + var currentReportDraft: DeliveryReportDraft? { + guard let draft = reportDrafts.last, + draft.contentKey.map({ $0 == reportContentKey }) ?? (draft.revision == revision) else { return nil } + return draft + } + /// Restore the same text and image selection even after an unrelated contact/location edit. + var reportComposition: (text: String, evidenceIDs: [UUID]) { + let report: DeliveryReport? = reports.last.flatMap { value in + (value.contentKey.map { $0 == reportContentKey } ?? (value.revision == revision)) ? value : nil + } + let allowed = Set(shareableEvidence.map(\.id)) + if let draft = currentReportDraft, draft.at >= (report?.preparedAt ?? .distantPast) { + return (draft.text == reportText() ? shareText() : draft.text, + (draft.evidenceIDs ?? defaultShareEvidenceIDs).filter { allowed.contains($0) }) + } + if let report { return (report.text, report.evidenceIDs.filter { allowed.contains($0) }) } + return (shareText(), defaultShareEvidenceIDs) + } + var requiresReport: Bool { settlement != nil && settlement?.route != .cashFull } + var reportNeeded: Bool { requiresReport && !reportSent && voidReason == nil } + var taskComplete: Bool { outcome == .delivered && (settlement?.route == .cashFull || reportSent) } + var workflowStatus: String { + if voidReason != nil { return "Đã hủy" } + if outcome != .delivered { return outcome == .pending ? "Đang giao" : outcome.rawValue } + if settlement?.route == .cashFull { return "Đã giao · Tiền mặt chờ nộp" } + if reportNeeded { return "Đã giao · Chờ gửi ảnh" } + return settlement?.route == .freight ? "Đã giao chành" : "Đã hoàn tất" } - var reportNeeded: Bool { settlement != nil && !reportSent && voidReason == nil } static func normalizedCode(_ text: String) -> String { text.trimmingCharacters(in: .whitespacesAndNewlines).uppercased().filter { !$0.isWhitespace } } - func missingEvidence() -> [EvidenceRole] { - var needed: [EvidenceRole] = [.invoice] - if settlement?.mode == .deferred || settlement?.mode == .mixed { needed.append(.signature) } - if bank > 0 { needed.append(.transfer) } - return needed.filter { role in !activeEvidence.contains { $0.role == role } } + var requiredReportRoles: [EvidenceRole] { + switch settlement?.route { + case .cashFull: return [] + case .transferNow: return [.invoice, .transfer] + case .transferLater: return [.signature] + case .freight: return [.freightSignature, .goods] + case nil: + var roles: [EvidenceRole] = [.invoice] + if settlement?.mode == .deferred || settlement?.mode == .mixed { roles.append(.signature) } + if bank > 0 { roles.append(.transfer) }; return roles + } + } + var allowedReportRoles: Set { + switch settlement?.route { + case .cashFull: return [] + case .transferNow: return [.invoice, .transfer] + case .transferLater: return [.signature] + case .freight: return [.freightSignature, .goods] + case nil: return [.invoice, .signature, .transfer] + } + } + func missingEvidence() -> [EvidenceRole] { requiredReportRoles.filter { role in !activeEvidence.contains { $0.role == role } } } + var deliveryNoteForDisplay: String { InvoiceParser.cleanStoredNote(note) } + var orderedEvidence: [DeliveryEvidence] { + [EvidenceRole.invoice, .signature, .transfer, .freightSignature, .goods].flatMap { role in activeEvidence.filter { $0.role == role } } + } + var shareableEvidence: [DeliveryEvidence] { orderedEvidence.filter { allowedReportRoles.contains($0.role) } } + var defaultShareEvidenceIDs: [UUID] { + let roles: Set = settlement?.route != nil ? allowedReportRoles : (bank > 0 ? [.invoice, .transfer] : [.invoice, .signature]) + return orderedEvidence.filter { roles.contains($0.role) }.map(\.id) + } + func shareText() -> String { + if settlement?.route == .freight { return "\(customer) · Đã giao chành · \(code)" } + if bank > 0 { + let mixed = cash > 0 ? " · Tiền mặt \(VND.format(cash))" : "" + let deferred = remaining > 0 ? " · Còn chuyển sau \(VND.format(remaining))" : "" + return "\(customer) đã chuyển khoản \(VND.format(bank))" + mixed + deferred + } + if settlement?.route == .transferLater { + let mixed = cash > 0 ? " · Đã thu tiền mặt \(VND.format(cash))" : "" + return "\(customer) · Chuyển khoản sau \(VND.format(remaining))" + mixed + } + if cash > 0 { return "\(customer) đã thanh toán tiền mặt \(VND.format(cash))" } + if settlement?.mode == .deferred { return "\(customer) · Chuyển khoản sau · \(VND.format(total))" } + return "\(customer) · \(VND.format(total))" } func reportText() -> String { var rows = [customer, "Mã phiếu: \(code)", "Kết quả: \(outcome.rawValue)", "Tổng đơn: \(VND.format(total))", @@ -191,6 +286,7 @@ struct DeliverySettings: Codable, Equatable { var company = "" var account = "" var qr: DeliveryEvidence? + var vietQR: VietQRAccount? } struct DeliveryAudit: Codable, Identifiable, Equatable { var id = UUID() @@ -200,7 +296,10 @@ struct DeliveryAudit: Codable, Identifiable, Equatable { var detail: String } struct DeliveryLedger: Codable, Equatable { - var schema = 1 + var schema = 3 + var payroll: PayrollBook? = nil + var contacts: [DeliveryContact]? = nil + var places: [DeliveryPlace]? = nil var orders: [DeliveryOrder] = [] var handovers: [CashHandover] = [] var handoverReversals: [HandoverReversal] = [] @@ -240,8 +339,10 @@ struct DeliveryLedger: Codable, Equatable { mutating func settle(_ id: UUID, value: Settlement) throws { guard let i = orders.firstIndex(where: { $0.id == id }), orders[i].voidReason == nil else { throw DeliveryError.invalid("Không tìm thấy hồ sơ hợp lệ.") } try value.validate(total: orders[i].total) + if value.route != nil, orders[i].activeAssignments.isEmpty { throw DeliveryError.invalid("Xác nhận đã ký nhận trước khi chốt giao.") } if let previous = orders[i].settlement, previous.cash == value.cash, previous.bank == value.bank, - previous.mode == value.mode, previous.outcome == value.outcome, previous.note == value.note, previous.at == value.at { return } + previous.mode == value.mode, previous.outcome == value.outcome, previous.note == value.note, + previous.at == value.at, previous.route == value.route { return } guard cashCollected - orders[i].cash + value.cash >= cashHanded else { throw DeliveryError.invalid("Điều chỉnh làm tiền đã thu thấp hơn số đã nộp. Kiểm tra sổ nộp tiền trước.") } @@ -257,29 +358,44 @@ struct DeliveryLedger: Codable, Equatable { orders[i].revision += 1 record("Đối soát CK", orderID: id, "\(payment.bank) · \(note)") } - mutating func prepareReport(_ id: UUID, text: String) throws -> DeliveryReport { + mutating func prepareReport(_ id: UUID, text: String, evidenceIDs: [UUID]? = nil) throws -> DeliveryReport { guard let i = orders.firstIndex(where: { $0.id == id }), orders[i].settlement != nil, orders[i].voidReason == nil else { throw DeliveryError.invalid("Chốt giao / tiền trước khi chuẩn bị báo cáo.") } - guard orders[i].missingEvidence().isEmpty else { throw DeliveryError.invalid("Thiếu: " + orders[i].missingEvidence().map(\.rawValue).joined(separator: ", ")) } + if evidenceIDs == nil { + guard orders[i].missingEvidence().isEmpty else { throw DeliveryError.invalid("Thiếu: " + orders[i].missingEvidence().map(\.rawValue).joined(separator: ", ")) } + } guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw DeliveryError.invalid("Nội dung báo cáo đang trống.") } - let evidence = [EvidenceRole.invoice, .signature, .transfer].flatMap { role in orders[i].activeEvidence.filter { $0.role == role }.map(\.id) } - if let previous = orders[i].reports.last, previous.revision == orders[i].revision, previous.text == text, previous.evidenceIDs == evidence { return previous } - let report = DeliveryReport(revision: orders[i].revision, text: text, evidenceIDs: evidence) + if orders[i].settlement?.route == .cashFull { throw DeliveryError.invalid("Thu đủ tiền mặt không cần gửi ảnh báo cáo.") } + let allowed = Set(orders[i].shareableEvidence.map(\.id)) + let evidence = evidenceIDs ?? orders[i].shareableEvidence.map(\.id) + guard Set(evidence).count == evidence.count, Set(evidence).isSubset(of: allowed) else { throw DeliveryError.invalid("Ảnh chọn gửi không còn trong hồ sơ. Chọn lại ảnh.") } + if orders[i].settlement?.route != nil { + let selectedRoles = Set(orders[i].activeEvidence.filter { evidence.contains($0.id) }.map(\.role)) + guard Set(orders[i].requiredReportRoles).isSubset(of: selectedRoles) else { throw DeliveryError.invalid("Chọn đủ: " + orders[i].requiredReportRoles.map(\.rawValue).joined(separator: ", ")) } + } + if let previous = orders[i].reports.last, + (previous.contentKey.map { $0 == orders[i].reportContentKey } ?? (previous.revision == orders[i].revision)), + previous.text == text, previous.evidenceIDs == evidence { return previous } + let report = DeliveryReport(revision: orders[i].revision, text: text, evidenceIDs: evidence, contentKey: orders[i].reportContentKey) orders[i].reports.append(report); record("Chuẩn bị báo cáo", orderID: id, report.id.uuidString) return report } - mutating func saveReportDraft(_ id: UUID, text: String) throws { + mutating func saveReportDraft(_ id: UUID, text: String, evidenceIDs: [UUID]? = nil) throws { guard let i = orders.firstIndex(where: { $0.id == id }), orders[i].voidReason == nil, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw DeliveryError.invalid("Nội dung nháp đang trống hoặc hồ sơ không hợp lệ.") } - if let draft = orders[i].reportDrafts.last, draft.text == text, draft.revision == orders[i].revision { return } - if let report = orders[i].reports.last, report.text != text, report.revision == orders[i].revision { orders[i].revision += 1 } - orders[i].reportDrafts.append(DeliveryReportDraft(revision: orders[i].revision, text: text)) + if let draft = orders[i].currentReportDraft, draft.text == text, draft.evidenceIDs == evidenceIDs { return } + orders[i].reportDrafts.append(DeliveryReportDraft(evidenceIDs: evidenceIDs, revision: orders[i].revision, text: text, contentKey: orders[i].reportContentKey)) record("Lưu nội dung báo cáo nháp", orderID: id, text) } mutating func acknowledgeReport(_ id: UUID, reportID: UUID) throws { guard let i = orders.firstIndex(where: { $0.id == id }), let report = orders[i].reports.last, - report.id == reportID, report.revision == orders[i].revision else { throw DeliveryError.invalid("Hồ sơ đã đổi. Chuẩn bị lại báo cáo trước khi xác nhận gửi.") } + report.id == reportID, (report.contentKey.map { $0 == orders[i].reportContentKey } ?? (report.revision == orders[i].revision)) else { throw DeliveryError.invalid("Hồ sơ đã đổi. Chuẩn bị lại báo cáo trước khi xác nhận gửi.") } + guard Set(report.evidenceIDs).isSubset(of: Set(orders[i].shareableEvidence.map(\.id))) else { throw DeliveryError.invalid("Bộ ảnh đã đổi. Chọn lại ảnh trước khi xác nhận gửi.") } + if let draft = orders[i].currentReportDraft, draft.at > report.preparedAt, + draft.text != report.text || (draft.evidenceIDs != nil && draft.evidenceIDs != report.evidenceIDs) { + throw DeliveryError.invalid("Nội dung hoặc bộ ảnh đã đổi. Chia sẻ lại bản đang xem trước khi xác nhận.") + } guard !orders[i].reportAcks.contains(where: { $0.reportID == reportID }) else { return } orders[i].reportAcks.append(ReportAcknowledgement(reportID: reportID)) record("Sếp xác nhận đã gửi", orderID: id, reportID.uuidString) @@ -329,8 +445,22 @@ struct DeliveryLedger: Codable, Equatable { return "\u{FEFF}" + ([header] + rows).map { $0.map(escape).joined(separator: ",") }.joined(separator: "\r\n") } func validate() throws { - guard schema == 1, orders.count <= 50_000, handovers.count <= 100_000, Set(orders.map(\.id)).count == orders.count else { throw DeliveryError.invalid("Sổ không đúng phiên bản hoặc trùng ID.") } + guard (1...3).contains(schema), orders.count <= 50_000, handovers.count <= 100_000, Set(orders.map(\.id)).count == orders.count else { throw DeliveryError.invalid("Sổ không đúng phiên bản hoặc trùng ID.") } + try payroll?.validate() + guard (contacts?.count ?? 0) <= 10_000, (places?.count ?? 0) <= 50_000, + Set((contacts ?? []).map(\.id)).count == (contacts?.count ?? 0), + Set((places ?? []).map(\.id)).count == (places?.count ?? 0) else { throw DeliveryError.invalid("Danh bạ / vị trí trùng ID hoặc quá giới hạn.") } + for place in places ?? [] { + guard !place.customer.isEmpty, !place.address.isEmpty, + (place.latitude == nil) == (place.longitude == nil) else { throw DeliveryError.invalid("Vị trí thiếu dữ liệu.") } + if let lat = place.latitude, let lon = place.longitude { guard lat.isFinite && lon.isFinite && (-90...90).contains(lat) && (-180...180).contains(lon) else { throw DeliveryError.invalid("Tọa độ không hợp lệ.") } } + } + for contact in contacts ?? [] { + guard !contact.name.isEmpty else { throw DeliveryError.invalid("Liên hệ thiếu tên.") } + if !contact.zalo.isEmpty { guard let url = URL(string: contact.zalo), url.scheme == "https", url.host != nil else { throw DeliveryError.invalid("Link Zalo không hợp lệ.") } } + } try VND.check(settings.fee) + try settings.vietQR?.validate() guard Set(orders.map { DeliveryOrder.normalizedCode($0.code) }).count == orders.count else { throw DeliveryError.invalid("Sổ có mã phiếu trùng.") } let sources = orders.compactMap(\.sourceID) guard Set(sources).count == sources.count else { throw DeliveryError.invalid("Sổ có gói nhập trùng.") } @@ -370,6 +500,7 @@ struct DeliveryLedger: Codable, Equatable { } } func validateAppendOnly(from previous: DeliveryLedger) throws { + try (payroll ?? PayrollBook()).validateAppendOnly(from: previous.payroll ?? PayrollBook()) func keeps(_ before: [T], _ after: [T]) -> Bool { after.starts(with: before) } guard keeps(previous.audit, audit), keeps(previous.handovers, handovers), keeps(previous.handoverReversals, handoverReversals) else { throw DeliveryError.invalid("Không được xóa hoặc sửa lịch sử tài chính.") } let indexed = Dictionary(uniqueKeysWithValues: orders.map { ($0.id, $0) }) diff --git a/Sweep/Core/DeliveryMonth.swift b/Sweep/Core/DeliveryMonth.swift new file mode 100644 index 0000000..8cbc1c8 --- /dev/null +++ b/Sweep/Core/DeliveryMonth.swift @@ -0,0 +1,49 @@ +import Foundation + +enum DeliveryMonth { + static var calendar: Calendar { + var value = Calendar(identifier: .gregorian) + value.timeZone = TimeZone(identifier: "Asia/Ho_Chi_Minh")! + return value + } + static func start(_ date: Date) -> Date { calendar.dateInterval(of: .month, for: date)!.start } + static func contains(_ date: Date, in month: Date) -> Bool { + guard let interval = calendar.dateInterval(of: .month, for: month) else { return false } + return date >= interval.start && date < interval.end + } + static func rollover(selected: Date, observed: Date, now: Date) -> Date { + start(observed) == start(now) ? selected : start(now) + } +} + +struct MonthlyReconciliation { + let month: Date + let commissions: [(DeliveryOrder, SignedAssignment)] + let orders: [DeliveryOrder] + let handovers: [CashHandover] + let validHandovers: [CashHandover] + var count: Int { commissions.count } + var fee: Int64 { commissions.reduce(0) { $0 + $1.1.fee } } + let cashCollected: Int64 + var cashHanded: Int64 { validHandovers.reduce(0) { $0 + $1.amount } } + var cashDifference: Int64 { cashCollected - cashHanded } + var bankPending: Int64 { orders.reduce(0) { $0 + $1.bank - $1.verifiedBank } } + var pendingOrders: [DeliveryOrder] { orders.filter { $0.bank > $0.verifiedBank } } + + init(ledger: DeliveryLedger, month: Date) { + self.month = DeliveryMonth.start(month) + commissions = ledger.commissions(in: month, calendar: DeliveryMonth.calendar).sorted { $0.1.signedAt < $1.1.signedAt } + orders = ledger.orders.filter { order in order.settlement.map { DeliveryMonth.contains($0.at, in: month) } ?? false } + cashCollected = ledger.orders.reduce(Int64(0)) { sum, order in + var previous: Int64 = 0, amount: Int64 = 0 + for entry in order.settlements { + if DeliveryMonth.contains(entry.at, in: month) { amount += entry.cash - previous } + previous = entry.cash + } + return sum + amount + } + handovers = ledger.handovers.filter { DeliveryMonth.contains($0.at, in: month) }.sorted { $0.at > $1.at } + let reversed = Set(ledger.handoverReversals.map(\.handoverID)) + validHandovers = handovers.filter { !reversed.contains($0.id) } + } +} diff --git a/Sweep/Core/DeliveryStorage.swift b/Sweep/Core/DeliveryStorage.swift index 8b8b0d7..c5918af 100644 --- a/Sweep/Core/DeliveryStorage.swift +++ b/Sweep/Core/DeliveryStorage.swift @@ -48,6 +48,24 @@ final class DeliveryDatabase { let ledger = try DeliveryCoding.decode(DeliveryLedger.self, from: Data(bytes: bytes, count: Int(sqlite3_column_bytes(statement, 0)))) try ledger.validate(); return ledger } + func reset(using verified: DeliveryBackup.Prepared) throws { + try execute("BEGIN IMMEDIATE") + do { + guard try load() == verified.ledger else { throw DeliveryError.invalid("Sổ đã đổi sau sao lưu. Chưa đặt lại dữ liệu.") } + let data = try DeliveryCoding.encode(DeliveryLedger()) + var statement: OpaquePointer? + guard sqlite3_prepare_v2(connection, "INSERT INTO ledger(id,payload) VALUES(1,?)", -1, &statement, nil) == SQLITE_OK else { throw failure() } + defer { sqlite3_finalize(statement) } + try execute("DELETE FROM ledger") + let result = data.withUnsafeBytes { bytes in + sqlite3_bind_blob(statement, 1, bytes.baseAddress, Int32(data.count), unsafeBitCast(-1, to: sqlite3_destructor_type.self)) + } + guard result == SQLITE_OK, sqlite3_step(statement) == SQLITE_DONE else { throw failure() } + try execute("COMMIT") + } catch { try? execute("ROLLBACK"); throw error } + // Reclaim pages after the atomic reset; reclamation failure cannot undo a committed empty ledger. + try? execute("PRAGMA wal_checkpoint(TRUNCATE); VACUUM;") + } func save(_ ledger: DeliveryLedger, replacing: Bool = false) throws { try ledger.validate() let data = try DeliveryCoding.encode(ledger) @@ -83,16 +101,21 @@ enum EvidenceFiles { } static func imageExtension(_ url: URL) throws -> String { guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), - CGImageSourceGetCount(source) == 1, let type = CGImageSourceGetType(source) as String?, - [UTType.jpeg.identifier, UTType.png.identifier, UTType.heic.identifier, UTType.heif.identifier].contains(type), - let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], - let w = properties[kCGImagePropertyPixelWidth] as? Int, let h = properties[kCGImagePropertyPixelHeight] as? Int, - w > 0, h > 0, w <= 120_000_000 / h, - CGImageSourceCreateThumbnailAtIndex(source, 0, [kCGImageSourceCreateThumbnailFromImageAlways: true, - kCGImageSourceThumbnailMaxPixelSize: 64, kCGImageSourceShouldCacheImmediately: true] as CFDictionary) != nil else { - throw DeliveryError.invalid("Chọn ảnh tĩnh JPEG/PNG/HEIC đọc được, tối đa 120 megapixel.") + CGImageSourceGetCount(source) > 0, let identifier = CGImageSourceGetType(source) as String?, let type = UTType(identifier) else { + throw DeliveryError.invalid("Dữ liệu nguồn chưa phải ảnh giải mã được; có thể nguồn chia sẻ cung cấp một dạng khác với tệp gốc.") } - return UTType(type)?.preferredFilenameExtension ?? "jpg" + let formats: [(UTType, String)] = [(.jpeg, "jpg"), (.png, "png"), (.heic, "heic"), (.heif, "heif")] + guard let ext = formats.first(where: { type.conforms(to: $0.0) })?.1 else { throw DeliveryError.invalid("Dạng ảnh nhận được là \(identifier); cần chuẩn hóa trước khi lưu.") } + if type.conforms(to: .png), CGImageSourceGetCount(source) > 1 { throw DeliveryError.invalid("Ảnh PNG động chưa được nhận làm phiếu. Chọn ảnh tĩnh.") } + let index = CGImageSourceGetPrimaryImageIndex(source) + guard let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any], + let w = (properties[kCGImagePropertyPixelWidth] as? NSNumber)?.int64Value, + let h = (properties[kCGImagePropertyPixelHeight] as? NSNumber)?.int64Value, w > 0, h > 0 else { throw DeliveryError.invalid("Chưa đọc được kích thước ảnh nguồn.") } + guard w <= 120_000_000 / h else { throw DeliveryError.invalid("Ảnh nguồn vượt 120 megapixel.") } + guard CGImageSourceCreateThumbnailAtIndex(source, index, [kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: 64, + kCGImageSourceShouldCacheImmediately: true] as CFDictionary) != nil else { throw DeliveryError.invalid("Không giải mã được ảnh \(identifier) kích thước \(w)×\(h).") } + return ext } static func importImage(_ source: URL, role: EvidenceRole, directory: URL) throws -> DeliveryEvidence { let accessed = source.startAccessingSecurityScopedResource() @@ -124,7 +147,7 @@ enum EvidenceFiles { /// Streaming, versioned archive: magic, manifest length, manifest SHA256, manifest, original image bytes. /// No decoding of arbitrary paths, no ZIP expansion and no unbounded allocation for image payloads. enum DeliveryBackup { - struct Manifest: Codable { var version = 1; var createdAt = Date(); var ledger: DeliveryLedger } + struct Manifest: Codable { var version = 3; var createdAt = Date(); var ledger: DeliveryLedger } final class Prepared: @unchecked Sendable { let ledger: DeliveryLedger let staging: URL @@ -132,9 +155,9 @@ enum DeliveryBackup { deinit { try? FileManager.default.removeItem(at: staging) } } static let magic = Data("SWEEP001".utf8) - static func write(_ ledger: DeliveryLedger, evidence: URL, to destination: URL) throws { + static func write(_ ledger: DeliveryLedger, evidence: URL, to destination: URL, version: Int = 3) throws { try ledger.validate() - let manifest = try DeliveryCoding.encode(Manifest(ledger: ledger)) + let manifest = try DeliveryCoding.encode(Manifest(version: version, ledger: ledger)) guard manifest.count <= 32 * 1024 * 1024 else { throw DeliveryError.invalid("Sổ quá lớn cho định dạng sao lưu này.") } FileManager.default.createFile(atPath: destination.path, contents: nil) let handle = try FileHandle(forWritingTo: destination) @@ -179,7 +202,7 @@ enum DeliveryBackup { let expected = try read(32, from: handle), data = try read(Int(length), from: handle) guard Data(SHA256.hash(data: data)) == expected else { throw DeliveryError.invalid("Thông tin sổ bị sai hash.") } let manifest = try DeliveryCoding.decode(Manifest.self, from: data) - guard manifest.version == 1 else { throw DeliveryError.invalid("Bản sao lưu cần phiên bản Sweep mới hơn.") } + guard (1...3).contains(manifest.version) else { throw DeliveryError.invalid("Bản sao lưu cần phiên bản Sweep mới hơn.") } try manifest.ledger.validate() for file in manifest.ledger.allEvidence { let target = staging.appendingPathComponent(file.filename) diff --git a/Sweep/Core/IncomingInvoiceImage.swift b/Sweep/Core/IncomingInvoiceImage.swift new file mode 100644 index 0000000..28e5ef7 --- /dev/null +++ b/Sweep/Core/IncomingInvoiceImage.swift @@ -0,0 +1,20 @@ +import Foundation +import ImageIO +import UniformTypeIdentifiers + +/// Normalize incoming images to a small, metadata-free JPEG. Source is never modified. +enum IncomingInvoiceImage { + static let maximumDimension = 3072 + + static func copy(from source: URL, directory: URL = FileManager.default.temporaryDirectory) throws -> URL { + try InvoiceImageEncoder.compact(source, directory: directory) + } + + static func copy(data: Data, directory: URL = FileManager.default.temporaryDirectory) throws -> URL { + guard !data.isEmpty, data.count <= EvidenceFiles.maximumBytes else { throw DeliveryError.invalid("Ảnh chia sẻ trống hoặc vượt 80 MB.") } + let source = directory.appendingPathComponent(UUID().uuidString + ".incoming") + defer { try? FileManager.default.removeItem(at: source) } + try data.write(to: source, options: .atomic) + return try copy(from: source, directory: directory) + } +} diff --git a/Sweep/Core/InvoiceImageEncoder.swift b/Sweep/Core/InvoiceImageEncoder.swift new file mode 100644 index 0000000..7a1ae04 --- /dev/null +++ b/Sweep/Core/InvoiceImageEncoder.swift @@ -0,0 +1,33 @@ +import Foundation +import ImageIO +import UniformTypeIdentifiers +import CoreGraphics + +/// Encode only pixels: no source EXIF, GPS, IPTC, XMP or filename metadata is copied. +/// Keep text legible at 2560 px; alternate/animated formats use their primary still frame. +enum InvoiceImageEncoder { + static func compact(_ source: URL, directory: URL = FileManager.default.temporaryDirectory) throws -> URL { + let access = source.startAccessingSecurityScopedResource() + defer { if access { source.stopAccessingSecurityScopedResource() } } + _ = try EvidenceFiles.hash(source) + guard let input = CGImageSourceCreateWithURL(source as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), CGImageSourceGetCount(input) > 0 else { throw DeliveryError.invalid("Chưa giải mã được ảnh. Chọn ảnh trong thư viện để thử lại.") } + let index = CGImageSourceGetPrimaryImageIndex(input) + let props = CGImageSourceCopyPropertiesAtIndex(input, index, nil) as? [CFString: Any] ?? [:] + let w = (props[kCGImagePropertyPixelWidth] as? NSNumber)?.int64Value ?? 0 + let h = (props[kCGImagePropertyPixelHeight] as? NSNumber)?.int64Value ?? 0 + guard w > 0, h > 0, w <= 120_000_000 / h else { throw DeliveryError.invalid("Ảnh vượt giới hạn 120 megapixel hoặc chưa đầy đủ.") } + guard let thumb = CGImageSourceCreateThumbnailAtIndex(input, index, [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: 2560, kCGImageSourceShouldCacheImmediately: true] as CFDictionary), + let space = CGColorSpace(name: CGColorSpace.sRGB), + let ctx = CGContext(data: nil, width: thumb.width, height: thumb.height, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { throw DeliveryError.invalid("Không xử lý được ảnh.") } + ctx.setFillColor(CGColor(gray: 1, alpha: 1)); ctx.fill(CGRect(x: 0, y: 0, width: thumb.width, height: thumb.height)) + ctx.draw(thumb, in: CGRect(x: 0, y: 0, width: thumb.width, height: thumb.height)) + guard let pixels = ctx.makeImage() else { throw DeliveryError.invalid("Không tạo được ảnh.") } + let url = directory.appendingPathComponent(UUID().uuidString + ".jpg") + do { + guard let out = CGImageDestinationCreateWithURL(url as CFURL, UTType.jpeg.identifier as CFString, 1, nil) else { throw DeliveryError.invalid("Không tạo được bản ảnh nhẹ.") } + CGImageDestinationAddImage(out, pixels, [kCGImageDestinationLossyCompressionQuality: 0.82, kCGImagePropertyOrientation: 1] as CFDictionary) + guard CGImageDestinationFinalize(out) else { throw DeliveryError.invalid("Không ghi được ảnh nén.") } + _ = try EvidenceFiles.imageExtension(url); return url + } catch { try? FileManager.default.removeItem(at: url); throw error } + } +} diff --git a/Sweep/Core/InvoiceParser.swift b/Sweep/Core/InvoiceParser.swift index abf0cda..465f63a 100644 --- a/Sweep/Core/InvoiceParser.swift +++ b/Sweep/Core/InvoiceParser.swift @@ -1,9 +1,10 @@ import Foundation -/// Label-based suggestions only. Never infer a total from item prices or a customer phone from a salesperson. +/// Label-based suggestions. The phone field below the salesperson is the customer's phone. struct InvoiceFields: Equatable { var code = "" var customer = "" + var salesperson = "" var address = "" var phone = "" var deliveryNote = "" @@ -12,6 +13,23 @@ struct InvoiceFields: Equatable { } enum InvoiceParser { + static func isTableHeader(_ text: String) -> Bool { + let value = folded(text).trimmingCharacters(in: .whitespacesAndNewlines) + let columns = [#"\bstt\b"#, #"\bma\s+hang\b"#, #"\bten\s+hang\b"#, #"\bdon\s+vi\s+tinh\b"#, #"\bso\s+luong\b"#, #"\bdon\s+gia\b"#, #"\bthanh\s+tien\b"#] + if columns.filter({ value.range(of: $0, options: .regularExpression) != nil }).count >= 2 { return true } + return value.range(of: #"^(?:stt|ma\s+hang|ten\s+hang(?:\s+hoa)?|so\s+luong|don\s+gia|thanh\s+tien|ma\s+hang\s+thanh(?:\s+tien)?)$"#, options: .regularExpression) != nil + } + static func cleanStoredNote(_ note: String) -> String { + note.split(separator: "\n").compactMap { line -> String? in + let raw = String(line).trimmingCharacters(in: .whitespacesAndNewlines) + let ascii = folded(raw) + if ascii.hasPrefix("dien thoai tren phieu can xac minh nguoi nhan:") { return nil } + let clean: String + if ascii.hasPrefix("giao hang:"), let colon = raw.firstIndex(of: ":") { clean = String(raw[raw.index(after: colon)...]).trimmingCharacters(in: .whitespaces) } + else { clean = raw } + return clean.isEmpty || isTableHeader(clean) ? nil : clean + }.joined(separator: "\n") + } private static let labels = #"(?:don\s+vi|nguoi\s+mua\s+hang|dia\s+chi\s+giao\s+hang|dia\s+chi|dien\s+thoai|sdt|nv\s+ban\s+hang|so)\s*[::]"# private static func folded(_ text: String) -> String { text.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "vi_VN")) @@ -40,19 +58,22 @@ enum InvoiceParser { .split(separator: "\n").map { String($0).trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } var result = InvoiceFields() var totalPriority = 0 + var inHeader = true for (i, line) in lines.enumerated() { + if isTableHeader(line) { inHeader = false } func field(_ label: String) -> String? { let found = value(line, pattern: #"(?:^|\s)(?:"# + label + #")\s*[::]\s*"#) // OCR may put a value on the next line. Do not consume another labelled field. - if found == "", i + 1 < lines.count, value(lines[i + 1], pattern: labels) == nil { return lines[i + 1] } + if found == "", i + 1 < lines.count, value(lines[i + 1], pattern: labels) == nil, !isTableHeader(lines[i + 1]) { return lines[i + 1] } return found } - if result.customer.isEmpty, let v = field(#"don\s+vi"#) { result.customer = v } - if result.address.isEmpty, let v = field(#"dia\s+chi"#) { result.address = v } - if result.deliveryNote.isEmpty, let v = field(#"dia\s+chi\s+giao\s+hang"#) { result.deliveryNote = v } - if result.code.isEmpty, let v = field("so"), let token = v.split(whereSeparator: { $0.isWhitespace }).first, + if inHeader, result.salesperson.isEmpty, let v = field(#"nv\s+ban\s+hang"#) { result.salesperson = v } + if inHeader, result.customer.isEmpty, let v = field(#"don\s+vi"#) { result.customer = v } + if inHeader, result.address.isEmpty, let v = field(#"dia\s+chi"#) { result.address = v } + if inHeader, result.deliveryNote.isEmpty, let v = field(#"dia\s+chi\s+giao\s+hang"#), !isTableHeader(v) { result.deliveryNote = v } + if inHeader, result.code.isEmpty, let v = field("so"), let token = v.split(whereSeparator: { $0.isWhitespace }).first, token.range(of: #"^[A-Za-z0-9][A-Za-z0-9./_-]{0,47}$"#, options: .regularExpression) != nil { result.code = String(token) } - if result.phone.isEmpty, let v = field(#"dien\s+thoai|sdt"#) { + if inHeader, result.phone.isEmpty, let v = field(#"dien\s+thoai|sdt"#) { let digits = v.filter { $0.isNumber || $0 == "+" } if digits.range(of: #"^(?:0[0-9]{9,10}|\+84[0-9]{9,10})$"#, options: .regularExpression) != nil { result.phone = digits } } diff --git a/Sweep/Core/Payroll.swift b/Sweep/Core/Payroll.swift new file mode 100644 index 0000000..f2bcb46 --- /dev/null +++ b/Sweep/Core/Payroll.swift @@ -0,0 +1,233 @@ +import Foundation + +enum PayrollDates { + static var calendar: Calendar { DeliveryMonth.calendar } + static func key(_ date: Date) -> String { + let c = calendar.dateComponents([.year, .month], from: date) + return String(format: "%04d-%02d", c.year!, c.month!) + } + static func days(_ month: Date) -> [Date] { + let start = DeliveryMonth.start(month) + return calendar.range(of: .day, in: .month, for: start)!.compactMap { calendar.date(byAdding: .day, value: $0 - 1, to: start) } + } + static func closeDay(_ month: Date) -> Date { days(month).last! } + static func fuelDay(_ month: Date) -> Date { days(month)[min(30, days(month).count) - 1] } +} + +enum AttendanceState: String, Codable, CaseIterable { + case work = "Đi làm", half = "Nửa công", leave = "Nghỉ phép không lương", off = "Nghỉ theo lịch" + var workUnits: Int { self == .work ? 2 : self == .half ? 1 : 0 } + var leaveUnits: Int { self == .leave ? 2 : self == .half ? 1 : 0 } +} +struct AttendanceEntry: Codable, Equatable, Identifiable { + var day: Date + var state: AttendanceState + var note = "" + var id: Date { day } +} +struct PayrollPolicy: Codable, Equatable { + var base: Int64 = 5_600_000 + var phone: Int64 = 400_000 + var meal: Int64 = 30_000 + var maintenance: Int64 = 25_000 + var attendance: Int64 = 500_000 + var insurance: Int64 = 588_000 + var fuelLitres = 3 + var weekdays: [Int] = [] // Empty until the actual work schedule is configured. + var confirmed = false + var fuelType = "" + var fuelRegion = "" + func validate() throws { + for n in [base, phone, meal, maintenance, attendance, insurance] { + guard (0...1_000_000_000).contains(n) else { throw DeliveryError.invalid("Mức lương/trợ cấp vượt giới hạn.") } + } + guard (0...20).contains(fuelLitres), Set(weekdays).count == weekdays.count, + weekdays.allSatisfy({ (1...7).contains($0) }), !confirmed || !weekdays.isEmpty else { + throw DeliveryError.invalid("Chọn lịch làm việc và kiểm tra định mức xăng.") + } + } +} +struct PayrollFuel: Codable, Equatable { + var price: Int64 + var effectiveDay: Date + var source: String + var recordedAt = Date() +} +struct SalaryAdvance: Codable, Equatable, Identifiable { + var id = UUID() + var day: Date + var amount: Int64 + var note: String +} +struct PayrollMonth: Codable, Equatable, Identifiable { + var month: Date + var policy = PayrollPolicy() + var entries: [AttendanceEntry] = [] + var fuel: PayrollFuel? + var advances: [SalaryAdvance] = [] + var adjustment: Int64 = 0 + var adjustmentReason = "" + var id: String { PayrollDates.key(month) } + func entry(_ day: Date) -> AttendanceEntry? { entries.first { PayrollDates.calendar.isDate($0.day, inSameDayAs: day) } } + func isPlanned(_ day: Date) -> Bool { + if let state = entry(day)?.state { return state != .off } + return policy.weekdays.contains(PayrollDates.calendar.component(.weekday, from: day)) + } +} +struct PayrollCalculation: Codable, Equatable { + var plannedUnits: Int + var workUnits: Int + var leaveUnits: Int + var missingDays: Int + var commissions: Int + var fee: Int64 + var base: Int64 + var phone: Int64 + var meal: Int64 + var maintenance: Int64 + var fuel: Int64 + var attendance: Int64 + var insurance: Int64 + var advances: Int64 + var adjustment: Int64 + var fuelConfirmed: Bool + var net: Int64 { base + phone + meal + maintenance + fuel + attendance + fee - insurance - advances + adjustment } + var rows: [(String, Int64)] { + [("Lương theo công", base), ("Công đơn", fee), ("Điện thoại", phone), ("Xăng xe", fuel), + ("Ăn", meal), ("Bảo trì xe", maintenance), ("Chuyên cần", attendance), + ("Bảo hiểm", -insurance), ("Tạm ứng", -advances), ("Điều chỉnh", adjustment), ("Thực nhận", net)] + } + static func round(_ number: Decimal) -> Int64 { + var source = number, result = Decimal() + NSDecimalRound(&result, &source, 0, .plain) + return NSDecimalNumber(decimal: result).int64Value + } + init(ledger: DeliveryLedger, period: PayrollMonth) { + let days = PayrollDates.days(period.month), entries = period.entries + plannedUnits = days.filter { period.isPlanned($0) }.count * 2 + workUnits = entries.reduce(0) { $0 + $1.state.workUnits } + leaveUnits = entries.reduce(0) { $0 + $1.state.leaveUnits } + missingDays = days.filter { period.isPlanned($0) && period.entry($0) == nil }.count + let assignments = ledger.commissions(in: period.month, calendar: PayrollDates.calendar) + commissions = assignments.count; fee = assignments.reduce(0) { $0 + $1.1.fee } + let p = period.policy, ratio = plannedUnits == 0 ? Decimal(0) : Decimal(workUnits) / Decimal(plannedUnits) + base = Self.round(Decimal(p.base) * ratio) + phone = Self.round(Decimal(p.phone) * ratio) + meal = Self.round(Decimal(p.meal) * Decimal(workUnits) / 2) + maintenance = Self.round(Decimal(p.maintenance) * Decimal(workUnits) / 2) + fuelConfirmed = period.fuel != nil + fuel = Self.round(Decimal(period.fuel?.price ?? 0) * Decimal(p.fuelLitres) * Decimal(workUnits) / 2) + attendance = leaveUnits > 6 ? 0 : p.attendance + insurance = p.insurance + advances = period.advances.reduce(0) { $0 + $1.amount } + adjustment = period.adjustment + } +} +struct PayrollSnapshot: Codable, Equatable, Identifiable { + var id = UUID() + var period: PayrollMonth + var calculation: PayrollCalculation + var assignmentIDs: [UUID] + var closedAt = Date() +} +struct PayrollBook: Codable, Equatable { + var months: [PayrollMonth] = [] + var snapshots: [PayrollSnapshot] = [] + var reopenedIDs: [UUID] = [] + var openingLeaveUnits: [String: Int] = [:] + func period(_ month: Date) -> PayrollMonth { + if let saved = months.first(where: { $0.id == PayrollDates.key(month) }) { return saved } + var next = PayrollMonth(month: DeliveryMonth.start(month)) + if let previous = months.filter({ $0.month < next.month }).max(by: { $0.month < $1.month }) { next.policy = previous.policy } + return next + } + func closed(_ month: Date) -> PayrollSnapshot? { + snapshots.last { $0.period.id == PayrollDates.key(month) && !reopenedIDs.contains($0.id) } + } + func annualLeaveUnits(year: Int) -> Int { + (openingLeaveUnits[String(year)] ?? 0) + months.filter { PayrollDates.calendar.component(.year, from: $0.month) == year } + .flatMap(\.entries).reduce(0) { $0 + $1.state.leaveUnits } + } + mutating func put(_ period: PayrollMonth) throws { + guard closed(period.month) == nil else { throw DeliveryError.invalid("Tháng đã chốt. Mở khóa có lý do trước khi sửa.") } + if let i = months.firstIndex(where: { $0.id == period.id }) { months[i] = period } else { months.append(period) } + } + func validate() throws { + guard months.count <= 1200, snapshots.count <= 5000, Set(months.map(\.id)).count == months.count, + Set(snapshots.map(\.id)).count == snapshots.count, Set(reopenedIDs).count == reopenedIDs.count, + Set(reopenedIDs).isSubset(of: Set(snapshots.map(\.id))), + openingLeaveUnits.values.allSatisfy({ (0...732).contains($0) }) else { throw DeliveryError.invalid("Sổ công/lương không hợp lệ.") } + for p in months + snapshots.map(\.period) { + guard p.month.timeIntervalSince1970.isFinite, (-2_208_988_800...10_413_792_000).contains(p.month.timeIntervalSince1970) else { + throw DeliveryError.invalid("Ngày kỳ lương ngoài phạm vi hỗ trợ.") + } + try p.policy.validate() + guard p.month == DeliveryMonth.start(p.month), Set(p.entries.map(\.day)).count == p.entries.count, + p.entries.count <= 31, p.entries.allSatisfy({ DeliveryMonth.contains($0.day, in: p.month) && $0.day == PayrollDates.calendar.startOfDay(for: $0.day) }), + p.advances.count <= 1000, (-1_000_000_000...1_000_000_000).contains(p.adjustment), + p.adjustment == 0 || !p.adjustmentReason.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + Set(p.advances.map(\.id)).count == p.advances.count else { throw DeliveryError.invalid("Dữ liệu công trong tháng chưa hợp lệ.") } + for a in p.advances { + guard a.amount > 0, a.amount <= 1_000_000_000, DeliveryMonth.contains(a.day, in: p.month) else { throw DeliveryError.invalid("Tạm ứng không hợp lệ.") } + } + if let fuel = p.fuel { + guard (1...1_000_000).contains(fuel.price), PayrollDates.calendar.isDate(fuel.effectiveDay, inSameDayAs: PayrollDates.fuelDay(p.month)), + !fuel.source.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw DeliveryError.invalid("Giá xăng phải có nguồn và đúng ngày chốt.") } + } + } + for snap in snapshots { + let c = snap.calculation + let amounts = [c.base, c.phone, c.meal, c.maintenance, c.fuel, c.attendance, c.insurance, c.advances, c.adjustment] + guard amounts.allSatisfy({ (-100_000_000_000_000...100_000_000_000_000).contains($0) }), + (0...50_000_000_000_000_000).contains(c.fee), (0...62).contains(c.plannedUnits), + (0...62).contains(c.workUnits), (0...62).contains(c.leaveUnits), (0...31).contains(c.missingDays), + (0...50_000).contains(c.commissions), snap.assignmentIDs.count == c.commissions, + Set(snap.assignmentIDs).count == snap.assignmentIDs.count else { throw DeliveryError.invalid("Bản lương đã chốt có số liệu không hợp lệ.") } + } + for snap in snapshots where !reopenedIDs.contains(snap.id) { + guard months.first(where: { $0.id == snap.period.id }) == snap.period else { throw DeliveryError.invalid("Tháng đã chốt bị thay đổi khi chưa mở khóa.") } + } + } + func validateAppendOnly(from previous: PayrollBook) throws { + guard snapshots.starts(with: previous.snapshots), reopenedIDs.starts(with: previous.reopenedIDs) else { throw DeliveryError.invalid("Không được xóa/sửa bản lương đã chốt.") } + for snap in previous.snapshots where !previous.reopenedIDs.contains(snap.id) && !reopenedIDs.contains(snap.id) { + guard period(snap.period.month) == snap.period else { throw DeliveryError.invalid("Tháng đã chốt phải được giữ nguyên.") } + } + } +} +extension DeliveryLedger { + mutating func changePayroll(_ action: String, _ operation: (inout PayrollBook) throws -> Void) throws { + var book = payroll ?? PayrollBook(); try operation(&book); try book.validate() + payroll = book; record(action, "Công và lương") + } + mutating func markAttendance(_ day: Date, state: AttendanceState?, note: String = "", now: Date = Date()) throws { + let normalized = PayrollDates.calendar.startOfDay(for: day) + guard normalized <= PayrollDates.calendar.startOfDay(for: now) else { throw DeliveryError.invalid("Chưa thể chấm công cho ngày tương lai.") } + try changePayroll("Sửa công " + normalized.ISO8601Format()) { book in + var p = book.period(normalized) + p.entries.removeAll { $0.day == normalized } + if let state { p.entries.append(AttendanceEntry(day: normalized, state: state, note: note)) } + try book.put(p) + } + } + mutating func closePayroll(_ month: Date, now: Date = Date()) throws { + let book = payroll ?? PayrollBook(), p = book.period(month), result = PayrollCalculation(ledger: self, period: p) + guard PayrollDates.calendar.startOfDay(for: now) >= PayrollDates.closeDay(month) else { throw DeliveryError.invalid("Chốt lương vào ngày cuối tháng, không cố định ngày 30.") } + guard result.plannedUnits > 0, p.policy.confirmed, !p.policy.fuelType.isEmpty, !p.policy.fuelRegion.isEmpty, result.missingDays == 0, result.fuelConfirmed else { + throw DeliveryError.invalid("Xác nhận lịch/mức lương, loại/vùng xăng, đủ công và giá chốt trước khi khóa tháng.") + } + let assignments = commissions(in: month, calendar: PayrollDates.calendar).map { $0.1.id } + try changePayroll("Chốt lương " + p.id) { book in + guard book.closed(month) == nil else { throw DeliveryError.invalid("Tháng đã được chốt.") } + try book.put(p) + book.snapshots.append(PayrollSnapshot(period: p, calculation: result, assignmentIDs: assignments, closedAt: now)) + } + } + mutating func reopenPayroll(_ month: Date, reason: String) throws { + guard !reason.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw DeliveryError.invalid("Ghi lý do mở khóa.") } + try changePayroll("Mở khóa lương: " + reason) { book in + guard let closed = book.closed(month) else { throw DeliveryError.invalid("Tháng chưa khóa.") } + book.reopenedIDs.append(closed.id) + } + } +} diff --git a/Sweep/Core/SharedInvoiceInbox.swift b/Sweep/Core/SharedInvoiceInbox.swift new file mode 100644 index 0000000..b194e13 --- /dev/null +++ b/Sweep/Core/SharedInvoiceInbox.swift @@ -0,0 +1,94 @@ +import Foundation + +/// The extension publishes immutable images, never writes the live ledger. +/// Staging + rename keeps an interrupted share from becoming a visible half-file. +struct SharedInvoiceInbox { + struct Item: Identifiable { + let id: UUID + let receivedAt: Date + let evidence: DeliveryEvidence + let directory: URL + var signedAt: Date? = nil + var image: URL { directory.appendingPathComponent(evidence.filename) } + var sourceID: String { "share:" + id.uuidString } + } + struct Scan { + var items: [Item] = [] + var warnings: [String] = [] + } + private struct Manifest: Codable { + var version = 1 + let id: UUID + let receivedAt: Date + let evidence: DeliveryEvidence + var signedAt: Date? = nil + } + let directory: URL + + static func live() throws -> SharedInvoiceInbox { + #if DEBUG + if ProcessInfo.processInfo.arguments.contains("--delivery-ui-testing") { + return SharedInvoiceInbox(directory: FileManager.default.temporaryDirectory.appendingPathComponent("Sweep-Delivery-UITests/Inbox", isDirectory: true)) + } + #endif + let info = Bundle.main.infoDictionary ?? [:] + let groups = AppGroupConfiguration.identifiers(in: info) + for group in groups { + if let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) { + return SharedInvoiceInbox(directory: container.appendingPathComponent("SharedInvoices", isDirectory: true)) + } + } + let source = info["ALTAppGroups"] == nil ? "cấu hình gốc" : "AltStore" + let details = groups.isEmpty ? "Chưa có nhóm được cấp." : "Nhóm từ \(source): " + groups.joined(separator: ", ") + throw DeliveryError.invalid("Tiện ích đã mở nhưng chưa truy cập được hộp thư chung. \(details) Dùng bản IPA dành cho AltStore, giữ tiện ích mở rộng khi cài. Nếu vẫn lỗi, gửi lại thông báo này để kiểm tra quyền nhóm; ảnh chưa được nhận vào Sweep.") + } + + @discardableResult func add(_ source: URL, signedAt: Date? = nil) throws -> Item { + let fm = FileManager.default + try fm.createDirectory(at: directory, withIntermediateDirectories: true) + let id = UUID(), date = Date() + let staging = directory.appendingPathComponent(".staging-" + id.uuidString, isDirectory: true) + let destination = directory.appendingPathComponent(id.uuidString, isDirectory: true) + try fm.createDirectory(at: staging, withIntermediateDirectories: false) + defer { try? fm.removeItem(at: staging) } + let image = try EvidenceFiles.importImage(source, role: .invoice, directory: staging) + let manifest = Manifest(id: id, receivedAt: date, evidence: image, signedAt: signedAt) + try DeliveryCoding.encode(manifest).write(to: staging.appendingPathComponent("manifest.json"), options: .atomic) + try fm.moveItem(at: staging, to: destination) + return Item(id: id, receivedAt: date, evidence: image, directory: destination, signedAt: signedAt) + } + + func scan() throws -> Scan { + let fm = FileManager.default + guard fm.fileExists(atPath: directory.path) else { return Scan() } + var result = Scan() + for folder in try fm.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isSymbolicLinkKey], options: [.skipsHiddenFiles]) { + do { + guard let folderID = UUID(uuidString: folder.lastPathComponent), + try folder.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { + throw DeliveryError.invalid("Thư mục phiếu không hợp lệ.") + } + let manifestURL = folder.appendingPathComponent("manifest.json") + let metadata = try manifestURL.resourceValues(forKeys: [.fileSizeKey, .isSymbolicLinkKey]) + guard metadata.isSymbolicLink != true, let size = metadata.fileSize, size <= 64 * 1024 else { throw DeliveryError.invalid("Dữ liệu phiếu không hợp lệ.") } + let manifest = try DeliveryCoding.decode(Manifest.self, from: Data(contentsOf: manifestURL)) + let file = manifest.evidence + guard manifest.version == 1, manifest.id == folderID, file.role == .invoice, + file.filename.range(of: #"^[A-Fa-f0-9-]{36}\.(jpg|jpeg|png|heic|heif)$"#, options: .regularExpression) != nil, + file.bytes > 0, file.bytes <= EvidenceFiles.maximumBytes else { throw DeliveryError.invalid("Thông tin ảnh không hợp lệ.") } + let properties = try folder.appendingPathComponent(file.filename).resourceValues(forKeys: [.fileSizeKey, .isSymbolicLinkKey]) + guard properties.isSymbolicLink != true, let bytes = properties.fileSize, Int64(bytes) == file.bytes else { throw DeliveryError.invalid("Ảnh chưa đủ dữ liệu.") } + result.items.append(Item(id: manifest.id, receivedAt: manifest.receivedAt, evidence: file, directory: folder, signedAt: manifest.signedAt)) + } catch { result.warnings.append("Một ảnh chờ nhận chưa đọc được, vẫn được giữ lại: " + error.localizedDescription) } + } + result.items.sort { $0.receivedAt < $1.receivedAt } + return result + } + + func remove(_ item: Item) throws { + // Only a known UUID child of this inbox can be removed. + let expected = directory.appendingPathComponent(item.id.uuidString, isDirectory: true) + guard expected.standardizedFileURL == item.directory.standardizedFileURL else { throw DeliveryError.invalid("Không đúng ảnh chờ nhận.") } + try FileManager.default.removeItem(at: expected) + } +} diff --git a/Sweep/Core/SharedInvoiceLoader.swift b/Sweep/Core/SharedInvoiceLoader.swift new file mode 100644 index 0000000..28d226e --- /dev/null +++ b/Sweep/Core/SharedInvoiceLoader.swift @@ -0,0 +1,128 @@ +import Foundation +import UniformTypeIdentifiers +#if canImport(UIKit) +import UIKit +#endif + +enum SharedInvoiceLoader { + static func imageTypes(_ identifiers: [String]) -> [String] { + let preferred = [UTType.jpeg.identifier, UTType.png.identifier, UTType.heic.identifier, UTType.heif.identifier] + let images = identifiers.filter { UTType($0)?.conforms(to: .image) == true } + return images.enumerated().sorted { + let a = preferred.firstIndex(of: $0.element) ?? preferred.count + let b = preferred.firstIndex(of: $1.element) ?? preferred.count + return a == b ? $0.offset < $1.offset : a < b + }.map(\.element) + } + + static func load(from provider: NSItemProvider) async throws -> URL { + var types = imageTypes(provider.registeredTypeIdentifiers) + if types.isEmpty, provider.hasItemConformingToTypeIdentifier(UTType.data.identifier) { types = [UTType.data.identifier] } + var failures: [String] = [] + for type in types { + try Task.checkCancellation() + // Zalo/older providers can vend a UIImage or URL for public.image rather than encoded bytes. + if type == UTType.image.identifier { + do { return try await loadItem(provider, type: type) } + catch { failures.append("ảnh nguồn: \(error.localizedDescription)") } + } + do { return try await loadFile(provider, type: type) } + catch { failures.append("tệp \(type): \(error.localizedDescription)") } + try Task.checkCancellation() + do { return try await loadData(provider, type: type) } + catch { failures.append("dữ liệu \(type): \(error.localizedDescription)") } + do { return try await loadItem(provider, type: type) } + catch { failures.append("đối tượng \(type): \(error.localizedDescription)") } + } + if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { + do { + return try await withCheckedThrowingContinuation { continuation in + provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, error in + do { + if let error { throw error } + guard let source = item as? URL, source.isFileURL else { throw DeliveryError.invalid("Nguồn chưa cung cấp đường dẫn ảnh.") } + continuation.resume(returning: try IncomingInvoiceImage.copy(from: source)) + } catch { continuation.resume(throwing: error) } + } + } + } catch { failures.append("đường dẫn: \(error.localizedDescription)") } + } + #if canImport(UIKit) + if provider.canLoadObject(ofClass: UIImage.self) { + do { + return try await withCheckedThrowingContinuation { continuation in + provider.loadObject(ofClass: UIImage.self) { item, error in + do { + if let error { throw error } + guard let image = item as? UIImage else { throw DeliveryError.invalid("Chưa nhận được đối tượng ảnh.") } + continuation.resume(returning: try copyImage(image)) + } catch { continuation.resume(throwing: error) } + } + } + } catch { failures.append("đối tượng ảnh: \(error.localizedDescription)") } + } + #endif + try Task.checkCancellation() + let source = provider.registeredTypeIdentifiers.prefix(6).joined(separator: ", ") + let detail = failures.suffix(3).map { String($0.prefix(220)) }.joined(separator: "\n") + throw DeliveryError.invalid("Chưa đọc được ảnh nguồn sau khi thử các cách nhận ảnh. Kiểu nguồn: \(source).\n\(detail)") + } + + private static func loadItem(_ provider: NSItemProvider, type: String) async throws -> URL { + try await withCheckedThrowingContinuation { continuation in + provider.loadItem(forTypeIdentifier: type, options: nil) { item, error in + do { + if let error { throw error } + #if canImport(UIKit) + if let image = item as? UIImage { continuation.resume(returning: try copyImage(image)); return } + #endif + if let url = item as? URL, url.isFileURL { continuation.resume(returning: try IncomingInvoiceImage.copy(from: url)); return } + if let data = item as? Data { continuation.resume(returning: try IncomingInvoiceImage.copy(data: data)); return } + if let text = item as? String, let url = URL(string: text), url.isFileURL { + continuation.resume(returning: try IncomingInvoiceImage.copy(from: url)); return + } + throw DeliveryError.invalid("Nguồn chưa cung cấp được ảnh hoặc đường dẫn ảnh hợp lệ.") + } catch { continuation.resume(throwing: error) } + } + } + } + + private static func loadFile(_ provider: NSItemProvider, type: String) async throws -> URL { + try await withCheckedThrowingContinuation { continuation in + provider.loadFileRepresentation(forTypeIdentifier: type) { source, error in + do { + if let error { throw error } + guard let source else { throw DeliveryError.invalid("Nguồn chưa cung cấp tệp ảnh.") } + // The provider's URL expires as soon as this callback returns. + continuation.resume(returning: try IncomingInvoiceImage.copy(from: source)) + } catch { continuation.resume(throwing: error) } + } + } + } + private static func loadData(_ provider: NSItemProvider, type: String) async throws -> URL { + try await withCheckedThrowingContinuation { continuation in + provider.loadDataRepresentation(forTypeIdentifier: type) { data, error in + do { + if let error { throw error } + guard let data else { throw DeliveryError.invalid("Nguồn chưa cung cấp dữ liệu ảnh.") } + continuation.resume(returning: try IncomingInvoiceImage.copy(data: data)) + } catch { continuation.resume(throwing: error) } + } + } + } + #if canImport(UIKit) + static func copyImage(_ image: UIImage) throws -> URL { + let still = image.images?.first ?? image + let width = still.size.width * still.scale, height = still.size.height * still.scale + guard width.isFinite, height.isFinite, width > 0, height > 0, width <= 120_000_000 / height else { + throw DeliveryError.invalid("Kích thước ảnh nguồn không hợp lệ hoặc vượt 120 megapixel.") + } + let factor = min(1, CGFloat(IncomingInvoiceImage.maximumDimension) / max(width, height)) + let size = CGSize(width: max(1, floor(width * factor)), height: max(1, floor(height * factor))) + let format = UIGraphicsImageRendererFormat(); format.scale = 1; format.preferredRange = .standard + let normalized = UIGraphicsImageRenderer(size: size, format: format).image { _ in still.draw(in: CGRect(origin: .zero, size: size)) } + guard let data = normalized.pngData() else { throw DeliveryError.invalid("Chưa mã hóa được ảnh nguồn.") } + return try IncomingInvoiceImage.copy(data: data) + } + #endif +} diff --git a/Sweep/Core/SigningExpiry.swift b/Sweep/Core/SigningExpiry.swift new file mode 100644 index 0000000..19c87fe --- /dev/null +++ b/Sweep/Core/SigningExpiry.swift @@ -0,0 +1,35 @@ +import Foundation + +enum SigningExpiry { + /// Reads the embedded plist, not a certificate validation API. Missing/unsupported profiles use manual entry. + static func expiration(in data: Data) -> Date? { + guard data.count <= 4 * 1024 * 1024, + let start = data.range(of: Data("".utf8), in: start.lowerBound..= expiry { return nil } + return expiry + } + static func reminders(expiry: Date, now: Date, limit: Int = 48) -> [Date] { + guard expiry.timeIntervalSince1970.isFinite, now.timeIntervalSince1970.isFinite else { return [] } + let start = expiry.addingTimeInterval(-24 * 3600), step: TimeInterval = 3 * 3600 + let offset = max(0, floor(now.timeIntervalSince(start) / step) + 1) + let first = start > now ? start : start.addingTimeInterval(offset * step) + return (0.. String { + var n = value.filter(\.isNumber) + if n.hasPrefix("84"), n.count == 11 { n = "0" + n.dropFirst(2) } + return n + } + static func zalo(_ text: String) -> URL? { + guard let u = URL(string: text.trimmingCharacters(in: .whitespacesAndNewlines)), u.scheme?.lowercased() == "https", + let host = u.host?.lowercased(), ["zalo.me", "www.zalo.me", "qr.zalo.me"].contains(host), + u.user == nil, u.password == nil, u.port == nil, u.path.count > 1 else { return nil } + return u + } +} diff --git a/Sweep/Core/VietQR.swift b/Sweep/Core/VietQR.swift new file mode 100644 index 0000000..1b17aab --- /dev/null +++ b/Sweep/Core/VietQR.swift @@ -0,0 +1,49 @@ +import Foundation + +/// Stored separately from the legacy free-form account note. Optional in old ledgers/backups. +struct VietQRAccount: Codable, Equatable { + var bankID: String + var accountNumber: String + var accountName: String + + func validate() throws { + guard bankID.range(of: #"^[A-Za-z0-9]{2,32}$"#, options: .regularExpression) != nil, + accountNumber.range(of: #"^[A-Za-z0-9]{1,19}$"#, options: .regularExpression) != nil, + !accountName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + accountName.count <= 100, !accountName.contains(where: { $0.isNewline }) else { + throw DeliveryError.invalid("Điền mã ngân hàng/BIN, số tài khoản (tối đa 19 chữ hoặc số) và tên chủ tài khoản.") + } + } +} + +enum VietQR { + static func suggestedAmount(for order: DeliveryOrder) -> Int64 { + if order.remaining > 0 { return order.remaining } + let awaitingBankCheck = order.bank - order.verifiedBank + return awaitingBankCheck > 0 ? awaitingBankCheck : order.total + } + static func transferNote(code: String) -> String { + let folded = code.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "vi_VN")) + .replacingOccurrences(of: "đ", with: "d").replacingOccurrences(of: "Đ", with: "D").uppercased() + let safe = folded.map { character -> Character in + character.unicodeScalars.allSatisfy { (65...90).contains($0.value) || (48...57).contains($0.value) } ? character : " " + } + let words = String(safe).split(whereSeparator: \.isWhitespace).joined(separator: " ") + return String(("TT DON " + words).prefix(50)).trimmingCharacters(in: .whitespaces) + } + + static func url(account: VietQRAccount, order: DeliveryOrder, amount: Int64) throws -> URL { + try account.validate(); try VND.check(amount) + guard order.voidReason == nil, amount > 0, amount <= order.total else { + throw DeliveryError.invalid("Số tiền QR phải lớn hơn 0 và không vượt tổng đơn đang hoạt động. Tạo lại QR không sửa khoản thu đã ghi nhận.") + } + var parts = URLComponents() + parts.scheme = "https"; parts.host = "img.vietqr.io" + parts.path = "/image/\(account.bankID)-\(account.accountNumber)-qr_only.svg" + parts.queryItems = [URLQueryItem(name: "amount", value: String(amount)), + URLQueryItem(name: "addInfo", value: transferNote(code: order.code)), + URLQueryItem(name: "accountName", value: account.accountName)] + guard let url = parts.url else { throw DeliveryError.invalid("Chưa tạo được yêu cầu VietQR.") } + return url + } +} diff --git a/Sweep/Imaging/InvoiceOCR.swift b/Sweep/Imaging/InvoiceOCR.swift index 2378a46..adbc082 100644 --- a/Sweep/Imaging/InvoiceOCR.swift +++ b/Sweep/Imaging/InvoiceOCR.swift @@ -6,7 +6,7 @@ import ImageIO enum InvoiceOCR { static func read(_ url: URL) throws -> InvoiceFields { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), - let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [ + let image = CGImageSourceCreateThumbnailAtIndex(source, CGImageSourceGetPrimaryImageIndex(source), [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: 4096 diff --git a/Sweep/Info.plist b/Sweep/Info.plist index b951582..276e5e6 100644 --- a/Sweep/Info.plist +++ b/Sweep/Info.plist @@ -2,6 +2,8 @@ CFBundleDisplayNameSweep + CFBundleURLTypesCFBundleURLNamecom.sentechtipsvn.sweepCFBundleURLSchemessweep + SweepAppGroupIdentifier$(SWEEP_APP_GROUP) CFBundleName$(PRODUCT_NAME) CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) CFBundleExecutable$(EXECUTABLE_NAME) @@ -9,6 +11,10 @@ CFBundleShortVersionString$(MARKETING_VERSION) CFBundleVersion$(CURRENT_PROJECT_VERSION) LSRequiresIPhoneOS + LSApplicationQueriesSchemescomgooglemaps + UIFileSharingEnabled + LSSupportsOpeningDocumentsInPlace + NSLocationWhenInUseUsageDescriptionSweep lưu vị trí giao hàng khi Sếp chọn Lấy vị trí hiện tại. UILaunchScreen UIApplicationSceneManifestUIApplicationSupportsMultipleScenes UISupportedInterfaceOrientations diff --git a/Sweep/Services/DeliveryStore.swift b/Sweep/Services/DeliveryStore.swift index 138643e..f66411f 100644 --- a/Sweep/Services/DeliveryStore.swift +++ b/Sweep/Services/DeliveryStore.swift @@ -23,8 +23,50 @@ final class DeliveryStore: ObservableObject { try FileManager.default.createDirectory(at: evidenceDirectory, withIntermediateDirectories: true) database = try DeliveryDatabase(url: base.appendingPathComponent("Sweep.sqlite")) ledger = try database!.load() + if ledger.schema == 1 { + let previous = base + let recovery = previous.appendingPathComponent("Before-upgrade-0.5-" + UUID().uuidString + ".sweepbackup") + try DeliveryBackup.write(ledger, evidence: evidenceDirectory, to: recovery, version: 1) + var upgraded = ledger; upgraded.schema = 2 + for i in upgraded.orders.indices where upgraded.orders[i].settlement != nil && upgraded.orders[i].settlement?.route == nil { + let reminder = "Chọn lại nhánh giao phù hợp; các khoản tiền cũ được giữ nguyên." + if !upgraded.orders[i].reviewNote.contains(reminder) { upgraded.orders[i].reviewNote += (upgraded.orders[i].reviewNote.isEmpty ? "" : "\n") + reminder } + } + upgraded.record("Nâng sổ 0.5", "Giữ nguyên tiền và công; bản trước nâng cấp: " + recovery.lastPathComponent) + try database!.save(upgraded); ledger = upgraded + } + if ledger.schema == 2 { + let recovery = base.appendingPathComponent("Before-upgrade-0.6-" + UUID().uuidString + ".sweepbackup") + try DeliveryBackup.write(ledger, evidence: evidenceDirectory, to: recovery, version: 2) + var upgraded = ledger; upgraded.schema = 3 + upgraded.record("Nâng sổ 0.6", "Giữ công và tiền; bản trước nâng cấp: " + recovery.lastPathComponent) + try database!.save(upgraded); ledger = upgraded + } + for name in ["Backups", "Exports"] { + try FileManager.default.createDirectory(at: documents.appendingPathComponent(name), withIntermediateDirectories: true) + } } catch { blocked = true; message = "Sổ chưa mở được. Dữ liệu được giữ nguyên. " + error.localizedDescription } } + nonisolated private static func importCompact(_ image: URL, role: EvidenceRole, directory: URL) throws -> DeliveryEvidence { + let compact = try InvoiceImageEncoder.compact(image) + defer { try? FileManager.default.removeItem(at: compact) } + return try EvidenceFiles.importImage(compact, role: role, directory: directory) + } + var documents: URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } + var shareCache: URL { FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("DeliveryShares", isDirectory: true) } + func outgoing(_ report: DeliveryReport, order: DeliveryOrder) async -> [URL]? { + guard !busy, !blocked else { return nil }; busy = true; defer { busy = false } + let files = report.evidenceIDs.compactMap { id in order.evidence.first { $0.id == id } }, dir = evidenceDirectory, cache = shareCache + do { + return try await Task.detached(priority: .userInitiated) { + try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true) + return try files.map { file in + try EvidenceFiles.verify(file, directory: dir) + return try InvoiceImageEncoder.compact(dir.appendingPathComponent(file.filename), directory: cache) + } + }.value + } catch { message = error.localizedDescription; return nil } + } func order(_ id: UUID) -> DeliveryOrder? { ledger.orders.first { $0.id == id } } func url(_ evidence: DeliveryEvidence) -> URL { evidenceDirectory.appendingPathComponent(evidence.filename) } @discardableResult func change(_ operation: (inout DeliveryLedger) throws -> Void) -> Bool { @@ -43,7 +85,7 @@ final class DeliveryStore: ObservableObject { do { if let image { let directory = evidenceDirectory - file = try await Task.detached(priority: .userInitiated) { try EvidenceFiles.importImage(image, role: .invoice, directory: directory) }.value + file = try await Task.detached(priority: .userInitiated) { try Self.importCompact(image, role: .invoice, directory: directory) }.value if !allowRepeatedImage, let file, let duplicate = ledger.orders.first(where: { $0.evidence.contains { $0.role == .invoice && $0.sha256 == file.sha256 } }) { try? FileManager.default.removeItem(at: url(file)) message = "Ảnh này đã có trong phiếu \(duplicate.code). Mở hồ sơ cũ để kiểm tra; nếu là một phiếu khác hợp lệ, bật xác nhận dùng lại ảnh." @@ -67,7 +109,7 @@ final class DeliveryStore: ObservableObject { var file: DeliveryEvidence? do { let directory = evidenceDirectory - let imported = try await Task.detached(priority: .userInitiated) { try EvidenceFiles.importImage(image, role: role, directory: directory) }.value + let imported = try await Task.detached(priority: .userInitiated) { try Self.importCompact(image, role: role, directory: directory) }.value file = imported var next = ledger if let id { @@ -83,13 +125,15 @@ final class DeliveryStore: ObservableObject { if let file { try? FileManager.default.removeItem(at: url(file)) }; message = error.localizedDescription } } - func prepareReport(_ id: UUID, text: String) async -> DeliveryReport? { + func prepareReport(_ id: UUID, text: String, evidenceIDs: [UUID]? = nil) async -> DeliveryReport? { guard !busy, let order = order(id) else { return nil } busy = true; defer { busy = false } do { + var next = ledger + let report = try next.prepareReport(id, text: text, evidenceIDs: evidenceIDs) + let files = report.evidenceIDs.compactMap { wanted in order.activeEvidence.first { $0.id == wanted } } let directory = evidenceDirectory - try await Task.detached(priority: .userInitiated) { for file in order.activeEvidence { try EvidenceFiles.verify(file, directory: directory) } }.value - var next = ledger; let report = try next.prepareReport(id, text: text) + try await Task.detached(priority: .userInitiated) { for file in files { try EvidenceFiles.verify(file, directory: directory) } }.value try database!.save(next); ledger = next; return report } catch { message = error.localizedDescription; return nil } } @@ -118,9 +162,77 @@ final class DeliveryStore: ObservableObject { } }.value var next = prepared.ledger + next.schema = 3 next.record("Khôi phục sổ", "Bản trước khi khôi phục: \(recovery.lastPathComponent)") try database!.save(next, replacing: true); ledger = next return true } catch { message = error.localizedDescription; return false } } } + +extension DeliveryStore { + func maintain(backupFolder: URL, reset: Bool) async -> URL? { + guard !busy, !blocked, let database else { return nil } + busy = true; defer { busy = false } + let access = backupFolder.startAccessingSecurityScopedResource() + defer { if access { backupFolder.stopAccessingSecurityScopedResource() } } + do { + let folder = backupFolder.resolvingSymlinksInPath().standardizedFileURL.path + let protected = documents.resolvingSymlinksInPath().standardizedFileURL.path + guard folder != protected, !folder.hasPrefix(protected + "/"), !folder.hasPrefix(root.path) else { throw DeliveryError.invalid("Chọn iCloud Drive hoặc thư mục ngoài Sweep để giữ bản sao.") } + let snapshot = ledger, dir = evidenceDirectory + let pendingInbox = try? SharedInvoiceInbox.live() + let pendingScan = try (reset ? pendingInbox?.scan() : nil) + guard pendingScan?.warnings.isEmpty != false else { throw DeliveryError.invalid("Có ảnh chờ lỗi cần kiểm tra trước khi sao lưu và đặt lại.") } + let pending = pendingScan?.items ?? [] + let destination = backupFolder.appendingPathComponent("Sweep-before-\(reset ? "reset" : "cleanup")-\(UUID().uuidString.prefix(8)).sweepbackup") + let verified = try await Task.detached(priority: .utility) { + let staging = FileManager.default.temporaryDirectory.appendingPathComponent("Backup-check-" + UUID().uuidString) + try DeliveryBackup.write(snapshot, evidence: dir, to: destination) + let checked = try DeliveryBackup.prepare(destination, staging: staging) + guard checked.ledger == snapshot else { throw DeliveryError.invalid("Bản sao chưa khớp sổ. Chưa xoá dữ liệu.") } + if !pending.isEmpty { + let extra = destination.deletingPathExtension().appendingPathExtension("pending") + try FileManager.default.createDirectory(at: extra, withIntermediateDirectories: true) + for item in pending { + try EvidenceFiles.verify(item.evidence, directory: item.directory) + let target = extra.appendingPathComponent(item.id.uuidString) + try FileManager.default.createDirectory(at: target, withIntermediateDirectories: false) + for source in [item.image, item.directory.appendingPathComponent("manifest.json")] { + try FileManager.default.copyItem(at: source, to: target.appendingPathComponent(source.lastPathComponent)) + } + try EvidenceFiles.verify(item.evidence, directory: target) + } + let scan = try SharedInvoiceInbox(directory: extra).scan() + guard scan.items.count == pending.count, scan.warnings.isEmpty else { throw DeliveryError.invalid("Ảnh chờ chưa sao lưu đủ. Chưa xoá.") } + } + return checked + }.value + // Never delete the live store if anything changed while the backup was checked. + guard ledger == snapshot else { throw DeliveryError.invalid("Sổ đã đổi; tạo lại bản sao trước khi dọn.") } + if reset { + try database.reset(using: verified); ledger = DeliveryLedger() + for file in try FileManager.default.contentsOfDirectory(at: evidenceDirectory, includingPropertiesForKeys: nil) { try FileManager.default.removeItem(at: file) } + for name in ["Backups", "Exports"] { + let path = documents.appendingPathComponent(name) + for file in try FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil) { try FileManager.default.removeItem(at: file) } + } + for file in try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) where file.pathExtension == "sweepbackup" { try FileManager.default.removeItem(at: file) } + if let inbox = pendingInbox { + // Shares published after backup began remain available; do not race an active extension. + for item in pending { try inbox.remove(item) } + } + for key in ["photoLimit", "allowCloudScan"] { UserDefaults.standard.removeObject(forKey: key) } + } + let fm = FileManager.default + if fm.fileExists(atPath: shareCache.path) { try fm.removeItem(at: shareCache) } + // Specific owned caches only. Do not remove system caches or live files from another tool. + let cache = fm.urls(for: .cachesDirectory, in: .userDomainMask)[0] + for name in ["VietQR", "SweepCompression"] { + let path = cache.appendingPathComponent(name) + if fm.fileExists(atPath: path.path) { try fm.removeItem(at: path) } + } + return destination + } catch { message = "Chưa hoàn tất: " + error.localizedDescription; return nil } + } +} diff --git a/Sweep/Services/RenewalManager.swift b/Sweep/Services/RenewalManager.swift new file mode 100644 index 0000000..ddc5c34 --- /dev/null +++ b/Sweep/Services/RenewalManager.swift @@ -0,0 +1,128 @@ +import SwiftUI +import UserNotifications + +@MainActor +final class RenewalManager: NSObject, ObservableObject, UNUserNotificationCenterDelegate { + @Published private(set) var expiry: Date? + @Published private(set) var source = "Chưa có ngày hết hạn" + @Published private(set) var status = "" + @Published private(set) var enabled = UserDefaults.standard.bool(forKey: "renewal.enabled") + private var generation = 0 + private var refreshing = false + private var refreshRequested = false + private let center = UNUserNotificationCenter.current() + override init() { super.init(); center.delegate = self } + func setEnabled(_ value: Bool) async { + if value { + do { + guard try await center.requestAuthorization(options: [.alert, .sound, .badge]) else { + status = "Thông báo chưa được cho phép. Bật quyền trong Cài đặt iPhone."; return + } + } catch { status = error.localizedDescription; return } + } + enabled = value; UserDefaults.standard.set(value, forKey: "renewal.enabled") + await refresh() + } + func saveManual(_ date: Date) async { + UserDefaults.standard.set(date.timeIntervalSince1970, forKey: "renewal.manualExpiry") + await refresh() + } + func refresh() async { + guard !refreshing else { refreshRequested = true; return } + refreshing = true; defer { refreshing = false } + repeat { + refreshRequested = false + await updateSchedule() + } while refreshRequested + } + private func updateSchedule() async { + generation += 1; let request = generation + var candidates: [Date] = [] + var bundles = [Bundle.main.bundleURL] + let plugins = Bundle.main.bundleURL.appendingPathComponent("PlugIns") + if let items = try? FileManager.default.contentsOfDirectory(at: plugins, includingPropertiesForKeys: nil) { + bundles += items.filter { $0.pathExtension == "appex" } + } + for bundle in bundles { + let profile = bundle.appendingPathComponent("embedded.mobileprovision") + if let size = try? profile.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= 4 * 1024 * 1024, + let data = try? Data(contentsOf: profile, options: .mappedIfSafe), let value = SigningExpiry.expiration(in: data) { + candidates.append(value) + } + } + if let value = candidates.min() { expiry = value; source = "Hồ sơ ký của bản đang cài" } + else { + let value = UserDefaults.standard.double(forKey: "renewal.manualExpiry") + expiry = value > 0 ? Date(timeIntervalSince1970: value) : nil + source = expiry == nil ? "Chưa có ngày hết hạn" : "Sếp nhập từ công cụ ký" + } + let pending = await center.pendingNotificationRequests() + guard request == generation else { return } + center.removePendingNotificationRequests(withIdentifiers: pending.filter { $0.identifier.hasPrefix("sweep.renewal.") }.map(\.identifier)) + let delivered = await center.deliveredNotifications() + guard request == generation else { return } + center.removeDeliveredNotifications(withIdentifiers: delivered.filter { $0.request.identifier.hasPrefix("sweep.renewal.") }.map { $0.request.identifier }) + guard enabled, let expiry else { status = enabled ? "Nhập hạn nhìn thấy trong AltStore nếu hồ sơ không đọc được." : "Nhắc gia hạn đang tắt."; return } + let permission = await center.notificationSettings() + guard request == generation else { return } + guard permission.authorizationStatus == .authorized || permission.authorizationStatus == .provisional else { + status = "iOS chưa cho phép thông báo. Kiểm tra quyền trong Cài đặt."; return + } + let now = Date(), dates = SigningExpiry.reminders(expiry: expiry, now: now) + do { + for date in dates { + guard request == generation else { return } + let content = UNMutableNotificationContent() + content.title = date < expiry ? "Sweep sắp hết hạn ký" : "Kiểm tra gia hạn Sweep" + content.body = "Hạn ký: \(expiry.formatted(date: .numeric, time: .shortened)). Gia hạn bằng công cụ ký, sau đó mở Sweep để cập nhật hạn." + content.sound = .default + content.userInfo = ["route": "renewal"] + let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, date.timeIntervalSinceNow), repeats: false) + let id = "sweep.renewal.\(Int(expiry.timeIntervalSince1970)).\(Int(date.timeIntervalSince1970))" + try await center.add(UNNotificationRequest(identifier: id, content: content, trigger: trigger)) + } + if request == generation { status = "Đã đặt lịch từ 24 giờ trước hạn, mỗi 3 giờ. Mở lại Sweep sau khi gia hạn để hủy lịch cũ." } + } catch { if request == generation { status = "Chưa đặt đủ thông báo: " + error.localizedDescription } } + } + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + completionHandler([.banner, .sound]) + } + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { + if response.notification.request.content.userInfo["route"] as? String == "renewal" { + Task { @MainActor in NotificationCenter.default.post(name: .sweepRenewalSelected, object: nil) } + } + completionHandler() + } +} +struct RenewalView: View { + @EnvironmentObject private var renewal: RenewalManager + @State private var manual = Date().addingTimeInterval(24 * 3600) + var body: some View { + Form { + Section("Hạn bản Sweep đang cài") { + if let expiry = renewal.expiry { + Text(expiry.formatted(date: .complete, time: .shortened)).font(.headline) + Text(expiry > Date() ? "Còn \(max(0, Int(expiry.timeIntervalSinceNow / 3600))) giờ" : "Hạn đã qua; kiểm tra công cụ ký.").foregroundStyle(expiry > Date() ? Color.secondary : Color.red) + } + Text(renewal.source).font(.footnote).foregroundStyle(.secondary) + Button("Kiểm tra lại hạn ký") { Task { await renewal.refresh() } } + } + Section { + Toggle("Nhắc gia hạn Sweep", isOn: Binding(get: { renewal.enabled }, set: { value in Task { await renewal.setEnabled(value) } })) + Text(renewal.status).font(.footnote).foregroundStyle(.secondary) + } + if renewal.source != "Hồ sơ ký của bản đang cài" { + Section("Nhập hạn từ AltStore / công cụ ký") { + DatePicker("Hết hạn lúc", selection: $manual, displayedComponents: [.date, .hourAndMinute]) + Button("Lưu ngày hết hạn đã kiểm tra") { Task { await renewal.saveManual(manual) } } + Text("Nhập đúng hạn hiển thị trong công cụ ký. Không tự cộng 7 ngày hoặc coi đây là thao tác gia hạn.").font(.footnote).foregroundStyle(.secondary) + } + } + Section { + Button("Mở cài đặt thông báo") { if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } } + Text("Sau khi refresh/ký lại, mở Sweep để nhận hạn mới và hủy nhắc cũ. Thông báo phụ thuộc quyền iOS/Focus; không bảo đảm phát khi app đã hết hạn. Lịch đặt theo từng lô, bổ sung khi mở app.").font(.footnote).foregroundStyle(.secondary) + } + }.navigationTitle("Gia hạn Sweep").navigationBarTitleDisplayMode(.inline) + .task { await renewal.refresh(); if let value = renewal.expiry { manual = value } } + } +} diff --git a/Sweep/Services/VietQRService.swift b/Sweep/Services/VietQRService.swift new file mode 100644 index 0000000..20ab9eb --- /dev/null +++ b/Sweep/Services/VietQRService.swift @@ -0,0 +1,39 @@ +import Foundation +import CryptoKit + +enum VietQRService { + /// Derived QR only. The invoice image and customer name/address are never uploaded. + static func svg(for url: URL) async throws -> Data { + guard url.scheme == "https", url.host == "img.vietqr.io", url.path.hasSuffix(".svg") else { throw DeliveryError.invalid("Địa chỉ VietQR không hợp lệ.") } + let directory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("VietQR", isDirectory: true) + let key = SHA256.hash(data: Data(url.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined() + let cached = directory.appendingPathComponent(key + ".svg") + if let bytes = try? cached.resourceValues(forKeys: [.fileSizeKey]).fileSize, bytes <= 2 * 1024 * 1024, + let data = try? Data(contentsOf: cached), isSVG(data) { return data } + var request = URLRequest(url: url); request.timeoutInterval = 20 + request.setValue("image/svg+xml", forHTTPHeaderField: "Accept") + let config = URLSessionConfiguration.ephemeral; config.httpCookieStorage = nil + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let (stream, response) = try await session.bytes(for: request) + guard let http = response as? HTTPURLResponse, http.statusCode == 200, + http.url?.host == "img.vietqr.io", http.url?.scheme == "https", + http.mimeType == "image/svg+xml", http.expectedContentLength <= 2 * 1024 * 1024 else { + throw DeliveryError.invalid("VietQR chưa trả về mã QR. Kiểm tra ngân hàng, số tài khoản và kết nối rồi thử lại.") + } + var data = Data() + for try await byte in stream { + try Task.checkCancellation() + guard data.count < 2 * 1024 * 1024 else { throw DeliveryError.invalid("Ảnh QR vượt giới hạn cho phép.") } + data.append(byte) + } + guard isSVG(data) else { throw DeliveryError.invalid("Dữ liệu trả về chưa phải ảnh QR SVG.") } + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try? data.write(to: cached, options: .atomic) + return data + } + private static func isSVG(_ data: Data) -> Bool { + guard !data.isEmpty, data.count <= 2 * 1024 * 1024, let text = String(data: data, encoding: .utf8) else { return false } + return text.contains("") + } +} diff --git a/Sweep/Sweep.entitlements b/Sweep/Sweep.entitlements new file mode 100644 index 0000000..0d1e82b --- /dev/null +++ b/Sweep/Sweep.entitlements @@ -0,0 +1,5 @@ + + + + com.apple.security.application-groups$(SWEEP_APP_GROUP) + diff --git a/Sweep/Views/DeliveryComponents.swift b/Sweep/Views/DeliveryComponents.swift index e7bae15..a7cc029 100644 --- a/Sweep/Views/DeliveryComponents.swift +++ b/Sweep/Views/DeliveryComponents.swift @@ -4,6 +4,29 @@ import UniformTypeIdentifiers import QuickLook import ImageIO +private enum EvidenceThumbnails { + static let cache: NSCache = { + let value = NSCache(); value.countLimit = 80; value.totalCostLimit = 24 * 1024 * 1024; return value + }() +} + +/// SwiftUI onAppear can run before a modal transition finishes. Offer alerts only once UIKit has appeared. +struct SweepAppearanceAction: UIViewControllerRepresentable { + let action: () -> Void + func makeUIViewController(context: Context) -> Controller { Controller(action: action) } + func updateUIViewController(_ controller: Controller, context: Context) { controller.action = action } + final class Controller: UIViewController { + var action: () -> Void + init(action: @escaping () -> Void) { self.action = action; super.init(nibName: nil, bundle: nil) } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + override func loadView() { view = UIView(); view.backgroundColor = .clear } + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + DispatchQueue.main.async { [weak self] in self?.action() } + } + } +} + struct EvidenceThumbnail: View { let url: URL var height: CGFloat = 160 @@ -16,13 +39,18 @@ struct EvidenceThumbnail: View { .frame(maxWidth: .infinity).frame(height: height) .background(Color(uiColor: .tertiarySystemFill), in: RoundedRectangle(cornerRadius: 14)) .task(id: url) { + let key = url.appendingPathExtension("thumb-\(Int(height))") as NSURL + if let cached = EvidenceThumbnails.cache.object(forKey: key) { image = cached; return } let pixels = max(160, min(1200, Int(height * 3))) - image = await Task.detached(priority: .utility) { Self.thumbnail(url, pixels: pixels) }.value + let result = await Task.detached(priority: .utility) { Self.thumbnail(url, pixels: pixels) }.value + guard !Task.isCancelled else { return } + if let result { EvidenceThumbnails.cache.setObject(result, forKey: key, cost: (result.cgImage?.bytesPerRow ?? 0) * (result.cgImage?.height ?? 0)) } + image = result } } nonisolated private static func thumbnail(_ url: URL, pixels: Int) -> UIImage? { guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), - let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [kCGImageSourceCreateThumbnailFromImageAlways: true, + let image = CGImageSourceCreateThumbnailAtIndex(source, CGImageSourceGetPrimaryImageIndex(source), [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: pixels] as CFDictionary) else { return nil } return UIImage(cgImage: image) } @@ -33,38 +61,33 @@ struct EvidencePicker: View { let title: String let onChoose: (URL) async -> Void @EnvironmentObject private var store: DeliveryStore + @Environment(\.dynamicTypeSize) private var typeSize @State private var selection: PhotosPickerItem? - @State private var filePicker = false @State private var camera = false + @State private var loading = false var body: some View { VStack(alignment: .leading, spacing: 10) { Text(title).font(.subheadline.bold()) - HStack { - PhotosPicker(selection: $selection, matching: .images, preferredItemEncoding: .current) { Label("Ảnh", systemImage: "photo") } - Button { filePicker = true } label: { Label("Tệp", systemImage: "folder") } - if UIImagePickerController.isSourceTypeAvailable(.camera) { - Button { camera = true } label: { Label("Chụp", systemImage: "camera") } - } - }.buttonStyle(.bordered).disabled(store.busy) + VStack(alignment: .leading, spacing: 8) { photoButton; cameraButton } + if loading { ProgressView() } } + .buttonStyle(SweepCompactPill()).disabled(store.busy || loading) .onChange(of: selection) { _, item in guard let item else { return } Task { + loading = true; defer { loading = false; selection = nil } do { - guard let image = try await item.loadTransferable(type: ImportedImage.self) else { throw DeliveryError.invalid("Không đọc được ảnh.") } - defer { withExtendedLifetime(image) {} } - await onChoose(image.url) - } catch { store.message = error.localizedDescription } - selection = nil - } - } - .fileImporter(isPresented: $filePicker, allowedContentTypes: [.jpeg, .png, .heic]) { result in - Task { - do { - let source = try result.get() - let image = try await Task.detached { try ImportedImage.copy(from: source) }.value - defer { withExtendedLifetime(image) {} } - await onChoose(image.url) + var ready: URL? + if let data = try? await item.loadTransferable(type: Data.self) { + ready = try? await Task.detached { try IncomingInvoiceImage.copy(data: data) }.value + } + if ready == nil, let image = try await item.loadTransferable(type: ImportedImage.self) { + ready = try await Task.detached { try IncomingInvoiceImage.copy(from: image.url) }.value + withExtendedLifetime(image) {} + } + guard let ready else { throw DeliveryError.invalid("Chưa tải được ảnh. Mở ảnh trong thư viện rồi chọn lại.") } + defer { try? FileManager.default.removeItem(at: ready) } + await onChoose(ready) } catch { store.message = error.localizedDescription } } } @@ -73,16 +96,26 @@ struct EvidencePicker: View { camera = false guard let image else { return } Task { - let destination = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".jpg") - defer { try? FileManager.default.removeItem(at: destination) } + loading = true; defer { loading = false } do { - guard let data = image.jpegData(compressionQuality: 0.95) else { throw DeliveryError.invalid("Chưa đọc được ảnh vừa chụp.") } - try data.write(to: destination, options: .atomic); await onChoose(destination) + let ready = try SharedInvoiceLoader.copyImage(image) + defer { try? FileManager.default.removeItem(at: ready) } + await onChoose(ready) } catch { store.message = error.localizedDescription } } }.ignoresSafeArea() } } + private var photoButton: some View { + PhotosPicker(selection: $selection, matching: .images, preferredItemEncoding: .compatible) { + Label("Chọn ảnh", systemImage: "photo.on.rectangle") + }.accessibilityIdentifier("evidence.photos") + } + private var cameraButton: some View { + Button { camera = true } label: { + Label("Chụp ảnh", systemImage: "camera") + }.disabled(!UIImagePickerController.isSourceTypeAvailable(.camera)).accessibilityIdentifier("evidence.camera") + } } private struct EvidenceCamera: UIViewControllerRepresentable { diff --git a/Sweep/Views/DeliveryFlowView.swift b/Sweep/Views/DeliveryFlowView.swift new file mode 100644 index 0000000..4d516aa --- /dev/null +++ b/Sweep/Views/DeliveryFlowView.swift @@ -0,0 +1,139 @@ +import SwiftUI + +enum DeliveryMethod: String, Identifiable { case cash = "Tiền mặt", bank = "Chuyển khoản", freight = "Giao chành"; var id: String { rawValue } } +struct DeliveryFlowView: View { + let id: UUID + let method: DeliveryMethod + @EnvironmentObject private var store: DeliveryStore + @Environment(\.dismiss) private var dismiss + @State private var stage = "start" + @State private var partial = "" + @State private var bankAmount = "" + @State private var confirmCash = false + @State private var confirmPartialNow = false + @State private var confirmBank = false + @State private var confirmFreight = false + @State private var confirmLater = false + private var order: DeliveryOrder? { store.order(id) } + var body: some View { + NavigationStack { + Group { + if let order { + if stage == "qr" { + VStack(spacing: 0) { + OrderQRView(id: id, suggested: order.remaining) + Button("Đã nhận chuyển khoản…") { bankAmount = String(order.remaining); confirmBank = true } + .buttonStyle(SweepPill(selected: true)).padding().background(.bar) + .disabled(order.remaining <= 0) + } + } else if stage == "proof" { + List { + Section { + Text(order.customer).font(.headline) + Text(order.shareText()) + } + ForEach(order.requiredReportRoles, id: \.self) { role in + Section(role.rawValue) { + ForEach(order.activeEvidence.filter { $0.role == role }) { file in EvidenceThumbnail(url: store.url(file), height: 150) } + EvidencePicker(title: role == .invoice ? "Phiếu có số tiền" : role.rawValue) { url in await store.attach(url, role: role, to: id) } + } + } + Section { + NavigationLink { OrderReportView(id: id) } label: { Label("Kiểm tra và gửi nhóm", systemImage: "square.and.arrow.up") } + .disabled(!order.missingEvidence().isEmpty).accessibilityIdentifier("flow.report") + } + } + } else { + Form { + Section { + Text(order.customer).font(.headline) + LabeledContent("Tổng đơn", value: VND.format(order.total)) + if order.cash > 0 { LabeledContent("Tiền mặt đã ghi", value: VND.format(order.cash)) } + if order.bank > 0 { LabeledContent("Chuyển khoản đã ghi", value: VND.format(order.bank)) } + } + if order.total <= 0 { Text("Kiểm tra tổng tiền trong Sửa đơn trước khi chốt.").foregroundStyle(.red) } + if method == .cash { + Section { + Button("Thu đủ tiền mặt") { confirmCash = true }.buttonStyle(SweepPill(selected: true)).accessibilityIdentifier("flow.cashFull") + Button("Thu một phần") { partial = String(order.cash); stage = "partial" }.buttonStyle(SweepPill()).accessibilityIdentifier("flow.partial") + }.disabled(order.bank > 0 || order.total <= 0) + if stage == "partial" { + Section("Tiền mặt thực nhận") { + MoneyInput(title: "Đã nhận", text: $partial, identifier: "flow.cash") + if let c = try? VND.parse(partial), c <= order.total { LabeledContent("Còn lại", value: VND.format(order.total-c)) } + Button("Phần còn lại chuyển khoản ngay") { confirmPartialNow = true } + Button("Phần còn lại chuyển khoản sau…") { confirmLater = true } + } + } + } else if method == .bank { + Section { + Button("Chuyển khoản ngay") { stage = "qr" }.buttonStyle(SweepPill(selected: true)).disabled(order.remaining <= 0) + Button("Chuyển khoản sau…") { confirmLater = true }.buttonStyle(SweepPill()).disabled(order.bank > 0 || order.remaining <= 0) + if order.bank > 0 { Button("Tiếp tục gửi chứng từ") { stage = "proof" }.buttonStyle(SweepPill()) } + } + } else { + Section { + Text("Gửi phiếu nhà xe đã ký và ảnh hàng đã gửi. Bán hàng theo dõi tiền.").font(.subheadline) + Button("Đã giao hàng cho chành…") { confirmFreight = true }.buttonStyle(SweepPill(selected: true)).disabled(order.cash > 0 || order.bank > 0) + } + } + Section { Button("Huỷ", role: .cancel) { dismiss() } } + } + } + } + } + .navigationTitle(stage == "proof" ? "Chứng từ giao hàng" : method.rawValue).navigationBarTitleDisplayMode(.inline) + .toolbar { CloseSheet { dismiss() } } + .disabled(store.busy) + .alert("Đã thu đủ tiền mặt?", isPresented: $confirmCash) { + Button("Đã nhận đủ") { if let o = order, save(cash: o.total, bank: 0, route: .cashFull) { stage = "done"; dismiss() } } + Button("Kiểm tra lại", role: .cancel) {} + } message: { Text("\(VND.format(order?.total ?? 0)). Không cần báo cáo ảnh; mang tiền và phiếu xuất kho về công ty.") } + .alert("Ghi khoản chuyển thực nhận", isPresented: $confirmBank) { + TextField("Số tiền đã chuyển", text: $bankAmount).keyboardType(.numberPad) + Button("Xác nhận khoản thực nhận") { confirmTransfer() } + Button("Chưa nhận", role: .cancel) {} + } message: { Text("Kiểm tra giao dịch thực tế. Đóng QR không ghi nhận tiền.") } + .alert("Xác nhận tiền mặt đã nhận?", isPresented: $confirmPartialNow) { + Button("Đã nhận, mở QR phần còn lại") { savePartial(now: true) } + Button("Kiểm tra lại", role: .cancel) {} + } message: { Text("Tiền mặt \(partial)₫ sẽ được lưu trước khi mở QR. Đóng QR vẫn giữ khoản đã nhận.") } + .alert("Khách chuyển khoản sau?", isPresented: $confirmLater) { + Button("Xác nhận, chọn phiếu đã ký") { + if method == .cash { savePartial(now: false) } + else if let o = order, save(cash: o.cash, bank: o.bank, route: .transferLater) { stage = "proof" } + } + Button("Huỷ", role: .cancel) {} + } message: { Text("Chỉ gửi phiếu xuất kho khách đã ký; không gửi phiếu có giá.") } + .alert("Đã bàn giao hàng cho chành?", isPresented: $confirmFreight) { + Button("Đã giao, thêm chứng từ") { if save(cash: 0, bank: 0, route: .freight) { stage = "proof" } } + Button("Chưa giao", role: .cancel) {} + } + } + } + private func save(cash: Int64, bank: Int64, route: DeliveryRoute) -> Bool { + let mode: PaymentMode = cash > 0 && bank > 0 ? .mixed : bank > 0 ? .bank : cash > 0 ? .cash : .deferred + return store.change { try $0.settle(id, value: Settlement(outcome: .delivered, mode: mode, cash: cash, bank: bank, note: "", at: Date(), route: route)) } + } + private func savePartial(now: Bool) { + guard let order else { return } + do { + let c = try VND.parse(partial) + guard c >= order.cash else { throw DeliveryError.invalid("Đã ghi nhận tiền mặt \(VND.format(order.cash)). Dùng Điều chỉnh giao / tiền nếu cần sửa khoản đã lưu.") } + guard c + order.bank <= order.total else { throw DeliveryError.invalid("Khoản đã nhận vượt tổng đơn. Kiểm tra lại số tiền.") } + if c == order.total, order.bank == 0 { + if save(cash: c, bank: 0, route: .cashFull) { dismiss() }; return + } + if c == 0 && now { stage = "qr"; return } + if save(cash: c, bank: order.bank, route: .transferLater) { stage = now ? "qr" : "proof" } + } catch { store.message = error.localizedDescription } + } + private func confirmTransfer() { + guard let order else { return } + do { + let amount = try VND.parse(bankAmount) + guard amount > 0, amount <= order.remaining else { throw DeliveryError.invalid("Khoản chuyển phải lớn hơn 0 và không vượt phần còn lại.") } + if save(cash: order.cash, bank: order.bank + amount, route: .transferNow) { stage = "proof" } + } catch { store.message = error.localizedDescription } + } +} diff --git a/Sweep/Views/DeliverySettingsView.swift b/Sweep/Views/DeliverySettingsView.swift index 8cb0506..ce87b7f 100644 --- a/Sweep/Views/DeliverySettingsView.swift +++ b/Sweep/Views/DeliverySettingsView.swift @@ -6,6 +6,9 @@ struct DeliverySettingsView: View { @State private var fee = "" @State private var company = "" @State private var account = "" + @State private var bankID = "" + @State private var accountNumber = "" + @State private var accountName = "" var body: some View { Form { Section("Công phiếu ký nhận") { @@ -15,14 +18,25 @@ struct DeliverySettingsView: View { Section("Tài khoản nhận của công ty") { TextField("Tên công ty", text: $company) TextField("Ngân hàng · STK · Chủ tài khoản", text: $account, axis: .vertical).lineLimit(3...6) - Text("Nhập đúng tài khoản công ty trước khi đưa khách. Sweep dùng ảnh QR Sếp cung cấp.").font(.caption).foregroundStyle(.secondary) + Text("Thông tin ghi chú cũ và ảnh QR được giữ nguyên. QR tự điền số tiền dùng tài khoản VietQR bên dưới.").font(.caption).foregroundStyle(.secondary) + } + Section("VietQR theo từng đơn") { + TextField("Mã ngân hàng / BIN, ví dụ VCB hoặc 970436", text: $bankID).textInputAutocapitalization(.characters).autocorrectionDisabled().accessibilityIdentifier("settings.bankID") + TextField("Số tài khoản nhận tiền", text: $accountNumber).textInputAutocapitalization(.never).autocorrectionDisabled().accessibilityIdentifier("settings.accountNumber") + TextField("Tên chủ tài khoản", text: $accountName).textInputAutocapitalization(.characters).accessibilityIdentifier("settings.accountName") + Text("Lưu một lần, sau đó mở QR chuyển khoản trong từng đơn. Ưu tiên khoản còn lại; nếu đã ghi nhận đủ tiền, vẫn tạo lại được QR mà không đổi sổ.").font(.caption).foregroundStyle(.secondary) + Text("Khi tạo QR, ngân hàng, số tài khoản, tên chủ tài khoản, số tiền và nội dung mã phiếu được gửi tới VietQR.io. Ảnh phiếu không được gửi. Tên chủ tài khoản do Sếp nhập, không phải kết quả xác minh từ ngân hàng.").font(.caption).foregroundStyle(.secondary) } Button("Lưu cấu hình") { do { let amount = try VND.parse(fee) + let fields = [bankID, accountNumber, accountName].map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + let qrAccount: VietQRAccount? = fields.allSatisfy(\.isEmpty) ? nil : VietQRAccount(bankID: fields[0], accountNumber: fields[1], accountName: fields[2]) + try qrAccount?.validate() if store.change({ ledger in let old = ledger.settings ledger.settings.fee = amount; ledger.settings.company = company; ledger.settings.account = account + ledger.settings.vietQR = qrAccount ledger.record("Cấu hình giao hàng", "Công \(old.fee) → \(amount); công ty \(old.company) → \(company); tài khoản \(old.account) → \(account)") }) { store.message = "Đã lưu cấu hình. Phiếu đã ký giữ nguyên mức công." } } catch { store.message = error.localizedDescription } @@ -34,7 +48,10 @@ struct DeliverySettingsView: View { } } .navigationTitle("Cấu hình giao hàng").navigationBarTitleDisplayMode(.inline) - .onAppear { fee = String(store.ledger.settings.fee); company = store.ledger.settings.company; account = store.ledger.settings.account } + .onAppear { + fee = String(store.ledger.settings.fee); company = store.ledger.settings.company; account = store.ledger.settings.account + bankID = store.ledger.settings.vietQR?.bankID ?? ""; accountNumber = store.ledger.settings.vietQR?.accountNumber ?? ""; accountName = store.ledger.settings.vietQR?.accountName ?? "" + } .disabled(store.busy) } } @@ -68,7 +85,7 @@ struct DeliveryBackupView: View { Section("Bản giữ trước các lần khôi phục") { ForEach(recoveries, id: \.self) { url in Button { sharing = DeliveryShare(items: [url]) } label: { - Label("Xuất bản trước khôi phục · \(url.lastPathComponent.dropFirst(15).prefix(8))", systemImage: "clock.arrow.circlepath") + Label("Xuất bản lưu trước thay đổi · \(url.lastPathComponent.dropFirst(15).prefix(8))", systemImage: "clock.arrow.circlepath") } } } @@ -95,7 +112,7 @@ struct DeliveryBackupView: View { Button("Giữ sổ đang dùng", role: .cancel) {} } message: { Text("Sổ \(store.ledger.orders.count) hồ sơ hiện tại sẽ được thay bằng \(prepared?.ledger.orders.count ?? 0) hồ sơ của bản sao. Xuất bản hiện tại ra Tệp trước nếu Sếp cần giữ riêng.") } .onAppear { - recoveries = ((try? FileManager.default.contentsOfDirectory(at: store.root, includingPropertiesForKeys: nil)) ?? []).filter { $0.lastPathComponent.hasPrefix("Before-restore-") && $0.pathExtension == "sweepbackup" } + recoveries = ((try? FileManager.default.contentsOfDirectory(at: store.root, includingPropertiesForKeys: nil)) ?? []).filter { $0.lastPathComponent.hasPrefix("Before-") && $0.pathExtension == "sweepbackup" } } } } diff --git a/Sweep/Views/DeliveryStyle.swift b/Sweep/Views/DeliveryStyle.swift new file mode 100644 index 0000000..f2061ff --- /dev/null +++ b/Sweep/Views/DeliveryStyle.swift @@ -0,0 +1,41 @@ +import SwiftUI + +enum SweepStyle { + static let green = Color(red: 90/255, green: 200/255, blue: 125/255) + static let blue = Color(red: 0, green: 122/255, blue: 1) +} +struct SweepPill: ButtonStyle { + var selected = false + var expanded = true + func makeBody(configuration: Configuration) -> some View { + configuration.label.font(.headline).foregroundStyle(SweepStyle.blue) + .frame(maxWidth: expanded ? .infinity : nil, minHeight: 44).padding(.horizontal, 14) + .background(.ultraThinMaterial, in: Capsule()) + .background(selected ? SweepStyle.green.opacity(0.22) : Color.clear, in: Capsule()) + .overlay(Capsule().stroke(selected ? SweepStyle.green : Color.primary.opacity(0.08), lineWidth: selected ? 1.5 : 0.5)) + .opacity(configuration.isPressed ? 0.6 : 1) + } +} + +struct SweepCompactPill: ButtonStyle { + @Environment(\.dynamicTypeSize) private var typeSize + @Environment(\.accessibilityReduceMotion) private var reduceMotion + func makeBody(configuration: Configuration) -> some View { + configuration.label.font(.subheadline.weight(.semibold)).foregroundStyle(SweepStyle.blue) + .fixedSize(horizontal: !typeSize.isAccessibilitySize, vertical: false).padding(.horizontal, 16).frame(minHeight: 44) + .background(Color(uiColor: .tertiarySystemFill), in: Capsule()) + .opacity(configuration.isPressed ? 0.6 : 1) + .animation(reduceMotion ? nil : .easeOut(duration: 0.18), value: configuration.isPressed) + } +} +struct SweepCallButton: View { + let phone: String + var body: some View { + if let url = URL(string: "tel:" + phone.filter { $0.isNumber || $0 == "+" }), !phone.isEmpty { + Link(destination: url) { + Text("Gọi").font(.system(size: 15, weight: .semibold)).foregroundStyle(Color(red: 0.03, green: 0.18, blue: 0.09)) + .frame(width: 52, height: 52).background(SweepStyle.green, in: Circle()) + }.buttonStyle(.plain).accessibilityLabel("Gọi " + phone).accessibilityIdentifier("contact.call") + } + } +} diff --git a/Sweep/Views/DirectoryViews.swift b/Sweep/Views/DirectoryViews.swift new file mode 100644 index 0000000..f392a8a --- /dev/null +++ b/Sweep/Views/DirectoryViews.swift @@ -0,0 +1,336 @@ +import SwiftUI +import MapKit +import CoreLocation +import ContactsUI +import PhotosUI +import Vision + +func openGoogleMaps(_ destination: String) { + guard let native = DeliveryDirections.googleMaps(address: destination), let web = DeliveryDirections.googleMaps(address: destination, native: false) else { return } + UIApplication.shared.open(UIApplication.shared.canOpenURL(native) ? native : web) +} +private struct DirectoryHeading: View { + let title: String + let kind: String + let edit: () -> Void + @Environment(\.dynamicTypeSize) private var typeSize + private var editLabel: some View { + HStack(spacing: 2) { + Text(kind).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: true, vertical: false) + Button(action: edit) { Image(systemName: "pencil").frame(width: 44, height: 44) } + .buttonStyle(.borderless).accessibilityLabel("Sửa " + title) + } + } + var body: some View { + if typeSize.isAccessibilitySize { + VStack(alignment: .leading, spacing: 4) { Text(title).font(.headline); editLabel } + } else { + HStack(alignment: .center, spacing: 8) { + Text(title).font(.headline).fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 4) + editLabel + } + } + } +} +private struct ContactDraft: Identifiable { + var id = UUID() + var contact: DeliveryContact? + var name = "" + var phone = "" +} +struct ContactsView: View { + var editable = false + var seller: String? = nil + @EnvironmentObject private var store: DeliveryStore + @State private var query = "" + @State private var draft: ContactDraft? + @State private var picker = false + @State private var picked: ContactDraft? + private var contacts: [DeliveryContact] { + let all = store.ledger.contacts ?? [] + guard let seller else { return all } + let matches = all.filter { $0.matches(seller) } + return matches.isEmpty ? all.filter { $0.role == "Bán hàng" } : matches + } + var body: some View { + List { + if seller != nil { Text("Chọn đúng người bán hàng trên phiếu để liên hệ.").font(.subheadline).foregroundStyle(.secondary) } + ForEach(contacts.filter { query.isEmpty || ($0.name + $0.phone + $0.aliases).localizedStandardContains(query) }) { contact in + VStack(alignment: .leading, spacing: 8) { + DirectoryHeading(title: contact.name, kind: contact.role) { draft = ContactDraft(contact: contact) } + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 8) { + if !contact.phone.isEmpty { Text(contact.phone).font(.subheadline).textSelection(.enabled) } + if let zalo = ContactLinks.zalo(contact.zalo) { Link("Zalo", destination: zalo).buttonStyle(SweepCompactPill()) } + } + Spacer(minLength: 8) + SweepCallButton(phone: contact.phone) + } + }.padding(.vertical, 8) + .contextMenu { + if !contact.phone.isEmpty { Button("Sao chép số", systemImage: "doc.on.doc") { UIPasteboard.general.string = contact.phone } } + Button("Sửa liên hệ", systemImage: "pencil") { draft = ContactDraft(contact: contact) } + } + } + if contacts.isEmpty { Text("Chưa có liên hệ. Chọn từ Danh bạ hoặc thêm thủ công.").foregroundStyle(.secondary) } + }.navigationTitle("Liên hệ nhanh").searchable(text: $query, prompt: "Tên, số điện thoại") + .toolbar { + Menu { + Button("Chọn từ Danh bạ", systemImage: "person.crop.circle.badge.plus") { picker = true } + Button("Nhập thủ công", systemImage: "square.and.pencil") { draft = ContactDraft() } + } label: { Image(systemName: "plus") }.accessibilityLabel("Thêm liên hệ") + } + .sheet(isPresented: $picker, onDismiss: { if let picked { draft = picked; self.picked = nil } }) { + SweepContactPicker(select: { name, phone in picked = ContactDraft(name: name, phone: phone); picker = false }, cancel: { picker = false }) + } + .sheet(item: $draft) { value in + NavigationStack { ContactEditor(contact: value.contact, initialName: value.name, initialPhone: value.phone) } + } + } +} +struct ContactEditor: View { + var contact: DeliveryContact? = nil + var initialName = "" + var initialPhone = "" + var role = "Bán hàng" + @EnvironmentObject private var store: DeliveryStore + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var phone = "" + @State private var zalo = "" + @State private var aliases = "" + @State private var kind = "Bán hàng" + @State private var remove = false + @State private var duplicate: DeliveryContact? + @State private var confirmDuplicate = false + @State private var qr: PhotosPickerItem? + @State private var qrCandidate = "" + @State private var confirmQR = false + @State private var readingQR = false + var body: some View { + Form { + Section { + TextField("Tên", text: $name) + TextField("Số điện thoại", text: $phone).keyboardType(.phonePad) + Picker("Nhóm", selection: $kind) { ForEach(["Bán hàng", "Tài xế", "Chành xe", "Khác"], id: \.self) { Text($0) } } + TextField("Mã trên phiếu, ví dụ TEL", text: $aliases) + Text("Nhiều mã cách nhau bằng dấu phẩy. Không dùng số khách để liên hệ bán hàng.").font(.caption).foregroundStyle(.secondary) + } + Section { + DisclosureGroup("Zalo · không bắt buộc") { + TextField("Dán liên kết Zalo nếu có", text: $zalo).keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled() + PhotosPicker(selection: $qr, matching: .images, preferredItemEncoding: .compatible) { Label("Đọc QR Zalo từ ảnh", systemImage: "qrcode") }.disabled(readingQR) + if readingQR { ProgressView("Đang đọc QR…") } + if !phone.isEmpty { Button("Sao chép số để tìm trong Zalo") { UIPasteboard.general.string = phone } } + Text("Không cần biết link để lưu liên hệ. QR sẽ được kiểm tra và cho xem trước; Sweep không tự nhắn tin.").font(.caption).foregroundStyle(.secondary) + } + } + Button("Lưu liên hệ") { saveCheckingDuplicate() }.buttonStyle(SweepPill(selected: true)) + if let contact { Button("Xoá liên hệ", role: .destructive) { remove = true } + .alert("Xoá \(contact.name)?", isPresented: $remove) { + Button("Xoá", role: .destructive) { if store.change({ $0.contacts?.removeAll { $0.id == contact.id } }) { dismiss() } } + Button("Huỷ", role: .cancel) {} + } + } + }.navigationTitle(contact == nil ? "Thêm liên hệ" : "Sửa liên hệ").navigationBarTitleDisplayMode(.inline) + .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Xong") { dismiss() } } } + .onAppear { name = contact?.name ?? initialName; phone = contact?.phone ?? initialPhone; zalo = contact?.zalo ?? ""; aliases = contact?.aliases ?? ""; kind = contact?.role ?? role } + .alert("Số này đã có trong Sweep", isPresented: $confirmDuplicate) { + Button("Cập nhật liên hệ đã có") { persist(replacing: duplicate) } + Button("Giữ thành người riêng") { persist(replacing: nil) } + Button("Hủy", role: .cancel) {} + } message: { Text(duplicate?.name ?? "") } + .alert("Dùng liên kết QR này?", isPresented: $confirmQR) { + Button("Dùng liên kết") { zalo = qrCandidate } + Button("Hủy", role: .cancel) {} + } message: { Text(qrCandidate) } + .onChange(of: qr) { _, item in + guard let item else { return } + Task { + readingQR = true; defer { readingQR = false; qr = nil } + do { + guard let data = try await item.loadTransferable(type: Data.self), data.count <= 80 * 1024 * 1024 else { throw DeliveryError.invalid("Chưa tải được ảnh QR hoặc ảnh quá lớn.") } + let values = try await Task.detached(priority: .userInitiated) { + let request = VNDetectBarcodesRequest(); request.symbologies = [.qr] + try VNImageRequestHandler(data: data).perform([request]) + return (request.results ?? []).compactMap(\.payloadStringValue).filter { ContactLinks.zalo($0) != nil } + }.value + guard Set(values).count == 1, let first = values.first else { throw DeliveryError.invalid("Ảnh cần có một QR liên kết Zalo hợp lệ. Sếp chọn lại ảnh hoặc dán link.") } + qrCandidate = first; confirmQR = true + } catch { store.message = error.localizedDescription } + } + } + } + private func saveCheckingDuplicate() { + let key = ContactLinks.phoneKey(phone) + duplicate = (store.ledger.contacts ?? []).first { $0.id != contact?.id && !key.isEmpty && ContactLinks.phoneKey($0.phone) == key } + if duplicate != nil { confirmDuplicate = true } else { persist(replacing: nil) } + } + private func persist(replacing other: DeliveryContact?) { + let value = DeliveryContact(id: other?.id ?? contact?.id ?? UUID(), name: name.trimmingCharacters(in: .whitespacesAndNewlines), phone: phone.trimmingCharacters(in: .whitespacesAndNewlines), zalo: other != nil && zalo.isEmpty ? other!.zalo : zalo.trimmingCharacters(in: .whitespacesAndNewlines), aliases: other != nil && aliases.isEmpty ? other!.aliases : aliases, role: kind) + if store.change({ try $0.saveContact(value) }) { dismiss() } + } +} +private struct SweepContactPicker: UIViewControllerRepresentable { + let select: (String, String) -> Void + let cancel: () -> Void + func makeCoordinator() -> Coordinator { Coordinator(select: select, cancel: cancel) } + func makeUIViewController(context: Context) -> CNContactPickerViewController { + let picker = CNContactPickerViewController(); picker.delegate = context.coordinator + picker.displayedPropertyKeys = [CNContactPhoneNumbersKey] + picker.predicateForEnablingContact = NSPredicate(format: "phoneNumbers.@count > 0") + picker.predicateForSelectionOfContact = NSPredicate(format: "phoneNumbers.@count == 1") + picker.predicateForSelectionOfProperty = NSPredicate(format: "key == 'phoneNumbers'") + return picker + } + func updateUIViewController(_ uiViewController: CNContactPickerViewController, context: Context) {} + final class Coordinator: NSObject, CNContactPickerDelegate { + let select: (String, String) -> Void + let cancel: () -> Void + init(select: @escaping (String, String) -> Void, cancel: @escaping () -> Void) { self.select = select; self.cancel = cancel } + func contactPickerDidCancel(_ picker: CNContactPickerViewController) { cancel() } + func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { + if let phone = contact.phoneNumbers.first?.value.stringValue { select(CNContactFormatter.string(from: contact, style: .fullName) ?? contact.givenName, phone) } + } + func contactPicker(_ picker: CNContactPickerViewController, didSelect property: CNContactProperty) { + if let phone = property.value as? CNPhoneNumber { select(CNContactFormatter.string(from: property.contact, style: .fullName) ?? property.contact.givenName, phone.stringValue) } + } + } +} +struct PlacesView: View { + @EnvironmentObject private var store: DeliveryStore + @State private var query = "" + @State private var editing: DeliveryPlace? + var body: some View { + List { + ForEach((store.ledger.places ?? []).filter { query.isEmpty || ($0.customer + $0.address + $0.phone).localizedStandardContains(query) }) { place in + VStack(alignment: .leading, spacing: 10) { + DirectoryHeading(title: place.customer, kind: place.kind) { editing = place } + Text(place.address).font(.subheadline) + if !place.phone.isEmpty { Text(place.phone).font(.subheadline).textSelection(.enabled) } + HStack { + Button("Google Maps") { openGoogleMaps(place.destination) }.buttonStyle(SweepCompactPill()) + Spacer(minLength: 8) + SweepCallButton(phone: place.phone) + } + }.padding(.vertical, 8) + } + if (store.ledger.places ?? []).isEmpty { Text("Chưa lưu vị trí.").foregroundStyle(.secondary) } + }.navigationTitle("Vị trí").searchable(text: $query, prompt: "Khách, chành, địa chỉ") + .toolbar { NavigationLink { PlaceEditor() } label: { Image(systemName: "plus") }.accessibilityLabel("Thêm vị trí") } + .sheet(item: $editing) { place in NavigationStack { PlaceEditor(place: place).toolbar { ToolbarItem(placement: .cancellationAction) { Button("Xong") { editing = nil } } } } } + } +} +@MainActor +final class DeliveryGPS: NSObject, ObservableObject, CLLocationManagerDelegate { + @Published var coordinate: CLLocationCoordinate2D? + @Published var problem = "" + @Published var accuracy: Double? + private let manager = CLLocationManager() + private var requested = false + override init() { super.init(); manager.delegate = self; manager.desiredAccuracy = kCLLocationAccuracyBest } + func request() { + problem = ""; requested = true + if manager.authorizationStatus == .notDetermined { manager.requestWhenInUseAuthorization() } + else if manager.authorizationStatus == .denied || manager.authorizationStatus == .restricted { problem = "Cho phép vị trí trong Cài đặt hoặc chọn trên bản đồ." } + else { manager.requestLocation() } + } + func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { + if requested && (manager.authorizationStatus == .authorizedWhenInUse || manager.authorizationStatus == .authorizedAlways) { manager.requestLocation() } + } + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + guard let location = locations.last, location.horizontalAccuracy >= 0, abs(location.timestamp.timeIntervalSinceNow) < 60 else { + problem = "Chưa nhận được vị trí mới. Sếp thử lại hoặc chọn trên bản đồ."; return + } + accuracy = location.horizontalAccuracy; coordinate = location.coordinate + } + func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { problem = error.localizedDescription } +} +struct PlaceEditor: View { + var place: DeliveryPlace? = nil + var order: DeliveryOrder? = nil + @EnvironmentObject private var store: DeliveryStore + @Environment(\.dismiss) private var dismiss + @StateObject private var gps = DeliveryGPS() + @State private var customer = "" + @State private var phone = "" + @State private var address = "" + @State private var kind = "Khách hàng" + @State private var lat = "" + @State private var lon = "" + @State private var map = false + @State private var remove = false + @State private var mapCenter = CLLocationCoordinate2D(latitude: 10.7769, longitude: 106.7009) + @State private var position: MapCameraPosition = .automatic + @State private var locating = false + var body: some View { + Form { + Section { + TextField("Tên khách / chành", text: $customer) + TextField("Số điện thoại", text: $phone).keyboardType(.phonePad) + TextField("Địa chỉ / chi nhánh", text: $address, axis: .vertical) + Picker("Loại", selection: $kind) { Text("Khách hàng").tag("Khách hàng"); Text("Chành xe").tag("Chành xe") } + } + Section("Vị trí chính xác · tuỳ chọn") { + Button("Lấy vị trí hiện tại") { gps.request() } + Button("Chọn trên bản đồ") { prepareMap() } + if locating { ProgressView() } + if !gps.problem.isEmpty { Text(gps.problem).font(.caption).foregroundStyle(.red) } + if let accuracy = gps.accuracy { Text("Độ chính xác GPS khoảng \(Int(accuracy.rounded())) m. Kiểm tra lại điểm trước khi lưu.").font(.caption).foregroundStyle(.secondary) } + TextField("Vĩ độ", text: $lat).keyboardType(.numbersAndPunctuation) + TextField("Kinh độ", text: $lon).keyboardType(.numbersAndPunctuation) + } + Button("Lưu vị trí") { save() }.buttonStyle(SweepPill(selected: true)) + if let place { Button("Xoá vị trí", role: .destructive) { remove = true } + .alert("Xoá vị trí đã lưu?", isPresented: $remove) { + Button("Xoá", role: .destructive) { if store.change({ $0.places?.removeAll { $0.id == place.id } }) { dismiss() } } + Button("Huỷ", role: .cancel) {} + } + } + }.navigationTitle("Lưu vị trí").navigationBarTitleDisplayMode(.inline) + .toolbar { CloseSheet { dismiss() } } + .onAppear { + customer = place?.customer ?? order?.customer ?? ""; phone = place?.phone ?? order?.phone ?? ""; address = place?.address ?? order?.address ?? "" + kind = place?.kind ?? (order?.settlement?.route == .freight ? "Chành xe" : "Khách hàng") + if kind == "Chành xe", place == nil { customer = ""; address = ""; phone = "" } + lat = place?.latitude.map { String($0) } ?? ""; lon = place?.longitude.map { String($0) } ?? "" + } + .onChange(of: gps.coordinate?.latitude) { _, _ in if let c = gps.coordinate { lat = String(c.latitude); lon = String(c.longitude) } } + .sheet(isPresented: $map) { + NavigationStack { + Map(position: $position).overlay { Image(systemName: "mappin.circle.fill").font(.largeTitle).foregroundStyle(.red).allowsHitTesting(false) } + .onMapCameraChange(frequency: .onEnd) { context in mapCenter = context.region.center } + .safeAreaInset(edge: .bottom) { Button("Dùng vị trí ghim") { lat = String(mapCenter.latitude); lon = String(mapCenter.longitude); map = false }.buttonStyle(SweepPill(selected: true)).padding().background(.bar) } + .navigationTitle("Kéo bản đồ đến vị trí").navigationBarTitleDisplayMode(.inline) + .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Huỷ") { map = false } } } + } + } + } + private func prepareMap() { + if let a = Double(lat), let b = Double(lon) { mapCenter = CLLocationCoordinate2D(latitude: a, longitude: b); showMap(); return } + guard !address.isEmpty else { showMap(); return } + locating = true + Task { + defer { locating = false } + do { + let request = MKLocalSearch.Request(); request.naturalLanguageQuery = address + let results = try await MKLocalSearch(request: request).start() + if let item = results.mapItems.first { mapCenter = item.placemark.coordinate } + showMap() + } catch { store.message = "Chưa tìm được địa chỉ. Sếp có thể kéo bản đồ để chọn."; showMap() } + } + } + private func showMap() { position = .region(MKCoordinateRegion(center: mapCenter, span: MKCoordinateSpan(latitudeDelta: 0.012, longitudeDelta: 0.012))); map = true } + private func save() { + if (!lat.isEmpty && Double(lat) == nil) || (!lon.isEmpty && Double(lon) == nil) { store.message = "Tọa độ phải là số, dùng dấu chấm thập phân."; return } + let value = DeliveryPlace(id: place?.id ?? UUID(), customer: customer, phone: phone, address: address, kind: kind, latitude: Double(lat), longitude: Double(lon)) + if store.change({ ledger in + try ledger.savePlace(value) + if let order, order.settlement?.route == .freight, kind == "Chành xe", + let i = ledger.orders.firstIndex(where: { $0.id == order.id }) { + ledger.orders[i].freightPlaceID = ledger.places?.first(where: { $0.key == value.key })?.id + } + }) { dismiss() } + } +} diff --git a/Sweep/Views/HomeView.swift b/Sweep/Views/HomeView.swift index 0d5fb3f..2d45859 100644 --- a/Sweep/Views/HomeView.swift +++ b/Sweep/Views/HomeView.swift @@ -6,63 +6,32 @@ private enum AppRelease { } struct HomeView: View { + @Environment(\.dynamicTypeSize) private var typeSize + private var columns: [GridItem] { Array(repeating: GridItem(.flexible(), spacing: 12), count: typeSize.isAccessibilitySize ? 2 : 4) } var body: some View { ScrollView { - VStack(alignment: .leading, spacing: 24) { - Text("Công cụ ảnh và tệp").font(.title3.bold()) - LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 14)], spacing: 14) { - NavigationLink { LibraryView(mode: .duplicates) } label: { - ToolCard(title: "Ảnh trùng", subtitle: "Đối chiếu dữ liệu gốc", icon: "square.on.square", color: .green) - }.accessibilityIdentifier("tool.duplicates") - NavigationLink { LibraryView(mode: .screenshots) } label: { - ToolCard(title: "Ảnh màn hình", subtitle: "Rà soát ảnh đã lưu", icon: "viewfinder", color: .teal) - } - NavigationLink { CompressionView() } label: { - ToolCard(title: "Nén ảnh", subtitle: "Nhẹ hơn, dễ chia sẻ", icon: "arrow.down.right.and.arrow.up.left", color: .blue) - }.accessibilityIdentifier("tool.compress") - NavigationLink { FilesView() } label: { - ToolCard(title: "File lớn", subtitle: "Xem thư mục được chọn", icon: "folder", color: .orange) - } - } - .buttonStyle(.plain) - - Label("Xử lý trên thiết bị", systemImage: "lock.shield") - .font(.headline) - Text("Sweep không có máy chủ tải ảnh lên, không cần tài khoản hay VPN. Ảnh chỉ tải từ iCloud khi Sếp cho phép hoặc chọn nhập ảnh đó.") - .font(.footnote).foregroundStyle(.secondary) - Text("BẢN THỬ NGHIỆM \(AppRelease.version) · © Sentechtipsvn") - .font(.caption2.weight(.medium)).foregroundStyle(.secondary) - } - .padding(20) - .frame(maxWidth: 700) - .frame(maxWidth: .infinity) - } - .background(Color(uiColor: .systemGroupedBackground)) - .navigationTitle("") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .topBarLeading) { Text("Sweep").font(.title2.bold()).accessibilityAddTraits(.isHeader) } - ToolbarItem(placement: .topBarTrailing) { Image(systemName: "sparkles").foregroundStyle(.green).accessibilityHidden(true) } - } + LazyVGrid(columns: columns, spacing: 24) { + NavigationLink { LibraryView(mode: .duplicates) } label: { ToolIcon(title: "Ảnh trùng", asset: "tool-duplicates") }.accessibilityIdentifier("tool.duplicates") + NavigationLink { LibraryView(mode: .screenshots) } label: { ToolIcon(title: "Ảnh màn hình", asset: "tool-screenshots") } + NavigationLink { CompressionView() } label: { ToolIcon(title: "Nén ảnh", asset: "tool-compress") }.accessibilityIdentifier("tool.compress") + NavigationLink { FilesView() } label: { ToolIcon(title: "Tệp lớn", asset: "tool-files") } + NavigationLink { PlacesView() } label: { ToolIcon(title: "Vị trí", asset: "tool-places") } + NavigationLink { ContactsView() } label: { ToolIcon(title: "Liên hệ", asset: "tool-contacts") } + NavigationLink { MaintenanceView() } label: { ToolIcon(title: "Dọn dẹp", asset: "tool-cleanup") } + NavigationLink { PayrollView() } label: { ToolIcon(title: "Chấm công", asset: "tool-payroll") }.accessibilityIdentifier("tool.payroll") + }.buttonStyle(.plain).padding(20) + }.background(Color(uiColor: .systemGroupedBackground)).navigationTitle("Công cụ") } } - -private struct ToolCard: View { +private struct ToolIcon: View { let title: String - let subtitle: String - let icon: String - let color: Color + let asset: String var body: some View { - VStack(alignment: .leading, spacing: 13) { - Image(systemName: icon).font(.title2).foregroundStyle(color) - .frame(width: 44, height: 44).background(color.opacity(0.12), in: RoundedRectangle(cornerRadius: 14)) - Text(title).font(.headline).foregroundStyle(.primary) - Text(subtitle).font(.caption).foregroundStyle(.secondary) - } - .frame(maxWidth: .infinity, minHeight: 140, alignment: .leading) - .padding(17) - .background(Color(uiColor: .secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 24)) - .overlay(RoundedRectangle(cornerRadius: 24).stroke(Color.primary.opacity(0.08), lineWidth: 1)) + VStack(spacing: 8) { + Image(asset).resizable().scaledToFit().frame(maxWidth: 66).aspectRatio(1, contentMode: .fit) + .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) + Text(title).font(.caption).foregroundStyle(.primary).multilineTextAlignment(.center).lineLimit(2).frame(minHeight: 32, alignment: .top) + }.frame(maxWidth: .infinity).contentShape(Rectangle()) } } @@ -73,7 +42,12 @@ struct SettingsView: View { var body: some View { Form { Section("Trợ lý giao hàng") { + NavigationLink("Liên hệ bán hàng / tài xế") { ContactsView(editable: true) } + NavigationLink("Dọn dẹp / đặt lại dữ liệu") { MaintenanceView() } NavigationLink("Công đơn và QR công ty") { DeliverySettingsView() } + NavigationLink("Chấm công và lương") { PayrollView() } + NavigationLink("Gia hạn Sweep") { RenewalView() } + NavigationLink("Nhận ảnh bằng Phím tắt") { SweepShortcutGuide() } NavigationLink("Sao lưu và khôi phục sổ / ảnh") { DeliveryBackupView() } Text("Sổ lưu trên thiết bị. Xóa app có thể xóa sổ; xuất bản sao ra Tệp trước khi đổi máy hoặc cài lại.").font(.footnote).foregroundStyle(.secondary) } diff --git a/Sweep/Views/MaintenanceView.swift b/Sweep/Views/MaintenanceView.swift new file mode 100644 index 0000000..3142d1b --- /dev/null +++ b/Sweep/Views/MaintenanceView.swift @@ -0,0 +1,40 @@ +import SwiftUI +import UniformTypeIdentifiers + +struct MaintenanceView: View { + @EnvironmentObject private var store: DeliveryStore + @State private var folder = false + @State private var reset = false + @State private var confirm = false + @State private var confirmation = "" + @State private var backupFolder: URL? + @State private var result = "" + var body: some View { + Form { + Section("Dọn bộ nhớ tạm") { + Text("Xoá bản ảnh chia sẻ và tệp tạm có thể tạo lại. Giữ sổ, chứng từ và liên hệ.").font(.subheadline) + Button("Sao lưu và dọn cache") { reset = false; folder = true }.buttonStyle(SweepPill()) + } + Section("Bắt đầu dùng chính thức") { + Text("Đặt lại toàn bộ dữ liệu thử nghiệm: đơn, ảnh trong Sweep, tiền, công, vị trí, liên hệ, cấu hình và ảnh chờ nhập. Không xoá ảnh trong thư viện hay Zalo.").font(.subheadline) + Button("Sao lưu và xoá dữ liệu thử nghiệm…", role: .destructive) { reset = true; folder = true }.accessibilityIdentifier("maintenance.reset") + } + Section { + Text("Chọn thư mục sao lưu ngoài Sweep. Chỉ xoá sau khi bản sao đã ghi xong và kiểm tra lại đầy đủ.").font(.caption).foregroundStyle(.secondary) + if store.busy { ProgressView("Đang sao lưu và kiểm tra…") } + if !result.isEmpty { Text(result).foregroundStyle(.secondary) } + } + }.navigationTitle("Dọn dẹp").disabled(store.busy) + .fileImporter(isPresented: $folder, allowedContentTypes: [.folder]) { selection in + do { backupFolder = try selection.get(); confirmation = ""; confirm = true } + catch { if (error as NSError).code != NSUserCancelledError { store.message = error.localizedDescription } } + } + .alert(reset ? "Xoá sạch dữ liệu thử nghiệm?" : "Sao lưu rồi dọn cache?", isPresented: $confirm) { + if reset { TextField("Nhập XOA để xác nhận", text: $confirmation).textInputAutocapitalization(.characters) } + Button(reset ? "Sao lưu và xoá sạch" : "Sao lưu và dọn", role: reset ? .destructive : nil) { + Task { if let dir = backupFolder, let backup = await store.maintain(backupFolder: dir, reset: reset) { result = "Đã hoàn tất. Bản sao: " + backup.lastPathComponent } } + }.disabled(reset && confirmation != "XOA") + Button("Huỷ", role: .cancel) {} + } message: { Text(reset ? "Toàn bộ sổ và cấu hình trong Sweep sẽ bị xoá sau khi sao lưu. Nhập XOA để tiếp tục." : "Giữ nguyên dữ liệu giao hàng. Nếu sao lưu lỗi, Sweep không dọn.") } + } +} diff --git a/Sweep/Views/OrderDetailView.swift b/Sweep/Views/OrderDetailView.swift index 31abe53..d79b832 100644 --- a/Sweep/Views/OrderDetailView.swift +++ b/Sweep/Views/OrderDetailView.swift @@ -6,6 +6,9 @@ struct OrderDetailView: View { @EnvironmentObject private var store: DeliveryStore @State private var preview: URL? @State private var settle = false + @State private var method: DeliveryMethod? + @State private var saveLocation = false + @State private var locationPrompt = false @State private var sign = false @State private var edit = false @State private var void = false @@ -20,22 +23,36 @@ struct OrderDetailView: View { VStack(spacing: 0) { List { Section { - Text(order.customer).font(.title2.bold()).textSelection(.enabled) - LabeledContent("Tổng đơn", value: VND.format(order.total)).font(.headline) - LabeledContent("Mã phiếu", value: order.code).textSelection(.enabled) - if let date = order.invoiceAt { LabeledContent("Ngày hóa đơn", value: date.formatted(date: .numeric, time: .omitted)) } if let invoice = order.activeEvidence.first(where: { $0.role == .invoice }) { - Button { preview = store.url(invoice) } label: { EvidenceThumbnail(url: store.url(invoice), height: 200) }.buttonStyle(.plain) + Button { preview = store.url(invoice) } label: { EvidenceThumbnail(url: store.url(invoice), height: 230) }.buttonStyle(.plain) + .overlay(alignment: .topTrailing) { + Menu { + let matches = (store.ledger.contacts ?? []).filter { $0.matches(order.salesperson ?? "") } + if matches.count == 1, let contact = matches.first { + if let u = phoneURL(contact.phone) { Link("Gọi \(contact.name)", destination: u) } + if let u = URL(string: contact.zalo), !contact.zalo.isEmpty { Link("Zalo \(contact.name)", destination: u) } + } else { + NavigationLink("Chọn liên hệ bán hàng") { ContactsView(seller: order.salesperson ?? "") } + NavigationLink("Thêm liên hệ bán hàng") { ContactEditor(initialName: order.salesperson ?? "", role: "Bán hàng") } + } + } label: { Image(systemName: "ellipsis.circle.fill").font(.title).symbolRenderingMode(.palette).foregroundStyle(.blue, .white).padding(8) }.accessibilityLabel("Liên hệ bán hàng") + } + } + HStack { Text(order.customer).font(.title3.bold()); Spacer(); Text(VND.format(order.total)).font(.headline).monospacedDigit() } + Text(order.code).font(.caption).foregroundStyle(.secondary) + if !order.address.isEmpty { + Text(order.address).textSelection(.enabled) + Button { openDirections(order.address) } label: { Label("Google Maps", systemImage: "location") }.buttonStyle(SweepPill()).accessibilityIdentifier("order.directions") } - HStack { - if let url = phoneURL(order.phone) { Link(destination: url) { Label("Gọi", systemImage: "phone") } } - if !order.address.isEmpty, let url = mapURL(order.address) { - Link(destination: url) { Label("Đường", systemImage: "map") } + if let u = phoneURL(order.phone) { Link(destination: u) { Label(order.phone, systemImage: "phone.fill").frame(maxWidth: .infinity, minHeight: 44) }.buttonStyle(SweepPill()) } + NavigationLink { OrderQRView(id: id) } label: { Label("QR chuyển khoản", systemImage: "qrcode") }.accessibilityIdentifier("order.qr") + } + if order.voidReason == nil { + Section { + ForEach([DeliveryMethod.cash, .bank, .freight]) { item in + Button(item.rawValue) { method = item }.buttonStyle(SweepPill(selected: true)).accessibilityIdentifier("method.\(item.id)") } - NavigationLink { BankCompanyView() } label: { Label("QR công ty", systemImage: "qrcode") } - }.font(.subheadline).buttonStyle(.bordered) - if !order.phone.isEmpty { Text(order.phone).font(.caption).textSelection(.enabled) } - if !order.address.isEmpty { Text(order.address).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) } + }.disabled(order.activeAssignments.isEmpty) } Section("Ký nhận và công đơn") { if let assignment = order.assignments.first { @@ -45,21 +62,20 @@ struct OrderDetailView: View { Text("Chưa xác nhận ký nhận · chưa tính công").foregroundStyle(.secondary) Button("Xác nhận Sếp đã ký nhận phiếu") { sign = true }.accessibilityIdentifier("order.sign") } - Text("Chữ ký khách là chứng từ giao hàng. Thêm ảnh hay báo cáo lại không cộng thêm công.").font(.caption).foregroundStyle(.secondary) } Section("Giao và tiền") { LabeledContent("Kết quả", value: order.outcome.rawValue) LabeledContent("Tiền mặt đã thu", value: VND.format(order.cash)) LabeledContent("CK khách báo", value: VND.format(order.bank)) - LabeledContent("CK đã đối soát", value: VND.format(order.verifiedBank)) + LabeledContent("Còn lại theo ghi nhận", value: VND.format(order.remaining)).foregroundStyle(order.remaining > 0 ? .orange : .primary) if let value = order.settlement { Text(value.at.formatted(date: .numeric, time: .shortened)).font(.caption).foregroundStyle(.secondary) if !value.note.isEmpty { Text(value.note).font(.footnote) } } - if order.bank > order.verifiedBank { Button("Xác nhận CK đã vào công ty…") { reason = ""; bank = true } } + } - ForEach([EvidenceRole.invoice, .signature, .transfer], id: \.self) { role in + ForEach([EvidenceRole.invoice, .signature, .transfer, .freightSignature, .goods].filter { role in role == .invoice || order.allowedReportRoles.contains(role) || order.activeEvidence.contains(where: { $0.role == role }) }, id: \.self) { role in Section(role.rawValue) { let files = order.activeEvidence.filter { $0.role == role } if !files.isEmpty { @@ -77,10 +93,11 @@ struct OrderDetailView: View { if order.voidReason == nil { EvidencePicker(title: "Bổ sung \(role.rawValue.lowercased())") { url in await store.attach(url, role: role, to: id) } } } } - Section("Báo cáo") { - Label(order.reportSent ? "Sếp đã xác nhận gửi" : order.reports.isEmpty ? "Chưa chuẩn bị báo cáo" : "Chưa xác nhận gửi / cần gửi lại", systemImage: order.reportSent ? "checkmark.circle.fill" : "paperplane") + if order.requiresReport { Section("Chia sẻ") { + Label(order.reportSent ? "Đã gửi" : "Chưa gửi", systemImage: order.reportSent ? "checkmark.circle.fill" : "paperplane") .foregroundStyle(order.reportSent ? .green : .secondary) - NavigationLink { OrderReportView(id: id) } label: { Label("Chuẩn bị và chia sẻ báo cáo", systemImage: "square.and.arrow.up") }.accessibilityIdentifier("order.report") + NavigationLink { OrderReportView(id: id) } label: { Label("Chia sẻ đơn", systemImage: "square.and.arrow.up") }.accessibilityIdentifier("order.report") + } } if !order.reviewNote.isEmpty { Section("Dữ liệu cũ cần rà soát") { @@ -93,10 +110,9 @@ struct OrderDetailView: View { ledger.record("Sếp xác nhận đã rà soát sổ cũ", orderID: id, previous) } } - Text("Thao tác này chỉ bỏ cờ nhắc, không tự xác nhận ngày ký, ghi công, đối soát CK hoặc gửi báo cáo.").font(.caption).foregroundStyle(.secondary) } } - if !order.note.isEmpty { Section("Ghi chú hồ sơ") { Text(order.note) } } + if !order.deliveryNoteForDisplay.isEmpty { Section("Ghi chú giao hàng") { Text(order.deliveryNoteForDisplay) } } Section { if !order.exclusions.isEmpty { NavigationLink("Ảnh gốc đã loại khỏi báo cáo (\(order.exclusions.count))") { @@ -111,18 +127,20 @@ struct OrderDetailView: View { } } NavigationLink("Lịch sử hồ sơ") { OrderHistoryView(id: id) } + if order.voidReason == nil { Button("Điều chỉnh giao / tiền…") { settle = true }.accessibilityIdentifier("order.settle") } if order.voidReason == nil { Button("Hủy hồ sơ nhập nhầm…", role: .destructive) { reason = ""; void = true } } else { Text("Đã hủy: \(order.voidReason ?? "")").foregroundStyle(.secondary) } } } - if order.voidReason == nil { - Button { settle = true } label: { - Label("Chốt giao / thu tiền", systemImage: "checkmark.circle") - .font(.headline).frame(maxWidth: .infinity, minHeight: 36) - } - .buttonStyle(.borderedProminent).padding(12).background(.bar).accessibilityIdentifier("order.settle") - } } + .sheet(item: $method, onDismiss: promptForLocation) { DeliveryFlowView(id: id, method: $0) } + .sheet(isPresented: $saveLocation) { NavigationStack { PlaceEditor(order: order) } } + .onAppear { promptForLocation() } + .alert("Lưu vị trí giao hàng?", isPresented: $locationPrompt) { + Button("Lưu vị trí") { markLocationPrompt(); saveLocation = true } + Button("Để sau", role: .cancel) { markLocationPrompt() } + } + .sheet(isPresented: $settle) { SettlementView(order: order) } .sheet(isPresented: $sign) { SignAssignmentView(id: id) } .sheet(isPresented: $edit) { EditOrderView(order: order) } @@ -131,11 +149,6 @@ struct OrderDetailView: View { Button("Hủy hồ sơ", role: .destructive) { _ = store.change { try $0.void(id, reason: reason) } } Button("Giữ hồ sơ", role: .cancel) {} } message: { Text("Giữ lịch sử và chứng từ; điều chỉnh công đã ghi. Hồ sơ có khoản thu phải được rà soát tiền trước.") } - .alert("Công ty đã xác nhận nhận CK?", isPresented: $bank) { - TextField("Ai / nội dung xác nhận", text: $reason) - Button("Ghi nhận đối soát") { _ = store.change { try $0.verifyBank(id, note: reason) } } - Button("Để sau", role: .cancel) {} - } message: { Text("Ảnh khách chuyển khoản chưa đủ để xác nhận tiền đã vào công ty. Chỉ ghi nhận khi Sếp có thông tin từ công ty.") } .alert("Loại ảnh khỏi bộ báo cáo?", isPresented: $excluding) { TextField("Lý do / ảnh bổ sung thay thế", text: $reason) Button("Loại khỏi báo cáo", role: .destructive) { if let excludedFile { _ = store.change { try $0.excludeEvidence(excludedFile, orderID: id, reason: reason) } } } @@ -148,15 +161,31 @@ struct OrderDetailView: View { .quickLookPreview($preview) .disabled(store.busy) } + private func promptForLocation() { + guard let order, order.taskComplete, order.locationPromptedAt == nil, !store.ledger.hasPlace(for: order) else { return } + locationPrompt = true + } + private func markLocationPrompt() { + _ = store.change { ledger in + if let i = ledger.orders.firstIndex(where: { $0.id == id }) { ledger.orders[i].locationPromptedAt = Date() } + } + } private func phoneURL(_ text: String) -> URL? { let number = text.filter { $0.isNumber || $0 == "+" } guard number.filter(\.isNumber).count >= 8 else { return nil } return URL(string: "tel:\(number)") } - private func mapURL(_ address: String) -> URL? { - var components = URLComponents(string: "https://maps.apple.com/") - components?.queryItems = [URLQueryItem(name: "q", value: address)] - return components?.url + private func openDirections(_ address: String) { + let saved = order.flatMap { o in + (store.ledger.places ?? []).first { + if o.settlement?.route == .freight { return $0.id == o.freightPlaceID } + return $0.key == DeliveryPlace.key(customer: o.customer, address: o.address, kind: "Khách hàng", phone: o.phone) + } + } + let destination = saved?.destination ?? address + guard let native = DeliveryDirections.googleMaps(address: destination), let web = DeliveryDirections.googleMaps(address: destination, native: false) else { return } + if UIApplication.shared.canOpenURL(native) { UIApplication.shared.open(native) } + else { UIApplication.shared.open(web) } } } @@ -197,7 +226,7 @@ private struct EditOrderView: View { init(order: DeliveryOrder) { self.order = order _code = State(initialValue: order.code); _name = State(initialValue: order.customer); _total = State(initialValue: String(order.total)) - _phone = State(initialValue: order.phone); _address = State(initialValue: order.address); _note = State(initialValue: order.note) + _phone = State(initialValue: order.phone); _address = State(initialValue: order.address); _note = State(initialValue: order.deliveryNoteForDisplay) } var body: some View { NavigationStack { @@ -234,8 +263,12 @@ struct SettlementView: View { @State private var bank: String @State private var date: Date @State private var note: String + @State private var route: DeliveryRoute? + @State private var pending: Settlement? + @State private var confirm = false init(order: DeliveryOrder) { self.order = order + _route = State(initialValue: order.settlement?.route) _outcome = State(initialValue: order.outcome); _mode = State(initialValue: order.settlement?.mode ?? .none) _cash = State(initialValue: String(order.cash)); _bank = State(initialValue: String(order.bank)) _date = State(initialValue: order.settlement?.at ?? Date()); _note = State(initialValue: order.settlement?.note ?? "") @@ -248,6 +281,10 @@ struct SettlementView: View { LabeledContent("Tổng đơn", value: VND.format(order.total)) Picker("Kết quả giao", selection: $outcome) { ForEach(DeliveryOutcome.allCases, id: \.self) { Text($0.rawValue).tag($0) } }.accessibilityIdentifier("settle.outcome") Picker("Thanh toán", selection: $mode) { ForEach(PaymentMode.allCases, id: \.self) { Text($0.rawValue).tag($0) } }.accessibilityIdentifier("settle.mode") + Picker("Nhánh giao", selection: $route) { + Text("Dữ liệu cũ / chưa phân loại").tag(Optional.none) + ForEach(DeliveryRoute.allCases, id: \.self) { Text($0.rawValue).tag(Optional($0)) } + } DatePicker("Thời điểm chốt", selection: $date, in: ...Date(), displayedComponents: [.date, .hourAndMinute]) } Section("Số tiền thực tế · giá trị tổng đã ghi nhận") { @@ -257,23 +294,28 @@ struct SettlementView: View { LabeledContent(remaining < 0 ? "Ghi nhận thừa" : "Còn theo ghi nhận", value: VND.format(abs(remaining))) .foregroundStyle(remaining == 0 ? .green : .orange).accessibilityIdentifier("settle.remaining") } - Button("Thu đủ bằng tiền mặt") { cash = String(order.total); bank = "0"; mode = .cash } - Button("CK sau, chưa nhận khoản nào") { cash = "0"; bank = "0"; mode = .deferred } - Text("Sửa là thay tổng khoản đã ghi của đơn, không cộng thêm lần nữa. Đổi số liệu làm báo cáo cần gửi lại; CK cần đối soát lại. Công ký nhận được giữ nguyên.").font(.caption).foregroundStyle(.secondary) + Button("Thu đủ bằng tiền mặt") { cash = String(order.total); bank = "0"; mode = .cash; route = .cashFull } + Button("CK sau, chưa nhận khoản nào") { cash = "0"; bank = "0"; mode = .deferred; route = .transferLater } } Section("Ghi chú / lý do hoãn, thất bại") { TextField("Nội dung", text: $note, axis: .vertical).lineLimit(3...6).accessibilityIdentifier("settle.note") } Section { Button("Lưu chốt giao / tiền") { do { - let value = Settlement(outcome: outcome, mode: mode, cash: try VND.parse(cash), bank: try VND.parse(bank), note: note, at: date) - if store.change({ try $0.settle(order.id, value: value) }) { dismiss() } + let value = Settlement(outcome: outcome, mode: mode, cash: try VND.parse(cash), bank: try VND.parse(bank), note: note, at: date, route: outcome == .delivered ? route : nil) + try value.validate(total: order.total) + pending = value; confirm = true } catch { store.message = error.localizedDescription } }.accessibilityIdentifier("settle.save") - Text("Có thể lưu khi chưa đủ ảnh. Báo cáo hoàn chỉnh sẽ kiểm tra chứng từ riêng. Hủy chia sẻ không hủy số tiền đã lưu.").font(.caption).foregroundStyle(.secondary) } } .scrollDismissesKeyboard(.interactively) .navigationTitle("Chốt giao / thu tiền").navigationBarTitleDisplayMode(.inline) + .alert("Lưu điều chỉnh giao / tiền?", isPresented: $confirm) { + Button("Xác nhận lưu") { if let pending, store.change({ try $0.settle(order.id, value: pending) }) { dismiss() } } + Button("Kiểm tra lại", role: .cancel) {} + } message: { + if let pending { Text("\(pending.outcome.rawValue) · TM \(VND.format(pending.cash)) · CK \(VND.format(pending.bank)). Đây là tổng khoản đã thu của đơn, không cộng thêm lần nữa.") } + } .toolbar { CloseSheet { dismiss() } ToolbarItemGroup(placement: .keyboard) { @@ -290,71 +332,131 @@ struct SettlementView: View { struct OrderReportView: View { let id: UUID @EnvironmentObject private var store: DeliveryStore + @Environment(\.scenePhase) private var scenePhase @State private var text = "" + @State private var selectedIDs: [UUID] = [] @State private var initialized = false @State private var prepared: DeliveryReport? @State private var sharing: DeliveryShare? @State private var confirm = false @State private var copied = false @State private var preview: URL? + @State private var choosingImages = false @State private var draftSaved = false var body: some View { List { if let order = store.order(id) { - Section("Nội dung có thể sửa") { - TextEditor(text: $text).frame(minHeight: 240).accessibilityIdentifier("report.text") - Button(draftSaved ? "Đã lưu nội dung nháp" : "Lưu nội dung nháp") { - if store.change({ try $0.saveReportDraft(id, text: text) }) { draftSaved = true } - }.disabled(store.busy) - Button(copied ? "Đã sao chép" : "Sao chép nội dung") { UIPasteboard.general.string = text; copied = true } - Button("Tạo lại từ số liệu hiện tại") { text = order.reportText(); prepared = nil; copied = false } + Section("Nội dung gửi") { + TextEditor(text: $text).frame(minHeight: 85).accessibilityIdentifier("report.text") + HStack { + Button(copied ? "Đã sao chép" : "Sao chép") { UIPasteboard.general.string = text; copied = true } + Spacer() + Button("Điền lại") { text = order.shareText(); prepared = nil } + }.buttonStyle(.borderless) + Button(draftSaved ? "Đã lưu nháp" : "Lưu nháp") { + if store.change({ try $0.saveReportDraft(id, text: text, evidenceIDs: selectedIDs) }) { draftSaved = true } + } + } + ForEach(order.requiredReportRoles.filter { role in !order.activeEvidence.contains { $0.role == role } }, id: \.self) { role in + Section(role.rawValue) { EvidencePicker(title: "Bổ sung ảnh") { url in await store.attach(url, role: role, to: id) } } } - Section("Thứ tự ảnh đính kèm") { - let files = [EvidenceRole.invoice, .signature, .transfer].flatMap { role in order.activeEvidence.filter { $0.role == role } } - ForEach(Array(files.enumerated()), id: \.element.id) { index, file in - Button { preview = store.url(file) } label: { - HStack { - EvidenceThumbnail(url: store.url(file), height: 70).frame(width: 60) - Text("\(index + 1) · \(file.role.rawValue)") - Spacer(); Image(systemName: "arrow.up.left.and.arrow.down.right") + Section("Ảnh gửi · \(selectedIDs.count)") { + ForEach(selectedIDs, id: \.self) { fileID in + if let file = order.orderedEvidence.first(where: { $0.id == fileID }) { + HStack(spacing: 12) { + Button { preview = store.url(file) } label: { EvidenceThumbnail(url: store.url(file), height: 75).frame(width: 95) }.buttonStyle(.plain) + Text(file.role.rawValue).font(.subheadline) + Spacer(minLength: 0) + Button { selectedIDs.removeAll { $0 == file.id } } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary).font(.title3) } + .buttonStyle(.borderless).accessibilityLabel("Bỏ ảnh khỏi lần gửi") + .accessibilityIdentifier("report.remove.\(file.role.rawValue)") } - }.buttonStyle(.plain) + } } - if !order.missingEvidence().isEmpty { Text("Còn thiếu: " + order.missingEvidence().map(\.rawValue).joined(separator: ", ")).foregroundStyle(.orange) } - Button("Kiểm tra và chuẩn bị báo cáo") { - Task { prepared = await store.prepareReport(id, text: text) } - }.disabled(order.settlement == nil || store.busy).accessibilityIdentifier("report.prepare") + Button { choosingImages = true } label: { Label("Chọn ảnh gửi", systemImage: "plus") }.accessibilityIdentifier("report.chooseImages") + Button("Chia sẻ vào nhóm") { startShare(includeText: true) } + .buttonStyle(SweepPill(selected: true)) + .disabled(order.settlement == nil || store.busy).accessibilityIdentifier("report.share") + Button("Chỉ gửi ảnh") { startShare(includeText: false) }.disabled(selectedIDs.isEmpty || store.busy) } - if let prepared, prepared.text == text, prepared.revision == order.revision { + if let prepared, prepared.text == text, + (prepared.contentKey.map { $0 == order.reportContentKey } ?? (prepared.revision == order.revision)), + prepared.evidenceIDs == selectedIDs { Section { - Button("Chia sẻ nội dung và ảnh") { share(prepared, order: order, includeText: true) } - Button("Chỉ chia sẻ bộ ảnh") { share(prepared, order: order, includeText: false) } - Text("Sếp chọn nhóm trong Zalo rồi gửi. Nếu Zalo không nhận kèm văn bản, dùng Sao chép nội dung và chia sẻ riêng ảnh.").font(.caption).foregroundStyle(.secondary) - Button(order.reportSent ? "Đã xác nhận gửi" : "Tôi đã gửi báo cáo…") { confirm = true } + Button(order.reportSent ? "Đã xác nhận gửi" : "Đã gửi nhóm…") { confirm = true } .disabled(order.reportSent).accessibilityIdentifier("report.ack") } } } } - .navigationTitle("Báo cáo đơn").navigationBarTitleDisplayMode(.inline) + .navigationTitle("Chia sẻ đơn").navigationBarTitleDisplayMode(.inline) + .disabled(store.busy) .onAppear { guard !initialized, let order = store.order(id) else { return }; initialized = true - if let draft = order.reportDrafts.last, draft.revision == order.revision, - order.reports.last?.text != draft.text, (order.reports.last?.preparedAt ?? .distantPast) < draft.at { text = draft.text } - else if let report = order.reports.last, report.revision == order.revision { text = report.text; prepared = report } - else { text = order.reportText() } + let composition = order.reportComposition + text = composition.text; selectedIDs = composition.evidenceIDs + if let report = order.reports.last, + (report.contentKey.map { $0 == order.reportContentKey } ?? (report.revision == order.revision)), + report.text == text, report.evidenceIDs == selectedIDs { + prepared = report + } + } + .task(id: text + selectedIDs.map(\.uuidString).joined()) { + guard initialized, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + do { try await Task.sleep(for: .milliseconds(600)); try Task.checkCancellation() } catch { return } + saveDraft() } + .onDisappear { saveDraft() } + .onChange(of: scenePhase) { _, phase in if phase != .active { saveDraft() } } + .onChange(of: selectedIDs) { _, _ in draftSaved = false; saveDraft() } .onChange(of: text) { _, _ in copied = false; draftSaved = false } - .sheet(item: $sharing) { DeliveryShareSheet(items: $0.items) } + .onChange(of: store.order(id)?.shareText()) { _, caption in if let caption { text = caption; prepared = nil } } + .onChange(of: store.order(id)?.orderedEvidence.map(\.id)) { previous, ids in + let valid = Set(ids ?? []), old = Set(previous ?? []); selectedIDs.removeAll { !valid.contains($0) }; if let order = store.order(id) { for added in order.defaultShareEvidenceIDs where !old.contains(added) && !selectedIDs.contains(added) { selectedIDs.append(added) } }; prepared = nil + } + .sheet(isPresented: $choosingImages) { + NavigationStack { + List { + if let order = store.order(id) { + ForEach(order.shareableEvidence) { file in + Button { + if selectedIDs.contains(file.id) { selectedIDs.removeAll { $0 == file.id } } + else { selectedIDs.append(file.id) } + } label: { + HStack { + EvidenceThumbnail(url: store.url(file), height: 75).frame(width: 100) + Text(file.role.rawValue) + Spacer() + Image(systemName: selectedIDs.contains(file.id) ? "checkmark.circle.fill" : "circle").foregroundStyle(.green) + } + }.buttonStyle(.plain).accessibilityIdentifier("report.select.\(file.role.rawValue)") + } + } + }.navigationTitle("Chọn ảnh gửi").navigationBarTitleDisplayMode(.inline) + .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Xong") { choosingImages = false }.accessibilityIdentifier("report.imagesDone") } } + } + } + .sheet(item: $sharing, onDismiss: { confirm = true }) { DeliveryShareSheet(items: $0.items) } .quickLookPreview($preview) - .alert("Sếp đã gửi đủ nội dung và ảnh?", isPresented: $confirm) { + .alert("Đã gửi nội dung và ảnh đã chọn?", isPresented: $confirm) { Button("Đúng, đã gửi") { if let prepared { _ = store.change { try $0.acknowledgeReport(id, reportID: prepared.id) } } } Button("Chưa gửi", role: .cancel) {} - } message: { Text("Sweep ghi theo xác nhận này. Việc mở hoặc đóng bảng chia sẻ không đánh dấu đã báo cáo.") } + } + } + private func saveDraft() { + guard initialized, !store.busy, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + _ = store.change { try $0.saveReportDraft(id, text: text, evidenceIDs: selectedIDs) } } - private func share(_ report: DeliveryReport, order: DeliveryOrder, includeText: Bool) { - let urls = report.evidenceIDs.compactMap { id in order.evidence.first { $0.id == id }.map { store.url($0) } } - sharing = DeliveryShare(items: (includeText ? [report.text as Any] : []) + urls.map { $0 as Any }) + private func startShare(includeText: Bool) { + Task { + guard store.change({ try $0.saveReportDraft(id, text: text, evidenceIDs: selectedIDs) }), + let report = await store.prepareReport(id, text: text, evidenceIDs: selectedIDs), + let order = store.order(id) else { return } + prepared = report + if let urls = await store.outgoing(report, order: order) { + sharing = DeliveryShare(items: (includeText ? [report.text as Any] : []) + urls.map { $0 as Any }) + } + } } } diff --git a/Sweep/Views/OrderQRView.swift b/Sweep/Views/OrderQRView.swift new file mode 100644 index 0000000..26a0469 --- /dev/null +++ b/Sweep/Views/OrderQRView.swift @@ -0,0 +1,113 @@ +import SwiftUI +import WebKit + +struct OrderQRView: View { + private struct Request: Equatable { let id = UUID(); let url: URL } + let id: UUID + var suggested: Int64? = nil + @EnvironmentObject private var store: DeliveryStore + @State private var amount = "" + @State private var requested: Request? + @State private var requestedAmount = "" + @State private var svg: Data? + @State private var loading = false + @State private var problem = "" + private var order: DeliveryOrder? { store.order(id) } + var body: some View { + Form { + if let order { + Section { + Text(order.customer).font(.headline) + LabeledContent("Mã phiếu", value: order.code) + LabeledContent("Tổng đơn", value: VND.format(order.total)) + LabeledContent("Còn lại theo ghi nhận", value: VND.format(order.remaining)) + } + if let account = store.ledger.settings.vietQR { + Section("Tài khoản nhận") { + LabeledContent("Ngân hàng / BIN", value: account.bankID) + LabeledContent("Số tài khoản", value: account.accountNumber).textSelection(.enabled) + Text(account.accountName).font(.headline) + } + Section("Chuyển khoản cho đơn này") { + MoneyInput(title: "Số tiền QR", text: $amount, identifier: "qr.amount") + Text("Nội dung: \(VietQR.transferNote(code: order.code))").font(.subheadline) + Button("Tạo QR chuyển khoản") { generate() } + .accessibilityIdentifier("qr.generate").disabled(loading || order.voidReason != nil) + + if loading { ProgressView("Đang tạo VietQR…") } + if !problem.isEmpty { Text(problem).foregroundStyle(.orange); Button("Thử lại") { generate() }.disabled(loading) } + if let svg { + QRImage(svg: svg).frame(height: 340).background(.white).clipShape(RoundedRectangle(cornerRadius: 16)) + .accessibilityLabel("Mã QR chuyển khoản cho đơn \(order.code), \(amount) đồng") + Text("\(VND.format((try? VND.parse(amount)) ?? 0))").font(.title2.bold()).frame(maxWidth: .infinity).monospacedDigit() + } + Text("Quý khách kiểm tra số tiền trước khi chuyển khoản") + .font(.headline).foregroundStyle(Color(red: 86/255, green: 1, blue: 44/255)) + .padding().frame(maxWidth: .infinity).background(Color(red: 0.07, green: 0.2, blue: 0.15), in: RoundedRectangle(cornerRadius: 16)) + + } + } else { + Section { + Text("Điền ngân hàng, số tài khoản và chủ tài khoản một lần trước khi tạo QR theo đơn.") + NavigationLink("Thiết lập tài khoản VietQR") { DeliverySettingsView() } + } + } + } + } + .navigationTitle("QR chuyển khoản").navigationBarTitleDisplayMode(.inline) + .scrollDismissesKeyboard(.interactively) + .toolbar { + ToolbarItemGroup(placement: .keyboard) { + Spacer() + Button("Xong") { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } + } + } + .onAppear { if amount.isEmpty, let order { amount = String(suggested ?? VietQR.suggestedAmount(for: order)); generate() } } + .onChange(of: amount) { _, value in if value != requestedAmount { invalidate() } } + .onChange(of: store.ledger.settings.vietQR) { _, _ in invalidate() } + .onChange(of: order) { _, _ in invalidate() } + .task(id: requested) { + guard let request = requested else { return } + loading = true; defer { if requested == request { loading = false } } + do { + let data = try await VietQRService.svg(for: request.url) + guard !Task.isCancelled, requested == request else { return }; svg = data + } catch { + guard !Task.isCancelled, requested == request else { return } + problem = "Chưa tải được QR: " + error.localizedDescription + } + } + } + private func invalidate() { requested = nil; svg = nil; problem = ""; loading = false } + private func generate() { + invalidate() + guard let order, let account = store.ledger.settings.vietQR else { return } + do { requestedAmount = amount; requested = Request(url: try VietQR.url(account: account, order: order, amount: VND.parse(amount))) } + catch { problem = error.localizedDescription } + } +} + +/// Display SVG as an inert image in a local, script-free document. No external navigation/resources. +private struct QRImage: UIViewRepresentable { + let svg: Data + func makeUIView(context: Context) -> WKWebView { + let configuration = WKWebViewConfiguration() + configuration.websiteDataStore = .nonPersistent() + configuration.defaultWebpagePreferences.allowsContentJavaScript = false + let web = WKWebView(frame: .zero, configuration: configuration) + web.isOpaque = false; web.backgroundColor = .white + web.scrollView.isScrollEnabled = false; web.isUserInteractionEnabled = false + return web + } + func updateUIView(_ web: WKWebView, context: Context) { + guard context.coordinator.data != svg else { return }; context.coordinator.data = svg + web.loadHTMLString(""" + + + + VietQR + """, baseURL: nil) + } + func makeCoordinator() -> Coordinator { Coordinator() } + final class Coordinator { var data: Data? } +} diff --git a/Sweep/Views/OrdersView.swift b/Sweep/Views/OrdersView.swift index dc66ffa..ba138fb 100644 --- a/Sweep/Views/OrdersView.swift +++ b/Sweep/Views/OrdersView.swift @@ -4,6 +4,12 @@ import QuickLook struct OrdersView: View { @EnvironmentObject private var store: DeliveryStore + @EnvironmentObject private var router: SweepRouter + @Environment(\.scenePhase) private var scenePhase + @StateObject private var inbox = SharedInboxStore() + @State private var sharedInbox = false + @State private var refreshingInbox = false + @State private var inboxRefreshRequested = false @State private var path: [UUID] = [] @State private var query = "" @State private var filter = "Tất cả" @@ -16,23 +22,38 @@ struct OrdersView: View { store.ledger.orders.filter { order in let matches = query.isEmpty || (order.customer + " " + order.code + " " + order.phone).localizedStandardContains(query) let dateOK = allDates || Calendar.current.isDate(order.importedAt, inSameDayAs: day) - let statusOK = filter == "Tất cả" || (filter == "Đang giao" && order.outcome != .delivered && order.voidReason == nil) || (filter == "Cần báo cáo" && order.reportNeeded) + let statusOK = filter == "Tất cả" || (filter == "Đang giao" && order.outcome != .delivered && order.voidReason == nil) || (filter == "Đã giao" && order.outcome == .delivered && order.voidReason == nil) return matches && dateOK && statusOK }.sorted { $0.importedAt > $1.importedAt } } var body: some View { NavigationStack(path: $path) { List { + if !inbox.items.isEmpty { + Section { + Button { sharedInbox = true } label: { Label("\(inbox.items.count) ảnh được chia sẻ · nhận đơn", systemImage: "tray.and.arrow.down.fill") }.accessibilityIdentifier("orders.shared") + } + } Section { - Picker("Bộ lọc", selection: $filter) { ForEach(["Tất cả", "Đang giao", "Cần báo cáo"], id: \.self) { Text($0).tag($0) } }.pickerStyle(.segmented) - Toggle("Mọi ngày", isOn: $allDates) - if !allDates { DatePicker("Ngày nhập vào Sweep", selection: $day, displayedComponents: .date) } + HStack(spacing: 6) { + ForEach(["Tất cả", "Đang giao", "Đã giao"], id: \.self) { value in + Button { filter = value } label: { + HStack(spacing: 4) { + Text(value).font(.subheadline.weight(.semibold)).lineLimit(1).minimumScaleFactor(0.7) + if value == "Đang giao", store.ledger.orders.contains(where: { $0.outcome != .delivered && $0.voidReason == nil }) { Circle().fill(SweepStyle.green).frame(width: 5, height: 5) } + } + }.buttonStyle(SweepPill(selected: filter == value)).accessibilityIdentifier("filter.\(value)") + } + Menu { Toggle("Mọi ngày", isOn: $allDates) } label: { Image(systemName: "ellipsis").rotationEffect(.degrees(90)).frame(width: 24, height: 44) }.accessibilityLabel("Tuỳ chọn ngày") + }.listRowBackground(Color.clear) + if !allDates { DatePicker("Ngày nhập", selection: $day, displayedComponents: .date) } + } if store.blocked { Text("Sổ chưa mở được. Dữ liệu cũ được giữ nguyên; xem thông báo lỗi.").foregroundStyle(.red) } else if visible.isEmpty { VStack(spacing: 16) { Label(query.isEmpty ? "Chưa có đơn đã lưu" : "Không tìm thấy đơn", systemImage: "shippingbox").font(.headline) - Text("Chọn thư mục → mở hồ sơ → kiểm tra → Nhập đơn vào Sweep.").font(.subheadline).foregroundStyle(.secondary).multilineTextAlignment(.center) + Button("Chọn ảnh đơn hàng") { newOrder = true }.buttonStyle(.borderedProminent) Button("Nhập đơn từ Bill") { bill = true }.buttonStyle(.borderedProminent) }.frame(maxWidth: .infinity).padding(.vertical, 28) } @@ -42,13 +63,13 @@ struct OrdersView: View { HStack { Text(order.customer).font(.headline); Spacer(); Text(VND.format(order.total)).font(.subheadline.bold()).monospacedDigit() } Text(order.code).font(.caption).foregroundStyle(.secondary) HStack { - Text(order.voidReason != nil ? "Đã hủy" : order.outcome.rawValue) + Text(order.workflowStatus) Spacer() if !order.activeAssignments.isEmpty { Label("Đã tính công", systemImage: "checkmark.seal.fill").foregroundStyle(.green) } else { Text("Chưa tính công").foregroundStyle(.secondary) } }.font(.caption) - if order.remaining > 0 { Text("Còn \(VND.format(order.remaining)) theo ghi nhận").font(.caption).foregroundStyle(.orange) } - if order.bank > order.verifiedBank { Text("CK chờ đối soát: \(VND.format(order.bank - order.verifiedBank))").font(.caption).foregroundStyle(.secondary) } + if order.remaining > 0 && !order.taskComplete { Text("Chưa thu \(VND.format(order.remaining))").font(.caption).foregroundStyle(.orange) } + if !order.reviewNote.isEmpty { Label("Cần rà soát dữ liệu cũ", systemImage: "exclamationmark.circle").font(.caption).foregroundStyle(.orange) } }.padding(.vertical, 6) }.accessibilityIdentifier("order.\(order.code)") @@ -57,14 +78,43 @@ struct OrdersView: View { .navigationTitle("Đơn hàng") .searchable(text: $query, prompt: "Tên khách, mã phiếu, số điện thoại") .toolbar { - ToolbarItem(placement: .topBarLeading) { Button { bill = true } label: { Label("Nhập Bill", systemImage: "tray.and.arrow.down") }.accessibilityIdentifier("orders.bill").disabled(store.busy || store.blocked) } + ToolbarItem(placement: .topBarLeading) { + Menu { + Button("Ảnh được chia sẻ", systemImage: "tray.and.arrow.down") { sharedInbox = true } + Button("Nhập từ kho Bill", systemImage: "folder") { bill = true }.accessibilityIdentifier("orders.bill") + } label: { Label("Nhận ảnh", systemImage: "tray.and.arrow.down") }.accessibilityIdentifier("orders.receive").disabled(store.busy || store.blocked) + } ToolbarItem(placement: .topBarTrailing) { Button { newOrder = true } label: { Label("Nhận đơn", systemImage: "plus") }.accessibilityIdentifier("orders.new").disabled(store.busy || store.blocked) } } .navigationDestination(for: UUID.self) { OrderDetailView(id: $0) } .sheet(isPresented: $newOrder, onDismiss: openSavedOrder) { OrderIntakeView { id in savedOrder = id; newOrder = false } } .sheet(isPresented: $bill, onDismiss: openSavedOrder) { BillInboxView { id in savedOrder = id; bill = false } } + .sheet(isPresented: $sharedInbox, onDismiss: openSavedOrder) { SharedInboxView(inbox: inbox) { id in savedOrder = id; sharedInbox = false } } + .task { + await refreshInbox() + if let id = router.orderID, store.order(id) != nil { path = [id]; router.orderID = nil } + } + .onReceive(NotificationCenter.default.publisher(for: .sweepInboxReceived)) { _ in Task { await refreshInbox() } } + .onChange(of: router.orderID) { _, id in + if let id, store.order(id) != nil { path = [id]; router.orderID = nil } + } + .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await refreshInbox() } } } } } + private func refreshInbox() async { + guard !refreshingInbox else { inboxRefreshRequested = true; return } + refreshingInbox = true; defer { refreshingInbox = false } + repeat { + inboxRefreshRequested = false + #if DEBUG + if ProcessInfo.processInfo.arguments.contains("--shared-ui-testing") { + do { try await store.installSharedUITestFixture() } catch { store.message = error.localizedDescription } + } + #endif + await inbox.reload() + if !inbox.items.isEmpty, !newOrder, !bill, !sharedInbox, !store.busy, !store.blocked { sharedInbox = true } + } while inboxRefreshRequested + } private func openSavedOrder() { guard let id = savedOrder else { return } savedOrder = nil; query = ""; filter = "Tất cả"; allDates = true @@ -74,6 +124,7 @@ struct OrdersView: View { struct OrderIntakeView: View { var candidate: BillCandidate? = nil + var shared: SharedInvoiceInbox.Item? = nil let saved: (UUID) -> Void @EnvironmentObject private var store: DeliveryStore @Environment(\.dismiss) private var dismiss @@ -88,78 +139,97 @@ struct OrderIntakeView: View { @State private var readingRequest = UUID() @State private var readingStatus = "" @State private var validation = "" + @State private var duplicateID: UUID? @State private var hasInvoiceDate = false @State private var invoiceDate = Date() + @State private var askSigned = false + @State private var signatureOffered = false @State private var signed = false + @State private var salesperson = "" @State private var signedAt = Date() @State private var allowRepeatedImage = false @State private var image: ImportedImage? @State private var preview: URL? - private var source: URL? { image?.url ?? candidate?.image } + private var source: URL? { image?.url ?? shared?.image ?? candidate?.image } var body: some View { NavigationStack { Form { Section("Phiếu nội bộ có tiền") { if let source { Button { preview = source } label: { EvidenceThumbnail(url: source, height: 220) }.buttonStyle(.plain) } - EvidencePicker(title: "Chọn hoặc chụp phiếu") { url in + EvidencePicker(title: "Ảnh phiếu") { url in do { image = try await Task.detached { try ImportedImage.copy(from: url) }.value } catch { store.message = error.localizedDescription } } - Text("Ảnh chưa được nhập vào sổ. Kiểm tra bên dưới rồi bấm Nhập đơn vào Sweep.").font(.caption).foregroundStyle(.secondary) if reading { ProgressView("Đang đọc thông tin trên phiếu…") } if !readingStatus.isEmpty { Text(readingStatus).font(.caption).foregroundStyle(.secondary) } if let source { Button("Đọc lại thông tin còn thiếu từ ảnh") { Task { await readInvoice(source) } }.disabled(reading) } } Section("Hồ sơ") { - TextField("Mã cạnh “Số:” trên phiếu (bắt buộc)", text: $code).textInputAutocapitalization(.characters).accessibilityIdentifier("intake.code") - TextField("Tên tiệm tại “Đơn vị:”", text: $customer).accessibilityIdentifier("intake.customer") + TextField("Mã phiếu", text: $code).textInputAutocapitalization(.characters).accessibilityIdentifier("intake.code") + TextField("Tên khách hàng", text: $customer).accessibilityIdentifier("intake.customer") MoneyInput(title: "Tổng đơn", text: $total, identifier: "intake.total") - TextField("Điện thoại trên phiếu (tùy chọn)", text: $phone).keyboardType(.phonePad) - if !phone.isEmpty { Text("Số in cạnh NV bán hàng có thể là nhân viên bán hàng. Xác minh trước khi gọi khách.").font(.caption).foregroundStyle(.orange) } - TextField("Địa chỉ (tùy chọn)", text: $address) + TextField("Số điện thoại khách", text: $phone).keyboardType(.phonePad) + TextField("Địa chỉ giao hàng", text: $address) TextField("Ghi chú giao hàng / giờ hẹn", text: $deliveryNote) - Text("Mã phiếu, tên tiệm và tổng tiền là bắt buộc. OCR là gợi ý; đối chiếu ảnh trước khi nhập.").font(.caption).foregroundStyle(.secondary) Toggle("Có ngày trên hóa đơn", isOn: $hasInvoiceDate) if hasInvoiceDate { DatePicker("Ngày hóa đơn", selection: $invoiceDate, displayedComponents: .date) } } - Section("Công đi giao") { - Toggle("Đã ký nhận phiếu để đi giao", isOn: $signed).accessibilityIdentifier("intake.signed") + Section("Ký nhận") { + if signed { + Label("Đã ký nhận phiếu", systemImage: "checkmark.seal.fill").foregroundStyle(SweepStyle.green).accessibilityIdentifier("intake.signed") + } else { + Button("Xác nhận đơn đã ký chưa") { askSigned = true }.accessibilityIdentifier("intake.confirmSignature") + } if signed { DatePicker("Ngày ký nhận", selection: $signedAt, in: ...Date(), displayedComponents: [.date, .hourAndMinute]) } - Text("Xác nhận chữ ký của Sếp khi nhận việc, khác chữ ký khách nhận hàng. Mức hiện tại \(VND.format(store.ledger.settings.fee))/phiếu. Chưa ký thì lưu nháp, chưa tính công.") - .font(.caption).foregroundStyle(.secondary) + LabeledContent("Công mỗi phiếu", value: VND.format(store.ledger.settings.fee)) Toggle("Đây là phiếu khác hợp lệ dù dùng lại ảnh", isOn: $allowRepeatedImage).font(.caption) } if let candidate { Section("Xem trước dữ liệu Bill") { - Text("Gói \(candidate.id.dropFirst(5).prefix(12)) · \(candidate.isLegacy ? "sổ cũ" : "sen-bill-v1")") if let date = candidate.createdAt { LabeledContent("Ngày lưu bên Bill", value: date.formatted(date: .numeric, time: .shortened)) } LabeledContent("Tiền mặt giữ lại", value: VND.format(candidate.cash)) LabeledContent("CK khách báo giữ lại", value: VND.format(candidate.bank)) Text(candidate.note.isEmpty ? "Gói nhập không xác nhận ngày ký. Sếp kiểm tra trước khi tính công." : candidate.note).font(.caption).foregroundStyle(.secondary) } } - if !validation.isEmpty { Section { Text(validation).foregroundStyle(.red) } } + if !validation.isEmpty { + Section { + Text(validation).foregroundStyle(.red) + if let duplicateID { Button("Đây là đơn đã có: bỏ ảnh chờ và mở hồ sơ") { saved(duplicateID) } } + } + } } .navigationTitle("Nhận đơn").navigationBarTitleDisplayMode(.inline) .toolbar { CloseSheet { dismiss() } } .quickLookPreview($preview) .onAppear { guard !initialized else { return }; initialized = true + if let at = shared?.signedAt { signed = true; signedAt = at } if let candidate { customer = candidate.customer; total = String(candidate.total); code = candidate.code phone = candidate.phone; address = candidate.address; deliveryNote = candidate.deliveryNote if let date = candidate.invoiceDate { invoiceDate = date; hasInvoiceDate = true } } } + .background(SweepAppearanceAction { + guard !signatureOffered else { return }; signatureOffered = true + if !signed, shared?.signedAt == nil { askSigned = true } + }.frame(width: 0, height: 0)) + .alert("Đơn này bạn đã ký chưa?", isPresented: $askSigned) { + Button("Đã ký") { signed = true } + Button("Bỏ qua", role: .cancel) { dismiss() } + } .task(id: source) { if let source { await readInvoice(source) } } .scrollDismissesKeyboard(.interactively) .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer(); Button("Xong") { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }.accessibilityIdentifier("keyboard.done") } } .safeAreaInset(edge: .bottom) { VStack(spacing: 6) { - if !validation.isEmpty { Text(validation).font(.caption).foregroundStyle(.red) } + if !signed { + Button("Xác nhận ký nhận phiếu") { askSigned = true }.buttonStyle(SweepCompactPill()) + } Button(signed ? "Nhập đơn và ghi công ký nhận" : "Nhập đơn vào Sweep") { Task { await save() } } .buttonStyle(.borderedProminent).frame(maxWidth: .infinity).controlSize(.large) - .accessibilityIdentifier("intake.save").disabled(store.busy || reading) + .accessibilityIdentifier("intake.save").disabled(store.busy || reading || !signed || source == nil) }.padding().frame(maxWidth: .infinity).background(.bar) } .disabled(store.busy) @@ -169,8 +239,10 @@ struct OrderIntakeView: View { let request = UUID(); readingRequest = request; reading = true defer { if readingRequest == request { reading = false } } do { + if let shared, image == nil { try await Task.detached { try EvidenceFiles.verify(shared.evidence, directory: shared.directory) }.value } let fields = try await Task.detached(priority: .userInitiated) { try InvoiceOCR.read(url) }.value guard !Task.isCancelled, source == url, readingRequest == request else { return } + if salesperson.isEmpty { salesperson = fields.salesperson } if code.isEmpty { code = fields.code } if customer.isEmpty { customer = fields.customer } if total.isEmpty || (candidate == nil && total == "0") { if let value = fields.total { total = String(value) } } @@ -182,20 +254,29 @@ struct OrderIntakeView: View { if code.isEmpty { missing.append("mã cạnh Số:") } if customer.isEmpty { missing.append("tên tại Đơn vị:") } if total.isEmpty { missing.append("tổng tiền") } - readingStatus = missing.isEmpty ? "Đã điền gợi ý. Kiểm tra với ảnh, rồi bấm Nhập đơn vào Sweep." : "Chưa đọc rõ " + missing.joined(separator: ", ") + ". Sếp điền tay phần còn thiếu." - if let value = fields.total, let current = try? VND.parse(total), current != value { readingStatus += " Tổng OCR khác dữ liệu Bill; em giữ tiền Bill để Sếp đối chiếu." } + readingStatus = missing.isEmpty ? "" : "Chưa đọc rõ " + missing.joined(separator: ", ") + "." + if let value = fields.total, let current = try? VND.parse(total), current != value { readingStatus += " Tổng OCR khác số tiền đang điền; em giữ số tiền hiện tại để Sếp đối chiếu." } } catch { readingStatus = "Chưa đọc được ảnh: " + error.localizedDescription + " Sếp có thể điền tay." } } private func save() async { - validation = "" + validation = ""; duplicateID = nil + guard signed, source != nil else { validation = "Chọn ảnh và xác nhận đã ký nhận."; return } guard !code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, !customer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { validation = "Điền mã cạnh Số: và tên tại Đơn vị: trước khi nhập."; return } do { var order = DeliveryOrder(code: code.trimmingCharacters(in: .whitespacesAndNewlines), customer: customer.trimmingCharacters(in: .whitespacesAndNewlines), total: try VND.parse(total)) - order.phone = phone; order.address = address; order.invoiceAt = hasInvoiceDate ? invoiceDate : nil - order.note = [deliveryNote.isEmpty ? "" : "Giao hàng: \(deliveryNote)", phone.isEmpty ? "" : "Điện thoại trên phiếu cần xác minh người nhận: \(phone)"].filter { !$0.isEmpty }.joined(separator: "\n") + if let shared { + if let old = store.ledger.orders.first(where: { $0.sourceID == shared.sourceID }) { saved(old.id); return } + if let old = store.ledger.orders.first(where: { DeliveryOrder.normalizedCode($0.code) == DeliveryOrder.normalizedCode(order.code) }) { + duplicateID = old.id; validation = "Mã \(old.code) đã có: \(old.customer), \(VND.format(old.total)). Ảnh chờ vẫn được giữ. Kiểm tra lại mã hoặc xác nhận đây là đơn cũ."; return + } + try await Task.detached { try EvidenceFiles.verify(shared.evidence, directory: shared.directory) }.value + order.sourceID = shared.sourceID; order.sourceCreatedAt = shared.receivedAt + } + order.salesperson = salesperson; order.phone = phone; order.address = address; order.invoiceAt = hasInvoiceDate ? invoiceDate : nil + order.note = InvoiceParser.cleanStoredNote(deliveryNote) if let candidate { guard order.total >= candidate.cash + candidate.bank else { throw DeliveryError.invalid("Tổng sửa thấp hơn khoản thu cũ. Kiểm tra sổ trước khi nhập.") } order.sourceID = candidate.id; order.sourceCreatedAt = candidate.createdAt; order.sourceSnapshot = candidate.sourceSnapshot diff --git a/Sweep/Views/PayrollView.swift b/Sweep/Views/PayrollView.swift new file mode 100644 index 0000000..cae61b8 --- /dev/null +++ b/Sweep/Views/PayrollView.swift @@ -0,0 +1,318 @@ +import SwiftUI + +private struct AttendanceDay: Identifiable { let date: Date; var id: Date { date } } + +struct PayrollView: View { + @EnvironmentObject private var store: DeliveryStore + @State private var month = DeliveryMonth.start(Date()) + @State private var day: AttendanceDay? + @State private var configure = false + @State private var advance = false + @State private var confirmClose = false + @State private var reopen = false + @State private var reason = "" + @State private var sharing: DeliveryShare? + private var book: PayrollBook { store.ledger.payroll ?? PayrollBook() } + private var period: PayrollMonth { book.period(month) } + private var closed: PayrollSnapshot? { book.closed(month) } + private var result: PayrollCalculation { closed?.calculation ?? PayrollCalculation(ledger: store.ledger, period: period) } + private var year: Int { PayrollDates.calendar.component(.year, from: month) } + var body: some View { + List { + monthSummarySection + attendanceSection + annualLeaveSection + salaryBreakdownSection + advancesSection + payrollActionsSection + payrollHelpSection + }.navigationTitle("Chấm công & lương").navigationBarTitleDisplayMode(.inline) + .toolbar { ToolbarItem(placement: .topBarTrailing) { Button { configure = true } label: { Image(systemName: "slider.horizontal.3") }.disabled(closed != nil).accessibilityLabel("Cấu hình lương") } } + .sheet(item: $day) { item in + NavigationStack { AttendanceEditor(day: item.date, existing: period.entry(item.date), suggested: hasAssignment(item.date)) } + } + .sheet(isPresented: $configure) { + NavigationStack { + PayrollConfigurationView(period: period, opening: book.openingLeaveUnits[String(year)] ?? 0) { value, opening in + store.change { ledger in + try ledger.changePayroll("Cấu hình lương " + value.id) { book in + try book.put(value); book.openingLeaveUnits[String(year)] = opening + } + } + } + } + } + .sheet(isPresented: $advance) { NavigationStack { SalaryAdvanceEditor(month: month) } } + .sheet(item: $sharing) { DeliveryShareSheet(items: $0.items) } + .alert("Chốt lương tháng này?", isPresented: $confirmClose) { + Button("Chốt và giữ bản tính") { _ = store.change { try $0.closePayroll(month) } } + Button("Hủy", role: .cancel) {} + } message: { Text("Chỉ chốt từ ngày cuối tháng, khi đã đủ công và có giá xăng đúng ngày. Bản tính sẽ được giữ nguyên sau khi khóa.") } + .alert("Lý do mở khóa", isPresented: $reopen) { + TextField("Lý do điều chỉnh", text: $reason) + Button("Mở khóa") { _ = store.change { try $0.reopenPayroll(month, reason: reason) } } + Button("Hủy", role: .cancel) {} + } message: { Text("Bản lương đã chốt vẫn lưu trong lịch sử; Sếp điều chỉnh rồi chốt thành bản mới.") } + } + private var monthSummarySection: some View { + Section { + HStack { + Button { move(-1) } label: { Image(systemName: "chevron.left").frame(width: 44, height: 44) }.buttonStyle(.borderless) + Spacer() + Text(verbatim: "Tháng \(PayrollDates.calendar.component(.month, from: month)) / \(year)").font(.headline) + Spacer() + Button { move(1) } label: { Image(systemName: "chevron.right").frame(width: 44, height: 44) }.buttonStyle(.borderless) + } + Label(closed == nil ? "Lương tạm tính" : "Bảng lương đã chốt", systemImage: closed == nil ? "clock" : "lock.fill") + .font(.caption).foregroundStyle(closed == nil ? Color.secondary : Color.green) + Text(period.policy.confirmed ? VND.format(result.net) : "Chưa cấu hình lương").font(.system(period.policy.confirmed ? .largeTitle : .title2, design: .rounded, weight: .bold)).monospacedDigit() + .accessibilityIdentifier("payroll.net") + HStack { + summary("Công", units: result.workUnits) + Spacer() + summary("Nghỉ", units: result.leaveUnits) + Spacer() + VStack { Text("\(result.commissions)").font(.headline); Text("Đơn").font(.caption).foregroundStyle(.secondary) } + } + if !period.policy.confirmed { Label("Chọn lịch làm việc và xác nhận mức lương trước khi chốt.", systemImage: "exclamationmark.circle").font(.footnote).foregroundStyle(.orange) } + if result.missingDays > 0 { Text("\(result.missingDays) ngày làm việc chưa chấm; ngày trống không tự coi là nghỉ.").font(.footnote).foregroundStyle(.secondary) } + } + } + + private var attendanceSection: some View { + Section("Chấm công") { calendar } + } + + private var annualLeaveSection: some View { + Section("Phép năm " + String(year)) { + LabeledContent("Đã nghỉ / hạn mức", value: "\(units(book.annualLeaveUnits(year: year))) / 12 ngày") + let remaining = 24 - book.annualLeaveUnits(year: year) + Text(remaining < 0 ? "Vượt \(units(-remaining)) ngày. Vẫn giữ toàn bộ ngày nghỉ để đối chiếu." : "Còn \(units(remaining)) ngày phép không lương.") + .font(.footnote).foregroundStyle(remaining < 0 ? Color.red : Color.secondary) + Text("Nghỉ quá 3 ngày/tháng mất chuyên cần. Đúng 3 ngày vẫn giữ.").font(.footnote).foregroundStyle(.secondary) + } + } + + private var salaryBreakdownSection: some View { + Section("Các khoản tháng này") { + ForEach(result.rows, id: \.0) { label, value in + LabeledContent(label, value: !period.policy.confirmed ? "Chưa cấu hình" : label == "Xăng xe" && !result.fuelConfirmed ? "Chờ chốt giá" : VND.format(value)) + } + LabeledContent("Công chuẩn", value: units(result.plannedUnits) + " ngày") + LabeledContent("Chốt lương", value: PayrollDates.closeDay(month).formatted(date: .numeric, time: .omitted)) + LabeledContent("Ngày chốt giá xăng", value: PayrollDates.fuelDay(month).formatted(date: .numeric, time: .omitted)) + if let fuel = period.fuel { + Text("\(fuel.price)₫/lít · \(fuel.source)").font(.footnote).foregroundStyle(.secondary) + } else { + Text("Giá ngày 30 áp dụng cho cả tháng; tháng 2 dùng ngày cuối tháng. Không có giá đúng thì để chờ chốt.").font(.footnote).foregroundStyle(.orange) + } + } + } + + private var advancesSection: some View { + Section("Tạm ứng") { + ForEach(period.advances) { item in + VStack(alignment: .leading) { + LabeledContent(item.day.formatted(date: .numeric, time: .omitted), value: VND.format(item.amount)) + if !item.note.isEmpty { Text(item.note).font(.caption).foregroundStyle(.secondary) } + } + } + if closed == nil { Button("Thêm khoản tạm ứng", systemImage: "plus.circle") { advance = true } } + } + } + + private var payrollActionsSection: some View { + Section { + if closed == nil { + Button("Cấu hình lương và giá xăng", systemImage: "slider.horizontal.3") { configure = true }.accessibilityIdentifier("payroll.configure") + Button("Chốt bảng lương tháng", systemImage: "lock") { confirmClose = true }.disabled(store.busy || store.blocked) + .accessibilityIdentifier("payroll.close") + } else { + Button("Mở khóa để điều chỉnh", systemImage: "lock.open") { reason = ""; reopen = true } + } + Button("Xuất bảng lương CSV", systemImage: "square.and.arrow.up") { exportCSV() } + } + } + + private var payrollHelpSection: some View { + Section { + Text("Chấm công thủ công; đơn đã ký chỉ gợi ý ngày đi làm. Tiền thu hộ không cộng vào lương. Mức tiền và lịch làm việc áp dụng theo cấu hình tháng.").font(.footnote).foregroundStyle(.secondary) + } + } + + private var calendar: some View { + let days = PayrollDates.days(month) + let assignments = signedDays + let offset = (PayrollDates.calendar.component(.weekday, from: days[0]) + 5) % 7 + return LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 7), spacing: 8) { + ForEach(["T2", "T3", "T4", "T5", "T6", "T7", "CN"], id: \.self) { Text($0).font(.caption2).foregroundStyle(.secondary) } + ForEach(0..<(offset + days.count), id: \.self) { index in + if index < offset { Color.clear.frame(height: 44) } + else { + let date = days[index - offset], value = period.entry(date)?.state + Button { day = AttendanceDay(date: date) } label: { + VStack(spacing: 2) { + Text("\(PayrollDates.calendar.component(.day, from: date))").font(.subheadline.weight(.medium)) + Text(value == .work ? "✓" : value == .half ? "½" : value == .leave ? "N" : value == .off ? "—" : assignments.contains(date) ? "•" : " ").font(.caption) + }.frame(maxWidth: .infinity, minHeight: 48) + .background(value == .work ? SweepStyle.green.opacity(0.2) : value == .leave ? Color.red.opacity(0.1) : Color(uiColor: .tertiarySystemFill), in: RoundedRectangle(cornerRadius: 10)) + }.buttonStyle(.plain) + .disabled(closed != nil || date > PayrollDates.calendar.startOfDay(for: Date()) || store.busy || store.blocked) + .accessibilityLabel("\(date.formatted(date: .complete, time: .omitted)), \(value?.rawValue ?? "Chưa chấm")") + .accessibilityIdentifier("attendance.day.\(PayrollDates.calendar.component(.day, from: date))") + } + } + }.padding(.vertical, 8) + } + private func summary(_ title: String, units value: Int) -> some View { VStack { Text(units(value)).font(.headline); Text(title).font(.caption).foregroundStyle(.secondary) } } + private func units(_ n: Int) -> String { n % 2 == 0 ? String(n / 2) : String(format: "%.1f", Double(n) / 2) } + private func move(_ step: Int) { month = PayrollDates.calendar.date(byAdding: .month, value: step, to: month)! } + private var signedDays: Set { Set(store.ledger.commissions(in: month, calendar: PayrollDates.calendar).map { PayrollDates.calendar.startOfDay(for: $0.1.signedAt) }) } + private func hasAssignment(_ day: Date) -> Bool { signedDays.contains(PayrollDates.calendar.startOfDay(for: day)) } + private func exportCSV() { + func escape(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" } + var csv = "\u{FEFF}Khoản,Số tiền (VND)\n" + csv += result.rows.map { escape($0.0) + "," + (!period.policy.confirmed ? "Chưa cấu hình" : $0.0 == "Xăng xe" && !result.fuelConfirmed ? "Chờ chốt giá" : String($0.1)) }.joined(separator: "\n") + csv += "\nTrạng thái," + (closed == nil ? "Tạm tính" : "Đã chốt") + "\nNgày,Công\n" + csv += period.entries.sorted { $0.day < $1.day }.map { escape($0.day.formatted(date: .numeric, time: .omitted)) + "," + escape($0.state.rawValue) }.joined(separator: "\n") + let url = FileManager.default.temporaryDirectory.appendingPathComponent("Sweep-luong-\(period.id).csv") + do { try csv.write(to: url, atomically: true, encoding: .utf8); sharing = DeliveryShare(items: [url]) } catch { store.message = error.localizedDescription } + } +} + +private struct AttendanceEditor: View { + let day: Date + let existing: AttendanceEntry? + let suggested: Bool + @EnvironmentObject private var store: DeliveryStore + @Environment(\.dismiss) private var dismiss + @State private var state = AttendanceState.work + @State private var note = "" + var body: some View { + Form { + Section { + Text(day.formatted(date: .complete, time: .omitted)) + Picker("Trạng thái", selection: $state) { ForEach(AttendanceState.allCases, id: \.self) { Text($0.rawValue).tag($0) } } + TextField("Ghi chú", text: $note) + if suggested { Text("Ngày này có đơn đã ký. Sếp xác nhận công thực tế.").font(.footnote).foregroundStyle(.secondary) } + Text("Nửa công tính 0,5 công và 0,5 ngày phép không lương; trợ cấp ngày hưởng một nửa.").font(.footnote).foregroundStyle(.secondary) + } + Button("Lưu công") { if store.change({ try $0.markAttendance(day, state: state, note: note) }) { dismiss() } } + .accessibilityIdentifier("attendance.save") + if existing != nil { Button("Bỏ chấm ngày này", role: .destructive) { if store.change({ try $0.markAttendance(day, state: nil) }) { dismiss() } } } + }.navigationTitle("Chấm công").navigationBarTitleDisplayMode(.inline) + .toolbar { CloseSheet { dismiss() } } + .onAppear { state = existing?.state ?? .work; note = existing?.note ?? "" } + } +} + +private struct PayrollConfigurationView: View { + @Environment(\.dismiss) private var dismiss + @State var period: PayrollMonth + let opening: Int + let save: (PayrollMonth, Int) -> Bool + @State private var base = "" + @State private var phone = "" + @State private var meal = "" + @State private var maintenance = "" + @State private var attendance = "" + @State private var insurance = "" + @State private var fuel = "" + @State private var source = "" + @State private var leave = "" + @State private var adjustment = "" + @State private var error = "" + @State private var initialized = false + var body: some View { + Form { + Section("Lịch làm việc chuẩn") { + ForEach(1...7, id: \.self) { weekday in + Toggle(weekday == 1 ? "Chủ nhật" : "Thứ \(weekday)", isOn: Binding(get: { period.policy.weekdays.contains(weekday) }, set: { yes in + period.policy.weekdays.removeAll { $0 == weekday }; if yes { period.policy.weekdays.append(weekday) } + })) + } + Text("Ngày nghỉ theo lịch có thể chỉnh trên lịch chấm công; không trừ phép năm.").font(.footnote).foregroundStyle(.secondary) + } + Section("Mức tháng và trợ cấp ngày") { + MoneyInput(title: "Lương cơ bản tháng", text: $base) + MoneyInput(title: "Điện thoại tháng", text: $phone) + MoneyInput(title: "Ăn / ngày", text: $meal) + MoneyInput(title: "Bảo trì / ngày", text: $maintenance) + MoneyInput(title: "Chuyên cần tháng", text: $attendance) + MoneyInput(title: "Bảo hiểm tháng", text: $insurance) + Stepper("\(period.policy.fuelLitres) lít xăng / ngày", value: $period.policy.fuelLitres, in: 0...20) + Text("Lương cơ bản và điện thoại phân bổ theo công thực làm / công chuẩn. Nghỉ quá 3 ngày mất chuyên cần; bảo hiểm giữ mức tháng đã nhập.").font(.footnote).foregroundStyle(.secondary) + Toggle("Đã kiểm tra lịch và mức tiền", isOn: $period.policy.confirmed) + } + Section("Giá xăng chốt của tháng") { + TextField("Loại xăng công ty dùng", text: $period.policy.fuelType) + TextField("Vùng giá", text: $period.policy.fuelRegion) + Text("Ngày giá áp dụng: " + PayrollDates.fuelDay(period.month).formatted(date: .numeric, time: .omitted)) + MoneyInput(title: "Giá xăng / lít", text: $fuel) + TextField("Nguồn giá / ghi nhận công ty", text: $source) + Link("Đối chiếu Petrolimex", destination: URL(string: "https://www.petrolimex.com.vn/")!) + Text("Nhập đúng giá có hiệu lực ngày chốt, không lấy giá hôm nay thay tháng cũ. Tự động lấy giá chưa được bật.").font(.footnote).foregroundStyle(.secondary) + } + Section("Phép năm và điều chỉnh") { + TextField("Phép đã dùng trước dữ liệu công trong Sweep", text: $leave).keyboardType(.decimalPad) + Text("Số ngày nghỉ không lương đã dùng trong năm ngoài các ngày đã chấm trong Sweep. Hạn mức 12 ngày.").font(.footnote).foregroundStyle(.secondary) + TextField("Điều chỉnh lương, số âm để trừ", text: $adjustment).keyboardType(.numbersAndPunctuation) + TextField("Lý do điều chỉnh", text: $period.adjustmentReason) + } + if !error.isEmpty { Text(error).foregroundStyle(.red) } + Button("Lưu cấu hình") { persist() }.accessibilityIdentifier("payroll.saveConfiguration") + }.navigationTitle("Cấu hình lương").navigationBarTitleDisplayMode(.inline) + .toolbar { CloseSheet { dismiss() } } + .onAppear { + guard !initialized else { return }; initialized = true + let p = period.policy + base = String(p.base); phone = String(p.phone); meal = String(p.meal); maintenance = String(p.maintenance) + attendance = String(p.attendance); insurance = String(p.insurance) + fuel = period.fuel.map { String($0.price) } ?? ""; source = period.fuel?.source ?? "" + leave = String(Double(opening) / 2); adjustment = String(period.adjustment) + } + } + private func persist() { + do { + var value = period + value.policy.base = try VND.parse(base); value.policy.phone = try VND.parse(phone) + value.policy.meal = try VND.parse(meal); value.policy.maintenance = try VND.parse(maintenance) + value.policy.attendance = try VND.parse(attendance); value.policy.insurance = try VND.parse(insurance) + guard let opening = Double(leave.replacingOccurrences(of: ",", with: ".")), opening.isFinite, opening >= 0, opening <= 366, (opening * 2).rounded() == opening * 2 else { throw DeliveryError.invalid("Phép đầu kỳ phải là số ngày hoặc nửa ngày hợp lệ.") } + guard let delta = Int64(adjustment.trimmingCharacters(in: .whitespaces)) else { throw DeliveryError.invalid("Điều chỉnh phải là số nguyên đồng, có thể thêm dấu trừ.") } + value.adjustment = delta + if !fuel.trimmingCharacters(in: .whitespaces).isEmpty { + guard PayrollDates.calendar.startOfDay(for: Date()) >= PayrollDates.fuelDay(period.month) else { throw DeliveryError.invalid("Chưa đến ngày chốt giá xăng của tháng. Để trống giá để lưu cấu hình trước.") } + value.fuel = PayrollFuel(price: try VND.parse(fuel), effectiveDay: PayrollDates.fuelDay(period.month), source: source) + } else { value.fuel = nil } + try value.policy.validate() + if save(value, Int(opening * 2)) { dismiss() } + } catch { self.error = error.localizedDescription } + } +} + +private struct SalaryAdvanceEditor: View { + let month: Date + @EnvironmentObject private var store: DeliveryStore + @Environment(\.dismiss) private var dismiss + @State private var amount = "" + @State private var note = "" + @State private var day = Date() + @State private var error = "" + var body: some View { + Form { + DatePicker("Ngày tạm ứng", selection: $day, displayedComponents: .date) + MoneyInput(title: "Số tiền đã ứng", text: $amount) + TextField("Ghi chú", text: $note) + if !error.isEmpty { Text(error).foregroundStyle(.red) } + Button("Ghi khoản tạm ứng") { + do { + guard DeliveryMonth.contains(day, in: month), day <= Date() else { throw DeliveryError.invalid("Chọn ngày đã ứng trong tháng đang xem.") } + let item = SalaryAdvance(day: day, amount: try VND.parse(amount), note: note) + if store.change({ ledger in try ledger.changePayroll("Ghi tạm ứng") { book in var p = book.period(month); p.advances.append(item); try book.put(p) } }) { dismiss() } + } catch { self.error = error.localizedDescription } + } + }.navigationTitle("Tạm ứng").toolbar { CloseSheet { dismiss() } } + .onAppear { day = DeliveryMonth.contains(Date(), in: month) ? Date() : month } + } +} diff --git a/Sweep/Views/ReconciliationView.swift b/Sweep/Views/ReconciliationView.swift index 531ff1d..eb6d6de 100644 --- a/Sweep/Views/ReconciliationView.swift +++ b/Sweep/Views/ReconciliationView.swift @@ -2,78 +2,102 @@ import SwiftUI struct ReconciliationView: View { @EnvironmentObject private var store: DeliveryStore - @State private var month = Date() + @Environment(\.scenePhase) private var scenePhase + @State private var month = DeliveryMonth.start(Date()) + @State private var observedMonth = DeliveryMonth.start(Date()) + @State private var query = "" @State private var accountantCount = "" @State private var accountantAmount = "" @State private var handover = false @State private var sharing: DeliveryShare? - private var entries: [(DeliveryOrder, SignedAssignment)] { store.ledger.commissions(in: month).sorted { $0.1.signedAt < $1.1.signedAt } } - private var fees: Int64 { entries.reduce(0) { $0 + $1.1.fee } } - private var monthTitle: String { let f = DateFormatter(); f.locale = Locale(identifier: "vi_VN"); f.dateFormat = "MM/yyyy"; return f.string(from: month) } + private var summary: MonthlyReconciliation { MonthlyReconciliation(ledger: store.ledger, month: month) } + private var monthTitle: String { + let f = DateFormatter(); f.locale = Locale(identifier: "vi_VN"); f.timeZone = DeliveryMonth.calendar.timeZone + f.dateFormat = "MM/yyyy"; return f.string(from: month) + } var body: some View { + let totals = summary List { - Section("Công theo ngày ký nhận") { + Section { HStack { - Button { moveMonth(-1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Tháng trước") + Button { moveMonth(-1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Tháng trước").accessibilityIdentifier("audit.previous") Spacer(); Text("Tháng \(monthTitle)").font(.headline); Spacer() - Button { moveMonth(1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Tháng sau") + Button { moveMonth(1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Tháng sau").accessibilityIdentifier("audit.next") }.buttonStyle(.borderless) - LabeledContent("Phiếu ký hợp lệ", value: "\(entries.count)").accessibilityIdentifier("audit.count") - LabeledContent("Công đã ghi nhận", value: VND.format(fees)).font(.headline).foregroundStyle(.green) - Text("Tính cả phiếu giao thất bại / chưa thu. Mức công lưu theo từng lượt ký, không phải lương đã nhận.").font(.caption).foregroundStyle(.secondary) - Button("Xuất toàn bộ phiếu tháng này (CSV)") { - let url = FileManager.default.temporaryDirectory.appendingPathComponent("Sweep-cong-\(monthTitle.replacingOccurrences(of: "/", with: "-"))-\(UUID().uuidString.prefix(6)).csv") - do { try Data(store.ledger.csv(in: month).utf8).write(to: url, options: .atomic); sharing = DeliveryShare(items: [url]) } - catch { store.message = error.localizedDescription } - } } - Section("Đối chiếu với kế toán · chưa lưu vào sổ") { - HStack { Text("Số phiếu kế toán"); TextField("Chưa nhập", text: $accountantCount).keyboardType(.numberPad).multilineTextAlignment(.trailing) } - MoneyInput(title: "Công kế toán", text: $accountantAmount) - if let count = Int(accountantCount), count >= 0 { Text("Sweep − kế toán: \(entries.count - count) phiếu").font(.subheadline) } - if !accountantAmount.isEmpty, let amount = try? VND.parse(accountantAmount) { Text("Chênh công: \(VND.format(fees - amount))").font(.subheadline) } - Text("Dùng danh sách mã phiếu phía dưới / CSV để tìm phần chênh, chưa kết luận bên nào đúng.").font(.caption).foregroundStyle(.secondary) + Section("Công giao hàng") { + LabeledContent("Phiếu tính công", value: "\(totals.count)").accessibilityIdentifier("audit.count") + LabeledContent("Tổng tiền đơn", value: VND.format(totals.commissions.reduce(0) { $0 + $1.0.total })) + LabeledContent("Tiền công", value: VND.format(totals.fee)).font(.headline).foregroundStyle(.green).accessibilityIdentifier("audit.fee") + Button("Xuất danh sách tháng (CSV)") { exportMonth() } } - Section("Tiền mặt công ty · toàn sổ") { - LabeledContent("Đã thu", value: VND.format(store.ledger.cashCollected)) - LabeledContent("Đã nộp", value: VND.format(store.ledger.cashHanded)) - LabeledContent("Còn giữ", value: VND.format(store.ledger.cashHeld)).font(.headline) - Button("Ghi lần nộp tiền…") { handover = true }.accessibilityIdentifier("audit.handover") - NavigationLink("Lịch sử nộp tiền") { - List(store.ledger.handovers.reversed()) { value in - VStack(alignment: .leading, spacing: 5) { - Text(VND.format(value.amount)).font(.headline) - Text(value.at.formatted(date: .numeric, time: .shortened)).font(.caption).foregroundStyle(.secondary) - Text(value.note).font(.footnote) - if let reversal = store.ledger.handoverReversals.first(where: { $0.handoverID == value.id }) { Text("Đã điều chỉnh: \(reversal.reason)").font(.caption).foregroundStyle(.orange) } - else { NavigationLink("Điều chỉnh ghi nhầm…") { HandoverCorrectionView(value: value) } } + Section("Tiền mặt") { + LabeledContent("Đã thu trong tháng", value: VND.format(totals.cashCollected)).accessibilityIdentifier("audit.cashCollected") + LabeledContent("Đã nộp trong tháng", value: VND.format(totals.cashHanded)).accessibilityIdentifier("audit.cashHanded") + LabeledContent("Chênh lệch thu − nộp", value: VND.format(totals.cashDifference)).font(.headline).accessibilityIdentifier("audit.cashDifference") + if totals.cashDifference < 0 { Text("Có tiền nộp từ khoản đã thu trước tháng này.").font(.caption).foregroundStyle(.secondary) } + LabeledContent("Còn giữ đến hiện tại · gồm tháng trước", value: VND.format(store.ledger.cashHeld)).font(.headline).accessibilityIdentifier("audit.cashHeld") + Button("Ghi nộp tiền") { handover = true }.accessibilityIdentifier("audit.handover") + NavigationLink("Lịch sử nộp trong tháng") { + List { + if totals.handovers.isEmpty { Text("Chưa có lần nộp tiền.").foregroundStyle(.secondary) } + ForEach(totals.handovers) { value in + VStack(alignment: .leading, spacing: 5) { + Text(VND.format(value.amount)).font(.headline) + Text(value.at.formatted(date: .numeric, time: .shortened)).font(.caption).foregroundStyle(.secondary) + Text(value.note).font(.footnote) + if let reversal = store.ledger.handoverReversals.first(where: { $0.handoverID == value.id }) { Text("Đã điều chỉnh: \(reversal.reason)").font(.caption).foregroundStyle(.orange) } + else { NavigationLink("Sửa lần ghi nhầm") { HandoverCorrectionView(value: value) } } + } } }.navigationTitle("Tiền đã nộp") } - Text("Tiền công tách riêng. Sweep không tự trừ công khỏi tiền phải nộp.").font(.caption).foregroundStyle(.secondary) } - Section("CK chờ đối soát công ty · toàn sổ") { - LabeledContent("Chưa xác nhận vào công ty", value: VND.format(store.ledger.bankPending)) - ForEach(store.ledger.orders.filter { $0.bank > $0.verifiedBank }) { order in - NavigationLink { OrderDetailView(id: order.id) } label: { LabeledContent(order.customer, value: VND.format(order.bank - order.verifiedBank)) } + Section("Phân loại đã giao trong tháng") { + ForEach([DeliveryRoute.cashFull, .transferNow, .transferLater, .freight], id: \.self) { route in + let orders = totals.orders.filter { $0.settlement?.route == route } + NavigationLink { + List(orders) { order in + NavigationLink { OrderDetailView(id: order.id) } label: { VStack(alignment: .leading) { Text(order.customer); Text(order.workflowStatus).font(.caption).foregroundStyle(.secondary) } } + }.navigationTitle(route.rawValue) + } label: { LabeledContent(route.rawValue, value: "\(orders.count)") } } } - Section("Phiếu tính công trong tháng · \(entries.count)") { - ForEach(entries, id: \.1.id) { order, assignment in + Section("Phiếu tính công · \(totals.count)") { + if totals.commissions.isEmpty { Text("Chưa có phiếu trong tháng.").foregroundStyle(.secondary) } + ForEach(totals.commissions.filter { query.isEmpty || ($0.0.customer + $0.0.code + $0.0.phone).localizedStandardContains(query) }, id: \.1.id) { order, assignment in NavigationLink { OrderDetailView(id: order.id) } label: { VStack(alignment: .leading, spacing: 4) { HStack { Text(order.customer); Spacer(); Text(VND.format(assignment.fee)) } - Text("\(order.code) · \(assignment.signedAt.formatted(date: .numeric, time: .omitted)) · \(order.outcome.rawValue)").font(.caption).foregroundStyle(.secondary) + Text("\(order.code) · \(assignment.signedAt.formatted(date: .numeric, time: .omitted)) · \(order.workflowStatus)").font(.caption).foregroundStyle(.secondary) } } } } } - .navigationTitle("Đối soát") + .navigationTitle("Lịch sử").searchable(text: $query, prompt: "Tên khách, mã phiếu, số điện thoại") .sheet(isPresented: $handover) { HandoverView() } .sheet(item: $sharing) { DeliveryShareSheet(items: $0.items) } + .onAppear { rollMonthIfNeeded() } + .onChange(of: scenePhase) { _, phase in if phase == .active { rollMonthIfNeeded() } } + .onReceive(NotificationCenter.default.publisher(for: .NSCalendarDayChanged)) { _ in rollMonthIfNeeded() } + .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer(); Button("Xong") { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } } + } + private func moveMonth(_ offset: Int) { + month = DeliveryMonth.calendar.date(byAdding: .month, value: offset, to: month) ?? month + accountantCount = ""; accountantAmount = "" + } + private func rollMonthIfNeeded() { + let now = Date() + let next = DeliveryMonth.rollover(selected: month, observed: observedMonth, now: now) + if next != month { month = next; accountantCount = ""; accountantAmount = "" } + observedMonth = DeliveryMonth.start(now) + } + private func exportMonth() { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("Sweep-cong-\(monthTitle.replacingOccurrences(of: "/", with: "-"))-\(UUID().uuidString.prefix(6)).csv") + do { try Data(store.ledger.csv(in: month, calendar: DeliveryMonth.calendar).utf8).write(to: url, options: .atomic); sharing = DeliveryShare(items: [url]) } + catch { store.message = error.localizedDescription } } - private func moveMonth(_ offset: Int) { month = Calendar.current.date(byAdding: .month, value: offset, to: month) ?? month; accountantCount = ""; accountantAmount = "" } } private struct HandoverCorrectionView: View { diff --git a/Sweep/Views/SharedInboxView.swift b/Sweep/Views/SharedInboxView.swift new file mode 100644 index 0000000..ff115a4 --- /dev/null +++ b/Sweep/Views/SharedInboxView.swift @@ -0,0 +1,77 @@ +import SwiftUI + +@MainActor +final class SharedInboxStore: ObservableObject { + @Published private(set) var items: [SharedInvoiceInbox.Item] = [] + @Published private(set) var warnings: [String] = [] + @Published private(set) var problem = "" + private var loading = false + + func reload() async { + guard !loading else { return }; loading = true; defer { loading = false } + do { + let scan = try await Task.detached(priority: .utility) { try SharedInvoiceInbox.live().scan() }.value + items = scan.items; warnings = scan.warnings; problem = "" + } catch { problem = error.localizedDescription } + } + func remove(_ item: SharedInvoiceInbox.Item) async -> Bool { + do { + try await Task.detached(priority: .utility) { try SharedInvoiceInbox.live().remove(item) }.value + await reload(); return true + } catch { problem = error.localizedDescription; return false } + } +} + +struct SharedInboxView: View { + @ObservedObject var inbox: SharedInboxStore + let saved: (UUID) -> Void + @EnvironmentObject private var store: DeliveryStore + @Environment(\.dismiss) private var dismiss + @State private var selected: SharedInvoiceInbox.Item? + @State private var discarding: SharedInvoiceInbox.Item? + @State private var imported: UUID? + @State private var autoOpened = false + var body: some View { + NavigationStack { + List { + if !inbox.problem.isEmpty { Section { Text(inbox.problem).foregroundStyle(.orange) } } + Section("\(inbox.items.count) ảnh chờ nhận") { + if inbox.items.isEmpty { Text("Chưa có ảnh chờ nhận.").foregroundStyle(.secondary) } + ForEach(inbox.items) { item in + Button { selected = item } label: { + HStack { + EvidenceThumbnail(url: item.image, height: 70).frame(width: 100) + VStack(alignment: .leading) { + Text("Kiểm tra và nhập phiếu").font(.headline) + Text(item.receivedAt.formatted(date: .numeric, time: .shortened)).font(.caption).foregroundStyle(.secondary) + } + } + }.accessibilityIdentifier("shared.item") + .swipeActions { Button("Xóa ảnh chờ", role: .destructive) { discarding = item } } + } + } + if !inbox.warnings.isEmpty { Section("Cần kiểm tra") { ForEach(Array(inbox.warnings.enumerated()), id: \.offset) { _, warning in Text(warning).font(.caption).foregroundStyle(.orange) } } } + } + .navigationTitle("Ảnh được chia sẻ").navigationBarTitleDisplayMode(.inline) + .toolbar { CloseSheet { dismiss() } } + .refreshable { await inbox.reload() } + .sheet(item: $selected, onDismiss: { if let id = imported { imported = nil; saved(id) } }) { item in + OrderIntakeView(shared: item) { id in + Task { + // The ledger commit must precede removing the queue item. sourceID makes a retry idempotent. + if !(await inbox.remove(item)) { store.message = "Đơn đã lưu, nhưng ảnh chờ chưa dọn được. Nhập lại sẽ mở đúng hồ sơ cũ. " + inbox.problem } + imported = id; selected = nil + } + } + } + .alert("Xóa ảnh chờ nhận?", isPresented: Binding(get: { discarding != nil }, set: { if !$0 { discarding = nil } })) { + Button("Xóa ảnh chờ", role: .destructive) { if let item = discarding { Task { _ = await inbox.remove(item) } }; discarding = nil } + Button("Giữ lại", role: .cancel) { discarding = nil } + } message: { Text("Chỉ bỏ ảnh trong hộp thư Sweep. Đơn đã nhập và ảnh gốc trong Zalo không bị thay đổi.") } + .background(SweepAppearanceAction { + guard !autoOpened else { return }; autoOpened = true + if inbox.items.count == 1 { selected = inbox.items.first } + }.frame(width: 0, height: 0)) + } + } +} diff --git a/SweepShare/Info.plist b/SweepShare/Info.plist new file mode 100644 index 0000000..fe5f127 --- /dev/null +++ b/SweepShare/Info.plist @@ -0,0 +1,22 @@ + + + + CFBundleDisplayNameSweep + CFBundleName$(PRODUCT_NAME) + CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleExecutable$(EXECUTABLE_NAME) + CFBundlePackageTypeXPC! + CFBundleShortVersionString$(MARKETING_VERSION) + CFBundleVersion$(CURRENT_PROJECT_VERSION) + SweepAppGroupIdentifier$(SWEEP_APP_GROUP) + NSExtension + NSExtensionPointIdentifiercom.apple.share-services + NSExtensionPrincipalClass$(PRODUCT_MODULE_NAME).ShareViewController + NSExtensionAttributes + NSExtensionActivationRule + NSExtensionActivationSupportsImageWithMaxCount1 + NSExtensionActivationSupportsFileWithMaxCount1 + + + + diff --git a/SweepShare/ShareViewController.swift b/SweepShare/ShareViewController.swift new file mode 100644 index 0000000..1c59497 --- /dev/null +++ b/SweepShare/ShareViewController.swift @@ -0,0 +1,148 @@ +import UIKit +import UniformTypeIdentifiers +import ImageIO +import PhotosUI + +/// Runs inside the sender's share sheet. No private openURL/UIApplication workaround. +@MainActor +final class ShareViewController: UIViewController, PHPickerViewControllerDelegate { + private let imageView = UIImageView() + private let status = UILabel() + private let saveButton = UIButton(type: .system) + private let photoButton = UIButton(type: .system) + private let detailsButton = UIButton(type: .system) + private var errorDetails = "" + private var inboxReady = false + private var saving = false + private var signedAt: Date? + private var imageURL: URL? + private var work: Task? + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemGroupedBackground + preferredContentSize = CGSize(width: 400, height: 530) + let title = UILabel(); title.text = "Nhận phiếu vào Sweep"; title.font = .preferredFont(forTextStyle: .title2) + title.adjustsFontForContentSizeCategory = true; title.numberOfLines = 0 + let cancel = UIButton(type: .system) + cancel.setTitle("Hủy", for: .normal) + cancel.addTarget(self, action: #selector(cancelShare), for: .touchUpInside) + let header = UIStackView(arrangedSubviews: [title, cancel]); header.spacing = 12 + imageView.contentMode = .scaleAspectFit + imageView.isHidden = true + imageView.heightAnchor.constraint(equalToConstant: 240).isActive = true + status.font = .preferredFont(forTextStyle: .body); status.adjustsFontForContentSizeCategory = true + status.numberOfLines = 0; status.text = "Đang nhận ảnh…" + var config = UIButton.Configuration.filled(); config.title = "Gửi đến Sweep"; config.baseBackgroundColor = .systemGreen + config.cornerStyle = .large; saveButton.configuration = config; saveButton.isEnabled = false + saveButton.addTarget(self, action: #selector(saveShare), for: .touchUpInside) + var photoConfig = UIButton.Configuration.tinted(); photoConfig.title = "Chọn từ Ảnh"; photoConfig.image = UIImage(systemName: "photo.on.rectangle"); photoConfig.imagePadding = 10 + photoConfig.baseBackgroundColor = .systemGreen; photoButton.configuration = photoConfig; photoButton.isEnabled = false + photoButton.addTarget(self, action: #selector(choosePhoto), for: .touchUpInside) + detailsButton.setTitle("Chi tiết lỗi", for: .normal); detailsButton.isHidden = true + detailsButton.addTarget(self, action: #selector(showDetails), for: .touchUpInside) + let stack = UIStackView(arrangedSubviews: [header, imageView, status, photoButton, detailsButton, saveButton]) + stack.axis = .vertical; stack.spacing = 20; stack.translatesAutoresizingMaskIntoConstraints = false + let scroll = UIScrollView(); scroll.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(scroll); scroll.addSubview(stack) + NSLayoutConstraint.activate([ + scroll.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), + scroll.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), + scroll.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + scroll.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), + stack.leadingAnchor.constraint(equalTo: scroll.contentLayoutGuide.leadingAnchor, constant: 20), + stack.trailingAnchor.constraint(equalTo: scroll.contentLayoutGuide.trailingAnchor, constant: -20), + stack.topAnchor.constraint(equalTo: scroll.contentLayoutGuide.topAnchor, constant: 20), + stack.bottomAnchor.constraint(equalTo: scroll.contentLayoutGuide.bottomAnchor, constant: -20), + stack.widthAnchor.constraint(equalTo: scroll.frameLayoutGuide.widthAnchor, constant: -40) + ]) + DispatchQueue.main.async { [weak self] in self?.confirmSignature() } + } + private func confirmSignature() { + let alert = UIAlertController(title: "Đơn này bạn đã ký chưa?", message: nil, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "Đã ký", style: .default) { [weak self] _ in + self?.signedAt = Date(); self?.work = Task { await self?.receive() } + }) + alert.addAction(UIAlertAction(title: "Bỏ qua", style: .cancel) { [weak self] _ in self?.cancelShare() }) + present(alert, animated: true) + + } + + private func receive() async { + do { + _ = try SharedInvoiceInbox.live() + inboxReady = true; photoButton.isEnabled = true + let providers = (extensionContext?.inputItems as? [NSExtensionItem] ?? []).flatMap { $0.attachments ?? [] } + var images = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.image.identifier) || $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) || $0.canLoadObject(ofClass: UIImage.self) } + if images.isEmpty, providers.count == 1, providers[0].hasItemConformingToTypeIdentifier(UTType.data.identifier) { images = providers } + guard images.count == 1, let provider = images.first else { throw DeliveryError.invalid("Mỗi lần nhận một ảnh phiếu. Sếp có thể chọn lại ảnh từ thư viện.") } + await load(provider) + } catch { showError(error) } + } + + private func load(_ provider: NSItemProvider) async { + cleanup(); imageView.image = nil; imageView.isHidden = true + saveButton.isEnabled = false; photoButton.isEnabled = false; detailsButton.isHidden = true + status.text = "Đang nhận ảnh…" + do { + let url = try await SharedInvoiceLoader.load(from: provider) + guard !Task.isCancelled else { try? FileManager.default.removeItem(at: url); return } + imageURL = url + if let source = CGImageSourceCreateWithURL(url as CFURL, nil), + let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, CGImageSourceGetPrimaryImageIndex(source), [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: 900 + ] as CFDictionary) { imageView.image = UIImage(cgImage: thumbnail); imageView.isHidden = false } + status.text = "Ảnh sẵn sàng. Gửi đến Sweep để nhập đơn." + saveButton.isEnabled = true + } catch { if !Task.isCancelled { showError(error) } } + photoButton.isEnabled = inboxReady + } + + @objc private func choosePhoto() { + var config = PHPickerConfiguration(photoLibrary: .shared()) + config.filter = .images; config.selectionLimit = 1; config.preferredAssetRepresentationMode = .compatible + let picker = PHPickerViewController(configuration: config); picker.delegate = self + present(picker, animated: true) + } + func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { + picker.dismiss(animated: true) + guard let provider = results.first?.itemProvider else { return } + work?.cancel(); work = Task { await load(provider) } + } + private func showError(_ error: Error) { + errorDetails = error.localizedDescription; detailsButton.isHidden = false + status.text = inboxReady ? "Chưa đọc được ảnh chia sẻ. Sếp có thể chọn ảnh từ thư viện để tiếp tục." : errorDetails + photoButton.isEnabled = inboxReady + } + @objc private func showDetails() { + let alert = UIAlertController(title: "Thông tin nguồn ảnh", message: errorDetails, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "Sao chép", style: .default) { [weak self] _ in UIPasteboard.general.string = self?.errorDetails }) + alert.addAction(UIAlertAction(title: "Đóng", style: .cancel)) + present(alert, animated: true) + } + + @objc private func saveShare() { + guard let imageURL else { return } + saving = true; photoButton.isEnabled = false; saveButton.isEnabled = false; status.text = "Đang lưu ảnh…" + let signature = signedAt + work = Task { + do { + try await Task.detached(priority: .userInitiated) { _ = try SharedInvoiceInbox.live().add(imageURL, signedAt: signature) }.value + cleanup() + extensionContext?.completeRequest(returningItems: nil) + } catch { saving = false; showError(error); saveButton.isEnabled = true } + } + } + @objc private func cancelShare() { + // Once a durable write starts, let it finish instead of racing cancellation with publication. + guard !saving else { return } + work?.cancel(); cleanup() + extensionContext?.cancelRequest(withError: CocoaError(.userCancelled)) + } + private func cleanup() { + if let imageURL { try? FileManager.default.removeItem(at: imageURL) }; imageURL = nil + } + deinit { work?.cancel(); if let imageURL { try? FileManager.default.removeItem(at: imageURL) } } +} diff --git a/SweepShare/SweepShare.entitlements b/SweepShare/SweepShare.entitlements new file mode 100644 index 0000000..0d1e82b --- /dev/null +++ b/SweepShare/SweepShare.entitlements @@ -0,0 +1,5 @@ + + + + com.apple.security.application-groups$(SWEEP_APP_GROUP) + diff --git a/Tests/AppGroupConfigurationTests.swift b/Tests/AppGroupConfigurationTests.swift new file mode 100644 index 0000000..21f9ecd --- /dev/null +++ b/Tests/AppGroupConfigurationTests.swift @@ -0,0 +1,24 @@ +import XCTest +@testable import SweepCore + +final class AppGroupConfigurationTests: XCTestCase { + func testAltStoreRemappingTakesPrecedenceOverOriginalGroup() { + let mapped = "group.com.sentechtipsvn.sweep.TESTTEAM01" + XCTAssertEqual(AppGroupConfiguration.identifiers(in: ["SweepAppGroupIdentifier": "group.com.sentechtipsvn.sweep", "ALTAppGroups": [mapped]]), [mapped]) + } + func testNormalSigningKeepsConfiguredGroup() { + XCTAssertEqual(AppGroupConfiguration.identifiers(in: ["SweepAppGroupIdentifier": "group.com.sentechtipsvn.sweep"]), ["group.com.sentechtipsvn.sweep"]) + } + func testEmptyOrMalformedInjectedGroupsDoNotPretendOriginalGroupIsGranted() { + let cases: [Any] = [[String](), "group.fake", ["../escape", "", "group.bad/name"]] + for value in cases { + XCTAssertTrue(AppGroupConfiguration.identifiers(in: ["SweepAppGroupIdentifier": "group.original", "ALTAppGroups": value]).isEmpty) + } + } + func testAppAndExtensionChooseSameDeterministicGroups() { + let groups = ["group.sweep.B", "group.sweep.A", "group.sweep.B"] + let app = AppGroupConfiguration.identifiers(in: ["CFBundleIdentifier": "app.remapped", "ALTAppGroups": groups]) + let ext = AppGroupConfiguration.identifiers(in: ["CFBundleIdentifier": "app.remapped.share", "ALTAppGroups": Array(groups.reversed())]) + XCTAssertEqual(app, ["group.sweep.A", "group.sweep.B"]); XCTAssertEqual(app, ext) + } +} diff --git a/Tests/ApprovedWorkflowTests.swift b/Tests/ApprovedWorkflowTests.swift new file mode 100644 index 0000000..4f1f6e2 --- /dev/null +++ b/Tests/ApprovedWorkflowTests.swift @@ -0,0 +1,75 @@ +import XCTest +@testable import SweepCore + +final class ApprovedWorkflowTests: XCTestCase { + func testSixRoutesEnforceEvidenceAndKeepMoneySeparate() throws { + for (route, cash, bank, roles) in [ + (DeliveryRoute.cashFull, Int64(1000), Int64(0), [EvidenceRole]()), + (.transferNow, 300, 700, [.invoice, .transfer]), + (.transferLater, 300, 0, [.signature]), + (.transferNow, 0, 1000, [.invoice, .transfer]), + (.transferLater, 0, 0, [.signature]), + (.freight, 0, 0, [.freightSignature, .goods]) + ] { + var ledger = DeliveryLedger(); let id = try ledger.insert(order()) + try ledger.sign(id, at: Date()); try ledger.sign(id, at: Date()) + let mode: PaymentMode = cash > 0 && bank > 0 ? .mixed : bank > 0 ? .bank : cash > 0 ? .cash : .deferred + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: mode, cash: cash, bank: bank, note: "", at: Date(), route: route)) + XCTAssertEqual(ledger.orders[0].requiredReportRoles, roles) + XCTAssertEqual(ledger.orders[0].activeAssignments.count, 1) + if route == .cashFull { + XCTAssertTrue(ledger.orders[0].taskComplete); XCTAssertFalse(ledger.orders[0].reportNeeded) + XCTAssertThrowsError(try ledger.prepareReport(id, text: "cash")) + } else { + XCTAssertThrowsError(try ledger.prepareReport(id, text: "test", evidenceIDs: [])) + for role in roles where role != .invoice { ledger.orders[0].evidence.append(file(role)) } + let wanted = ledger.orders[0].defaultShareEvidenceIDs + let report = try ledger.prepareReport(id, text: ledger.orders[0].shareText(), evidenceIDs: wanted) + XCTAssertFalse(ledger.orders[0].taskComplete) + try ledger.acknowledgeReport(id, reportID: report.id) + XCTAssertTrue(ledger.orders[0].taskComplete) + if route == .transferLater || route == .freight { XCTAssertFalse(wanted.contains(ledger.orders[0].evidence[0].id)) } + } + XCTAssertEqual(ledger.cashHeld, cash); try ledger.validate() + } + } + func testReportStatusSurvivesUnrelatedEditsButNotMoneyChanges() throws { + var ledger = DeliveryLedger(); let id = try ledger.insert(order()); try ledger.sign(id, at: Date()) + ledger.orders[0].evidence.append(file(.transfer)) + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .bank, cash: 0, bank: 1000, note: "", at: Date(), route: .transferNow)) + let report = try ledger.prepareReport(id, text: ledger.orders[0].shareText()) + try ledger.acknowledgeReport(id, reportID: report.id) + try ledger.verifyBank(id, note: "Legacy accountant check") + ledger.orders[0].address = "Updated address"; ledger.orders[0].revision += 1 + ledger.orders[0].evidence.append(file(.signature)); ledger.orders[0].revision += 1 + XCTAssertTrue(ledger.orders[0].reportSent) + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .bank, cash: 0, bank: 900, note: "Correction", at: Date(), route: .transferNow)) + XCTAssertFalse(ledger.orders[0].reportSent) + } + func testNewFieldsDecodeOldBackupAndDirectoryRoundTrips() throws { + var ledger = DeliveryLedger(); ledger.schema = 1; _ = try ledger.insert(order()) + let data = try DeliveryCoding.encode(ledger) + let decoded = try DeliveryCoding.decode(DeliveryLedger.self, from: data) + XCTAssertNil(decoded.places); XCTAssertNil(decoded.contacts); XCTAssertNil(decoded.orders[0].settlement?.route) + try ledger.saveContact(DeliveryContact(name: "Ngọc", phone: "0900000000", zalo: "https://zalo.me/0900000000", aliases: "TEL, N", role: "Bán hàng")) + XCTAssertTrue(ledger.contacts![0].matches("tel")); XCTAssertFalse(ledger.contacts![0].matches("")) + let p = DeliveryPlace(customer: "Bánh A", phone: "", address: "12A", kind: "Khách hàng", latitude: 10.7, longitude: 106.7) + try ledger.savePlace(p); try ledger.savePlace(p) + var branch = p; branch.id = UUID(); branch.address = "12B"; try ledger.savePlace(branch) + XCTAssertEqual(ledger.places?.count, 2) + var invalid = p; invalid.latitude = 91; XCTAssertThrowsError(try ledger.savePlace(invalid)) + XCTAssertEqual(try DeliveryCoding.decode(DeliveryLedger.self, from: DeliveryCoding.encode(ledger)), ledger) + } + func testTransferNextMonthDoesNotMoveLastMonthCashReceipt() throws { + let october = ISO8601DateFormatter().date(from: "2026-10-31T10:00:00Z")! + let november = ISO8601DateFormatter().date(from: "2026-11-01T10:00:00Z")! + var ledger = DeliveryLedger(); let id = try ledger.insert(order()); try ledger.sign(id, at: october) + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .cash, cash: 300, bank: 0, note: "", at: october, route: .transferLater)) + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .mixed, cash: 300, bank: 700, note: "", at: november, route: .transferNow)) + XCTAssertEqual(MonthlyReconciliation(ledger: ledger, month: october).cashCollected, 300) + XCTAssertEqual(MonthlyReconciliation(ledger: ledger, month: november).cashCollected, 0) + XCTAssertEqual(ledger.cashHeld, 300) + } + private func order() -> DeliveryOrder { var o = DeliveryOrder(code: UUID().uuidString, customer: "Khách", total: 1000); o.evidence = [file(.invoice)]; return o } + private func file(_ role: EvidenceRole) -> DeliveryEvidence { DeliveryEvidence(role: role, filename: UUID().uuidString + ".jpg", sha256: String(repeating: "a", count: 64), bytes: 100) } +} diff --git a/Tests/DeliveryWorkflowRegressionTests.swift b/Tests/DeliveryWorkflowRegressionTests.swift new file mode 100644 index 0000000..05d67d6 --- /dev/null +++ b/Tests/DeliveryWorkflowRegressionTests.swift @@ -0,0 +1,137 @@ +import XCTest +import Foundation +@testable import SweepCore + +final class DeliveryWorkflowRegressionTests: XCTestCase { + func testEveryReconciliationFigureUsesTheSelectedMonth() throws { + var ledger = DeliveryLedger() + let october = date("2026-10-12T03:00:00Z"), november = date("2026-11-12T03:00:00Z") + let old = try ledger.insert(order("OCT")), current = try ledger.insert(order("NOV")) + try ledger.sign(old, at: october); try ledger.sign(current, at: november) + try ledger.settle(old, value: settlement(.mixed, cash: 600_000, bank: 1_500_000, at: october)) + try ledger.settle(current, value: settlement(.mixed, cash: 665_000, bank: 1_500_000, at: november)) + try ledger.handover(400_000, at: october, note: "Nộp tháng 10") + try ledger.handover(500_000, at: november, note: "Nộp tháng 11") + try ledger.verifyBank(old, note: "Kế toán đã nhận") + let before = ledger + let oct = MonthlyReconciliation(ledger: ledger, month: october) + XCTAssertEqual(oct.count, 1); XCTAssertEqual(oct.fee, 5_000) + XCTAssertEqual(oct.cashCollected, 600_000); XCTAssertEqual(oct.cashHanded, 400_000) + XCTAssertEqual(oct.cashDifference, 200_000); XCTAssertEqual(oct.bankPending, 0) + let nov = MonthlyReconciliation(ledger: ledger, month: november) + XCTAssertEqual(nov.count, 1); XCTAssertEqual(nov.fee, 5_000) + XCTAssertEqual(nov.cashCollected, 665_000); XCTAssertEqual(nov.cashHanded, 500_000) + XCTAssertEqual(nov.cashDifference, 165_000); XCTAssertEqual(nov.bankPending, 1_500_000) + XCTAssertEqual(nov.pendingOrders.map(\.id), [current]) + let empty = MonthlyReconciliation(ledger: ledger, month: date("2026-09-12T03:00:00Z")) + XCTAssertEqual(empty.count, 0); XCTAssertEqual(empty.fee, 0) + XCTAssertEqual(empty.cashCollected, 0); XCTAssertEqual(empty.cashHanded, 0) + XCTAssertEqual(empty.cashDifference, 0); XCTAssertEqual(empty.bankPending, 0) + XCTAssertTrue(empty.orders.isEmpty); XCTAssertTrue(empty.handovers.isEmpty) + XCTAssertEqual(ledger, before); XCTAssertEqual(ledger.cashHeld, 365_000) + } + + func testCrossMonthRemittanceAndReversalKeepTheCashLedgerIntact() throws { + var ledger = DeliveryLedger(); let id = try ledger.insert(order("CASH")) + try ledger.settle(id, value: settlement(.cash, cash: 2_165_000, bank: 0, at: date("2026-10-31T03:00:00Z"))) + let november = date("2026-11-01T03:00:00Z") + try ledger.handover(1_000_000, at: november, note: "Nộp tiền đã thu tháng trước") + XCTAssertEqual(MonthlyReconciliation(ledger: ledger, month: november).cashDifference, -1_000_000) + XCTAssertEqual(ledger.cashHeld, 1_165_000) + try ledger.reverseHandover(ledger.handovers[0].id, reason: "Ghi nhầm") + let summary = MonthlyReconciliation(ledger: ledger, month: november) + XCTAssertEqual(summary.cashHanded, 0); XCTAssertEqual(summary.handovers.count, 1) + XCTAssertEqual(ledger.cashHeld, 2_165_000) + XCTAssertThrowsError(try ledger.handover(2_166_000, at: november, note: "Vượt số đang giữ")) + try ledger.validate() + } + + func testVietnamMonthBoundaryAndAutomaticRolloverPreserveHistorySelection() { + let before = date("2026-10-31T16:59:59Z"), after = date("2026-10-31T17:00:00Z") + let historical = date("2026-09-12T03:00:00Z") + XCTAssertTrue(DeliveryMonth.contains(before, in: before)) + XCTAssertFalse(DeliveryMonth.contains(after, in: before)) + XCTAssertEqual(DeliveryMonth.calendar.component(.month, from: DeliveryMonth.start(after)), 11) + XCTAssertEqual(DeliveryMonth.rollover(selected: historical, observed: before, now: before), historical) + XCTAssertEqual(DeliveryMonth.rollover(selected: historical, observed: before, now: after), DeliveryMonth.start(after)) + XCTAssertEqual(DeliveryMonth.rollover(selected: after, observed: after, now: after), after) + } + + func testTwoChosenReportImagesDoNotRemoveTheThirdOriginalOrChangeMoney() throws { + var ledger = DeliveryLedger(); let id = try ledger.insert(order("SEND")) + try ledger.sign(id, at: Date()) + try ledger.settle(id, value: settlement(.mixed, cash: 665_000, bank: 1_500_000, at: Date())) + let saved = ledger.orders[0], chosen = saved.defaultShareEvidenceIDs + XCTAssertEqual(chosen, saved.orderedEvidence.filter { $0.role != .signature }.map(\.id)) + let two = try ledger.prepareReport(id, text: saved.shareText(), evidenceIDs: chosen) + XCTAssertEqual(two.evidenceIDs.count, 2); XCTAssertEqual(ledger.orders[0].evidence.count, 3) + XCTAssertTrue(ledger.orders[0].exclusions.isEmpty) + let one = try ledger.prepareReport(id, text: saved.shareText(), evidenceIDs: [chosen[0]]) + XCTAssertEqual(one.evidenceIDs.count, 1) + let restored = try ledger.prepareReport(id, text: saved.shareText(), evidenceIDs: chosen) + XCTAssertEqual(restored.evidenceIDs, two.evidenceIDs) + XCTAssertEqual(ledger.orders[0].settlements, saved.settlements) + XCTAssertEqual(ledger.orders[0].assignments, saved.assignments) + XCTAssertFalse(ledger.orders[0].reportSent) + XCTAssertThrowsError(try ledger.prepareReport(id, text: "Sai", evidenceIDs: [chosen[0], chosen[0]])) + XCTAssertThrowsError(try ledger.prepareReport(id, text: "Sai", evidenceIDs: [UUID()])) + try ledger.validate() + } + + func testExplicitPhotoSelectionCanSendTransferWithoutSignedCustomerSlip() throws { + var ledger = DeliveryLedger(); var invoice = order("NO-SIGNATURE") + invoice.evidence.removeAll { $0.role == .signature } + let id = try ledger.insert(invoice) + try ledger.settle(id, value: settlement(.mixed, cash: 665_000, bank: 1_500_000, at: Date())) + XCTAssertThrowsError(try ledger.prepareReport(id, text: "Legacy validation")) + let report = try ledger.prepareReport(id, text: ledger.orders[0].shareText(), evidenceIDs: ledger.orders[0].defaultShareEvidenceIDs) + XCTAssertEqual(report.evidenceIDs.count, 2) + XCTAssertTrue(ledger.orders[0].exclusions.isEmpty) + } + + func testCompactCaptionUsesActualTransferAmountAndDoesNotInventPayment() throws { + var ledger = DeliveryLedger(); let id = try ledger.insert(order("CAPTION")) + try ledger.settle(id, value: settlement(.mixed, cash: 665_000, bank: 1_500_000, at: Date())) + XCTAssertEqual(ledger.orders[0].shareText(), "Khách thử đã chuyển khoản 1.500.000₫ · Tiền mặt 665.000₫") + try ledger.settle(id, value: settlement(.cash, cash: 2_165_000, bank: 0, at: Date())) + XCTAssertEqual(ledger.orders[0].shareText(), "Khách thử đã thanh toán tiền mặt 2.165.000₫") + try ledger.settle(id, value: settlement(.deferred, cash: 0, bank: 0, at: Date())) + XCTAssertEqual(ledger.orders[0].shareText(), "Khách thử · Chuyển khoản sau · 2.165.000₫") + } + + func testBlankDeliveryNoteDoesNotConsumeTableHeadersOrItemPhoneNumbers() { + let fields = InvoiceParser.parse("Số: 3876\nNV bán hàng: TEL\nĐơn vị: BÁNH THỬ\nĐiện thoại: 0900000000\nĐịa chỉ giao hàng:\nMã hàng Thành\nTên hàng hóa Số lượng Thành tiền\nĐiện thoại: 0999999999\nTiền hàng 2.573.000") + XCTAssertEqual(fields.phone, "0900000000"); XCTAssertEqual(fields.customer, "BÁNH THỬ") + XCTAssertEqual(fields.total, 2_573_000); XCTAssertTrue(fields.deliveryNote.isEmpty) + XCTAssertEqual(InvoiceParser.cleanStoredNote("Giao hàng: Mã hàng Thành"), "") + XCTAssertEqual(InvoiceParser.cleanStoredNote("Điện thoại trên phiếu cần xác minh người nhận: 0900000000\nGiao hàng: Trước 10h sáng"), "Trước 10h sáng") + XCTAssertEqual(InvoiceParser.cleanStoredNote("Mã hàng ABC cần giao trước 10h"), "Mã hàng ABC cần giao trước 10h") + } + + func testGoogleMapsDirectionsKeepTheDestinationAndUseDrivingNavigation() throws { + let address = " 12 Đường Mẫu + Cổng B, TP.HCM " + let native = try XCTUnwrap(DeliveryDirections.googleMaps(address: address)) + XCTAssertEqual(native.scheme, "comgooglemaps") + let items = try XCTUnwrap(URLComponents(url: native, resolvingAgainstBaseURL: false)?.queryItems) + XCTAssertEqual(items.first { $0.name == "daddr" }?.value, address.trimmingCharacters(in: .whitespaces)) + XCTAssertEqual(items.first { $0.name == "directionsmode" }?.value, "driving") + XCTAssertTrue(native.absoluteString.contains("%2B")) + let web = try XCTUnwrap(DeliveryDirections.googleMaps(address: address, native: false)) + XCTAssertEqual(web.host, "www.google.com") + XCTAssertTrue(web.absoluteString.hasPrefix("https://www.google.com/maps/dir/?")) + XCTAssertEqual(URLComponents(url: web, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "destination" }?.value, address.trimmingCharacters(in: .whitespaces)) + XCTAssertNil(DeliveryDirections.googleMaps(address: " \n")) + } + + private func date(_ text: String) -> Date { ISO8601DateFormatter().date(from: text)! } + private func order(_ code: String) -> DeliveryOrder { + var value = DeliveryOrder(code: code, customer: "Khách thử", total: 2_165_000) + value.evidence = [EvidenceRole.invoice, .signature, .transfer].map { + DeliveryEvidence(role: $0, filename: UUID().uuidString + ".png", sha256: String(repeating: "a", count: 64), bytes: 100) + } + return value + } + private func settlement(_ mode: PaymentMode, cash: Int64, bank: Int64, at: Date) -> Settlement { + Settlement(outcome: .delivered, mode: mode, cash: cash, bank: bank, note: "", at: at) + } +} diff --git a/Tests/IncomingInvoiceImageTests.swift b/Tests/IncomingInvoiceImageTests.swift new file mode 100644 index 0000000..19d32a2 --- /dev/null +++ b/Tests/IncomingInvoiceImageTests.swift @@ -0,0 +1,121 @@ +import XCTest +import Foundation +import CoreGraphics +import ImageIO +import UniformTypeIdentifiers +@testable import SweepCore + +final class IncomingInvoiceImageTests: XCTestCase { + func testJPEGWithGenericFilenameIsNormalizedAndMetadataRemoved() throws { + let bytes = try encoded(.jpeg) + let source = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".tmp") + try bytes.write(to: source); defer { try? FileManager.default.removeItem(at: source) } + let result = try IncomingInvoiceImage.copy(from: source) + defer { try? FileManager.default.removeItem(at: result) } + try assertSanitized(result) + XCTAssertEqual(try EvidenceFiles.imageExtension(result), "jpg") + } + + func testTIFFAlternateRepresentationIsNormalizedToReadableJPEG() throws { + let result = try IncomingInvoiceImage.copy(data: encoded(.tiff)) + defer { try? FileManager.default.removeItem(at: result) } + XCTAssertEqual(try EvidenceFiles.imageExtension(result), "jpg") + let source = try XCTUnwrap(CGImageSourceCreateWithURL(result as CFURL, nil)) + let properties = try XCTUnwrap(CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]) + XCTAssertEqual((properties[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue, 733) + XCTAssertEqual((properties[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue, 1032) + } + + func testJPEGDataProviderCanBeQueuedAndOutliveItsTemporaryInput() async throws { + let bytes = try encoded(.jpeg) + let provider = NSItemProvider() + provider.registerDataRepresentation(forTypeIdentifier: UTType.jpeg.identifier, visibility: .all) { done in done(bytes, nil); return nil } + let result = try await SharedInvoiceLoader.load(from: provider) + try assertSanitized(result) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root); try? FileManager.default.removeItem(at: result) } + let inbox = SharedInvoiceInbox(directory: root) + let entry = try inbox.add(result) + try FileManager.default.removeItem(at: result) + XCTAssertEqual(try inbox.scan().items.count, 1) + try EvidenceFiles.verify(entry.evidence, directory: entry.directory) + } + + func testBrokenFileRepresentationFallsBackToJPEGData() async throws { + let bytes = try encoded(.jpeg) + let broken = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try Data("invalid file representation".utf8).write(to: broken) + defer { try? FileManager.default.removeItem(at: broken) } + let provider = NSItemProvider() + provider.registerFileRepresentation(forTypeIdentifier: UTType.jpeg.identifier, fileOptions: [], visibility: .all) { done in done(broken, false, nil); return nil } + provider.registerDataRepresentation(forTypeIdentifier: UTType.jpeg.identifier, visibility: .all) { done in done(bytes, nil); return nil } + let result = try await SharedInvoiceLoader.load(from: provider) + defer { try? FileManager.default.removeItem(at: result) } + try assertSanitized(result) + } + + func testJPEGIsPreferredOverAnEarlierGenericRepresentation() async throws { + let tiff = try encoded(.tiff), jpeg = try encoded(.jpeg) + let provider = NSItemProvider() + provider.registerDataRepresentation(forTypeIdentifier: UTType.tiff.identifier, visibility: .all) { done in done(tiff, nil); return nil } + provider.registerDataRepresentation(forTypeIdentifier: UTType.jpeg.identifier, visibility: .all) { done in done(jpeg, nil); return nil } + let result = try await SharedInvoiceLoader.load(from: provider) + defer { try? FileManager.default.removeItem(at: result) } + try assertSanitized(result) + } + + func testInvalidPayloadsAreNotAcceptedAsInvoices() throws { + XCTAssertThrowsError(try IncomingInvoiceImage.copy(data: Data())) + XCTAssertThrowsError(try IncomingInvoiceImage.copy(data: Data("not an image".utf8))) + } + + func testLegacyPublicImageItemAcceptsEncodedData() async throws { + let bytes = try encoded(.jpeg) + let provider = NSItemProvider(item: bytes as NSData, typeIdentifier: UTType.image.identifier) + let result = try await SharedInvoiceLoader.load(from: provider) + defer { try? FileManager.default.removeItem(at: result) } + try assertSanitized(result) + } + + func testBMPAndGIFAreConvertedToReadableStillImages() throws { + for type in [UTType.bmp, .gif] { + let result = try IncomingInvoiceImage.copy(data: encoded(type)) + defer { try? FileManager.default.removeItem(at: result) } + XCTAssertEqual(try EvidenceFiles.imageExtension(result), "jpg") + } + } + + func testAnimatedGIFFirstFrameCanBeImportedAsInvoice() throws { + let data = NSMutableData() + let input = try XCTUnwrap(CGImageSourceCreateWithData(encoded(.png) as CFData, nil)) + let frame = try XCTUnwrap(CGImageSourceCreateImageAtIndex(input, 0, nil)) + let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.gif.identifier as CFString, 2, nil)) + CGImageDestinationAddImage(destination, frame, nil); CGImageDestinationAddImage(destination, frame, nil) + XCTAssertTrue(CGImageDestinationFinalize(destination)) + let result = try IncomingInvoiceImage.copy(data: data as Data) + defer { try? FileManager.default.removeItem(at: result) } + XCTAssertEqual(try EvidenceFiles.imageExtension(result), "jpg") + let normalized = try XCTUnwrap(CGImageSourceCreateWithURL(result as CFURL, nil)) + XCTAssertEqual(CGImageSourceGetCount(normalized), 1) + } + + private func assertSanitized(_ url: URL) throws { + XCTAssertEqual(try EvidenceFiles.imageExtension(url), "jpg") + let source = try XCTUnwrap(CGImageSourceCreateWithURL(url as CFURL, nil)) + let p = try XCTUnwrap(CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]) + XCTAssertNil(p[kCGImagePropertyGPSDictionary]); XCTAssertNil(p[kCGImagePropertyIPTCDictionary]) + let exif = p[kCGImagePropertyExifDictionary] as? [CFString: Any] + XCTAssertNil(exif?[kCGImagePropertyExifDateTimeOriginal]) + XCTAssertEqual(CGImageSourceGetCount(source), 1) + } + private func encoded(_ type: UTType) throws -> Data { + let context = try XCTUnwrap(CGContext(data: nil, width: 1032, height: 733, bitsPerComponent: 8, + bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)) + context.setFillColor(CGColor(gray: 1, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 1032, height: 733)) + let data = NSMutableData() + let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil)) + CGImageDestinationAddImage(destination, try XCTUnwrap(context.makeImage()), [kCGImagePropertyOrientation: 6, kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 10.7, kCGImagePropertyGPSLatitudeRef: "N"], kCGImagePropertyExifDictionary: [kCGImagePropertyExifDateTimeOriginal: "2026:11:14 10:00:00"]] as CFDictionary) + XCTAssertTrue(CGImageDestinationFinalize(destination)) + return data as Data + } +} diff --git a/Tests/PayrollTests.swift b/Tests/PayrollTests.swift new file mode 100644 index 0000000..89f84cb --- /dev/null +++ b/Tests/PayrollTests.swift @@ -0,0 +1,141 @@ +import XCTest +@testable import SweepCore + +final class PayrollTests: XCTestCase { + func testNewMonthCarriesOnlyPolicyAndKeepsRecordedMonthIndependent() throws { + let first = ready(date()); var book = PayrollBook(); try book.put(first) + var next = book.period(date(2026, 10)) + XCTAssertEqual(next.policy, first.policy); XCTAssertTrue(next.entries.isEmpty) + XCTAssertNil(next.fuel); XCTAssertTrue(next.advances.isEmpty) + try book.put(next) + var changed = first; changed.policy.meal = 99_000; try book.put(changed) + next = book.period(date(2026, 10)) + XCTAssertEqual(next.policy.meal, 30_000) + } + func date(_ year: Int = 2026, _ month: Int = 9, _ day: Int = 1) -> Date { + PayrollDates.calendar.date(from: DateComponents(year: year, month: month, day: day, hour: 12))! + } + func ready(_ month: Date) -> PayrollMonth { + var p = PayrollMonth(month: DeliveryMonth.start(month)) + p.policy.weekdays = [2, 3, 4, 5, 6, 7]; p.policy.confirmed = true + p.policy.fuelType = "RON95"; p.policy.fuelRegion = "Vùng 1" + p.fuel = PayrollFuel(price: 27_008, effectiveDay: PayrollDates.fuelDay(month), source: "Mẫu công ty") + p.entries = PayrollDates.days(month).map { AttendanceEntry(day: $0, state: .off) } + return p + } + func testSalarySampleMatchesAndCustomerMoneyNeverBecomesSalary() throws { + var ledger = DeliveryLedger(), p = ready(date()) + for i in 0..<24 { p.entries[i].state = .work } + for i in 0..<92 { + var order = DeliveryOrder(code: "PAY-\(i)", customer: "Khách", total: 1_000_000) + order.evidence = [DeliveryEvidence(role: .invoice, filename: UUID().uuidString + ".jpg", sha256: String(repeating: "a", count: 64), bytes: 100)] + let id = try ledger.insert(order); try ledger.sign(id, at: date()) + } + p.advances = [SalaryAdvance(day: date(), amount: 3_000_000, note: "Tạm ứng")] + let result = PayrollCalculation(ledger: ledger, period: p) + XCTAssertEqual(result.plannedUnits, 48); XCTAssertEqual(result.workUnits, 48) + XCTAssertEqual(result.commissions, 92); XCTAssertEqual(result.fee, 460_000) + XCTAssertEqual(result.fuel, 1_944_576); XCTAssertEqual(result.net, 6_636_576) + } + func testExactlyThreeDaysRetainsAttendanceAndMoreThanThreeLosesIt() { + var p = ready(date()) + p.entries[0].state = .leave; p.entries[1].state = .leave; p.entries[2].state = .leave + XCTAssertEqual(PayrollCalculation(ledger: DeliveryLedger(), period: p).attendance, 500_000) + p.entries[3].state = .half + XCTAssertEqual(PayrollCalculation(ledger: DeliveryLedger(), period: p).attendance, 0) + } + func testLeaveHasNoDailyAllowancesAndHalfDayIsExact() { + var p = ready(date()) + p.entries[0].state = .work; p.entries[1].state = .leave; p.entries[2].state = .half + let r = PayrollCalculation(ledger: DeliveryLedger(), period: p) + XCTAssertEqual(r.workUnits, 3); XCTAssertEqual(r.leaveUnits, 3) + XCTAssertEqual(r.meal, 45_000); XCTAssertEqual(r.maintenance, 37_500); XCTAssertEqual(r.fuel, 121_536) + } + func testMonthEndAndFuelDatesHandle31AndLeapFebruary() { + XCTAssertEqual(PayrollDates.calendar.component(.day, from: PayrollDates.closeDay(date(2026, 1))), 31) + XCTAssertEqual(PayrollDates.calendar.component(.day, from: PayrollDates.fuelDay(date(2026, 1))), 30) + XCTAssertEqual(PayrollDates.calendar.component(.day, from: PayrollDates.closeDay(date(2028, 2))), 29) + XCTAssertEqual(PayrollDates.calendar.component(.day, from: PayrollDates.fuelDay(date(2026, 2))), 28) + } + func testClosingOn30FailsFor31DayMonthAndSnapshotCannotBeOverwritten() throws { + let month = date(2026, 1); var ledger = DeliveryLedger(); var p = ready(month) + p.entries[0].state = .work + try ledger.changePayroll("Cấu hình") { try $0.put(p) } + XCTAssertThrowsError(try ledger.closePayroll(month, now: date(2026, 1, 30))) + try ledger.closePayroll(month, now: date(2026, 1, 31)) + let frozen = try XCTUnwrap(ledger.payroll?.closed(month)) + XCTAssertThrowsError(try ledger.markAttendance(date(2026, 1, 10), state: .work)) + XCTAssertThrowsError(try ledger.reopenPayroll(month, reason: " ")) + let before = ledger + try ledger.reopenPayroll(month, reason: "Bổ sung ngày công") + try ledger.markAttendance(date(2026, 1, 10), state: .work) + try ledger.validateAppendOnly(from: before) + XCTAssertEqual(ledger.payroll?.snapshots.first, frozen) + var invalid = ledger; invalid.payroll?.snapshots[0].calculation.base += 1 + XCTAssertThrowsError(try invalid.validateAppendOnly(from: ledger)) + } + func testAttendanceIsIdempotentNoFutureAndNoAutomaticAbsence() throws { + var ledger = DeliveryLedger() + try ledger.markAttendance(date(), state: .work) + try ledger.markAttendance(date(), state: .half) + XCTAssertEqual(ledger.payroll?.period(date()).entries.count, 1) + XCTAssertThrowsError(try ledger.markAttendance(date(2099), state: .work)) + var p = PayrollMonth(month: DeliveryMonth.start(date())); p.policy.weekdays = [1, 2, 3, 4, 5, 6, 7] + let r = PayrollCalculation(ledger: ledger, period: p) + XCTAssertEqual(r.leaveUnits, 0); XCTAssertEqual(r.missingDays, 30) + } + func testAnnual12DayLimitDoesNotDiscardRealLeaveAndDoesNotRollIntoNextYear() throws { + var ledger = DeliveryLedger() + try ledger.changePayroll("Số đầu kỳ") { $0.openingLeaveUnits["2026"] = 22 } + try ledger.markAttendance(date(), state: .leave) + XCTAssertEqual(ledger.payroll?.annualLeaveUnits(year: 2026), 24) + try ledger.markAttendance(date(2026, 9, 2), state: .half) + XCTAssertEqual(ledger.payroll?.annualLeaveUnits(year: 2026), 25) + XCTAssertEqual(ledger.payroll?.annualLeaveUnits(year: 2027), 0) + try ledger.validate() + } + func testPayrollBackupAndLegacyLedgerRoundTrip() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + var ledger = DeliveryLedger(); try ledger.markAttendance(date(), state: .work) + let file = root.appendingPathComponent("test.sweepbackup") + try DeliveryBackup.write(ledger, evidence: root, to: file) + let restored = try DeliveryBackup.prepare(file, staging: root.appendingPathComponent("check")) + XCTAssertEqual(restored.ledger, ledger) + var object = try JSONSerialization.jsonObject(with: DeliveryCoding.encode(DeliveryLedger())) as! [String: Any] + object["schema"] = 2; object.removeValue(forKey: "payroll") + let legacy = try DeliveryCoding.decode(DeliveryLedger.self, from: JSONSerialization.data(withJSONObject: object)) + XCTAssertNil(legacy.payroll); try legacy.validate() + } + func testWrongFuelDayOrMissingWorkSchedulePreventsClose() throws { + var p = ready(date()); p.fuel?.effectiveDay = date(2026, 9, 29) + var b = PayrollBook(); b.months = [p] + XCTAssertThrowsError(try b.validate()) + p = ready(date()); p.policy.confirmed = false + var ledger = DeliveryLedger(); try ledger.changePayroll("Cấu hình") { try $0.put(p) } + XCTAssertThrowsError(try ledger.closePayroll(date(), now: date(2026, 9, 30))) + } + func testRemindersAreEveryThreeHoursAndRenewalChangesTheWholeSchedule() { + let expiry = date(), now = expiry.addingTimeInterval(-30 * 3600) + let times = SigningExpiry.reminders(expiry: expiry, now: now) + XCTAssertEqual(times.count, 48); XCTAssertEqual(times.first, expiry.addingTimeInterval(-24 * 3600)) + XCTAssertEqual(times[1].timeIntervalSince(times[0]), 3 * 3600) + XCTAssertTrue(SigningExpiry.reminders(expiry: expiry, now: expiry.addingTimeInterval(3600)).allSatisfy { $0 > expiry }) + XCTAssertNotEqual(times, SigningExpiry.reminders(expiry: expiry.addingTimeInterval(7 * 86400), now: now)) + } + func testEmbeddedProfileReadAndUnsupportedProfilesFallBack() throws { + let expiration = date() + let xml = try PropertyListSerialization.data(fromPropertyList: ["CreationDate": expiration.addingTimeInterval(-86400), "ExpirationDate": expiration], format: .xml, options: 0) + XCTAssertEqual(SigningExpiry.expiration(in: Data([0x30, 0x82]) + xml + Data([0])), expiration) + XCTAssertNil(SigningExpiry.expiration(in: Data("broken".utf8))) + XCTAssertNil(SigningExpiry.expiration(in: try PropertyListSerialization.data(fromPropertyList: ["ExpirationDate": "bad"], format: .xml, options: 0))) + } + func testContactsNormalizePhonesAndOnlyOpenZaloHosts() { + XCTAssertEqual(ContactLinks.phoneKey("+84 903 123 456"), ContactLinks.phoneKey("0903123456")) + XCTAssertNotNil(ContactLinks.zalo("https://zalo.me/0903123456")) + XCTAssertNil(ContactLinks.zalo("https://zalo.me.example.com/fake")) + XCTAssertNil(ContactLinks.zalo("https://zalo.me@evil.com/fake")) + XCTAssertNil(ContactLinks.zalo("file:///tmp/image.png")) + } +} diff --git a/Tests/ReleaseReadinessTests.swift b/Tests/ReleaseReadinessTests.swift new file mode 100644 index 0000000..33451cd --- /dev/null +++ b/Tests/ReleaseReadinessTests.swift @@ -0,0 +1,85 @@ +import XCTest +@testable import SweepCore + +final class ReleaseReadinessTests: XCTestCase { + func testImageOnlyDraftRestoresAfterUnrelatedEditAndRoundTrip() throws { + var ledger = try transferredOrder() + let order = ledger.orders[0], selected = [order.evidence[0].id] + try ledger.saveReportDraft(order.id, text: order.shareText(), evidenceIDs: selected) + ledger.orders[0].address = "Địa chỉ cập nhật"; ledger.orders[0].revision += 1 + let restored = try DeliveryCoding.decode(DeliveryLedger.self, from: DeliveryCoding.encode(ledger)) + XCTAssertEqual(restored.orders[0].reportComposition.text, order.shareText()) + XCTAssertEqual(restored.orders[0].reportComposition.evidenceIDs, selected) + XCTAssertThrowsError(try ledger.prepareReport(order.id, text: order.shareText(), evidenceIDs: selected)) + } + + func testReopeningSentReportDoesNotCreateAnUnsentCopy() throws { + var ledger = try transferredOrder(); let id = ledger.orders[0].id + let composition = ledger.orders[0].reportComposition + try ledger.saveReportDraft(id, text: composition.text, evidenceIDs: composition.evidenceIDs) + let report = try ledger.prepareReport(id, text: composition.text, evidenceIDs: composition.evidenceIDs) + try ledger.acknowledgeReport(id, reportID: report.id) + ledger.orders[0].phone = "0901234567"; ledger.orders[0].revision += 1 + let reopened = ledger.orders[0].reportComposition + try ledger.saveReportDraft(id, text: reopened.text, evidenceIDs: reopened.evidenceIDs) + XCTAssertTrue(ledger.orders[0].reportSent) + let repeated = try ledger.prepareReport(id, text: reopened.text, evidenceIDs: reopened.evidenceIDs) + XCTAssertEqual(repeated.id, report.id); XCTAssertEqual(ledger.orders[0].reports.count, 1) + } + + func testChangedDraftCannotAcknowledgeOldSharedContent() throws { + var ledger = try transferredOrder(); let id = ledger.orders[0].id + let original = ledger.orders[0].reportComposition + let report = try ledger.prepareReport(id, text: original.text, evidenceIDs: original.evidenceIDs) + try ledger.saveReportDraft(id, text: "Khách đã chuyển, gửi lại bằng chứng", evidenceIDs: original.evidenceIDs) + XCTAssertThrowsError(try ledger.acknowledgeReport(id, reportID: report.id)) + XCTAssertFalse(ledger.orders[0].reportSent) + let updated = try ledger.prepareReport(id, text: ledger.orders[0].reportComposition.text, evidenceIDs: original.evidenceIDs) + try ledger.acknowledgeReport(id, reportID: updated.id) + XCTAssertTrue(ledger.orders[0].reportSent) + } + + func testFinancialChangeDoesNotResurrectAnOldCaption() throws { + var ledger = try transferredOrder(); let id = ledger.orders[0].id + try ledger.saveReportDraft(id, text: "Đã thu đủ", evidenceIDs: ledger.orders[0].defaultShareEvidenceIDs) + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .bank, cash: 0, bank: 700, note: "Sửa khoản thực nhận", at: Date(), route: .transferNow)) + XCTAssertNil(ledger.orders[0].currentReportDraft) + XCTAssertTrue(ledger.orders[0].reportComposition.text.contains("700")) + XCTAssertTrue(ledger.orders[0].reportComposition.text.contains("300")) + } + + func testDifferentCustomersAtSameAddressAreNotMergedAndPhoneFormatsMatch() throws { + var ledger = DeliveryLedger() + let first = DeliveryPlace(customer: "Tiệm Mẫu", phone: "0901234567", address: "12A", kind: "Khách hàng") + var second = first; second.id = UUID(); second.phone = "0907654321" + try ledger.savePlace(first); try ledger.savePlace(second) + XCTAssertEqual(ledger.places?.count, 2) + var equivalent = first; equivalent.id = UUID(); equivalent.phone = "+84 901 234 567" + try ledger.savePlace(equivalent) + XCTAssertEqual(ledger.places?.count, 2) + } + + func testFreightLocationIsLinkedSeparatelyFromInvoiceCustomer() throws { + var ledger = try transferredOrder(); let id = ledger.orders[0].id + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .deferred, cash: 0, bank: 0, note: "Giao chành", at: Date(), route: .freight)) + let carrier = DeliveryPlace(customer: "Nhà xe Mẫu", phone: "0901234567", address: "Bến xe", kind: "Chành xe", latitude: 10.7, longitude: 106.7) + try ledger.savePlace(carrier) + XCTAssertFalse(ledger.hasPlace(for: ledger.orders[0])) + ledger.orders[0].freightPlaceID = carrier.id + XCTAssertTrue(ledger.hasPlace(for: ledger.orders[0])) + XCTAssertEqual(ledger.orders[0].customer, "Khách Mẫu") + XCTAssertNotEqual(ledger.orders[0].address, carrier.address) + } + + private func transferredOrder() throws -> DeliveryLedger { + var ledger = DeliveryLedger() + var order = DeliveryOrder(code: UUID().uuidString, customer: "Khách Mẫu", total: 1000) + order.evidence = [file(.invoice), file(.transfer)] + let id = try ledger.insert(order); try ledger.sign(id, at: Date()) + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .bank, cash: 0, bank: 1000, note: "", at: Date(), route: .transferNow)) + return ledger + } + private func file(_ role: EvidenceRole) -> DeliveryEvidence { + DeliveryEvidence(role: role, filename: UUID().uuidString + ".jpg", sha256: String(repeating: "a", count: 64), bytes: 100) + } +} diff --git a/Tests/ShareAndQRTests.swift b/Tests/ShareAndQRTests.swift new file mode 100644 index 0000000..007388a --- /dev/null +++ b/Tests/ShareAndQRTests.swift @@ -0,0 +1,121 @@ +import XCTest +import Foundation +import CoreGraphics +import ImageIO +import UniformTypeIdentifiers +@testable import SweepCore + +final class ShareAndQRTests: XCTestCase { + private let account = VietQRAccount(bankID: "VCB", accountNumber: "0012345678", accountName: "CONG TY THU NGHIEM") + + func testQRContainsExactIntegerAmountAccountAndOrderCode() throws { + let order = DeliveryOrder(code: "3877", customer: "Không gửi tên khách", total: 5_350_000) + let url = try VietQR.url(account: account, order: order, amount: order.remaining) + let parts = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)) + XCTAssertEqual(parts.scheme, "https"); XCTAssertEqual(parts.host, "img.vietqr.io") + XCTAssertEqual(parts.path, "/image/VCB-0012345678-qr_only.svg") + let fields = Dictionary(uniqueKeysWithValues: (parts.queryItems ?? []).map { ($0.name, $0.value ?? "") }) + XCTAssertEqual(fields, ["amount": "5350000", "addInfo": "TT DON 3877", "accountName": account.accountName]) + XCTAssertFalse(url.absoluteString.contains("Không")) + } + + func testQRUsesRemainderAndAllowsReissuingWithoutChangingPayments() throws { + var order = DeliveryOrder(code: "DH-12", customer: "Test", total: 2_165_000) + order.settlements = [Settlement(outcome: .delivered, mode: .mixed, cash: 600_000, bank: 1_500_000, note: "", at: Date())] + XCTAssertEqual(order.remaining, 65_000) + XCTAssertEqual(VietQR.suggestedAmount(for: order), 65_000) + XCTAssertNoThrow(try VietQR.url(account: account, order: order, amount: 65_000)) + XCTAssertNoThrow(try VietQR.url(account: account, order: order, amount: order.total)) + for amount in [Int64(-1), 0, order.total + 1, VND.maximum + 1] { XCTAssertThrowsError(try VietQR.url(account: account, order: order, amount: amount)) } + order.voidReason = "Hủy phiếu" + XCTAssertThrowsError(try VietQR.url(account: account, order: order, amount: 1)) + order.voidReason = nil; order.settlements[0].cash = 665_000 + let before = order + XCTAssertEqual(order.remaining, 0) + XCTAssertEqual(VietQR.suggestedAmount(for: order), 1_500_000) + XCTAssertNoThrow(try VietQR.url(account: account, order: order, amount: order.total)) + XCTAssertEqual(order, before) + } + + func testFullyVerifiedOrderStillHasAnAmountForShowingItsQRAgain() throws { + var order = DeliveryOrder(code: "DEMO", customer: "Test", total: 123_000) + let payment = Settlement(outcome: .delivered, mode: .bank, cash: 0, bank: 123_000, note: "", at: Date()) + order.settlements = [payment] + order.bankChecks = [BankVerification(settlementID: payment.id, amount: payment.bank, note: "Đã kiểm tra")] + let before = order + XCTAssertEqual(VietQR.suggestedAmount(for: order), order.total) + XCTAssertNoThrow(try VietQR.url(account: account, order: order, amount: order.total)) + XCTAssertEqual(order, before) + } + + func testQRRejectsPathInjectionAndNormalizesTransferNote() throws { + for bank in ["../VCB", "VCB?amount=1", "VCB/ABC", "", "VCB-1"] { + XCTAssertThrowsError(try VietQRAccount(bankID: bank, accountNumber: "123", accountName: "TEST").validate()) + } + for number in ["../123", "123&amount=1", "123 456", String(repeating: "1", count: 20)] { + XCTAssertThrowsError(try VietQRAccount(bankID: "VCB", accountNumber: number, accountName: "TEST").validate()) + } + XCTAssertEqual(VietQR.transferNote(code: "Đơn #38/77 & thử"), "TT DON DON 38 77 THU") + XCTAssertLessThanOrEqual(VietQR.transferNote(code: String(repeating: "A", count: 100)).count, 50) + } + + func testOldLedgerWithoutVietQRStillLoadsAndNewSettingsRoundTrip() throws { + let data = try DeliveryCoding.encode(DeliveryLedger()) + var json = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + var settings = try XCTUnwrap(json["settings"] as? [String: Any]); settings.removeValue(forKey: "vietQR"); json["settings"] = settings + let old = try DeliveryCoding.decode(DeliveryLedger.self, from: JSONSerialization.data(withJSONObject: json)) + XCTAssertNil(old.settings.vietQR); XCTAssertEqual(old.settings.fee, 5_000) + var next = old; next.settings.vietQR = account + try next.validate() + XCTAssertEqual(try DeliveryCoding.decode(DeliveryLedger.self, from: DeliveryCoding.encode(next)), next) + } + + func testShareSurvivesRelaunchAndCopiesSourceBeforeDeletingPending() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let source = root.appendingPathComponent("source.png"); try png().write(to: source) + let inbox = SharedInvoiceInbox(directory: root.appendingPathComponent("Inbox")) + let queued = try inbox.add(source) + try FileManager.default.removeItem(at: source) + let reopened = SharedInvoiceInbox(directory: inbox.directory) + let scan = try reopened.scan(); XCTAssertEqual(scan.items.map(\.id), [queued.id]); XCTAssertTrue(scan.warnings.isEmpty) + let item = try XCTUnwrap(scan.items.first) + try EvidenceFiles.verify(item.evidence, directory: item.directory) + let evidence = root.appendingPathComponent("Evidence"); try FileManager.default.createDirectory(at: evidence, withIntermediateDirectories: true) + let file = try EvidenceFiles.importImage(item.image, role: .invoice, directory: evidence) + var order = DeliveryOrder(code: "3877", customer: "Test", total: 5_350_000); order.sourceID = item.sourceID; order.evidence = [file] + let db = try DeliveryDatabase(url: root.appendingPathComponent("ledger.sqlite")) + var ledger = DeliveryLedger(); let id = try ledger.insert(order); try db.save(ledger) + // A crash after commit but before queue cleanup cannot create a second order. + var retry = try db.load(); XCTAssertEqual(try retry.insert(order), id); XCTAssertEqual(retry.orders.count, 1) + try reopened.remove(item) + XCTAssertTrue(try reopened.scan().items.isEmpty) + try EvidenceFiles.verify(file, directory: evidence) + } + + func testBrokenShareDoesNotHideValidImageAndRejectsNonImage() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let source = root.appendingPathComponent("source.png"); try png().write(to: source) + let inbox = SharedInvoiceInbox(directory: root.appendingPathComponent("Inbox")); let valid = try inbox.add(source) + let bad = inbox.directory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: bad, withIntermediateDirectories: true) + try Data("invalid".utf8).write(to: bad.appendingPathComponent("manifest.json")) + let scan = try inbox.scan(); XCTAssertEqual(scan.items.map(\.id), [valid.id]); XCTAssertEqual(scan.warnings.count, 1) + try Data("not an image".utf8).write(to: source) + XCTAssertThrowsError(try inbox.add(source)) + XCTAssertEqual(try inbox.scan().items.count, 1) + let staging = try FileManager.default.contentsOfDirectory(atPath: inbox.directory.path).filter { $0.hasPrefix(".staging-") } + XCTAssertTrue(staging.isEmpty) + } + + private func png() throws -> Data { + let context = try XCTUnwrap(CGContext(data: nil, width: 10, height: 10, bitsPerComponent: 8, bytesPerRow: 40, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) + let image = try XCTUnwrap(context.makeImage()); let data = NSMutableData() + let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)) + CGImageDestinationAddImage(destination, image, nil); XCTAssertTrue(CGImageDestinationFinalize(destination)) + return data as Data + } +} diff --git a/Tests/VerifiedResetTests.swift b/Tests/VerifiedResetTests.swift new file mode 100644 index 0000000..64ee2ce --- /dev/null +++ b/Tests/VerifiedResetTests.swift @@ -0,0 +1,34 @@ +import XCTest +import CoreGraphics +import ImageIO +import UniformTypeIdentifiers +@testable import SweepCore + +final class VerifiedResetTests: XCTestCase { + func testOnlyVerifiedMatchingBackupCanResetLedgerAndRestoreIt() throws { + let fm = FileManager.default, root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let image = root.appendingPathComponent("source.png") + let ctx = try XCTUnwrap(CGContext(data: nil, width: 16, height: 16, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)) + let out = try XCTUnwrap(CGImageDestinationCreateWithURL(image as CFURL, UTType.png.identifier as CFString, 1, nil)) + CGImageDestinationAddImage(out, try XCTUnwrap(ctx.makeImage()), nil); XCTAssertTrue(CGImageDestinationFinalize(out)) + var order = DeliveryOrder(code: "RESET", customer: "Khách", total: 1000) + order.evidence = [try EvidenceFiles.importImage(image, role: .invoice, directory: root)] + var ledger = DeliveryLedger(); let id = try ledger.insert(order); try ledger.sign(id, at: Date()) + try ledger.settle(id, value: Settlement(outcome: .delivered, mode: .cash, cash: 1000, bank: 0, note: "", at: Date(), route: .cashFull)) + let db = try DeliveryDatabase(url: root.appendingPathComponent("test.sqlite")); try db.save(ledger) + let backup = root.appendingPathComponent("test.sweepbackup") + try DeliveryBackup.write(ledger, evidence: root, to: backup) + let verified = try DeliveryBackup.prepare(backup, staging: root.appendingPathComponent("verified")) + var updated = ledger; try updated.handover(100, at: Date(), note: "Nộp") + try db.save(updated) + XCTAssertThrowsError(try db.reset(using: verified)); XCTAssertEqual(try db.load(), updated) + try db.save(ledger, replacing: true) + try db.reset(using: verified) + XCTAssertEqual(try db.load(), DeliveryLedger()) + XCTAssertEqual(verified.ledger.cashHeld, 1000) + try db.save(verified.ledger, replacing: true); XCTAssertEqual(try db.load(), ledger) + try EvidenceFiles.verify(order.evidence[0], directory: verified.staging) + } +} diff --git a/Tools/make_icon.py b/Tools/make_icon.py index 8cb2cd7..1913122 100644 --- a/Tools/make_icon.py +++ b/Tools/make_icon.py @@ -1,25 +1,12 @@ -"""Regenerate the code-drawn Sweep app icon (development tool; requires Pillow).""" +"""Build the iOS icon from Sếp Sen's supplied art, without redrawing/cropping the character.""" from pathlib import Path import json -from PIL import Image, ImageDraw - +from PIL import Image root = Path(__file__).resolve().parents[1] -size = 1024 -image = Image.new('RGB', (size, size)) -pixels = image.load() -for y in range(size): - for x in range(size): - t = (x + y) / (2 * (size - 1)) - pixels[x, y] = tuple(round(a + (b - a) * t) for a, b in zip((5, 63, 48), (44, 204, 116))) -draw = ImageDraw.Draw(image) -# Three sweeping strokes and a small glint; no text or platform-specific glyphs. -for box, width in [((180, 260, 850, 790), 48), ((240, 355, 825, 815), 43), ((310, 450, 800, 840), 38)]: - draw.arc(box, start=30, end=160, fill=(255, 255, 255), width=width) -draw.line([(389, 457), (627, 239)], fill=(255, 255, 255), width=55) -draw.ellipse((599, 213, 654, 268), fill=(255, 255, 255)) -draw.polygon([(758, 234), (773, 279), (817, 294), (773, 309), (758, 354), (743, 309), (699, 294), (743, 279)], fill=(214, 255, 208)) +source = Image.open(root / 'Design/AppIcon-Source.jpeg').convert('RGB') +source.thumbnail((1024, 1024), Image.Resampling.LANCZOS) +image = Image.new('RGB', (1024, 1024), '#336C68') +image.paste(source, ((1024-source.width)//2, (1024-source.height)//2)) target = root / 'Sweep/Assets.xcassets/AppIcon.appiconset' -target.mkdir(parents=True, exist_ok=True) image.save(target / 'AppIcon.png', optimize=True) -(target / 'Contents.json').write_text(json.dumps({'images': [{'filename': 'AppIcon.png', 'idiom': 'universal', 'platform': 'ios', 'size': '1024x1024'}], 'info': {'author': 'xcode', 'version': 1}}, indent=2) + '\n') -(target.parent / 'Contents.json').write_text(json.dumps({'info': {'author': 'xcode', 'version': 1}}, indent=2) + '\n') +(target / 'Contents.json').write_text(json.dumps({'images':[{'filename':'AppIcon.png','idiom':'universal','platform':'ios','size':'1024x1024'}],'info':{'author':'xcode','version':1}}, indent=2)+'\n') diff --git a/Tools/package_ipa.py b/Tools/package_ipa.py new file mode 100644 index 0000000..b8064c4 --- /dev/null +++ b/Tools/package_ipa.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Retain entitlement metadata for AltStore to provision, then package an IPA. + +Ad-hoc signatures carry the requested rights; they do not authorize installation +on an iPhone. AltStore must issue profiles and replace both signatures. +""" +import argparse +import hashlib +import json +import plistlib +import shutil +import struct +import subprocess +import tempfile +import zipfile +from pathlib import Path + + +def signed_entitlements(binary: Path) -> dict: + data = binary.read_bytes() + if struct.unpack_from("III", signature) + if magic != 0xFADE0CC0 or total > len(signature): + raise ValueError("Invalid code-signature superblob") + for index in range(blobs): + slot, blob_offset = struct.unpack_from(">II", signature, 12 + 8 * index) + if slot == 5: # CSSLOT_ENTITLEMENTS + blob_magic, blob_length = struct.unpack_from(">II", signature, blob_offset) + if blob_magic != 0xFADE7171 or blob_offset + blob_length > total: + raise ValueError("Invalid XML entitlement blob") + return plistlib.loads(signature[blob_offset + 8:blob_offset + blob_length].rstrip(b"\0")) + if size < 8: + raise ValueError("Invalid Mach-O load command") + position += size + raise ValueError(f"Missing signed entitlement metadata: {binary.name}") + + +def package(app: Path, output: Path) -> dict: + output = output.resolve(); output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="sweep-package-") as temp: + root = Path(temp); payload = root / "Payload"; payload.mkdir() + copied = payload / app.name; shutil.copytree(app, copied, symlinks=True) + bundles = [copied / "PlugIns/SweepShare.appex", copied] + infos = [plistlib.loads((bundle / "Info.plist").read_bytes()) for bundle in bundles] + group = infos[-1]["SweepAppGroupIdentifier"] + if not group.startswith("group.") or any(info["SweepAppGroupIdentifier"] != group for info in infos): + raise ValueError("App and extension must request the same group") + if infos[0]["CFBundleShortVersionString"] != infos[1]["CFBundleShortVersionString"]: + raise ValueError("App/extension versions differ") + requested = {"com.apple.security.application-groups": [group]} + entitlement_file = root / "entitlements.plist" + entitlement_file.write_bytes(plistlib.dumps(requested)) + verified = [] + for bundle, info in zip(bundles, infos): + subprocess.run(["/usr/bin/codesign", "--force", "--sign", "-", "--timestamp=none", + "--generate-entitlement-der", "--entitlements", str(entitlement_file), str(bundle)], check=True) + actual = signed_entitlements(bundle / info["CFBundleExecutable"]) + if actual.get("com.apple.security.application-groups") != [group]: + raise ValueError(f"Signed group declaration missing in {bundle.name}") + verified.append({"bundle_id": info["CFBundleIdentifier"], "app_groups": actual["com.apple.security.application-groups"]}) + subprocess.run(["/usr/bin/codesign", "--verify", "--deep", "--strict", str(copied)], check=True) + with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive: + for file in sorted(payload.rglob("*")): + if file.is_file(): + archive.write(file, file.relative_to(root).as_posix()) + with zipfile.ZipFile(output) as archive: + if archive.testzip() is not None: + raise ValueError("IPA CRC validation failed") + digest = hashlib.sha256(output.read_bytes()).hexdigest() + (output.parent / "SHA256.txt").write_text(f"{digest} {output.name}\n") + result = {"ipa": output.name, "version": infos[-1]["CFBundleShortVersionString"], + "build": infos[-1]["CFBundleVersion"], "sha256": digest, "bundles": verified, + "signing": "ad-hoc entitlement metadata only; AltStore signing and profiles required for installation"} + (output.parent / "SIGNING-METADATA.json").write_text(json.dumps(result, indent=2) + "\n") + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--app", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(package(args.app, args.output), indent=2)) diff --git a/UITests/SweepUITests.swift b/UITests/SweepUITests.swift index ef1971b..22d5709 100644 --- a/UITests/SweepUITests.swift +++ b/UITests/SweepUITests.swift @@ -1,6 +1,167 @@ import XCTest final class SweepUITests: XCTestCase { + func testUpdate02CompactContactsAndPlaces() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery", "--update02-ui-testing"] + app.launch() + XCTAssertTrue(app.tabBars.buttons["Công cụ"].waitForExistence(timeout: 20)); app.tabBars.buttons["Công cụ"].tap() + app.buttons["Liên hệ"].tap() + let call = app.buttons["contact.call"].firstMatch + XCTAssertTrue(call.waitForExistence(timeout: 10)) + XCTAssertLessThanOrEqual(call.frame.width, 60); XCTAssertGreaterThanOrEqual(call.frame.width, 44) + XCTAssertGreaterThan(call.frame.midX, app.frame.width * 0.7) + XCTAssertTrue(app.staticTexts["0900000001"].exists) + attach(app, name: "update02-compact-contacts") + app.navigationBars.buttons.element(boundBy: 0).tap() + app.buttons["Vị trí"].tap() + XCTAssertTrue(app.buttons["Google Maps"].waitForExistence(timeout: 10)) + XCTAssertLessThanOrEqual(app.buttons["contact.call"].firstMatch.frame.width, 60) + attach(app, name: "update02-compact-places") + } + func testUpdate02AttendanceCalendarSavesAndPersists() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery"] + app.launch() + XCTAssertTrue(app.tabBars.buttons["Công cụ"].waitForExistence(timeout: 20)); app.tabBars.buttons["Công cụ"].tap() + app.buttons["tool.payroll"].tap() + var calendar = Calendar(identifier: .gregorian); calendar.timeZone = TimeZone(identifier: "Asia/Ho_Chi_Minh")! + let today = app.buttons["attendance.day.\(calendar.component(.day, from: Date()))"] + XCTAssertTrue(today.waitForExistence(timeout: 10)); today.tap() + XCTAssertTrue(app.buttons["attendance.save"].waitForExistence(timeout: 10)); app.buttons["attendance.save"].tap() + XCTAssertTrue(app.staticTexts["payroll.net"].waitForExistence(timeout: 10)) + attach(app, name: "update02-attendance-and-salary") + app.terminate() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing"] + app.launch(); app.tabBars.buttons["Công cụ"].tap(); app.buttons["tool.payroll"].tap() + XCTAssertTrue(today.waitForExistence(timeout: 10)); XCTAssertTrue(today.label.contains("Đi làm")) + } + func testReportImageSelectionAndCompactTransferCaption() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery", "--seed-delivery", "--qr-ui-testing"] + app.launch() + let order = app.buttons["order.TEST-001"] + XCTAssertTrue(order.waitForExistence(timeout: 20)); order.tap() + reveal(app.buttons["order.report"], in: app); app.buttons["order.report"].tap() + let caption = app.textViews["report.text"] + XCTAssertTrue(caption.waitForExistence(timeout: 10)) + XCTAssertEqual(caption.value as? String, "Khách thử nghiệm đã chuyển khoản 2.165.000₫") + let invoice = app.buttons["report.remove.Phiếu nội bộ"] + let transfer = app.buttons["report.remove.Ảnh giao dịch"] + XCTAssertTrue(invoice.exists); XCTAssertTrue(transfer.exists) + XCTAssertFalse(app.buttons["report.remove.Phiếu khách ký"].exists) + transfer.tap(); XCTAssertFalse(transfer.exists) + // Image-only edits must survive leaving the composer without changing the caption. + app.navigationBars["Chia sẻ đơn"].buttons.element(boundBy: 0).tap() + reveal(app.buttons["order.report"], in: app); app.buttons["order.report"].tap() + XCTAssertTrue(invoice.waitForExistence(timeout: 10)); XCTAssertFalse(transfer.exists) + app.buttons["report.chooseImages"].tap() + let transferChoice = app.buttons["report.select.Ảnh giao dịch"] + XCTAssertTrue(transferChoice.waitForExistence(timeout: 5)); transferChoice.tap() + XCTAssertFalse(app.buttons["report.select.Phiếu khách ký"].exists) + app.buttons["report.imagesDone"].tap() + let signature = app.buttons["report.remove.Phiếu khách ký"] + XCTAssertFalse(signature.exists) + XCTAssertTrue(transfer.exists); XCTAssertTrue(invoice.exists) + XCTAssertFalse(app.buttons["report.prepare"].exists) + reveal(app.buttons["report.share"], in: app); app.buttons["report.share"].tap() + dismissActivity(in: app) + XCTAssertTrue(app.alerts.buttons["Chưa gửi"].waitForExistence(timeout: 10)); app.alerts.buttons["Chưa gửi"].tap() + XCTAssertTrue(app.buttons["report.ack"].waitForExistence(timeout: 10)); XCTAssertTrue(app.buttons["report.ack"].isEnabled) + XCTAssertFalse(app.buttons["report.remove.Phiếu khách ký"].exists) + attach(app, name: "report-two-selected-images-short-caption") + app.buttons["report.ack"].tap(); app.alerts.buttons["Đúng, đã gửi"].tap() + XCTAssertFalse(app.buttons["report.ack"].isEnabled) + attach(app, name: "report-explicit-sent-confirmation") + } + + func testReconciliationEmptyMonthHasNoFiguresFromAnotherMonth() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery", "--seed-delivery", "--monthly-ui-testing"] + app.launch() + XCTAssertTrue(app.buttons["order.TEST-001"].waitForExistence(timeout: 20)) + app.tabBars.buttons["Lịch sử"].tap() + assertRow("audit.count", contains: "1", in: app) + assertRow("audit.cashCollected", contains: "665.000₫", in: app) + assertRow("audit.cashHanded", contains: "500.000₫", in: app) + assertRow("audit.cashHeld", contains: "165.000₫", in: app) + attach(app, name: "audit-current-month") + app.swipeDown(); app.swipeDown() + app.buttons["audit.previous"].tap() + for id in ["audit.count", "audit.fee", "audit.cashCollected", "audit.cashHanded", "audit.cashDifference"] { + assertRow(id, contains: id == "audit.count" ? "0" : "0₫", in: app) + } + XCTAssertFalse(app.staticTexts["665.000₫"].exists) + attach(app, name: "audit-empty-month-all-zero") + app.swipeDown(); app.swipeDown() + app.buttons["audit.next"].tap() + assertRow("audit.count", contains: "1", in: app) + assertRow("audit.cashCollected", contains: "665.000₫", in: app) + } + + func testIntakeHasOnlyPhotoAndCameraSourcesAtLargeTextSize() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL", "--delivery-ui-testing", "--reset-delivery"] + app.launch() + let newOrder = app.buttons["orders.new"] + XCTAssertTrue(newOrder.waitForExistence(timeout: 20)); newOrder.tap() + XCTAssertTrue(app.alerts.buttons["Đã ký"].waitForExistence(timeout: 5)); app.alerts.buttons["Đã ký"].tap() + let photos = app.buttons["evidence.photos"], camera = app.buttons["evidence.camera"] + XCTAssertTrue(photos.waitForExistence(timeout: 10)); XCTAssertTrue(camera.exists) + XCTAssertTrue(photos.label.contains("Chọn ảnh")); XCTAssertTrue(camera.label.contains("Chụp ảnh")) + XCTAssertFalse(app.buttons["Tệp"].exists) + attach(app, name: "intake-two-photo-sources-large-text") + } + + func testRecordedTransferStillDisplaysQRCode() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery", "--seed-delivery", "--qr-ui-testing"] + app.launch() + let order = app.buttons["order.TEST-001"] + XCTAssertTrue(order.waitForExistence(timeout: 20)); order.tap() + reveal(app.buttons["order.qr"], in: app); app.buttons["order.qr"].tap() + let amount = app.textFields["qr.amount"] + XCTAssertTrue(amount.waitForExistence(timeout: 10)) + XCTAssertEqual(amount.value as? String, "2165000") + reveal(app.buttons["qr.generate"], in: app) + XCTAssertTrue(app.webViews.firstMatch.waitForExistence(timeout: 45)) + waitUntil(app.buttons["qr.generate"], in: app) { $0.exists && $0.isEnabled } + attach(app, name: "qr-recorded-transfer-can-show-again") + } + + func testSharedImageReviewImportQRSetupAndRelaunch() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery", "--shared-ui-testing"] + app.launch() + XCTAssertTrue(app.alerts.buttons["Đã ký"].waitForExistence(timeout: 20)); app.alerts.buttons["Đã ký"].tap() + let code = app.textFields["intake.code"] + XCTAssertTrue(code.waitForExistence(timeout: 20)) + let populated = XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == %@", "TEST-7856"), object: code) + XCTAssertEqual(XCTWaiter.wait(for: [populated], timeout: 40), .completed) + let save = app.buttons["intake.save"] + waitUntil(save, in: app) { $0.exists && $0.isEnabled } + attach(app, name: "share-01-review") + save.tap() + XCTAssertTrue(app.navigationBars["Chi tiết đơn"].waitForExistence(timeout: 20)) + reveal(app.buttons["order.qr"], in: app); app.buttons["order.qr"].tap() + let setup = app.buttons["Thiết lập tài khoản VietQR"] + XCTAssertTrue(setup.waitForExistence(timeout: 10)) + attach(app, name: "share-02-qr-needs-account") + app.terminate() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--shared-ui-testing"] + app.launch() + XCTAssertTrue(app.buttons["order.TEST-7856"].waitForExistence(timeout: 15)) + XCTAssertFalse(app.buttons["orders.shared"].exists) + attach(app, name: "share-03-persisted") + } + func testLaunchNavigationAndPermissionEntry() throws { continueAfterFailure = false let app = XCUIApplication() @@ -50,16 +211,19 @@ final class SweepUITests: XCTestCase { note.tap(); note.typeText("Hen giao lai, da nhan mot phan") dismissKeyboard(in: app) reveal(app.buttons["settle.save"], in: app); app.buttons["settle.save"].tap() + XCTAssertTrue(app.alerts.buttons["Xác nhận lưu"].waitForExistence(timeout: 5)); app.alerts.buttons["Xác nhận lưu"].tap() XCTAssertTrue(app.buttons["order.settle"].waitForExistence(timeout: 5)) reveal(app.buttons["order.report"], in: app); app.buttons["order.report"].tap() - reveal(app.buttons["report.prepare"], in: app); app.buttons["report.prepare"].tap() + reveal(app.buttons["report.share"], in: app); app.buttons["report.share"].tap() + dismissActivity(in: app) + XCTAssertTrue(app.alerts.buttons["Chưa gửi"].waitForExistence(timeout: 10)); app.alerts.buttons["Chưa gửi"].tap() let ack = app.buttons["report.ack"] reveal(ack, in: app); XCTAssertTrue(ack.waitForExistence(timeout: 5)); XCTAssertTrue(ack.isEnabled) // Preparing/sharing is not a sent receipt. Only the explicit user acknowledgement changes this state. attach(app, name: "05-report-awaiting-confirmation") ack.tap(); app.alerts.buttons["Đúng, đã gửi"].tap() XCTAssertTrue(app.buttons["report.ack"].waitForExistence(timeout: 5)); XCTAssertFalse(app.buttons["report.ack"].isEnabled) - app.tabBars.buttons["Đối soát"].tap() + app.tabBars.buttons["Lịch sử"].tap() XCTAssertTrue(app.staticTexts["5.000₫"].firstMatch.waitForExistence(timeout: 5)) attach(app, name: "06-reconciliation") app.terminate() @@ -77,9 +241,10 @@ final class SweepUITests: XCTestCase { let app = XCUIApplication() app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery", "--bill-ui-testing"] app.launch() - app.buttons["orders.bill"].tap() + app.buttons["orders.receive"].tap(); app.buttons["orders.bill"].tap() let candidate = app.buttons["bill.candidate.bill:ui-fixture"] XCTAssertTrue(candidate.waitForExistence(timeout: 15)); candidate.tap() + XCTAssertTrue(app.alerts.buttons["Đã ký"].waitForExistence(timeout: 5)); app.alerts.buttons["Đã ký"].tap() let code = app.textFields["intake.code"] XCTAssertTrue(code.waitForExistence(timeout: 15)) let populated = XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == %@", "TEST-7856"), object: code) @@ -92,7 +257,7 @@ final class SweepUITests: XCTestCase { // LabeledContent exposes its value through the row, not a separate StaticText. // Wait for both sheets to finish dismissing before observing the detail screen. XCTAssertTrue(app.navigationBars["Chi tiết đơn"].waitForExistence(timeout: 20)) - XCTAssertTrue(app.staticTexts["Mã phiếu"].waitForExistence(timeout: 10)) + XCTAssertTrue(app.staticTexts["TEST-7856"].waitForExistence(timeout: 10)) attach(app, name: "09-bill-saved-order") app.terminate() app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--bill-ui-testing"] @@ -100,9 +265,9 @@ final class SweepUITests: XCTestCase { let persisted = app.buttons["order.TEST-7856"] XCTAssertTrue(persisted.waitForExistence(timeout: 15)) XCTAssertEqual(app.buttons.matching(identifier: "order.TEST-7856").count, 1) - XCTAssertTrue(app.staticTexts["Chưa tính công"].firstMatch.exists) + XCTAssertTrue(app.staticTexts["Đã tính công"].firstMatch.exists) attach(app, name: "10-bill-persisted-list") - app.buttons["orders.bill"].tap() + app.buttons["orders.receive"].tap(); app.buttons["orders.bill"].tap() let existing = app.buttons["bill.existing.bill:ui-fixture"] XCTAssertTrue(existing.waitForExistence(timeout: 10)) existing.tap() @@ -113,6 +278,28 @@ final class SweepUITests: XCTestCase { attach(app, name: "11-bill-no-duplicate") } + func testApprovedCashWorkflowAndNewTools() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(vi)", "-AppleLocale", "vi_VN", "--delivery-ui-testing", "--reset-delivery", "--seed-delivery"] + app.launch() + XCTAssertTrue(app.buttons["order.TEST-001"].waitForExistence(timeout: 20)); app.buttons["order.TEST-001"].tap() + reveal(app.buttons["order.sign"], in: app); app.buttons["order.sign"].tap(); app.buttons["sign.confirm"].tap(); app.buttons["sign.save"].tap() + app.swipeDown(); app.swipeDown() + reveal(app.buttons["method.Tiền mặt"], in: app); app.buttons["method.Tiền mặt"].tap() + XCTAssertTrue(app.buttons["flow.cashFull"].waitForExistence(timeout: 10)); app.buttons["flow.cashFull"].tap() + app.alerts.buttons["Đã nhận đủ"].tap() + XCTAssertTrue(app.navigationBars["Chi tiết đơn"].waitForExistence(timeout: 10)) + if app.alerts["Lưu vị trí giao hàng?"].waitForExistence(timeout: 3) { app.alerts.buttons["Để sau"].tap() } + attach(app, name: "approved-cash-full-no-report") + app.tabBars.buttons["Lịch sử"].tap(); assertRow("audit.cashHeld", contains: "2.165.000₫", in: app) + app.tabBars.buttons["Công cụ"].tap() + XCTAssertTrue(app.buttons["Vị trí"].waitForExistence(timeout: 10)); XCTAssertTrue(app.buttons["Dọn dẹp"].exists); XCTAssertTrue(app.buttons["Liên hệ"].exists) + attach(app, name: "approved-seven-svg-tools") + app.buttons["Dọn dẹp"].tap(); XCTAssertTrue(app.buttons["maintenance.reset"].waitForExistence(timeout: 10)) + attach(app, name: "approved-maintenance-backup-before-reset") + } + private func reveal(_ element: XCUIElement, in app: XCUIApplication) { for _ in 0..<8 { if element.exists && element.isHittable { return } @@ -123,6 +310,23 @@ final class SweepUITests: XCTestCase { } } + private func dismissActivity(in app: XCUIApplication) { + let close = app.buttons["Close"] + if close.waitForExistence(timeout: 8), close.isHittable { close.tap(); return } + let localized = app.buttons["Đóng"] + if localized.exists && localized.isHittable { localized.tap(); return } + // The system activity sheet also supports the standard modal dismissal gesture. + app.swipeDown() + } + + private func assertRow(_ id: String, contains text: String, in app: XCUIApplication) { + let row = app.descendants(matching: .any).matching(identifier: id).firstMatch + reveal(row, in: app) + XCTAssertTrue(row.waitForExistence(timeout: 5), id) + let visible = row.label + " " + String(describing: row.value ?? "") + " " + row.staticTexts.allElementsBoundByIndex.map(\.label).joined(separator: " ") + XCTAssertTrue(visible.contains(text), "\(id): \(visible)") + } + private func dismissKeyboard(in app: XCUIApplication) { let done = app.buttons["keyboard.done"] XCTAssertTrue(done.waitForExistence(timeout: 5)) diff --git a/docs/ALTSTORE.md b/docs/ALTSTORE.md new file mode 100644 index 0000000..fd0b267 --- /dev/null +++ b/docs/ALTSTORE.md @@ -0,0 +1,20 @@ +# Shared AltStore catalogue + +Sweep 0.4.0 (7) is published alongside StikDebug VN 3.2.9 (9) in the existing repository catalogue: + +https://raw.githubusercontent.com/Sentechtipsvn/Stikdebug-VN/main/altstore/altstore.json + +The legacy raw URL under dammeiosvn resolves to the same two-app catalogue. The old StikDebug release attachment at releases/latest/download/altstore.json is a StikDebug release snapshot; use the canonical raw URL above for the shared catalogue. + +The Sweep listing uses the exact IPA previously delivered and tested, hosted at an immutable commit: + +https://raw.githubusercontent.com/Sentechtipsvn/Sweep/a8f31f71fd5b12040a321c5f1c748f75c2b4109c/Releases/0.4.0/Sweep-0.4.0-AltStore.ipa + +- App ID: com.sentechtipsvn.sweep; iOS 17.0 minimum; version 0.4.0; build 7. +- Bytes: 1296709. +- SHA-256: 25b01fcd19cc66d84792e9a72d779a14a9526523eb2058477154f75cc92754ef. +- appPermissions lists the App Group entitlement and the exact three camera/Photos privacy descriptions in the IPA. +- Source publication commit: Sentechtipsvn/Stikdebug-VN@4306e18895e0e77c3ad47fd2c8daa4bd03e914c6. +- Validation: downloaded the public IPA and matched its SHA-256; checked versions/build/minimum OS/size/privacy against Info.plist; verified source/app icons and fetched both canonical and legacy raw feeds with both app entries. Existing StikDebug app data is unchanged. + +Keep the Share Extension when AltStore signs and installs the app. Distribution did not rebuild or change the tested application code. diff --git a/docs/RELEASE-0.3.0.md b/docs/RELEASE-0.3.0.md new file mode 100644 index 0000000..872479f --- /dev/null +++ b/docs/RELEASE-0.3.0.md @@ -0,0 +1,37 @@ +# Sweep 0.3.0 — nhận ảnh chia sẻ và VietQR theo đơn + +## Nhận đơn trực tiếp + +- Trong Zalo, mở ảnh phiếu → bảng chia sẻ iOS → Sweep → Gửi đến Sweep. Bản đầu nhận một ảnh tĩnh JPEG/PNG/HEIC mỗi lượt; Sweep hiện trong danh sách ứng dụng ở bảng chia sẻ hệ thống, không phải menu chuyển tiếp nội bộ Zalo. +- Ảnh được sao chép vào hộp thư trên thiết bị, không cần Bill hoặc iCloud. Mở Sweep sẽ tự hiện màn hình nhận đơn và OCR khi có một ảnh chờ. Có nhiều ảnh thì chọn phiếu trong hộp thư. +- Kiểm tra mã phiếu, khách và số tiền rồi nhập bằng màn hình đang có. Hủy màn hình không xóa ảnh chờ. Chỉ sau khi lưu sổ thành công mới xóa bản chờ; nguồn Zalo giữ nguyên. Chưa xác nhận ký nhận thì chưa tính công. +- Mã phiếu trùng cần xác nhận là hồ sơ cũ trước khi bỏ ảnh chờ; không tự ghi đè hoặc tạo thêm công. Kho Bill, ảnh/Tệp/camera, đối soát, sao lưu và công cụ ảnh cũ vẫn giữ. +- Không ép mở app chính từ Share Extension bằng API riêng. iOS chạy giao diện nhận ảnh trong bảng chia sẻ; Sếp mở Sweep để kiểm tra và làm các bước giao hàng. + +## VietQR + +- Cài đặt → Công đơn và QR công ty: nhập mã ngân hàng/BIN, số tài khoản và chủ tài khoản, lưu một lần. +- Chi tiết đơn → QR chuyển khoản: mặc định tổng đơn khi chưa thu, hoặc khoản còn lại theo ghi nhận sau khi đã thu một phần. Có thể sửa số tiền từ 1 đồng đến khoản còn lại. Đơn đã ghi nhận đủ hoặc đã hủy không tạo QR thu thêm. +- Nội dung `TT DON ` được bỏ dấu, bỏ ký tự đặc biệt và giới hạn 50 ký tự. Số tài khoản giữ số 0 đầu; amount gửi là số nguyên VND. +- Dùng Quick Link `https://img.vietqr.io/image/--qr_only.svg` với `amount`, `addInfo`, `accountName`. Không dùng endpoint `/v2/generate` ngừng hỗ trợ từ 01/01/2027 theo thông báo chính thức. +- SVG hiển thị trong app bằng tài liệu cục bộ không JavaScript, không mở Safari. Cache theo toàn bộ tham số, không dùng mã của số tiền/tài khoản cũ khi sửa. Tạo mã mới cần mạng; cache có thể bị iOS dọn. +- VietQR nhận thông tin tài khoản, tên chủ tài khoản, mã phiếu và số tiền. Không gửi ảnh phiếu, tên khách hoặc địa chỉ. Tên chủ tài khoản do người dùng nhập, không tự tra cứu xác minh. +- Tạo/xem QR không ghi nhận tiền, xác nhận chuyển khoản hay đối soát. Sổ/backup cũ thiếu cấu hình VietQR vẫn đọc được; ảnh QR cố định cũ vẫn ở Cài đặt. + +## Cài đặt và ký + +IPA chứa `PlugIns/SweepShare.appex`. Cả app `com.sentechtipsvn.sweep` và extension `com.sentechtipsvn.sweep.share` cần được ký và có cùng App Group `group.com.sentechtipsvn.sweep`. Có thể đổi group bằng build setting `SWEEP_APP_GROUP` nhưng phải thống nhất cả hai provisioning profiles và entitlements. Bản ký lại làm mất quyền App Groups hoặc bỏ extension sẽ không nhận ảnh; app báo lỗi cụ thể, không thông báo đã lưu giả. + +Không chuyển sổ đang dùng sang container mới: SQLite, ảnh chứng từ và bộ sao lưu hiện tại vẫn ở nơi cũ. App Group chỉ chứa ảnh chờ. Ký lại phải giữ bundle ID để cập nhật app đang có; xuất sao lưu sổ và ảnh trước khi thay bản cài. Không gỡ app chứa sổ thật. + +## Phạm vi kiểm chứng + +Đã chạy đạt 32 kiểm thử Swift cho logic URL/số tiền, tương thích dữ liệu cũ, inbox sống qua lần mở mới và dữ liệu lỗi không che mục tốt. Xcode 16.4 build thành công bản Release arm64 cho iPhone, gồm app và SweepShare.appex; IPA 0.3.0 (4) đã được tạo và kiểm tra checksum/CRC, bundle ID và cấu hình App Group của hai target. IPA chưa ký. + +Luồng nhập OCR trên simulator nằm trong CI riêng và còn đang chạy tại thời điểm bàn giao IPA: [lượt kiểm thử](https://github.com/Sentechtipsvn/Sweep/actions/runs/43453650463). Không coi build thành công là đã xác nhận thao tác giao diện. Test fixture dùng inbox riêng, không chứng minh được provisioning thật hay menu Zalo trên iPhone. Mã nguồn tạo IPA: c1d1262aa304585674802368c06fe4da2d5cf088. + +Đã kiểm tra tại môi trường soạn mã: cú pháp 37 tệp Swift bằng parser, cấu trúc plist/YAML và whitespace. Đã gọi Quick Link SVG bằng tài khoản ví dụ công khai trong tài liệu VietQR, nhận HTTP 200, render ảnh và giải mã QR để đối chiếu đúng BIN 970415, tài khoản ví dụ 113366668888, số tiền 790000 và nội dung TT DON 3877. Không dùng dữ liệu tài khoản của chủ dự án và không thực hiện chuyển tiền. Parser không thay thế type-check/build Swift. + +Cần thử trên iPhone với bản ký giữ App Groups: Zalo → Sweep khi app bị đóng và khi app đang mở, hủy rồi nhận lại, khởi động lại app, mã trùng, hết dung lượng, offline; quét QR bằng app ngân hàng thứ hai để đối chiếu tài khoản/số tiền/nội dung, chỉ kiểm tra thông tin trước bước xác nhận chuyển tiền. + +Tài liệu: [Apple Share Extension](https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/Share.html), [Apple App Groups](https://developer.apple.com/documentation/xcode/configuring-app-groups), [VietQR Quick Link](https://www.vietqr.io/qr-dong), [Thông báo API](https://www.vietqr.io/thong-bao-cap-nhat). diff --git a/docs/RELEASE-0.3.1.md b/docs/RELEASE-0.3.1.md new file mode 100644 index 0000000..b9fc09e --- /dev/null +++ b/docs/RELEASE-0.3.1.md @@ -0,0 +1,26 @@ +# Sweep 0.3.1 — sửa hộp thư chia sẻ khi ký bằng AltStore + +Video thử trên iPhone cho thấy SweepShare mở được từ Zalo nhưng không truy cập được container chung. Giữ extension không đồng nghĩa với việc App Groups đã được cấp đúng cho cả hai tiến trình. + +## Nguyên nhân trong 0.3.0 + +1. Gói build tắt code signing không có LC_CODE_SIGNATURE, nên không chứa khai báo entitlement App Groups trong executable của cả app lẫn extension. AltStore đọc entitlements của IPA để quyết định bật capability và tạo provisioning profile. Tệp `.entitlements` trong repo không tự nằm trong IPA. +2. App đọc duy nhất `SweepAppGroupIdentifier` cố định. AltStore đổi nhóm theo tài khoản ký và ghi nhóm thực vào `ALTAppGroups` của từng bundle. Tên cấu hình riêng của Sweep không được AltStore tự đổi. + +Đối chiếu mã nguồn AltStore tại commit `56854e66fef2eac32dad88dcbad1dc131d430e60`: `FetchProvisioningProfilesOperation.swift` đọc `app.entitlements[.appGroups]`; `ResignAppOperation.swift` ghi groups từ profile vào Info.plist; `Shared/Extensions/Bundle+AltStore.swift` xác định khóa `ALTAppGroups`. + +## Bản sửa + +- Đóng gói với chữ ký ad-hoc để giữ metadata App Groups thật trong executable của cả app và extension. Đây không phải chữ ký Apple cho phép cài trên iPhone; Sếp vẫn dùng AltStore ký và cài. +- Bước đóng gói đọc lại Mach-O của hai executable, kiểm tra chính xác quyền nhóm, xác minh chữ ký/resource bundle và checksum. Không chỉ kiểm tra khóa trong Info.plist. +- Lúc chạy ưu tiên nhóm do AltStore cấp qua `ALTAppGroups`; chỉ dùng nhóm cấu hình gốc khi không có thông tin remap. Không tự suy đoán Team ID hay tên nhóm mới. +- Thông báo lỗi phân biệt extension đã mở với quyền container chưa cấp, kèm nguồn/tên nhóm để chẩn đoán. +- Giữ vị trí SQLite, ảnh chứng từ và dữ liệu cũ; không đổi bundle ID gốc. Sửa một selector của bài test Bill sau khi nút nhận ảnh chuyển thành menu. + +## Kiểm chứng + +Bổ sung bốn kiểm thử chọn nhóm: AltStore remap, ký thông thường, nhóm rỗng/sai và tính nhất quán giữa app/extension. CI kiểm tra core, build iPhone và kiểm tra entitlement trong IPA; bài kiểm tra giao diện chạy riêng. Chỉ xác nhận kết quả sau khi CI trả về. Luồng App Groups thật của AltStore vẫn cần thử trên iPhone sau khi ký lại bản 0.3.1. + +Kết quả build `a48825871f49df21f457df7103743f9410cebaf1`: 36 kiểm thử Swift đạt; Xcode 16.4 build iPhone đạt; job validate hoàn tất thành công. Đã tải IPA và đọc lại Mach-O của cả hai executable, xác nhận `com.apple.security.application-groups = [group.com.sentechtipsvn.sweep]`, phiên bản 0.3.1 (5), CRC và SHA256 đúng. SHA256 IPA: `75faf0a21cd30411093ae0a4a1c35924e7b8b7d283e02992b8932f3b2445a4c9`. [Lượt CI](https://github.com/Sentechtipsvn/Sweep/actions/runs/43461155526) có job UI riêng còn đang chạy tại lúc bàn giao. Đây chưa phải xác nhận AltStore/iPhone thật đã cấp và mở được container. + +Không cần gỡ app đang chứa dữ liệu. Xuất sao lưu trước khi cài đè, giữ extension khi AltStore hỏi. Không ký lại bản 0.3.0 để thử sửa lỗi này. diff --git a/docs/RELEASE-0.3.2.md b/docs/RELEASE-0.3.2.md new file mode 100644 index 0000000..aea4350 --- /dev/null +++ b/docs/RELEASE-0.3.2.md @@ -0,0 +1,28 @@ +# Sweep 0.3.2 — nhận ảnh chia sẻ và tạo lại QR + +## Nhận ảnh + +Thông báo cũ gộp mọi lỗi đọc ảnh vào “JPEG/PNG/HEIC tối đa 120 MP”, không đủ để xác định vì sao tệp JPEG nhỏ bị từ chối. Ảnh chụp người dùng gửi xác nhận JPEG 1032×733, nhưng không chứa bytes hoặc danh sách representation do Zalo đưa vào NSItemProvider; chưa thể khẳng định representation cụ thể trên máy thật. + +- Thử JPEG/PNG/HEIC cụ thể trước kiểu ảnh chung, không chỉ lấy representation đầu tiên. +- Nếu bản tệp không đọc được, thử dữ liệu ảnh, đường dẫn rồi UIImage. Sao chép dữ liệu trước khi callback của nguồn hết hiệu lực. +- JPEG/PNG/HEIC hợp lệ giữ nguyên bytes; representation ảnh tĩnh khác, như TIFF, được chuẩn hóa cục bộ sang PNG tối đa cạnh 3072 px. Không tải ảnh lên máy chủ. +- Đọc ảnh chính và hướng ảnh; JPEG/HEIC có dữ liệu phụ không bị loại chỉ vì số ảnh lớn hơn một. Giữ chặn ảnh động PNG, dữ liệu hỏng, quá 80 MB hoặc quá 120 MP. +- Lỗi cuối hiển thị UTI và cách đọc thất bại để chẩn đoán, không gán mọi trường hợp thành vượt megapixel. + +## QR + +Ảnh màn hình cho thấy khoản còn lại theo ghi nhận bằng 0; điều kiện trong app đã khóa nút trước khi gọi VietQR. Đây là giới hạn ở UI/model, không phải phản hồi lỗi API. + +- Cho tạo/xem lại QR theo số tiền nhập từ 1 đồng đến tổng đơn, kể cả đã ghi nhận đủ tiền hoặc khách đã báo CK nhưng chưa đối soát. +- Mặc định: khoản còn lại, nếu bằng 0 thì khoản CK còn chờ đối soát, sau cùng là tổng đơn. Có thể sửa số tiền. +- Tạo QR không sửa tiền mặt, CK, đối soát, công hoặc trạng thái giao. Hồ sơ đã hủy vẫn không tạo QR. +- Tiếp tục giữ App Group metadata và cơ chế đọc ALTAppGroups của 0.3.1. + +## Kiểm tra + +Thêm kiểm thử JPEG có metadata/tên tệp chung, Data provider, tệp lỗi rồi fallback Data, ưu tiên JPEG thay TIFF, chuẩn hóa TIFF và từ chối dữ liệu hỏng. Bổ sung QR khi khoản còn lại bằng 0 và khi CK đã đối soát. Fixture simulator nhận UIImage qua cùng loader; thêm UI test QR bằng tài khoản ví dụ công khai của tài liệu VietQR. Không dùng tài khoản thật hoặc ảnh hóa đơn của người dùng trong CI. + +Kết quả chỉ được xác nhận sau khi CI hoàn tất. Tệp JPEG gốc trong Zalo và Share Sheet trên iPhone vẫn cần thử lại sau khi cài. Không gỡ app chứa sổ; ký cài đè và giữ tiện ích mở rộng như trước. + +Đã xác nhận cho build `e0275db45d40082eb9cd327249a1e277eaf81c5b`: 43 kiểm thử Swift đạt, Xcode 16.4 build Release arm64 đạt, đóng gói và xác minh App Group trong chữ ký của cả hai executable đạt. IPA 0.3.2 (6) tải về có CRC/SHA256 đúng; SHA256 `836271d7a97f624b3914ca75c1d362207f24002c63f3ffae73e846a498d98487`. [Lượt CI](https://github.com/Sentechtipsvn/Sweep/actions/runs/43468132064) có bài UI riêng còn chạy tại thời điểm bàn giao. Chưa xác nhận đọc đúng tệp cụ thể từ Zalo trên iPhone của người dùng. diff --git a/docs/RELEASE-0.4.0.md b/docs/RELEASE-0.4.0.md new file mode 100644 index 0000000..635a276 --- /dev/null +++ b/docs/RELEASE-0.4.0.md @@ -0,0 +1,21 @@ +# Sweep 0.4.0 (7) + +Changes requested during the delivery trial: + +- Receive legacy `public.image` items as UIImage, URL or encoded bytes, in addition to file/data/object representations. Keep original supported JPEG/PNG/HEIC files; convert other ImageIO-readable formats, including the first frame of animated images, to a bounded PNG. Reject unreadable, oversized or invalid payloads. +- Choose from Photos in the app and directly in the Share Extension. Photo attachment controls now contain only **Chọn ảnh** and **Chụp ảnh**, with a stacked layout for accessibility text sizes. +- Choose and remove individual photos from each outgoing report. A transfer initially selects the invoice and transfer proof. Removing a photo from this selection preserves the original order evidence. The default transfer caption contains only the customer name and actual recorded transfer amount. Cash and deferred orders use appropriate captions. +- Open driving directions in Google Maps; use Google's web directions if the app is unavailable. +- Remove redundant explanations. Treat the labelled phone field beneath the salesperson as the customer's phone. Stop OCR header extraction at the item table and suppress old table-header contamination in delivery notes while preserving stored history. +- Scope commission count, fees, cash collected, cash handed over, transfer checks and handover history to the selected month in Vietnam time. An empty month shows zero. Select the new month on rollover without deleting history or forgiving cash still held from a previous month. Monthly cash is labelled **Chênh lệch thu − nộp** because remittance can include cash collected earlier. + +Validation passed in [feature workflow 43525588962](https://github.com/Sentechtipsvn/Sweep/actions/runs/43525588962), source commit `b1ad9da4c92c160d6dca7d32b8f12029222f60c3`: + +- 54 core tests: legacy image-provider data, JPEG/TIFF/BMP/GIF intake, animated first-frame import, selectable report snapshots, concise captions, OCR table boundaries, Google Maps destinations, Vietnam month boundaries and monthly financial totals. +- Release device build and embedded Share Extension build succeeded. Packager verified the code signatures and App Group declarations for both bundles. +- All 6 iPhone 16 / iOS 18.5 simulator tests passed: Bill OCR/import/persistence; Photos/camera controls at large text; empty-month figures and navigation; QR for an already-recorded transfer; selecting/removing/restoring report photos and short captions; legacy `public.image` UIImage intake through review, import and relaunch. +- Reviewed exported screenshots of intake, report photo selection and an empty monthly reconciliation. Verified the downloaded artifact digest, IPA CRC, version/build, bundle IDs, Google Maps scheme and signed entitlement blobs. + +IPA SHA-256: `25b01fcd19cc66d84792e9a72d779a14a9526523eb2058477154f75cc92754ef`. + +The IPA retains the embedded Share Extension and matching ad-hoc App Group entitlement metadata for AltStore to re-sign. Installation still needs AltStore provisioning. Real Zalo delivery and a physical camera must be checked on the phone; simulator fixtures do not reproduce the sender app or its installed signing environment. diff --git a/docs/RELEASE-0.5.0.md b/docs/RELEASE-0.5.0.md new file mode 100644 index 0000000..0e3680c --- /dev/null +++ b/docs/RELEASE-0.5.0.md @@ -0,0 +1,17 @@ +# Sweep 0.5.0 (8) + +Implementation of the approved 14 November design and supplemental instructions. + +- Signed intake: Signed accepts a slip; Skip accepts nothing. A signature confirmed in the Share Extension is retained in its atomic inbox manifest and is not requested again in the main app. Existing queued entries without a signature still ask. No private extension-to-app launch API is used. +- Incoming supported ImageIO formats, including primary still frames of animations, are normalized to JPEG at up to 2560 px / 82% quality. Orientation is applied and pixels are drawn into a new sRGB bitmap; source GPS/EXIF/IPTC/XMP is not copied. The source outside Sweep is unchanged. Older stored originals stay intact; outgoing copies are also normalized. +- Three delivery choices: cash, transfer and freight. Cash full requires no photo report; partial cash is committed before opening a QR for the remainder. Closing a QR does not record money. Transfer requires explicit actual-payment confirmation. +- Transfer-now reports require priced invoice + transfer proof. Later reports allow only the signed warehouse slip. Freight requires carrier-signed slip + dispatched goods. All retain one commission per signed assignment. Driver-facing company bank reconciliation is removed. +- Report images can be selected/removed without deleting originals. Draft text/selection persist. Irrelevant address, contact and bank-verification changes do not mark a sent report unsent. +- History replaces Reconciliation. Monthly commission/receipts/remittances are separate from current cash held, which carries across months. Cash uses dated snapshot deltas so a later bank receipt does not move an earlier cash receipt into a different month. +- Four-column tools grid uses seven bundled colored SVG assets; accessibility sizes use two columns. Existing photo tools remain. Locations support manual address, GPS and map-center pin; navigation uses Google Maps. Contacts support aliases from NV bán hàng and supplied HTTPS Zalo profile links. The invoice phone remains the customer's number. +- Documents/Backups and Exports are visible in Files. SQLite and evidence remain in Application Support. Deleting the app still deletes its container. +- Cleanup and Reset require a full external backup, read back with evidence hash validation before deletion. Reset also backs up queued shared slips in a sibling `.pending` folder and only deletes those captured before backup. New concurrent shares remain queued. Reset removes app ledger/evidence/settings/contacts/places and does not delete Photos or Zalo data. A reset is never run automatically on update. +- Ledger schema 1 migrates to schema 2 with a readable v1 pre-upgrade backup, preserving money/commission and flagging unclassified old deliveries for review. New v2 backups cannot be silently opened by the old app; the new app restores both v1 and v2. +- New app icon uses the supplied delivery character, contained in a square without cutting the artwork. + +Validation results and distribution commit are appended after CI. Physical Zalo delivery, camera, GPS and installed Google Maps/Zalo still need device verification; simulator checks do not establish these physical integration results. diff --git a/docs/RELEASE-0.6.0.md b/docs/RELEASE-0.6.0.md new file mode 100644 index 0000000..c9d93a0 --- /dev/null +++ b/docs/RELEASE-0.6.0.md @@ -0,0 +1,13 @@ +# Sweep 0.6.0 (10) — cập nhật 02 + +Nút gọi tròn xanh sát phải, nút Maps gọn, chọn/chụp ảnh xếp dọc. Thêm chọn từ Danh bạ, xác nhận số trùng và đọc QR Zalo tùy chọn; giữ liên hệ, vị trí và chức năng cũ. + +Thêm lịch chấm công và bảng lương theo công thực làm. Nghỉ không lương trừ quỹ 12 ngày/năm; đúng 3 ngày nghỉ vẫn có chuyên cần, hơn 3 ngày mất. Giá xăng chốt ngày 30 (tháng 2: ngày cuối tháng) dùng cả tháng. Bảng lương chốt vào ngày cuối tháng, kể cả 28/29/30/31; giữ bản tính khi mở khóa, có CSV, khoản ứng và điều chỉnh có lý do. + +Trước khi tính lương thật, cấu hình lịch làm việc, loại/vùng xăng và mức tiền của tháng. Giá xăng nhập tay có nguồn/ngày; chưa bật dịch vụ tự động lấy giá. Số 4,5 ngày nghỉ trong ảnh cũ không tự nhập vào năm hiện tại. + +Nhắc gia hạn dựa trên ngày đọc được từ profile bản ký đang cài, hoặc ngày người dùng nhập nếu không đọc được. Bắt đầu 24 giờ trước hạn, mỗi 3 giờ, lô 48 thông báo. Sau khi refresh cần mở Sweep để nhận hạn mới và hủy lịch cũ; không có cam kết iOS chuyển thông báo khi chữ ký đã hết hạn. + +Thêm tác vụ App Intents “Nhận phiếu Sweep” để cấu hình Phím tắt nhận ảnh từ bảng chia sẻ và mở app. Giữ Share Extension cũ. Luồng Zalo/Phím tắt và profile ký lại cần thử trên iPhone; simulator/build không thay thế kiểm tra này. Không dùng API riêng tư để tự bật app từ Share Extension. + +Sổ nâng từ schema 1/2 lên 3 có bản sao trước nâng cấp; sao lưu/khôi phục gồm dữ liệu công và lương. Không tự xóa dữ liệu và không cập nhật nguồn AltStore. Bàn giao IPA trực tiếp sau khi build và kiểm thử. diff --git a/project.yml b/project.yml index 6495abb..e7fc690 100644 --- a/project.yml +++ b/project.yml @@ -6,8 +6,9 @@ options: settings: base: SWIFT_VERSION: "5.0" - MARKETING_VERSION: "0.2.1" - CURRENT_PROJECT_VERSION: "3" + MARKETING_VERSION: "0.6.0" + CURRENT_PROJECT_VERSION: "10" + SWEEP_APP_GROUP: group.com.sentechtipsvn.sweep CODE_SIGNING_ALLOWED: NO targets: Sweep: @@ -17,12 +18,33 @@ targets: - path: Sweep excludes: - Info.plist + - Sweep.entitlements + dependencies: + - target: SweepShare + embed: true settings: base: PRODUCT_BUNDLE_IDENTIFIER: com.sentechtipsvn.sweep INFOPLIST_FILE: Sweep/Info.plist + CODE_SIGN_ENTITLEMENTS: Sweep/Sweep.entitlements TARGETED_DEVICE_FAMILY: "1,2" ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon + SweepShare: + type: app-extension + platform: iOS + sources: + - path: SweepShare + excludes: [Info.plist, SweepShare.entitlements] + - path: Sweep/Core + - path: Sweep/PrivacyInfo.xcprivacy + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: com.sentechtipsvn.sweep.share + INFOPLIST_FILE: SweepShare/Info.plist + CODE_SIGN_ENTITLEMENTS: SweepShare/SweepShare.entitlements + APPLICATION_EXTENSION_API_ONLY: YES + SKIP_INSTALL: YES + TARGETED_DEVICE_FAMILY: "1,2" SweepUITests: type: bundle.ui-testing platform: iOS