23 Commits

Author SHA1 Message Date
23186ffd29 feat(ticket): add paginated class detection preview with image and map 2026-07-08 10:48:03 +05:30
fb9a654aea feat(results): replace video playback with detection image preview and map 2026-07-07 15:36:27 +05:30
d88978a830 chore: class location change 2026-07-07 12:02:29 +05:30
ba9731de86 refactor: refactor report proff section 2026-07-06 17:04:05 +05:30
c0f3a718ef feat(upload): display no-defects analysis result 2026-07-06 14:17:32 +05:30
14220445ad chore: ignore auto-generated next-env.d.ts 2026-07-04 00:57:42 +05:30
79272c7abc feat(ticket): add extension requests and improve repair proof upload UI 2026-07-04 00:56:08 +05:30
26e15360f7 feat(ticket): add due date picker and contractor details to assign flow 2026-07-03 16:07:08 +05:30
b6a0f04f1e Merge branch 'videoplayer' of https://git.convexsol.co/santasri.pachhal/visionRoad-ui into feat/mod 2026-07-03 10:36:32 +05:30
9cf4f0e795 feat(ticket): redesign overview with AI summary, location, and shared defect visuals 2026-07-03 10:30:59 +05:30
fdcfc3a8db feat: add action to open ticket action in upload 2026-07-02 15:44:26 +05:30
278b9591d7 feat: added sse for upload section 2026-07-02 14:28:28 +05:30
02adbb4c10 feat: introduce custom video player for video analysis 2026-07-02 14:23:00 +05:30
53fe4e11fe feat: change interface of analysis video log 2026-07-02 13:57:18 +05:30
2eb58856af feat(ticket): add section icons, theme-aware system timeline, and nested sidebar active routes 2026-07-02 11:33:53 +05:30
c73ba0a01f feat(ticket): redesign audit timeline with structured history events 2026-07-01 22:23:49 +05:30
1a94ff80e6 fix: scrollbar gutter shifting issue 2026-07-01 17:28:25 +05:30
b1174c8825 feat(ticket): split overview/class detail queries and add loading skeletons 2026-07-01 16:13:42 +05:30
d4a7a7c139 chore(ticket) : add uploader email to ticket list 2026-07-01 14:49:48 +05:30
57b33bd061 feat(upload): add upload status column and rename analysis status 2026-07-01 12:38:53 +05:30
81df3a9973 refactor: remove all trace of status from ticket 2026-07-01 10:14:19 +05:30
09ce57c9e0 refactor(ticket): remove ticket status from list events and use assignment status for closure 2026-06-30 19:30:44 +05:30
ea684fc9fe refactor(upload): replace upload card views with list table and addition details in table 2026-06-30 18:03:50 +05:30
95 changed files with 4831 additions and 1846 deletions

1
.gitignore vendored
View File

@@ -44,6 +44,7 @@ Thumbs.db
# TypeScript # TypeScript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts
# Test / coverage # Test / coverage
coverage/ coverage/

6
next-env.d.ts vendored
View File

@@ -1,6 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

147
package-lock.json generated
View File

