ProjectsPage.tsx 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. import { useState, useRef } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { useTranslation } from 'react-i18next';
  4. import { useNavigate } from 'react-router-dom';
  5. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  6. import {
  7. FolderKanban,
  8. Loader2,
  9. Plus,
  10. Trash2,
  11. Edit3,
  12. Archive,
  13. ListTodo,
  14. Package,
  15. Layers,
  16. FolderTree,
  17. Clock,
  18. CheckCircle2,
  19. AlertTriangle,
  20. ChevronRight,
  21. MoreVertical,
  22. Download,
  23. Upload,
  24. ExternalLink,
  25. Image as ImageIcon,
  26. X,
  27. } from 'lucide-react';
  28. import { api } from '../api/client';
  29. import type { ProjectListItem, ProjectCreate, ProjectUpdate, ProjectImport, Permission } from '../api/client';
  30. import { Button } from '../components/Button';
  31. import { ConfirmModal } from '../components/ConfirmModal';
  32. import { useToast } from '../contexts/ToastContext';
  33. import { useAuth } from '../contexts/AuthContext';
  34. import { getCurrencySymbol } from '../utils/currency';
  35. import { eligibleParents } from '../utils/projectTree';
  36. const PROJECT_COLORS = [
  37. '#ef4444', // red
  38. '#f97316', // orange
  39. '#eab308', // yellow
  40. '#22c55e', // green
  41. '#06b6d4', // cyan
  42. '#3b82f6', // blue
  43. '#8b5cf6', // violet
  44. '#ec4899', // pink
  45. '#6b7280', // gray
  46. ];
  47. type TFunction = (key: string, options?: Record<string, unknown>) => string;
  48. interface ProjectModalProps {
  49. project?: ProjectListItem;
  50. onClose: () => void;
  51. onSave: (data: ProjectCreate | ProjectUpdate) => void;
  52. isLoading: boolean;
  53. currencySymbol: string;
  54. t: TFunction;
  55. }
  56. export function ProjectModal({ project, onClose, onSave, isLoading, currencySymbol, t }: ProjectModalProps) {
  57. const [name, setName] = useState(project?.name || '');
  58. const [description, setDescription] = useState(project?.description || '');
  59. const [color, setColor] = useState(project?.color || PROJECT_COLORS[0]);
  60. const [targetCount, setTargetCount] = useState(project?.target_count?.toString() || '');
  61. const [targetPartsCount, setTargetPartsCount] = useState(project?.target_parts_count?.toString() || '');
  62. const [targetSets, setTargetSets] = useState(project?.target_sets?.toString() || '');
  63. const [status, setStatus] = useState(project?.status || 'active');
  64. const [tags, setTags] = useState(project?.tags || '');
  65. const [dueDate, setDueDate] = useState(project?.due_date?.split('T')[0] || '');
  66. const [priority, setPriority] = useState(project?.priority || 'normal');
  67. const [budget, setBudget] = useState(project?.budget?.toString() || '');
  68. const [url, setUrl] = useState(project?.url || '');
  69. const [urlError, setUrlError] = useState<string | null>(null);
  70. const [parentId, setParentId] = useState<number | null>(project?.parent_id ?? null);
  71. const queryClient = useQueryClient();
  72. // Unfiltered on purpose: a completed or archived project is still a legal
  73. // parent, and the picker offering fewer options than the list does would be
  74. // hard to explain.
  75. const { data: allProjects } = useQuery({
  76. queryKey: ['projects', undefined],
  77. queryFn: () => api.getProjects(),
  78. });
  79. const parentOptions = eligibleParents(allProjects || [], project?.id);
  80. const [coverImageFilename, setCoverImageFilename] = useState(project?.cover_image_filename || null);
  81. const coverFileInputRef = useRef<HTMLInputElement>(null);
  82. const [coverUploading, setCoverUploading] = useState(false);
  83. // Cache-bust the cover image URL when it changes mid-edit so the preview
  84. // refreshes after upload/remove.
  85. const [coverCacheKey, setCoverCacheKey] = useState(0);
  86. const handleCoverFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
  87. const file = e.target.files?.[0];
  88. if (!file || !project) return;
  89. setCoverUploading(true);
  90. try {
  91. const result = await api.uploadProjectCoverImage(project.id, file);
  92. setCoverImageFilename(result.filename);
  93. setCoverCacheKey((k) => k + 1);
  94. queryClient.invalidateQueries({ queryKey: ['projects'] });
  95. } catch {
  96. // Upload failed — leave existing cover image in place.
  97. } finally {
  98. setCoverUploading(false);
  99. if (coverFileInputRef.current) coverFileInputRef.current.value = '';
  100. }
  101. };
  102. const handleRemoveCover = async () => {
  103. if (!project) return;
  104. setCoverUploading(true);
  105. try {
  106. await api.deleteProjectCoverImage(project.id);
  107. setCoverImageFilename(null);
  108. setCoverCacheKey((k) => k + 1);
  109. queryClient.invalidateQueries({ queryKey: ['projects'] });
  110. } finally {
  111. setCoverUploading(false);
  112. }
  113. };
  114. const handleSubmit = (e: React.FormEvent) => {
  115. e.preventDefault();
  116. const trimmedUrl = url.trim();
  117. if (trimmedUrl && !/^https?:\/\//i.test(trimmedUrl)) {
  118. setUrlError(t('projects.urlInvalid'));
  119. return;
  120. }
  121. setUrlError(null);
  122. onSave({
  123. name: name.trim(),
  124. description: description.trim() || undefined,
  125. color,
  126. target_count: targetCount ? parseInt(targetCount, 10) : undefined,
  127. target_parts_count: targetPartsCount ? parseInt(targetPartsCount, 10) : undefined,
  128. // Null clears the copies-per-file target on edit (#1897); undefined omits on create.
  129. target_sets: project ? (targetSets ? parseInt(targetSets, 10) : null) : (targetSets ? parseInt(targetSets, 10) : undefined),
  130. // Null clears the stored value on edit; undefined omits the key on create.
  131. // Sending undefined on edit would make an emptied field un-clearable.
  132. tags: project ? (tags.trim() || null) : (tags.trim() || undefined),
  133. due_date: project ? (dueDate || null) : (dueDate || undefined),
  134. priority,
  135. budget: budget.trim() ? parseFloat(budget) : null,
  136. // Pydantic accepts null to clear the URL; an empty string would fail the
  137. // http(s) prefix validator.
  138. url: project ? (trimmedUrl || null) : (trimmedUrl || undefined),
  139. // The API reads 0 as "remove the parent" — null would be indistinguishable
  140. // from the field having been omitted (#1264).
  141. parent_id: project ? (parentId ?? 0) : (parentId ?? undefined),
  142. ...(project && { status }),
  143. });
  144. };
  145. return (
  146. // max-h + flex column on the card + overflow on the fields wrapper so the
  147. // modal stays inside the viewport on short screens (#1642). Outer p-4 is
  148. // 1rem each side, hence the 2rem subtraction below.
  149. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  150. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary flex flex-col max-h-[calc(100vh-2rem)]">
  151. <div className="p-4 border-b border-bambu-dark-tertiary flex-shrink-0">
  152. <h2 className="text-lg font-semibold text-white">
  153. {project ? t('projects.editProject') : t('projects.newProject')}
  154. </h2>
  155. </div>
  156. <form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
  157. <div className="p-4 space-y-4 overflow-y-auto flex-1">
  158. <div>
  159. <label className="block text-sm font-medium text-white mb-1">
  160. {t('common.name')}
  161. </label>
  162. <input
  163. type="text"
  164. value={name}
  165. onChange={(e) => setName(e.target.value)}
  166. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  167. placeholder={t('projects.namePlaceholder')}
  168. required
  169. />
  170. </div>
  171. <div>
  172. <label className="block text-sm font-medium text-white mb-1">
  173. {t('common.description')}
  174. </label>
  175. <textarea
  176. value={description}
  177. onChange={(e) => setDescription(e.target.value)}
  178. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none"
  179. placeholder={t('projects.descriptionPlaceholder')}
  180. rows={2}
  181. />
  182. </div>
  183. {/* #1155: External URL */}
  184. <div>
  185. <label className="block text-sm font-medium text-white mb-1">
  186. {t('projects.urlLabel')}
  187. </label>
  188. <input
  189. type="url"
  190. value={url}
  191. onChange={(e) => { setUrl(e.target.value); if (urlError) setUrlError(null); }}
  192. className={`w-full bg-bambu-dark border rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none ${
  193. urlError ? 'border-red-500 focus:border-red-500' : 'border-bambu-dark-tertiary focus:border-bambu-green'
  194. }`}
  195. placeholder={t('projects.urlPlaceholder')}
  196. maxLength={2048}
  197. />
  198. {urlError && <p className="text-xs text-red-600 dark:text-red-400 mt-1">{urlError}</p>}
  199. </div>
  200. {/* #1264: Nest this project under another one */}
  201. <div>
  202. <label className="block text-sm font-medium text-white mb-1">
  203. {t('projects.parentLabel')}
  204. </label>
  205. <select
  206. value={parentId ?? ''}
  207. onChange={(e) => setParentId(e.target.value ? parseInt(e.target.value, 10) : null)}
  208. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"
  209. >
  210. <option value="">{t('projects.parentNone')}</option>
  211. {parentOptions.map((option) => (
  212. <option key={option.id} value={option.id}>
  213. {option.name}
  214. </option>
  215. ))}
  216. </select>
  217. <p className="text-xs text-bambu-gray mt-1">{t('projects.parentHint')}</p>
  218. </div>
  219. {/* #1155: Cover image — only available when editing an existing project,
  220. since uploading needs a project_id. New projects can add it after save. */}
  221. {project && (
  222. <div>
  223. <label className="block text-sm font-medium text-white mb-1">
  224. {t('projects.coverImageLabel')}
  225. </label>
  226. <div className="flex items-center gap-3">
  227. <div className="w-20 h-20 rounded bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden flex items-center justify-center flex-shrink-0">
  228. {coverImageFilename ? (
  229. <img
  230. src={`${api.getProjectCoverImageUrl(project.id)}?v=${coverCacheKey}`}
  231. alt={t('projects.coverImageAlt')}
  232. className="w-full h-full object-cover"
  233. />
  234. ) : (
  235. <ImageIcon className="w-6 h-6 text-bambu-gray" />
  236. )}
  237. </div>
  238. <div className="flex flex-col gap-2">
  239. <input
  240. ref={coverFileInputRef}
  241. type="file"
  242. accept="image/jpeg,image/png,image/gif,image/webp"
  243. onChange={handleCoverFileChange}
  244. className="hidden"
  245. />
  246. <Button
  247. type="button"
  248. variant="secondary"
  249. onClick={() => coverFileInputRef.current?.click()}
  250. disabled={coverUploading}
  251. >
  252. {coverUploading ? (
  253. <Loader2 className="w-4 h-4 animate-spin" />
  254. ) : (
  255. <Upload className="w-4 h-4 mr-1" />
  256. )}
  257. {coverImageFilename ? t('projects.coverImageReplace') : t('projects.coverImageUpload')}
  258. </Button>
  259. {coverImageFilename && (
  260. <Button
  261. type="button"
  262. variant="secondary"
  263. onClick={handleRemoveCover}
  264. disabled={coverUploading}
  265. >
  266. <X className="w-4 h-4 mr-1" />
  267. {t('projects.coverImageRemove')}
  268. </Button>
  269. )}
  270. </div>
  271. </div>
  272. </div>
  273. )}
  274. <div>
  275. <label className="block text-sm font-medium text-white mb-1">
  276. {t('projects.color')}
  277. </label>
  278. <div className="flex gap-2 flex-wrap">
  279. {PROJECT_COLORS.map((c) => (
  280. <button
  281. key={c}
  282. type="button"
  283. onClick={() => setColor(c)}
  284. className={`w-8 h-8 rounded-full transition-transform ${
  285. color === c ? 'ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110' : ''
  286. }`}
  287. style={{ backgroundColor: c }}
  288. />
  289. ))}
  290. </div>
  291. </div>
  292. {/* Target Counts - Plates and Parts side by side */}
  293. <div className="grid grid-cols-2 gap-4">
  294. <div>
  295. <label className="block text-sm font-medium text-white mb-1">
  296. {t('projects.targetPlates')}
  297. </label>
  298. <input
  299. type="number"
  300. value={targetCount}
  301. onChange={(e) => setTargetCount(e.target.value)}
  302. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  303. placeholder={t('projects.targetPlatesPlaceholder')}
  304. min="1"
  305. />
  306. <p className="text-xs text-bambu-gray mt-1">{t('projects.targetPlatesHelp')}</p>
  307. </div>
  308. <div>
  309. <label className="block text-sm font-medium text-white mb-1">
  310. {t('projects.targetParts')}
  311. </label>
  312. <input
  313. type="number"
  314. value={targetPartsCount}
  315. onChange={(e) => setTargetPartsCount(e.target.value)}
  316. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  317. placeholder={t('projects.targetPartsPlaceholder')}
  318. min="1"
  319. />
  320. <p className="text-xs text-bambu-gray mt-1">{t('projects.targetPartsHelp')}</p>
  321. </div>
  322. </div>
  323. {/* Copies-per-file target (#1897) */}
  324. <div>
  325. <label className="block text-sm font-medium text-white mb-1">
  326. {t('projects.targetSets')}
  327. </label>
  328. <input
  329. type="number"
  330. value={targetSets}
  331. onChange={(e) => setTargetSets(e.target.value)}
  332. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  333. placeholder={t('projects.targetSetsPlaceholder')}
  334. min="1"
  335. />
  336. <p className="text-xs text-bambu-gray mt-1">{t('projects.targetSetsHelp')}</p>
  337. </div>
  338. {/* Tags */}
  339. <div>
  340. <label className="block text-sm font-medium text-white mb-1">
  341. {t('projects.tagsLabel')}
  342. </label>
  343. <input
  344. type="text"
  345. value={tags}
  346. onChange={(e) => setTags(e.target.value)}
  347. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  348. placeholder={t('projects.tagsPlaceholder')}
  349. />
  350. </div>
  351. {/* Due Date and Priority in a row */}
  352. <div className="grid grid-cols-2 gap-4">
  353. <div>
  354. <label className="block text-sm font-medium text-white mb-1">
  355. {t('projects.dueDate')}
  356. </label>
  357. <input
  358. type="date"
  359. value={dueDate}
  360. onChange={(e) => setDueDate(e.target.value)}
  361. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"
  362. />
  363. </div>
  364. <div>
  365. <label className="block text-sm font-medium text-white mb-1">
  366. {t('projects.priority')}
  367. </label>
  368. <select
  369. value={priority}
  370. onChange={(e) => setPriority(e.target.value)}
  371. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"
  372. >
  373. <option value="low">{t('projects.priorityLow')}</option>
  374. <option value="normal">{t('projects.priorityNormal')}</option>
  375. <option value="high">{t('projects.priorityHigh')}</option>
  376. <option value="urgent">{t('projects.priorityUrgent')}</option>
  377. </select>
  378. </div>
  379. </div>
  380. <div>
  381. <label className="block text-sm font-medium text-white mb-1">
  382. {t('projectDetail.cost.budget')}
  383. </label>
  384. <div className="relative">
  385. <span className="absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none">
  386. {currencySymbol}
  387. </span>
  388. <input
  389. type="number"
  390. step="0.01"
  391. min="0"
  392. value={budget}
  393. onChange={(e) => setBudget(e.target.value)}
  394. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  395. placeholder="0.00"
  396. />
  397. </div>
  398. </div>
  399. {project && (
  400. <div>
  401. <label className="block text-sm font-medium text-white mb-1">
  402. {t('common.status')}
  403. </label>
  404. <select
  405. value={status}
  406. onChange={(e) => setStatus(e.target.value)}
  407. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"
  408. >
  409. <option value="active">{t('projects.statusActive')}</option>
  410. <option value="completed">{t('projects.statusCompleted')}</option>
  411. <option value="archived">{t('projects.statusArchived')}</option>
  412. </select>
  413. </div>
  414. )}
  415. </div>
  416. {/* Sticky action footer — stays visible regardless of scroll
  417. position so Save/Cancel are always reachable on short screens
  418. (#1642). Buttons stay inside <form> for type="submit". */}
  419. <div className="flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0">
  420. <Button type="button" variant="secondary" onClick={onClose}>
  421. {t('common.cancel')}
  422. </Button>
  423. <Button type="submit" disabled={!name.trim() || isLoading}>
  424. {isLoading ? (
  425. <Loader2 className="w-4 h-4 animate-spin" />
  426. ) : project ? (
  427. t('common.save')
  428. ) : (
  429. t('projects.create')
  430. )}
  431. </Button>
  432. </div>
  433. </form>
  434. </div>
  435. </div>
  436. );
  437. }
  438. /**
  439. * Cover thumbnail with portal-rendered hover preview (#1155 follow-up).
  440. *
  441. * Why a portal: the parent ``ProjectCard`` carries ``overflow-hidden`` for
  442. * its rounded-corner clipping and color accent bar; an in-tree popover
  443. * gets clipped by that and only the part that overlaps the card is
  444. * visible. Rendering the preview via ``createPortal`` to ``document.body``
  445. * escapes every ancestor clipping context, and ``position: fixed`` with
  446. * ``getBoundingClientRect()`` keeps it pinned next to the thumbnail
  447. * regardless of where the card sits in the grid.
  448. */
  449. function ProjectCoverThumbnail({
  450. projectId,
  451. altText,
  452. }: {
  453. projectId: number;
  454. altText: string;
  455. }) {
  456. const thumbRef = useRef<HTMLDivElement>(null);
  457. const [hovered, setHovered] = useState(false);
  458. const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
  459. const handleEnter = () => {
  460. if (!thumbRef.current) return;
  461. const rect = thumbRef.current.getBoundingClientRect();
  462. // Anchor the 384px preview just to the right of the thumbnail (8px gap).
  463. // Clamp ``top`` so the preview never overflows the viewport vertically;
  464. // similar story for ``left`` if the card is near the right edge — flip
  465. // to the LEFT side of the thumbnail in that case.
  466. const PREVIEW = 384;
  467. const GAP = 8;
  468. const vw = window.innerWidth;
  469. const vh = window.innerHeight;
  470. let left = rect.right + GAP;
  471. if (left + PREVIEW > vw - 8) {
  472. left = rect.left - PREVIEW - GAP;
  473. }
  474. let top = rect.top;
  475. if (top + PREVIEW > vh - 8) {
  476. top = vh - PREVIEW - 8;
  477. }
  478. if (top < 8) top = 8;
  479. setPos({ left, top });
  480. setHovered(true);
  481. };
  482. const handleLeave = () => setHovered(false);
  483. return (
  484. <div
  485. ref={thumbRef}
  486. className="relative flex-shrink-0"
  487. onMouseEnter={handleEnter}
  488. onMouseLeave={handleLeave}
  489. onClick={(e) => e.stopPropagation()}
  490. >
  491. <div className="w-10 h-10 rounded-lg overflow-hidden bg-bambu-dark border border-bambu-dark-tertiary">
  492. <img
  493. src={api.getProjectCoverImageUrl(projectId)}
  494. alt={altText}
  495. className="w-full h-full object-cover"
  496. loading="lazy"
  497. />
  498. </div>
  499. {hovered && pos &&
  500. createPortal(
  501. <div
  502. className="fixed z-[100] w-96 h-96 rounded-lg overflow-hidden border border-bambu-dark-tertiary shadow-2xl bg-bambu-dark pointer-events-none"
  503. style={{ left: pos.left, top: pos.top }}
  504. aria-hidden="true"
  505. >
  506. <img
  507. src={api.getProjectCoverImageUrl(projectId)}
  508. alt=""
  509. className="w-full h-full object-contain"
  510. loading="lazy"
  511. />
  512. </div>,
  513. document.body,
  514. )}
  515. </div>
  516. );
  517. }
  518. interface ProjectCardProps {
  519. project: ProjectListItem;
  520. parentName?: string; // #1264 — resolved by the caller, which holds the whole list
  521. onClick: () => void;
  522. onEdit: () => void;
  523. onDelete: () => void;
  524. hasPermission: (permission: Permission) => boolean;
  525. t: TFunction;
  526. }
  527. function ProjectCard({ project, parentName, onClick, onEdit, onDelete, hasPermission, t }: ProjectCardProps) {
  528. // Plates progress: archive_count / target_count
  529. const platesProgressPercent = project.target_count
  530. ? Math.round((project.archive_count / project.target_count) * 100)
  531. : 0;
  532. // Parts progress: completed_count / target_parts_count
  533. const partsProgressPercent = project.target_parts_count
  534. ? Math.round((project.completed_count / project.target_parts_count) * 100)
  535. : 0;
  536. const isCompleted = project.status === 'completed';
  537. const isArchived = project.status === 'archived';
  538. const [showActions, setShowActions] = useState(false);
  539. // Status icon and color
  540. const getStatusConfig = () => {
  541. if (isCompleted) return { icon: CheckCircle2, color: 'text-bambu-green', bg: 'bg-bambu-green/10' };
  542. if (isArchived) return { icon: Archive, color: 'text-bambu-gray', bg: 'bg-bambu-gray/10' };
  543. if (project.queue_count > 0) return { icon: Clock, color: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-400/10' };
  544. return { icon: FolderKanban, color: 'text-bambu-gray', bg: 'bg-bambu-gray/10' };
  545. };
  546. const statusConfig = getStatusConfig();
  547. return (
  548. <div
  549. className="group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden"
  550. onClick={onClick}
  551. >
  552. {/* Color accent bar with glow */}
  553. <div
  554. className="absolute top-0 left-0 w-1.5 h-full"
  555. style={{
  556. backgroundColor: project.color || '#6b7280',
  557. boxShadow: `0 0 12px ${project.color || '#6b7280'}40`
  558. }}
  559. />
  560. <div className="p-5 pl-6">
  561. {/* Header */}
  562. <div className="flex items-start justify-between mb-4">
  563. <div className="flex items-center gap-3 min-w-0 flex-1">
  564. {project.cover_image_filename ? (
  565. // #1155: cover photo replaces the status-icon box. The thumbnail
  566. // itself stays small so the card layout doesn't shift; on hover
  567. // a portal-rendered 384×384 preview pops out beside the card
  568. // so the user can identify the print without navigating into
  569. // the project view. The portal is needed because ProjectCard's
  570. // own ``overflow-hidden`` (for rounded corners) clips any
  571. // in-tree popover before it can extend outside the card.
  572. <ProjectCoverThumbnail
  573. projectId={project.id}
  574. altText={t('projects.coverImageAlt')}
  575. />
  576. ) : (
  577. <div className={`p-2 rounded-lg ${statusConfig.bg} flex-shrink-0`}>
  578. <statusConfig.icon className={`w-5 h-5 ${statusConfig.color}`} />
  579. </div>
  580. )}
  581. <div className="min-w-0 flex-1">
  582. <div className="flex items-center gap-2 flex-wrap">
  583. <h3 className="font-semibold text-white truncate">{project.name}</h3>
  584. {project.url && (
  585. <a
  586. href={project.url}
  587. target="_blank"
  588. rel="noopener noreferrer"
  589. onClick={(e) => e.stopPropagation()}
  590. title={project.url}
  591. aria-label={t('projects.openExternalUrl')}
  592. className="inline-flex items-center justify-center w-6 h-6 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-green hover:bg-bambu-green/10 hover:border-bambu-green transition-colors flex-shrink-0"
  593. >
  594. <ExternalLink className="w-3.5 h-3.5" />
  595. </a>
  596. )}
  597. {project.target_parts_count ? (
  598. <span className={`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${
  599. partsProgressPercent >= 100
  600. ? 'bg-bambu-green/20 text-bambu-green'
  601. : 'bg-bambu-dark text-bambu-gray'
  602. }`}>
  603. {project.completed_count}/{project.target_parts_count} {t('projects.parts')}
  604. </span>
  605. ) : project.target_count ? (
  606. <span className={`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${
  607. platesProgressPercent >= 100
  608. ? 'bg-bambu-green/20 text-bambu-green'
  609. : 'bg-bambu-dark text-bambu-gray'
  610. }`}>
  611. {project.archive_count}/{project.target_count} {t('projects.plates')}
  612. </span>
  613. ) : project.completed_count > 0 ? (
  614. <span className="text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray">
  615. {project.completed_count} {t('projects.parts')}
  616. </span>
  617. ) : null}
  618. {isCompleted && (
  619. <span className="text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap">
  620. {t('projects.done')}
  621. </span>
  622. )}
  623. {isArchived && (
  624. <span className="text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap">
  625. {t('projects.statusArchived')}
  626. </span>
  627. )}
  628. {/* #1264: without these, eight sub-projects of one programme
  629. look like eight unrelated projects in the grid. */}
  630. {project.child_count > 0 && (
  631. <span
  632. className="text-xs bg-bambu-dark text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap inline-flex items-center gap-1"
  633. title={t('projects.subProjectCount', { count: project.child_count })}
  634. >
  635. <FolderTree className="w-3 h-3" />
  636. {project.child_count}
  637. </span>
  638. )}
  639. </div>
  640. {parentName && (
  641. <p className="text-xs text-bambu-gray mt-1 flex items-center gap-1">
  642. <Layers className="w-3 h-3 flex-shrink-0" />
  643. <span className="truncate">{t('projects.partOf', { name: parentName })}</span>
  644. </p>
  645. )}
  646. {project.description && (
  647. <p className="text-sm text-bambu-gray/70 mt-1 line-clamp-1">
  648. {project.description}
  649. </p>
  650. )}
  651. {/* Filament materials/colors */}
  652. {project.archives && project.archives.length > 0 && (() => {
  653. // Flatten comma-separated materials and deduplicate
  654. const allMaterials = project.archives
  655. .map(a => a.filament_type)
  656. .filter(Boolean)
  657. .flatMap(m => (m as string).split(',').map(s => s.trim()))
  658. .filter(Boolean);
  659. const materials = [...new Set(allMaterials)];
  660. // Flatten comma-separated colors and deduplicate
  661. const allColors = project.archives
  662. .map(a => a.filament_color)
  663. .filter(Boolean)
  664. .flatMap(c => (c as string).split(',').map(s => s.trim()))
  665. .filter(c => c.startsWith('#') || /^[0-9A-Fa-f]{6}$/.test(c));
  666. const colors = [...new Set(allColors)];
  667. if (materials.length === 0 && colors.length === 0) return null;
  668. return (
  669. <div className="flex items-center gap-2 mt-1.5">
  670. {/* Material types as text badges */}
  671. {materials.slice(0, 3).map((mat) => (
  672. <span key={mat} className="text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded">
  673. {mat}
  674. </span>
  675. ))}
  676. {/* Colors as swatches */}
  677. {colors.length > 0 && (
  678. <div className="flex items-center gap-0.5">
  679. {colors.slice(0, 5).map((col) => (
  680. <div
  681. key={col}
  682. className="w-3 h-3 rounded-full border border-black/20"
  683. style={{ backgroundColor: col.startsWith('#') ? col : `#${col}` }}
  684. title={col}
  685. />
  686. ))}
  687. {colors.length > 5 && (
  688. <span className="text-[10px] text-bambu-gray ml-0.5">+{colors.length - 5}</span>
  689. )}
  690. </div>
  691. )}
  692. </div>
  693. );
  694. })()}
  695. </div>
  696. </div>
  697. {/* Actions menu */}
  698. <div className="relative" onClick={(e) => e.stopPropagation()}>
  699. <button
  700. className="p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors can-hover:opacity-0 group-hover:opacity-100 focus-visible:opacity-100"
  701. onClick={() => setShowActions(!showActions)}
  702. >
  703. <MoreVertical className="w-4 h-4" />
  704. </button>
  705. {showActions && (
  706. <>
  707. <div className="fixed inset-0 z-10" onClick={() => setShowActions(false)} />
  708. <div className="absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]">
  709. <button
  710. className={`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${
  711. hasPermission('projects:update') ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  712. }`}
  713. onClick={() => { if (hasPermission('projects:update')) { onEdit(); setShowActions(false); } }}
  714. disabled={!hasPermission('projects:update')}
  715. title={!hasPermission('projects:update') ? t('projects.noEditPermission') : undefined}
  716. >
  717. <Edit3 className="w-4 h-4" />
  718. {t('common.edit')}
  719. </button>
  720. <button
  721. className={`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${
  722. hasPermission('projects:delete') ? 'text-red-600 dark:text-red-400 hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  723. }`}
  724. onClick={() => { if (hasPermission('projects:delete')) { onDelete(); setShowActions(false); } }}
  725. disabled={!hasPermission('projects:delete')}
  726. title={!hasPermission('projects:delete') ? t('projects.noDeletePermission') : undefined}
  727. >
  728. <Trash2 className="w-4 h-4" />
  729. {t('common.delete')}
  730. </button>
  731. </div>
  732. </>
  733. )}
  734. </div>
  735. </div>
  736. {/* Progress section - show for all projects */}
  737. <div className="mb-4">
  738. {(project.target_count || project.target_parts_count) ? (
  739. <div className="space-y-3">
  740. {/* Plates progress */}
  741. {project.target_count && (
  742. <div>
  743. <div className="flex items-center justify-between text-xs mb-1">
  744. <span className="text-bambu-gray">{t('projects.plates')}</span>
  745. <span className={platesProgressPercent >= 100 ? 'text-bambu-green font-medium' : 'text-white'}>
  746. {project.archive_count} / {project.target_count}
  747. </span>
  748. </div>
  749. <div className="h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm">
  750. <div
  751. className="h-full transition-all duration-500 ease-out rounded-full relative"
  752. style={{
  753. width: `${Math.min(platesProgressPercent, 100)}%`,
  754. background: platesProgressPercent >= 100
  755. ? 'linear-gradient(90deg, #22c55e, #4ade80)'
  756. : `linear-gradient(90deg, ${project.color || '#6b7280'}, ${project.color || '#6b7280'}cc)`,
  757. boxShadow: `0 0 8px ${platesProgressPercent >= 100 ? '#22c55e' : project.color || '#6b7280'}60`
  758. }}
  759. />
  760. </div>
  761. </div>
  762. )}
  763. {/* Parts progress */}
  764. {project.target_parts_count && (
  765. <div>
  766. <div className="flex items-center justify-between text-xs mb-1">
  767. <span className="text-bambu-gray">{t('projects.parts')}</span>
  768. <span className={partsProgressPercent >= 100 ? 'text-bambu-green font-medium' : 'text-white'}>
  769. {project.completed_count} / {project.target_parts_count}
  770. </span>
  771. </div>
  772. <div className="h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm">
  773. <div
  774. className="h-full transition-all duration-500 ease-out rounded-full relative"
  775. style={{
  776. width: `${Math.min(partsProgressPercent, 100)}%`,
  777. background: partsProgressPercent >= 100
  778. ? 'linear-gradient(90deg, #22c55e, #4ade80)'
  779. : `linear-gradient(90deg, ${project.color || '#6b7280'}, ${project.color || '#6b7280'}cc)`,
  780. boxShadow: `0 0 8px ${partsProgressPercent >= 100 ? '#22c55e' : project.color || '#6b7280'}60`
  781. }}
  782. />
  783. </div>
  784. </div>
  785. )}
  786. {/* Failed count */}
  787. {project.failed_count > 0 && (
  788. <div className="text-xs text-red-600 dark:text-red-400">
  789. {project.failed_count} {t('projects.failed')}
  790. </div>
  791. )}
  792. </div>
  793. ) : project.completed_count > 0 || project.failed_count > 0 ? (
  794. <div className="flex items-center gap-4 text-xs">
  795. {project.completed_count > 0 && (
  796. <div className="flex items-center gap-1.5 text-bambu-gray">
  797. <Archive className="w-3.5 h-3.5" />
  798. <span>{project.completed_count} {t('projects.completed')}</span>
  799. </div>
  800. )}
  801. {project.failed_count > 0 && (
  802. <div className="flex items-center gap-1.5 text-red-600 dark:text-red-400">
  803. <AlertTriangle className="w-3.5 h-3.5" />
  804. <span>{project.failed_count} {t('projects.failed')}</span>
  805. </div>
  806. )}
  807. {project.queue_count > 0 && (
  808. <div className="flex items-center gap-1.5 text-blue-600 dark:text-blue-400">
  809. <Clock className="w-3.5 h-3.5" />
  810. <span>{project.queue_count} {t('projects.inQueue')}</span>
  811. </div>
  812. )}
  813. </div>
  814. ) : (
  815. <div className="text-xs text-bambu-gray/60 italic">
  816. {t('projects.noPrintsYet')}
  817. </div>
  818. )}
  819. </div>
  820. {/* Archive thumbnails - compact 4-column grid */}
  821. {project.archives && project.archives.length > 0 && (
  822. <div className="mb-4">
  823. <div className="grid grid-cols-4 gap-1.5">
  824. {project.archives.slice(0, 4).map((archive) => (
  825. <div
  826. key={archive.id}
  827. className="relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary"
  828. title={archive.print_name || 'Unknown'}
  829. >
  830. {archive.thumbnail_path ? (
  831. <img
  832. src={api.getArchiveThumbnail(archive.id)}
  833. alt={archive.print_name || ''}
  834. className="w-full h-full object-cover"
  835. />
  836. ) : (
  837. <div className="w-full h-full flex items-center justify-center text-bambu-gray/50">
  838. <Package className="w-6 h-6" />
  839. </div>
  840. )}
  841. {archive.status === 'failed' && (
  842. <div className="absolute inset-0 bg-red-500/40 flex items-center justify-center">
  843. <AlertTriangle className="w-4 h-4 text-white" />
  844. </div>
  845. )}
  846. </div>
  847. ))}
  848. </div>
  849. {project.archive_count > 4 && (
  850. <p className="text-xs text-bambu-gray mt-1.5 text-center">
  851. {t('common.more', { count: project.archive_count - 4 })}
  852. </p>
  853. )}
  854. </div>
  855. )}
  856. {/* Stats footer */}
  857. <div className="flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary">
  858. <div className="flex items-center gap-4 text-xs text-bambu-gray">
  859. <div className="flex items-center gap-1.5" title={t('projects.printJobs')}>
  860. <Layers className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400" />
  861. <span>{project.archive_count} {t('projects.plates')}</span>
  862. </div>
  863. <div className="flex items-center gap-1.5" title={t('projects.partsPrinted')}>
  864. <Package className="w-3.5 h-3.5 text-bambu-green" />
  865. <span>{project.completed_count} {t('projects.parts')}</span>
  866. </div>
  867. {project.failed_count > 0 && (
  868. <div className="flex items-center gap-1.5 text-red-600 dark:text-red-400" title={t('projects.failedParts')}>
  869. <AlertTriangle className="w-3.5 h-3.5" />
  870. <span>{project.failed_count}</span>
  871. </div>
  872. )}
  873. {project.queue_count > 0 && (
  874. <div className="flex items-center gap-1.5 text-yellow-600 dark:text-yellow-400" title={t('projects.inQueue')}>
  875. <ListTodo className="w-3.5 h-3.5" />
  876. <span>{project.queue_count}</span>
  877. </div>
  878. )}
  879. </div>
  880. <ChevronRight className="w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors" />
  881. </div>
  882. </div>
  883. </div>
  884. );
  885. }
  886. export function ProjectsPage() {
  887. const { t } = useTranslation();
  888. const navigate = useNavigate();
  889. const queryClient = useQueryClient();
  890. const { showToast } = useToast();
  891. const { hasPermission } = useAuth();
  892. const [showModal, setShowModal] = useState(false);
  893. const [editingProject, setEditingProject] = useState<ProjectListItem | undefined>();
  894. const [statusFilter, setStatusFilter] = useState<string>('active');
  895. const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
  896. const { data: settings } = useQuery({
  897. queryKey: ['settings'],
  898. queryFn: api.getSettings,
  899. });
  900. const currencySymbol = getCurrencySymbol(settings?.currency || 'USD');
  901. const { data: projects, isLoading } = useQuery({
  902. queryKey: ['projects', statusFilter === 'all' ? undefined : statusFilter],
  903. queryFn: () => api.getProjects(statusFilter === 'all' ? undefined : statusFilter),
  904. });
  905. // Parent names come from the unfiltered list, so a sub-project still says
  906. // what it belongs to when the status filter has hidden its parent (#1264).
  907. // Same query key the parent picker uses — one request shared between them,
  908. // and the same one as above whenever the filter is 'all'.
  909. const { data: allProjects } = useQuery({
  910. queryKey: ['projects', undefined],
  911. queryFn: () => api.getProjects(),
  912. });
  913. const namesById = new Map((allProjects || []).map((p) => [p.id, p.name]));
  914. // A sub-project is drawn inside its parent's group rather than as another
  915. // card somewhere in the grid — two cards that belong together are not
  916. // something a caption can convey when they sit columns apart (#1264).
  917. const visible = projects || [];
  918. const visibleIds = new Set(visible.map((p) => p.id));
  919. const childrenByParent = new Map<number, ProjectListItem[]>();
  920. for (const project of visible) {
  921. // Parent hidden by the status filter: the child has nothing to nest under
  922. // here, so it stays a top-level card and keeps its "part of" caption.
  923. if (project.parent_id !== null && visibleIds.has(project.parent_id)) {
  924. const siblings = childrenByParent.get(project.parent_id) || [];
  925. siblings.push(project);
  926. childrenByParent.set(project.parent_id, siblings);
  927. }
  928. }
  929. // Everything drawn at the top of the grid, in order. Roots first, then any
  930. // project the roots cannot reach: a database written before the API refused
  931. // A -> B -> A can still hold a cycle, and a cycle has no root, so filtering
  932. // on "has no visible parent" alone would drop every project in it off the
  933. // page. Each entry point marks its whole branch as drawn, so nothing appears
  934. // twice either.
  935. const drawn = new Set<number>();
  936. const markDrawn = (id: number) => {
  937. if (drawn.has(id)) return;
  938. drawn.add(id);
  939. for (const child of childrenByParent.get(id) || []) markDrawn(child.id);
  940. };
  941. const topLevel: ProjectListItem[] = [];
  942. for (const project of visible) {
  943. if (project.parent_id !== null && visibleIds.has(project.parent_id)) continue;
  944. topLevel.push(project);
  945. markDrawn(project.id);
  946. }
  947. for (const project of visible) {
  948. if (drawn.has(project.id)) continue;
  949. topLevel.push(project);
  950. markDrawn(project.id);
  951. }
  952. const renderProjectTree = (project: ProjectListItem, depth: number, seen: Set<number>) => {
  953. const card = (
  954. <ProjectCard
  955. project={project}
  956. // Only when it is detached from its parent — inside the group the
  957. // nesting is already visible, and the caption would be noise.
  958. parentName={depth === 0 && project.parent_id !== null ? namesById.get(project.parent_id) : undefined}
  959. onClick={() => handleClick(project)}
  960. onEdit={() => handleEdit(project)}
  961. onDelete={() => handleDeleteClick(project.id)}
  962. hasPermission={hasPermission}
  963. t={t}
  964. />
  965. );
  966. // Drop any child that is already an ancestor on this path. A database
  967. // written before the API refused A -> B -> A can still hold a cycle, and
  968. // following one would draw the same project over and over.
  969. const descended = new Set(seen).add(project.id);
  970. const children = (childrenByParent.get(project.id) || []).filter((c) => !descended.has(c.id));
  971. if (children.length === 0) return <div key={project.id}>{card}</div>;
  972. return (
  973. <div key={project.id} className="col-span-full space-y-4">
  974. {card}
  975. <div
  976. className="ml-4 md:ml-8 pl-4 md:pl-6 border-l-2 rounded-l space-y-4"
  977. style={{ borderColor: project.color || '#6b7280' }}
  978. >
  979. <p className="text-xs uppercase tracking-wide text-bambu-gray flex items-center gap-1.5">
  980. <FolderTree className="w-3.5 h-3.5" />
  981. {t('projects.subProjectsOf', { name: project.name })}
  982. </p>
  983. <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
  984. {children.map((child) => renderProjectTree(child, depth + 1, descended))}
  985. </div>
  986. </div>
  987. </div>
  988. );
  989. };
  990. const createMutation = useMutation({
  991. mutationFn: (data: ProjectCreate) => api.createProject(data),
  992. onSuccess: () => {
  993. queryClient.invalidateQueries({ queryKey: ['projects'] });
  994. setShowModal(false);
  995. showToast(t('projects.toast.created'), 'success');
  996. },
  997. onError: (error: Error) => {
  998. showToast(error.message, 'error');
  999. },
  1000. });
  1001. const updateMutation = useMutation({
  1002. mutationFn: ({ id, data }: { id: number; data: ProjectUpdate }) =>
  1003. api.updateProject(id, data),
  1004. onSuccess: () => {
  1005. queryClient.invalidateQueries({ queryKey: ['projects'] });
  1006. setShowModal(false);
  1007. setEditingProject(undefined);
  1008. showToast(t('projects.toast.updated'), 'success');
  1009. },
  1010. onError: (error: Error) => {
  1011. showToast(error.message, 'error');
  1012. },
  1013. });
  1014. const deleteMutation = useMutation({
  1015. mutationFn: (id: number) => api.deleteProject(id),
  1016. onSuccess: () => {
  1017. setDeleteConfirm(null);
  1018. showToast(t('projects.toast.deleted'), 'success');
  1019. // Reload to refresh the list (React Query cache invalidation not working reliably)
  1020. setTimeout(() => window.location.reload(), 100);
  1021. },
  1022. onError: (error: Error) => {
  1023. setDeleteConfirm(null);
  1024. showToast(error.message, 'error');
  1025. },
  1026. });
  1027. const importMutation = useMutation({
  1028. mutationFn: (data: ProjectImport) => api.importProject(data),
  1029. onSuccess: () => {
  1030. queryClient.invalidateQueries({ queryKey: ['projects'] });
  1031. showToast(t('projects.toast.imported'), 'success');
  1032. },
  1033. onError: (error: Error) => {
  1034. showToast(error.message, 'error');
  1035. },
  1036. });
  1037. const fileInputRef = useRef<HTMLInputElement>(null);
  1038. const handleExportAll = async () => {
  1039. try {
  1040. // Export all projects as JSON (metadata only, no files)
  1041. const allProjects = await api.getProjects();
  1042. const exports = await Promise.all(
  1043. allProjects.map(async (p) => {
  1044. const exported = await api.exportProjectJson(p.id);
  1045. return exported;
  1046. })
  1047. );
  1048. const blob = new Blob([JSON.stringify(exports, null, 2)], { type: 'application/json' });
  1049. const url = URL.createObjectURL(blob);
  1050. const a = document.createElement('a');
  1051. a.href = url;
  1052. a.download = `bambuddy_projects_${new Date().toISOString().split('T')[0]}.json`;
  1053. a.click();
  1054. URL.revokeObjectURL(url);
  1055. showToast(t('projects.toast.exported'), 'success');
  1056. } catch (error) {
  1057. showToast((error as Error).message, 'error');
  1058. }
  1059. };
  1060. const handleImportClick = () => {
  1061. fileInputRef.current?.click();
  1062. };
  1063. const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
  1064. const file = e.target.files?.[0];
  1065. if (!file) return;
  1066. try {
  1067. const filename = file.name.toLowerCase();
  1068. if (filename.endsWith('.zip')) {
  1069. // ZIP file: upload via file endpoint
  1070. await api.importProjectFile(file);
  1071. queryClient.invalidateQueries({ queryKey: ['projects'] });
  1072. showToast(t('projects.toast.imported'), 'success');
  1073. } else {
  1074. // JSON file: parse and handle bulk or single import
  1075. const text = await file.text();
  1076. const data = JSON.parse(text);
  1077. // Handle both single project and array of projects
  1078. const projectsToImport = Array.isArray(data) ? data : [data];
  1079. for (const project of projectsToImport) {
  1080. await importMutation.mutateAsync(project);
  1081. }
  1082. if (projectsToImport.length > 1) {
  1083. showToast(t('projects.toast.multipleImported', { count: projectsToImport.length }), 'success');
  1084. }
  1085. }
  1086. } catch (error) {
  1087. showToast(`${t('projects.toast.importFailed')}: ${(error as Error).message}`, 'error');
  1088. }
  1089. // Reset file input
  1090. e.target.value = '';
  1091. };
  1092. const handleSave = (data: ProjectCreate | ProjectUpdate) => {
  1093. if (editingProject) {
  1094. updateMutation.mutate({ id: editingProject.id, data });
  1095. } else {
  1096. createMutation.mutate(data as ProjectCreate);
  1097. }
  1098. };
  1099. const handleEdit = (project: ProjectListItem) => {
  1100. setEditingProject(project);
  1101. setShowModal(true);
  1102. };
  1103. const handleClick = (project: ProjectListItem) => {
  1104. // Navigate to project detail page
  1105. navigate(`/projects/${project.id}`);
  1106. };
  1107. const handleDeleteClick = (id: number) => {
  1108. setDeleteConfirm(id);
  1109. };
  1110. const handleDeleteConfirm = () => {
  1111. if (deleteConfirm !== null) {
  1112. deleteMutation.mutate(deleteConfirm);
  1113. }
  1114. };
  1115. // Count projects by status for filter badges
  1116. const projectCounts = projects?.reduce((acc, p) => {
  1117. acc[p.status] = (acc[p.status] || 0) + 1;
  1118. acc.all = (acc.all || 0) + 1;
  1119. return acc;
  1120. }, {} as Record<string, number>) || {};
  1121. return (
  1122. <div className="p-4 md:p-8 space-y-8">
  1123. {/* Hidden file input for import */}
  1124. <input
  1125. ref={fileInputRef}
  1126. type="file"
  1127. accept=".json,.zip"
  1128. onChange={handleFileChange}
  1129. className="hidden"
  1130. />
  1131. {/* Header */}
  1132. <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
  1133. <div>
  1134. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  1135. <FolderKanban className="w-7 h-7 text-bambu-green" />
  1136. {t('projects.title')}
  1137. </h1>
  1138. <p className="text-bambu-gray mt-1">
  1139. {t('projects.subtitle')}
  1140. </p>
  1141. </div>
  1142. <div className="flex gap-2">
  1143. <Button
  1144. variant="secondary"
  1145. onClick={handleImportClick}
  1146. disabled={!hasPermission('projects:create')}
  1147. title={!hasPermission('projects:create') ? t('projects.noImportPermission') : t('projects.importProject')}
  1148. >
  1149. <Upload className="w-4 h-4 mr-2" />
  1150. {t('projects.import')}
  1151. </Button>
  1152. <Button
  1153. variant="secondary"
  1154. onClick={handleExportAll}
  1155. disabled={!hasPermission('projects:read')}
  1156. title={!hasPermission('projects:read') ? t('projects.noExportPermission') : t('projects.exportAll')}
  1157. >
  1158. <Download className="w-4 h-4 mr-2" />
  1159. {t('projects.export')}
  1160. </Button>
  1161. <Button
  1162. onClick={() => setShowModal(true)}
  1163. className="sm:w-auto w-full"
  1164. disabled={!hasPermission('projects:create')}
  1165. title={!hasPermission('projects:create') ? t('projects.noCreatePermission') : undefined}
  1166. >
  1167. <Plus className="w-4 h-4 mr-2" />
  1168. {t('projects.newProject')}
  1169. </Button>
  1170. </div>
  1171. </div>
  1172. {/* Filter tabs */}
  1173. <div className="flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit">
  1174. {[
  1175. { key: 'active', label: t('projects.statusActive'), icon: Clock },
  1176. { key: 'completed', label: t('projects.statusCompleted'), icon: CheckCircle2 },
  1177. { key: 'archived', label: t('projects.statusArchived'), icon: Archive },
  1178. { key: 'all', label: t('common.all'), icon: FolderKanban },
  1179. ].map(({ key, label, icon: Icon }) => (
  1180. <button
  1181. key={key}
  1182. onClick={() => setStatusFilter(key)}
  1183. className={`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${
  1184. statusFilter === key
  1185. ? 'bg-bambu-card text-white shadow-sm'
  1186. : 'text-bambu-gray hover:text-white'
  1187. }`}
  1188. >
  1189. <Icon className="w-4 h-4" />
  1190. <span>{label}</span>
  1191. {projectCounts[key] > 0 && (
  1192. <span className={`text-xs px-1.5 py-0.5 rounded-full ${
  1193. statusFilter === key ? 'bg-bambu-green/20 text-bambu-green' : 'bg-bambu-dark-tertiary'
  1194. }`}>
  1195. {projectCounts[key]}
  1196. </span>
  1197. )}
  1198. </button>
  1199. ))}
  1200. </div>
  1201. {/* Content */}
  1202. {isLoading ? (
  1203. <div className="flex items-center justify-center py-20">
  1204. <div className="flex flex-col items-center gap-3">
  1205. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  1206. <p className="text-sm text-bambu-gray">{t('projects.loading')}</p>
  1207. </div>
  1208. </div>
  1209. ) : projects?.length === 0 ? (
  1210. <div className="flex flex-col items-center justify-center py-20 px-4">
  1211. <div className="p-4 bg-bambu-dark rounded-2xl mb-4">
  1212. <FolderKanban className="w-12 h-12 text-bambu-gray/50" />
  1213. </div>
  1214. <h3 className="text-lg font-medium text-white mb-2">
  1215. {statusFilter === 'all' ? t('projects.noProjects') : t('projects.noProjectsFiltered', { status: statusFilter })}
  1216. </h3>
  1217. <p className="text-bambu-gray text-center max-w-md mb-6">
  1218. {statusFilter === 'all'
  1219. ? t('projects.createFirst')
  1220. : t('projects.noProjectsFilteredHelp', { status: statusFilter })
  1221. }
  1222. </p>
  1223. {statusFilter === 'all' && (
  1224. <Button
  1225. onClick={() => setShowModal(true)}
  1226. disabled={!hasPermission('projects:create')}
  1227. title={!hasPermission('projects:create') ? t('projects.noCreatePermission') : undefined}
  1228. >
  1229. <Plus className="w-4 h-4 mr-2" />
  1230. {t('projects.createFirstButton')}
  1231. </Button>
  1232. )}
  1233. </div>
  1234. ) : (
  1235. <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8">
  1236. {topLevel.map((project) => renderProjectTree(project, 0, new Set()))}
  1237. </div>
  1238. )}
  1239. {/* Delete Confirmation Modal */}
  1240. {deleteConfirm !== null && (
  1241. <ConfirmModal
  1242. title={t('projects.deleteProject')}
  1243. message={t('projects.deleteConfirm')}
  1244. confirmText={t('projects.deleteProject')}
  1245. variant="danger"
  1246. onConfirm={handleDeleteConfirm}
  1247. onCancel={() => setDeleteConfirm(null)}
  1248. />
  1249. )}
  1250. {/* Modal */}
  1251. {showModal && (
  1252. <ProjectModal
  1253. project={editingProject}
  1254. onClose={() => {
  1255. setShowModal(false);
  1256. setEditingProject(undefined);
  1257. }}
  1258. onSave={handleSave}
  1259. isLoading={createMutation.isPending || updateMutation.isPending}
  1260. currencySymbol={currencySymbol}
  1261. t={t}
  1262. />
  1263. )}
  1264. </div>
  1265. );
  1266. }