diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml index f80cf0b02..e300219dc 100644 --- a/.github/workflows/ci-rust.yml +++ b/.github/workflows/ci-rust.yml @@ -378,27 +378,20 @@ jobs: -A clippy::missing_panics_doc \ -A clippy::too_many_lines - # Advisory for now — same reasoning as the rustfmt step above, and the - # same instruction: flip this to a gate in the change that clears the - # backlog. There are 62 (41 on Result, 21 on Option) as of 2026-08-09. + # GATE since 2026-11-26. Production `unwrap()` was driven to zero across the + # workspace (R12), so any new `.unwrap()` in a lib or bin target now fails + # the build. Use `?` with thiserror/anyhow, `ok_or_else`/`map_err`, or, for + # a provably-present constant, `expect("")`. # # The previous implementation was a line-based grep that excluded lines - # *containing* `#[cfg(test)]`. Inline `#[cfg(test)] mod tests { … }` is - # the dominant pattern here, and an unwrap 120 lines inside such a block - # is nowhere near the attribute — so the check reported test doubles and - # assertions as production violations. It could not have passed on a - # healthy repo, and it never ran, so nobody found out. - # - # Clippy knows what test code is. Without `--all-targets`, `cfg(test)` is - # off, so inline test modules are not compiled and not linted — which is - # exactly the boundary this check was trying and failing to express. - - name: Check for .unwrap() in production paths (advisory) - continue-on-error: true + # *containing* `#[cfg(test)]`; it reported test doubles and assertions as + # production violations and never ran. Clippy knows what test code is. + # Without `--all-targets`, `cfg(test)` is off, so inline test modules are + # not compiled and not linted, which is exactly the boundary wanted here. + - name: Check for .unwrap() in production paths run: | cargo clippy --workspace --lib --bins --all-features \ - -- -W clippy::unwrap_used 2>&1 | grep -E "unwrap\(\) on" -A 2 || true - echo "" - echo "Use the ? operator with thiserror/anyhow instead." + -- -D clippy::unwrap_used # Replaces a check that could not fail: it grepped src/main.rs and # src/router.rs — files these services do not use for routing — and @@ -753,7 +746,7 @@ jobs: run: cargo install cargo-deny --locked --quiet - name: Run cargo audit (RustSec CVE check) - # Three advisories are ignored, each because no fixed version is + # Nine advisories are ignored, each because no fixed version is # reachable from where the crate actually sits. # below re-derives the justification on every run and fails when it # stops holding: @@ -767,6 +760,25 @@ jobs: # aws-sdk-s3's internals. No released lru fixes it # and aws-sdk-s3 pins the major version. Unsoundness # rather than a remotely reachable vulnerability. + # RUSTSEC-2026-0258 h2 0.3 HTTP/2 DoS; internal gRPC only (see deny.toml). + # Added 2026-11-27, after rustc 1.100 / the advisory-db refresh: + # RUSTSEC-2026-0387 crypto-bigint 0.5.5 timing variability. Compiled, + # but only through aws-sigv4's sigv4a feature (ECDSA + # signing for S3 multi-region access points), which + # nothing here calls; we sign with HMAC SigV4. The + # fix is 0.7.6 and aws-sigv4 1.x pins 0.5. + # RUSTSEC-2026-0459 libsqlite3-sys (C SQLite CVE). Never compiled: in + # Cargo.lock only as sqlx-sqlite's optional dep; we + # are Postgres-only. Same shape as the rsa ignore. + # RUSTSEC-2026-0543 chrono unmaintained. Informational, no fixed + # version and no drop-in successor; sqlx, the AWS + # SDK and every service depend on it. + # RUSTSEC-2026-0555 chrono-tz unmaintained, via tera (payments + # RUSTSEC-2026-0559 chrono-tz-build invoice templates). Informational. + # RUSTSEC-2026-0441 pin-utils unmaintained, via aws-smithy-http and + # aws-smithy-runtime. A macro-only crate. + # scripts/check-audit-ignores.sh re-checks every one of these and fails + # the job when a justification stops holding. run: | cargo audit \ --deny warnings \ @@ -775,7 +787,13 @@ jobs: --deny yanked \ --ignore RUSTSEC-2023-0071 \ --ignore RUSTSEC-2026-0253 \ - --ignore RUSTSEC-2026-0258 + --ignore RUSTSEC-2026-0258 \ + --ignore RUSTSEC-2026-0387 \ + --ignore RUSTSEC-2026-0441 \ + --ignore RUSTSEC-2026-0459 \ + --ignore RUSTSEC-2026-0543 \ + --ignore RUSTSEC-2026-0555 \ + --ignore RUSTSEC-2026-0559 # An --ignore never expires on its own: once upstream ships a fix, the flag # keeps suppressing the finding and the job stays green for a reason that diff --git a/Cargo.lock b/Cargo.lock index 6dffe0fc7..93757e728 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -465,9 +465,9 @@ dependencies = [ [[package]] name = "aws-smithy-eventstream" -version = "0.61.2" +version = "0.61.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6de526c7b567420a31bc283657a7921b45c4cafe0827fdf2490713dcc770c28f" +checksum = "14c8a643d0e114cae39e45415e3225793a6396698b7779a0c9e3ede731d8fc71" dependencies = [ "aws-smithy-types", "bytes", @@ -476,9 +476,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.64.0" +version = "0.64.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37843d9add67c3aff5856f409c6dc315d3cdff60f9c0cb5b670dab1e9920306d" +checksum = "639b4d8f8555f24a9be649811c3eb0b4d4616f4d61daf0c32e28873bc1ea9af1" dependencies = [ "aws-smithy-eventstream", "aws-smithy-runtime-api", @@ -581,9 +581,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api" -version = "1.14.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b98f2e1fd67ec06618f9c291e5e495a468e60519e44c9c1979cd0521f3affdb" +checksum = "c0730c16f91124c6a2abb4932c77e299288b3dd9f967ea2e9ec48cc6731e87a4" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", @@ -621,9 +621,9 @@ dependencies = [ [[package]] name = "aws-smithy-types" -version = "1.6.2" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fce83ce9abbb198d25bc7131e468d0f9fe1257125e58c39f3f9fc9f5098c9647" +checksum = "55752025c39c0e094962fd73f1c57014b191f678612e517f219468e575af9822" dependencies = [ "base64-simd", "bytes", @@ -637,7 +637,6 @@ dependencies = [ "itoa", "num-integer", "pin-project-lite", - "pin-utils", "ryu", "serde", "time", @@ -1357,9 +1356,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", ] @@ -1370,8 +1369,18 @@ version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.23.0", + "darling_macro 0.23.0", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", ] [[package]] @@ -1387,17 +1396,41 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.3", +] + [[package]] name = "darling_macro" version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" dependencies = [ - "darling_core", + "darling_core 0.23.0", "quote", "syn 2.0.117", ] +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.3", +] + [[package]] name = "data-encoding" version = "2.10.0" @@ -1656,9 +1689,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -2441,6 +2474,41 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +dependencies = [ + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "jobserver" version = "0.1.34" @@ -2788,6 +2856,7 @@ dependencies = [ "tokio", "tonic", "tonic-build", + "tower 0.4.13", "tower-http 0.5.2", "tracing", "uuid", @@ -2945,6 +3014,7 @@ dependencies = [ "thiserror 1.0.69", "tokio", "tonic", + "tower 0.4.13", "tower-http 0.5.2", "tracing", "uuid", @@ -3259,6 +3329,7 @@ dependencies = [ "thiserror 1.0.69", "tokio", "tonic", + "tower 0.4.13", "tower-http 0.5.2", "tracing", "uuid", @@ -4104,6 +4175,21 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -4204,7 +4290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4" dependencies = [ "bytes", - "heck 0.4.1", + "heck 0.5.0", "itertools", "log", "multimap", @@ -4326,9 +4412,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.16" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", "getrandom 0.4.2", @@ -4348,16 +4434,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.14" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2 0.6.3", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4469,9 +4555,9 @@ dependencies = [ [[package]] name = "redis" -version = "0.25.4" +version = "0.25.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0d7a6955c7511f60f3ba9e86c6d02b3c3f144f8c24b288d1f4e18074ab8bbec" +checksum = "5e46922bd01fefcfdcf58d9cd626da082bb2cde27211920dacfde6b2ecf9a35b" dependencies = [ "arc-swap", "async-trait", @@ -4628,9 +4714,9 @@ dependencies = [ [[package]] name = "rmcp" -version = "3.0.1" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3797d226787327b35b0b6f9e878fe55f3af2bb4daf916c0411079885454042f0" +checksum = "fc4fa9a7558c480e1817c0f02e9a73782001ac1f47fb9d26cc073915963282ea" dependencies = [ "async-trait", "base64 0.23.0", @@ -4640,13 +4726,18 @@ dependencies = [ "http 1.4.0", "http-body 1.0.1", "http-body-util", + "indexmap 2.13.1", + "jiff", + "libc", "pastey", + "percent-encoding", "pin-project-lite", "rand 0.10.2", "rmcp-macros", "schemars", "serde", "serde_json", + "sha2 0.11.0", "sse-stream", "thiserror 2.0.18", "tokio", @@ -4654,20 +4745,22 @@ dependencies = [ "tokio-util", "tower-service", "tracing", + "unicode-general-category", + "unicode-normalization", "uuid", ] [[package]] name = "rmcp-macros" -version = "3.0.1" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f5bc0c6851a20cd627ef4b90defb79f39a261c467de52af5d38000d7979c52" +checksum = "43c1bf063ba32333267a8bc282ec33ae0edf56bf74890118cb0c7bf910a7a1c0" dependencies = [ - "darling", + "darling 0.24.1", "proc-macro2", "quote", "serde_json", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -4742,9 +4835,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.11.0", "errno", @@ -4755,9 +4848,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "once_cell", @@ -4792,9 +4885,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -5467,7 +5560,7 @@ dependencies = [ "fastrand", "getrandom 0.4.2", "once_cell", - "rustix 1.1.4", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -5609,9 +5702,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.51.0" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bd1c4c0fc4a7ab90fc15ef6daaa3ec3b893f004f915f2392557ed23237820cd" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -6055,6 +6148,12 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -6096,9 +6195,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -6157,7 +6256,7 @@ version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240e4b81c20a1d6d50d1d7265c658dfbd204e8b9ac4d80f3c931f39462196335" dependencies = [ - "darling", + "darling 0.23.0", "proc-macro-error3", "proc-macro2", "quote", @@ -6348,9 +6447,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "1.0.7" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] diff --git a/Cargo.toml b/Cargo.toml index e906d60fa..ecf89c9a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,7 +71,7 @@ tonic-build = { version = "0.11" } prost = { version = "0.12" } # Model Context Protocol — remote MCP server transport (ai-layer) -rmcp = { version = "3.0.1", features = ["server", "transport-streamable-http-server"] } +rmcp = { version = "3.9.0", features = ["server", "transport-streamable-http-server"] } # Database sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "uuid", "chrono", "json", "migrate"] } diff --git a/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx b/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx index c75ba626a..929465450 100644 --- a/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx +++ b/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx @@ -331,6 +331,7 @@ function ComplianceConsole() { onReject={handleReject} onSuspend={canAdmin ? handleSuspend : undefined} onReinstate={canAdmin ? handleReinstate : undefined} + canAdmin={canAdmin} typeNames={typeNames} entityNames={entityNames} /> diff --git a/apps/admin-portal/src/app/(dashboard)/dispatch/page.tsx b/apps/admin-portal/src/app/(dashboard)/dispatch/page.tsx index 61acf91b6..c9cb4549a 100644 --- a/apps/admin-portal/src/app/(dashboard)/dispatch/page.tsx +++ b/apps/admin-portal/src/app/(dashboard)/dispatch/page.tsx @@ -13,7 +13,7 @@ import { LiveDispatchMap } from "@/components/maps/live-dispatch-map"; import type { DriverPin } from "@/components/maps/live-dispatch-map"; import { variants } from "@/lib/design-system/tokens"; import { authFetch } from "@/lib/auth/auth-fetch"; -import { readBus, subscribeToBus, type BusBooking } from "@/lib/api/marketplace-bus"; +import { fetchAllBookings, type AdminBooking } from "@/lib/api/marketplace"; import { useDriverRoster } from "@/context/driver-roster-context"; import { usePermissions } from "@/hooks/usePermissions"; @@ -36,7 +36,6 @@ interface QueueItem { cod_amount_cents?: number | null; tracking_number?: string | null; origin?: "dispatch" | "marketplace"; - partner_display?: string; auto_dispatch_attempts?: number | null; last_dispatch_error?: string | null; last_attempt_at?: string | null; @@ -45,19 +44,18 @@ interface QueueItem { type QueueFilter = "pending" | "dispatched" | "all"; -function busToQueueItem(b: BusBooking): QueueItem { +function bookingToQueueItem(b: AdminBooking): QueueItem { return { id: `mp-${b.id}`, shipment_id: b.shipment_id, - customer_name: b.merchant_display, + customer_name: b.consumer_name, dest_address_line1: b.dropoff_label, dest_city: b.dropoff_label.split(",").pop()?.trim() ?? "—", - service_type: b.size_class, + service_type: "marketplace", status: "pending", cod_amount_cents: null, tracking_number: b.awb, origin: "marketplace", - partner_display: b.partner_display_name, }; } @@ -211,6 +209,7 @@ function DispatchPageInner() { const [queue, setQueue] = useState([]); const [marketplaceQueue, setMarketplaceQueue] = useState([]); + const [marketplaceError, setMarketplaceError] = useState(false); const [drivers, setDrivers] = useState([]); const [driverSummary, setDriverSummary] = useState(null); const [dispatching, setDispatching] = useState(null); @@ -272,18 +271,41 @@ function DispatchPageInner() { return () => clearInterval(id); }, [fetchData]); - // Marketplace-origin queue: accepted bookings from the bus become synthetic queue rows - const refreshMarketplaceQueue = useCallback(() => { - const accepted = readBus() - .filter((b) => b.status === "accepted") - .map(busToQueueItem); - setMarketplaceQueue(accepted); + // Marketplace-origin queue: accepted bookings (GET /v1/marketplace/admin/bookings, the + // same call the Marketplace page makes) become synthetic queue rows. The + // booking carries no carrier name or vehicle class, so rows show neither. + const marketplaceInFlight = useRef(false); + const marketplaceSeq = useRef(0); + const refreshMarketplaceQueue = useCallback(async (isMounted: () => boolean) => { + if (marketplaceInFlight.current) return; // skip a tick while a request is outstanding + marketplaceInFlight.current = true; + const seq = ++marketplaceSeq.current; + try { + const bookings = await fetchAllBookings(); + if (!isMounted() || seq !== marketplaceSeq.current) return; + setMarketplaceQueue( + bookings.filter((b) => b.status === "accepted").map(bookingToQueueItem), + ); + setMarketplaceError(false); + } catch { + // Keep the previous rows: an outage is not "no marketplace bookings". + if (isMounted() && seq === marketplaceSeq.current) setMarketplaceError(true); + } finally { + marketplaceInFlight.current = false; + } }, []); useEffect(() => { - refreshMarketplaceQueue(); - const unsubscribe = subscribeToBus(refreshMarketplaceQueue); - return unsubscribe; + let mounted = true; + const isMounted = () => mounted; + void refreshMarketplaceQueue(isMounted); + const id = setInterval(() => void refreshMarketplaceQueue(isMounted), 30_000); + return () => { + mounted = false; + // A dev StrictMode remount must not find the first load skipped as "in flight". + marketplaceInFlight.current = false; + clearInterval(id); + }; }, [refreshMarketplaceQueue]); useEffect(() => { @@ -591,6 +613,12 @@ function DispatchPageInner() { "All Shipments"} · {mergedQueue.length} + {marketplaceError && ( +