@@ -23,26 +23,34 @@
"@tanstack/react-query-devtools": "^5.101.0", "@tanstack/react-query-devtools": "^5.101.0",
"@tanstack/react-table": "^8.21.3", "@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.14.3", "@tanstack/react-virtual": "^3.14.3",
"@vidstack/react": "^1.15.6",
"axios": "^1.13.6", "axios": "^1.13.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"date-fns": "^4.4.0",
"leaflet": "^1.9.4",
"libphonenumber-js": "^1.13.7", "libphonenumber-js": "^1.13.7",
"lightgallery": "^2.9.0",
"lucide-react": "^0.548.0", "lucide-react": "^0.548.0",
"motion": "^12.38.0", "motion": "^12.38.0",
"next": "16.0.10", "next": "16.0.10",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"radix-ui": "^1.6.0", "radix-ui": "^1.6.0",
"react": "19.2.0", "react": "19.2.0",
"react-day-picker": "^10.0.1",
"react-dom": "19.2.0", "react-dom": "19.2.0",
"react-hook-form": "^7.79.0", "react-hook-form": "^7.79.0",
"react-leaflet": "^5.0.0",
"recharts": "2.15.4", "recharts": "2.15.4",
"sonner": "^1.7.4", "sonner": "^1.7.4",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1",
"vaul": "^1.1.2",
"zod": "^4.4.3", "zod": "^4.4.3",
"zustand": "^5.0.14" "zustand": "^5.0.14"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.1.9", "@tailwindcss/postcss": "^4.1.9",
"@types/leaflet": "^1.9.21",
"@types/node": "^22", "@types/node": "^22",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
@@ -402,6 +410,12 @@
} }
} }
}, },
"node_modules/@date-fns/tz": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz",
"integrity": "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==",
"license": "MIT"
},
"node_modules/@emnapi/core": { "node_modules/@emnapi/core": {
"version": "1.9.0", "version": "1.9.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.0.tgz", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.0.tgz",
@@ -2879,6 +2893,17 @@
"integrity": "sha512-xnXE7wG13PI+cxieVssYXlQJuYVRhH9NBoxt3KNwzghDIA69GMm7d4wXRouHIYjE+KvS6U/MsMO73NdS2MH9ZA==", "integrity": "sha512-xnXE7wG13PI+cxieVssYXlQJuYVRhH9NBoxt3KNwzghDIA69GMm7d4wXRouHIYjE+KvS6U/MsMO73NdS2MH9ZA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@react-leaflet/core": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@react-leaflet/core/-/core-3.0.0.tgz",
"integrity": "sha512-3EWmekh4Nz+pGcr+xjf0KNyYfC3U2JjnkWsh0zcqaexYqmmB5ZhH37kz41JXGmKzpaMZCnPofBBm64i+YrEvGQ==",
"license": "Hippocratic-2.1",
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
},
"node_modules/@rtsao/scc": { "node_modules/@rtsao/scc": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",
@@ -3366,6 +3391,13 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/json-schema": { "node_modules/@types/json-schema": {
"version": "7.0.15", "version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -3380,6 +3412,16 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/leaflet": {
"version": "1.9.21",
"resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.21.tgz",
"integrity": "sha512-TbAd9DaPGSnzp6QvtYngntMZgcRk+igFELwR2N99XZn7RXUdKgsXMR+28bUO0rPsWp8MIu/f47luLIQuSLYv/w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "22.19.15", "version": "22.19.15",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
@@ -3394,7 +3436,6 @@
"version": "19.2.14", "version": "19.2.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
"devOptional": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"csstype": "^3.2.2" "csstype": "^3.2.2"
@@ -3961,6 +4002,23 @@
"win32" "win32"
] ]
}, },
"node_modules/@vidstack/react": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/@vidstack/react/-/react-1.15.6.tgz",
"integrity": "sha512-hO7cLld5yfxCdDnDCYqh5aS7JxmHfsmX43PmKBJWzDTwK40P3hh5qAdDQzl3qDtEJLYjuo3Sv+kr6tt/VRtJzQ==",
"license": "MIT",
"dependencies": {
"@floating-ui/dom": "^1.6.10",
"media-captions": "^1.0.4"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
}
},
"node_modules/acorn": { "node_modules/acorn": {
"version": "8.16.0", "version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
@@ -4763,6 +4821,16 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/date-fns": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
"integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
}
},
"node_modules/debug": { "node_modules/debug": {
"version": "4.4.3", "version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -6820,6 +6888,12 @@
"node": ">=0.10" "node": ">=0.10"
} }
}, },
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause"
},
"node_modules/levn": { "node_modules/levn": {
"version": "0.4.1", "version": "0.4.1",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
@@ -6840,6 +6914,15 @@
"integrity": "sha512-rvr3HIMdOgzhz1RFGjftji+wjoAFlzhqCNqJOU/MKTZQ8d9NZxAR/tI+0weDicyoucqVR0U1GCniqHJ0f8aM2A==", "integrity": "sha512-rvr3HIMdOgzhz1RFGjftji+wjoAFlzhqCNqJOU/MKTZQ8d9NZxAR/tI+0weDicyoucqVR0U1GCniqHJ0f8aM2A==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/lightgallery": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/lightgallery/-/lightgallery-2.9.0.tgz",
"integrity": "sha512-58Ud1DyhD2ao58t+kPEqSZrjFxg23tGd5ZKr75erm7q31g5xhUtWUJH3sTUkhHzlyJAKHj5eTrJ37HQRXG4Wbg==",
"license": "GPLv3",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/lightningcss": { "node_modules/lightningcss": {
"version": "1.31.1", "version": "1.31.1",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.31.1.tgz", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.31.1.tgz",
@@ -7180,6 +7263,15 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/media-captions": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/media-captions/-/media-captions-1.0.4.tgz",
"integrity": "sha512-cyDNmuZvvO4H27rcBq2Eudxo9IZRDCOX/I7VEyqbxsEiD2Ei7UYUhG/Sc5fvMZjmathgz3fEK7iAKqvpY+Ux1w==",
"license": "MIT",
"engines": {
"node": ">=16"
}
},
"node_modules/merge2": { "node_modules/merge2": {
"version": "1.4.1", "version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@@ -7953,6 +8045,32 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/react-day-picker": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-10.0.1.tgz",
"integrity": "sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w==",
"license": "MIT",
"dependencies": {
"@date-fns/tz": "^1.4.1",
"date-fns": "^4.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/gpbl"
},
"peerDependencies": {
"@types/react": ">=16.8.0",
"react": ">=16.8.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/react-dom": { "node_modules/react-dom": {
"version": "19.2.0", "version": "19.2.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",
@@ -7987,6 +8105,20 @@
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/react-leaflet": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-5.0.0.tgz",
"integrity": "sha512-CWbTpr5vcHw5bt9i4zSlPEVQdTVcML390TjeDG0cK59z1ylexpqC6M1PJFjV8jD7CF+ACBFsLIDs6DRMoLEofw==",
"license": "Hippocratic-2.1",
"dependencies": {
"@react-leaflet/core": "^3.0.0"
},
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
},
"node_modules/react-remove-scroll": { "node_modules/react-remove-scroll": {
"version": "2.7.2", "version": "2.7.2",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
@@ -9189,6 +9321,19 @@
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
} }
}, },
"node_modules/vaul": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",
"integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-dialog": "^1.1.1"
},
"peerDependencies": {
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
}
},
"node_modules/victory-vendor": { "node_modules/victory-vendor": {
"version": "36.9.2", "version": "36.9.2",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz", "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",

View File

@@ -27,26 +27,34 @@
"@tanstack/react-query-devtools": "^5.101.0", "@tanstack/react-query-devtools": "^5.101.0",
"@tanstack/react-table": "^8.21.3", "@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.14.3", "@tanstack/react-virtual": "^3.14.3",
"@vidstack/react": "^1.15.6",
"axios": "^1.13.6", "axios": "^1.13.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"date-fns": "^4.4.0",
"leaflet": "^1.9.4",
"libphonenumber-js": "^1.13.7", "libphonenumber-js": "^1.13.7",
"lightgallery": "^2.9.0",
"lucide-react": "^0.548.0", "lucide-react": "^0.548.0",
"motion": "^12.38.0", "motion": "^12.38.0",
"next": "16.0.10", "next": "16.0.10",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"radix-ui": "^1.6.0", "radix-ui": "^1.6.0",
"react": "19.2.0", "react": "19.2.0",
"react-day-picker": "^10.0.1",
"react-dom": "19.2.0", "react-dom": "19.2.0",
"react-hook-form": "^7.79.0", "react-hook-form": "^7.79.0",
"react-leaflet": "^5.0.0",
"recharts": "2.15.4", "recharts": "2.15.4",
"sonner": "^1.7.4", "sonner": "^1.7.4",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1",
"vaul": "^1.1.2",
"zod": "^4.4.3", "zod": "^4.4.3",
"zustand": "^5.0.14" "zustand": "^5.0.14"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.1.9", "@tailwindcss/postcss": "^4.1.9",
"@types/leaflet": "^1.9.21",
"@types/node": "^22", "@types/node": "^22",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",

View File

@@ -16,7 +16,7 @@ const ModulesLayout = ({
<SidebarProvider> <SidebarProvider>
<AppSidebar /> <AppSidebar />
<main className="flex flex-1 flex-col w-full h-screen overflow-hidden"> <main className="flex flex-1 flex-col w-full h-screen overflow-hidden">
<div className="flex-1 overflow-auto"> <div className="scroll-stable flex-1 overflow-auto">
<div className="max-w-380 mx-auto w-full flex flex-col min-h-full"> <div className="max-w-380 mx-auto w-full flex flex-col min-h-full">
<div className="flex gap-3 items-center sticky top-0 bg-background z-50 py-3 px-6 border-b border-border"> <div className="flex gap-3 items-center sticky top-0 bg-background z-50 py-3 px-6 border-b border-border">
<SidebarTrigger /> <SidebarTrigger />

View File

@@ -14,10 +14,13 @@ function StatSkeleton() {
function DetectionLogSkeleton() { function DetectionLogSkeleton() {
return ( return (
<div className="rounded-md border bg-card p-4"> <div className="rounded-md border bg-card p-3">
<div className="mb-3 flex items-start justify-between gap-4"> <div className="flex gap-3">
<Skeleton className="size-20 shrink-0 rounded-md" />
<div className="min-w-0 flex-1 space-y-2">
<div className="flex items-start justify-between gap-3">
<div className="space-y-2"> <div className="space-y-2">
<Skeleton className="h-4 w-36" /> <Skeleton className="h-5 w-28" />
<Skeleton className="h-3 w-20" /> <Skeleton className="h-3 w-20" />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
@@ -25,11 +28,11 @@ function DetectionLogSkeleton() {
<Skeleton className="h-3 w-10" /> <Skeleton className="h-3 w-10" />
</div> </div>
</div> </div>
<div className="space-y-2">
<Skeleton className="h-3 w-32" /> <Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-44" /> <Skeleton className="h-3 w-44" />
</div> </div>
</div> </div>
</div>
); );
} }

View File

@@ -0,0 +1,111 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
export function TicketClassContentSkeleton() {
return (
<div className="space-y-5" aria-label="Loading defect class details">
<Card>
<CardHeader className="sm:grid-cols-[1fr_auto]">
<Skeleton className="h-5 w-36" />
<Skeleton className="h-3 w-32 sm:col-start-2 sm:row-start-1" />
</CardHeader>
<CardContent className="space-y-5">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{Array.from({ length: 2 }).map((_, index) => (
<div key={index} className="space-y-1">
<Skeleton className="h-3 w-20" />
<Skeleton className="h-4 w-36" />
</div>
))}
</div>
<div className="space-y-2">
<Skeleton className="h-3 w-24" />
<div className="rounded-lg border bg-muted/15 px-4 py-3">
<Skeleton className="h-4 w-full" />
<Skeleton className="mt-2 h-4 w-3/4" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<Skeleton className="h-5 w-40" />
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Skeleton className="aspect-video w-full rounded-md" />
<Skeleton className="aspect-video w-full rounded-md" />
</CardContent>
</Card>
<Card>
<CardHeader>
<Skeleton className="h-5 w-32" />
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{Array.from({ length: 5 }).map((_, index) => (
<div key={index} className="space-y-2 rounded-lg border p-2">
<Skeleton className="aspect-4/3 w-full rounded-lg" />
<Skeleton className="h-3 w-16" />
</div>
))}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Skeleton className="size-5 rounded" />
<Skeleton className="h-5 w-56" />
</div>
</CardHeader>
<CardContent>
{Array.from({ length: 3 }).map((_, index) => (
<div key={index} className="relative flex gap-4 pb-8 last:pb-0">
{index < 2 ? (
<span className="absolute top-6 left-2.75 h-[calc(100%-10px)] w-px bg-border" />
) : null}
<Skeleton className="relative z-10 mt-0.5 size-6 shrink-0 rounded-full" />
<div className="min-w-0 flex-1 space-y-3">
<div className="flex flex-wrap items-center gap-3">
<Skeleton className="h-4 w-44" />
<Skeleton className="h-3 w-28" />
</div>
<Skeleton className="h-3 w-56" />
<Skeleton className="h-12 w-full" />
</div>
</div>
))}
</CardContent>
</Card>
</div>
);
}
export function TicketClassActionsSkeleton() {
return (
<Card aria-label="Loading defect class actions">
<CardHeader>
<div className="flex items-center gap-2">
<Skeleton className="size-4 rounded" />
<Skeleton className="h-5 w-32" />
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="space-y-2">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-10 w-full" />
</div>
<div className="space-y-2">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-20 w-full" />
</div>
<Skeleton className="h-10 w-full" />
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,280 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { AlertTriangle, ChevronLeft, ChevronRight } from 'lucide-react';
import DetectionLocationMap from '@/components/map/detectionLocationMap';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import AnnotatedDetectionImage from '@/components/video/annotatedDetectionImage';
import { getDefectVisual } from '@/constants/defectVisualConfig';
import { cn } from '@/lib/utils';
import { useTicketClassDetectionsQuery } from '../../hooks/useTicketQueries';
interface TicketClassDetectionPreviewProps {
videoId?: string | null;
defectClassName: string;
displayName: string;
totalCount?: number;
}
function DetectionMetadataBar({
items,
}: {
items: { label: string; value: string | number }[];
}) {
return (
<div className="rounded-lg bg-muted/40 px-4 py-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 sm:divide-x sm:divide-border/70">
{items.map((item, index) => (
<div
key={item.label}
className={cn(
'space-y-1',
index === 0 && 'sm:pr-4',
index === 1 && 'sm:px-4',
index === 2 && 'sm:pl-4',
)}
>
<p className="text-xs text-muted-foreground">{item.label}</p>
<div className="text-sm font-semibold text-foreground">
{item.value}
</div>
</div>
))}
</div>
</div>
);
}
function TicketClassDetectionPreviewSkeleton() {
return (
<>
<div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
<div className="min-w-0 space-y-2">
<Skeleton className="h-3 w-24" />
<Skeleton className="aspect-video w-full rounded-lg" />
</div>
<div className="min-w-0 space-y-2">
<Skeleton className="h-3 w-28" />
<Skeleton
className="w-full rounded-lg"
style={{ aspectRatio: '16 / 9' }}
/>
</div>
</div>
<div className="rounded-lg bg-muted/40 px-4 py-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 sm:divide-x sm:divide-border/70">
{Array.from({ length: 3 }).map((_, index) => (
<div
key={index}
className={cn(
'space-y-1',
index === 0 && 'sm:pr-4',
index === 1 && 'sm:px-4',
index === 2 && 'sm:pl-4',
)}
>
<Skeleton className="h-3 w-16" />
<Skeleton className="h-4 w-20" />
</div>
))}
</div>
</div>
</>
);
}
export function TicketClassDetectionPreview({
videoId,
defectClassName,
displayName,
totalCount,
}: TicketClassDetectionPreviewProps) {
const [currentIndex, setCurrentIndex] = useState(0);
const visual = getDefectVisual(defectClassName);
const IssueIcon = visual.icon;
useEffect(() => {
setCurrentIndex(0);
}, [defectClassName]);
const queryParams = useMemo(
() => ({
class_name: defectClassName,
skip: currentIndex,
limit: 1,
sort: 'timestamp_asc',
}),
[currentIndex, defectClassName],
);
const detectionsQuery = useTicketClassDetectionsQuery(
videoId ?? undefined,
queryParams,
);
const detectionResult = detectionsQuery.data;
const activeDetection = detectionResult?.items[0];
const detectionCount = detectionResult?.total ?? totalCount ?? 0;
const mediaAspectRatio =
detectionResult &&
detectionResult.video_width > 0 &&
detectionResult.video_height > 0
? `${detectionResult.video_width} / ${detectionResult.video_height}`
: '16 / 9';
useEffect(() => {
if (detectionCount === 0 && currentIndex !== 0) {
setCurrentIndex(0);
return;
}
if (detectionCount > 0 && currentIndex > detectionCount - 1) {
setCurrentIndex(detectionCount - 1);
}
}, [currentIndex, detectionCount]);
const isPreviousDisabled = currentIndex === 0 || detectionsQuery.isLoading;
const isNextDisabled =
detectionCount === 0 ||
currentIndex + 1 >= detectionCount ||
detectionsQuery.isLoading;
return (
<div className="space-y-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 items-center gap-3">
<span
className={cn(
'flex size-10 shrink-0 items-center justify-center rounded-full',
visual.cardClassName,
)}
>
<IssueIcon className={cn('size-5', visual.colorClassName)} />
</span>
<div className="min-w-0 space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<h3 className="truncate text-lg font-semibold text-foreground">
{displayName}
</h3>
<Badge
variant="secondary"
className={cn(
'rounded-full border-0 px-2.5 py-1 text-xs font-semibold',
visual.cardClassName,
visual.colorClassName,
)}
>
{detectionCount} Detections
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Review detections in ascending timestamp order.
</p>
</div>
</div>
<div className="flex items-center gap-2 self-start sm:self-auto">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setCurrentIndex((index) => Math.max(index - 1, 0))}
disabled={isPreviousDisabled}
>
<ChevronLeft className="size-4" />
Previous
</Button>
<div className="min-w-16 text-center text-sm font-medium text-foreground">
{detectionCount === 0
? '0 of 0'
: `${currentIndex + 1} of ${detectionCount}`}
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setCurrentIndex((index) => index + 1)}
disabled={isNextDisabled}
>
Next
<ChevronRight className="size-4" />
</Button>
</div>
</div>
{detectionsQuery.isLoading && !detectionsQuery.data ? (
<TicketClassDetectionPreviewSkeleton />
) : detectionsQuery.isError ? (
<div className="rounded-lg border border-dashed border-destructive/40 bg-destructive/5 px-4 py-8 text-center">
<div className="flex flex-col items-center gap-2">
<AlertTriangle className="size-6 text-destructive" />
<p className="text-sm font-medium text-destructive">
Failed to load detection preview.
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void detectionsQuery.refetch()}
>
Retry
</Button>
</div>
</div>
) : !activeDetection || !detectionResult ? (
<div className="rounded-lg border border-dashed bg-muted/20 px-4 py-10 text-center text-sm text-muted-foreground">
No detections are available for this issue.
</div>
) : (
<>
<div className="grid grid-cols-1 items-start gap-4 xl:grid-cols-2">
<div className="min-w-0 space-y-2">
<p className="text-xs font-medium text-muted-foreground">
Detection Image
</p>
<div className="overflow-hidden rounded-lg">
<AnnotatedDetectionImage
detection={activeDetection}
videoWidth={detectionResult.video_width}
videoHeight={detectionResult.video_height}
/>
</div>
</div>
<DetectionLocationMap
className="min-w-0"
latitude={activeDetection.location.latitude}
longitude={activeDetection.location.longitude}
label={`${displayName} - Frame ${activeDetection.frame.number}`}
title="Location on Map"
variant="plain"
aspectRatio={mediaAspectRatio}
showCoordinates={false}
/>
</div>
<DetectionMetadataBar
items={[
{
label: 'Confidence',
value: `${Math.round(activeDetection.detection.confidence * 100)}%`,
},
{
label: 'Frame',
value: activeDetection.frame.number,
},
{
label: 'Timestamp',
value: `${activeDetection.frame.timestamp_seconds}s`,
},
]}
/>
</>
)}
</div>
);
}

View File

@@ -2,22 +2,26 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation'; import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { Component } from 'lucide-react'; import { Component, ListChecks } from 'lucide-react';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { DEFECT_CLASS_STATUS_CONFIG } from '@/constants/defectClassStatus'; import { DEFECT_CLASS_STATUS_CONFIG } from '@/constants/defectClassStatus';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import type { TicketOverviewDetail } from '@/types';
import { useTicketDefectClassesQuery } from '../../hooks/useTicketQueries'; import { useTicketDefectClassesQuery } from '../../hooks/useTicketQueries';
import { TicketClassDetectionPreview } from './TicketClassDetectionPreview';
interface TicketDefectClassTabsProps { interface TicketDefectClassTabsProps {
ticketId: string; ticketId: string;
ticket?: TicketOverviewDetail;
} }
export function TicketDefectClassTabs({ export function TicketDefectClassTabs({
ticketId, ticketId,
ticket,
}: TicketDefectClassTabsProps) { }: TicketDefectClassTabsProps) {
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
@@ -37,15 +41,17 @@ export function TicketDefectClassTabs({
(item) => item.class_name === defectClassParam, (item) => item.class_name === defectClassParam,
); );
setSelectedClass((current) => { if (hasUrlClass) {
if (hasUrlClass) return defectClassParam ?? undefined; setSelectedClass(defectClassParam ?? undefined);
return;
}
return current && const firstClass = defectClasses[0].class_name;
defectClasses.some((item) => item.class_name === current) const nextParams = new URLSearchParams(searchParams.toString());
? current nextParams.set('defect_class', firstClass);
: defectClasses[0].class_name; setSelectedClass(firstClass);
}); router.replace(`${pathname}?${nextParams.toString()}`, { scroll: false });
}, [defectClassParam, defectClasses]); }, [defectClassParam, defectClasses, pathname, router, searchParams]);
const handleClassChange = (className: string) => { const handleClassChange = (className: string) => {
const nextParams = new URLSearchParams(searchParams.toString()); const nextParams = new URLSearchParams(searchParams.toString());
@@ -54,20 +60,32 @@ export function TicketDefectClassTabs({
setSelectedClass(className); setSelectedClass(className);
router.replace(`${pathname}?${nextParams.toString()}`, { scroll: false }); router.replace(`${pathname}?${nextParams.toString()}`, { scroll: false });
}; };
const selectedIssue = ticket?.ai_result.detections_by_class.find(
(item) => item.class_name === selectedClass,
);
const selectedClassItem = defectClasses.find(
(item) => item.class_name === selectedClass,
);
const previewDisplayName =
selectedIssue?.display_name ??
selectedClassItem?.display_name ??
selectedClass ??
'Detection';
const previewVideoId = ticket?.video_id ?? defectClassesQuery.data?.video_id;
if (defectClassesQuery.isLoading) { if (defectClassesQuery.isLoading) {
return ( return (
<Card className="w-full"> <Card className="w-full">
<CardHeader> <CardContent className="space-y-4 p-5">
<div className="h-5 w-24 animate-pulse rounded bg-muted" /> <div className="h-5 w-24 animate-pulse rounded bg-muted" />
</CardHeader> <div className="flex flex-col gap-2">
<CardContent className="flex flex-col gap-2">
{Array.from({ length: 3 }).map((_, index) => ( {Array.from({ length: 3 }).map((_, index) => (
<div <div
key={index} key={index}
className="h-11 w-full animate-pulse rounded-lg bg-muted" className="h-11 w-full animate-pulse rounded-lg bg-muted"
/> />
))} ))}
</div>
</CardContent> </CardContent>
</Card> </Card>
); );
@@ -85,15 +103,19 @@ export function TicketDefectClassTabs({
className="w-full" className="w-full"
> >
<Card className="w-full"> <Card className="w-full">
<CardHeader> <CardContent className="grid gap-0 p-0 lg:grid-cols-[minmax(220px,280px)_1fr] lg:divide-x lg:divide-border">
<CardTitle className="flex items-center gap-2 text-base"> <div className="space-y-4 p-5">
<span>Issues</span> <div className="flex items-center gap-2">
<Badge variant="secondary" className="min-w-5 min-h-5 justify-center rounded-full"> <ListChecks className="size-5 shrink-0 text-primary" />
<h2 className="text-base font-semibold">Detected Issues</h2>
<Badge
variant="secondary"
className="min-w-5 min-h-5 justify-center rounded-full"
>
{defectClasses.length} {defectClasses.length}
</Badge> </Badge>
</CardTitle> </div>
</CardHeader>
<CardContent>
<TabsList className="flex h-auto w-full flex-col items-stretch gap-2 bg-transparent p-0"> <TabsList className="flex h-auto w-full flex-col items-stretch gap-2 bg-transparent p-0">
{defectClasses.map((item) => { {defectClasses.map((item) => {
const statusConfig = const statusConfig =
@@ -124,6 +146,16 @@ export function TicketDefectClassTabs({
); );
})} })}
</TabsList> </TabsList>
</div>
<div className="min-w-0 p-5">
<TicketClassDetectionPreview
videoId={previewVideoId}
defectClassName={selectedClass}
displayName={previewDisplayName}
totalCount={selectedIssue?.count}
/>
</div>
</CardContent> </CardContent>
</Card> </Card>
</Tabs> </Tabs>

View File

@@ -4,14 +4,15 @@ import { ArrowLeft } from 'lucide-react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { SparkleButton } from '@/components/ui/sparkle-button'; import type { TicketOverviewDetail } from '@/types';
import { PERMISSIONS } from '@/constants/permissions';
import { PermissionGuard } from '@/guards';
import type { TicketDetail } from '@/types';
export function TicketDetailHeader({ ticket }: { ticket: TicketDetail }) { export function TicketDetailHeader({
ticket,
}: {
ticket: TicketOverviewDetail;
}) {
const router = useRouter(); const router = useRouter();
const ticketLabel = ticket.ticket_name; const ticketLabel = ticket.ticket_name || ticket.id;
return ( return (
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between"> <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
@@ -21,17 +22,6 @@ export function TicketDetailHeader({ ticket }: { ticket: TicketDetail }) {
</div> </div>
<div className="flex shrink-0 items-center gap-2"> <div className="flex shrink-0 items-center gap-2">
{ticket.video_id ? (
<PermissionGuard permissions={PERMISSIONS.TICKET.ASSIGN}>
<SparkleButton
className="h-10 min-w-36 px-5"
onClick={() => router.push(`/results/${ticket.video_id}`)}
>
View Analysis
</SparkleButton>
</PermissionGuard>
) : null}
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"

View File

@@ -1,115 +0,0 @@
'use client';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
function OverviewSkeletonField() {
return (
<div className="space-y-2">
<Skeleton className="h-3 w-24" />
<Skeleton className="h-4 w-32" />
</div>
);
}
function TimelineSkeletonItem({ isLast = false }: { isLast?: boolean }) {
return (
<div className="relative flex gap-4 pb-8 last:pb-0">
{!isLast ? (
<span
aria-hidden
className="absolute top-6 left-2.75 h-[calc(100%-10px)] w-px bg-border"
/>
) : null}
<Skeleton className="relative z-10 mt-0.5 size-6 shrink-0 rounded-full" />
<div className="min-w-0 flex-1 space-y-3">
<div className="flex flex-wrap items-center gap-3">
<Skeleton className="h-4 w-44" />
<Skeleton className="h-3 w-28" />
</div>
<Skeleton className="h-3 w-56" />
<Skeleton className="h-12 w-full" />
</div>
</div>
);
}
export function TicketDetailSkeleton() {
return (
<main className="relative z-10 space-y-5">
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<Skeleton className="h-8 w-40" />
<Skeleton className="h-6 w-24 rounded-full" />
</div>
<Skeleton className="h-3 w-72 max-w-full" />
</div>
<div className="flex shrink-0 items-center gap-2">
<Skeleton className="h-10 w-36" />
<Skeleton className="h-8 w-28" />
</div>
</div>
<div className="grid gap-5 xl:grid-cols-[minmax(0,7fr)_minmax(0,3fr)]">
<div className="space-y-5">
<Card>
<CardHeader>
<Skeleton className="h-4 w-20" />
</CardHeader>
<CardContent className="grid grid-cols-2 gap-x-4 gap-y-6 md:grid-cols-4">
{Array.from({ length: 8 }).map((_, index) => (
<OverviewSkeletonField key={index} />
))}
</CardContent>
</Card>
<section className="space-y-5">
<Card>
<CardHeader>
<Skeleton className="h-5 w-40" />
</CardHeader>
<CardContent className="space-y-3">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-5/6" />
<Skeleton className="h-4 w-2/3" />
</CardContent>
</Card>
<Card>
<CardHeader>
<Skeleton className="h-5 w-44" />
</CardHeader>
<CardContent>
<Skeleton className="aspect-video w-full rounded-lg" />
</CardContent>
</Card>
</section>
<Card>
<CardHeader className="flex-row items-center">
<Skeleton className="size-5 rounded-full" />
<Skeleton className="h-5 w-56" />
</CardHeader>
<CardContent className="pl-5.5">
<TimelineSkeletonItem />
<TimelineSkeletonItem />
<TimelineSkeletonItem isLast />
</CardContent>
</Card>
</div>
<Card className="self-start">
<CardHeader>
<Skeleton className="h-5 w-36" />
</CardHeader>
<CardContent className="space-y-3">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-24 w-full" />
</CardContent>
</Card>
</div>
</main>
);
}

View File

@@ -2,87 +2,84 @@
import { History, MessageSquareText } from 'lucide-react'; import { History, MessageSquareText } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { PersonInfo } from '@/components/person-avatar';
import { Badge } from '@/components/ui/badge';
import { Timeline, TimelineItem } from '@/components/ui/timeline';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import type { TicketDetail, TicketHistoryItem, TicketStatus } from '@/types'; import type { TicketDetail, TicketHistoryItem, TicketHistorySource } from '@/types';
import { formatDate } from '@/utils/date'; import { formatTimelineDateTime } from '@/utils/date';
import { getPersonLabel } from '@/utils/person';
function getActorLabel(item: TicketHistoryItem) { function TimelineDate({ value }: { value: string }) {
return item.actor?.name || item.actor?.email || 'System'; const { date, time } = formatTimelineDateTime(value);
}
function getLifecycleTitle(status: TicketStatus) {
const titles: Record<TicketStatus, string> = {
unassigned: 'Awaiting Assignment',
assigned: 'Dispatched to Maintenance',
under_review: 'Maintenance Finalized',
closed: 'Ticket Closed',
};
return titles[status];
}
function HistoryEntry({
item,
isLast,
}: {
item: TicketHistoryItem;
isLast: boolean;
}) {
const isClosed = item.to_status === 'closed';
return ( return (
<div className="relative flex gap-4 pb-8 last:pb-0"> <time dateTime={value} className="block tabular-nums">
{!isLast ? ( <span className="block text-sm font-semibold text-foreground">{date}</span>
<span <span className="block text-xs text-muted-foreground">{time}</span>
aria-hidden
className="absolute top-6 left-2.75 h-[calc(100%-10px)] w-px bg-border"
/>
) : null}
<span
aria-hidden
className={cn(
'relative z-10 mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full border-2 bg-background',
isClosed
? 'border-primary bg-primary text-primary-foreground'
: 'border-primary/60',
)}
>
<span
className={cn(
'size-2 rounded-full bg-primary',
isClosed &&
'h-1.5 w-2.5 -rotate-45 rounded-none border-b-2 border-l-2 border-current bg-transparent',
)}
/>
</span>
<div className="min-w-0 flex-1 space-y-2">
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<h3 className="text-sm font-semibold text-foreground">
{getLifecycleTitle(item.to_status)}
</h3>
<time
dateTime={item.created_at}
className="text-xs font-semibold text-muted-foreground tabular-nums"
>
{formatDate(item.created_at)}
</time> </time>
</div> );
}
<p className="text-xs font-medium text-muted-foreground"> function HistoryNote({ item }: { item: TicketHistoryItem }) {
Updated By{' '} const noteText = item.note?.text?.trim();
<span className="text-foreground/90">{getActorLabel(item)}</span> if (!noteText) return null;
return (
<div className="mt-3 rounded-lg border border-amber-300/80 bg-amber-50/90 px-3 py-2.5 dark:border-amber-500/30 dark:bg-amber-500/10">
<div className="flex items-center gap-1.5 text-xs font-medium text-amber-900 dark:text-amber-200">
<MessageSquareText className="size-3.5 shrink-0 text-amber-700 dark:text-amber-300" />
<span>
Note by {getPersonLabel(item.note?.author ?? item.actor)}
</span>
</div>
<p className="mt-1.5 text-sm leading-relaxed text-amber-950/80 dark:text-amber-100/90">
{noteText}
</p> </p>
{item.note ? (
<div className="flex gap-2 rounded-md border border-border bg-background px-3 py-2 text-sm leading-relaxed text-foreground">
<MessageSquareText className="mt-0.5 size-4 shrink-0 text-primary" />
<p>{item.note}</p>
</div> </div>
);
}
function getSourceLabel(source: TicketHistorySource) {
return source === 'system' ? 'System Generated' : 'User Action';
}
function SystemHistoryEntry({ item }: { item: TicketHistoryItem }) {
const noteText = item.note?.text?.trim();
return (
<div className="rounded-md border border-dashed border-primary/25 bg-primary/5 px-4 py-3.5">
<Badge
className="rounded-xs px-2.5 py-0.5 text-[10px] font-semibold tracking-wider uppercase"
>
{getSourceLabel(item.source)}
</Badge>
<h3 className="mt-2 text-sm font-semibold text-foreground">{item.title}</h3>
{noteText ? (
<p className="mt-1 text-sm leading-relaxed text-muted-foreground">
{noteText}
</p>
) : null} ) : null}
</div> </div>
);
}
function UserHistoryEntry({ item }: { item: TicketHistoryItem }) {
const noteText = item.note?.text?.trim();
const isAssigned = item.event_type === 'assigned';
return (
<div className="rounded-md border border-border bg-card p-4">
<h3 className="mb-3 text-sm font-semibold text-foreground">{item.title}</h3>
<PersonInfo person={item.actor} />
{isAssigned && item.target_user ? (
<div className="mt-3 space-y-1">
<p className="text-xs text-muted-foreground">Assigned to</p>
<PersonInfo person={item.target_user} />
</div>
) : null}
{noteText ? <HistoryNote item={item} /> : null}
</div> </div>
); );
} }
@@ -91,33 +88,48 @@ export function TicketHistoryCard({ ticket }: { ticket: TicketDetail }) {
const history = ticket.history ?? []; const history = ticket.history ?? [];
return ( return (
<Card> <div className="space-y-4">
<CardHeader> <div className="flex items-center gap-2">
<CardTitle className="flex items-center gap-2">
<History className="size-5 text-primary" /> <History className="size-5 text-primary" />
Audit & Lifecycle Timeline <h2 className="text-base font-semibold">Audit & Lifecycle Timeline</h2>
</CardTitle>
</CardHeader>
<CardContent>
{history.length ? (
<div className="pl-0.5">
{history.map((item, index) => (
<HistoryEntry
key={item.id}
item={item}
isLast={index === history.length - 1}
/>
))}
</div> </div>
{history.length ? (
<Timeline>
{history.map((item, index) => (
<TimelineItem
key={item.id}
layout="left"
isLast={index === history.length - 1}
opposite={<TimelineDate value={item.created_at} />}
marker={
<span className="flex size-4 items-center justify-center rounded-full border bg-background shadow-xs">
<span
className={cn(
'size-1.5 rounded-full',
item.source === 'system'
? 'bg-muted-foreground'
: 'bg-primary',
)}
/>
</span>
}
>
{item.source === 'system' ? (
<SystemHistoryEntry item={item} />
) : ( ) : (
<div className="rounded-lg border border-dashed border-border/80 bg-muted/10 px-4 py-8 text-center"> <UserHistoryEntry item={item} />
)}
</TimelineItem>
))}
</Timeline>
) : (
<div className="rounded-md border border-dashed border-border/80 bg-muted/10 px-4 py-8 text-center">
<p className="text-sm font-medium text-muted-foreground"> <p className="text-sm font-medium text-muted-foreground">
No timeline entries yet No timeline entries yet
</p> </p>
</div> </div>
)} )}
</CardContent> </div>
</Card>
); );
} }

View File

@@ -1,28 +1,33 @@
'use client'; 'use client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import {
import type { TicketActor, TicketDetail } from '@/types'; Activity,
ArrowRight,
CalendarDays,
Clock3,
Gauge,
MapPin,
Monitor,
UserRound,
} from 'lucide-react';
import { useRouter } from 'next/navigation';
function formatCreatedDate(value: string | null | undefined) { import {
if (!value) return '-'; Card,
return new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium' }).format( CardAction,
new Date(value), CardContent,
); CardHeader,
} CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { getDefectVisual } from '@/constants/defectVisualConfig';
import { PERMISSIONS } from '@/constants/permissions';
import { PermissionGuard } from '@/guards';
import { cn } from '@/lib/utils';
import type { TicketOverviewDetail } from '@/types';
import { formatDate } from '@/utils/date';
function getInitials(person: TicketActor | null | undefined) { type IconComponent = React.ComponentType<{ className?: string }>;
const source = person?.name || person?.email || '?';
return source
.split(/[\s@._-]+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part.charAt(0).toUpperCase())
.join('');
}
function getPersonLabel(person: TicketActor | null | undefined) {
return person?.name || person?.email || '-';
}
function MetaLabel({ children }: { children: React.ReactNode }) { function MetaLabel({ children }: { children: React.ReactNode }) {
return ( return (
@@ -36,29 +41,6 @@ function MetaValue({ children }: { children: React.ReactNode }) {
return <p className="text-sm font-semibold text-foreground">{children}</p>; return <p className="text-sm font-semibold text-foreground">{children}</p>;
} }
function PersonMetaValue({
person,
accentClassName = 'bg-primary/15 text-primary',
}: {
person: TicketActor | null | undefined;
accentClassName?: string;
}) {
if (!person) {
return <MetaValue>-</MetaValue>;
}
return (
<div className="flex min-w-0 items-center gap-2">
<span
className={`flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold ${accentClassName}`}
>
{getInitials(person)}
</span>
<p className="truncate text-sm font-medium">{getPersonLabel(person)}</p>
</div>
);
}
function OverviewField({ function OverviewField({
label, label,
children, children,
@@ -67,43 +49,186 @@ function OverviewField({
children: React.ReactNode; children: React.ReactNode;
}) { }) {
return ( return (
<div className="space-y-1"> <div className="min-w-0 space-y-1">
<MetaLabel>{label}</MetaLabel> <MetaLabel>{label}</MetaLabel>
{children} {children}
</div> </div>
); );
} }
export function TicketOverviewCard({ ticket }: { ticket: TicketDetail }) { function SummaryCard({
const detectionCount = ticket.ai_result?.detection_count; label,
value,
colorClassName,
cardClassName,
}: {
label: string;
value: number;
colorClassName: string;
cardClassName: string;
}) {
return ( return (
<Card> <div
<CardHeader> className={cn(
<CardTitle>Overview</CardTitle> 'rounded-xl bg-muted/40 p-4 transition-colors hover:bg-muted/60',
</CardHeader> cardClassName,
)}
<CardContent className="grid grid-cols-2 gap-x-4 gap-y-6 md:grid-cols-4"> >
<OverviewField label="Detection Count"> <p className={cn('text-2xl font-bold tracking-tight', colorClassName)}>
<MetaValue> {value}
{detectionCount != null ? `${detectionCount} Occurrences` : '-'} </p>
</MetaValue> <p className="mt-2 truncate text-xs font-semibold text-foreground">
</OverviewField> {label}
</p>
<OverviewField label="Chainage"> <p className="mt-0.5 text-[11px] text-muted-foreground">Detected</p>
<MetaValue>{ticket.chainage_name}</MetaValue> </div>
</OverviewField> );
}
<OverviewField label="Uploaded By">
<PersonMetaValue person={ticket.uploader} /> function VideoMetric({
</OverviewField> icon: Icon,
label,
<OverviewField label="Created Date"> }: {
<MetaValue> icon: IconComponent;
{formatCreatedDate(ticket.timestamps.created_at)} label: string;
</MetaValue> }) {
</OverviewField> return (
</CardContent> <div className="flex items-center justify-center gap-2 font-medium">
</Card> <Icon className="size-4 text-muted-foreground" />
<span>{label}</span>
</div>
);
}
export function TicketOverviewCard({
ticket,
}: {
ticket: TicketOverviewDetail;
}) {
const router = useRouter();
const videoMetadata = ticket.video_metadata;
const duration =
typeof videoMetadata?.duration_seconds === 'number'
? `${Math.floor(videoMetadata.duration_seconds / 60)}:${Math.floor(
videoMetadata.duration_seconds % 60,
)
.toString()
.padStart(2, '0')}`
: null;
const chainageName =
ticket.location?.chainage?.name || ticket.chainage_name || null;
const packageName = ticket.location?.package?.name || null;
const locationLabel =
[chainageName, packageName].filter(Boolean).join(', ') || null;
const uploadedOn =
ticket.timestamps?.created_at || ticket.ai_result.completed_at || null;
const uploaderName = ticket.uploader?.name || null;
const analysisVideoId = ticket.video_id || ticket.video?.id || null;
const videoName = ticket.video?.name || null;
const hasVideoMetrics = Boolean(
videoName ||
videoMetadata?.fps ||
duration ||
videoMetadata?.resolution?.label,
);
return (
<div className="space-y-5">
{uploadedOn || uploaderName || locationLabel ? (
<Card>
<CardContent className="grid gap-4 py-4 sm:grid-cols-3 sm:divide-x">
{uploadedOn ? (
<div className="flex items-center gap-3 sm:pr-4">
<CalendarDays className="size-5 shrink-0 text-muted-foreground" />
<OverviewField label="Uploaded On">
<MetaValue>{formatDate(uploadedOn)}</MetaValue>
</OverviewField>
</div>
) : null}
{uploaderName ? (
<div className="flex items-center gap-3 sm:px-4">
<UserRound className="size-5 shrink-0 text-muted-foreground" />
<OverviewField label="Uploaded By">
<MetaValue>{uploaderName}</MetaValue>
</OverviewField>
</div>
) : null}
{locationLabel ? (
<div className="flex items-center gap-3 sm:pl-4">
<MapPin className="size-5 shrink-0 text-muted-foreground" />
<OverviewField label="Location">
<MetaValue>{locationLabel}</MetaValue>
</OverviewField>
</div>
) : null}
</CardContent>
</Card>
) : null}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Activity className="size-5 text-primary" />
AI Detection Summary
</CardTitle>
{analysisVideoId ? (
<CardAction>
<PermissionGuard permissions={PERMISSIONS.TICKET.ASSIGN}>
<Button
variant="ghost"
size="sm"
className="text-primary hover:bg-primary/10 hover:text-primary"
onClick={() => router.push(`/results/${analysisVideoId}`)}
>
View Analysis
<ArrowRight className="size-3.5" />
</Button>
</PermissionGuard>
</CardAction>
) : null}
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-6">
<SummaryCard
label="Total Detections"
value={ticket.ai_result.detection_count}
colorClassName="text-violet-600"
cardClassName="bg-violet-500/8"
/>
{ticket.ai_result.detections_by_class.map((item) => {
const visual = getDefectVisual(item.class_name);
return (
<SummaryCard
key={item.class_name}
label={item.display_name}
value={item.count}
colorClassName={visual.colorClassName}
cardClassName={visual.cardClassName}
/>
);
})}
</div>
{hasVideoMetrics ? (
<div className="grid gap-3 rounded-lg bg-muted/35 px-4 py-3 text-sm sm:grid-cols-3">
{videoName ? (
<VideoMetric icon={Monitor} label={videoName} />
) : null}
{videoMetadata?.fps ? (
<VideoMetric icon={Gauge} label={`${videoMetadata.fps} FPS`} />
) : null}
{duration ? (
<VideoMetric icon={Clock3} label={`${duration} Duration`} />
) : null}
{videoMetadata?.resolution?.label ? (
<VideoMetric
icon={Monitor}
label={`${videoMetadata.resolution.label} Resolution`}
/>
) : null}
</div>
) : null}
</CardContent>
</Card>
</div>
); );
} }

View File

@@ -0,0 +1,41 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
function OverviewSkeletonField() {
return (
<div className="space-y-2">
<Skeleton className="h-3 w-24" />
<Skeleton className="h-4 w-32" />
</div>
);
}
export function TicketOverviewHeaderSkeleton() {
return (
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0 space-y-2">
<Skeleton className="h-8 w-40" />
<Skeleton className="h-3 w-36 max-w-full" />
</div>
<div className="flex shrink-0 items-center gap-2">
<Skeleton className="h-8 w-28" />
</div>
</div>
);
}
export function TicketOverviewCardSkeleton() {
return (
<Card aria-label="Loading ticket overview">
<CardHeader>
<Skeleton className="h-4 w-20" />
</CardHeader>
<CardContent className="grid grid-cols-2 gap-x-4 gap-y-6 md:grid-cols-4">
{Array.from({ length: 4 }).map((_, index) => (
<OverviewSkeletonField key={index} />
))}
</CardContent>
</Card>
);
}

View File

@@ -1,42 +0,0 @@
'use client';
import { ImageIcon } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
import { RepairProofImagesGrid } from './repair-report/RepairProofImagesGrid';
import { RepairReportPanel } from './repair-report/RepairReportPanel';
import { RepairVideoComparison } from './repair-report/RepairVideoComparison';
export function TicketRepairReportCard({ ticket }: { ticket: TicketDetail }) {
const repair = ticket.repair;
if (!repair) {
return null;
}
return (
<section className="space-y-5">
<RepairReportPanel ticket={ticket} />
<RepairVideoComparison ticket={ticket} />
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ImageIcon className="size-5 text-primary" />
Repair Images
</CardTitle>
</CardHeader>
<CardContent>
<RepairProofImagesGrid
imageUrls={repair?.proof_image_urls ?? []}
submittedAt={repair?.submitted_at ?? null}
/>
</CardContent>
</Card>
</section>
);
}

View File

@@ -7,9 +7,10 @@ import type { TicketDetail } from '@/types';
import { AssignTicketAction } from './actions/AssignTicketAction'; import { AssignTicketAction } from './actions/AssignTicketAction';
import { ClosedTicketAction } from './actions/ClosedTicketAction'; import { ClosedTicketAction } from './actions/ClosedTicketAction';
import { NoTicketAction } from './actions/NoTicketAction'; import { NoTicketAction } from './actions/NoTicketAction';
import { ReviewExtensionRequestAction } from './actions/ReviewExtensionRequestAction';
import { ReviewRepairAction } from './actions/ReviewRepairAction'; import { ReviewRepairAction } from './actions/ReviewRepairAction';
import { SubmittedRepairProofAction } from './actions/SubmittedRepairProofAction';
import { SubmitRepairAction } from './actions/SubmitRepairAction'; import { SubmitRepairAction } from './actions/SubmitRepairAction';
import { TicketDefectClassTabs } from './TicketDefectClassTabs';
interface TicketStatusActionsProps { interface TicketStatusActionsProps {
ticket: TicketDetail; ticket: TicketDetail;
@@ -29,12 +30,19 @@ function getTicketAction(ticket: TicketDetail) {
if (ticket.assignment_status === 'assigned') { if (ticket.assignment_status === 'assigned') {
return ( return (
<PermissionGuard
permissions={PERMISSIONS.TICKET.ASSIGN}
fallback={
<PermissionGuard <PermissionGuard
permissions={PERMISSIONS.TICKET.WORK} permissions={PERMISSIONS.TICKET.WORK}
fallback={<NoTicketAction />} fallback={<NoTicketAction />}
> >
<SubmitRepairAction ticket={ticket} /> <SubmitRepairAction ticket={ticket} />
</PermissionGuard> </PermissionGuard>
}
>
<ReviewExtensionRequestAction ticket={ticket} />
</PermissionGuard>
); );
} }
@@ -49,7 +57,10 @@ function getTicketAction(ticket: TicketDetail) {
); );
} }
if (ticket.status === 'closed') { if (
ticket.assignment_status === 'approved' ||
ticket.assignment_status === 'rejected'
) {
return <ClosedTicketAction ticket={ticket} />; return <ClosedTicketAction ticket={ticket} />;
} }
@@ -57,10 +68,15 @@ function getTicketAction(ticket: TicketDetail) {
} }
export function TicketStatusActions({ ticket }: TicketStatusActionsProps) { export function TicketStatusActions({ ticket }: TicketStatusActionsProps) {
const action = getTicketAction(ticket);
const submittedProof = ticket.repair?.submitted_at ? (
<SubmittedRepairProofAction ticket={ticket} />
) : null;
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<TicketDefectClassTabs ticketId={ticket.id} /> {submittedProof}
{getTicketAction(ticket)} {action}
</div> </div>
); );
} }

View File

@@ -1,56 +1,93 @@
'use client'; 'use client';
import { useState } from 'react'; import { useState } from 'react';
import { Send, UserPlus } from 'lucide-react'; import { Users, Mail, Phone, Send, ShieldCheck } from 'lucide-react';
import { DatePicker } from '@/components/form/DatePicker';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
import { AssignableWorkerSelect } from '@/components/lookups/AssignableWorkerSelect'; import { AssignableWorkerSelect } from '@/components/lookups/AssignableWorkerSelect';
import type { TicketDetail } from '@/types'; import type { AssignableTicketUser, TicketDetail } from '@/types';
import { useAssignTicketMutation } from '../../../hooks/useTicketQueries'; import { useAssignTicketMutation } from '../../../hooks/useTicketQueries';
import { TicketActionCard } from './TicketActionCard'; import { TicketActionCard } from './TicketActionCard';
export function AssignTicketAction({ ticket }: { ticket: TicketDetail }) { export function AssignTicketAction({ ticket }: { ticket: TicketDetail }) {
const [selectedUserId, setSelectedUserId] = useState(''); const [selectedUserId, setSelectedUserId] = useState('');
const [selectedContractor, setSelectedContractor] =
useState<AssignableTicketUser | null>(null);
const [dueDate, setDueDate] = useState<Date>();
const [assignNote, setAssignNote] = useState(''); const [assignNote, setAssignNote] = useState('');
const assignMutation = useAssignTicketMutation(ticket.id); const assignMutation = useAssignTicketMutation(ticket.id);
return ( return (
<TicketActionCard icon={UserPlus} title="Assign Ticket"> <TicketActionCard icon={Users} title="Assign to Contractor">
<div className="space-y-4"> <div className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label>Contractor</Label> <Label>Contractor *</Label>
<AssignableWorkerSelect <AssignableWorkerSelect
value={selectedUserId} value={selectedUserId}
onValueChange={setSelectedUserId} onValueChange={(userId, user) => {
setSelectedUserId(userId);
setSelectedContractor(user);
}}
disabled={assignMutation.isPending} disabled={assignMutation.isPending}
/> />
</div> </div>
{selectedContractor ? (
<div className="space-y-2 rounded-lg border bg-muted/30 p-3">
<p className="text-sm font-medium">Contractor Details</p>
{selectedContractor.phone_number ? (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Phone className="size-4 shrink-0" />
{selectedContractor.phone_number}
</p>
) : null}
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Mail className="size-4 shrink-0" />
<span className="truncate">{selectedContractor.email}</span>
</p>
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<ShieldCheck className="size-4 shrink-0" />
{selectedContractor.role.name}
</p>
</div>
) : null}
<div className="space-y-2"> <div className="space-y-2">
<Label>Note</Label> <Label>Due Date *</Label>
<DatePicker
value={dueDate}
onChange={setDueDate}
showTimeZone={false}
disabled={assignMutation.isPending}
className="w-full"
/>
</div>
<div className="space-y-2">
<Label>Assignment Note (Optional)</Label>
<Textarea <Textarea
value={assignNote} value={assignNote}
onChange={(event) => setAssignNote(event.target.value)} onChange={(event) => setAssignNote(event.target.value)}
placeholder="Please inspect and repair" placeholder="Add any instructions or notes for the contractor..."
/> />
</div> </div>
<Button <Button
disabled={!selectedUserId || assignMutation.isPending} disabled={!selectedUserId || !dueDate || assignMutation.isPending}
onClick={() => { onClick={() => {
if (!selectedUserId) return; if (!selectedUserId || !dueDate) return;
assignMutation.mutate({ assignMutation.mutate({
assigned_to_user_id: Number(selectedUserId), assigned_to_user_id: Number(selectedUserId),
defect_class: ticket.defect_class, defect_class: ticket.defect_class,
due_at: dueDate.toISOString(),
note: assignNote || undefined, note: assignNote || undefined,
}); });
}} }}
className="w-full" className="w-full"
> >
<Send /> <Send />
Assign Assign Ticket
</Button> </Button>
</div> </div>
</TicketActionCard> </TicketActionCard>

View File

@@ -3,7 +3,7 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { Lock, MessageSquare } from 'lucide-react'; import { Lock, MessageSquare } from 'lucide-react';
import { Avatar, AvatarFallback } from '@/components/ui/avatar'; import { PersonInfo } from '@/components/person-avatar';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
Card, Card,
@@ -14,34 +14,18 @@ import {
} from '@/components/ui/card'; } from '@/components/ui/card';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import type { TicketDetail } from '@/types'; import type { TicketDetail } from '@/types';
import { formatDateOnly } from '@/utils/date';
function getInitials(name?: string | null, email?: string | null) {
const source = name || email || '?';
return source
.split(/[\s@._-]+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part.charAt(0).toUpperCase())
.join('');
}
function getPersonLabel(person: TicketDetail['reviewer']) {
return person?.name || person?.email || 'Unknown';
}
function formatReviewDate(value: string | null | undefined) {
if (!value) return '-';
return new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium' }).format(
new Date(value),
);
}
function getClosedAt(ticket: TicketDetail) { function getClosedAt(ticket: TicketDetail) {
const closedEntry = ticket.history?.find( const approvedEntry = [...(ticket.history ?? [])]
(item) => item.to_status === 'closed', .reverse()
.find(
(item) =>
item.event_type === 'repair_approved' ||
item.to_class_status === 'approved',
); );
return ( return (
closedEntry?.created_at ?? approvedEntry?.created_at ??
ticket.reviewer?.reviewed_at ?? ticket.reviewer?.reviewed_at ??
ticket.timestamps.updated_at ticket.timestamps.updated_at
); );
@@ -101,35 +85,19 @@ export function ClosedTicketAction({ ticket }: { ticket: TicketDetail }) {
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="text-lg">Resolution Details</CardTitle> <CardTitle className="text-lg">Resolution Details</CardTitle>
<CardDescription>Review record for {ticket.id}</CardDescription> <CardDescription>Review record for {ticket.ticket_name}</CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-5"> <CardContent className="space-y-5">
<div className="space-y-4 rounded-xl border bg-muted/20 p-4"> <div className="space-y-4 rounded-xl border bg-muted/20 p-4">
<MetaField <MetaField
label="Reviewed By" label="Reviewed By"
value={ value={<PersonInfo person={reviewer} size="lg" />}
<div className="flex min-w-0 items-center gap-3">
<Avatar className="size-10 border border-primary/30">
<AvatarFallback className="bg-primary/15 text-sm text-primary">
{getInitials(reviewer?.name, reviewer?.email)}
</AvatarFallback>
</Avatar>
<div className="min-w-0">
<p className="truncate">{getPersonLabel(reviewer)}</p>
{reviewer?.email ? (
<p className="mt-0.5 truncate text-xs font-medium text-muted-foreground">
{reviewer.email}
</p>
) : null}
</div>
</div>
}
/> />
<MetaField <MetaField
label="Reviewed Date" label="Reviewed Date"
value={formatReviewDate(reviewedAt)} value={formatDateOnly(reviewedAt)}
/> />
</div> </div>

View File

@@ -1,7 +1,16 @@
'use client'; 'use client';
import { useEffect, useRef, useState, type ReactNode } from 'react'; import { useEffect, useRef, useState, type ReactNode } from 'react';
import { ImageIcon, Loader2, Send, Video, X } from 'lucide-react'; import {
Camera,
ImageIcon,
Loader2,
Play,
Plus,
Send,
Video,
X,
} from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
@@ -10,89 +19,119 @@ import { cn } from '@/lib/utils';
import { useSubmitRepairUploadMutation } from '../../../hooks/useTicketQueries'; import { useSubmitRepairUploadMutation } from '../../../hooks/useTicketQueries';
const MAX_IMAGES = 5; const MAX_IMAGES = 30;
const MAX_NOTES = 500;
function RequiredMark() { function RequiredMark() {
return <span className="text-destructive">*</span>; return <span className="text-destructive">*</span>;
} }
interface MediaDropzoneProps { function formatVideoDuration(seconds: number) {
const totalSeconds = Math.floor(seconds);
const minutes = Math.floor(totalSeconds / 60);
const remainingSeconds = totalSeconds % 60;
return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
}
interface MediaSectionHeaderProps {
icon: ReactNode; icon: ReactNode;
label: string; title: string;
accept: string; addLabel: string;
file: File | null; onAdd: () => void;
onFileChange: (file: File | null) => void;
disabled?: boolean; disabled?: boolean;
} }
function MediaDropzone({ function MediaSectionHeader({
icon, icon,
label, title,
accept, addLabel,
file, onAdd,
onFileChange,
disabled = false, disabled = false,
}: MediaDropzoneProps) { }: MediaSectionHeaderProps) {
const inputRef = useRef<HTMLInputElement | null>(null); return (
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<span className="text-primary">{icon}</span>
<span className="text-sm font-semibold">{title}</span>
</div>
<Button
type="button"
variant="outline"
size="sm"
disabled={disabled}
onClick={onAdd}
className="h-8 shrink-0 border-primary/30 text-primary hover:bg-primary/5 hover:text-primary"
>
<Plus className="size-3.5" />
{addLabel}
</Button>
</div>
);
}
function MediaHint({ children }: { children: ReactNode }) {
return (
<p className="rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground">
{children}
</p>
);
}
interface EmptyMediaPlaceholderProps {
icon: ReactNode;
title: string;
description: string;
className?: string;
disabled?: boolean;
onClick: () => void;
}
function EmptyMediaPlaceholder({
icon,
title,
description,
className,
disabled = false,
onClick,
}: EmptyMediaPlaceholderProps) {
return ( return (
<button <button
type="button" type="button"
disabled={disabled} disabled={disabled}
onClick={() => inputRef.current?.click()} onClick={onClick}
className={cn( className={cn(
'flex w-full items-center cursor-pointer gap-3 rounded-lg border border-dashed px-4 py-3 text-left transition-colors', 'flex w-full min-w-0 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border/80 bg-muted/15 px-4 py-6 text-center transition-colors',
'hover:border-primary/50 hover:bg-muted/30', 'hover:border-primary/40 hover:bg-primary/5',
disabled && 'pointer-events-none opacity-60', disabled && 'cursor-not-allowed opacity-60',
file && 'border-primary/40 bg-muted/20', className,
)} )}
> >
<input <span className="flex size-10 items-center justify-center rounded-full bg-primary/10 text-primary">
ref={inputRef}
type="file"
accept={accept}
className="hidden"
disabled={disabled}
onChange={(event) => {
onFileChange(event.target.files?.[0] ?? null);
event.target.value = '';
}}
/>
<span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
{icon} {icon}
</span> </span>
<span className="min-w-0 flex-1"> <span className="text-sm font-medium text-foreground">{title}</span>
<span className="block truncate text-sm font-medium"> <span className="max-w-xs text-xs text-muted-foreground">
{file ? file.name : label} {description}
</span>
{file ? (
<span className="text-xs text-muted-foreground">
Click to replace
</span>
) : null}
</span> </span>
</button> </button>
); );
} }
interface ImageSlotProps { interface ImageThumbnailProps {
file: File | null; file: File;
previewUrl: string | null; previewUrl: string;
disabled?: boolean; disabled?: boolean;
onAdd: () => void;
onRemove: () => void; onRemove: () => void;
} }
function ImageSlot({ function ImageThumbnail({
file, file,
previewUrl, previewUrl,
disabled = false, disabled = false,
onAdd,
onRemove, onRemove,
}: ImageSlotProps) { }: ImageThumbnailProps) {
if (file && previewUrl) {
return ( return (
<div className="group relative aspect-square overflow-hidden rounded-lg border bg-muted/30"> <div className="group relative size-20 shrink-0 overflow-hidden rounded-lg border bg-muted/30">
{/* eslint-disable-next-line @next/next/no-img-element */} {/* eslint-disable-next-line @next/next/no-img-element */}
<img <img
src={previewUrl} src={previewUrl}
@@ -103,7 +142,7 @@ function ImageSlot({
type="button" type="button"
disabled={disabled} disabled={disabled}
onClick={onRemove} onClick={onRemove}
className="absolute top-1 right-1 flex size-5 cursor-pointer items-center justify-center rounded-full bg-background/90 text-foreground opacity-0 shadow-sm transition-opacity group-hover:opacity-100 disabled:cursor-not-allowed disabled:opacity-50" className="absolute top-1 right-1 flex size-5 cursor-pointer items-center justify-center rounded-full bg-foreground/80 text-background shadow-sm transition-opacity disabled:cursor-not-allowed disabled:opacity-50"
aria-label={`Remove ${file.name}`} aria-label={`Remove ${file.name}`}
> >
<X className="size-3" /> <X className="size-3" />
@@ -112,20 +151,51 @@ function ImageSlot({
); );
} }
interface VideoThumbnailProps {
file: File;
previewUrl: string;
duration: string | null;
disabled?: boolean;
onRemove: () => void;
}
function VideoThumbnail({
file,
previewUrl,
duration,
disabled = false,
onRemove,
}: VideoThumbnailProps) {
return ( return (
<div className="group relative h-20 w-36 shrink-0 overflow-hidden rounded-lg border bg-muted/30">
<video
src={previewUrl}
className="size-full object-cover"
muted
playsInline
preload="metadata"
aria-label={file.name}
/>
<div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-black/20">
<span className="flex size-8 items-center justify-center rounded-full bg-background/90 text-foreground shadow-sm">
<Play className="size-3.5 fill-current" />
</span>
</div>
{duration ? (
<span className="pointer-events-none absolute bottom-1.5 right-1.5 rounded bg-black/75 px-1.5 py-0.5 text-[10px] font-medium text-white">
{duration}
</span>
) : null}
<button <button
type="button" type="button"
disabled={disabled} disabled={disabled}
onClick={onAdd} onClick={onRemove}
className={cn( className="absolute top-1 right-1 flex size-5 cursor-pointer items-center justify-center rounded-full bg-foreground/80 text-background shadow-sm transition-opacity disabled:cursor-not-allowed disabled:opacity-50"
'flex aspect-square cursor-pointer items-center justify-center rounded-lg border border-dashed bg-muted/20 text-muted-foreground transition-colors', aria-label={`Remove ${file.name}`}
'hover:border-primary/50 hover:bg-muted/40 hover:text-primary',
disabled && 'cursor-not-allowed opacity-60',
)}
aria-label="Add image"
> >
<ImageIcon className="size-4" /> <X className="size-3" />
</button> </button>
</div>
); );
} }
@@ -139,14 +209,18 @@ export function RepairEvidenceForm({
defectClass, defectClass,
}: RepairEvidenceFormProps) { }: RepairEvidenceFormProps) {
const imageInputRef = useRef<HTMLInputElement | null>(null); const imageInputRef = useRef<HTMLInputElement | null>(null);
const videoInputRef = useRef<HTMLInputElement | null>(null);
const [notes, setNotes] = useState(''); const [notes, setNotes] = useState('');
const [videoFile, setVideoFile] = useState<File | null>(null); const [videoFile, setVideoFile] = useState<File | null>(null);
const [videoPreview, setVideoPreview] = useState<string | null>(null);
const [videoDuration, setVideoDuration] = useState<string | null>(null);
const [imageFiles, setImageFiles] = useState<File[]>([]); const [imageFiles, setImageFiles] = useState<File[]>([]);
const [imagePreviews, setImagePreviews] = useState<string[]>([]); const [imagePreviews, setImagePreviews] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const submitRepairUploadMutation = useSubmitRepairUploadMutation(ticketId); const submitRepairUploadMutation = useSubmitRepairUploadMutation(ticketId);
const isSubmitting = submitRepairUploadMutation.isPending; const isSubmitting = submitRepairUploadMutation.isPending;
const canSubmit = Boolean(notes.trim() && videoFile); const canSubmit = Boolean(notes.trim() && videoFile);
const canAddMoreImages = imageFiles.length < MAX_IMAGES;
useEffect(() => { useEffect(() => {
const urls = imageFiles.map((file) => URL.createObjectURL(file)); const urls = imageFiles.map((file) => URL.createObjectURL(file));
@@ -156,6 +230,32 @@ export function RepairEvidenceForm({
}; };
}, [imageFiles]); }, [imageFiles]);
useEffect(() => {
if (!videoFile) {
setVideoPreview(null);
setVideoDuration(null);
return;
}
const url = URL.createObjectURL(videoFile);
setVideoPreview(url);
setVideoDuration(null);
let cancelled = false;
const video = document.createElement('video');
video.preload = 'metadata';
video.onloadedmetadata = () => {
if (cancelled || !Number.isFinite(video.duration)) return;
setVideoDuration(formatVideoDuration(video.duration));
};
video.src = url;
return () => {
cancelled = true;
URL.revokeObjectURL(url);
};
}, [videoFile]);
const addImages = (files: FileList | null) => { const addImages = (files: FileList | null) => {
if (!files?.length) return; if (!files?.length) return;
@@ -177,6 +277,16 @@ export function RepairEvidenceForm({
); );
}; };
const selectVideo = (files: FileList | null) => {
setVideoFile(files?.[0] ?? null);
setError(null);
};
const removeVideo = () => {
setVideoFile(null);
setError(null);
};
const removeImage = (index: number) => { const removeImage = (index: number) => {
setImageFiles((current) => setImageFiles((current) =>
current.filter((_, itemIndex) => itemIndex !== index), current.filter((_, itemIndex) => itemIndex !== index),
@@ -186,7 +296,7 @@ export function RepairEvidenceForm({
const handleSubmit = async () => { const handleSubmit = async () => {
if (!notes.trim() || !videoFile) { if (!notes.trim() || !videoFile) {
setError('Repair notes and video are required.'); setError('Repair notes and a video are required.');
return; return;
} }
@@ -206,81 +316,143 @@ export function RepairEvidenceForm({
} }
}; };
const imageSlots = Array.from({ length: MAX_IMAGES }, (_, index) => ({ const openImagePicker = () => {
file: imageFiles[index] ?? null, if (!isSubmitting && canAddMoreImages) {
previewUrl: imagePreviews[index] ?? null, imageInputRef.current?.click();
})); }
};
const openVideoPicker = () => {
if (!isSubmitting) {
videoInputRef.current?.click();
}
};
return ( return (
<div className="space-y-5"> <div className="space-y-5">
<div className="space-y-2"> <div className="flex gap-3 rounded-lg border border-primary/15 bg-primary/5 p-4">
<Label htmlFor="repair-notes"> <Camera className="mt-0.5 size-5 shrink-0 text-primary" />
Repair Notes <RequiredMark /> <div className="space-y-1">
</Label> <p className="text-sm font-semibold">Instructions</p>
<Textarea <p className="text-sm text-muted-foreground">
id="repair-notes" Upload clear photos and one video of the repaired area and provide
value={notes} relevant details.
onChange={(event) => { </p>
setNotes(event.target.value); </div>
setError(null);
}}
placeholder="Describe the repair work performed..."
disabled={isSubmitting}
className="min-h-24 resize-none"
/>
</div> </div>
<div className="space-y-3">
<Label className="text-muted-foreground">Media Upload</Label>
<div className="space-y-2">
<Label className="text-sm font-normal">
Repair Video <RequiredMark />
</Label>
<MediaDropzone
icon={<Video className="size-4" />}
label="Upload Repair Video (MP4, max 50MB)"
accept="video/mp4,video/*"
file={videoFile}
onFileChange={(file) => {
setVideoFile(file);
setError(null);
}}
disabled={isSubmitting}
/>
</div>
<div className="space-y-2">
<Label className="text-sm font-normal">
Upload Images (Max {MAX_IMAGES})
</Label>
<input <input
ref={imageInputRef} ref={imageInputRef}
type="file" type="file"
accept="image/*" accept="image/jpeg,image/png,image/*"
multiple multiple
className="hidden" className="hidden"
disabled={isSubmitting || imageFiles.length >= MAX_IMAGES} disabled={isSubmitting || !canAddMoreImages}
onChange={(event) => { onChange={(event) => {
addImages(event.target.files); addImages(event.target.files);
event.target.value = ''; event.target.value = '';
}} }}
/> />
<div className="grid grid-cols-5 gap-2"> <input
{imageSlots.map((slot, index) => ( ref={videoInputRef}
<ImageSlot type="file"
key={index} accept="video/mp4,video/quicktime,video/x-msvideo,video/*"
file={slot.file} className="hidden"
previewUrl={slot.previewUrl} disabled={isSubmitting}
disabled={ onChange={(event) => {
isSubmitting || selectVideo(event.target.files);
(!slot.file && imageFiles.length >= MAX_IMAGES) event.target.value = '';
} }}
onAdd={() => imageInputRef.current?.click()} />
<section className="space-y-3">
<MediaSectionHeader
icon={<Camera className="size-4" />}
title="Photos"
addLabel="Add Photos"
onAdd={openImagePicker}
disabled={isSubmitting || !canAddMoreImages}
/>
<div className="overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{imageFiles.length === 0 ? (
<EmptyMediaPlaceholder
icon={<ImageIcon className="size-5" />}
title="No photos added yet"
description="Tap to upload repair photos"
disabled={isSubmitting}
onClick={openImagePicker}
className="min-h-[104px]"
/>
) : (
<div className="flex min-w-min gap-3">
{imageFiles.map((file, index) => (
<ImageThumbnail
key={`${file.name}-${file.lastModified}-${index}`}
file={file}
previewUrl={imagePreviews[index]}
disabled={isSubmitting}
onRemove={() => removeImage(index)} onRemove={() => removeImage(index)}
/> />
))} ))}
</div> </div>
)}
</div>
<MediaHint>
You can upload up to {MAX_IMAGES} images (JPG, PNG)
</MediaHint>
</section>
<section className="space-y-3">
<div className="flex items-center gap-2">
<Video className="size-4 text-primary" />
<span className="text-sm font-semibold">Video</span>
</div>
<div>
{!videoFile || !videoPreview ? (
<EmptyMediaPlaceholder
icon={<Video className="size-5" />}
title="No video added yet"
description="Tap to upload a repair video"
disabled={isSubmitting}
onClick={openVideoPicker}
className="min-h-[104px]"
/>
) : (
<VideoThumbnail
file={videoFile}
previewUrl={videoPreview}
duration={videoDuration}
disabled={isSubmitting}
onRemove={removeVideo}
/>
)}
</div>
<MediaHint>You can upload one video (MP4, MOV, AVI)</MediaHint>
</section>
<div className="space-y-2">
<Label htmlFor="repair-notes">
Repair Notes <RequiredMark />
</Label>
<div className="relative">
<Textarea
id="repair-notes"
value={notes}
onChange={(event) => {
setNotes(event.target.value.slice(0, MAX_NOTES));
setError(null);
}}
placeholder="Describe the repair work completed, materials used, and any additional observations."
disabled={isSubmitting}
className="min-h-28 resize-none pb-8"
/>
<span className="pointer-events-none absolute bottom-2 right-3 text-xs text-muted-foreground">
{notes.length} / {MAX_NOTES}
</span>
</div> </div>
</div> </div>

View File

@@ -0,0 +1,139 @@
'use client';
import { useState } from 'react';
import { Clock3, Loader2, Send } from 'lucide-react';
import { DatePicker } from '@/components/form/DatePicker';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type { TicketDetail } from '@/types';
import { useRequestTicketExtensionMutation } from '../../../hooks/useTicketQueries';
const MAX_REASON_LENGTH = 300;
interface RequestExtensionFormProps {
ticket: TicketDetail;
onCancel: () => void;
}
export function RequestExtensionForm({
ticket,
onCancel,
}: RequestExtensionFormProps) {
const currentDueDate = ticket.worker?.due_at
? new Date(ticket.worker.due_at)
: undefined;
const [requestedDueDate, setRequestedDueDate] = useState<Date>();
const [reason, setReason] = useState('');
const assignmentId = ticket.worker?.assignment_id;
const requestExtensionMutation = useRequestTicketExtensionMutation(
ticket.id,
assignmentId,
ticket.defect_class,
);
const isPending = requestExtensionMutation.isPending;
const isRequestedDateValid = Boolean(
requestedDueDate &&
(!currentDueDate || requestedDueDate.getTime() > currentDueDate.getTime()),
);
const canSubmit =
Boolean(assignmentId) &&
isRequestedDateValid &&
Boolean(reason.trim()) &&
!isPending;
const handleSubmit = async () => {
if (!requestedDueDate || !canSubmit) return;
await requestExtensionMutation.mutateAsync({
requested_due_at: requestedDueDate.toISOString(),
reason: reason.trim(),
});
setRequestedDueDate(undefined);
setReason('');
onCancel();
};
return (
<div className="space-y-5">
<div className="flex gap-3 rounded-lg border border-primary/15 bg-primary/5 p-4">
<Clock3 className="mt-0.5 size-5 shrink-0 text-primary" />
<p className="text-sm text-muted-foreground">
Request more time to complete the repair. Your manager will review the
request.
</p>
</div>
<div className="space-y-2">
<Label>Current Due Date</Label>
<DatePicker
value={currentDueDate}
showTimeZone={false}
placeholder="No due date available"
disabled
className="w-full"
/>
</div>
<div className="space-y-2">
<Label>
Requested Due Date <span className="text-destructive">*</span>
</Label>
<DatePicker
value={requestedDueDate}
onChange={setRequestedDueDate}
showTimeZone={false}
disabled={isPending}
className="w-full"
/>
{requestedDueDate && !isRequestedDateValid ? (
<p className="text-xs text-destructive">
Requested date must be after the current due date.
</p>
) : null}
</div>
<div className="space-y-2">
<Label htmlFor="extension-reason">
Reason for Extension <span className="text-destructive">*</span>
</Label>
<div className="relative">
<Textarea
id="extension-reason"
value={reason}
onChange={(event) =>
setReason(event.target.value.slice(0, MAX_REASON_LENGTH))
}
placeholder="Explain why additional time is required to complete the repair."
disabled={isPending}
className="min-h-28 resize-none pb-8"
/>
<span className="pointer-events-none absolute right-3 bottom-2 text-xs text-muted-foreground">
{reason.length} / {MAX_REASON_LENGTH}
</span>
</div>
</div>
<p className="text-xs text-muted-foreground">
This request will be sent to your manager for approval.
</p>
<div className="grid grid-cols-2 gap-3">
<Button
type="button"
variant="outline"
disabled={isPending}
onClick={onCancel}
>
Cancel
</Button>
<Button type="button" disabled={!canSubmit} onClick={handleSubmit}>
{isPending ? <Loader2 className="animate-spin" /> : <Send />}
{isPending ? 'Submitting...' : 'Submit Request'}
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,232 @@
'use client';
import { useState } from 'react';
import {
ArrowRight,
CalendarClock,
Check,
Clock3,
Loader2,
X,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type {
TicketDetail,
TicketExtensionRequest,
TicketExtensionRequestsResponse,
} from '@/types';
import { formatDate } from '@/utils/date';
import {
useReviewTicketExtensionMutation,
useTicketExtensionRequestQuery,
} from '../../../hooks/useTicketQueries';
import { NoTicketAction } from './NoTicketAction';
import { TicketActionCard } from './TicketActionCard';
const MAX_NOTE_LENGTH = 300;
function getPendingRequest(response: TicketExtensionRequestsResponse) {
return response.items
.filter((request) => request.status === 'pending')
.reduce<TicketExtensionRequest | null>((latest, request) => {
if (!latest) return request;
return new Date(request.requested_at) > new Date(latest.requested_at)
? request
: latest;
}, null);
}
function getExtensionDays(request: TicketExtensionRequest) {
const difference =
new Date(request.requested_due_at).getTime() -
new Date(request.current_due_at).getTime();
return Math.max(0, Math.ceil(difference / (24 * 60 * 60 * 1000)));
}
function Requester({ request }: { request: TicketExtensionRequest }) {
const name = request.requested_by?.name ?? 'Assigned worker';
const initials = name
.split(/\s+/)
.slice(0, 2)
.map((part) => part[0]?.toUpperCase())
.join('');
return (
<div className="grid grid-cols-2 gap-3 rounded-lg bg-muted/40 p-3">
<div className="flex items-center gap-2">
<span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/15 text-xs font-semibold text-primary">
{initials || 'W'}
</span>
<div className="min-w-0">
<p className="text-[11px] text-muted-foreground">Requested By</p>
<p className="truncate text-sm font-medium">{name}</p>
</div>
</div>
<div>
<p className="text-[11px] text-muted-foreground">Requested On</p>
<p className="text-sm font-medium">
{formatDate(request.requested_at)}
</p>
</div>
</div>
);
}
function ExtensionReviewForm({
ticket,
request,
}: {
ticket: TicketDetail;
request: TicketExtensionRequest;
}) {
const [note, setNote] = useState('');
const [selectedAction, setSelectedAction] = useState<
'approve' | 'reject' | null
>(null);
const assignmentId = ticket.worker?.assignment_id as number;
const reviewMutation = useReviewTicketExtensionMutation(
ticket.id,
assignmentId,
ticket.defect_class,
);
const extensionDays = getExtensionDays(request);
const submitDecision = async (action: 'approve' | 'reject') => {
setSelectedAction(action);
try {
await reviewMutation.mutateAsync({ action, note: note.trim() });
} finally {
setSelectedAction(null);
}
};
return (
<TicketActionCard icon={CalendarClock} title="Extension Request Details">
<div className="space-y-4">
<Requester request={request} />
<section className="space-y-2">
<p className="text-xs font-semibold">Request Summary</p>
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-start gap-3 rounded-lg border p-3">
<div>
<p className="text-[11px] text-muted-foreground">
Current Due Date
</p>
<p className="text-xs font-medium">
{formatDate(request.current_due_at)}
</p>
</div>
<ArrowRight className="mt-6 size-4 text-muted-foreground" />
<div>
<p className="text-[11px] text-muted-foreground">
Requested Due Date
</p>
<p className="text-xs font-medium">
{formatDate(request.requested_due_at)}
</p>
{extensionDays > 0 ? (
<span className="mt-1 inline-flex rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-semibold text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300">
+{extensionDays} {extensionDays === 1 ? 'Day' : 'Days'}
</span>
) : null}
</div>
</div>
<div className="rounded-lg border p-3">
<p className="text-[11px] text-muted-foreground">Reason</p>
<p className="mt-1 text-sm leading-relaxed">{request.reason}</p>
</div>
</section>
<div className="space-y-2">
<Label htmlFor="extension-manager-note">
Add Manager Comments{' '}
<span className="text-muted-foreground">(Optional)</span>
</Label>
<div className="relative">
<Textarea
id="extension-manager-note"
value={note}
onChange={(event) =>
setNote(event.target.value.slice(0, MAX_NOTE_LENGTH))
}
placeholder="Add a note explaining your decision..."
disabled={reviewMutation.isPending}
className="min-h-24 resize-none pb-8"
/>
<span className="pointer-events-none absolute right-3 bottom-2 text-xs text-muted-foreground">
{note.length} / {MAX_NOTE_LENGTH}
</span>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<Button
type="button"
variant="outline"
className="border-destructive/40 text-destructive hover:bg-destructive/5 hover:text-destructive"
disabled={reviewMutation.isPending}
onClick={() => submitDecision('reject')}
>
{selectedAction === 'reject' ? (
<Loader2 className="animate-spin" />
) : (
<X />
)}
Reject Request
</Button>
<Button
type="button"
disabled={reviewMutation.isPending}
onClick={() => submitDecision('approve')}
>
{selectedAction === 'approve' ? (
<Loader2 className="animate-spin" />
) : (
<Check />
)}
Approve Extension
</Button>
</div>
</div>
</TicketActionCard>
);
}
export function ReviewExtensionRequestAction({
ticket,
}: {
ticket: TicketDetail;
}) {
const assignmentId = ticket.worker?.assignment_id;
const extensionRequestQuery = useTicketExtensionRequestQuery(
ticket.id,
assignmentId,
);
if (!assignmentId || extensionRequestQuery.isError) {
return <NoTicketAction />;
}
if (extensionRequestQuery.isLoading) {
return (
<TicketActionCard icon={Clock3} title="Extension Request">
<div className="flex items-center justify-center py-8 text-muted-foreground">
<Loader2 className="mr-2 size-4 animate-spin" />
<span className="text-sm">Checking for requests...</span>
</div>
</TicketActionCard>
);
}
const pendingRequest = extensionRequestQuery.data
? getPendingRequest(extensionRequestQuery.data)
: null;
if (!pendingRequest) return <NoTicketAction />;
return <ExtensionReviewForm ticket={ticket} request={pendingRequest} />;
}

View File

@@ -1,19 +1,52 @@
'use client'; 'use client';
import { useState } from 'react';
import { Wrench } from 'lucide-react'; import { Wrench } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import type { TicketDetail } from '@/types'; import type { TicketDetail } from '@/types';
import { RepairEvidenceForm } from './RepairEvidenceForm'; import { RepairEvidenceForm } from './RepairEvidenceForm';
import { TicketExtensionRequestPanel } from './TicketExtensionRequestPanel';
import { TicketActionCard } from './TicketActionCard'; import { TicketActionCard } from './TicketActionCard';
type RepairActionTab = 'repair-proof' | 'request-extension';
export function SubmitRepairAction({ ticket }: { ticket: TicketDetail }) { export function SubmitRepairAction({ ticket }: { ticket: TicketDetail }) {
const [activeTab, setActiveTab] = useState<RepairActionTab>('repair-proof');
if (ticket.repair?.submitted_at) {
return null;
}
return ( return (
<TicketActionCard icon={Wrench} title="Submit Repair Evidence"> <TicketActionCard icon={Wrench} title="Repair Proof">
<Tabs
value={activeTab}
onValueChange={(value) => setActiveTab(value as RepairActionTab)}
className="gap-5"
>
<TabsList variant="line" className="grid h-auto w-full grid-cols-2 p-0">
<TabsTrigger value="repair-proof" className="pb-3">
Upload Repair Proof
</TabsTrigger>
<TabsTrigger value="request-extension" className="pb-3">
Request Extension
</TabsTrigger>
</TabsList>
<TabsContent value="repair-proof">
<RepairEvidenceForm <RepairEvidenceForm
ticketId={ticket.id} ticketId={ticket.id}
defectClass={ticket.defect_class} defectClass={ticket.defect_class}
/> />
</TabsContent>
<TabsContent value="request-extension">
<TicketExtensionRequestPanel
ticket={ticket}
onCancelRequest={() => setActiveTab('repair-proof')}
/>
</TabsContent>
</Tabs>
</TicketActionCard> </TicketActionCard>
); );
} }

View File

@@ -0,0 +1 @@
export { RepairProofSummary as SubmittedRepairProofAction } from '../repair/RepairProofSummary';

View File

@@ -0,0 +1,248 @@
'use client';
import {
AlertCircle,
CalendarDays,
CheckCircle2,
Clock3,
History,
Loader2,
RotateCcw,
XCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import type {
TicketDetail,
TicketExtensionRequest,
TicketExtensionRequestsResponse,
} from '@/types';
import { formatDate } from '@/utils/date';
import { useTicketExtensionRequestQuery } from '../../../hooks/useTicketQueries';
import { RequestExtensionForm } from './RequestExtensionForm';
interface TicketExtensionRequestPanelProps {
ticket: TicketDetail;
onCancelRequest: () => void;
}
interface DetailRowProps {
label: string;
value: string;
children?: React.ReactNode;
className?: string;
}
function DetailRow({ label, value, children, className }: DetailRowProps) {
return (
<div className={cn('space-y-1 px-3 py-2.5', className)}>
<p className="text-[11px] font-medium text-muted-foreground">{label}</p>
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium">{value}</p>
{children}
</div>
</div>
);
}
const statusConfig = {
pending: {
title: 'Request Pending',
description: 'Your extension request is waiting for manager approval.',
icon: Clock3,
className:
'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300',
},
approved: {
title: 'Request Approved',
description: 'Your extension request has been approved by the manager.',
icon: CheckCircle2,
className:
'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300',
},
rejected: {
title: 'Request Rejected',
description: 'Your extension request has been rejected by the manager.',
icon: AlertCircle,
className:
'border-red-200 bg-red-50 text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300',
},
cancelled: {
title: 'Request Cancelled',
description: 'This extension request was cancelled.',
icon: XCircle,
className: 'border-border bg-muted/50 text-muted-foreground',
},
} satisfies Record<
TicketExtensionRequest['status'],
{
title: string;
description: string;
icon: typeof Clock3;
className: string;
}
>;
function getLatestRequest(response: TicketExtensionRequestsResponse) {
return response.items.reduce<TicketExtensionRequest | null>(
(latest, item) => {
if (!latest) return item;
return new Date(item.requested_at) > new Date(latest.requested_at)
? item
: latest;
},
null,
);
}
function getExtensionDays(request: TicketExtensionRequest) {
const difference =
new Date(request.requested_due_at).getTime() -
new Date(request.current_due_at).getTime();
return Math.max(0, Math.ceil(difference / (24 * 60 * 60 * 1000)));
}
function ExtensionRequestDetails({
request,
}: {
request: TicketExtensionRequest;
}) {
const config = statusConfig[request.status];
const StatusIcon = config.icon;
const extensionDays = getExtensionDays(request);
return (
<div className="space-y-4">
<div className={cn('flex gap-3 rounded-lg border p-4', config.className)}>
<StatusIcon className="mt-0.5 size-5 shrink-0" />
<div className="space-y-1">
<p className="text-sm font-semibold">{config.title}</p>
<p className="text-xs leading-relaxed">{config.description}</p>
</div>
</div>
<section className="space-y-2">
<p className="text-xs font-semibold">Request Details</p>
<div className="divide-y overflow-hidden rounded-lg border">
<DetailRow
label="Requested On"
value={formatDate(request.requested_at)}
/>
<DetailRow
label="Requested Due Date"
value={formatDate(request.requested_due_at)}
>
{extensionDays > 0 ? (
<span className="shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-semibold text-primary">
+{extensionDays} {extensionDays === 1 ? 'Day' : 'Days'}
</span>
) : null}
</DetailRow>
<DetailRow label="Reason for Extension" value={request.reason} />
</div>
</section>
{request.resolved_at || request.resolved_by ? (
<section className="space-y-2">
<p className="text-xs font-semibold">Manager Response</p>
<div className="divide-y overflow-hidden rounded-lg border">
{request.resolved_at ? (
<DetailRow
label="Responded On"
value={formatDate(request.resolved_at)}
/>
) : null}
{request.resolved_by ? (
<DetailRow
label="Resolved By"
value={`${request.resolved_by.name} · ${request.resolved_by.role.name}`}
/>
) : null}
{request.status === 'approved' ? (
<DetailRow
label="Approved Due Date"
value={formatDate(request.requested_due_at)}
/>
) : null}
</div>
</section>
) : null}
<section className="space-y-2">
<p className="text-xs font-semibold">Original Due Date</p>
<div className="rounded-lg border">
<DetailRow
label="Original schedule"
value={formatDate(request.current_due_at)}
>
<CalendarDays className="size-4 text-muted-foreground" />
</DetailRow>
</div>
</section>
<Button type="button" variant="outline" className="w-full">
<History />
View Approval History
</Button>
</div>
);
}
export function TicketExtensionRequestPanel({
ticket,
onCancelRequest,
}: TicketExtensionRequestPanelProps) {
const assignmentId = ticket.worker?.assignment_id;
const extensionRequestQuery = useTicketExtensionRequestQuery(
ticket.id,
assignmentId,
);
if (!assignmentId) {
return (
<div className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
No active assignment is available for this ticket.
</div>
);
}
if (extensionRequestQuery.isLoading) {
return (
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
<Loader2 className="size-5 animate-spin" />
<span className="ml-2 text-sm">Loading extension request...</span>
</div>
);
}
if (extensionRequestQuery.isError) {
return (
<div className="space-y-3 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
<p className="text-sm text-destructive">
Extension request details could not be loaded.
</p>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => extensionRequestQuery.refetch()}
>
<RotateCcw />
Try Again
</Button>
</div>
);
}
const latestRequest = extensionRequestQuery.data
? getLatestRequest(extensionRequestQuery.data)
: null;
if (!latestRequest) {
return <RequestExtensionForm ticket={ticket} onCancel={onCancelRequest} />;
}
return <ExtensionRequestDetails request={latestRequest} />;
}

View File

@@ -1,121 +0,0 @@
'use client';
import { ImageIcon } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { useProtectedMediaObjectUrl } from '@/hooks/useProtectedMedia';
import { cn } from '@/lib/utils';
import { formatRepairDate, ReportSurface } from './repairReportUtils';
const MAX_MEDIA_SLOTS = 5;
const imageBadgeStyles = [
'bg-primary/90 text-primary-foreground',
'bg-secondary text-secondary-foreground',
'bg-accent text-accent-foreground',
'bg-muted text-muted-foreground',
'bg-primary/70 text-primary-foreground',
] as const;
export function RepairProofImagesGrid({
imageUrls,
submittedAt,
layout = 'row',
}: {
imageUrls: string[];
submittedAt: string | null;
layout?: 'row' | 'sidebar';
}) {
const imageSlots = Array.from(
{ length: MAX_MEDIA_SLOTS },
(_, index) => imageUrls[index] ?? null,
);
return (
<div
className={cn(
'grid gap-3',
layout === 'sidebar'
? 'grid-cols-2 auto-rows-fr'
: 'grid-cols-2 sm:grid-cols-3 lg:grid-cols-5',
)}
>
{imageSlots.map((url, index) => (
<RepairProofImageSlot
key={index}
url={url}
index={index}
submittedAt={submittedAt}
/>
))}
</div>
);
}
function RepairProofImageSlot({
url,
index,
submittedAt,
}: {
url: string | null;
index: number;
submittedAt: string | null;
}) {
const { objectUrl, isLoading, isError } = useProtectedMediaObjectUrl(url);
if (!url) {
return (
<ReportSurface className="space-y-2 p-2">
<div className="flex aspect-4/3 items-center justify-center rounded-lg border border-dashed border-border/70 bg-muted/10 text-muted-foreground/70">
<ImageIcon className="size-4" />
</div>
<p className="truncate px-1 text-[11px] text-muted-foreground/70">
No image added
</p>
</ReportSurface>
);
}
if (isLoading) {
return (
<ReportSurface className="space-y-2 p-2">
<Skeleton className="aspect-4/3 w-full rounded-lg" />
<Skeleton className="h-3 w-16" />
</ReportSurface>
);
}
if (isError || !objectUrl) {
return (
<ReportSurface className="space-y-2 p-2">
<div className="flex aspect-4/3 items-center justify-center rounded-lg border border-dashed bg-muted/10 text-xs text-muted-foreground">
Unavailable
</div>
<p className="truncate px-1 text-[11px] text-muted-foreground">
Image {index + 1}
</p>
</ReportSurface>
);
}
return (
<ReportSurface className="space-y-2 p-2">
<a
href={objectUrl}
target="_blank"
rel="noreferrer"
className="group relative block overflow-hidden rounded-lg border bg-muted/20"
>
<img
src={objectUrl}
alt={`Repair proof ${index + 1}`}
className="aspect-4/3 w-full object-cover transition-transform group-hover:scale-[1.02]"
/>
</a>
<p className="truncate px-1 text-[11px] text-muted-foreground">
{submittedAt ? formatRepairDate(submittedAt) : `Image ${index + 1}`}
</p>
</ReportSurface>
);
}

View File

@@ -1,108 +0,0 @@
'use client';
import { FileText, MessageSquareQuote } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
import {
EmptyPanel,
formatRepairDate,
getPersonLabel,
} from './repairReportUtils';
function MetaLabel({ children }: { children: React.ReactNode }) {
return (
<p className="text-xs font-medium tracking-wide text-muted-foreground">
{children}
</p>
);
}
function ReportField({
label,
value,
}: {
label: string;
value: string | null | undefined;
}) {
return (
<div className="space-y-1">
<MetaLabel>{label}</MetaLabel>
<p className="text-sm font-semibold text-foreground">{value || '-'}</p>
</div>
);
}
export function RepairReportPanel({ ticket }: { ticket: TicketDetail }) {
const repair = ticket.repair;
if (!repair) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FileText className="size-5 text-primary" />
Repair Report
</CardTitle>
</CardHeader>
<CardContent>
<EmptyPanel
icon={MessageSquareQuote}
title="No repair report submitted yet"
description="Repair details will appear here once the assigned worker submits evidence."
className="py-10"
/>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader className="sm:grid-cols-[1fr_auto]">
<CardTitle className="flex items-center gap-2">
<FileText className="size-5 text-primary" />
Repair Report
</CardTitle>
{repair.submitted_at ? (
<span className="text-xs text-muted-foreground italic sm:col-start-2 sm:row-start-1">
Completed {formatRepairDate(repair.submitted_at)}
</span>
) : null}
</CardHeader>
<CardContent className="space-y-5">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<ReportField
label="Technician"
value={getPersonLabel(ticket.worker)}
/>
<ReportField
label="Submitted At"
value={
repair.submitted_at ? formatRepairDate(repair.submitted_at) : null
}
/>
</div>
<div className="space-y-2">
<MetaLabel>Repair Summary</MetaLabel>
{repair.notes?.trim() ? (
<div className="rounded-lg border bg-muted/15 px-4 py-3">
<p className="text-sm leading-relaxed text-foreground/90">
{repair.notes}
</p>
</div>
) : (
<EmptyPanel
icon={MessageSquareQuote}
title="No repair notes added yet"
className="py-6"
/>
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,78 +0,0 @@
'use client';
import { ShieldCheck } from 'lucide-react';
import { ProtectedVideoPlayer } from '@/components/media/ProtectedVideoPlayer';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
export function RepairVideoComparison({ ticket }: { ticket: TicketDetail }) {
const originalVideoUrl = ticket.video?.url ?? null;
const repairVideoUrl = ticket.repair?.proof_video_url ?? null;
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ShieldCheck className="size-5 text-primary" />
Repair Verification
</CardTitle>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<ComparisonVideoItem
tooltip={ticket.video?.name ?? 'Original inspection video'}
videoLabel="Before"
videoUrl={originalVideoUrl}
meta="AI detection video"
emptyTitle="No original video available"
emptyDescription="The source inspection video is not attached to this ticket."
/>
<ComparisonVideoItem
tooltip="Contractor repair evidence video"
videoLabel="After"
videoUrl={repairVideoUrl}
meta="Contractor evidence video"
emptyTitle={
ticket.repair
? 'No repair video uploaded'
: 'No evidence submitted yet'
}
emptyDescription={
ticket.repair
? 'The assigned worker has not uploaded a repair video yet.'
: 'Repair video will appear here once evidence is submitted.'
}
/>
</CardContent>
</Card>
);
}
function ComparisonVideoItem({
tooltip,
videoLabel,
videoUrl,
meta,
emptyTitle,
emptyDescription,
}: {
tooltip: string;
videoLabel: string;
videoUrl: string | null;
meta: string;
emptyTitle: string;
emptyDescription: string;
}) {
return (
<div title={tooltip}>
<ProtectedVideoPlayer
url={videoUrl}
label={videoLabel}
meta={meta}
emptyTitle={emptyTitle}
emptyDescription={emptyDescription}
/>
</div>
);
}

View File

@@ -1,69 +0,0 @@
'use client';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { TicketActor } from '@/types';
export function formatRepairDate(value: string | null | undefined) {
if (!value) return '-';
return new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(value));
}
export function getPersonLabel(person: TicketActor | null | undefined) {
return person?.name || person?.email || 'Unknown';
}
export function SectionLabel({ children }: { children: React.ReactNode }) {
return (
<p className="text-[11px] font-semibold tracking-[0.12em] text-foreground uppercase">
{children}
</p>
);
}
export function ReportSurface({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div className={cn('rounded-lg border bg-muted/15 p-3', className)}>
{children}
</div>
);
}
export function EmptyPanel({
icon: Icon,
title,
description,
className,
}: {
icon: LucideIcon;
title: string;
description?: string;
className?: string;
}) {
return (
<div
className={cn(
'flex flex-col items-center justify-center rounded-lg border border-dashed border-border/80 bg-muted/10 px-4 py-8 text-center',
className,
)}
>
<Icon className="mb-3 size-6 text-muted-foreground" />
<p className="text-sm font-medium text-muted-foreground">{title}</p>
{description ? (
<p className="mt-1 max-w-xs text-xs text-muted-foreground/80">
{description}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,114 @@
'use client';
import { useEffect, useMemo } from 'react';
import { useQueries } from '@tanstack/react-query';
import LightGallery from 'lightgallery/react';
import lgThumbnail from 'lightgallery/plugins/thumbnail';
import lgZoom from 'lightgallery/plugins/zoom';
import { Skeleton } from '@/components/ui/skeleton';
import { protectedMediaService } from '@/services/api';
interface RepairProofGalleryProps {
imageUrls: string[];
}
const MAX_VISIBLE_IMAGES = 8;
export function RepairProofGallery({ imageUrls }: RepairProofGalleryProps) {
const queries = useQueries({
queries: imageUrls.map((url) => ({
queryKey: ['protected-media', 'v2', url],
queryFn: () => protectedMediaService.getBlob(url),
staleTime: Infinity,
gcTime: 1000 * 60 * 30,
})),
});
const blobs = queries.map((query) => query.data);
const objectUrls = useMemo(
() => blobs.map((blob) => (blob ? URL.createObjectURL(blob) : null)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[...blobs],
);
useEffect(
() => () => {
objectUrls.forEach((url) => {
if (url) URL.revokeObjectURL(url);
});
},
[objectUrls],
);
if (queries.some((query) => query.isLoading)) {
return (
<div className="grid grid-cols-4 gap-1 overflow-hidden rounded-xl">
{imageUrls.slice(0, MAX_VISIBLE_IMAGES).map((url, index) => (
<Skeleton
key={`${url}-${index}`}
className="aspect-square rounded-none"
/>
))}
</div>
);
}
const images = objectUrls.flatMap((url, index) =>
url ? [{ url, originalIndex: index }] : [],
);
const visibleCount = Math.min(MAX_VISIBLE_IMAGES, images.length);
const overflowCount = images.length - visibleCount;
if (images.length === 0) {
return (
<div className="rounded-lg border border-dashed py-8 text-center text-sm text-muted-foreground">
Repair images are unavailable.
</div>
);
}
return (
<LightGallery
elementClassNames="grid grid-cols-4 gap-1 overflow-hidden rounded-xl"
mode="lg-fade"
speed={400}
plugins={[lgThumbnail, lgZoom]}
thumbnail
download={false}
mobileSettings={{ controls: true, showCloseIcon: true, download: false }}
>
{images.map(({ url, originalIndex }, index) => {
const isVisible = index < visibleCount;
const isOverflowTile = overflowCount > 0 && index === visibleCount - 1;
return (
<a
key={imageUrls[originalIndex]}
data-src={url}
data-sub-html={`<p>Repair evidence ${originalIndex + 1}</p>`}
className={isVisible ? 'group relative aspect-square' : 'hidden'}
aria-label={
isOverflowTile
? `View all ${images.length} repair images`
: `View repair image ${originalIndex + 1} of ${images.length}`
}
>
{/* Blob URLs cannot be handled by next/image. */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={url}
alt={`Repair evidence ${originalIndex + 1}`}
className="size-full object-cover transition duration-300 group-hover:scale-[1.03] group-hover:brightness-90"
/>
{isOverflowTile ? (
<span className="absolute inset-0 flex items-center justify-center bg-black/55 text-xl font-semibold text-white transition-colors group-hover:bg-black/65">
+{overflowCount}
</span>
) : null}
</a>
);
})}
</LightGallery>
);
}

View File

@@ -0,0 +1,103 @@
import { CheckCircle2, HardHat, Wrench } from 'lucide-react';
import { ProtectedVideoPlayer } from '@/components/media/ProtectedVideoPlayer';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
import { formatDate } from '@/utils/date';
import { RepairProofGallery } from './RepairProofGallery';
function SubmittedBanner({
submittedAt,
submitterName,
}: {
submittedAt: string;
submitterName: string;
}) {
return (
<div className="flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-3 dark:border-emerald-900/60 dark:bg-emerald-950/30">
<CheckCircle2 className="mt-0.5 size-5 shrink-0 text-emerald-600 dark:text-emerald-400" />
<div className="min-w-0 space-y-0.5">
<p className="text-sm font-semibold text-emerald-800 dark:text-emerald-200">
Repair Submitted
</p>
<p className="text-xs text-emerald-700/80 dark:text-emerald-300/80">
{formatDate(submittedAt)} by {submitterName}
</p>
</div>
</div>
);
}
function ImageGallery({
imageUrls,
hasVideo,
}: {
imageUrls: string[];
hasVideo: boolean;
}) {
if (imageUrls.length === 0) {
return hasVideo ? null : (
<div className="flex items-center gap-2 rounded-lg border border-dashed px-3 py-4 text-sm text-muted-foreground">
<HardHat className="size-4 shrink-0" />
No media attached
</div>
);
}
return <RepairProofGallery imageUrls={imageUrls} />;
}
function Notes({ notes }: { notes: string | null | undefined }) {
return (
<div className="space-y-1.5">
<p className="text-xs font-semibold text-foreground">Repair Notes</p>
<p className="text-sm leading-relaxed text-muted-foreground">
{notes?.trim() || 'No repair notes provided.'}
</p>
</div>
);
}
export function RepairProofSummary({ ticket }: { ticket: TicketDetail }) {
const repair = ticket.repair;
if (!repair?.submitted_at) {
return null;
}
const submitterName = ticket.worker?.name?.trim() || 'Assigned worker';
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Wrench className="size-4 text-primary" />
Repair Proof
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<SubmittedBanner
submittedAt={repair.submitted_at}
submitterName={submitterName}
/>
<ProtectedVideoPlayer
url={repair.proof_video_url}
meta="Contractor evidence video"
emptyTitle="No repair video uploaded"
emptyDescription="The assigned worker has not uploaded a repair video."
className="rounded-lg"
/>
<ImageGallery
imageUrls={repair.proof_image_urls}
hasVideo={Boolean(repair.proof_video_url)}
/>
<Notes notes={repair.notes} />
</CardContent>
</Card>
);
}

View File

@@ -6,14 +6,24 @@ import { ArrowLeft } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { TicketDetailHeader } from './components/TicketDetailHeader'; import { TicketDetailHeader } from './components/TicketDetailHeader';
import { TicketDetailSkeleton } from './components/TicketDetailSkeleton'; import {
TicketOverviewCardSkeleton,
TicketOverviewHeaderSkeleton,
} from './components/TicketOverviewSkeleton';
import {
TicketClassActionsSkeleton,
TicketClassContentSkeleton,
} from './components/TicketClassDetailSkeleton';
import { TicketHistoryCard } from './components/TicketHistoryCard'; import { TicketHistoryCard } from './components/TicketHistoryCard';
import { TicketOverviewCard } from './components/TicketOverviewCard'; import { TicketOverviewCard } from './components/TicketOverviewCard';
import { TicketRepairReportCard } from './components/TicketRepairReportCard';
import { TicketStatusActions } from './components/TicketStatusActions'; import { TicketStatusActions } from './components/TicketStatusActions';
import { TicketDefectClassTabs } from './components/TicketDefectClassTabs';
import { useTicketDetailEvents } from '../hooks/useTicketDetailEvents'; import { useTicketDetailEvents } from '../hooks/useTicketDetailEvents';
import { useTicketDetailQuery } from '../hooks/useTicketQueries'; import {
useTicketClassDetailQuery,
useTicketOverviewQuery,
} from '../hooks/useTicketQueries';
export default function TicketDetailPage() { export default function TicketDetailPage() {
const router = useRouter(); const router = useRouter();
@@ -21,16 +31,17 @@ export default function TicketDetailPage() {
const { ticketId } = useParams() as { ticketId: string }; const { ticketId } = useParams() as { ticketId: string };
const defectClass = searchParams.get('defect_class') ?? undefined; const defectClass = searchParams.get('defect_class') ?? undefined;
const ticketQuery = useTicketDetailQuery(ticketId, defectClass); const overviewQuery = useTicketOverviewQuery(ticketId);
const ticket = ticketQuery.data; const classDetailQuery = useTicketClassDetailQuery(ticketId, defectClass);
const overview = overviewQuery.data;
const classDetail = classDetailQuery.data;
const isClassDetailLoading = Boolean(
defectClass && classDetailQuery.isLoading,
);
useTicketDetailEvents(ticketId, defectClass, Boolean(ticketId)); useTicketDetailEvents(ticketId, defectClass, Boolean(ticketId));
if (ticketQuery.isLoading) { if (overviewQuery.isError) {
return <TicketDetailSkeleton />;
}
if (ticketQuery.isError || !ticket) {
return ( return (
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-3"> <div className="flex min-h-[60vh] flex-col items-center justify-center gap-3">
<p className="text-sm text-destructive">Failed to load ticket.</p> <p className="text-sm text-destructive">Failed to load ticket.</p>
@@ -48,17 +59,31 @@ export default function TicketDetailPage() {
return ( return (
<main className="relative z-10 space-y-5"> <main className="relative z-10 space-y-5">
<TicketDetailHeader ticket={ticket} /> {overview ? (
<TicketDetailHeader ticket={overview} />
) : (
<TicketOverviewHeaderSkeleton />
)}
<div className="grid gap-5 xl:grid-cols-[minmax(0,7fr)_minmax(0,3fr)]"> <div className="grid gap-5 xl:grid-cols-[minmax(0,7fr)_minmax(0,3fr)]">
<div className="space-y-5"> <div className="space-y-5">
<TicketOverviewCard ticket={ticket} /> {overview ? (
<TicketRepairReportCard ticket={ticket} /> <TicketOverviewCard ticket={overview} />
<TicketHistoryCard ticket={ticket} /> ) : (
<TicketOverviewCardSkeleton />
)}
<TicketDefectClassTabs ticketId={ticketId} ticket={overview} />
{isClassDetailLoading ? <TicketClassContentSkeleton /> : null}
{!isClassDetailLoading && classDetail ? (
<TicketHistoryCard ticket={classDetail} />
) : null}
</div> </div>
<div className="self-start"> <div className="space-y-3 self-start">
<TicketStatusActions ticket={ticket} /> {isClassDetailLoading ? <TicketClassActionsSkeleton /> : null}
{!isClassDetailLoading && classDetail ? (
<TicketStatusActions ticket={classDetail} />
) : null}
</div> </div>
</div> </div>
</main> </main>

View File

@@ -30,16 +30,21 @@ export function useTicketColumns(): ColumnDef<TicketListItem>[] {
size: 120, size: 120,
}, },
{ {
accessorKey: 'assigned_to_name', id: 'created_by',
header: 'Assigned To',
size: 220,
cell: ({ row }) => row.original.assigned_to_name || 'N/A',
},
{
accessorKey: 'created_by_name',
header: 'Uploaded By', header: 'Uploaded By',
size: 220, size: 220,
cell: ({ row }) => row.original.created_by_name || 'N/A', cell: ({ row }) => (
<div>
<p className="font-medium">
{row.original.created_by_name || 'N/A'}
</p>
{row.original.created_by_email ? (
<p className="text-xs text-muted-foreground">
{row.original.created_by_email}
</p>
) : null}
</div>
),
}, },
{ {
accessorKey: 'updated_at', accessorKey: 'updated_at',

View File

@@ -59,7 +59,6 @@ function shouldCountCreatedTicket(
event: TicketTableStatusEvent, event: TicketTableStatusEvent,
params?: TicketListParams, params?: TicketListParams,
) { ) {
if (params?.status && event.status !== params.status) return false;
if (params?.chainage_id && event.chainage_id !== params.chainage_id) { if (params?.chainage_id && event.chainage_id !== params.chainage_id) {
return false; return false;
} }
@@ -87,7 +86,6 @@ function buildTicketListItem(
if ( if (
!event.id || !event.id ||
!event.ticket_name || !event.ticket_name ||
!event.status ||
event.detection_count === undefined || event.detection_count === undefined ||
!event.updated_at !event.updated_at
) { ) {
@@ -99,11 +97,10 @@ function buildTicketListItem(
ticket_name: event.ticket_name, ticket_name: event.ticket_name,
chainage_id: event.chainage_id ?? null, chainage_id: event.chainage_id ?? null,
chainage_name: event.chainage_name ?? null, chainage_name: event.chainage_name ?? null,
status: event.status,
default_defect_class: event.default_defect_class ?? null, default_defect_class: event.default_defect_class ?? null,
assigned_to_name: event.assigned_to_name ?? null,
detection_count: event.detection_count, detection_count: event.detection_count,
created_by_name: event.created_by_name ?? null, created_by_name: event.created_by_name ?? null,
created_by_email: event.created_by_email ?? null,
created_at: event.created_at ?? event.updated_at, created_at: event.created_at ?? event.updated_at,
updated_at: event.updated_at, updated_at: event.updated_at,
}; };
@@ -118,12 +115,11 @@ function mergeTicketListItem(
ticket_name: event.ticket_name ?? current.ticket_name, ticket_name: event.ticket_name ?? current.ticket_name,
chainage_id: event.chainage_id ?? current.chainage_id, chainage_id: event.chainage_id ?? current.chainage_id,
chainage_name: event.chainage_name ?? current.chainage_name, chainage_name: event.chainage_name ?? current.chainage_name,
status: event.status ?? current.status,
default_defect_class: default_defect_class:
event.default_defect_class ?? current.default_defect_class, event.default_defect_class ?? current.default_defect_class,
assigned_to_name: event.assigned_to_name ?? current.assigned_to_name,
detection_count: event.detection_count ?? current.detection_count, detection_count: event.detection_count ?? current.detection_count,
created_by_name: event.created_by_name ?? current.created_by_name, created_by_name: event.created_by_name ?? current.created_by_name,
created_by_email: event.created_by_email ?? current.created_by_email,
created_at: event.created_at ?? current.created_at, created_at: event.created_at ?? current.created_at,
updated_at: event.updated_at ?? current.updated_at, updated_at: event.updated_at ?? current.updated_at,
}; };

View File

@@ -31,9 +31,12 @@ export function useTicketDetailEvents(
const refetchTicket = useCallback(() => { const refetchTicket = useCallback(() => {
if (!ticketId) return; if (!ticketId) return;
queryClient.refetchQueries({ queryKey: ticketKeys.overview(ticketId) });
if (defectClassRef.current) {
queryClient.refetchQueries({ queryClient.refetchQueries({
queryKey: ticketKeys.detail(ticketId, defectClassRef.current), queryKey: ticketKeys.classDetail(ticketId, defectClassRef.current),
}); });
}
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ticketKeys.defectClasses(ticketId), queryKey: ticketKeys.defectClasses(ticketId),
}); });
@@ -63,19 +66,11 @@ export function useTicketDetailEvents(
[refetchTicket], [refetchTicket],
); );
const shouldStop = useCallback(
(eventName: keyof typeof events, event: unknown) =>
eventName === 'ticket_status' &&
(event as TicketDetailStatusEvent).status === 'closed',
[],
);
useSseWithToken({ useSseWithToken({
enabled: Boolean(enabled && ticketId), enabled: Boolean(enabled && ticketId),
getToken, getToken,
getPath, getPath,
events, events,
reconnectOnEvents: TICKET_DETAIL_RECONNECT_EVENTS, reconnectOnEvents: TICKET_DETAIL_RECONNECT_EVENTS,
shouldStop,
}); });
} }

View File

@@ -4,16 +4,18 @@ import { useMemo } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { ticketService } from '@/services/api'; import { ticketService, videoService } from '@/services/api';
import type { import type {
AssignTicketPayload, AssignTicketPayload,
CloseTicketPayload, CloseTicketPayload,
RequestTicketExtensionPayload,
ReviewTicketExtensionPayload,
ReviewRepairPayload, ReviewRepairPayload,
SubmitRepairPayload, SubmitRepairPayload,
SubmitRepairUploadPayload, SubmitRepairUploadPayload,
TicketDetail, TicketDetail,
TicketListParams, TicketListParams,
TicketStatus, VideoDetectionsParams,
} from '@/types'; } from '@/types';
import { ticketKeys } from '../queries/ticketKeys'; import { ticketKeys } from '../queries/ticketKeys';
@@ -53,15 +55,26 @@ export function useTicketsQuery(params: UseTicketsQueryParams) {
}); });
} }
export function useTicketDetailQuery( export function useTicketOverviewQuery(ticketId: string | undefined) {
return useQuery({
queryKey: ticketKeys.overview(ticketId ?? ''),
queryFn: () => ticketService.getTicketOverview(ticketId as string),
enabled: Boolean(ticketId),
});
}
export function useTicketClassDetailQuery(
ticketId: string | undefined, ticketId: string | undefined,
defectClass: string | undefined, defectClass: string | undefined,
) { ) {
return useQuery({ return useQuery({
queryKey: ticketKeys.detail(ticketId ?? '', defectClass), queryKey: ticketKeys.classDetail(ticketId ?? '', defectClass ?? ''),
queryFn: () => queryFn: () =>
ticketService.getTicketDetail(ticketId as string, defectClass), ticketService.getTicketClassDetail(
enabled: Boolean(ticketId), ticketId as string,
defectClass as string,
),
enabled: Boolean(ticketId && defectClass),
}); });
} }
@@ -73,6 +86,52 @@ export function useTicketDefectClassesQuery(ticketId: string | undefined) {
}); });
} }
export function useTicketClassDetectionsQuery(
videoId: string | undefined,
params: VideoDetectionsParams,
) {
const queryParams = useMemo(
() => ({
skip: params.skip ?? 0,
limit: params.limit ?? 1,
class_name: params.class_name,
min_confidence: params.min_confidence,
sort: params.sort ?? 'timestamp_asc',
search: params.search,
}),
[
params.class_name,
params.limit,
params.min_confidence,
params.search,
params.skip,
params.sort,
],
);
return useQuery({
queryKey: ticketKeys.classDetections(videoId ?? '', queryParams),
queryFn: () =>
videoService.getVideoDetections(videoId as string, queryParams),
enabled: Boolean(videoId && queryParams.class_name),
});
}
export function useTicketExtensionRequestQuery(
ticketId: string | undefined,
assignmentId: number | undefined,
) {
return useQuery({
queryKey: ticketKeys.extensionRequest(ticketId ?? '', assignmentId),
queryFn: () =>
ticketService.getTicketExtensionRequest(
ticketId as string,
assignmentId as number,
),
enabled: Boolean(ticketId && assignmentId),
});
}
export function useAssignableTicketUsersQuery(enabled: boolean) { export function useAssignableTicketUsersQuery(enabled: boolean) {
return useQuery({ return useQuery({
queryKey: ticketKeys.assignableUsers(), queryKey: ticketKeys.assignableUsers(),
@@ -103,7 +162,7 @@ export function useAssignTicketMutation(ticketId: string) {
onSuccess: (ticket, payload) => { onSuccess: (ticket, payload) => {
toast.success('Ticket assigned'); toast.success('Ticket assigned');
queryClient.setQueryData<TicketDetail>( queryClient.setQueryData<TicketDetail>(
ticketKeys.detail(ticketId, payload.defect_class), ticketKeys.classDetail(ticketId, payload.defect_class),
(current) => mergeTicketDetailResponse(current, ticket), (current) => mergeTicketDetailResponse(current, ticket),
); );
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() }); queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
@@ -121,7 +180,7 @@ export function useSubmitRepairMutation(ticketId: string) {
onSuccess: (ticket) => { onSuccess: (ticket) => {
toast.success('Repair submitted'); toast.success('Repair submitted');
queryClient.setQueryData<TicketDetail>( queryClient.setQueryData<TicketDetail>(
ticketKeys.detail(ticketId), ticketKeys.classDetail(ticketId, ticket.defect_class),
(current) => mergeTicketDetailResponse(current, ticket), (current) => mergeTicketDetailResponse(current, ticket),
); );
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() }); queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
@@ -139,7 +198,7 @@ export function useSubmitRepairUploadMutation(ticketId: string) {
onSuccess: (ticket, payload) => { onSuccess: (ticket, payload) => {
toast.success('Repair evidence uploaded'); toast.success('Repair evidence uploaded');
queryClient.setQueryData<TicketDetail>( queryClient.setQueryData<TicketDetail>(
ticketKeys.detail(ticketId, payload.defect_class), ticketKeys.classDetail(ticketId, payload.defect_class),
(current) => mergeTicketDetailResponse(current, ticket), (current) => mergeTicketDetailResponse(current, ticket),
); );
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() }); queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
@@ -148,6 +207,64 @@ export function useSubmitRepairUploadMutation(ticketId: string) {
}); });
} }
export function useRequestTicketExtensionMutation(
ticketId: string,
assignmentId: number | undefined,
defectClass: string,
) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: RequestTicketExtensionPayload) => {
if (assignmentId === undefined) {
throw new Error('No active assignment is available for this ticket.');
}
return ticketService.requestTicketExtension(
ticketId,
assignmentId,
payload,
);
},
onSuccess: () => {
toast.success('Extension request submitted');
queryClient.invalidateQueries({
queryKey: ticketKeys.extensionRequest(ticketId, assignmentId),
});
queryClient.invalidateQueries({
queryKey: ticketKeys.classDetail(ticketId, defectClass),
});
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
},
onError: () => toast.error('Failed to request an extension'),
});
}
export function useReviewTicketExtensionMutation(
ticketId: string,
assignmentId: number,
defectClass: string,
) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: ReviewTicketExtensionPayload) =>
ticketService.reviewTicketExtension(ticketId, assignmentId, payload),
onSuccess: (_response, payload) => {
toast.success(
payload.action === 'approve'
? 'Extension request approved'
: 'Extension request rejected',
);
queryClient.invalidateQueries({
queryKey: ticketKeys.extensionRequest(ticketId, assignmentId),
});
queryClient.invalidateQueries({
queryKey: ticketKeys.classDetail(ticketId, defectClass),
});
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
},
onError: () => toast.error('Failed to review extension request'),
});
}
export function useReviewRepairMutation(ticketId: string) { export function useReviewRepairMutation(ticketId: string) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@@ -159,7 +276,7 @@ export function useReviewRepairMutation(ticketId: string) {
payload.action === 'approve' ? 'Repair approved' : 'Repair rejected', payload.action === 'approve' ? 'Repair approved' : 'Repair rejected',
); );
queryClient.setQueryData<TicketDetail>( queryClient.setQueryData<TicketDetail>(
ticketKeys.detail(ticketId, payload.defect_class), ticketKeys.classDetail(ticketId, payload.defect_class),
(current) => mergeTicketDetailResponse(current, ticket), (current) => mergeTicketDetailResponse(current, ticket),
); );
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() }); queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
@@ -177,7 +294,7 @@ export function useCloseTicketMutation(ticketId: string) {
onSuccess: (ticket, payload) => { onSuccess: (ticket, payload) => {
toast.success('Ticket closed'); toast.success('Ticket closed');
queryClient.setQueryData<TicketDetail>( queryClient.setQueryData<TicketDetail>(
ticketKeys.detail(ticketId, payload.defect_class), ticketKeys.classDetail(ticketId, payload.defect_class),
(current) => mergeTicketDetailResponse(current, ticket), (current) => mergeTicketDetailResponse(current, ticket),
); );
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() }); queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });

View File

@@ -1,13 +1,25 @@
import type { TicketListParams } from '@/types'; import type { TicketListParams, VideoDetectionsParams } from '@/types';
export const ticketKeys = { export const ticketKeys = {
all: ['tickets'] as const, all: ['tickets'] as const,
lists: () => [...ticketKeys.all, 'list'] as const, lists: () => [...ticketKeys.all, 'list'] as const,
list: (params: TicketListParams) => [...ticketKeys.lists(), params] as const, list: (params: TicketListParams) => [...ticketKeys.lists(), params] as const,
details: () => [...ticketKeys.all, 'detail'] as const, details: () => [...ticketKeys.all, 'detail'] as const,
detail: (ticketId: string, defectClass?: string) => overview: (ticketId: string) =>
[...ticketKeys.details(), ticketId, defectClass] as const, [...ticketKeys.details(), ticketId, 'overview'] as const,
classDetail: (ticketId: string, defectClass: string) =>
[...ticketKeys.details(), ticketId, 'class', defectClass] as const,
classDetections: (videoId: string, params: VideoDetectionsParams) =>
[...ticketKeys.details(), 'video', videoId, 'detections', params] as const,
defectClasses: (ticketId: string) => defectClasses: (ticketId: string) =>
[...ticketKeys.detail(ticketId), 'defect-classes'] as const, [...ticketKeys.details(), ticketId, 'defect-classes'] as const,
extensionRequest: (ticketId: string, assignmentId: number | undefined) =>
[
...ticketKeys.details(),
ticketId,
'assignments',
assignmentId,
'extension-request',
] as const,
assignableUsers: () => [...ticketKeys.all, 'assignable-users'] as const, assignableUsers: () => [...ticketKeys.all, 'assignable-users'] as const,
}; };

View File

@@ -1,79 +0,0 @@
'use client';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
const pageSizes = [10, 20, 40, 50, 100];
interface CardPaginationProps {
skip: number;
limit: number;
total: number;
count: number;
onPageChange: (skip: number) => void;
onLimitChange: (limit: number) => void;
}
export function CardPagination({
skip,
limit,
total,
count,
onPageChange,
onLimitChange,
}: CardPaginationProps) {
return (
<div className="flex flex-col gap-3 text-sm text-muted-foreground md:flex-row md:items-center md:justify-between">
<div className="flex flex-wrap items-center gap-3">
<span>Showing {count} of {total}</span>
<div className="flex items-center gap-2">
<span>Rows per page</span>
<Select
value={String(limit)}
onValueChange={(value) => onLimitChange(Number(value))}
>
<SelectTrigger className="h-8 w-18 bg-background">
<SelectValue />
</SelectTrigger>
<SelectContent>
{pageSizes.map((size) => (
<SelectItem key={size} value={String(size)}>
{size}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={skip === 0}
onClick={() => onPageChange(Math.max(0, skip - limit))}
>
<ChevronLeft className="size-4" />
Previous
</Button>
<Button
variant="outline"
size="sm"
disabled={skip + limit >= total}
onClick={() => onPageChange(skip + limit)}
>
Next
<ChevronRight className="size-4" />
</Button>
</div>
</div>
);
}

View File

@@ -1,27 +1,37 @@
'use client'; 'use client';
import { Eye, MoreVertical, PlayCircle } from 'lucide-react'; import { useRouter } from 'next/navigation';
import {
Download,
Eye,
MoreVertical,
PlayCircle,
RotateCcw,
Ticket,
Trash2,
} from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'; } from '@/components/ui/dropdown-menu';
import type { UploadVideo } from '@/types'; import type { UploadListItem } from '@/types';
interface UploadActionsMenuProps { interface UploadActionsMenuProps {
upload: UploadVideo; upload: UploadListItem;
onViewVideo: (upload: UploadVideo) => void; onViewVideo: (upload: UploadListItem) => void;
onViewDetails: (upload: UploadVideo) => void;
} }
export function UploadActionsMenu({ export function UploadActionsMenu({
upload, upload,
onViewVideo, onViewVideo,
onViewDetails,
}: UploadActionsMenuProps) { }: UploadActionsMenuProps) {
const router = useRouter();
return ( return (
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
@@ -37,7 +47,7 @@ export function UploadActionsMenu({
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{upload.video_url ? ( {upload.raw_video_url ? (
<DropdownMenuItem <DropdownMenuItem
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
@@ -48,14 +58,26 @@ export function UploadActionsMenu({
View Video View Video
</DropdownMenuItem> </DropdownMenuItem>
) : null} ) : null}
<DropdownMenuItem>
<Eye /> View Details
</DropdownMenuItem>
<DropdownMenuItem>
<RotateCcw /> Retry Analysis
</DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem
disabled={!upload.ticket_id}
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
onViewDetails(upload); if (upload.ticket_id) {
router.push(`/ticket/${upload.ticket_id}`);
}
}} }}
> >
<Eye className="size-4" /> <Ticket /> Open Ticket
View Details </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">
<Trash2 /> Delete
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>

View File

@@ -1,107 +0,0 @@
'use client';
import { FileVideo } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import type { UploadVideo } from '@/types';
import { CardPagination } from './CardPagination';
import { UploadActionsMenu } from './UploadActionsMenu';
import { UploadThumbnail } from './UploadThumbnail';
import { formatUploadedAt } from './uploadUtils';
interface UploadCardGridProps {
uploads: UploadVideo[];
isLoading: boolean;
skip: number;
limit: number;
total: number;
onPageChange: (skip: number) => void;
onLimitChange: (limit: number) => void;
onUploadNew: () => void;
onOpenUpload: (upload: UploadVideo) => void;
onViewVideo: (upload: UploadVideo) => void;
onViewDetails: (upload: UploadVideo) => void;
}
export function UploadCardGrid({
uploads,
isLoading,
skip,
limit,
total,
onPageChange,
onLimitChange,
onUploadNew,
onOpenUpload,
onViewVideo,
onViewDetails,
}: UploadCardGridProps) {
const skeletonItems = Array.from({ length: 6 });
if (!isLoading && uploads.length === 0) {
return (
<Card>
<CardContent className="flex min-h-80 flex-col items-center justify-center gap-3 text-center">
<div className="flex size-12 items-center justify-center rounded-md border bg-muted/40">
<FileVideo className="size-6 text-muted-foreground" />
</div>
<div>
<h2 className="text-base">No uploads found</h2>
<p className="text-sm text-muted-foreground">
Upload your first road inspection video.
</p>
</div>
<Button onClick={onUploadNew}>Upload New</Button>
</CardContent>
</Card>
);
}
return (
<section className="space-y-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-5">
{isLoading
? skeletonItems.map((_, index) => (
<Card key={index} className="h-62 animate-pulse bg-muted/30" />
))
: uploads.map((upload) => (
<Card
key={upload.video_id}
className="cursor-pointer overflow-hidden transition-colors hover:bg-muted/30"
onClick={() => onOpenUpload(upload)}
>
<CardContent className="space-y-3 p-3">
<UploadThumbnail upload={upload} />
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{upload.filename}
</p>
<p className="text-xs text-muted-foreground">
Uploaded {formatUploadedAt(upload.uploaded_at)}
</p>
</div>
<UploadActionsMenu
upload={upload}
onViewVideo={onViewVideo}
onViewDetails={onViewDetails}
/>
</div>
</CardContent>
</Card>
))}
</div>
<CardPagination
skip={skip}
limit={limit}
total={total}
count={uploads.length}
onPageChange={onPageChange}
onLimitChange={onLimitChange}
/>
</section>
);
}

View File

@@ -1,77 +0,0 @@
'use client';
import { useMemo } from 'react';
import type { ColumnDef } from '@tanstack/react-table';
import { UploadActionsMenu } from './UploadActionsMenu';
import { UploadThumbnail } from './UploadThumbnail';
import { formatUploadedAt, getUploadStatus } from './uploadUtils';
import { Badge } from '@/components/ui/badge';
import type { UploadVideo } from '@/types';
interface UseUploadColumnsProps {
onViewVideo: (upload: UploadVideo) => void;
onViewDetails: (upload: UploadVideo) => void;
}
export function useUploadColumns({
onViewVideo,
onViewDetails,
}: UseUploadColumnsProps) {
return useMemo<ColumnDef<UploadVideo>[]>(
() => [
{
id: 'thumbnail',
header: 'Thumbnail',
size: 140,
minSize: 120,
enableSorting: false,
meta: { disableTruncate: true },
cell: ({ row }) => (
<UploadThumbnail upload={row.original} className="w-28" />
),
},
{
accessorKey: 'filename',
header: 'Filename',
cell: ({ row }) => (
<span className="font-medium">{row.original.filename}</span>
),
},
{
id: 'status',
header: 'Status',
size: 130,
cell: ({ row }) => (
<Badge className="rounded-full">
{getUploadStatus(row.original)}
</Badge>
),
},
{
accessorKey: 'uploaded_at',
header: 'Uploaded At',
cell: ({ row }) => formatUploadedAt(row.original.uploaded_at),
},
{
id: 'actions',
header: () => <span className="sr-only">Actions</span>,
size: 56,
minSize: 56,
enableSorting: false,
enableHiding: false,
meta: { disableTruncate: true },
cell: ({ row }) => (
<div className="flex justify-center">
<UploadActionsMenu
upload={row.original}
onViewVideo={onViewVideo}
onViewDetails={onViewDetails}
/>
</div>
),
},
],
[onViewDetails, onViewVideo],
);
}

View File

@@ -1,79 +0,0 @@
'use client';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
import type { UploadVideo } from '@/types';
import { formatUploadedAt, getUploadStatus } from './uploadUtils';
interface UploadDetailsDialogProps {
upload: UploadVideo | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function UploadDetailsDialog({
upload,
open,
onOpenChange,
}: UploadDetailsDialogProps) {
const title = upload?.filename ?? 'Upload Details';
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader className="min-w-0 pr-8">
<DialogTitle className="min-w-0 max-w-full overflow-hidden text-left">
{upload?.filename ? (
<TooltipProvider delayDuration={200}>
<Tooltip>
<TooltipTrigger asChild>
<span
className="block w-full overflow-hidden text-ellipsis whitespace-nowrap"
title={title}
>
{title}
</span>
</TooltipTrigger>
<TooltipContent className="max-w-80 break-all">
{title}
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
title
)}
</DialogTitle>
<DialogDescription>Uploaded video details</DialogDescription>
</DialogHeader>
{upload ? (
<dl className="grid grid-cols-[120px_1fr] gap-x-4 gap-y-3 text-sm">
<dt className="text-muted-foreground">Status</dt>
<dd>
<Badge className="rounded-full">{getUploadStatus(upload)}</Badge>
</dd>
<dt className="text-muted-foreground">Uploaded At</dt>
<dd>{formatUploadedAt(upload.uploaded_at)}</dd>
<dt className="text-muted-foreground">Uploaded By</dt>
<dd>{upload.uploaded_by_email ?? '-'}</dd>
<dt className="text-muted-foreground">Video ID</dt>
<dd className="break-all font-mono text-xs">{upload.video_id}</dd>
</dl>
) : null}
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,156 @@
'use client';
import { useMemo } from 'react';
import type { ColumnDef } from '@tanstack/react-table';
import { Video } from 'lucide-react';
import { ENV_CONSTANT } from '@/constants/secrect.constant';
import { Badge } from '@/components/ui/badge';
import type { UploadListItem } from '@/types';
import { formatDate } from '@/utils/date';
import { UploadActionsMenu } from './UploadActionsMenu';
import { UploadResultCell } from './UploadResultCell';
import { UploadStatusBadge } from './UploadStatusBadge';
function resolveThumbnailUrl(value: string | null) {
if (!value) return null;
if (/^https?:\/\//i.test(value)) return value;
const baseUrl = ENV_CONSTANT.BASE_API_URL?.replace(/\/$/, '');
const path = value.startsWith('/') ? value : `/${value}`;
return baseUrl ? `${baseUrl}${path}` : path;
}
export function useUploadListColumns(
onViewVideo: (upload: UploadListItem) => void,
): ColumnDef<UploadListItem>[] {
return useMemo(
() => [
{
id: 'thumbnail',
header: 'Thumbnail',
size: 104,
minSize: 96,
enableSorting: false,
meta: { disableTruncate: true },
cell: ({ row }) => {
const thumbnail = resolveThumbnailUrl(row.original.thumbnail);
return (
<div
className="flex aspect-video w-20 items-center justify-center overflow-hidden rounded-md border bg-muted bg-cover bg-center"
style={
thumbnail
? { backgroundImage: `url("${thumbnail}")` }
: undefined
}
role={thumbnail ? 'img' : undefined}
aria-label={thumbnail ? 'Upload thumbnail' : undefined}
>
{!thumbnail ? (
<Video className="size-5 text-muted-foreground" />
) : null}
</div>
);
},
},
{
id: 'uploaded_by',
header: 'Uploader',
size: 190,
cell: ({ row }) => (
<div>
<p className="font-medium">
{row.original.uploaded_by.name ?? '—'}
</p>
<p className="text-xs text-muted-foreground">
{row.original.uploaded_by.email ?? '—'}
</p>
</div>
),
},
{
accessorKey: 'project',
header: 'Project',
size: 165,
cell: ({ row }) => row.original.project ?? '—',
},
{
accessorKey: 'package',
header: 'Package',
size: 110,
cell: ({ row }) => row.original.package ?? '—',
},
{
accessorKey: 'segment',
header: 'Segment',
size: 140,
cell: ({ row }) => row.original.segment ?? '—',
},
{
accessorKey: 'chainage',
header: 'Chainage',
size: 155,
cell: ({ row }) => row.original.chainage ?? '—',
},
{
accessorKey: 'uploaded_at',
header: 'Uploaded At',
size: 175,
cell: ({ row }) => formatDate(row.original.uploaded_at),
},
{
accessorKey: 'is_uploaded',
header: 'Upload Status',
size: 125,
meta: { disableTruncate: true },
cell: ({ row }) =>
row.original.is_uploaded ? (
<Badge className="bg-emerald-500/15 text-emerald-600 dark:text-emerald-400">
Uploaded
</Badge>
) : (
<span className="text-muted-foreground"></span>
),
},
{
id: 'status',
header: 'Analysis Status',
size: 145,
meta: { disableTruncate: true },
cell: ({ row }) => (
<UploadStatusBadge
status={row.original.status}
progress={row.original.progress}
/>
),
},
{
id: 'result',
header: 'Result',
size: 170,
meta: { disableTruncate: true },
cell: ({ row }) => <UploadResultCell item={row.original} />,
},
{
id: 'actions',
header: () => <span className="sr-only">Actions</span>,
size: 64,
minSize: 64,
enableSorting: false,
enableHiding: false,
meta: { disableTruncate: true },
cell: ({ row }) => (
<div className="flex justify-center">
<UploadActionsMenu
upload={row.original}
onViewVideo={onViewVideo}
/>
</div>
),
},
],
[onViewVideo],
);
}

View File

@@ -0,0 +1,46 @@
import { CircleMinus, CircleX, TicketCheck } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type { UploadListItem } from '@/types';
export function UploadResultCell({ item }: { item: UploadListItem }) {
if (item.result === 'ticket_created') {
return (
<div className="space-y-1">
<Badge className="bg-violet-500/15 text-violet-600 dark:text-violet-400">
<TicketCheck /> Ticket Created
</Badge>
<p className="text-xs font-medium">
{item.ticket_name ?? item.ticket_id}
</p>
</div>
);
}
if (item.result === 'analysis_failed') {
return (
<div className="space-y-1 text-red-600 dark:text-red-400">
<div className="flex items-center gap-1.5 text-xs font-medium">
<CircleX className="size-3.5" /> Analysis Failed
</div>
<p className="text-xs text-muted-foreground">
{item.error_message ?? 'Processing failed'}
</p>
</div>
);
}
if (item.result === 'no_defects_found') {
return (
<div className="space-y-1">
<div className="flex items-center gap-1.5 text-xs font-medium text-amber-500">
<CircleMinus className="size-3.5" /> No Defects Found
</div>
<p className="text-xs text-muted-foreground">
{item.total_detections ?? 0} issues detected
</p>
</div>
);
}
return <span className="text-muted-foreground"></span>;
}

View File

@@ -0,0 +1,65 @@
import { CheckCircle2, Clock3, LoaderCircle, XCircle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import type { UploadStatus } from '@/types';
interface UploadStatusBadgeProps {
status: UploadStatus;
progress: number;
}
const statusConfig = {
queued: {
label: 'Queued',
icon: Clock3,
className: 'bg-zinc-500/15 text-zinc-500 dark:text-zinc-300',
},
processing: {
label: 'Processing',
icon: LoaderCircle,
className: 'bg-blue-500/15 text-blue-600 dark:text-blue-400',
},
completed: {
label: 'Completed',
icon: CheckCircle2,
className: 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400',
},
failed: {
label: 'Failed',
icon: XCircle,
className: 'bg-red-500/15 text-red-600 dark:text-red-400',
},
} satisfies Record<
UploadStatus,
{ label: string; icon: typeof Clock3; className: string }
>;
export function UploadStatusBadge({
status,
progress,
}: UploadStatusBadgeProps) {
const config = statusConfig[status];
const Icon = config.icon;
return (
<div className="space-y-1.5">
<Badge variant="secondary" className={config.className}>
<Icon
className={status === 'processing' ? 'animate-spin' : undefined}
/>
{config.label}
</Badge>
{status === 'processing' ? (
<div className="w-24 space-y-1">
<span className="text-xs text-muted-foreground">
{progress}% complete
</span>
<Progress value={progress} className="h-1.5" />
</div>
) : status === 'completed' ? (
<p className="text-xs text-muted-foreground">100%</p>
) : null}
</div>
);
}

View File

@@ -3,18 +3,17 @@
import type { ColumnDef } from '@tanstack/react-table'; import type { ColumnDef } from '@tanstack/react-table';
import { DataTable } from '@/components/data-table'; import { DataTable } from '@/components/data-table';
import type { UploadVideo } from '@/types'; import type { UploadListItem } from '@/types';
interface UploadTableProps { interface UploadTableProps {
columns: ColumnDef<UploadVideo>[]; columns: ColumnDef<UploadListItem>[];
uploads: UploadVideo[]; uploads: UploadListItem[];
isLoading: boolean; isLoading: boolean;
skip: number; skip: number;
limit: number; limit: number;
total: number; total: number;
onPageChange: (skip: number) => void; onPageChange: (skip: number) => void;
onLimitChange: (limit: number) => void; onLimitChange: (limit: number) => void;
onRowClick: (upload: UploadVideo) => void;
} }
export function UploadTable({ export function UploadTable({
@@ -26,7 +25,6 @@ export function UploadTable({
total, total,
onPageChange, onPageChange,
onLimitChange, onLimitChange,
onRowClick,
}: UploadTableProps) { }: UploadTableProps) {
return ( return (
<DataTable <DataTable
@@ -42,7 +40,6 @@ export function UploadTable({
onPageChange, onPageChange,
onLimitChange, onLimitChange,
}} }}
onRowClick={onRowClick}
enableColumnControls={false} enableColumnControls={false}
minColumnSize={120} minColumnSize={120}
/> />

View File

@@ -1,33 +0,0 @@
import { ImageIcon } from 'lucide-react';
import type { UploadVideo } from '@/types';
import { resolveMediaUrl } from './uploadUtils';
interface UploadThumbnailProps {
upload: UploadVideo;
className?: string;
}
export function UploadThumbnail({ upload, className }: UploadThumbnailProps) {
const thumbnailUrl = resolveMediaUrl(upload.thumbnail);
return (
<div className={className}>
<div className="aspect-video overflow-hidden rounded-md border bg-muted/40">
{thumbnailUrl ? (
<img
src={thumbnailUrl}
alt={upload.filename}
loading="lazy"
className="h-full w-full object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-muted-foreground">
<ImageIcon className="size-8" />
</div>
)}
</div>
</div>
);
}

View File

@@ -8,10 +8,10 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import type { UploadVideo } from '@/types'; import type { UploadListItem } from '@/types';
interface UploadVideoDialogProps { interface UploadVideoDialogProps {
upload: UploadVideo | null; upload: UploadListItem | null;
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
} }
@@ -29,12 +29,12 @@ export function UploadVideoDialog({
Video Preview Video Preview
</DialogTitle> </DialogTitle>
<DialogDescription className="truncate text-xs"> <DialogDescription className="truncate text-xs">
{upload?.filename ?? 'Uploaded video'} {upload?.video_name ?? 'Uploaded video'}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<ProtectedVideoPlayer <ProtectedVideoPlayer
url={open ? upload?.video_url : undefined} url={open ? upload?.raw_video_url : undefined}
className="rounded-lg" className="rounded-lg"
unavailableTitle="Video preview unavailable" unavailableTitle="Video preview unavailable"
/> />

View File

@@ -1,46 +0,0 @@
'use client';
import { Grid2X2, Table2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import type { UploadViewMode } from '../hooks/useUploadFilters';
interface ViewSwitcherProps {
value: UploadViewMode;
onValueChange: (value: UploadViewMode) => void;
}
export function ViewSwitcher({ value, onValueChange }: ViewSwitcherProps) {
const items: Array<{
value: UploadViewMode;
label: string;
icon: React.ReactNode;
}> = [
{ value: 'card', label: 'Card View', icon: <Grid2X2 className="size-4" /> },
{ value: 'table', label: 'Table View', icon: <Table2 className="size-4" /> },
];
return (
<div className="inline-flex rounded-md border bg-card p-1">
{items.map((item) => (
<Button
key={item.value}
type="button"
variant="ghost"
size="sm"
onClick={() => onValueChange(item.value)}
className={cn(
'gap-2',
value === item.value && 'bg-secondary text-foreground',
)}
>
{item.icon}
{item.label}
</Button>
))}
</div>
);
}

View File

@@ -1,29 +0,0 @@
import { ENV_CONSTANT } from '@/constants/secrect.constant';
import type { UploadVideo } from '@/types';
export function getUploadStatus(upload: UploadVideo) {
return upload.status?.status || 'unknown';
}
export function formatUploadedAt(value: string) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '-';
return new Intl.DateTimeFormat('en-IN', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
}).format(date);
}
export function resolveMediaUrl(url?: string | null) {
if (!url) return null;
if (/^https?:\/\//i.test(url)) return url;
const baseUrl = ENV_CONSTANT.BASE_API_URL?.replace(/\/$/, '');
const path = url.startsWith('/') ? url : `/${url}`;
return baseUrl ? `${baseUrl}${path}` : path;
}

View File

@@ -2,14 +2,11 @@
import { useState } from 'react'; import { useState } from 'react';
export type UploadViewMode = 'card' | 'table';
const DEFAULT_LIMIT = 20; const DEFAULT_LIMIT = 20;
export function useUploadFilters() { export function useUploadFilters() {
const [skip, setSkip] = useState(0); const [skip, setSkip] = useState(0);
const [limit, setLimitValue] = useState(DEFAULT_LIMIT); const [limit, setLimitValue] = useState(DEFAULT_LIMIT);
const [viewMode, setViewMode] = useState<UploadViewMode>('card');
const setLimit = (nextLimit: number) => { const setLimit = (nextLimit: number) => {
setLimitValue(nextLimit); setLimitValue(nextLimit);
@@ -21,7 +18,5 @@ export function useUploadFilters() {
setSkip, setSkip,
limit, limit,
setLimit, setLimit,
viewMode,
setViewMode,
}; };
} }

View File

@@ -0,0 +1,112 @@
'use client';
import { useCallback, useMemo, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { API_ROUTES } from '@/constants/apiRoutes';
import { useSseWithToken } from '@/hooks/sse/useSseWithToken';
import { videoService } from '@/services/api';
import type {
PaginationParams,
UploadListResponse,
UploadStatusEvent,
} from '@/types';
import { uploadKeys } from './useUploadQueries';
function getUploadListParams(queryKey: readonly unknown[]) {
const params = queryKey[2];
if (!params || typeof params !== 'object' || Array.isArray(params)) {
return undefined;
}
return params as PaginationParams;
}
function patchUploadList(
current: UploadListResponse | undefined,
event: UploadStatusEvent,
params?: PaginationParams,
) {
if (!current) return current;
const existingIndex = current.items.findIndex(
(upload) => upload.id === event.item.id,
);
if (existingIndex >= 0) {
return {
...current,
items: current.items.map((upload) =>
upload.id === event.item.id ? event.item : upload,
),
};
}
if (event.kind !== 'created') return current;
const nextTotal = current.total + 1;
if ((params?.skip ?? 0) !== 0) {
return { ...current, total: nextTotal };
}
const pageLimit = params?.limit ?? current.items.length + 1;
return {
items: [event.item, ...current.items].slice(0, pageLimit),
total: nextTotal,
};
}
export function useUploadListEvents(enabled = true) {
const queryClient = useQueryClient();
const hasInvalidatedAfterConnectionErrorRef = useRef(false);
const events = useMemo(
() => ({
upload_status: (event: UploadStatusEvent) => {
queryClient
.getQueryCache()
.findAll({ queryKey: uploadKeys.lists() })
.forEach((query) => {
queryClient.setQueryData<UploadListResponse>(
query.queryKey,
(current) =>
patchUploadList(
current,
event,
getUploadListParams(query.queryKey),
),
);
});
},
heartbeat: () => undefined,
}),
[queryClient],
);
const getPath = useCallback(
(token: string) => API_ROUTES.VIDEOS.UPLOAD_EVENTS(token),
[],
);
const onConnectionError = useCallback(() => {
if (hasInvalidatedAfterConnectionErrorRef.current) return;
hasInvalidatedAfterConnectionErrorRef.current = true;
queryClient.invalidateQueries({ queryKey: uploadKeys.lists() });
}, [queryClient]);
const onConnectionOpen = useCallback(() => {
hasInvalidatedAfterConnectionErrorRef.current = false;
}, []);
useSseWithToken({
enabled,
getToken: videoService.createUploadEventsToken,
getPath,
events,
onConnectionError,
onConnectionOpen,
});
}

View File

@@ -13,7 +13,7 @@ export const uploadKeys = {
list: (params: PaginationParams) => [...uploadKeys.lists(), params] as const, list: (params: PaginationParams) => [...uploadKeys.lists(), params] as const,
}; };
interface UseMyUploadsQueryParams { interface UseUploadsQueryParams {
skip: number; skip: number;
limit: number; limit: number;
} }
@@ -21,14 +21,14 @@ interface UseMyUploadsQueryParams {
function buildUploadListParams({ function buildUploadListParams({
skip, skip,
limit, limit,
}: UseMyUploadsQueryParams): PaginationParams { }: UseUploadsQueryParams): PaginationParams {
return { return {
skip, skip,
limit, limit,
}; };
} }
export function useMyUploadsQuery(params: UseMyUploadsQueryParams) { export function useUploadsQuery(params: UseUploadsQueryParams) {
const { skip, limit } = params; const { skip, limit } = params;
const listParams = useMemo( const listParams = useMemo(
() => buildUploadListParams({ skip, limit }), () => buildUploadListParams({ skip, limit }),
@@ -37,7 +37,7 @@ export function useMyUploadsQuery(params: UseMyUploadsQueryParams) {
return useQuery({ return useQuery({
queryKey: uploadKeys.list(listParams), queryKey: uploadKeys.list(listParams),
queryFn: () => videoService.getMyUploads(listParams), queryFn: () => videoService.getUploads(listParams),
}); });
} }

View File

@@ -1,62 +1,39 @@
'use client'; 'use client';
import { useCallback, useState } from 'react'; import { useState } from 'react';
import { Plus, UploadCloud } from 'lucide-react'; import { Plus, UploadCloud } from 'lucide-react';
import { PageHeader } from '@/components/page-header'; import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import type { UploadVideo } from '@/types'; import type { UploadListItem } from '@/types';
import { CreateUploadDialog } from './components/CreateUploadDialog'; import { CreateUploadDialog } from './components/CreateUploadDialog';
import { UploadCardGrid } from './components/UploadCardGrid'; import { useUploadListColumns } from './components/UploadListColumns';
import { useUploadColumns } from './components/UploadColumns';
import { UploadDetailsDialog } from './components/UploadDetailsDialog';
import { UploadTable } from './components/UploadTable'; import { UploadTable } from './components/UploadTable';
import { UploadVideoDialog } from './components/UploadVideoDialog'; import { UploadVideoDialog } from './components/UploadVideoDialog';
import { ViewSwitcher } from './components/ViewSwitcher';
import { useUploadFilters } from './hooks/useUploadFilters'; import { useUploadFilters } from './hooks/useUploadFilters';
import { useMyUploadsQuery } from './hooks/useUploadQueries'; import { useUploadListEvents } from './hooks/useUploadListEvents';
import { useUploadsQuery } from './hooks/useUploadQueries';
export default function UploadPage() { export default function UploadPage() {
const { skip, setSkip, limit, setLimit, viewMode, setViewMode } = const { skip, setSkip, limit, setLimit } = useUploadFilters();
useUploadFilters(); const uploadsQuery = useUploadsQuery({ skip, limit });
const uploadsQuery = useMyUploadsQuery({ skip, limit }); useUploadListEvents();
const [isCreateOpen, setIsCreateOpen] = useState(false); const [isCreateOpen, setIsCreateOpen] = useState(false);
const [detailsUpload, setDetailsUpload] = useState<UploadVideo | null>(null); const [videoUpload, setVideoUpload] = useState<UploadListItem | null>(null);
const [videoUpload, setVideoUpload] = useState<UploadVideo | null>(null);
const uploads = uploadsQuery.data?.items ?? []; const uploads = uploadsQuery.data?.items ?? [];
const total = uploadsQuery.data?.total ?? 0; const total = uploadsQuery.data?.total ?? 0;
const isLoading = uploadsQuery.isLoading; const isLoading = uploadsQuery.isLoading;
const handleViewDetails = useCallback((upload: UploadVideo) => { const columns = useUploadListColumns(setVideoUpload);
setDetailsUpload(upload);
}, []);
const handleViewUploadVideo = useCallback((upload: UploadVideo) => {
setVideoUpload(upload);
}, []);
const handleOpenUpload = useCallback(
(upload: UploadVideo) => {
if (upload.video_url) {
handleViewUploadVideo(upload);
}
},
[handleViewUploadVideo],
);
const columns = useUploadColumns({
onViewVideo: handleViewUploadVideo,
onViewDetails: handleViewDetails,
});
return ( return (
<> <>
<main className="space-y-5"> <main className="space-y-5">
<PageHeader <PageHeader
title="My Uploads" title="Uploads"
description="View and manage uploaded road inspection videos." description="Track uploaded road inspection videos, processing progress, and results."
icon={UploadCloud} icon={UploadCloud}
actions={ actions={
<Button onClick={() => setIsCreateOpen(true)} size="sm"> <Button onClick={() => setIsCreateOpen(true)} size="sm">
@@ -66,25 +43,6 @@ export default function UploadPage() {
} }
/> />
<div className="flex justify-end">
<ViewSwitcher value={viewMode} onValueChange={setViewMode} />
</div>
{viewMode === 'card' ? (
<UploadCardGrid
uploads={uploads}
isLoading={isLoading}
skip={skip}
limit={limit}
total={total}
onPageChange={setSkip}
onLimitChange={setLimit}
onUploadNew={() => setIsCreateOpen(true)}
onOpenUpload={handleOpenUpload}
onViewVideo={handleViewUploadVideo}
onViewDetails={handleViewDetails}
/>
) : (
<UploadTable <UploadTable
columns={columns} columns={columns}
uploads={uploads} uploads={uploads}
@@ -94,19 +52,10 @@ export default function UploadPage() {
total={total} total={total}
onPageChange={setSkip} onPageChange={setSkip}
onLimitChange={setLimit} onLimitChange={setLimit}
onRowClick={handleOpenUpload}
/> />
)}
</main> </main>
<CreateUploadDialog open={isCreateOpen} onOpenChange={setIsCreateOpen} /> <CreateUploadDialog open={isCreateOpen} onOpenChange={setIsCreateOpen} />
<UploadDetailsDialog
upload={detailsUpload}
open={Boolean(detailsUpload)}
onOpenChange={(open) => {
if (!open) setDetailsUpload(null);
}}
/>
<UploadVideoDialog <UploadVideoDialog
upload={videoUpload} upload={videoUpload}
open={Boolean(videoUpload)} open={Boolean(videoUpload)}

View File

@@ -122,6 +122,16 @@
} }
@layer base { @layer base {
html:has(body[data-scroll-locked]) {
scrollbar-gutter: auto;
}
@supports not (scrollbar-gutter: stable) {
.scroll-stable {
overflow-y: scroll;
}
}
* { * {
@apply border-border outline-none; @apply border-border outline-none;
} }
@@ -129,4 +139,17 @@
body { body {
@apply bg-background text-foreground; @apply bg-background text-foreground;
} }
.scroll-stable {
scrollbar-gutter: stable;
}
}
.detection-video-player .vds-slider-preview {
display: none;
}
.detection-video-player
.vds-slider-preview:has(.vds-slider-thumbnail img[src^='blob:']) {
display: flex;
} }

View File

@@ -1,5 +1,11 @@
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import { Geist_Mono, Poppins } from 'next/font/google'; import { Geist_Mono, Poppins } from 'next/font/google';
import '@vidstack/react/player/styles/default/theme.css';
import '@vidstack/react/player/styles/default/layouts/video.css';
import 'leaflet/dist/leaflet.css';
import 'lightgallery/css/lightgallery.css';
import 'lightgallery/css/lg-thumbnail.css';
import 'lightgallery/css/lg-zoom.css';
import './globals.css'; import './globals.css';
import { ThemeProvider } from '@/providers/ThemeProvider'; import { ThemeProvider } from '@/providers/ThemeProvider';
import AppInitializer from '@/providers/AppInitializer'; import AppInitializer from '@/providers/AppInitializer';

View File

@@ -0,0 +1,66 @@
import { getDefectVisual } from '@/constants/defectVisualConfig';
import type { DetectionResultItem } from '@/types';
interface BoundingBoxOverlayProps {
detections: DetectionResultItem[];
videoWidth: number;
videoHeight: number;
}
export default function BoundingBoxOverlay({
detections,
videoWidth,
videoHeight,
}: BoundingBoxOverlayProps) {
if (videoWidth <= 0 || videoHeight <= 0 || detections.length === 0) {
return null;
}
return (
<svg
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[2] size-full"
viewBox={`0 0 ${videoWidth} ${videoHeight}`}
preserveAspectRatio="xMidYMid meet"
>
{detections.map(({ id, detection }) => {
const { bounding_box: box } = detection;
const color = getDefectVisual(detection.class_name).boundingBoxColor;
const label = `${detection.display_name} ${(detection.confidence * 100).toFixed(0)}%`;
const labelY = Math.max(box.y1 - 34, 0);
const labelWidth = Math.max(150, label.length * 17);
return (
<g key={id}>
<rect
x={box.x1}
y={box.y1}
width={box.x2 - box.x1}
height={box.y2 - box.y1}
fill="none"
stroke={color}
strokeWidth="4"
vectorEffect="non-scaling-stroke"
/>
<rect
x={box.x1}
y={labelY}
width={labelWidth}
height="34"
fill={color}
/>
<text
x={box.x1 + 8}
y={labelY + 23}
fill="white"
fontSize="20"
fontWeight="600"
>
{label}
</text>
</g>
);
})}
</svg>
);
}

View File

@@ -33,6 +33,11 @@ import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { useAppStore } from '@/store/app.store'; import { useAppStore } from '@/store/app.store';
function isRouteActive(pathname: string, path?: string) {
if (!path) return false;
return pathname === path || pathname.startsWith(`${path}/`);
}
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) { export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const pathname = usePathname(); const pathname = usePathname();
const { hasPermission } = usePermissions(); const { hasPermission } = usePermissions();
@@ -85,16 +90,23 @@ function SidebarNavItem({
item: MenuItem; item: MenuItem;
pathname: string; pathname: string;
}) { }) {
const isActive = item.path ? pathname === item.path : false; const isActive = isRouteActive(pathname, item.path);
const isChildActive = const isChildActive =
item.children?.some((child) => child.path === pathname) ?? false; item.children?.some((child) => isRouteActive(pathname, child.path)) ??
false;
const hasChildren = Boolean(item.children?.length); const hasChildren = Boolean(item.children?.length);
const [open, setOpen] = React.useState(isChildActive);
React.useEffect(() => {
if (isChildActive) setOpen(true);
}, [isChildActive]);
if (hasChildren) { if (hasChildren) {
return ( return (
<Collapsible <Collapsible
asChild asChild
defaultOpen={isChildActive} open={open}
onOpenChange={setOpen}
className="group/collapsible" className="group/collapsible"
> >
<SidebarMenuItem> <SidebarMenuItem>
@@ -112,7 +124,7 @@ function SidebarNavItem({
{child.path ? ( {child.path ? (
<SidebarMenuSubButton <SidebarMenuSubButton
asChild asChild
isActive={pathname === child.path} isActive={isRouteActive(pathname, child.path)}
> >
<Link href={child.path}> <Link href={child.path}>
<child.icon /> <child.icon />

View File

@@ -14,11 +14,9 @@ import {
ComboboxTrigger, ComboboxTrigger,
ComboboxValue, ComboboxValue,
} from '@/components/ui/combobox'; } from '@/components/ui/combobox';
import { cn } from '@/lib/utils';
import type { import type { AsyncSelectOption, AsyncSelectProps } from './AsyncSelect.types';
AsyncSelectOption,
AsyncSelectProps,
} from './AsyncSelect.types';
import { VirtualSelectList } from './VirtualSelectList'; import { VirtualSelectList } from './VirtualSelectList';
type VirtualizerHandle = Virtualizer<HTMLDivElement, Element>; type VirtualizerHandle = Virtualizer<HTMLDivElement, Element>;
@@ -30,6 +28,8 @@ export function AsyncSelect({
searchPlaceholder = 'Search...', searchPlaceholder = 'Search...',
emptyMessage = 'No items found.', emptyMessage = 'No items found.',
disabled = false, disabled = false,
triggerClassName,
renderSelectedOption,
portalContainer, portalContainer,
}: AsyncSelectProps) { }: AsyncSelectProps) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@@ -125,7 +125,10 @@ export function AsyncSelect({
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
className="w-full justify-between font-normal" className={cn(
'w-full justify-between font-normal',
triggerClassName,
)}
disabled={isDisabled} disabled={isDisabled}
> >
{isLoading && !selectedOption ? ( {isLoading && !selectedOption ? (
@@ -133,15 +136,21 @@ export function AsyncSelect({
<Loader2 className="size-4 animate-spin" /> <Loader2 className="size-4 animate-spin" />
Loading... Loading...
</span> </span>
) : (
<>
{selectedOption && renderSelectedOption ? (
renderSelectedOption(selectedOption)
) : ( ) : (
<ComboboxValue placeholder={triggerPlaceholder} /> <ComboboxValue placeholder={triggerPlaceholder} />
)} )}
</>
)}
</Button> </Button>
} }
/> />
<ComboboxContent <ComboboxContent
container={portalContainer} container={portalContainer}
className="min-w-[var(--anchor-width)]" className="min-w-(--anchor-width)"
> >
<div className="border-b p-2"> <div className="border-b p-2">
<ComboboxInput <ComboboxInput

View File

@@ -1,8 +1,9 @@
import type { RefObject } from 'react'; import type { ReactNode, RefObject } from 'react';
export type AsyncSelectOption = { export type AsyncSelectOption = {
value: string; value: string;
label: string; label: string;
data?: unknown;
}; };
export type PaginatedResult<T> = { export type PaginatedResult<T> = {
@@ -47,5 +48,7 @@ export interface AsyncSelectProps {
searchPlaceholder?: string; searchPlaceholder?: string;
emptyMessage?: string; emptyMessage?: string;
disabled?: boolean; disabled?: boolean;
triggerClassName?: string;
renderSelectedOption?: (option: AsyncSelectOption) => ReactNode;
portalContainer?: RefObject<HTMLDivElement | null>; portalContainer?: RefObject<HTMLDivElement | null>;
} }

View File

@@ -0,0 +1,171 @@
'use client';
import * as React from 'react';
import { CalendarDays, ChevronDownIcon, Globe2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
const DEFAULT_TIME_ZONES = [
'UTC',
'Asia/Kolkata',
'Asia/Dubai',
'Asia/Singapore',
'Asia/Tokyo',
'Europe/London',
'America/New_York',
'America/Los_Angeles',
'Australia/Sydney',
] as const;
export interface DatePickerProps {
value?: Date;
defaultValue?: Date;
onChange?: (date: Date | undefined) => void;
timeZone?: string;
defaultTimeZone?: string;
onTimeZoneChange?: (timeZone: string) => void;
timeZones?: readonly string[];
showTimeZone?: boolean;
placeholder?: string;
disabled?: boolean;
className?: string;
}
function getBrowserTimeZone() {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
}
function formatDate(date: Date, timeZone: string) {
return new Intl.DateTimeFormat(undefined, {
dateStyle: 'long',
timeZone,
}).format(date);
}
function getTimeZoneLabel(timeZone: string) {
return timeZone.replaceAll('_', ' ');
}
export function DatePicker(props: DatePickerProps) {
const {
value,
defaultValue,
onChange,
timeZone,
defaultTimeZone,
onTimeZoneChange,
timeZones = DEFAULT_TIME_ZONES,
showTimeZone = true,
placeholder = 'Pick a date',
disabled = false,
className,
} = props;
const isDateControlled = Object.hasOwn(props, 'value');
const isTimeZoneControlled = Object.hasOwn(props, 'timeZone');
const [internalDate, setInternalDate] = React.useState(defaultValue);
const [internalTimeZone, setInternalTimeZone] = React.useState(
defaultTimeZone ?? 'UTC',
);
React.useEffect(() => {
if (!isTimeZoneControlled && !defaultTimeZone) {
setInternalTimeZone(getBrowserTimeZone());
}
}, [defaultTimeZone, isTimeZoneControlled]);
const selectedDate = isDateControlled ? value : internalDate;
const selectedTimeZone = timeZone ?? internalTimeZone;
const availableTimeZones = React.useMemo(
() => Array.from(new Set([selectedTimeZone, ...timeZones])).filter(Boolean),
[selectedTimeZone, timeZones],
);
const handleDateChange = (nextDate: Date | undefined) => {
if (!isDateControlled) setInternalDate(nextDate);
onChange?.(nextDate);
};
const handleTimeZoneChange = (nextTimeZone: string | null) => {
if (!nextTimeZone) return;
if (!isTimeZoneControlled) setInternalTimeZone(nextTimeZone);
onTimeZoneChange?.(nextTimeZone);
};
return (
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
data-empty={!selectedDate}
className={cn(
'w-64 justify-between text-left font-normal data-[empty=true]:text-muted-foreground',
className,
)}
>
<span className="flex min-w-0 items-center gap-2">
<CalendarDays className="size-4 shrink-0" />
<span className="truncate">
{selectedDate
? formatDate(selectedDate, selectedTimeZone)
: placeholder}
</span>
</span>
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={selectedDate}
onSelect={handleDateChange}
defaultMonth={selectedDate}
timeZone={selectedTimeZone}
/>
{showTimeZone ? (
<div className="flex items-center gap-2 border-t p-3">
<Globe2 className="size-4 shrink-0 text-muted-foreground" />
<Select
value={selectedTimeZone}
onValueChange={handleTimeZoneChange}
>
<SelectTrigger
size="sm"
className="min-w-0 flex-1"
aria-label="Time zone"
>
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
{availableTimeZones.map((zone) => (
<SelectItem key={zone} value={zone}>
{getTimeZoneLabel(zone)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : null}
</PopoverContent>
</Popover>
);
}
export { DEFAULT_TIME_ZONES };

View File

@@ -1,5 +1,7 @@
'use client'; 'use client';
import { UserRound } from 'lucide-react';
import { AsyncSelect, usePaginatedSelect } from '@/components/async-select'; import { AsyncSelect, usePaginatedSelect } from '@/components/async-select';
import type { AsyncSelectOption } from '@/components/async-select'; import type { AsyncSelectOption } from '@/components/async-select';
import { ticketKeys } from '@/app/(modules)/ticket/queries/ticketKeys'; import { ticketKeys } from '@/app/(modules)/ticket/queries/ticketKeys';
@@ -14,6 +16,7 @@ function mapWorkerOption(user: AssignableTicketUser): AsyncSelectOption {
return { return {
value: String(user.id), value: String(user.id),
label: user.name || user.email || user.username, label: user.name || user.email || user.username,
data: user,
}; };
} }
@@ -58,14 +61,40 @@ export function AssignableWorkerSelect({
[...ticketKeys.assignableUsers(), 'selected', workerId] as const, [...ticketKeys.assignableUsers(), 'selected', workerId] as const,
}); });
const handleValueChange = (workerId: string) => {
const option = lookup.options.find((item) => item.value === workerId);
const user = option?.data as AssignableTicketUser | undefined;
if (user) onValueChange(workerId, user);
};
const selectedUser = lookup.selectedOption?.data as
| AssignableTicketUser
| undefined;
return ( return (
<AsyncSelect <AsyncSelect
lookup={lookup} lookup={lookup}
onValueChange={onValueChange} onValueChange={handleValueChange}
disabled={disabled} disabled={disabled}
placeholder="Select contractor" placeholder="Select contractor"
searchPlaceholder="Search contractors" searchPlaceholder="Search contractors"
emptyMessage="No assignable contractors found." emptyMessage="No assignable contractors found."
triggerClassName="h-auto min-h-14 py-2"
renderSelectedOption={(option) => (
<span className="flex min-w-0 items-center gap-2.5">
<span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
<UserRound className="size-5" aria-hidden />
</span>
<span className="min-w-0 text-left">
<span className="block truncate font-medium text-foreground">
{option.label}
</span>
<span className="block truncate text-xs text-muted-foreground">
{selectedUser?.role.name}
</span>
</span>
</span>
)}
/> />
); );
} }

View File

@@ -1,5 +1,7 @@
import type { AssignableTicketUser } from '@/types';
export interface AssignableWorkerSelectProps { export interface AssignableWorkerSelectProps {
value: string; value: string;
onValueChange: (value: string) => void; onValueChange: (value: string, user: AssignableTicketUser) => void;
disabled?: boolean; disabled?: boolean;
} }

View File

@@ -0,0 +1,142 @@
'use client';
import dynamic from 'next/dynamic';
import { MapPin } from 'lucide-react';
import { cn } from '@/lib/utils';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
type DetectionLocationMapProps = {
latitude: number | null;
longitude: number | null;
label: string;
title?: string;
description?: string;
aspectRatio?: string;
showCoordinates?: boolean;
variant?: 'card' | 'plain';
className?: string;
};
type ClientDetectionLocationMapProps = {
latitude: number;
longitude: number;
label: string;
};
const ClientDetectionLocationMap = dynamic<ClientDetectionLocationMapProps>(
async () => {
const { CircleMarker, MapContainer, Popup, TileLayer } =
await import('react-leaflet');
return function ClientDetectionLocationMapInner({
latitude,
longitude,
label,
}: ClientDetectionLocationMapProps) {
return (
<MapContainer
key={`${latitude}:${longitude}`}
center={[latitude, longitude]}
zoom={17}
scrollWheelZoom={false}
className="h-full w-full"
>
<TileLayer
attribution="&copy; OpenStreetMap contributors"
url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<CircleMarker
center={[latitude, longitude]}
radius={10}
pathOptions={{
color: '#dc2626',
fillColor: '#dc2626',
fillOpacity: 0.75,
weight: 2,
}}
>
<Popup>{label}</Popup>
</CircleMarker>
</MapContainer>
);
};
},
{
ssr: false,
loading: () => <div className="h-full w-full animate-pulse bg-muted" />,
},
);
export default function DetectionLocationMap({
latitude,
longitude,
label,
title = 'Detection Location',
description = 'Selected log GPS coordinates',
aspectRatio = '16 / 9',
showCoordinates = true,
variant = 'card',
className,
}: DetectionLocationMapProps) {
const mapContent =
latitude == null || longitude == null ? (
<div
className="flex items-center justify-center rounded-lg border border-dashed bg-muted/30 px-4 py-8 text-sm text-muted-foreground"
style={{ aspectRatio }}
>
Coordinates are unavailable for the selected log.
</div>
) : (
<>
{showCoordinates ? (
<div className="text-sm text-muted-foreground">
{latitude.toFixed(6)}, {longitude.toFixed(6)}
</div>
) : null}
<div
className="overflow-hidden rounded-lg border bg-muted"
style={{ aspectRatio }}
>
<ClientDetectionLocationMap
latitude={latitude}
longitude={longitude}
label={label}
/>
</div>
</>
);
if (variant === 'plain') {
return (
<div className={cn('space-y-2', className)}>
{title ? (
<p className="text-xs font-medium text-muted-foreground">{title}</p>
) : null}
{mapContent}
</div>
);
}
return (
<Card className={cn('overflow-hidden', className)}>
<CardHeader className="border-b pb-4">
<div className="flex items-center gap-3">
<div className="rounded bg-secondary p-2">
<MapPin className="h-5 w-5 text-primary" />
</div>
<div>
<CardTitle className="text-base font-semibold">{title}</CardTitle>
<CardDescription className="text-xs">{description}</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4 pt-6">{mapContent}</CardContent>
</Card>
);
}

View File

@@ -24,7 +24,8 @@ export function ProtectedVideoPlayer({
unavailableTitle = 'Video unavailable', unavailableTitle = 'Video unavailable',
className, className,
}: ProtectedVideoPlayerProps) { }: ProtectedVideoPlayerProps) {
const { objectUrl, isLoading, isError } = useProtectedMediaObjectUrl(url); const { objectUrl, mediaType, isLoading, isError } =
useProtectedMediaObjectUrl(url);
if (!url) { if (!url) {
return ( return (
@@ -73,11 +74,14 @@ export function ProtectedVideoPlayer({
)} )}
> >
<video <video
src={objectUrl} key={objectUrl}
className="aspect-video w-full object-cover" className="aspect-video w-full bg-black object-contain"
controls controls
playsInline playsInline
/> preload="metadata"
>
<source src={objectUrl} type={mediaType ?? 'video/mp4'} />
</video>
{label ? ( {label ? (
<span className="absolute top-3 left-3 rounded bg-black/65 px-2.5 py-1 text-[11px] font-semibold text-white backdrop-blur-sm"> <span className="absolute top-3 left-3 rounded bg-black/65 px-2.5 py-1 text-[11px] font-semibold text-white backdrop-blur-sm">
@@ -86,7 +90,7 @@ export function ProtectedVideoPlayer({
) : null} ) : null}
{meta ? ( {meta ? (
<span className="pointer-events-none absolute top-3 right-3 max-w-[55%] truncate text-xs font-medium"> <span className="pointer-events-none absolute top-3 right-3 max-w-[55%] truncate text-xs font-medium text-white/90">
{meta} {meta}
</span> </span>
) : null} ) : null}

View File

@@ -0,0 +1,72 @@
'use client';
import { UserRound } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { cn } from '@/lib/utils';
import type { TicketActor } from '@/types';
import { getPersonLabel } from '@/utils/person';
type PersonAvatarProps = {
person: TicketActor | null | undefined;
size?: 'default' | 'sm' | 'lg';
className?: string;
};
export function PersonAvatar({
person,
size = 'default',
className,
}: PersonAvatarProps) {
const avatarUrl = person?.avatar_url?.trim();
return (
<Avatar size={size} className={className}>
{avatarUrl ? (
<AvatarImage src={avatarUrl} alt={getPersonLabel(person)} />
) : null}
<AvatarFallback className="bg-muted text-muted-foreground">
<UserRound
className={cn(
'shrink-0',
size === 'sm' ? 'size-3.5' : size === 'lg' ? 'size-5' : 'size-4',
)}
aria-hidden
/>
</AvatarFallback>
</Avatar>
);
}
type PersonInfoProps = {
person: TicketActor | null | undefined;
size?: 'default' | 'sm' | 'lg';
className?: string;
};
export function PersonInfo({
person,
size = 'sm',
className,
}: PersonInfoProps) {
if (!person) {
return <p className="text-sm text-muted-foreground">-</p>;
}
const name = person.name?.trim();
const email = person.email?.trim();
return (
<div className={cn('flex min-w-0 items-center gap-2.5', className)}>
<PersonAvatar person={person} size={size} />
<div className="min-w-0">
<p className="truncate text-sm text-foreground">
{name || email || 'Unknown'}
</p>
{name && email ? (
<p className="truncate text-xs text-muted-foreground">{email}</p>
) : null}
</div>
</div>
);
}

View File

@@ -1,54 +1,54 @@
import * as React from 'react'; import * as React from "react"
import { cva, type VariantProps } from 'class-variance-authority'; import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from 'radix-ui'; import { Slot } from "radix-ui"
import { cn } from '@/lib/utils'; import { cn } from "@/lib/utils"
const buttonVariants = cva( const buttonVariants = cva(
"inline-flex cursor-pointer shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50 aria-invalid:border-destructive [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{ {
variants: { variants: {
variant: { variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90', default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: destructive:
'bg-destructive text-white hover:bg-destructive/90 dark:bg-destructive/60', "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
outline: outline:
'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground focus-visible:border-ring dark:border-input dark:bg-input/30 dark:hover:bg-input/50', "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary: secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80', "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: ghost:
'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50', "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: 'text-primary underline-offset-4 hover:underline', link: "text-primary underline-offset-4 hover:underline",
}, },
size: { size: {
default: 'h-9 px-4 py-2 has-[>svg]:px-3', default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: 'h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5', sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
lg: 'h-10 rounded-md px-6 has-[>svg]:px-4', lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: 'size-9', icon: "size-9",
'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
'icon-sm': 'size-8', "icon-sm": "size-8",
'icon-lg': 'size-10', "icon-lg": "size-10",
}, },
}, },
defaultVariants: { defaultVariants: {
variant: 'default', variant: "default",
size: 'default', size: "default",
}, },
}, }
); )
function Button({ function Button({
className, className,
variant = 'default', variant = "default",
size = 'default', size = "default",
asChild = false, asChild = false,
...props ...props
}: React.ComponentProps<'button'> & }: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & { VariantProps<typeof buttonVariants> & {
asChild?: boolean; asChild?: boolean
}) { }) {
const Comp = asChild ? Slot.Root : 'button'; const Comp = asChild ? Slot.Root : "button"
return ( return (
<Comp <Comp
@@ -58,7 +58,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))} className={cn(buttonVariants({ variant, size, className }))}
{...props} {...props}
/> />
); )
} }
export { Button, buttonVariants }; export { Button, buttonVariants }

View File

@@ -0,0 +1,220 @@
"use client"
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import {
DayPicker,
getDefaultClassNames,
type DayButton,
} from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months
),
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
nav: cn(
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_next
),
month_caption: cn(
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute inset-0 bg-popover opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"font-medium select-none",
captionLayout === "label"
? "text-sm"
: "flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
defaultClassNames.caption_label
),
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none",
defaultClassNames.weekday
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-(--cell-size) select-none",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] text-muted-foreground select-none",
defaultClassNames.week_number
),
day: cn(
"group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-md",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
defaultClassNames.day
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

View File

@@ -0,0 +1,135 @@
"use client"
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
function Drawer({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
}
function DrawerTrigger({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
}
function DrawerPortal({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
}
function DrawerClose({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
}
function DrawerOverlay({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
return (
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function DrawerContent({
className,
children,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
"group/drawer-content fixed z-50 flex h-auto flex-col bg-background",
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
className
)}
{...props}
>
<div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
)
}
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-header"
className={cn(
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
className
)}
{...props}
/>
)
}
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function DrawerTitle({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn("font-semibold text-foreground", className)}
{...props}
/>
)
}
function DrawerDescription({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}

View File

@@ -0,0 +1,115 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
function Timeline({ className, ...props }: React.ComponentProps<'ol'>) {
return (
<ol
data-slot="timeline"
className={cn('flex w-full flex-col', className)}
{...props}
/>
);
}
function TimelineItem({
className,
marker,
opposite,
layout = 'alternate',
side = 'right',
isLast = false,
children,
...props
}: Omit<React.ComponentProps<'li'>, 'children'> & {
marker: React.ReactNode;
opposite: React.ReactNode;
layout?: 'left' | 'alternate';
side?: 'left' | 'right';
isLast?: boolean;
children: React.ReactNode;
}) {
if (layout === 'left') {
return (
<li
data-slot="timeline-item"
className={cn(
'grid grid-cols-[minmax(5.5rem,auto)_1rem_minmax(0,1fr)] items-start gap-x-4',
className,
)}
{...props}
>
<div
data-slot="timeline-opposite"
className="pt-0.5 text-right tabular-nums"
>
{opposite}
</div>
<div className="relative flex justify-center self-stretch">
{!isLast ? (
<span
aria-hidden
className="absolute top-4 bottom-0 w-px bg-border"
/>
) : null}
<div data-slot="timeline-marker" className="relative z-10">
{marker}
</div>
</div>
<div
data-slot="timeline-content"
className={cn('min-w-0 pb-8', isLast && 'pb-0')}
>
{children}
</div>
</li>
);
}
return (
<li
data-slot="timeline-item"
className={cn(
'grid grid-cols-[2.5rem_minmax(0,1fr)] grid-rows-[auto_auto] gap-x-3 md:grid-cols-[minmax(0,1fr)_2.5rem_minmax(0,1fr)] md:grid-rows-1 md:gap-x-4',
className,
)}
{...props}
>
<div
data-slot="timeline-opposite"
className={cn(
'col-start-2 row-start-1 mb-2 pt-0.5 md:mb-0',
side === 'right'
? 'md:col-start-1 md:text-right'
: 'md:col-start-3 md:text-left',
)}
>
{opposite}
</div>
<div className="relative col-start-1 row-span-2 row-start-1 flex justify-center md:col-start-2 md:row-span-1">
{!isLast ? (
<span
aria-hidden
className="absolute top-4 bottom-0 w-px bg-border"
/>
) : null}
<div data-slot="timeline-marker" className="relative z-10">
{marker}
</div>
</div>
<div
data-slot="timeline-content"
className={cn(
'col-start-2 row-start-2 min-w-0 pb-7 md:row-start-1 md:pb-8',
side === 'right' ? 'md:col-start-3' : 'md:col-start-1',
)}
>
{children}
</div>
</li>
);
}
export { Timeline, TimelineItem };

View File

@@ -0,0 +1,69 @@
'use client';
import { AlertTriangle, ImageIcon, Loader2 } from 'lucide-react';
import Image from 'next/image';
import { useProtectedMediaObjectUrl } from '@/hooks/useProtectedMedia';
import type { DetectionResultItem } from '@/types';
import BoundingBoxOverlay from '@/components/annotation/boundingBoxOverlay';
interface AnnotatedDetectionImageProps {
detection?: DetectionResultItem;
videoWidth: number;
videoHeight: number;
}
export default function AnnotatedDetectionImage({
detection,
videoWidth,
videoHeight,
}: AnnotatedDetectionImageProps) {
const { objectUrl, isLoading, isError } = useProtectedMediaObjectUrl(
detection?.detection.context_image_url,
);
const aspectRatio =
videoWidth > 0 && videoHeight > 0
? `${videoWidth} / ${videoHeight}`
: '16 / 9';
return (
<div
className="relative flex w-full items-center justify-center overflow-hidden rounded-lg border bg-black"
style={{ aspectRatio }}
>
{!detection ? (
<div className="flex flex-col items-center gap-2 text-muted-foreground">
<ImageIcon className="size-7" />
<p className="text-sm">Select a detection to view its image.</p>
</div>
) : isLoading ? (
<div className="flex flex-col items-center gap-2 text-muted-foreground">
<Loader2 className="size-7 animate-spin text-primary" />
<p className="text-sm">Loading detection image...</p>
</div>
) : isError || !objectUrl ? (
<div className="flex flex-col items-center gap-2 text-destructive">
<AlertTriangle className="size-7" />
<p className="text-sm">Failed to load the detection image.</p>
</div>
) : (
<>
<Image
src={objectUrl}
alt={`${detection.detection.display_name} detection`}
fill
unoptimized
className="object-contain"
/>
<BoundingBoxOverlay
detections={[detection]}
videoWidth={videoWidth}
videoHeight={videoHeight}
/>
</>
)}
</div>
);
}

View File

@@ -1,39 +1,106 @@
'use client'; 'use client';
import { RefObject } from 'react'; import { RefObject, useEffect } from 'react';
import { AlertTriangle, Loader2 } from 'lucide-react'; import { AlertTriangle, Loader2 } from 'lucide-react';
import type { DetectionResultLog } from '@/types';
import { useDetectionThumbnails } from './useDetectionThumbnails';
import BoundingBoxOverlay from '@/components/annotation/boundingBoxOverlay';
import {
MediaPlayer,
MediaProvider,
Poster,
isVideoProvider,
type MediaPlayerInstance,
useMediaProvider,
} from '@vidstack/react';
import {
DefaultVideoLayout,
defaultLayoutIcons,
} from '@vidstack/react/player/layouts/default';
interface AnnotatedVideoPlayerProps { interface AnnotatedVideoPlayerProps {
videoRef: RefObject<HTMLVideoElement | null>; videoRef: RefObject<MediaPlayerInstance | null>;
logs: DetectionResultLog[];
visibleLogs: DetectionResultLog[];
videoWidth: number;
videoHeight: number;
videoUrl: string | null; videoUrl: string | null;
isLoading: boolean; isLoading: boolean;
isError: boolean; isError: boolean;
onRetry: () => void; onRetry: () => void;
onTimeUpdate: () => void; onTimeUpdate: () => void;
onVideoFrame: (mediaTime: number) => void;
onSeeked: () => void; onSeeked: () => void;
} }
function VideoFrameSync({
onVideoFrame,
}: Pick<AnnotatedVideoPlayerProps, 'onVideoFrame'>) {
const provider = useMediaProvider();
useEffect(() => {
if (!isVideoProvider(provider)) return;
const video = provider.video;
let callbackId: number;
const update = (_now: number, metadata: VideoFrameCallbackMetadata) => {
onVideoFrame(metadata.mediaTime);
callbackId = video.requestVideoFrameCallback(update);
};
callbackId = video.requestVideoFrameCallback(update);
return () => video.cancelVideoFrameCallback(callbackId);
}, [onVideoFrame, provider]);
return null;
}
export default function AnnotatedVideoPlayer({ export default function AnnotatedVideoPlayer({
videoRef, videoRef,
logs,
visibleLogs,
videoWidth,
videoHeight,
videoUrl, videoUrl,
isLoading, isLoading,
isError, isError,
onRetry, onRetry,
onTimeUpdate, onTimeUpdate,
onVideoFrame,
onSeeked, onSeeked,
}: AnnotatedVideoPlayerProps) { }: AnnotatedVideoPlayerProps) {
const thumbnails = useDetectionThumbnails(logs);
return ( return (
<div className="relative overflow-hidden rounded-lg border bg-black"> <div className="relative overflow-hidden rounded-lg border bg-black">
{videoUrl ? ( {videoUrl ? (
<video <MediaPlayer
ref={videoRef} ref={videoRef}
src={videoUrl} src={{ src: videoUrl, type: 'video/mp4' }}
controls viewType="video"
preload="metadata" streamType="on-demand"
crossOrigin
playsInline
onTimeUpdate={onTimeUpdate} onTimeUpdate={onTimeUpdate}
onSeeked={onSeeked} onSeeked={onSeeked}
className="block w-full aspect-video" className="detection-video-player aspect-video w-full"
>
<MediaProvider>
<Poster className="vds-poster" />
</MediaProvider>
<VideoFrameSync onVideoFrame={onVideoFrame} />
<BoundingBoxOverlay
detections={visibleLogs}
videoWidth={videoWidth}
videoHeight={videoHeight}
/> />
<DefaultVideoLayout
thumbnails={thumbnails}
icons={defaultLayoutIcons}
/>
</MediaPlayer>
) : ( ) : (
<div className="flex aspect-video w-full flex-col items-center justify-center gap-3 text-center text-muted-foreground"> <div className="flex aspect-video w-full flex-col items-center justify-center gap-3 text-center text-muted-foreground">
{isError ? ( {isError ? (
@@ -54,7 +121,9 @@ export default function AnnotatedVideoPlayer({
<> <>
<Loader2 className="h-7 w-7 animate-spin text-primary" /> <Loader2 className="h-7 w-7 animate-spin text-primary" />
<p className="text-xs"> <p className="text-xs">
{isLoading ? 'Loading annotated video...' : 'Preparing video...'} {isLoading
? 'Loading annotated video...'
: 'Preparing video...'}
</p> </p>
</> </>
)} )}

View File

@@ -4,7 +4,7 @@ import { Activity, MapPin } from 'lucide-react';
import type { CompletedVideoResult, DetectionResultLog } from '@/types'; import type { CompletedVideoResult, DetectionResultLog } from '@/types';
import { getDefectVisual } from './defectVisualConfig'; import { getDefectVisual } from '@/constants/defectVisualConfig';
interface CurrentDetectionBarProps { interface CurrentDetectionBarProps {
activeLog?: DetectionResultLog; activeLog?: DetectionResultLog;

View File

@@ -1,15 +1,18 @@
'use client'; 'use client';
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { Activity, Film, MapPin } from 'lucide-react'; import { Activity, Film, ImageIcon, MapPin } from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area'; import { ScrollArea } from '@/components/ui/scroll-area';
import { DetectionResultLog } from '@/types'; import { Skeleton } from '@/components/ui/skeleton';
import { useProtectedMediaObjectUrl } from '@/hooks/useProtectedMedia';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import type { DetectionResultLog } from '@/types';
interface DetectionLogsProps { interface DetectionLogsProps {
logs: DetectionResultLog[]; logs: DetectionResultLog[];
activeLogId?: string; activeLogId?: string;
onSeek: (log: DetectionResultLog) => void; onSelect: (log: DetectionResultLog) => void;
} }
const formatVideoTime = (seconds: number) => { const formatVideoTime = (seconds: number) => {
@@ -19,7 +22,48 @@ const formatVideoTime = (seconds: number) => {
return `${minutes}:${secs.toString().padStart(2, '0')}`; return `${minutes}:${secs.toString().padStart(2, '0')}`;
}; };
const DetectionLogs = ({ logs, activeLogId, onSeek }: DetectionLogsProps) => { function DetectionLogThumbnail({
url,
label,
}: {
url?: string | null;
label: string;
}) {
const { objectUrl, isLoading, isError } = useProtectedMediaObjectUrl(url);
if (!url) {
return (
<div className="flex size-20 shrink-0 items-center justify-center rounded-md border border-dashed border-border/70 bg-muted/20 text-muted-foreground/60">
<ImageIcon className="size-5" />
</div>
);
}
if (isLoading) {
return <Skeleton className="size-20 shrink-0 rounded-md" />;
}
if (isError || !objectUrl) {
return (
<div className="flex size-20 shrink-0 items-center justify-center rounded-md border border-dashed bg-muted/20 text-[10px] text-muted-foreground">
N/A
</div>
);
}
return (
<div className="size-20 shrink-0 overflow-hidden rounded-md border bg-muted/20">
<img
src={objectUrl}
alt={label}
className="size-full object-cover"
loading="lazy"
/>
</div>
);
}
const DetectionLogs = ({ logs, activeLogId, onSelect }: DetectionLogsProps) => {
const activeLogRef = useRef<HTMLButtonElement | null>(null); const activeLogRef = useRef<HTMLButtonElement | null>(null);
useEffect(() => { useEffect(() => {
@@ -49,27 +93,36 @@ const DetectionLogs = ({ logs, activeLogId, onSeek }: DetectionLogsProps) => {
const timestampSeconds = log.frame.timestamp_seconds; const timestampSeconds = log.frame.timestamp_seconds;
const { latitude, longitude } = log.location; const { latitude, longitude } = log.location;
const isActive = activeLogId === log.id; const isActive = activeLogId === log.id;
const label = log.detection.display_name;
return ( return (
<button <button
key={`${log.id}-${log.frame.number}`} key={`${log.id}-${log.frame.number}`}
ref={isActive ? activeLogRef : null} ref={isActive ? activeLogRef : null}
type="button" type="button"
onClick={() => onSeek(log)} onClick={() => onSelect(log)}
className={cn( className={cn(
'w-full rounded-md border bg-card p-4 text-left transition-colors hover:border-primary', 'w-full rounded-md border bg-card p-3 text-left transition-colors hover:border-primary',
isActive && 'border-primary bg-primary/5', isActive && 'border-primary bg-primary/5',
)} )}
> >
<div className="mb-3 flex items-start justify-between gap-4"> <div className="flex gap-3">
<div> <DetectionLogThumbnail
<div className="text-[13px] font-bold"> url={log.detection.context_image_url}
{log.detection.display_name} ID: {log.id} label={label}
</div> />
<div className="text-[11px] font-medium text-muted-foreground">
<div className="min-w-0 flex-1">
<div className="mb-2 flex items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
<p className="text-sm font-semibold text-foreground">
{label}
</p>
<p className="text-[11px] text-muted-foreground">
Frame {log.frame.number} Frame {log.frame.number}
</p>
</div> </div>
</div>
<div className="shrink-0 text-right"> <div className="shrink-0 text-right">
<div className="text-xs font-bold"> <div className="text-xs font-bold">
{formatVideoTime(timestampSeconds)} {formatVideoTime(timestampSeconds)}
@@ -80,20 +133,20 @@ const DetectionLogs = ({ logs, activeLogId, onSeek }: DetectionLogsProps) => {
</div> </div>
</div> </div>
<div className="space-y-2 text-[12px] font-medium text-muted-foreground/90"> <div className="space-y-1.5 text-[12px] text-muted-foreground">
<div> <p>{(log.detection.confidence * 100).toFixed(1)}%</p>
Confidence: {(log.detection.confidence * 100).toFixed(1)}%
</div>
{typeof latitude === 'number' && {typeof latitude === 'number' &&
typeof longitude === 'number' && ( typeof longitude === 'number' && (
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<MapPin className="h-3 w-3" /> <MapPin className="h-3 w-3 shrink-0" />
<span> <span className="truncate font-mono text-[11px]">
{latitude.toFixed(8)}, {longitude.toFixed(8)} {latitude.toFixed(8)}, {longitude.toFixed(8)}
</span> </span>
</div> </div>
)} )}
</div> </div>
</div>
</div>
</button> </button>
); );
}) })

View File

@@ -1,9 +1,10 @@
'use client'; 'use client';
import { Activity, Clock, Gauge } from 'lucide-react'; import { Activity, Clock, Gauge } from 'lucide-react';
import { CompletedVideoResult } from '@/types';
import { getDefectVisual } from './defectVisualConfig'; import { getDefectVisual } from '@/constants/defectVisualConfig';
import { cn } from '@/lib/utils';
import type { CompletedVideoResult } from '@/types';
const formatDuration = (seconds?: number) => { const formatDuration = (seconds?: number) => {
if (typeof seconds !== 'number' || !Number.isFinite(seconds)) return '-'; if (typeof seconds !== 'number' || !Number.isFinite(seconds)) return '-';
@@ -28,8 +29,8 @@ export default function ResultStatsGrid({ data }: ResultStatsGridProps) {
label: item.display_name, label: item.display_name,
value: item.count, value: item.count,
icon: visual.icon, icon: visual.icon,
color: visual.colorClassName, colorClassName: visual.colorClassName,
bgColor: visual.iconClassName, iconClassName: visual.iconClassName,
}; };
}); });
@@ -38,23 +39,23 @@ export default function ResultStatsGrid({ data }: ResultStatsGridProps) {
label: 'Total Detections', label: 'Total Detections',
value: data.summary.total_detections, value: data.summary.total_detections,
icon: Activity, icon: Activity,
color: 'text-green-500', colorClassName: 'text-green-500',
bgColor: 'bg-green-500/10 text-green-500', iconClassName: 'bg-green-500/10 text-green-500',
}, },
...defectStats, ...defectStats,
{ {
label: 'FPS', label: 'FPS',
value: formatFps(data.summary.fps), value: formatFps(data.summary.fps),
icon: Gauge, icon: Gauge,
color: 'text-purple-500', colorClassName: 'text-purple-500',
bgColor: 'bg-purple-500/10 text-purple-500', iconClassName: 'bg-purple-500/10 text-purple-500',
}, },
{ {
label: 'Duration', label: 'Duration',
value: formatDuration(data.summary.duration_seconds), value: formatDuration(data.summary.duration_seconds),
icon: Clock, icon: Clock,
color: 'text-cyan-500', colorClassName: 'text-cyan-500',
bgColor: 'bg-cyan-500/10 text-cyan-500', iconClassName: 'bg-cyan-500/10 text-cyan-500',
}, },
]; ];
@@ -66,17 +67,29 @@ export default function ResultStatsGrid({ data }: ResultStatsGridProps) {
return ( return (
<div <div
key={stat.label} key={stat.label}
className="flex flex-col items-center rounded-lg border border-muted bg-muted/30 p-4 text-center" className="rounded-xl bg-muted/40 p-4 transition-colors hover:bg-muted/60"
>
<div className="flex items-center justify-between gap-3">
<p
className={cn(
'text-2xl font-bold tracking-tight',
stat.colorClassName,
)}
> >
<div className={`mb-2 rounded-md p-2 ${stat.bgColor}`}>
<Icon className="h-5 w-5" />
</div>
<div className={`text-xl font-bold ${stat.color}`}>
{stat.value} {stat.value}
</p>
<span
className={cn(
'flex size-8 shrink-0 items-center justify-center rounded-lg',
stat.iconClassName,
)}
>
<Icon className="size-3.5" />
</span>
</div> </div>
<div className="mt-1 text-[10px] font-bold uppercase tracking-wider text-muted-foreground"> <p className="mt-2 truncate text-xs font-semibold text-foreground">
{stat.label} {stat.label}
</div> </p>
</div> </div>
); );
})} })}

View File

@@ -1,15 +1,18 @@
'use client'; 'use client';
import { RefObject, useMemo, useRef, useState } from 'react'; import { RefObject, useCallback, useMemo, useRef, useState } from 'react';
import type { MediaPlayerInstance } from '@vidstack/react';
import { CompletedVideoResult, DetectionResultLog } from '@/types'; import { CompletedVideoResult, DetectionResultLog } from '@/types';
interface UseDetectionPlaybackParams { interface UseDetectionPlaybackParams {
logs: CompletedVideoResult['logs']; logs: CompletedVideoResult['logs'];
videoRef: RefObject<HTMLVideoElement | null>; fps: number;
videoRef: RefObject<MediaPlayerInstance | null>;
} }
export function useDetectionPlayback({ export function useDetectionPlayback({
logs, logs,
fps,
videoRef, videoRef,
}: UseDetectionPlaybackParams) { }: UseDetectionPlaybackParams) {
const shouldPauseAfterSeekRef = useRef(false); const shouldPauseAfterSeekRef = useRef(false);
@@ -23,6 +26,36 @@ export function useDetectionPlayback({
const [activeLog, setActiveLog] = useState<DetectionResultLog | undefined>( const [activeLog, setActiveLog] = useState<DetectionResultLog | undefined>(
sortedLogs[0], sortedLogs[0],
); );
const [visibleLogs, setVisibleLogs] = useState<DetectionResultLog[]>([]);
const visibleLogIdsRef = useRef('');
const getVisibleLogs = useCallback(
(currentTime: number) => {
const frameDuration = fps > 0 ? 1 / fps : 0;
return sortedLogs.filter((log) => {
const start =
log.frame.start_timestamp_seconds ?? log.frame.timestamp_seconds;
const end = log.frame.end_timestamp_seconds ?? start + frameDuration;
return currentTime >= start && currentTime < end;
});
},
[fps, sortedLogs],
);
const updateVisibleLogs = useCallback(
(currentTime: number) => {
const nextLogs = getVisibleLogs(currentTime);
const nextIds = nextLogs.map((log) => log.id).join('|');
if (nextIds === visibleLogIdsRef.current) return;
visibleLogIdsRef.current = nextIds;
setVisibleLogs(nextLogs);
},
[getVisibleLogs],
);
const handleSeek = (log: DetectionResultLog) => { const handleSeek = (log: DetectionResultLog) => {
const video = videoRef.current; const video = videoRef.current;
@@ -32,6 +65,7 @@ export function useDetectionPlayback({
video.pause(); video.pause();
video.currentTime = log.frame.timestamp_seconds; video.currentTime = log.frame.timestamp_seconds;
setActiveLog(log); setActiveLog(log);
updateVisibleLogs(log.frame.timestamp_seconds);
}; };
const handleSeeked = () => { const handleSeeked = () => {
@@ -57,9 +91,11 @@ export function useDetectionPlayback({
return { return {
activeLog, activeLog,
visibleLogs,
sortedLogs, sortedLogs,
handleSeek, handleSeek,
handleSeeked, handleSeeked,
handleTimeUpdate, handleTimeUpdate,
handleVideoFrame: updateVisibleLogs,
}; };
} }

View File

@@ -0,0 +1,66 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { useQueries } from '@tanstack/react-query';
import { protectedMediaService } from '@/services/api';
import type { DetectionResultLog } from '@/types';
type DetectionThumbnail = {
url: string;
startTime: number;
endTime: number;
};
const PREVIEW_WINDOW_SECONDS = 0.5;
export function useDetectionThumbnails(logs: DetectionResultLog[]) {
const imageUrls = useMemo(
() => logs.map((log) => log.detection.context_image_url),
[logs],
);
const blobs = useQueries({
queries: imageUrls.map((url) => ({
queryKey: ['protected-media', url],
queryFn: () => protectedMediaService.getBlob(url),
enabled: Boolean(url),
staleTime: Infinity,
gcTime: 1000 * 60 * 30,
})),
combine: (results) => results.map((result) => result.data),
});
const [objectUrls, setObjectUrls] = useState<Array<string | null>>([]);
useEffect(() => {
const nextUrls = blobs.map((blob) =>
blob ? URL.createObjectURL(blob) : null,
);
setObjectUrls(nextUrls);
return () => {
nextUrls.forEach((url) => {
if (url) URL.revokeObjectURL(url);
});
};
}, [blobs]);
return useMemo<DetectionThumbnail[]>(
() =>
logs.flatMap((log, index) => {
const url = objectUrls[index];
if (!url) return [];
const timestamp = log.frame.timestamp_seconds;
return [
{
url,
startTime: Math.max(0, timestamp - PREVIEW_WINDOW_SECONDS),
endTime: timestamp + PREVIEW_WINDOW_SECONDS,
},
];
}),
[logs, objectUrls],
);
}

View File

@@ -1,7 +1,7 @@
'use client'; 'use client';
import { useRef } from 'react'; import { useMemo, useState } from 'react';
import { Film } from 'lucide-react'; import { ImageIcon } from 'lucide-react';
import { import {
Card, Card,
CardContent, CardContent,
@@ -10,35 +10,27 @@ import {
CardTitle, CardTitle,
} from '@/components/ui/card'; } from '@/components/ui/card';
import { CompletedVideoResult } from '@/types'; import { CompletedVideoResult } from '@/types';
import { useAnnotatedVideoQuery } from '@/app/(modules)/results/hooks/useVideoResults'; import DetectionLocationMap from './map/detectionLocationMap';
import AnnotatedVideoPlayer from './video/annotatedVideoPlayer'; import AnnotatedDetectionImage from './video/annotatedDetectionImage';
import CurrentDetectionBar from './video/currentDetectionBar'; import CurrentDetectionBar from './video/currentDetectionBar';
import DetectionLogs from './video/detectionLogs'; import DetectionLogs from './video/detectionLogs';
import ResultStatsGrid from './video/resultStatsGrid'; import ResultStatsGrid from './video/resultStatsGrid';
import { useDetectionPlayback } from './video/useDetectionPlayback';
type VideoPlayerSectionProps = { type VideoPlayerSectionProps = {
data: CompletedVideoResult; data: CompletedVideoResult;
}; };
export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) { export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
const videoRef = useRef<HTMLVideoElement>(null); const sortedLogs = useMemo(
const { () =>
activeLog, [...data.logs].sort(
sortedLogs, (a, b) => a.frame.timestamp_seconds - b.frame.timestamp_seconds,
handleSeek, ),
handleSeeked, [data.logs],
handleTimeUpdate, );
} = useDetectionPlayback({ const [selectedLogId, setSelectedLogId] = useState(sortedLogs[0]?.id);
logs: data.logs, const activeLog =
videoRef, sortedLogs.find((log) => log.id === selectedLogId) ?? sortedLogs[0];
});
const {
videoUrl,
isLoading: isVideoLoading,
isError: isVideoError,
refetch: refetchVideo,
} = useAnnotatedVideoQuery(data.processed_video_url || '');
return ( return (
<div className="space-y-6"> <div className="space-y-6">
@@ -46,14 +38,14 @@ export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
<CardHeader className="border-b pb-4"> <CardHeader className="border-b pb-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="rounded bg-secondary p-2"> <div className="rounded bg-secondary p-2">
<Film className="h-5 w-5 text-primary" /> <ImageIcon className="h-5 w-5 text-primary" />
</div> </div>
<div> <div>
<CardTitle className="text-lg font-bold"> <CardTitle className="text-lg font-bold">
Detection Playback Detection Preview
</CardTitle> </CardTitle>
<CardDescription className="text-xs"> <CardDescription className="text-xs">
Annotated video with backend detection logs Selected detection image with its bounding box
</CardDescription> </CardDescription>
</div> </div>
</div> </div>
@@ -61,14 +53,16 @@ export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
<CardContent className="pt-6"> <CardContent className="pt-6">
<div className="grid grid-cols-1 gap-6 lg:grid-cols-3"> <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
<div className="space-y-6 lg:col-span-2"> <div className="space-y-6 lg:col-span-2">
<AnnotatedVideoPlayer <AnnotatedDetectionImage
videoRef={videoRef} detection={activeLog}
videoUrl={videoUrl} videoWidth={data.summary.video_width}
isLoading={isVideoLoading} videoHeight={data.summary.video_height}
isError={isVideoError} />
onRetry={() => void refetchVideo()}
onTimeUpdate={handleTimeUpdate} <DetectionLocationMap
onSeeked={handleSeeked} latitude={activeLog?.location.latitude ?? null}
longitude={activeLog?.location.longitude ?? null}
label={activeLog?.detection.display_name ?? 'Detection'}
/> />
<CurrentDetectionBar activeLog={activeLog} data={data} /> <CurrentDetectionBar activeLog={activeLog} data={data} />
@@ -77,7 +71,7 @@ export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
<DetectionLogs <DetectionLogs
logs={sortedLogs} logs={sortedLogs}
activeLogId={activeLog?.id} activeLogId={activeLog?.id}
onSeek={handleSeek} onSelect={(log) => setSelectedLogId(log.id)}
/> />
</div> </div>

View File

@@ -2,7 +2,7 @@ import {
Layers, Layers,
Milestone, Milestone,
Package, Package,
Plus, UploadCloud,
Settings, Settings,
ShieldCheck, ShieldCheck,
Ticket, Ticket,
@@ -28,7 +28,7 @@ export const menuItems: MenuItem[] = [
{ {
title: 'Upload', title: 'Upload',
path: ROUTES.UPLOAD, path: ROUTES.UPLOAD,
icon: Plus, icon: UploadCloud,
permission: PERMISSIONS.VIDEO.UPLOAD, permission: PERMISSIONS.VIDEO.UPLOAD,
}, },
{ {
@@ -130,7 +130,9 @@ export function getFirstAccessibleMenuPath(
hasPermission: (permission?: string) => boolean, hasPermission: (permission?: string) => boolean,
fallback = ROUTES.ACCESS, fallback = ROUTES.ACCESS,
) { ) {
return findFirstMenuPath(filterMenuItems(menuItems, hasPermission)) ?? fallback; return (
findFirstMenuPath(filterMenuItems(menuItems, hasPermission)) ?? fallback
);
} }
export function getFirstAccessiblePathForPermissions( export function getFirstAccessiblePathForPermissions(

View File

@@ -49,8 +49,12 @@ export const API_ROUTES = {
}, },
VIDEOS: { VIDEOS: {
UPLOAD: '/biz/api/v1/upload', UPLOAD: '/biz/api/v1/upload',
MY_UPLOADS: '/biz/api/v1/videos/me', UPLOADS: '/biz/api/v1/uploads',
UPLOAD_EVENTS_TOKEN: '/biz/api/v1/uploads/events/token',
UPLOAD_EVENTS: (token: string) =>
`/biz/api/v1/uploads/events?sse_token=${encodeURIComponent(token)}`,
RESULTS: (id: string) => `/biz/api/v1/results/${id}/completed`, RESULTS: (id: string) => `/biz/api/v1/results/${id}/completed`,
DETECTIONS: (id: string) => `/biz/api/v1/results/${id}/detections`,
}, },
TICKETS: { TICKETS: {
BASE: '/biz/api/v1/tickets', BASE: '/biz/api/v1/tickets',
@@ -62,6 +66,12 @@ export const API_ROUTES = {
SUBMIT_REPAIR: (id: string) => `/biz/api/v1/tickets/${id}/submit-repair`, SUBMIT_REPAIR: (id: string) => `/biz/api/v1/tickets/${id}/submit-repair`,
SUBMIT_REPAIR_UPLOAD: (id: string) => SUBMIT_REPAIR_UPLOAD: (id: string) =>
`/biz/api/v1/tickets/${id}/repair-proof`, `/biz/api/v1/tickets/${id}/repair-proof`,
REQUEST_EXTENSION: (ticketId: string, assignmentId: number) =>
`/biz/api/v1/tickets/${ticketId}/assignments/${assignmentId}/extension-requests`,
EXTENSION_REQUESTS: (ticketId: string) =>
`/biz/api/v1/tickets/${ticketId}/extension-requests`,
REVIEW_EXTENSION_REQUEST: (ticketId: string, assignmentId: number) =>
`/biz/api/v1/tickets/${ticketId}/assignments/${assignmentId}/extension-request/decision`,
REVIEW: (id: string) => `/biz/api/v1/tickets/${id}/review`, REVIEW: (id: string) => `/biz/api/v1/tickets/${id}/review`,
CLOSE: (id: string) => `/biz/api/v1/tickets/${id}/close`, CLOSE: (id: string) => `/biz/api/v1/tickets/${id}/close`,
DETAIL_EVENTS_TOKEN: (id: string) => DETAIL_EVENTS_TOKEN: (id: string) =>

View File

@@ -2,52 +2,66 @@
import { import {
Activity, Activity,
AlertTriangle, Construction,
CircleAlert, Spline,
CircleDot, CircleDot,
Droplets, Droplets,
LucideIcon, type LucideIcon,
SignpostBig, SignpostBig,
} from 'lucide-react'; } from 'lucide-react';
type DefectVisualConfig = { type DefectVisualConfig = {
icon: LucideIcon; icon: LucideIcon;
boundingBoxColor: string;
colorClassName: string; colorClassName: string;
iconClassName: string; iconClassName: string;
cardClassName: string;
}; };
const DEFECT_VISUALS: Record<string, DefectVisualConfig> = { const DEFECT_VISUALS: Record<string, DefectVisualConfig> = {
manhole_cover: { manhole_cover: {
icon: CircleDot, icon: CircleDot,
boundingBoxColor: '#71717a',
colorClassName: 'text-zinc-500', colorClassName: 'text-zinc-500',
iconClassName: 'bg-zinc-500/10 text-zinc-500', iconClassName: 'bg-zinc-500/10 text-zinc-500',
cardClassName: 'bg-zinc-500/5',
}, },
pothole: { pothole: {
icon: AlertTriangle, icon: Construction,
boundingBoxColor: '#f97316',
colorClassName: 'text-orange-500', colorClassName: 'text-orange-500',
iconClassName: 'bg-orange-500/10 text-orange-500', iconClassName: 'bg-orange-500/10 text-orange-500',
cardClassName: 'bg-orange-500/5',
}, },
road_crack: { road_crack: {
icon: CircleAlert, icon: Spline,
boundingBoxColor: '#f43f5e',
colorClassName: 'text-rose-500', colorClassName: 'text-rose-500',
iconClassName: 'bg-rose-500/10 text-rose-500', iconClassName: 'bg-rose-500/10 text-rose-500',
cardClassName: 'bg-rose-500/5',
}, },
sign_board: { sign_board: {
icon: SignpostBig, icon: SignpostBig,
boundingBoxColor: '#3b82f6',
colorClassName: 'text-blue-500', colorClassName: 'text-blue-500',
iconClassName: 'bg-blue-500/10 text-blue-500', iconClassName: 'bg-blue-500/10 text-blue-500',
cardClassName: 'bg-blue-500/5',
}, },
water_puddle: { water_puddle: {
icon: Droplets, icon: Droplets,
boundingBoxColor: '#06b6d4',
colorClassName: 'text-cyan-500', colorClassName: 'text-cyan-500',
iconClassName: 'bg-cyan-500/10 text-cyan-500', iconClassName: 'bg-cyan-500/10 text-cyan-500',
cardClassName: 'bg-cyan-500/5',
}, },
}; };
const DEFAULT_VISUAL: DefectVisualConfig = { const DEFAULT_VISUAL: DefectVisualConfig = {
icon: Activity, icon: Activity,
boundingBoxColor: '#22c55e',
colorClassName: 'text-green-500', colorClassName: 'text-green-500',
iconClassName: 'bg-green-500/10 text-green-500', iconClassName: 'bg-green-500/10 text-green-500',
cardClassName: 'bg-green-500/5',
}; };
export const getDefectVisual = (className: string) => export const getDefectVisual = (className: string) =>

View File

@@ -1,38 +1,41 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; import { useEffect, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { protectedMediaService } from '@/services/api'; import { protectedMediaService } from '@/services/api';
export function useProtectedMediaObjectUrl(url: string | null | undefined) { export function useProtectedMediaObjectUrl(url: string | null | undefined) {
const query = useQuery({ const query = useQuery({
queryKey: ['protected-media', url], queryKey: ['protected-media', 'v2', url],
queryFn: () => protectedMediaService.getBlob(url as string), queryFn: () => protectedMediaService.getBlob(url as string),
enabled: Boolean(url), enabled: Boolean(url),
staleTime: Infinity, staleTime: Infinity,
gcTime: 1000 * 60 * 30, gcTime: 1000 * 60 * 30,
}); });
const [objectUrl, setObjectUrl] = useState<string | null>(null); const objectUrl = useMemo(() => {
useEffect(() => {
if (!query.data) { if (!query.data) {
setObjectUrl(null); return null;
return;
} }
const nextUrl = URL.createObjectURL(query.data); return URL.createObjectURL(query.data);
setObjectUrl(nextUrl);
return () => {
URL.revokeObjectURL(nextUrl);
};
}, [query.data]); }, [query.data]);
useEffect(() => {
return () => {
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
};
}, [objectUrl]);
const isLoading = query.isLoading || (Boolean(query.data) && !objectUrl);
return { return {
objectUrl, objectUrl,
isLoading: query.isLoading, mediaType: query.data?.type ?? null,
isLoading,
isError: query.isError, isError: query.isError,
error: query.error, error: query.error,
}; };

View File

@@ -1,10 +1,49 @@
import axiosClient from '../axios/axios'; import axiosClient from '../axios/axios';
const MIME_BY_EXTENSION: Record<string, string> = {
mp4: 'video/mp4',
webm: 'video/webm',
mov: 'video/quicktime',
m4v: 'video/mp4',
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
webp: 'image/webp',
};
function normalizeMediaBlob(url: string, blob: Blob): Blob {
if (blob.type && blob.type !== 'application/octet-stream') {
return blob;
}
const extension = url.split('?')[0].split('.').pop()?.toLowerCase();
const mimeType = extension ? MIME_BY_EXTENSION[extension] : undefined;
if (!mimeType) {
return blob;
}
return new Blob([blob], { type: mimeType });
}
export const protectedMediaService = { export const protectedMediaService = {
getBlob: async (url: string): Promise<Blob> => { getBlob: async (url: string): Promise<Blob> => {
const response = await axiosClient.get<Blob>(url, { const response = await axiosClient.get<Blob>(url, {
responseType: 'blob', responseType: 'blob',
headers: {
Accept: '*/*',
},
transformRequest: [
(data, headers) => {
if (headers) {
delete headers['Content-Type'];
}
return data;
},
],
}); });
return response.data;
return normalizeMediaBlob(url, response.data);
}, },
}; };

View File

@@ -5,11 +5,15 @@ import type {
AssignableTicketUsersResponse, AssignableTicketUsersResponse,
AssignableTicketUsersParams, AssignableTicketUsersParams,
CloseTicketPayload, CloseTicketPayload,
RequestTicketExtensionPayload,
ReviewTicketExtensionPayload,
ReviewRepairPayload, ReviewRepairPayload,
SseTokenResponse, SseTokenResponse,
SubmitRepairPayload, SubmitRepairPayload,
SubmitRepairUploadPayload, SubmitRepairUploadPayload,
TicketDetail, TicketDetail,
TicketExtensionRequestsResponse,
TicketOverviewDetail,
TicketDefectClassesResponse, TicketDefectClassesResponse,
TicketListParams, TicketListParams,
TicketListResponse, TicketListResponse,
@@ -25,7 +29,6 @@ export const ticketService = {
params: { params: {
skip: params?.skip ?? 0, skip: params?.skip ?? 0,
limit: params?.limit ?? 10, limit: params?.limit ?? 10,
status: params?.status,
chainage_id: params?.chainage_id, chainage_id: params?.chainage_id,
}, },
}, },
@@ -33,15 +36,22 @@ export const ticketService = {
return response.data; return response.data;
}, },
getTicketDetail: async ( getTicketOverview: async (
ticketId: string, ticketId: string,
defectClass?: string, ): Promise<TicketOverviewDetail> => {
): Promise<TicketDetail> => { const response = await axiosClient.get<TicketOverviewDetail>(
const path = defectClass API_ROUTES.TICKETS.DETAIL(ticketId),
? API_ROUTES.TICKETS.CLASS_DETAIL(ticketId, defectClass) );
: API_ROUTES.TICKETS.DETAIL(ticketId); return response.data;
},
const response = await axiosClient.get<TicketDetail>(path); getTicketClassDetail: async (
ticketId: string,
defectClass: string,
): Promise<TicketDetail> => {
const response = await axiosClient.get<TicketDetail>(
API_ROUTES.TICKETS.CLASS_DETAIL(ticketId, defectClass),
);
return response.data; return response.data;
}, },
@@ -116,6 +126,42 @@ export const ticketService = {
return response.data; return response.data;
}, },
requestTicketExtension: async (
ticketId: string,
assignmentId: number,
payload: RequestTicketExtensionPayload,
): Promise<unknown> => {
const response = await axiosClient.post<unknown>(
API_ROUTES.TICKETS.REQUEST_EXTENSION(ticketId, assignmentId),
payload,
);
return response.data;
},
getTicketExtensionRequest: async (
ticketId: string,
assignmentId: number,
): Promise<TicketExtensionRequestsResponse> => {
const response = await axiosClient.get<TicketExtensionRequestsResponse>(
API_ROUTES.TICKETS.EXTENSION_REQUESTS(ticketId),
{
params: { assignment_id: assignmentId },
},
);
return response.data;
},
reviewTicketExtension: async (
ticketId: string,
assignmentId: number,
payload: ReviewTicketExtensionPayload,
): Promise<unknown> => {
const response = await axiosClient.post<unknown>(
API_ROUTES.TICKETS.REVIEW_EXTENSION_REQUEST(ticketId, assignmentId),
payload,
);
return response.data;
},
reviewRepair: async ( reviewRepair: async (
ticketId: string, ticketId: string,
payload: ReviewRepairPayload, payload: ReviewRepairPayload,

View File

@@ -1,16 +1,23 @@
import axiosClient from '../axios/axios'; import axiosClient from '../axios/axios';
import { API_ROUTES } from '@/constants/apiRoutes'; import { API_ROUTES } from '@/constants/apiRoutes';
import { CompletedVideoResult, PaginationParams, UploadVideosResponse } from '@/types'; import {
CompletedVideoResult,
PaginationParams,
SseTokenResponse,
UploadListResponse,
VideoDetectionsParams,
VideoDetectionsResponse,
} from '@/types';
/** /**
* Video Service * Video Service
*/ */
export const videoService = { export const videoService = {
getMyUploads: async ( getUploads: async (
params?: PaginationParams, params?: PaginationParams,
): Promise<UploadVideosResponse> => { ): Promise<UploadListResponse> => {
const response = await axiosClient.get<UploadVideosResponse>( const response = await axiosClient.get<UploadListResponse>(
API_ROUTES.VIDEOS.MY_UPLOADS, API_ROUTES.VIDEOS.UPLOADS,
{ {
params: { params: {
skip: params?.skip ?? 0, skip: params?.skip ?? 0,
@@ -21,6 +28,13 @@ export const videoService = {
return response.data; return response.data;
}, },
createUploadEventsToken: async (): Promise<SseTokenResponse> => {
const response = await axiosClient.post<SseTokenResponse>(
API_ROUTES.VIDEOS.UPLOAD_EVENTS_TOKEN,
);
return response.data;
},
/** /**
* Upload a video for processing * Upload a video for processing
*/ */
@@ -41,7 +55,29 @@ export const videoService = {
* Get analysis results for a video * Get analysis results for a video
*/ */
getVideoResults: async (videoId: string): Promise<CompletedVideoResult> => { getVideoResults: async (videoId: string): Promise<CompletedVideoResult> => {
const response = await axiosClient.get(API_ROUTES.VIDEOS.RESULTS(videoId)); const response = await axiosClient.get<CompletedVideoResult>(
API_ROUTES.VIDEOS.RESULTS(videoId),
);
return response.data;
},
getVideoDetections: async (
videoId: string,
params?: VideoDetectionsParams,
): Promise<VideoDetectionsResponse> => {
const response = await axiosClient.get<VideoDetectionsResponse>(
API_ROUTES.VIDEOS.DETECTIONS(videoId),
{
params: {
skip: params?.skip ?? 0,
limit: params?.limit ?? 1,
class_name: params?.class_name,
min_confidence: params?.min_confidence,
sort: params?.sort ?? 'timestamp_asc',
search: params?.search,
},
},
);
return response.data; return response.data;
}, },

View File

@@ -2,12 +2,14 @@ import { DetectionClassCount, DetectionResultLog } from './detection';
export type CompletedVideoResult = { export type CompletedVideoResult = {
video_id: string; video_id: string;
status: 'completed' | string; status: 'completed';
processed_video_url: string | null; raw_video_url: string;
raw_video_url: string | null; processed_video_url: string;
summary: { summary: {
fps?: number; fps: number;
duration_seconds?: number; duration_seconds: number;
video_width: number;
video_height: number;
total_detections: number; total_detections: number;
}; };
defect_counts: DetectionClassCount[]; defect_counts: DetectionClassCount[];

View File

@@ -5,22 +5,38 @@ export type DetectionClassCount = {
unique_count: number; unique_count: number;
}; };
export type DetectionResultLog = { export type DetectionBoundingBox = {
x1: number;
y1: number;
x2: number;
y2: number;
width: number;
height: number;
};
export type DetectionResultItem = {
id: string; id: string;
detection: { detection: {
id: number; id: number;
class_name: string; class_name: string;
display_name: string; display_name: string;
confidence: number; confidence: number;
context_image_url: string;
bounding_box: DetectionBoundingBox;
}; };
frame: { frame: {
number: number; number: number;
timestamp_seconds: number; timestamp_seconds: number;
start_timestamp_seconds?: number;
end_timestamp_seconds?: number;
}; };
location: { location: {
latitude: number | null; latitude: number | null;
longitude: number | null; longitude: number | null;
}; };
};
export type DetectionResultLog = DetectionResultItem & {
running_counts: { running_counts: {
total: number; total: number;
by_class: Array<{ by_class: Array<{
@@ -30,3 +46,23 @@ export type DetectionResultLog = {
}>; }>;
}; };
}; };
export type VideoDetectionsParams = {
skip?: number;
limit?: number;
class_name?: string | string[];
min_confidence?: number;
sort?: string;
search?: string;
};
export type VideoDetectionsResponse = {
video_id: string;
video_width: number;
video_height: number;
skip: number;
limit: number;
total: number;
sort: string;
items: DetectionResultItem[];
};

View File

@@ -5,6 +5,12 @@ export interface AssignableTicketUser {
name: string; name: string;
email: string; email: string;
username: string; username: string;
phone_number: string | null;
role: {
id: number;
name: string;
};
} }
export interface AssignableTicketUsersParams extends PaginationParams { export interface AssignableTicketUsersParams extends PaginationParams {
@@ -19,6 +25,7 @@ export interface AssignableTicketUsersResponse {
export interface AssignTicketPayload { export interface AssignTicketPayload {
assigned_to_user_id: number; assigned_to_user_id: number;
defect_class: string; defect_class: string;
due_at: string;
note?: string; note?: string;
} }
@@ -34,6 +41,45 @@ export interface SubmitRepairUploadPayload {
images: File[]; images: File[];
} }
export interface RequestTicketExtensionPayload {
requested_due_at: string;
reason: string;
}
export interface ReviewTicketExtensionPayload {
action: 'approve' | 'reject';
note: string;
}
export interface TicketExtensionRequestActor {
id: number;
name: string;
role: {
id: number;
name: string;
};
}
export interface TicketExtensionRequest {
id: number;
ticket_id: string;
assignment_id: number;
defect_class: string;
current_due_at: string;
requested_due_at: string;
reason: string;
status: 'pending' | 'approved' | 'rejected' | 'cancelled';
requested_by: TicketExtensionRequestActor | null;
requested_at: string;
resolved_by: TicketExtensionRequestActor | null;
resolved_at: string | null;
}
export interface TicketExtensionRequestsResponse {
items: TicketExtensionRequest[];
total: number;
}
export interface ReviewRepairPayload { export interface ReviewRepairPayload {
defect_class: string; defect_class: string;
action: 'approve' | 'reject'; action: 'approve' | 'reject';

View File

@@ -5,14 +5,29 @@ export interface TicketActor {
user_id: number | null; user_id: number | null;
name: string | null; name: string | null;
email: string | null; email: string | null;
avatar_url?: string | null;
}
export type TicketHistorySource = 'system' | 'user';
export interface TicketHistoryNote {
kind: string;
author: TicketActor | null;
text: string;
} }
export interface TicketHistoryItem { export interface TicketHistoryItem {
id: number; id: number;
from_status: TicketStatus | null; event_type: string;
to_status: TicketStatus; title: string;
source: TicketHistorySource;
assignment_id: number | null;
defect_class: string | null;
from_class_status: TicketDefectClassTicketStatus | null;
to_class_status: TicketDefectClassTicketStatus | null;
actor: TicketActor | null; actor: TicketActor | null;
note: string | null; target_user: TicketActor | null;
note: TicketHistoryNote | null;
created_at: string; created_at: string;
} }
@@ -34,8 +49,15 @@ export interface TicketVideo {
} }
export interface TicketWorker extends TicketActor { export interface TicketWorker extends TicketActor {
assignment_id: number;
assigned_at: string | null; assigned_at: string | null;
assigned_by: TicketActor | null; due_at: string | null;
assigned_by_user_id: number | null;
assigned_by_name: string | null;
role: {
id: number;
name: string;
} | null;
} }
export interface TicketRepair { export interface TicketRepair {
@@ -65,6 +87,56 @@ export interface TicketTimestamps {
updated_at: string; updated_at: string;
} }
export interface TicketLocationReference {
id: string;
name: string;
}
export interface TicketLocation {
project: TicketLocationReference | null;
package: TicketLocationReference | null;
chainage: TicketLocationReference | null;
}
export interface TicketVideoMetadata {
duration_seconds: number;
fps: number;
resolution: {
width: number;
height: number;
label: string;
};
}
export interface TicketDetectionClassCount {
class_name: string;
display_name: string;
count: number;
}
export interface TicketOverviewDetail {
id: string;
ticket_name?: string | null;
video_id?: string | null;
video?: TicketVideo | null;
chainage_id?: string | null;
chainage_name?: string | null;
location: TicketLocation | null;
video_metadata?: TicketVideoMetadata | null;
uploader?: {
user_id: number;
name: string | null;
email: string | null;
} | null;
ai_result: {
detection_count: number;
completed_at: string;
available_defect_classes: string[];
detections_by_class: TicketDetectionClassCount[];
};
timestamps?: TicketTimestamps | null;
}
export interface TicketDetail { export interface TicketDetail {
id: string; id: string;
ticket_name?: string; ticket_name?: string;

View File

@@ -13,11 +13,10 @@ export type TicketTableStatusEvent = {
ticket_name?: string; ticket_name?: string;
chainage_id?: string | null; chainage_id?: string | null;
chainage_name?: string | null; chainage_name?: string | null;
status?: TicketStatus;
default_defect_class?: string | null; default_defect_class?: string | null;
assigned_to_name?: string | null;
detection_count?: number; detection_count?: number;
created_by_name?: string | null; created_by_name?: string | null;
created_by_email?: string | null;
created_at?: string; created_at?: string;
updated_at?: string; updated_at?: string;
message?: string; message?: string;

View File

@@ -1,8 +1,6 @@
import type { PaginationParams } from '../common'; import type { PaginationParams } from '../common';
import type { TicketStatus } from './status';
export interface TicketListParams extends PaginationParams { export interface TicketListParams extends PaginationParams {
status?: TicketStatus;
chainage_id?: string; chainage_id?: string;
} }
@@ -11,11 +9,10 @@ export interface TicketListItem {
ticket_name: string; ticket_name: string;
chainage_id: string | null; chainage_id: string | null;
chainage_name: string | null; chainage_name: string | null;
status: TicketStatus;
default_defect_class: string | null; default_defect_class: string | null;
assigned_to_name: string | null;
detection_count: number; detection_count: number;
created_by_name: string | null; created_by_name: string | null;
created_by_email: string | null;
created_at: string; created_at: string;
updated_at: string; updated_at: string;
} }

View File

@@ -1,25 +1,41 @@
export interface UploadVideoStatus { export type UploadStatus = 'queued' | 'processing' | 'completed' | 'failed';
status: string; export type UploadResult =
| 'ticket_created'
| 'no_defects_found'
| 'analysis_failed'
| null;
export type UploadEventKind = 'created' | 'progressed' | 'transitioned';
export interface UploadListItem {
id: string;
video_name: string;
thumbnail: string | null;
raw_video_url: string | null;
uploaded_by: { name: string | null; email: string | null };
project: string | null;
package: string | null;
segment: string | null;
chainage: string | null;
uploaded_at: string | null;
is_uploaded: boolean;
status: UploadStatus;
progress: number; progress: number;
message: string | null;
total_detections: number | null;
result: UploadResult;
ticket_id: string | null;
ticket_name: string | null;
error_message: string | null;
} }
export interface UploadVideo { export interface UploadListResponse {
video_id: string; items: UploadListItem[];
filename: string;
chainage_id: string;
detection_mode: string;
speed_kmh?: number | null;
thumbnail?: string | null;
uploaded_at: string;
uploaded_by_user_id?: number | null;
uploaded_by_email?: string | null;
video_url?: string | null;
processed_video_path?: string | null;
processed_video_url?: string | null;
status: UploadVideoStatus;
}
export interface UploadVideosResponse {
items: UploadVideo[];
total: number; total: number;
} }
export interface UploadStatusEvent {
kind: UploadEventKind;
event_id: string;
item: UploadListItem;
occurred_at: string;
}

View File

@@ -5,3 +5,24 @@ export function formatDate(value: string | null | undefined) {
timeStyle: 'short', timeStyle: 'short',
}).format(new Date(value)); }).format(new Date(value));
} }
export function formatDateOnly(value: string | null | undefined) {
if (!value) return '-';
return new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium' }).format(
new Date(value),
);
}
export function formatTimelineDateTime(value: string | null | undefined) {
if (!value) return { date: '-', time: '-' };
const parsed = new Date(value);
return {
date: new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium' }).format(
parsed,
),
time: new Intl.DateTimeFormat('en-IN', { timeStyle: 'short' }).format(
parsed,
),
};
}

View File

@@ -1,2 +1,4 @@
export * from './routes'; export * from './routes';
export * from './date'; export * from './date';
export * from './person';
export * from './media';

13
src/utils/media.ts Normal file
View File

@@ -0,0 +1,13 @@
import { ENV_CONSTANT } from '@/constants/secrect.constant';
export function resolveMediaUrl(url?: string | null) {
if (!url?.trim()) return null;
const value = url.trim();
if (/^https?:\/\//i.test(value)) return value;
const baseUrl = ENV_CONSTANT.BASE_API_URL?.replace(/\/$/, '');
const path = value.startsWith('/') ? value : `/${value}`;
return baseUrl ? `${baseUrl}${path}` : path;
}

8
src/utils/person.ts Normal file
View File

@@ -0,0 +1,8 @@
import type { TicketActor } from '@/types';
export function getPersonLabel(
person: TicketActor | null | undefined,
fallback = 'Unknown',
) {
return person?.name || person?.email || fallback;
}