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("