+ Marketplace bookings could not be refreshed; the list may be out of date. +

+ )} + {mergedQueue.length === 0 && !loading && (

{queueFilter === "pending" ? "No pending shipments" : @@ -611,11 +639,6 @@ function DispatchPageInner() {

{item.customer_name}

{item.dest_address_line1}

{item.dest_city} · {item.service_type}

- {item.origin === "marketplace" && item.partner_display && ( -

- via {item.partner_display} -

- )}
{item.origin === "marketplace" && ( diff --git a/apps/admin-portal/src/app/(dashboard)/marketplace/page.tsx b/apps/admin-portal/src/app/(dashboard)/marketplace/page.tsx index 5130dca69..8582dabb8 100644 --- a/apps/admin-portal/src/app/(dashboard)/marketplace/page.tsx +++ b/apps/admin-portal/src/app/(dashboard)/marketplace/page.tsx @@ -12,7 +12,7 @@ * tracking. Read-only — mutation flows are owned by the partner portal. */ -import { useCallback, useEffect, useMemo, useState, Suspense } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState, Suspense } from "react"; import { useSearchParams } from "next/navigation"; import { useRosterEvents } from "@/hooks/useRosterEvents"; import { motion, AnimatePresence } from "framer-motion"; @@ -30,7 +30,6 @@ import { Zap, ExternalLink, Map as MapIcon, - Building2, User as UserIcon, X, Receipt as ReceiptIcon, @@ -48,18 +47,14 @@ import { fetchMarketplaceStats, formatCentsPhp, SIZE_CLASS_LABEL, - VEHICLE_FEATURE_LABEL, - subscribeToMarketplaceUpdates, type AdminListing, type AdminBooking, type BookingStatus, type ListingStatus, type MarketplaceStats, type PartnerType, - type VehicleFeature, } from "@/lib/api/marketplace"; -import { findReceiptByBookingId, type BusReceipt } from "@/lib/api/marketplace-bus"; -import { ReceiptModal, type ReceiptModalBooking } from "@/components/marketplace/ReceiptModal"; +import { ReceiptModal } from "@/components/marketplace/ReceiptModal"; import { authFetch } from "@/lib/auth/auth-fetch"; const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000"; @@ -180,12 +175,11 @@ function AdminMarketplacePageInner() { const [bookings, setBookings] = useState([]); const [stats, setStats] = useState(null); const [loading, setLoading] = useState(true); + // A failed refresh keeps the last good lists and flags the outage; the next success clears it. + const [loadError, setLoadError] = useState(false); - // Oversight view — receipts issued by partners on tenant bookings. Read-only. - const [receiptsByBookingId, setReceiptsByBookingId] = useState>({}); - const [receiptModal, setReceiptModal] = useState< - { open: boolean; booking: ReceiptModalBooking | null; receipt: BusReceipt | null } - >({ open: false, booking: null, receipt: null }); + // Oversight view — read-only receipt rendered from the booking itself. + const [receiptBooking, setReceiptBooking] = useState(null); const [disputeBooking, setDisputeBooking] = useState(null); const [tab, setTab] = useState(qpAwb || qpStatus ? "bookings" : "listings"); const [search, setSearch] = useState(qpAwb ?? ""); @@ -196,16 +190,35 @@ function AdminMarketplacePageInner() { (qpStatus as BookingStatus) || "all", ); + // Set false on unmount so a poll tick that resolves late never sets state. + const mountedRef = useRef(true); + useEffect(() => { + mountedRef.current = true; + return () => { mountedRef.current = false; }; + }, []); + + // A tick (or roster nudge) that lands while a request is outstanding is skipped. + const inFlightRef = useRef(false); const refresh = useCallback(async () => { - const [l, b, s] = await Promise.all([ - fetchAllListings(), - fetchAllBookings(), - fetchMarketplaceStats(), - ]); - setListings(l); - setBookings(b); - setStats(s); - setLoading(false); + if (inFlightRef.current) return; + inFlightRef.current = true; + try { + const [l, b, s] = await Promise.all([ + fetchAllListings(), + fetchAllBookings(), + fetchMarketplaceStats(), + ]); + if (!mountedRef.current) return; + setListings(l); + setBookings(b); + setStats(s); + setLoadError(false); + } catch { + if (mountedRef.current) setLoadError(true); + } finally { + inFlightRef.current = false; + if (mountedRef.current) setLoading(false); + } }, []); useEffect(() => { @@ -222,46 +235,9 @@ function AdminMarketplacePageInner() { }); useEffect(() => { const id = setInterval(refresh, 20_000); - const unsubscribe = subscribeToMarketplaceUpdates(() => refresh()); - return () => { - clearInterval(id); - unsubscribe(); - }; + return () => clearInterval(id); }, [refresh]); - // Hydrate receipts for tenant-wide visible bookings. - useEffect(() => { - if (bookings.length === 0) { - setReceiptsByBookingId({}); - return; - } - const next: Record = {}; - for (const b of bookings) { - const r = findReceiptByBookingId(b.id); - if (r) next[b.id] = r; - } - setReceiptsByBookingId(next); - }, [bookings]); - - function openReceiptFor(b: AdminBooking) { - const receipt = receiptsByBookingId[b.id] ?? null; - if (!receipt) return; - const modalBooking: ReceiptModalBooking = { - id: b.id, - awb: b.awb, - partner_display_name: b.partner_display_name, - merchant_display: b.consumer_display, - consumer_display: b.consumer_display, - pickup_label: b.pickup_label, - dropoff_label: b.dropoff_label, - pickup_at: b.pickup_at, - cargo_weight_kg: b.cargo_weight_kg, - quoted_price_cents: b.quoted_price_cents, - status: b.status, - }; - setReceiptModal({ open: true, booking: modalBooking, receipt }); - } - // Distinct partners for filter dropdown const partnerOptions = useMemo(() => { const m = new Map(); @@ -300,7 +276,7 @@ function AdminMarketplacePageInner() { return ( b.awb.toLowerCase().includes(q) || b.partner_display_name.toLowerCase().includes(q) || - b.consumer_display.toLowerCase().includes(q) || + b.consumer_name.toLowerCase().includes(q) || b.pickup_label.toLowerCase().includes(q) || b.dropoff_label.toLowerCase().includes(q) ); @@ -508,6 +484,17 @@ function AdminMarketplacePageInner() { the real marketplace service will replace in Phase 2. */} {tab === "listings" && } + {loadError && ( +
+ Could not load marketplace data. {bookings.length > 0 || listings.length > 0 + ? "Showing the last data received; retrying automatically." + : "Retrying automatically."} +
+ )} + {/* ── Content ───────────────────────────────────────────────────────── */} {tab === "listings" ? ( @@ -516,18 +503,16 @@ function AdminMarketplacePageInner() { rows={filteredBookings} total={bookings.length} loading={loading} - receipts={receiptsByBookingId} - onOpenReceipt={openReceiptFor} + onOpenReceipt={setReceiptBooking} onResolveDispute={(b) => setDisputeBooking(b)} /> )} {/* Shipment receipt (view-only — tenant oversight) */} setReceiptModal({ open: false, booking: null, receipt: null })} - booking={receiptModal.booking} - receipt={receiptModal.receipt} + open={receiptBooking !== null} + onClose={() => setReceiptBooking(null)} + booking={receiptBooking} /> {/* Dispute resolution modal */} @@ -558,12 +543,6 @@ function dispatchDeepLink(shipmentId: string): string { return `/admin/dispatch?order=${encodeURIComponent(shipmentId)}`; } -function merchantPortalDeepLink(awb: string): string { - // Cross-portal — jumps into the merchant's own marketplace view with the - // AWB surfaced for support/escalation context. Plain preserves /merchant basePath. - return `/merchant/marketplace?awb=${encodeURIComponent(awb)}`; -} - // ── Dispute Resolution Modal ────────────────────────────────────────────────── function DisputeResolutionModal({ @@ -645,7 +624,7 @@ function DisputeResolutionModal({

Booking

{booking.awb}

- {booking.partner_display_name} · {booking.consumer_display} + {booking.partner_display_name} · {booking.consumer_name}

)} @@ -820,17 +799,6 @@ function ListingsTable({

{SIZE_CLASS_LABEL[l.size_class]}

- {l.features && l.features.length > 0 && ( -
- {(l.features as VehicleFeature[]).map((f) => ( - {VEHICLE_FEATURE_LABEL[f]} - ))} -
- )} @@ -904,14 +872,12 @@ function BookingsTable({ rows, total, loading, - receipts, onOpenReceipt, onResolveDispute, }: { rows: AdminBooking[]; total: number; loading: boolean; - receipts: Record; onOpenReceipt: (b: AdminBooking) => void; onResolveDispute: (b: AdminBooking) => void; }) { @@ -923,7 +889,7 @@ function BookingsTable({ AWB Partner - Booked by + Consignee Route Cargo Quoted @@ -973,32 +939,19 @@ function BookingsTable({
- {b.merchant_type === "business" ? ( - - - {b.consumer_display} - - - ) : ( - - - {b.consumer_display} - · walk-up - - )} + + + {b.consumer_name} + {b.pickup_label}
→ {b.dropoff_label}
- {SIZE_CLASS_LABEL[b.size_class]} + {b.cargo_weight_kg.toLocaleString()} kg
- {b.cargo_weight_kg.toLocaleString()} kg + {b.distance_km.toLocaleString()} km
@@ -1022,7 +975,7 @@ function BookingsTable({ {b.status.replace("_", " ")}
- {receipts[b.id] && ( + {b.status !== "pending" && b.status !== "rejected" && b.status !== "cancelled" && (
)} + {canAdmin && ( +
+ +
+ )} + {canAdmin && uploadOpen && ( + setUploadOpen(false)} + onUploaded={() => setLocalRefresh((n) => n + 1)} + /> + )} + {/* Document list */}
{sorted.length === 0 && ( diff --git a/apps/admin-portal/src/components/compliance/upload-document-modal.tsx b/apps/admin-portal/src/components/compliance/upload-document-modal.tsx new file mode 100644 index 000000000..95d108aa5 --- /dev/null +++ b/apps/admin-portal/src/components/compliance/upload-document-modal.tsx @@ -0,0 +1,263 @@ +"use client"; +import { useEffect, useRef, useState } from "react"; +import { motion } from "framer-motion"; +import { Loader2, Upload, X } from "lucide-react"; +import { fetchDocumentTypes, uploadDocumentOnBehalf } from "@/lib/api/compliance"; +import type { DocumentType } from "@/lib/api/compliance"; +import { + ACCEPTED_CONTENT_TYPES, + MAX_DOCUMENT_NUMBER_LENGTH, + nextFocusIndex, + readFileAsBase64, + replacesApproved, + typesForProfile, + validateUploadFile, +} from "@/lib/compliance/upload"; + +interface Props { + profileId: string; + /** The profile being uploaded onto; only types that apply to it are offered. */ + profile: { entity_type: string; jurisdiction: string }; + /** The profile's current documents, to warn when an upload replaces an approved one. */ + documents: { document_type_id: string; status: string }[]; + onClose: () => void; + /** Called after a successful upload, before the modal closes. */ + onUploaded: () => void; +} + +const INPUT = + "w-full rounded-lg border border-glass-border bg-glass-100 px-3 py-2 text-sm text-white placeholder:text-white/25 outline-none focus:border-cyan-glow/50"; +const FOCUSABLE = + 'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])'; +const LABEL = "text-[11px] uppercase tracking-wider text-white/40"; + +/** + * Upload a document into a courier's profile on their behalf (compliance:admin). + * The parent decides whether to render this at all; the server enforces the + * permission regardless. + */ +export function UploadDocumentModal({ profileId, profile, documents, onClose, onUploaded }: Props) { + const [types, setTypes] = useState([]); + const [typesErr, setTypesErr] = useState(null); + const [typeId, setTypeId] = useState(""); + const [number, setNumber] = useState(""); + const [issue, setIssue] = useState(""); + const [expiry, setExpiry] = useState(""); + const [file, setFile] = useState(null); + const [fileErr, setFileErr] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const dialogRef = useRef(null); + const firstFieldRef = useRef(null); + // Latest busy/onClose for the document-level key handler without re-binding it. + const busyRef = useRef(busy); + busyRef.current = busy; + const onCloseRef = useRef(onClose); + onCloseRef.current = onClose; + + // Focus management: remember the trigger, move focus in, restore on close. + useEffect(() => { + const trigger = document.activeElement as HTMLElement | null; + firstFieldRef.current?.focus(); + + function onKeyDown(e: KeyboardEvent) { + if (e.key === "Escape") { + if (busyRef.current) return; + e.preventDefault(); + onCloseRef.current(); + return; + } + if (e.key !== "Tab") return; + const root = dialogRef.current; + if (!root) return; + const items = Array.from(root.querySelectorAll(FOCUSABLE)).filter( + (el) => !(el as HTMLButtonElement).disabled, + ); + const next = nextFocusIndex(items.indexOf(document.activeElement as HTMLElement), items.length, e.shiftKey); + e.preventDefault(); + if (next !== null) items[next].focus(); + } + document.addEventListener("keydown", onKeyDown); + return () => { + document.removeEventListener("keydown", onKeyDown); + trigger?.focus(); + }; + }, []); + + useEffect(() => { + let live = true; + fetchDocumentTypes() + .then((t) => { if (live) setTypes(t); }) + .catch((e) => { + if (live) setTypesErr(e instanceof Error ? e.message : "Could not load document types."); + }); + return () => { live = false; }; + }, []); + + function onFile(f: File | null) { + setError(null); + if (!f) { setFile(null); setFileErr(null); return; } + const problem = validateUploadFile(f); + setFileErr(problem); + setFile(problem ? null : f); + } + + const offered = typesForProfile(types, profile); + const chosen = offered.find((t) => t.id === typeId); + const trimmedNumber = number.trim(); + const canSubmit = + !busy && !!typeId && trimmedNumber.length > 0 && + trimmedNumber.length <= MAX_DOCUMENT_NUMBER_LENGTH && !!file; + + async function submit() { + if (!canSubmit || !file) return; + setBusy(true); + setError(null); + try { + const file_base64 = await readFileAsBase64(file); + await uploadDocumentOnBehalf(profileId, { + document_type_id: typeId, + document_number: trimmedNumber, + file_base64, + content_type: file.type, + ...(issue ? { issue_date: issue } : {}), + ...(expiry ? { expiry_date: expiry } : {}), + }); + onUploaded(); + onClose(); + } catch (e) { + setError(e instanceof Error ? e.message : "Upload failed."); + setBusy(false); + } + } + + return ( +
+
+ e.stopPropagation()} + > +
+
+ +

Upload document

+
+ +
+ +
+
+ + + {typesErr && {typesErr}} + {chosen && replacesApproved(documents, chosen.id) && ( + + This replaces the courier's current {chosen.name} and returns them to review. + + )} +
+ +
+ + setNumber(e.target.value)} + maxLength={MAX_DOCUMENT_NUMBER_LENGTH} + disabled={busy} + placeholder="e.g. N01-23-456789" + className={`${INPUT} font-mono`} + /> +
+ +
+
+ + setIssue(e.target.value)} + disabled={busy} className={INPUT} + /> +
+
+ + setExpiry(e.target.value)} + disabled={busy} className={INPUT} + /> +
+
+ +
+ + onFile(e.target.files?.[0] ?? null)} + disabled={busy} + className="text-xs text-white/60 file:mr-3 file:rounded-lg file:border file:border-glass-border file:bg-glass-100 file:px-3 file:py-1.5 file:text-xs file:text-white/70" + /> + {fileErr && {fileErr}} +
+ + {error && ( +
+ {error} +
+ )} +
+ +
+ + +
+
+
+ ); +} diff --git a/apps/admin-portal/src/components/fleet/RegisterVehicleModal.tsx b/apps/admin-portal/src/components/fleet/RegisterVehicleModal.tsx index 76e99b310..716391b61 100644 --- a/apps/admin-portal/src/components/fleet/RegisterVehicleModal.tsx +++ b/apps/admin-portal/src/components/fleet/RegisterVehicleModal.tsx @@ -9,38 +9,38 @@ import { GlassCard } from "@/components/ui/glass-card"; import { createFleetApi, type RegisterVehiclePayload, type VehicleType } from "@/lib/api/fleet"; import { createVehicleListing, + fetchCarrierOptions, + SIZE_CLASS_LABEL, + type CarrierOption, type SizeClass, - type VehicleFeature, type CreateListingPayload, } from "@/lib/api/marketplace"; -// ── Vehicle type config (1-to-1 with marketplace SizeClass) ────────────────── +// ── Vehicle type config (1-to-1 with the carrier service's SizeClass) ─────── +// +// `fleet_type` is the fleet service's own vehicle enum, sent when registering +// the vehicle in step 1. It is not the marketplace size class. interface TypeConfig { label: string; - size_class: SizeClass; + fleet_type: VehicleType; icon: string; - def_features: VehicleFeature[]; def_weight_kg: number; def_base_php: number; def_km_php: number; } -const TYPE_CONFIG: Record = { - Scooter: { label: "Scooter / Bicycle", size_class: "scooter_bicycle", icon: "🛵", def_features: [], def_weight_kg: 30, def_base_php: 150, def_km_php: 8 }, - Motorcycle: { label: "Motorcycle", size_class: "motorcycle", icon: "🏍", def_features: [], def_weight_kg: 80, def_base_php: 250, def_km_php: 12 }, - Sedan: { label: "Sedan", size_class: "sedan", icon: "🚗", def_features: [], def_weight_kg: 300, def_base_php: 500, def_km_php: 15 }, - Van: { label: "Van", size_class: "van", icon: "🚐", def_features: [], def_weight_kg: 800, def_base_php: 900, def_km_php: 18 }, - Truck_1T: { label: "1 Ton - Pickup", size_class: "1ton", icon: "🚛", def_features: [], def_weight_kg: 1000, def_base_php: 1200, def_km_php: 22 }, - Truck_3T: { label: "3 Ton", size_class: "3ton", icon: "🚛", def_features: [], def_weight_kg: 3000, def_base_php: 2200, def_km_php: 28 }, - Truck_7T: { label: "7 Ton", size_class: "7ton", icon: "🚛", def_features: [], def_weight_kg: 7000, def_base_php: 3800, def_km_php: 35 }, - Truck_10T: { label: "10 Ton", size_class: "10ton", icon: "🚛", def_features: [], def_weight_kg: 10000, def_base_php: 5500, def_km_php: 42 }, - Trailer: { label: "Trailer", size_class: "trailer", icon: "🚚", def_features: [], def_weight_kg: 20000, def_base_php: 9000, def_km_php: 55 }, - Refrigerated_Truck: { label: "Refrigerated Truck", size_class: "refrigerated_truck", icon: "❄️", def_features: [], def_weight_kg: 5000, def_base_php: 4500, def_km_php: 40 }, - Recovery_Truck: { label: "Recovery Truck", size_class: "recovery_truck", icon: "🔧", def_features: [], def_weight_kg: 5000, def_base_php: 3000, def_km_php: 35 }, +const TYPE_CONFIG: Record = { + motorcycle: { label: SIZE_CLASS_LABEL.motorcycle, fleet_type: "Motorcycle", icon: "🏍", def_weight_kg: 80, def_base_php: 250, def_km_php: 12 }, + sedan: { label: SIZE_CLASS_LABEL.sedan, fleet_type: "Sedan", icon: "🚗", def_weight_kg: 300, def_base_php: 500, def_km_php: 15 }, + van: { label: SIZE_CLASS_LABEL.van, fleet_type: "Van", icon: "🚐", def_weight_kg: 800, def_base_php: 900, def_km_php: 18 }, + l300: { label: SIZE_CLASS_LABEL.l300, fleet_type: "Truck_1T", icon: "🚛", def_weight_kg: 1500, def_base_php: 1200, def_km_php: 22 }, + "6wheeler": { label: SIZE_CLASS_LABEL["6wheeler"], fleet_type: "Truck_7T", icon: "🚛", def_weight_kg: 5000, def_base_php: 3800, def_km_php: 35 }, + "10wheeler":{ label: SIZE_CLASS_LABEL["10wheeler"], fleet_type: "Truck_10T", icon: "🚛", def_weight_kg: 10000, def_base_php: 5500, def_km_php: 42 }, + trailer: { label: SIZE_CLASS_LABEL.trailer, fleet_type: "Trailer", icon: "🚚", def_weight_kg: 20000, def_base_php: 9000, def_km_php: 55 }, }; -const ALL_TYPES = Object.keys(TYPE_CONFIG) as VehicleType[]; +const ALL_TYPES = Object.keys(TYPE_CONFIG) as SizeClass[]; // Most-used vehicle colors in PH logistics fleet (ordered by frequency) const COMMON_COLORS = [ @@ -94,37 +94,11 @@ const MODELS_BY_MAKE: Record>> = { "UD Trucks": { Truck_3T: ["Condor MK11E"], Truck_7T: ["Condor PK9E"], Truck_10T: ["Quester CWE"], Trailer: ["Quester CGE"] }, }; -// ── Feature metadata ────────────────────────────────────────────────────────── - -const FEATURE_META: Record = { - tail_lift: { - label: "Tail-lift Gate", - activeClass: "border-amber-400/50 bg-amber-400/15 text-amber-300", - inactiveClass:"border-glass-border bg-glass-100 text-white/40", - }, - chiller: { - label: "Chiller (0–8 °C)", - activeClass: "border-cyan-neon/50 bg-cyan-neon/15 text-cyan-neon", - inactiveClass:"border-glass-border bg-glass-100 text-white/40", - }, - freezer: { - label: "Freezer (−18 °C)", - activeClass: "border-blue-400/50 bg-blue-400/15 text-blue-300", - inactiveClass:"border-glass-border bg-glass-100 text-white/40", - }, -}; - -const FEATURE_ICONS: Record = { - tail_lift: "⬆", - chiller: "🌡", - freezer: "❄️", -}; - // ── Types ───────────────────────────────────────────────────────────────────── interface Step1Fields { plate_number: string; - vehicle_type: VehicleType; + size_class: SizeClass; make: string; model: string; year: string; @@ -133,7 +107,6 @@ interface Step1Fields { interface Step2Fields { list_on_marketplace: boolean; - features: VehicleFeature[]; max_weight_kg: string; base_price_php: string; per_km_php: string; @@ -159,13 +132,12 @@ interface Props { const STEP_LABELS = ["Vehicle Identity", "Marketplace Listing"]; const THIS_YEAR = new Date().getFullYear(); -function defaultStep2(vtype: VehicleType = "Van"): Step2Fields { +function defaultStep2(vtype: SizeClass = "van"): Step2Fields { const cfg = TYPE_CONFIG[vtype]; const now = new Date(); const end = new Date(now.getTime() + 6 * 3_600_000); return { list_on_marketplace: true, - features: [...cfg.def_features], max_weight_kg: String(cfg.def_weight_kg), base_price_php: String(cfg.def_base_php), per_km_php: String(cfg.def_km_php), @@ -184,24 +156,9 @@ const inputCls = const labelCls = "block text-xs text-white/50 mb-1.5 font-medium"; -// ── FeatureBadge (small inline tag) ────────────────────────────────────────── - -function FeatureBadge({ feature }: { feature: VehicleFeature }) { - const palette: Record = { - tail_lift: "text-amber-400 bg-amber-400/10 border-amber-400/20", - chiller: "text-cyan-400 bg-cyan-400/10 border-cyan-400/20", - freezer: "text-blue-400 bg-blue-400/10 border-blue-400/20", - }; - return ( - - {FEATURE_ICONS[feature]} {FEATURE_META[feature].label.split(" ")[0]} - - ); -} - // ── VehicleTypePicker ───────────────────────────────────────────────────────── -function VehicleTypePicker({ value, onChange }: { value: VehicleType; onChange: (v: VehicleType) => void }) { +function VehicleTypePicker({ value, onChange }: { value: SizeClass; onChange: (v: SizeClass) => void }) { const [open, setOpen] = useState(false); const ref = useRef(null); const cfg = TYPE_CONFIG[value]; @@ -224,11 +181,6 @@ function VehicleTypePicker({ value, onChange }: { value: VehicleType; onChange: {cfg.icon} {cfg.label} - {cfg.def_features.length > 0 && ( - - {cfg.def_features.map((f) => )} - - )} {c.label} - {c.def_features.map((f) => )} {active && ( )} @@ -383,26 +334,39 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { const [error, setError] = useState(null); const [s1, setS1] = useState({ - plate_number: "", vehicle_type: "Van", + plate_number: "", size_class: "van", make: "", model: "", year: String(THIS_YEAR), color: "", }); - const [s2, setS2] = useState(() => defaultStep2("Van")); + const [s2, setS2] = useState(() => defaultStep2("van")); const [result, setResult] = useState(null); + const [carriers, setCarriers] = useState([]); + const [carrierId, setCarrierId] = useState(""); + const [carriersError, setCarriersError] = useState(false); + + // The listing belongs to a carrier in this tenant; load the choices when the modal opens. + useEffect(() => { + if (!open) return; + let live = true; + fetchCarrierOptions() + .then((c) => { if (live) { setCarriers(c); setCarriersError(false); } }) + .catch(() => { if (live) setCarriersError(true); }); + return () => { live = false; }; + }, [open]); function reset() { setStep(1); setLoading(false); setError(null); setResult(null); - setS1({ plate_number: "", vehicle_type: "Van", make: "", model: "", year: String(THIS_YEAR), color: "" }); - setS2(defaultStep2("Van")); + setS1({ plate_number: "", size_class: "van", make: "", model: "", year: String(THIS_YEAR), color: "" }); + setS2(defaultStep2("van")); + setCarrierId(""); } function handleClose() { reset(); onClose(); } - function handleTypeChange(type: VehicleType) { - setS1((p) => ({ ...p, vehicle_type: type, make: "", model: "" })); + function handleTypeChange(type: SizeClass) { + setS1((p) => ({ ...p, size_class: type, make: "", model: "" })); const cfg = TYPE_CONFIG[type]; setS2((p) => ({ ...p, - features: [...cfg.def_features], max_weight_kg: String(cfg.def_weight_kg), base_price_php:String(cfg.def_base_php), per_km_php: String(cfg.def_km_php), @@ -413,15 +377,6 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { setS1((p) => ({ ...p, make, model: "" })); } - function toggleFeature(f: VehicleFeature) { - setS2((p) => ({ - ...p, - features: p.features.includes(f) - ? p.features.filter((x) => x !== f) - : [...p.features, f], - })); - } - // ── Step 1: Register vehicle in fleet service ──────────────────────────────── async function handleStep1(e: React.FormEvent) { e.preventDefault(); @@ -436,7 +391,7 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { const api = createFleetApi(); const payload: RegisterVehiclePayload = { plate_number: s1.plate_number.toUpperCase().trim(), - vehicle_type: s1.vehicle_type, + vehicle_type: TYPE_CONFIG[s1.size_class].fleet_type, make: s1.make.trim(), model: s1.model.trim(), year, @@ -467,6 +422,7 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { if (isNaN(weightKg) || weightKg <= 0) { setError("Max weight must be a positive number."); return; } if (isNaN(baseCents) || baseCents <= 0) { setError("Base price must be a positive number."); return; } if (isNaN(kmCents) || kmCents <= 0) { setError("Per-km rate must be a positive number."); return; } + if (!carrierId) { setError("Choose the carrier this listing belongs to."); return; } if (!s2.service_area_label.trim()) { setError("Service area is required."); return; } if (new Date(s2.idle_until) <= new Date(s2.idle_from)) { setError("'Available until' must be after 'Available from'."); return; @@ -475,9 +431,9 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { setError(null); setLoading(true); try { const listing: CreateListingPayload = { + carrier_id: carrierId, vehicle_plate: result.plate, - size_class: TYPE_CONFIG[s1.vehicle_type].size_class, - features: s2.features, + size_class: s1.size_class, max_weight_kg: weightKg, max_volume_m3: null, base_price_cents: baseCents, @@ -486,7 +442,6 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { service_area_label: s2.service_area_label.trim(), idle_from: new Date(s2.idle_from).toISOString(), idle_until: new Date(s2.idle_until).toISOString(), - status: "active", carrier_response_window_mins: 15, }; await createVehicleListing(listing); @@ -496,9 +451,7 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { } catch (err: unknown) { const e = err as { message?: string }; setError( - e.message?.includes("carrier") || e.message?.includes("401") || e.message?.includes("403") - ? "Vehicle registered. Marketplace listing requires carrier portal access — list it from the Partner Portal." - : (e.message ?? "Marketplace listing failed. The vehicle was registered successfully."), + `Vehicle registered, but the marketplace listing failed: ${e.message ?? "unknown error"}`, ); } finally { setLoading(false); @@ -507,9 +460,10 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { if (!open) return null; - const vCfg = TYPE_CONFIG[s1.vehicle_type]; - const makeOptions = MAKES_BY_TYPE[s1.vehicle_type] ?? []; - const modelOptions = (MODELS_BY_MAKE[s1.make]?.[s1.vehicle_type] ?? []); + const vCfg = TYPE_CONFIG[s1.size_class]; + const fleetType = vCfg.fleet_type; + const makeOptions = MAKES_BY_TYPE[fleetType] ?? []; + const modelOptions = (MODELS_BY_MAKE[s1.make]?.[fleetType] ?? []); return ( @@ -598,10 +552,10 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) {
- {/* Vehicle Type — full SizeClass list with feature badges */} + {/* Vehicle Type — the carrier service's SizeClass list */}
- +
{/* Make + Model — combobox with brand pre-fill */} @@ -702,35 +656,21 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { {/* Listing fields */} {s2.list_on_marketplace && (
-
- 🏢 Listed under: LogisticOS Platform Fleet · auto-assigned carrier -
- - {/* Vehicle Features */}
- -
- {(["tail_lift", "chiller", "freezer"] as VehicleFeature[]).map((f) => { - const meta = FEATURE_META[f]; - const checked = s2.features.includes(f); - return ( - - ); - })} -
+ + + {carriersError && ( +

Carriers could not be loaded. Close and reopen to retry.

+ )}
{/* Weight + Pricing */} @@ -886,14 +826,6 @@ export function RegisterVehicleModal({ open, onClose, onSuccess }: Props) { Marketplace Listed · Active
- {s2.features.length > 0 && ( -
- Features - - {s2.features.map((f) => )} - -
- )} )} diff --git a/apps/admin-portal/src/components/marketplace/ReceiptModal.tsx b/apps/admin-portal/src/components/marketplace/ReceiptModal.tsx index 7d3f23982..8a6b4842e 100644 --- a/apps/admin-portal/src/components/marketplace/ReceiptModal.tsx +++ b/apps/admin-portal/src/components/marketplace/ReceiptModal.tsx @@ -1,48 +1,25 @@ "use client"; /** - * Shipment Receipt Modal — renders a BusReceipt or an issue form for a booking - * that has no receipt yet. Shared structure across portals (partner, merchant, - * admin) so the customer-facing artifact is identical regardless of where it's - * viewed. Partner owns the issue mutation; merchant and admin are read-only. - * - * Production: modal fetches `GET /v1/marketplace/receipts/by-booking/{id}` and, - * on issue, POSTs `/v1/marketplace/receipts`. The engagement engine then fans - * it out to the consumer's preferred channel (ADR-0013 §Booking flow). + * Booking receipt — a read-only summary of a marketplace booking, driven + * straight from the `MarketplaceBooking` the carrier service returned. It shows + * only what the booking holds: there is no separate receipt record. */ import { useState } from "react"; import { motion, AnimatePresence } from "framer-motion"; -import { X, Printer, Share2, CheckCircle2, FileText, Loader2 } from "lucide-react"; +import { X, Printer, Share2, CheckCircle2, FileText } from "lucide-react"; import { cn } from "@/lib/design-system/cn"; -import type { BusReceipt, BusBookingStatus } from "@/lib/api/marketplace-bus"; - -export interface ReceiptModalBooking { - id: string; - awb: string; - partner_display_name: string; - merchant_display?: string; - consumer_display?: string; - pickup_label: string; - dropoff_label: string; - pickup_at: string; - cargo_weight_kg: number; - quoted_price_cents: number; - status: BusBookingStatus; -} +import { useDialogA11y } from "@/lib/hooks/use-dialog-a11y"; +import { formatCentsPhp, type MarketplaceBooking } from "@/lib/api/marketplace"; interface Props { - open: boolean; - onClose: () => void; - booking?: ReceiptModalBooking | null; // required when receipt is null (for issue form) - receipt: BusReceipt | null; - /** Provide to show the issue form when receipt is null. Partner-side only. */ - onIssue?: (input: { signed_by: string; notes: string }) => Promise; + open: boolean; + onClose: () => void; + booking: MarketplaceBooking | null; } -function fmtPhp(cents: number): string { - return "₱" + (cents / 100).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ","); -} +const TITLE_ID = "booking-receipt-title"; function fmtDateTime(iso: string): string { return new Date(iso).toLocaleString("en-PH", { @@ -51,46 +28,32 @@ function fmtDateTime(iso: string): string { }); } -export function ReceiptModal({ open, onClose, booking, receipt, onIssue }: Props) { - const [signedBy, setSignedBy] = useState(""); - const [notes, setNotes] = useState(""); - const [busy, setBusy] = useState(false); - const [copied, setCopied] = useState(false); +const PAYMENT_STATUS_LABEL: Record = { + pending: "Pending", + authorized: "Authorized", + captured: "Paid", + voided: "Voided", + failed: "Failed", +}; - const canIssue = open && !receipt && !!booking && !!onIssue; - const showPrint = open && !!receipt; +export function ReceiptModal({ open, onClose, booking }: Props) { + const [copied, setCopied] = useState(false); + const dialogRef = useDialogA11y(open && !!booking, onClose); - async function handleIssue() { - if (!onIssue) return; - setBusy(true); + async function handleCopyAwb() { + if (!booking) return; try { - await onIssue({ signed_by: signedBy.trim(), notes: notes.trim() }); - setSignedBy(""); - setNotes(""); - } finally { - setBusy(false); - } - } - - async function handleCopyShareLink() { - if (!receipt) return; - const shareUrl = `https://cargomarket.app/t/${receipt.awb}`; - try { - await navigator.clipboard.writeText(shareUrl); + await navigator.clipboard.writeText(booking.awb); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch { - // Clipboard permission may be denied — silent no-op, user can still print. + // Clipboard permission may be denied: silent no-op, the AWB is on screen. } } - function handlePrint() { - if (typeof window !== "undefined") window.print(); - } - return ( - {open && ( + {open && booking && ( <>