mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fee6f39828 | ||
|
|
1066900c78 | ||
|
|
f2febaf652 | ||
|
|
5a1655e4ef | ||
|
|
e32445684f | ||
|
|
9c8eb16259 |
@@ -125,7 +125,7 @@ An **Operation** is defined once and exposed across built-in agent tools, the MC
|
|||||||
- **Route Code-Splitting**: Split all routes into `[route].tsx` (route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
|
- **Route Code-Splitting**: Split all routes into `[route].tsx` (route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
|
||||||
- **Radix / Shadcn UI**: Set `modal={false}` on `<DropdownMenu>` when triggering a `Dialog` or `AlertDialog` from inside it to prevent focus-trap UI freezes. Use `ScrollArea` (`@/ui/components/ui/scroll-area`) for scrollable containers.
|
- **Radix / Shadcn UI**: Set `modal={false}` on `<DropdownMenu>` when triggering a `Dialog` or `AlertDialog` from inside it to prevent focus-trap UI freezes. Use `ScrollArea` (`@/ui/components/ui/scroll-area`) for scrollable containers.
|
||||||
- **Pagination & Infinite Scroll**: Use `useInfiniteQuery` + `react-intersection-observer` with default `limit: 20` and the API's `total` field. Backend list APIs use `paginateQuery` from `packages/core/src/pagination.ts` (default `limit: 20`).
|
- **Pagination & Infinite Scroll**: Use `useInfiniteQuery` + `react-intersection-observer` with default `limit: 20` and the API's `total` field. Backend list APIs use `paginateQuery` from `packages/core/src/pagination.ts` (default `limit: 20`).
|
||||||
- **Internationalization (i18n)**: Hardcoded UI text is strictly forbidden. Add `snake_case` keys to both `packages/webui/messages/en.json` and `packages/webui/messages/zh.json`, run `bun run i18n:compile` (or `bun run i18n:watch`), and import `m` from `@/ui/paraglide/messages.js`.
|
- **Internationalization (i18n)**: Hardcoded UI text is strictly forbidden. Add `snake_case` keys to **all** locale files in `packages/webui/messages/*.json` (do not assume only `en.json` and `zh.json` exist; check the directory for all supported languages), run `bun run i18n:compile` (or `bun run i18n:watch`), and import `m` from `@/ui/paraglide/messages.js`.
|
||||||
|
|
||||||
## Database & Prisma (`packages/db`)
|
## Database & Prisma (`packages/db`)
|
||||||
|
|
||||||
|
|||||||
@@ -8,8 +8,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
- **comments**: Add Internal Comments with a Public/Internal selector in the comment composer so team and project members can have private discussions (marked with a lock icon) that never appear on public share links.
|
||||||
|
- **comments**: Allow comment authors to edit their comments inline from the comment menu, including updating text, switching between Public and Internal, removing timestamps, and adding or removing attachments.
|
||||||
|
|
||||||
|
- **comments**: Add a "Print Comments" option in the comments menu (available in both project file views and public share links) that opens a dedicated print-friendly page with asset metadata, comment thumbnails, visual markup overlays, replies, completion status, emoji reactions, and attachments.
|
||||||
|
|
||||||
|
- **share**: See view counts, last viewed times, and activity for public share links, including file and folder views, downloads, and comments.
|
||||||
|
|
||||||
|
- **share**: Add options to create a share link or add to existing share links directly from the media view dropdown menu, and open a quick share dialog with inline renaming, one-click link copying, and security settings upon creation.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing.
|
||||||
|
- **security**: Security improvements.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
## [0.7.1] - 2026-11-23
|
## [0.7.1] - 2026-11-23
|
||||||
|
|||||||
@@ -77,8 +77,13 @@ apps/web/e2e/
|
|||||||
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
|
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
|
||||||
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
|
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
|
||||||
| Owner deletes a version stack and restores it from recently deleted | `tests/project/delete-restore.spec.ts` |
|
| Owner deletes a version stack and restores it from recently deleted | `tests/project/delete-restore.spec.ts` |
|
||||||
| Owner creates a share link from a file context menu and lands on the share page | `tests/project/create-share-link.spec.ts` |
|
| Owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings | `tests/project/create-share-link.spec.ts` |
|
||||||
|
| Owner creates a share link and adds to an existing share link from media view | `tests/project/create-share-link.spec.ts` |
|
||||||
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
|
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
|
||||||
|
| Guests can unlock a protected printable comments link directly | `tests/project/share-password.spec.ts` |
|
||||||
|
| Public page views and share activity appear in both management sidebars | `tests/project/share-activity.spec.ts` |
|
||||||
|
| Opening a direct historical version link records the selected version | `tests/project/share-activity.spec.ts` |
|
||||||
|
| Concurrent public opens count every view and deduplicate matching activity | `tests/project/share-activity.spec.ts` |
|
||||||
| Owner creates a collection from the sidebar; the collection shows project files | `tests/project/create-collection.spec.ts` |
|
| Owner creates a collection from the sidebar; the collection shows project files | `tests/project/create-collection.spec.ts` |
|
||||||
| Owner invites a member to a project; the member only sees the invited project | `tests/project/invite-member.spec.ts` |
|
| Owner invites a member to a project; the member only sees the invited project | `tests/project/invite-member.spec.ts` |
|
||||||
| Owner changes a project member role in the members dialog and permissions update | `tests/project/change-member-role.spec.ts` |
|
| Owner changes a project member role in the members dialog and permissions update | `tests/project/change-member-role.spec.ts` |
|
||||||
@@ -113,6 +118,8 @@ apps/web/e2e/
|
|||||||
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
|
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
|
||||||
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
|
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
|
||||||
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
|
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
|
||||||
|
| Create internal and public comments, verify internal comments are hidden on public share links | `tests/file/internal-comment-and-edit.spec.ts` |
|
||||||
|
| Author edits comment text, switches to internal, removes timestamp, and updates attachments | `tests/file/internal-comment-and-edit.spec.ts` |
|
||||||
| Show a breathing poster preview and "Preparing..." while a video is still transcoding | `tests/file/processing-preview.spec.ts` |
|
| Show a breathing poster preview and "Preparing..." while a video is still transcoding | `tests/file/processing-preview.spec.ts` |
|
||||||
| Show a preparing circle before the poster is generated | `tests/file/processing-preview.spec.ts` |
|
| Show a preparing circle before the poster is generated | `tests/file/processing-preview.spec.ts` |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
import { expect, test } from '../../fixtures'
|
||||||
|
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
|
||||||
|
|
||||||
|
test('internal comments show lock icon in workspace and are hidden on public share pages', async ({
|
||||||
|
browser,
|
||||||
|
file,
|
||||||
|
prisma,
|
||||||
|
}) => {
|
||||||
|
const { context, page, projectId, fileId, fileName } = file
|
||||||
|
const publicText = `Public note ${Date.now()}`
|
||||||
|
const internalText = `Internal secret ${Date.now()}`
|
||||||
|
|
||||||
|
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||||
|
|
||||||
|
const editor = page.locator('[contenteditable="true"]').first()
|
||||||
|
const sendBtn = page.locator('button:has(svg.lucide-arrow-up)').last()
|
||||||
|
const visibilityTrigger = page.getByTestId('comment-visibility-trigger')
|
||||||
|
|
||||||
|
// Default visibility is Public
|
||||||
|
await expect(visibilityTrigger).toBeVisible()
|
||||||
|
await expect(visibilityTrigger).toContainText('Public')
|
||||||
|
|
||||||
|
// Post a public comment
|
||||||
|
await editor.fill(publicText)
|
||||||
|
await sendBtn.click()
|
||||||
|
await expect(page.getByText(publicText)).toBeVisible()
|
||||||
|
|
||||||
|
// Switch to Internal and post an internal comment
|
||||||
|
await visibilityTrigger.click()
|
||||||
|
await page.getByTestId('comment-visibility-internal').click()
|
||||||
|
await expect(visibilityTrigger).toContainText('Internal')
|
||||||
|
|
||||||
|
await editor.fill(internalText)
|
||||||
|
await sendBtn.click()
|
||||||
|
await expect(page.getByText(internalText)).toBeVisible()
|
||||||
|
|
||||||
|
// Visibility pill resets to Public after sending
|
||||||
|
await expect(visibilityTrigger).toContainText('Public')
|
||||||
|
|
||||||
|
// Internal comment shows lock icon, public comment does not
|
||||||
|
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
|
||||||
|
|
||||||
|
// Verify DB persisted isInternal flags
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const comments = await prisma.assetComment.findMany({
|
||||||
|
where: { assetId: fileId },
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
})
|
||||||
|
return comments.map((c) => ({ message: c.message, isInternal: c.isInternal }))
|
||||||
|
})
|
||||||
|
.toEqual([
|
||||||
|
{ message: publicText, isInternal: false },
|
||||||
|
{ message: internalText, isInternal: true },
|
||||||
|
])
|
||||||
|
|
||||||
|
// Create a public share link for this file
|
||||||
|
const share = await apiCreateShare(context.request, projectId, 'External Review Share')
|
||||||
|
await apiAddAssetsToShare(context.request, share.id, [fileId])
|
||||||
|
|
||||||
|
// Open public share page as an unauthenticated guest
|
||||||
|
const guestContext = await browser.newContext()
|
||||||
|
try {
|
||||||
|
const guestPage = await guestContext.newPage()
|
||||||
|
await guestPage.goto(`/share/${share.id}`)
|
||||||
|
|
||||||
|
// File card comment badge should only count the 1 public comment
|
||||||
|
const card = fileCard(guestPage, fileName)
|
||||||
|
await expect(card).toBeVisible()
|
||||||
|
await expect(card).toContainText('1')
|
||||||
|
|
||||||
|
// Open the shared file
|
||||||
|
await card.dblclick()
|
||||||
|
await expect(guestPage.getByText(publicText)).toBeVisible()
|
||||||
|
await expect(guestPage.getByText(internalText)).toHaveCount(0)
|
||||||
|
await expect(guestPage.getByTestId('comment-visibility-trigger')).toHaveCount(0)
|
||||||
|
} finally {
|
||||||
|
await guestContext.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test.describe('author edits comment with timestamp and attachments', () => {
|
||||||
|
test.use({ fileOptions: { mediaType: 'audio' } })
|
||||||
|
|
||||||
|
test('author edits comment text, switches to internal, removes timestamp, and updates attachments', async ({
|
||||||
|
file,
|
||||||
|
prisma,
|
||||||
|
}) => {
|
||||||
|
const { page, projectId, fileId } = file
|
||||||
|
const originalText = `Initial audio note ${Date.now()}`
|
||||||
|
const editedText = `Edited private note ${Date.now()}`
|
||||||
|
|
||||||
|
// Wait for audio transcode completion
|
||||||
|
await expect
|
||||||
|
.poll(
|
||||||
|
async () => {
|
||||||
|
const asset = await prisma.asset.findUnique({ where: { id: fileId } })
|
||||||
|
return asset?.status
|
||||||
|
},
|
||||||
|
{ timeout: 30_000 },
|
||||||
|
)
|
||||||
|
.toBe('processed')
|
||||||
|
|
||||||
|
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||||
|
|
||||||
|
const mediaEl = page.locator('audio, video').first()
|
||||||
|
await expect(mediaEl).toBeVisible({ timeout: 30_000 })
|
||||||
|
|
||||||
|
// Seek to non-zero timestamp
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const el = document.querySelector('audio, video') as HTMLMediaElement | null
|
||||||
|
if (el) el.currentTime = 1
|
||||||
|
})
|
||||||
|
await page.waitForTimeout(500)
|
||||||
|
|
||||||
|
// Attach initial file in composer
|
||||||
|
const composerFileInput = page.locator('input[type="file"]').last()
|
||||||
|
await composerFileInput.setInputFiles({
|
||||||
|
name: 'old-attachment.txt',
|
||||||
|
mimeType: 'text/plain',
|
||||||
|
buffer: Buffer.from('old attachment content'),
|
||||||
|
})
|
||||||
|
await expect(page.getByText('old-attachment.txt')).toBeVisible()
|
||||||
|
|
||||||
|
// Submit public comment with timestamp and attachment
|
||||||
|
const editor = page.locator('[contenteditable="true"]').first()
|
||||||
|
await editor.fill(originalText)
|
||||||
|
const sendBtn = page.locator('button:has(svg.lucide-arrow-up)').last()
|
||||||
|
await expect(sendBtn).toBeEnabled()
|
||||||
|
await sendBtn.click()
|
||||||
|
|
||||||
|
await expect(page.getByText(originalText)).toBeVisible()
|
||||||
|
await expect(page.getByText('old-attachment.txt')).toBeVisible()
|
||||||
|
|
||||||
|
// Wait for DB persistence
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
return prisma.assetComment.findFirst({
|
||||||
|
where: { assetId: fileId, message: originalText },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.not.toBeNull()
|
||||||
|
|
||||||
|
// Open three-dot menu on comment card and click Edit
|
||||||
|
const moreBtn = page.getByRole('button', { name: 'More options' }).last()
|
||||||
|
await moreBtn.click({ force: true })
|
||||||
|
await page.getByRole('menuitem', { name: 'Edit' }).click()
|
||||||
|
|
||||||
|
const editForm = page.getByTestId('comment-edit-form')
|
||||||
|
await expect(editForm).toBeVisible()
|
||||||
|
|
||||||
|
// Remove timestamp
|
||||||
|
await expect(editForm.getByTestId('edit-comment-timestamp')).toBeVisible()
|
||||||
|
await editForm.getByTestId('edit-comment-remove-timestamp').click()
|
||||||
|
await expect(editForm.getByTestId('edit-comment-timestamp')).toHaveCount(0)
|
||||||
|
|
||||||
|
// Remove existing attachment
|
||||||
|
await editForm.getByTestId('edit-existing-attachment').locator('button').click()
|
||||||
|
await expect(editForm.getByTestId('edit-existing-attachment')).toHaveCount(0)
|
||||||
|
|
||||||
|
// Add a new attachment
|
||||||
|
await editForm.getByTestId('edit-comment-file-input').setInputFiles({
|
||||||
|
name: 'new-attachment.txt',
|
||||||
|
mimeType: 'text/plain',
|
||||||
|
buffer: Buffer.from('new attachment content'),
|
||||||
|
})
|
||||||
|
await expect(editForm.getByText('new-attachment.txt')).toBeVisible()
|
||||||
|
|
||||||
|
// Switch Public -> Internal
|
||||||
|
await editForm.getByTestId('comment-visibility-trigger').click()
|
||||||
|
await page.getByTestId('comment-visibility-internal').click()
|
||||||
|
await expect(editForm.getByTestId('comment-visibility-trigger')).toContainText('Internal')
|
||||||
|
|
||||||
|
// Change comment text
|
||||||
|
const editInput = editForm.getByTestId('edit-comment-input')
|
||||||
|
await editInput.click()
|
||||||
|
await page.keyboard.press('ControlOrMeta+a')
|
||||||
|
await page.keyboard.type(editedText)
|
||||||
|
|
||||||
|
// Save
|
||||||
|
const saveBtn = editForm.getByTestId('edit-comment-save')
|
||||||
|
await expect(saveBtn).toBeEnabled()
|
||||||
|
await saveBtn.click()
|
||||||
|
|
||||||
|
await expect(editForm).toHaveCount(0)
|
||||||
|
await expect(page.getByText(editedText)).toBeVisible()
|
||||||
|
await expect(page.getByText('new-attachment.txt')).toBeVisible()
|
||||||
|
await expect(page.getByText('old-attachment.txt')).toHaveCount(0)
|
||||||
|
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
|
||||||
|
|
||||||
|
// Reload and verify persistence in UI and DB
|
||||||
|
await page.reload()
|
||||||
|
await expect(page.getByText(editedText)).toBeVisible()
|
||||||
|
await expect(page.getByText('new-attachment.txt')).toBeVisible()
|
||||||
|
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
|
||||||
|
|
||||||
|
const updated = await prisma.assetComment.findFirst({
|
||||||
|
where: { assetId: fileId, message: editedText },
|
||||||
|
include: { attachments: { include: { asset: true } } },
|
||||||
|
})
|
||||||
|
expect(updated).not.toBeNull()
|
||||||
|
expect(updated?.isInternal).toBe(true)
|
||||||
|
expect(updated?.second).toBeNull()
|
||||||
|
expect(updated?.attachments.map((a) => a.asset.name)).toEqual(['new-attachment.txt'])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { expect, test } from '../../fixtures'
|
import { expect, test } from '../../fixtures'
|
||||||
import { fileCard } from '../../helpers/files'
|
import { apiCreateShare, fileCard } from '../../helpers/files'
|
||||||
|
|
||||||
test('owner creates a share link from a file context menu and lands on the share page', async ({
|
test('owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings', async ({
|
||||||
file,
|
file,
|
||||||
prisma,
|
prisma,
|
||||||
}) => {
|
}) => {
|
||||||
@@ -14,19 +14,38 @@ test('owner creates a share link from a file context menu and lands on the share
|
|||||||
await fileCard(page, fileName).click({ button: 'right' })
|
await fileCard(page, fileName).click({ button: 'right' })
|
||||||
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||||
|
|
||||||
// The toast offers a "View" action that navigates to the share page
|
// Quick share dialog opens with share name, URL, security controls, and footer actions
|
||||||
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
|
const dialog = page.getByRole('dialog')
|
||||||
await expect(toast).toBeVisible()
|
await expect(dialog).toBeVisible()
|
||||||
await toast.getByRole('button', { name: 'View' }).click()
|
await expect(dialog.getByText(fileName)).toBeVisible()
|
||||||
|
await expect(dialog.getByRole('button', { name: 'Copy Link' }).last()).toBeVisible()
|
||||||
|
await expect(dialog.getByRole('button', { name: 'Done' })).toBeVisible()
|
||||||
|
|
||||||
|
// Rename share link inline via the pen icon
|
||||||
|
await dialog.getByRole('button', { name: 'Rename Share Link' }).click()
|
||||||
|
const nameInput = dialog.getByRole('textbox', { name: 'Rename Share Link' })
|
||||||
|
await expect(nameInput).toBeVisible()
|
||||||
|
await nameInput.fill('Client Review Cut')
|
||||||
|
await nameInput.press('Enter')
|
||||||
|
await expect(dialog.getByText('Client Review Cut')).toBeVisible()
|
||||||
|
|
||||||
|
// Toggle Allow download off in quick security settings
|
||||||
|
const allowDownloadRow = dialog.getByText('Allow download').locator('..')
|
||||||
|
await allowDownloadRow.getByRole('switch').click()
|
||||||
|
await expect(page.getByText('Settings updated')).toBeVisible()
|
||||||
|
|
||||||
|
// Navigate to full settings via Advanced settings
|
||||||
|
await dialog.getByRole('button', { name: 'Advanced settings' }).click()
|
||||||
await expect(page).toHaveURL(/\/projects\/[^/]+\/shares\/[^/]+/)
|
await expect(page).toHaveURL(/\/projects\/[^/]+\/shares\/[^/]+/)
|
||||||
|
|
||||||
// The shared file is listed in the share contents
|
// The shared file is listed in the share contents
|
||||||
await expect(fileCard(page, fileName)).toBeVisible()
|
await expect(fileCard(page, fileName)).toBeVisible()
|
||||||
|
|
||||||
// DB: the share exists and the file is symlinked under the share root
|
// DB: the share exists with updated settings and the file is symlinked under the share root
|
||||||
const share = await prisma.shareLink.findFirst({ where: { projectId } })
|
const share = await prisma.shareLink.findFirst({ where: { projectId } })
|
||||||
expect(share).not.toBeNull()
|
expect(share).not.toBeNull()
|
||||||
|
expect(share?.name).toBe('Client Review Cut')
|
||||||
|
expect(share?.allowDownload).toBe(false)
|
||||||
|
|
||||||
const symlink = await prisma.asset.findFirst({
|
const symlink = await prisma.asset.findFirst({
|
||||||
where: { parentId: share?.rootFolderId, targetId: fileId },
|
where: { parentId: share?.rootFolderId, targetId: fileId },
|
||||||
@@ -34,3 +53,58 @@ test('owner creates a share link from a file context menu and lands on the share
|
|||||||
expect(symlink).not.toBeNull()
|
expect(symlink).not.toBeNull()
|
||||||
expect(symlink?.type).toBe('symlink')
|
expect(symlink?.type).toBe('symlink')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('owner creates a share link and adds to an existing share link from media view', async ({
|
||||||
|
file,
|
||||||
|
prisma,
|
||||||
|
}) => {
|
||||||
|
const { context, page, projectId, fileName, fileId } = file
|
||||||
|
|
||||||
|
// Seed an existing share link so "Add to Share Links" submenu is available
|
||||||
|
const existingShare = await apiCreateShare(context.request, projectId, 'Existing Client Share')
|
||||||
|
|
||||||
|
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||||
|
const headerTrigger = page.getByRole('button', { name: fileName })
|
||||||
|
await expect(headerTrigger).toBeVisible()
|
||||||
|
|
||||||
|
// Open the media view header arrow dropdown and create a new share link
|
||||||
|
await headerTrigger.click()
|
||||||
|
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||||
|
|
||||||
|
const dialog = page.getByRole('dialog')
|
||||||
|
await expect(dialog).toBeVisible()
|
||||||
|
await expect(dialog.getByText(fileName)).toBeVisible()
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
|
||||||
|
|
||||||
|
// Close the dialog with Done and stay on the media view
|
||||||
|
await dialog.getByRole('button', { name: 'Done' }).click()
|
||||||
|
await expect(dialog).toBeHidden()
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
|
||||||
|
|
||||||
|
// DB: new share link created with symlink to the file
|
||||||
|
const createdShare = await prisma.shareLink.findFirst({
|
||||||
|
where: { projectId, id: { not: existingShare.id } },
|
||||||
|
})
|
||||||
|
expect(createdShare).not.toBeNull()
|
||||||
|
expect(createdShare?.name).toBe(fileName)
|
||||||
|
|
||||||
|
const createdSymlink = await prisma.asset.findFirst({
|
||||||
|
where: { parentId: createdShare?.rootFolderId, targetId: fileId },
|
||||||
|
})
|
||||||
|
expect(createdSymlink).not.toBeNull()
|
||||||
|
expect(createdSymlink?.type).toBe('symlink')
|
||||||
|
|
||||||
|
// Open the header dropdown again and add the file to the existing share link
|
||||||
|
await headerTrigger.click()
|
||||||
|
await page.getByRole('menuitem', { name: 'Add to Share Links' }).hover()
|
||||||
|
await page.getByRole('menuitem', { name: 'Existing Client Share' }).click()
|
||||||
|
|
||||||
|
const addedToast = page.locator('[data-sonner-toast]').filter({ hasText: 'Added to share link' })
|
||||||
|
await expect(addedToast).toBeVisible()
|
||||||
|
|
||||||
|
const addedSymlink = await prisma.asset.findFirst({
|
||||||
|
where: { parentId: existingShare.rootFolderId, targetId: fileId },
|
||||||
|
})
|
||||||
|
expect(addedSymlink).not.toBeNull()
|
||||||
|
expect(addedSymlink?.type).toBe('symlink')
|
||||||
|
})
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import { expect, test } from '../../fixtures'
|
||||||
|
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
|
||||||
|
|
||||||
|
test('counts public page views and shows activity in both share management sidebars', async ({
|
||||||
|
file,
|
||||||
|
browser,
|
||||||
|
prisma,
|
||||||
|
}) => {
|
||||||
|
const { context, page, projectId, rootFolderId, fileId, fileName } = file
|
||||||
|
const folder = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'Review Folder',
|
||||||
|
projectId,
|
||||||
|
parentId: rootFolderId,
|
||||||
|
type: 'folder',
|
||||||
|
status: 'processed',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await prisma.asset.update({ where: { id: fileId }, data: { parentId: folder.id } })
|
||||||
|
const share = await apiCreateShare(context.request, projectId, 'Client Review')
|
||||||
|
await apiAddAssetsToShare(context.request, share.id, [folder.id])
|
||||||
|
const password = 'review-password'
|
||||||
|
const lock = await context.request.put(`/api/shares/${share.id}`, { data: { password } })
|
||||||
|
expect(lock.ok()).toBe(true)
|
||||||
|
const readShare = () => prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
|
||||||
|
|
||||||
|
await page.goto(`/projects/${projectId}/shares`)
|
||||||
|
await expect(page.getByText('Never viewed')).toBeVisible()
|
||||||
|
|
||||||
|
const guest = await browser.newContext()
|
||||||
|
try {
|
||||||
|
const guestPage = await guest.newPage()
|
||||||
|
await guestPage.goto(`/share/${share.id}`)
|
||||||
|
await guestPage.getByPlaceholder('Enter password').fill(password)
|
||||||
|
await guestPage.getByRole('button', { name: 'Access Share' }).click()
|
||||||
|
await expect(fileCard(guestPage, folder.name)).toBeVisible()
|
||||||
|
await expect.poll(async () => (await readShare()).views).toBe(1)
|
||||||
|
await fileCard(guestPage, folder.name).click()
|
||||||
|
await expect(fileCard(guestPage, fileName)).toBeVisible()
|
||||||
|
await expect.poll(async () => (await readShare()).views).toBe(2)
|
||||||
|
await fileCard(guestPage, fileName).click()
|
||||||
|
await expect.poll(async () => (await readShare()).views).toBe(3)
|
||||||
|
const beforeReload = (await readShare()).lastViewedAt
|
||||||
|
await guestPage.reload()
|
||||||
|
await expect.poll(async () => (await readShare()).views).toBe(4)
|
||||||
|
expect((await readShare()).lastViewedAt!.getTime()).toBeGreaterThan(beforeReload!.getTime())
|
||||||
|
|
||||||
|
const downloadResponse = guestPage.waitForResponse((response) =>
|
||||||
|
response.url().endsWith('/download-url'),
|
||||||
|
)
|
||||||
|
await guestPage.getByTestId('default-viewer-download-button').click()
|
||||||
|
const download = await downloadResponse
|
||||||
|
expect(download.status()).toBe(200)
|
||||||
|
|
||||||
|
const comment = await context.request.post(`/api/shares/${share.id}/files/${fileId}/comments`, {
|
||||||
|
headers: { 'x-share-password': password },
|
||||||
|
data: { message: 'Ready for review', attachmentIds: [] },
|
||||||
|
})
|
||||||
|
expect(comment.status()).toBe(201)
|
||||||
|
} finally {
|
||||||
|
await guest.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.reload()
|
||||||
|
const row = page.getByRole('row').filter({ hasText: share.name })
|
||||||
|
await expect(row.getByRole('cell', { name: '4', exact: true })).toBeVisible()
|
||||||
|
await expect(row.locator('time')).toContainText('Today')
|
||||||
|
await row.getByRole('button', { name: 'View Activity' }).click()
|
||||||
|
const sidebar = page.getByRole('dialog', { name: 'Activity' })
|
||||||
|
await expect(sidebar.getByText('Opened Share Link')).toHaveCount(1)
|
||||||
|
await expect(sidebar.getByText('Viewed Asset')).toHaveCount(2)
|
||||||
|
await expect(sidebar.getByText(folder.name)).toBeVisible()
|
||||||
|
await expect(sidebar.getByText('Downloaded')).toBeVisible()
|
||||||
|
await expect(sidebar.getByText('Commented')).toBeVisible()
|
||||||
|
await expect(sidebar.getByText('Someone').first()).toBeVisible()
|
||||||
|
|
||||||
|
await page.goto(`/projects/${projectId}/shares/${share.id}`)
|
||||||
|
await expect(page.getByRole('tab', { name: 'Settings' })).toHaveAttribute('aria-selected', 'true')
|
||||||
|
await page.getByRole('tab', { name: 'Activity' }).click()
|
||||||
|
const tab = page.getByRole('tabpanel', { name: 'Activity' })
|
||||||
|
await expect(tab.getByText('Opened Share Link')).toHaveCount(1)
|
||||||
|
await expect(tab.getByText('Viewed Asset')).toHaveCount(2)
|
||||||
|
await expect(tab.getByText('Commented')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a direct historical version link records the version as the viewed asset', async ({
|
||||||
|
file,
|
||||||
|
browser,
|
||||||
|
prisma,
|
||||||
|
}) => {
|
||||||
|
const { context, projectId, rootFolderId, fileId } = file
|
||||||
|
const stack = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'Review Versions',
|
||||||
|
projectId,
|
||||||
|
parentId: rootFolderId,
|
||||||
|
type: 'version_stack',
|
||||||
|
status: 'processed',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await prisma.asset.update({
|
||||||
|
where: { id: fileId },
|
||||||
|
data: { parentId: stack.id, sortIndex: 'a' },
|
||||||
|
})
|
||||||
|
const oldVersion = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'Earlier Cut',
|
||||||
|
projectId,
|
||||||
|
parentId: stack.id,
|
||||||
|
sortIndex: 'b',
|
||||||
|
type: 'file',
|
||||||
|
status: 'processed',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const share = await apiCreateShare(context.request, projectId, 'Version Review')
|
||||||
|
await apiAddAssetsToShare(context.request, share.id, [stack.id])
|
||||||
|
const guest = await browser.newContext()
|
||||||
|
try {
|
||||||
|
const page = await guest.newPage()
|
||||||
|
await page.goto(`/share/${share.id}/files/${stack.id}?version=${oldVersion.id}`)
|
||||||
|
await expect
|
||||||
|
.poll(() => prisma.shareActivity.count({ where: { shareLinkId: share.id } }))
|
||||||
|
.toBe(2)
|
||||||
|
const activities = await prisma.shareActivity.findMany({ where: { shareLinkId: share.id } })
|
||||||
|
expect(activities).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({ kind: 'share_viewed', assetId: null }),
|
||||||
|
expect.objectContaining({ kind: 'asset_viewed', assetId: oldVersion.id }),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
const link = await prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
|
||||||
|
expect(link.views).toBe(1)
|
||||||
|
} finally {
|
||||||
|
await guest.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('concurrent authorized page opens add every view and one matching activity', async ({
|
||||||
|
project,
|
||||||
|
browser,
|
||||||
|
prisma,
|
||||||
|
}) => {
|
||||||
|
const share = await apiCreateShare(
|
||||||
|
project.context.request,
|
||||||
|
project.projectId,
|
||||||
|
'Concurrent Review',
|
||||||
|
)
|
||||||
|
const guest = await browser.newContext()
|
||||||
|
try {
|
||||||
|
const responses = await Promise.all(
|
||||||
|
Array.from({ length: 8 }, () =>
|
||||||
|
guest.request.post(`/api/shares/${share.id}/views`, { data: {} }),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
expect(responses.map((response) => response.status())).toEqual(Array(8).fill(204))
|
||||||
|
const link = await prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
|
||||||
|
expect(link).toMatchObject({ views: 8, lastViewedAt: expect.any(Date) })
|
||||||
|
const activities = await prisma.shareActivity.findMany({ where: { shareLinkId: share.id } })
|
||||||
|
expect(activities).toMatchObject([{ kind: 'share_viewed', userId: null, assetId: null }])
|
||||||
|
} finally {
|
||||||
|
await guest.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -49,3 +49,33 @@ test('owner protects a share with a password and guests must enter it to view',
|
|||||||
await guestContext.close()
|
await guestContext.close()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('a guest can unlock a protected printable comments link directly', async ({
|
||||||
|
file,
|
||||||
|
browser,
|
||||||
|
}) => {
|
||||||
|
const { context, projectId, fileName, fileId } = file
|
||||||
|
const share = await apiCreateShare(context.request, projectId, 'Shared Print')
|
||||||
|
await apiAddAssetsToShare(context.request, share.id, [fileId])
|
||||||
|
const res = await context.request.put(`/api/shares/${share.id}`, {
|
||||||
|
data: { password: 'secret123' },
|
||||||
|
})
|
||||||
|
expect(res.ok()).toBe(true)
|
||||||
|
|
||||||
|
const guestContext = await browser.newContext()
|
||||||
|
const page = await guestContext.newPage()
|
||||||
|
try {
|
||||||
|
await page.goto(`/print/comments/${fileId}?shareId=${share.id}`)
|
||||||
|
const passwordInput = page.getByPlaceholder('Enter password')
|
||||||
|
await expect(passwordInput).toBeVisible()
|
||||||
|
await passwordInput.fill('wrong-password')
|
||||||
|
await page.getByRole('button', { name: 'Confirm' }).click()
|
||||||
|
await expect(page.getByText('Incorrect password. Please try again.')).toBeVisible()
|
||||||
|
await passwordInput.fill('secret123')
|
||||||
|
await page.getByRole('button', { name: 'Confirm' }).click()
|
||||||
|
await expect(page.getByTitle(fileName)).toBeVisible()
|
||||||
|
await expect(page).toHaveURL(`/print/comments/${fileId}?shareId=${share.id}`)
|
||||||
|
} finally {
|
||||||
|
await guestContext.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|||||||
@@ -147,8 +147,10 @@ test('dissolving a shared version stack renders the remaining standalone file na
|
|||||||
// Share the version stack
|
// Share the version stack
|
||||||
await fileCard(page, fileB.name).click({ button: 'right' })
|
await fileCard(page, fileB.name).click({ button: 'right' })
|
||||||
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||||
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
|
const shareDialog = page.getByRole('dialog')
|
||||||
await expect(toast).toBeVisible()
|
await expect(shareDialog).toBeVisible()
|
||||||
|
await shareDialog.getByRole('button', { name: 'Done' }).click()
|
||||||
|
await expect(shareDialog).toBeHidden()
|
||||||
|
|
||||||
const share = await prisma.shareLink.findFirstOrThrow({
|
const share = await prisma.shareLink.findFirstOrThrow({
|
||||||
where: { projectId },
|
where: { projectId },
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ Shumai allows you to collaborate with external stakeholders who do not have acco
|
|||||||
|
|
||||||
1. Select the files or folders you want to share, then right-click and choose **Create New Share Link**.
|
1. Select the files or folders you want to share, then right-click and choose **Create New Share Link**.
|
||||||
2. Click the newly created **Share Link** in the project sidebar to open its settings page.
|
2. Click the newly created **Share Link** in the project sidebar to open its settings page.
|
||||||
3. Configure the share link in the right sidebar. You can:
|
3. Use the **Settings** tab in the right sidebar to configure the share link.
|
||||||
- Add password protection
|
- Add password protection
|
||||||
- Set an expiration date
|
- Set an expiration date
|
||||||
- Allow or disallow downloads
|
- Allow or disallow downloads
|
||||||
@@ -33,6 +33,16 @@ Once a share link is created, you can easily add more files or folders to it wit
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Viewing Share Activity
|
||||||
|
|
||||||
|
Open **All Share Links** in the project sidebar to see **Views** and **Last Viewed** for each link. Click **View Activity** on a link’s row to open its history, or select the **Activity** tab on that link’s settings page.
|
||||||
|
|
||||||
|
The history groups share opens, file and folder views, downloads, and comments by day. It shows the visitor’s name when available and **Someone** for anonymous activity. A download entry appears when a visitor starts an authorized download.
|
||||||
|
|
||||||
|
Every successful open of the share, a shared folder, or a shared file adds one view and updates **Last Viewed**, including reloads. The history shows matching actions once within 30 minutes. A match uses the share link, action, visitor, and asset when there is one. For this check, all anonymous visitors are treated as the same visitor. For example, if a visitor opens the same file twice in ten minutes, **Views** increases by two and the history shows one **Viewed Asset** entry.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Security and Settings
|
## Security and Settings
|
||||||
|
|
||||||
### Expiration Date
|
### Expiration Date
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
|
|||||||
|
|
||||||
1. 选中要分享的文件或文件夹,右键单击并选择**创建新分享链接**。
|
1. 选中要分享的文件或文件夹,右键单击并选择**创建新分享链接**。
|
||||||
2. 在项目侧边栏中点击刚创建的**分享链接**,进入其配置页面。
|
2. 在项目侧边栏中点击刚创建的**分享链接**,进入其配置页面。
|
||||||
3. 在右侧边栏中配置分享链接参数:
|
3. 在右侧边栏的**设置**选项卡中配置分享链接。
|
||||||
- 添加密码保护
|
- 添加密码保护
|
||||||
- 设置过期时间
|
- 设置过期时间
|
||||||
- 开启或禁止文件下载
|
- 开启或禁止文件下载
|
||||||
@@ -33,6 +33,16 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 查看分享活动
|
||||||
|
|
||||||
|
在项目侧边栏打开**所有分享链接**,即可看到每条链接的**浏览次数**和**最近浏览**时间。点击对应行的**查看活动**,或在该链接的配置页面切换到**活动**选项卡,即可查看活动记录。
|
||||||
|
|
||||||
|
活动按天分组,包括打开分享链接、浏览文件和文件夹、下载以及发表评论。可以识别访客时显示其姓名,匿名活动显示为**有人**。访客开始下载且通过权限验证后,系统会记录下载活动。
|
||||||
|
|
||||||
|
每次成功打开分享页面、共享文件夹或共享文件(包括刷新页面)都会增加一次**浏览次数**,并更新**最近浏览**时间。系统根据分享链接、操作、访客和相关资产(如有)判断活动是否重复,30 分钟内的重复活动只显示一次。判断时,所有匿名访客视为同一位访客。例如,同一位访客在十分钟内两次打开同一文件,**浏览次数**会增加两次,活动列表显示一条**浏览了素材**的记录。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 安全与权限配置
|
## 安全与权限配置
|
||||||
|
|
||||||
### 有效期
|
### 有效期
|
||||||
|
|||||||
@@ -601,6 +601,7 @@ export const createCommentActivity = defineStep(
|
|||||||
sessionId?: string | null
|
sessionId?: string | null
|
||||||
agentId?: string | null
|
agentId?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
|
isInternal?: boolean
|
||||||
}) {
|
}) {
|
||||||
if (params.sessionId) {
|
if (params.sessionId) {
|
||||||
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
|
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
|
||||||
@@ -669,6 +670,7 @@ export const createCommentActivity = defineStep(
|
|||||||
sessionId: params.sessionId ?? null,
|
sessionId: params.sessionId ?? null,
|
||||||
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
|
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
|
||||||
replyToId: params.replyToId,
|
replyToId: params.replyToId,
|
||||||
|
isInternal: params.isInternal ?? false,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -205,6 +205,43 @@ describe('Agent Chat Workflow', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('marks agent placeholder reply as internal when user comment is internal', async () => {
|
||||||
|
mockActivities.getCommentActivity.mockResolvedValue({
|
||||||
|
id: 'c-internal',
|
||||||
|
message: 'hello agent privately',
|
||||||
|
assetId: 'a1',
|
||||||
|
creatorId: 'user-c1',
|
||||||
|
second: null,
|
||||||
|
annotation: null,
|
||||||
|
replyToId: null,
|
||||||
|
isInternal: true,
|
||||||
|
attachments: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'chat',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: 'a1',
|
||||||
|
payload: {
|
||||||
|
projectId: 'p1',
|
||||||
|
agent: { userCommentId: 'c-internal', agentId: 'b1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await agentChat(task)
|
||||||
|
|
||||||
|
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||||
|
assetId: 'a1',
|
||||||
|
message: '__CHAT__',
|
||||||
|
sessionId: 'pending',
|
||||||
|
agentId: 'b1',
|
||||||
|
replyToId: 'c-internal',
|
||||||
|
isInternal: true,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('should skip session initialization if sessionId is already provided', async () => {
|
it('should skip session initialization if sessionId is already provided', async () => {
|
||||||
const task = await prisma.workflowTask.create({
|
const task = await prisma.workflowTask.create({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
sessionId: sessionId || 'pending',
|
sessionId: sessionId || 'pending',
|
||||||
agentId: agentId,
|
agentId: agentId,
|
||||||
replyToId: userComment.replyToId ?? userComment.id,
|
replyToId: userComment.replyToId ?? userComment.id,
|
||||||
|
...(userComment.isInternal ? { isInternal: true } : {}),
|
||||||
})
|
})
|
||||||
placeholderCommentId = placeholder.id
|
placeholderCommentId = placeholder.id
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { AssetType } from '@shumai/db'
|
|||||||
import { authMiddleware } from './middleware/auth'
|
import { authMiddleware } from './middleware/auth'
|
||||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
|
||||||
vi.mock('./middleware/auth', () => ({
|
vi.mock('./middleware/auth', () => ({
|
||||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||||
@@ -84,4 +85,28 @@ describe('Attachment API', () => {
|
|||||||
itemId: 'asset1',
|
itemId: 'asset1',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('keeps the upload key inside the attachment folder', async () => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any)
|
||||||
|
vi.mocked(s3Service.presign).mockResolvedValue('http://mock-s3-url')
|
||||||
|
|
||||||
|
const fileName = '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov'
|
||||||
|
const res = await app.request('/projects/project1/attachments', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||||
|
body: JSON.stringify({ fileName, contentType: 'video/quicktime', size: 100 }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const key = vi.mocked(assetService.createAsset).mock.lastCall?.[0].key as string
|
||||||
|
const parts = key.split('/')
|
||||||
|
expect(parts[0]).toBe('attachments')
|
||||||
|
expect(parts).toHaveLength(3)
|
||||||
|
expect(parts).not.toContain('..')
|
||||||
|
expect(s3Service.presign).toHaveBeenCalledWith(expect.any(String), key, 'PUT')
|
||||||
|
expect(assetService.createAsset).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ name: fileName }),
|
||||||
|
)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
|||||||
import { projectService } from '@shumai/core/src/project/project'
|
import { projectService } from '@shumai/core/src/project/project'
|
||||||
import { AssetType } from '@shumai/db'
|
import { AssetType } from '@shumai/db'
|
||||||
import { ulid } from 'ulid'
|
import { ulid } from 'ulid'
|
||||||
|
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||||
import type { Prisma } from '@shumai/db'
|
import type { Prisma } from '@shumai/db'
|
||||||
|
|
||||||
@@ -27,7 +28,7 @@ const route = new Hono<{ Variables: { user: User } }>().post(
|
|||||||
id: projectId,
|
id: projectId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const key = `attachments/${ulid()}/${req.fileName}`
|
const key = `attachments/${ulid()}/${sanitizeFilename(req.fileName)}`
|
||||||
|
|
||||||
const assetInfo = await assetService.createAsset({
|
const assetInfo = await assetService.createAsset({
|
||||||
name: req.fileName,
|
name: req.fileName,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Hono, type Context, type Next } from 'hono'
|
|||||||
import { HTTPException } from 'hono/http-exception'
|
import { HTTPException } from 'hono/http-exception'
|
||||||
import fileRoute from './file'
|
import fileRoute from './file'
|
||||||
import { assetService } from '@shumai/core/src/asset/asset'
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||||
import { projectService } from '@shumai/core/src/project/project'
|
import { projectService } from '@shumai/core/src/project/project'
|
||||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||||
@@ -81,6 +82,7 @@ describe('file api', () => {
|
|||||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||||
|
vi.spyOn(assetService, 'updateComment').mockImplementation(vi.fn())
|
||||||
vi.spyOn(assetService, 'completeComment').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'completeComment').mockImplementation(vi.fn())
|
||||||
vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn())
|
||||||
vi.spyOn(assetService, 'addCommentReaction').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'addCommentReaction').mockImplementation(vi.fn())
|
||||||
@@ -90,7 +92,10 @@ describe('file api', () => {
|
|||||||
assetId: 'file1',
|
assetId: 'file1',
|
||||||
} as unknown as Awaited<ReturnType<typeof assetService.getComment>>)
|
} as unknown as Awaited<ReturnType<typeof assetService.getComment>>)
|
||||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||||
|
vi.spyOn(assetService, 'listAllComments').mockImplementation(vi.fn())
|
||||||
|
vi.spyOn(assetService, 'getProjectNameForAsset').mockResolvedValue('Demo Project')
|
||||||
vi.spyOn(assetService, 'exportComments').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'exportComments').mockImplementation(vi.fn())
|
||||||
|
vi.spyOn(commentFrameService, 'extractFrame').mockImplementation(vi.fn())
|
||||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||||
@@ -287,6 +292,7 @@ describe('file api', () => {
|
|||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
})
|
})
|
||||||
@@ -347,6 +353,7 @@ describe('file api', () => {
|
|||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
})
|
})
|
||||||
@@ -404,6 +411,7 @@ describe('file api', () => {
|
|||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
},
|
},
|
||||||
@@ -549,6 +557,7 @@ describe('file api', () => {
|
|||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: true,
|
isCompleted: true,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: { id: 'user1', name: 'Test User' },
|
completionLastChangedBy: { id: 'user1', name: 'Test User' },
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
})
|
})
|
||||||
@@ -575,6 +584,110 @@ describe('file api', () => {
|
|||||||
expect(assetService.getComment).toHaveBeenCalledWith('comment-id', 'user1')
|
expect(assetService.getComment).toHaveBeenCalledWith('comment-id', 'user1')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('POST /files/:fileId/comments forwards isInternal', async () => {
|
||||||
|
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||||
|
id: 'comment-internal-id',
|
||||||
|
assetId: 'test-id',
|
||||||
|
message: 'internal note',
|
||||||
|
annotations: null,
|
||||||
|
second: null,
|
||||||
|
creator: { id: 'user1', name: 'Test User' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: true,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||||
|
const res = await app.request('/files/test-id/comments', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ message: 'internal note', attachmentIds: [], isInternal: true }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(201)
|
||||||
|
const json = await res.json()
|
||||||
|
expect(json.isInternal).toBe(true)
|
||||||
|
expect(assetService.createComment).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
assetId: 'test-id',
|
||||||
|
userId: 'user1',
|
||||||
|
message: 'internal note',
|
||||||
|
isInternal: true,
|
||||||
|
}),
|
||||||
|
expect.anything(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('PATCH /comments/:commentId updates comment and logs comment_update audit entry', async () => {
|
||||||
|
vi.mocked(assetService.updateComment).mockResolvedValue({
|
||||||
|
id: 'comment-id',
|
||||||
|
assetId: 'file-id',
|
||||||
|
message: 'edited text',
|
||||||
|
annotations: null,
|
||||||
|
second: null,
|
||||||
|
creator: { id: 'user1', name: 'Test User' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: true,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
})
|
||||||
|
vi.mocked(assetService.getAssetContext).mockResolvedValue({
|
||||||
|
teamId: 'test-team',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
})
|
||||||
|
|
||||||
|
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||||
|
const res = await app.request('/comments/comment-id', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
message: 'edited text',
|
||||||
|
isInternal: true,
|
||||||
|
second: null,
|
||||||
|
attachmentIds: ['att-1'],
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const json = await res.json()
|
||||||
|
expect(json.message).toBe('edited text')
|
||||||
|
expect(json.isInternal).toBe(true)
|
||||||
|
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||||
|
user: { id: 'user1', name: 'Test User' },
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Comment,
|
||||||
|
id: 'comment-id',
|
||||||
|
})
|
||||||
|
expect(assetService.updateComment).toHaveBeenCalledWith({
|
||||||
|
commentId: 'comment-id',
|
||||||
|
userId: 'user1',
|
||||||
|
message: 'edited text',
|
||||||
|
isInternal: true,
|
||||||
|
second: null,
|
||||||
|
attachmentIds: ['att-1'],
|
||||||
|
})
|
||||||
|
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||||
|
action: 'comment_update',
|
||||||
|
teamId: 'test-team',
|
||||||
|
userId: 'user1',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
itemId: 'comment-id',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('POST /comments/:commentId/complete reopens with isCompleted false', async () => {
|
it('POST /comments/:commentId/complete reopens with isCompleted false', async () => {
|
||||||
vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: false })
|
vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: false })
|
||||||
vi.mocked(assetService.getComment).mockResolvedValue({
|
vi.mocked(assetService.getComment).mockResolvedValue({
|
||||||
@@ -1095,4 +1208,90 @@ describe('file api', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('GET /files/:fileId/comments/print and /frame routes', () => {
|
||||||
|
it('returns asset, top-down breadcrumbs, and all comments for printing', async () => {
|
||||||
|
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||||
|
id: 'file-1',
|
||||||
|
name: 'demo.mp4',
|
||||||
|
sizeByte: 100,
|
||||||
|
fileCount: 1,
|
||||||
|
type: 'file',
|
||||||
|
status: 'active',
|
||||||
|
proxyType: 'video',
|
||||||
|
ancestorFolders: [
|
||||||
|
{ id: 'f2', name: 'Inner' },
|
||||||
|
{ id: 'f1', name: 'Outer' },
|
||||||
|
],
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
vi.mocked(assetService.getProjectNameForAsset).mockResolvedValue('My Project')
|
||||||
|
vi.mocked(assetService.listAllComments).mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'c1',
|
||||||
|
assetId: 'file-1',
|
||||||
|
message: 'Looks great',
|
||||||
|
annotations: null,
|
||||||
|
second: 1.5,
|
||||||
|
creator: { id: 'u1', name: 'Alice' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
|
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||||
|
const res = await app.request('/files/file-1/comments/print')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.breadcrumbs).toEqual(['My Project', 'Outer', 'Inner'])
|
||||||
|
expect(body.comments).toHaveLength(1)
|
||||||
|
expect(body.asset.id).toBe('file-1')
|
||||||
|
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||||
|
user: { id: 'user1', name: 'Test User' },
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Asset,
|
||||||
|
id: 'file-1',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('streams extracted frame image with cache headers', async () => {
|
||||||
|
const buf = Buffer.from('mock-webp-bytes')
|
||||||
|
vi.mocked(commentFrameService.extractFrame).mockResolvedValue({
|
||||||
|
buffer: buf,
|
||||||
|
mimeType: 'image/webp',
|
||||||
|
})
|
||||||
|
|
||||||
|
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||||
|
const res = await app.request('/files/file-1/comments/frame?second=2.5&width=400')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.headers.get('content-type')).toBe('image/webp')
|
||||||
|
expect(res.headers.get('cache-control')).toBe('private, max-age=300')
|
||||||
|
const arr = new Uint8Array(await res.arrayBuffer())
|
||||||
|
expect(Buffer.from(arr).toString()).toBe('mock-webp-bytes')
|
||||||
|
expect(commentFrameService.extractFrame).toHaveBeenCalledWith({
|
||||||
|
assetId: 'file-1',
|
||||||
|
second: 2.5,
|
||||||
|
width: 400,
|
||||||
|
signal: expect.any(AbortSignal),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects invalid second query parameter with 400', async () => {
|
||||||
|
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||||
|
const res = await app.request('/files/file-1/comments/frame?second=-5')
|
||||||
|
expect(res.status).toBe(400)
|
||||||
|
expect(commentFrameService.extractFrame).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { assetService } from '@shumai/core/src/asset/asset'
|
|||||||
import { projectService } from '@shumai/core/src/project/project'
|
import { projectService } from '@shumai/core/src/project/project'
|
||||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||||
import { commentService } from '@shumai/core/src/comment/comment'
|
import { commentService } from '@shumai/core/src/comment/comment'
|
||||||
|
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
import type { Prisma } from '@shumai/db'
|
import type { Prisma } from '@shumai/db'
|
||||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||||
@@ -17,6 +18,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
archiveAssetsRequestSchema,
|
archiveAssetsRequestSchema,
|
||||||
createCommentRequestSchema,
|
createCommentRequestSchema,
|
||||||
|
updateCommentRequestSchema,
|
||||||
deleteFilesRequestSchema,
|
deleteFilesRequestSchema,
|
||||||
batchGetFilesRequestSchema,
|
batchGetFilesRequestSchema,
|
||||||
paginationParamsSchema,
|
paginationParamsSchema,
|
||||||
@@ -29,6 +31,7 @@ import {
|
|||||||
getDownloadLinksRequestSchema,
|
getDownloadLinksRequestSchema,
|
||||||
getStoragePathsRequestSchema,
|
getStoragePathsRequestSchema,
|
||||||
completeCommentRequestSchema,
|
completeCommentRequestSchema,
|
||||||
|
commentFrameQuerySchema,
|
||||||
exportCommentsRequestSchema,
|
exportCommentsRequestSchema,
|
||||||
addCommentReactionRequestSchema,
|
addCommentReactionRequestSchema,
|
||||||
removeCommentReactionRequestSchema,
|
removeCommentReactionRequestSchema,
|
||||||
@@ -197,6 +200,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
annotations: req.annotations,
|
annotations: req.annotations,
|
||||||
second: req.second,
|
second: req.second,
|
||||||
attachmentIds: req.attachmentIds,
|
attachmentIds: req.attachmentIds,
|
||||||
|
isInternal: req.isInternal,
|
||||||
})
|
})
|
||||||
|
|
||||||
const context = await assetService.getAssetContext(fileId)
|
const context = await assetService.getAssetContext(fileId)
|
||||||
@@ -248,6 +252,60 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
return c.body(result.content)
|
return c.body(result.content)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
.get('/files/:fileId/comments/print', async (c) => {
|
||||||
|
const fileId = c.req.param('fileId')
|
||||||
|
const user = c.get('user')
|
||||||
|
|
||||||
|
await authzService.hasPermission({
|
||||||
|
user,
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Asset,
|
||||||
|
id: fileId,
|
||||||
|
})
|
||||||
|
|
||||||
|
const [asset, projectName, comments] = await Promise.all([
|
||||||
|
assetService.getAsset({ assetId: fileId }),
|
||||||
|
assetService.getProjectNameForAsset(fileId),
|
||||||
|
assetService.listAllComments(fileId, user.id),
|
||||||
|
])
|
||||||
|
|
||||||
|
const folderNames = (asset.ancestorFolders ?? [])
|
||||||
|
.slice()
|
||||||
|
.reverse()
|
||||||
|
.map((f) => f.name)
|
||||||
|
.filter((name): name is string => Boolean(name))
|
||||||
|
const breadcrumbs = projectName ? [projectName, ...folderNames] : folderNames
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
asset,
|
||||||
|
breadcrumbs,
|
||||||
|
comments,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/files/:fileId/comments/frame', zValidator('query', commentFrameQuerySchema), async (c) => {
|
||||||
|
const fileId = c.req.param('fileId')
|
||||||
|
const user = c.get('user')
|
||||||
|
const { second, width } = c.req.valid('query')
|
||||||
|
|
||||||
|
await authzService.hasPermission({
|
||||||
|
user,
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Asset,
|
||||||
|
id: fileId,
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await commentFrameService.extractFrame({
|
||||||
|
assetId: fileId,
|
||||||
|
second,
|
||||||
|
width,
|
||||||
|
signal: c.req.raw.signal,
|
||||||
|
})
|
||||||
|
|
||||||
|
return c.body(new Uint8Array(result.buffer), 200, {
|
||||||
|
'Content-Type': result.mimeType,
|
||||||
|
'Cache-Control': 'private, max-age=300',
|
||||||
|
})
|
||||||
|
})
|
||||||
.post(
|
.post(
|
||||||
'/comments/:commentId/reactions',
|
'/comments/:commentId/reactions',
|
||||||
zValidator('json', addCommentReactionRequestSchema),
|
zValidator('json', addCommentReactionRequestSchema),
|
||||||
@@ -305,6 +363,38 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
return c.json(await assetService.getComment(commentId, user.id))
|
return c.json(await assetService.getComment(commentId, user.id))
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
.patch('/comments/:commentId', zValidator('json', updateCommentRequestSchema), async (c) => {
|
||||||
|
const commentId = c.req.param('commentId')
|
||||||
|
const user = c.get('user')
|
||||||
|
const req = c.req.valid('json')
|
||||||
|
|
||||||
|
await authzService.hasPermission({
|
||||||
|
user,
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Comment,
|
||||||
|
id: commentId,
|
||||||
|
})
|
||||||
|
|
||||||
|
const updated = await assetService.updateComment({
|
||||||
|
commentId,
|
||||||
|
userId: user.id,
|
||||||
|
message: req.message,
|
||||||
|
isInternal: req.isInternal,
|
||||||
|
second: req.second,
|
||||||
|
attachmentIds: req.attachmentIds,
|
||||||
|
})
|
||||||
|
|
||||||
|
const context = await assetService.getAssetContext(updated.assetId)
|
||||||
|
await auditLogService.logAction({
|
||||||
|
action: AuditAction.comment_update,
|
||||||
|
teamId: context.teamId,
|
||||||
|
userId: user.id,
|
||||||
|
projectId: context.projectId,
|
||||||
|
itemId: commentId,
|
||||||
|
})
|
||||||
|
|
||||||
|
return c.json(updated)
|
||||||
|
})
|
||||||
.delete('/comments/:commentId', async (c) => {
|
.delete('/comments/:commentId', async (c) => {
|
||||||
const commentId = c.req.param('commentId')
|
const commentId = c.req.param('commentId')
|
||||||
const user = c.get('user')
|
const user = c.get('user')
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: teamId,
|
id: teamId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const attachment = await kanbanService.createAttachment(teamId, req)
|
const attachment = await kanbanService.createAttachment(teamId, user.id, req)
|
||||||
return c.json(attachment)
|
return c.json(attachment)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -123,7 +123,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: taskId,
|
id: taskId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const events = await kanbanService.listEvents(taskId)
|
const events = await kanbanService.listEvents(taskId, user.id)
|
||||||
return c.json({ data: events })
|
return c.json({ data: events })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { kanbanService } from '@shumai/core/src/kanban/kanban'
|
|||||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||||
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
||||||
|
import { HTTPException } from 'hono/http-exception'
|
||||||
|
import { authzService } from '@shumai/core/src/authz/authz'
|
||||||
import kanbanRoute from './index'
|
import kanbanRoute from './index'
|
||||||
|
|
||||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||||
@@ -19,6 +21,7 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
|
|||||||
ResourceType: {
|
ResourceType: {
|
||||||
Team: 'team',
|
Team: 'team',
|
||||||
Project: 'project',
|
Project: 'project',
|
||||||
|
Asset: 'asset',
|
||||||
KanbanGoal: 'kanbanGoal',
|
KanbanGoal: 'kanbanGoal',
|
||||||
KanbanTask: 'kanbanTask',
|
KanbanTask: 'kanbanTask',
|
||||||
},
|
},
|
||||||
@@ -51,6 +54,7 @@ describe('Kanban API Routes', () => {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
|
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||||
vi.mocked(auditLogService.logAction).mockResolvedValue({} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
vi.mocked(auditLogService.logAction).mockResolvedValue({} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
vi.mocked(notificationService.notifyKanbanTaskEvent).mockResolvedValue(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
vi.mocked(notificationService.notifyKanbanTaskEvent).mockResolvedValue(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
app = new Hono()
|
app = new Hono()
|
||||||
@@ -218,6 +222,7 @@ describe('Kanban API Routes', () => {
|
|||||||
status: 'READY',
|
status: 'READY',
|
||||||
goalId: 'goal-1',
|
goalId: 'goal-1',
|
||||||
}),
|
}),
|
||||||
|
'user-1',
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -248,7 +253,7 @@ describe('Kanban API Routes', () => {
|
|||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
expect(json.id).toBe(taskId)
|
expect(json.id).toBe(taskId)
|
||||||
expect(mockGet).toHaveBeenCalledWith(taskId)
|
expect(mockGet).toHaveBeenCalledWith(taskId, 'user-1')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('PATCH /teams/:teamId/kanban/tasks/:taskId', async () => {
|
it('PATCH /teams/:teamId/kanban/tasks/:taskId', async () => {
|
||||||
@@ -493,6 +498,74 @@ describe('Kanban API Routes', () => {
|
|||||||
expect(mockLinkAssets).toHaveBeenCalledWith(teamId, taskId, ['asset-1', 'asset-2'])
|
expect(mockLinkAssets).toHaveBeenCalledWith(teamId, taskId, ['asset-1', 'asset-2'])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('linking files the caller cannot read', () => {
|
||||||
|
const denyAsset = (deniedAssetId: string) =>
|
||||||
|
vi.mocked(authzService.hasPermission).mockImplementation(async (req) => {
|
||||||
|
if (req.type === 'asset' && req.id === deniedAssetId) {
|
||||||
|
throw new HTTPException(403, { message: 'User has only project scope' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('checks Read on every file linked to a task', async () => {
|
||||||
|
const mockLinkAssets = vi.spyOn(kanbanService, 'linkAssets').mockResolvedValue(undefined)
|
||||||
|
denyAsset('asset-2')
|
||||||
|
|
||||||
|
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/assets`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ assetIds: ['asset-1', 'asset-2'] }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(403)
|
||||||
|
expect(mockLinkAssets).not.toHaveBeenCalled()
|
||||||
|
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ type: 'asset', id: 'asset-1', permission: 'Read' }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('checks Read on the file when linking it from the file side', async () => {
|
||||||
|
const mockLinkAsset = vi.spyOn(kanbanService, 'linkAsset').mockResolvedValue(undefined)
|
||||||
|
denyAsset('asset-1')
|
||||||
|
|
||||||
|
const res = await app.request(`/teams/${teamId}/kanban/assets/asset-1/tasks`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ taskId }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(403)
|
||||||
|
expect(mockLinkAsset).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('checks Read on files passed when updating a task', async () => {
|
||||||
|
const mockUpdate = vi.spyOn(kanbanService, 'updateTask')
|
||||||
|
denyAsset('asset-9')
|
||||||
|
|
||||||
|
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ assetIds: ['asset-9'] }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(403)
|
||||||
|
expect(mockUpdate).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('checks Read on files passed when creating a task', async () => {
|
||||||
|
const mockCreate = vi.spyOn(kanbanService, 'createTask')
|
||||||
|
denyAsset('asset-9')
|
||||||
|
|
||||||
|
const res = await app.request(`/teams/${teamId}/kanban/tasks`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ title: 'Task', assetIds: ['asset-9'] }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(403)
|
||||||
|
expect(mockCreate).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('DELETE /teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async () => {
|
it('DELETE /teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async () => {
|
||||||
const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined)
|
const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined)
|
||||||
|
|
||||||
@@ -530,7 +603,7 @@ describe('Kanban API Routes', () => {
|
|||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
expect(json.total).toBe(1)
|
expect(json.total).toBe(1)
|
||||||
expect(json.data).toHaveLength(1)
|
expect(json.data).toHaveLength(1)
|
||||||
expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1')
|
expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1', 'user-1')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('POST /teams/:teamId/kanban/assets/:assetId/tasks', async () => {
|
it('POST /teams/:teamId/kanban/assets/:assetId/tasks', async () => {
|
||||||
@@ -585,7 +658,7 @@ describe('Kanban API Routes', () => {
|
|||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
expect(json.id).toBe('att-1')
|
expect(json.id).toBe('att-1')
|
||||||
expect(mockAttachment).toHaveBeenCalledWith(teamId, {
|
expect(mockAttachment).toHaveBeenCalledWith(teamId, 'user-1', {
|
||||||
fileName: 'test.png',
|
fileName: 'test.png',
|
||||||
size: 1024,
|
size: 1024,
|
||||||
contentType: 'image/png',
|
contentType: 'image/png',
|
||||||
@@ -683,7 +756,7 @@ describe('Kanban API Routes', () => {
|
|||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
expect(json.data).toHaveLength(1)
|
expect(json.data).toHaveLength(1)
|
||||||
expect(mockEvents).toHaveBeenCalledWith(taskId)
|
expect(mockEvents).toHaveBeenCalledWith(taskId, 'user-1')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -22,6 +22,21 @@ import { HTTPException } from 'hono/http-exception'
|
|||||||
|
|
||||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Linking a file to a task shows its name, folder path and thumbnail to everyone
|
||||||
|
* who can read the task, so the caller must be able to read each linked file.
|
||||||
|
*/
|
||||||
|
async function assertCanReadAssets(user: User, assetIds: string[] | undefined) {
|
||||||
|
for (const id of new Set(assetIds ?? [])) {
|
||||||
|
await authzService.hasPermission({
|
||||||
|
user,
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Asset,
|
||||||
|
id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const route = new Hono<{ Variables: { user: User } }>()
|
const route = new Hono<{ Variables: { user: User } }>()
|
||||||
.post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => {
|
.post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => {
|
||||||
const { teamId } = c.req.param()
|
const { teamId } = c.req.param()
|
||||||
@@ -40,6 +55,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
throw new HTTPException(403, { message: 'User is not a member of the team' })
|
throw new HTTPException(403, { message: 'User is not a member of the team' })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await assertCanReadAssets(user, req.assetIds)
|
||||||
|
|
||||||
const task = await kanbanService.createTask(teamId, req, user.id, role)
|
const task = await kanbanService.createTask(teamId, req, user.id, role)
|
||||||
|
|
||||||
await auditLogService.logAction({
|
await auditLogService.logAction({
|
||||||
@@ -89,7 +106,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: teamId,
|
id: teamId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const result = await kanbanService.listTasks(teamId, req)
|
const result = await kanbanService.listTasks(teamId, req, user.id)
|
||||||
return c.json(result)
|
return c.json(result)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -104,7 +121,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: taskId,
|
id: taskId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const task = await kanbanService.getTask(taskId)
|
const task = await kanbanService.getTask(taskId, user.id)
|
||||||
return c.json(task)
|
return c.json(task)
|
||||||
})
|
})
|
||||||
.patch(
|
.patch(
|
||||||
@@ -122,6 +139,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: taskId,
|
id: taskId,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await assertCanReadAssets(user, req.assetIds)
|
||||||
|
|
||||||
const existing = await kanbanService.getTask(taskId)
|
const existing = await kanbanService.getTask(taskId)
|
||||||
const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id)
|
const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id)
|
||||||
const task = await kanbanService.updateTask(taskId, req, user.id, role)
|
const task = await kanbanService.updateTask(taskId, req, user.id, role)
|
||||||
@@ -262,6 +281,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: taskId,
|
id: taskId,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await assertCanReadAssets(user, req.assetIds)
|
||||||
|
|
||||||
await kanbanService.linkAssets(teamId, taskId, req.assetIds)
|
await kanbanService.linkAssets(teamId, taskId, req.assetIds)
|
||||||
return c.json({ success: true })
|
return c.json({ success: true })
|
||||||
},
|
},
|
||||||
@@ -291,7 +312,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: teamId,
|
id: teamId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const tasks = await kanbanService.listTasksForAsset(teamId, assetId)
|
const tasks = await kanbanService.listTasksForAsset(teamId, assetId, user.id)
|
||||||
return c.json({ data: tasks, total: tasks.length })
|
return c.json({ data: tasks, total: tasks.length })
|
||||||
})
|
})
|
||||||
.post(
|
.post(
|
||||||
@@ -309,6 +330,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
id: req.taskId,
|
id: req.taskId,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await assertCanReadAssets(user, [assetId])
|
||||||
|
|
||||||
await kanbanService.linkAsset(teamId, req.taskId, assetId)
|
await kanbanService.linkAsset(teamId, req.taskId, assetId)
|
||||||
return c.json({ success: true })
|
return c.json({ success: true })
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { Hono } from 'hono'
|
||||||
|
import publicShareRoute from './public-share'
|
||||||
|
import { shareService } from '@shumai/core/src/share/share'
|
||||||
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||||
|
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||||
|
import { auth } from '@shumai/core/src/auth/auth'
|
||||||
|
import { ShareLinkPasswordInvalidError } from '@shumai/core/src/share/errors'
|
||||||
|
|
||||||
|
describe('public share print comments and frame api', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(auth.api, 'getSession').mockResolvedValue(null)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('GET /shares/:shareId/files/:fileId/comments/print returns share-scoped breadcrumbs and comments', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
id: 'share-1',
|
||||||
|
name: 'Client Review',
|
||||||
|
rootFolderId: 'share-root',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
watermarkConfigId: null,
|
||||||
|
fieldVisibility: { status: true, internalNote: false },
|
||||||
|
} as never)
|
||||||
|
|
||||||
|
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
|
||||||
|
id: 'file-1',
|
||||||
|
name: 'spot.mp4',
|
||||||
|
sizeByte: 100,
|
||||||
|
fileCount: 1,
|
||||||
|
type: 'file',
|
||||||
|
status: 'active',
|
||||||
|
proxyType: 'video',
|
||||||
|
fieldValues: [
|
||||||
|
{ fieldId: 'status', value: 'Approved' },
|
||||||
|
{ fieldId: 'internalNote', value: 'Private note' },
|
||||||
|
{ fieldId: 'rating', value: 3 },
|
||||||
|
],
|
||||||
|
ancestorFolders: [
|
||||||
|
{ id: 'inner', name: 'Inner Folder' },
|
||||||
|
{ id: 'share-root', name: 'Share Root' },
|
||||||
|
{ id: 'private-parent', name: 'Secret Project Folder' },
|
||||||
|
],
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file-1')
|
||||||
|
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file-1')
|
||||||
|
vi.spyOn(assetService, 'listAllComments').mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'c1',
|
||||||
|
assetId: 'file-1',
|
||||||
|
message: 'Great cut!',
|
||||||
|
annotations: null,
|
||||||
|
second: 3,
|
||||||
|
creator: { id: 'u1', name: 'Guest' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
|
const app = new Hono().route('/', publicShareRoute)
|
||||||
|
const res = await app.request('/shares/share-1/files/file-1/comments/print', {
|
||||||
|
headers: { 'x-share-password': 'secret' },
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(assetService.listAllComments).toHaveBeenCalledWith('file-1', undefined, {
|
||||||
|
excludeInternal: true,
|
||||||
|
})
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.breadcrumbs).toEqual(['Client Review', 'Inner Folder'])
|
||||||
|
expect(body.asset.ancestorFolders).toEqual([{ id: 'inner', name: 'Inner Folder' }])
|
||||||
|
expect(body.asset.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||||
|
expect(JSON.stringify(body)).not.toContain('Secret Project Folder')
|
||||||
|
expect(JSON.stringify(body)).not.toContain('private-parent')
|
||||||
|
expect(body.comments).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('GET /shares/:shareId/files/:fileId/comments/print returns 401 on invalid password', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue(
|
||||||
|
new ShareLinkPasswordInvalidError('Invalid password'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const app = new Hono().route('/', publicShareRoute)
|
||||||
|
const res = await app.request('/shares/share-1/files/file-1/comments/print')
|
||||||
|
|
||||||
|
expect(res.status).toBe(401)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('GET /shares/:shareId/files/:fileId/comments/frame passes watermarkConfigId and password query param', async () => {
|
||||||
|
const verifySpy = vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
id: 'share-1',
|
||||||
|
name: 'Watermarked Review',
|
||||||
|
rootFolderId: 'share-root',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
watermarkConfigId: 'wm-1',
|
||||||
|
} as never)
|
||||||
|
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('target-file-1')
|
||||||
|
const extractSpy = vi.spyOn(commentFrameService, 'extractFrame').mockResolvedValue({
|
||||||
|
buffer: Buffer.from('wm-webp'),
|
||||||
|
mimeType: 'image/webp',
|
||||||
|
})
|
||||||
|
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||||
|
|
||||||
|
const app = new Hono().route('/', publicShareRoute)
|
||||||
|
const res = await app.request(
|
||||||
|
'/shares/share-1/files/file-1/comments/frame?second=4.2&width=400&p=pw123',
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.headers.get('content-type')).toBe('image/webp')
|
||||||
|
expect(verifySpy).toHaveBeenCalledWith('share-1', 'file-1', 'pw123')
|
||||||
|
expect(extractSpy).toHaveBeenCalledWith({
|
||||||
|
assetId: 'target-file-1',
|
||||||
|
second: 4.2,
|
||||||
|
width: 400,
|
||||||
|
watermarkConfigId: 'wm-1',
|
||||||
|
signal: expect.any(AbortSignal),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('GET /shares/:shareId/files/:fileId/comments excludes internal comments', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
id: 'share-1',
|
||||||
|
rootFolderId: 'share-root',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
} as never)
|
||||||
|
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file-1')
|
||||||
|
const listSpy = vi.spyOn(assetService, 'listComments').mockResolvedValue({
|
||||||
|
data: [],
|
||||||
|
pageInfo: { cursor: undefined, total: 0 },
|
||||||
|
})
|
||||||
|
|
||||||
|
const app = new Hono().route('/', publicShareRoute)
|
||||||
|
const res = await app.request('/shares/share-1/files/file-1/comments')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(listSpy).toHaveBeenCalledWith('file-1', expect.anything(), undefined, {
|
||||||
|
excludeInternal: true,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('POST /shares/:shareId/files/:fileId/comments rejects isInternal=true with 400', async () => {
|
||||||
|
const app = new Hono().route('/', publicShareRoute)
|
||||||
|
const res = await app.request('/shares/share-1/files/file-1/comments', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ message: 'secret', attachmentIds: [], isInternal: true }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(400)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,11 +1,19 @@
|
|||||||
import { Hono } from 'hono'
|
import { Hono } from 'hono'
|
||||||
import type { Context } from 'hono'
|
import type { Context } from 'hono'
|
||||||
|
import { HTTPException } from 'hono/http-exception'
|
||||||
import { getCookie } from 'hono/cookie'
|
import { getCookie } from 'hono/cookie'
|
||||||
import { zValidator } from '@hono/zod-validator'
|
import { zValidator } from '@hono/zod-validator'
|
||||||
import { shareService } from '@shumai/core/src/share/share'
|
import { shareService } from '@shumai/core/src/share/share'
|
||||||
|
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||||
import { assetService } from '@shumai/core/src/asset/asset'
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||||
import { paginationParamsSchema, assetTypeFilterSchema } from '@shumai/dtos'
|
import {
|
||||||
|
paginationParamsSchema,
|
||||||
|
assetTypeFilterSchema,
|
||||||
|
commentFrameQuerySchema,
|
||||||
|
recordShareViewRequestSchema,
|
||||||
|
} from '@shumai/dtos'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||||
import { FieldInfo } from '@shumai/dtos'
|
import { FieldInfo } from '@shumai/dtos'
|
||||||
@@ -115,6 +123,20 @@ async function applyWatermarkToAssetMedia(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps only the custom field values the share link is configured to show.
|
||||||
|
* Fields are hidden by default; `fieldVisibility` lists the keys turned on
|
||||||
|
* for this share, matching what `GET /shares/:shareId/fields` returns.
|
||||||
|
*/
|
||||||
|
function filterSharedFieldValues(asset: AssetInfo, fieldVisibility: unknown): AssetInfo {
|
||||||
|
if (!asset.fieldValues) return asset
|
||||||
|
const visibility = (fieldVisibility || {}) as Record<string, boolean>
|
||||||
|
return {
|
||||||
|
...asset,
|
||||||
|
fieldValues: asset.fieldValues.filter((fv) => Boolean(visibility[fv.fieldId])),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const app = new Hono()
|
const app = new Hono()
|
||||||
|
|
||||||
function toFieldInfo(
|
function toFieldInfo(
|
||||||
@@ -133,6 +155,9 @@ function toFieldInfo(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function handlePublicShareError(c: Context, err: unknown) {
|
export function handlePublicShareError(c: Context, err: unknown) {
|
||||||
|
if (err instanceof HTTPException) {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
if (err instanceof ShareLinkPasswordInvalidError) {
|
if (err instanceof ShareLinkPasswordInvalidError) {
|
||||||
return c.json({ error: 'Unauthorized' }, 401)
|
return c.json({ error: 'Unauthorized' }, 401)
|
||||||
}
|
}
|
||||||
@@ -156,7 +181,36 @@ const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
|||||||
assetType: assetTypeFilterSchema.optional().default('file'),
|
assetType: assetTypeFilterSchema.optional().default('file'),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
async function getPublicShareUserId(c: Context, shareId: string) {
|
||||||
|
const session = await auth.api.getSession({ headers: c.req.raw.headers })
|
||||||
|
if (session?.user) return session.user.id
|
||||||
|
|
||||||
|
const token = getCookie(c, `shumai_guest_${shareId}`) || getCookie(c, 'shumai_guest')
|
||||||
|
const verified = token && verifyGuestToken(token, shareId)
|
||||||
|
if (!verified) return undefined
|
||||||
|
|
||||||
|
const guestUser = await userService.getUserById(verified.userId)
|
||||||
|
return guestUser?.guestEmail ? guestUser.id : undefined
|
||||||
|
}
|
||||||
|
|
||||||
const route = app
|
const route = app
|
||||||
|
.post('/shares/:shareId/views', zValidator('json', recordShareViewRequestSchema), async (c) => {
|
||||||
|
const shareId = c.req.param('shareId')
|
||||||
|
const password = c.req.header('x-share-password')
|
||||||
|
const { assetId, isShareEntry } = c.req.valid('json')
|
||||||
|
try {
|
||||||
|
const share = await shareService.verifyPublicAccess(shareId, assetId, password)
|
||||||
|
const targetId =
|
||||||
|
assetId && assetId !== share.rootFolderId
|
||||||
|
? await assetService.resolveLatestVersionId(assetId)
|
||||||
|
: undefined
|
||||||
|
const userId = await getPublicShareUserId(c, shareId)
|
||||||
|
await shareActivityService.recordView(shareId, { assetId: targetId, isShareEntry, userId })
|
||||||
|
return c.body(null, 204)
|
||||||
|
} catch (err) {
|
||||||
|
return handlePublicShareError(c, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
.get('/shares/:shareId/info', async (c) => {
|
.get('/shares/:shareId/info', async (c) => {
|
||||||
const shareId = c.req.param('shareId')
|
const shareId = c.req.param('shareId')
|
||||||
const password = c.req.header('x-share-password')
|
const password = c.req.header('x-share-password')
|
||||||
@@ -222,13 +276,16 @@ const route = app
|
|||||||
order = parts[1]
|
order = parts[1]
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await assetService.listChildren({
|
const res = await assetService.listChildren(
|
||||||
...req,
|
{
|
||||||
assetId: folderId,
|
...req,
|
||||||
assetType: req.assetType || 'file',
|
assetId: folderId,
|
||||||
sort,
|
assetType: req.assetType || 'file',
|
||||||
order,
|
sort,
|
||||||
})
|
order,
|
||||||
|
},
|
||||||
|
{ excludeInternalComments: true },
|
||||||
|
)
|
||||||
|
|
||||||
if (shareLink.watermarkConfigId && res.data.length > 0) {
|
if (shareLink.watermarkConfigId && res.data.length > 0) {
|
||||||
// Resolve symlink targets once and reuse for the media lookup, so each
|
// Resolve symlink targets once and reuse for the media lookup, so each
|
||||||
@@ -260,6 +317,8 @@ const route = app
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
res.data = res.data.map((item) => filterSharedFieldValues(item, shareLink.fieldVisibility))
|
||||||
|
|
||||||
return c.json(res)
|
return c.json(res)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return handlePublicShareError(c, err)
|
return handlePublicShareError(c, err)
|
||||||
@@ -274,7 +333,10 @@ const route = app
|
|||||||
try {
|
try {
|
||||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||||
|
|
||||||
let asset = await assetService.getAsset({ assetId: fileId })
|
let asset = await assetService.getAsset(
|
||||||
|
{ assetId: fileId },
|
||||||
|
{ excludeInternalComments: true },
|
||||||
|
)
|
||||||
|
|
||||||
// Only video/image/3d assets are subject to watermark protection; skip the
|
// Only video/image/3d assets are subject to watermark protection; skip the
|
||||||
// watermark lookup entirely for other media types (pdf, audio, ...).
|
// watermark lookup entirely for other media types (pdf, audio, ...).
|
||||||
@@ -298,19 +360,25 @@ const route = app
|
|||||||
asset.media.hls.url = `/api/shares/${shareLink.id}/files/${asset.id}/m3u8/master.m3u8${pwQuery}`
|
asset.media.hls.url = `/api/shares/${shareLink.id}/files/${asset.id}/m3u8/master.m3u8${pwQuery}`
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.json(asset)
|
return c.json(filterSharedFieldValues(asset, shareLink.fieldVisibility))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return handlePublicShareError(c, err)
|
return handlePublicShareError(c, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.post(
|
.post(
|
||||||
'/shares/:shareId/files/:fileId/download-url',
|
'/shares/:shareId/files/:fileId/download-url',
|
||||||
zValidator('json', z.object({ key: z.string().min(1) })),
|
zValidator(
|
||||||
|
'json',
|
||||||
|
z.object({
|
||||||
|
key: z.string().min(1),
|
||||||
|
purpose: z.enum(['download', 'prepare', 'clipboard']).default('download'),
|
||||||
|
}),
|
||||||
|
),
|
||||||
async (c) => {
|
async (c) => {
|
||||||
const shareId = c.req.param('shareId')
|
const shareId = c.req.param('shareId')
|
||||||
const fileId = c.req.param('fileId')
|
const fileId = c.req.param('fileId')
|
||||||
const password = c.req.header('x-share-password')
|
const password = c.req.header('x-share-password')
|
||||||
const { key } = c.req.valid('json')
|
const { key, purpose } = c.req.valid('json')
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||||
@@ -323,7 +391,16 @@ const route = app
|
|||||||
return c.json({ error: 'Invalid key' }, 400)
|
return c.json({ error: 'Invalid key' }, 400)
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = await assetService.getDownloadUrl(fileId, key)
|
const { url, assetId } = await assetService.getDownloadUrlWithAsset(fileId, key)
|
||||||
|
if (assetId !== fileId) await shareService.verifyPublicAccess(shareId, assetId, password)
|
||||||
|
if (purpose === 'download') {
|
||||||
|
const userId = await getPublicShareUserId(c, shareId)
|
||||||
|
await shareActivityService.recordEvent(shareId, {
|
||||||
|
kind: 'asset_downloaded',
|
||||||
|
assetId,
|
||||||
|
userId,
|
||||||
|
})
|
||||||
|
}
|
||||||
return c.json({ url })
|
return c.json({ url })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return handlePublicShareError(c, err)
|
return handlePublicShareError(c, err)
|
||||||
@@ -343,32 +420,107 @@ const route = app
|
|||||||
await shareService.verifyPublicAccess(shareId, fileId, password)
|
await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||||
|
|
||||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||||
let userId: string | undefined
|
const userId = await getPublicShareUserId(c, shareId)
|
||||||
const session = await auth.api.getSession({
|
const res = await assetService.listComments(targetFileId, req, userId, {
|
||||||
headers: c.req.raw.headers,
|
excludeInternal: true,
|
||||||
})
|
})
|
||||||
if (session?.user) {
|
|
||||||
userId = session.user.id
|
|
||||||
} else {
|
|
||||||
const cookieName = `shumai_guest_${shareId}`
|
|
||||||
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
|
|
||||||
if (token) {
|
|
||||||
const verified = verifyGuestToken(token, shareId)
|
|
||||||
if (verified) {
|
|
||||||
const guestUser = await userService.getUserById(verified.userId)
|
|
||||||
if (guestUser && guestUser.guestEmail) {
|
|
||||||
userId = guestUser.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const res = await assetService.listComments(targetFileId, req, userId)
|
|
||||||
return c.json(res)
|
return c.json(res)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return handlePublicShareError(c, err)
|
return handlePublicShareError(c, err)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
.get('/shares/:shareId/files/:fileId/comments/print', async (c) => {
|
||||||
|
const shareId = c.req.param('shareId')
|
||||||
|
const fileId = c.req.param('fileId')
|
||||||
|
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||||
|
|
||||||
|
try {
|
||||||
|
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||||
|
let asset = await assetService.getAsset(
|
||||||
|
{ assetId: fileId },
|
||||||
|
{ excludeInternalComments: true },
|
||||||
|
)
|
||||||
|
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||||
|
|
||||||
|
if (
|
||||||
|
shareLink.watermarkConfigId &&
|
||||||
|
(asset.proxyType === 'video' || asset.proxyType === 'image' || asset.proxyType === '3d')
|
||||||
|
) {
|
||||||
|
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
|
||||||
|
[targetAssetId],
|
||||||
|
shareLink.watermarkConfigId,
|
||||||
|
)
|
||||||
|
asset = await applyWatermarkToAssetMedia(
|
||||||
|
asset,
|
||||||
|
wfMap.get(targetAssetId) ?? null,
|
||||||
|
shareLink.id,
|
||||||
|
password,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||||
|
const userId = await getPublicShareUserId(c, shareId)
|
||||||
|
const comments = await assetService.listAllComments(targetFileId, userId, {
|
||||||
|
excludeInternal: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Scope breadcrumbs strictly to folders inside the share link root so private
|
||||||
|
// project and parent folder names are never leaked.
|
||||||
|
const ancestors = asset.ancestorFolders ?? []
|
||||||
|
const rootIndex = ancestors.findIndex((f) => f.id === shareLink.rootFolderId)
|
||||||
|
const scopedAncestors = rootIndex !== -1 ? ancestors.slice(0, rootIndex) : []
|
||||||
|
const scopedFolders = [...scopedAncestors]
|
||||||
|
.reverse()
|
||||||
|
.map((f) => f.name)
|
||||||
|
.filter((name): name is string => Boolean(name))
|
||||||
|
const breadcrumbs = shareLink.name ? [shareLink.name, ...scopedFolders] : scopedFolders
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
asset: {
|
||||||
|
...filterSharedFieldValues(asset, shareLink.fieldVisibility),
|
||||||
|
ancestorFolders: scopedAncestors,
|
||||||
|
},
|
||||||
|
breadcrumbs,
|
||||||
|
comments,
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
return handlePublicShareError(c, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.get(
|
||||||
|
'/shares/:shareId/files/:fileId/comments/frame',
|
||||||
|
zValidator('query', commentFrameQuerySchema),
|
||||||
|
async (c) => {
|
||||||
|
const shareId = c.req.param('shareId')
|
||||||
|
const fileId = c.req.param('fileId')
|
||||||
|
const password =
|
||||||
|
c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||||
|
const { second, width } = c.req.valid('query')
|
||||||
|
|
||||||
|
try {
|
||||||
|
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||||
|
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||||
|
const result = await commentFrameService.extractFrame({
|
||||||
|
assetId: targetFileId,
|
||||||
|
second,
|
||||||
|
width,
|
||||||
|
watermarkConfigId: shareLink.watermarkConfigId,
|
||||||
|
signal: c.req.raw.signal,
|
||||||
|
})
|
||||||
|
|
||||||
|
return c.body(new Uint8Array(result.buffer), 200, {
|
||||||
|
'Content-Type': result.mimeType,
|
||||||
|
'Cache-Control': 'private, max-age=300',
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof HTTPException) {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
return handlePublicShareError(c, err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
.post(
|
.post(
|
||||||
'/shares/:shareId/files/:fileId/comments',
|
'/shares/:shareId/files/:fileId/comments',
|
||||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||||
@@ -382,49 +534,36 @@ const route = app
|
|||||||
return c.json({ error: 'Attachments are not allowed on public share comments' }, 400)
|
return c.json({ error: 'Attachments are not allowed on public share comments' }, 400)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (req.isInternal) {
|
||||||
|
return c.json({ error: 'Internal comments are not allowed on public share links' }, 400)
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const shareLink = await shareService.getShareLink(shareId)
|
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||||
await shareService.verifyPublicAccess(shareId, fileId, password)
|
|
||||||
|
|
||||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||||
|
|
||||||
const teamId = await projectService.getProjectTeam(shareLink.projectId)
|
const teamId = await projectService.getProjectTeam(shareLink.projectId)
|
||||||
|
|
||||||
// Identify user
|
const userId = await getPublicShareUserId(c, shareId)
|
||||||
let userId: string | null = null
|
|
||||||
const session = await auth.api.getSession({
|
|
||||||
headers: c.req.raw.headers,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (session?.user) {
|
|
||||||
userId = session.user.id
|
|
||||||
} else {
|
|
||||||
const cookieName = `shumai_guest_${shareId}`
|
|
||||||
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
|
|
||||||
if (token) {
|
|
||||||
const verified = verifyGuestToken(token, shareId)
|
|
||||||
if (verified) {
|
|
||||||
const guestUser = await userService.getUserById(verified.userId)
|
|
||||||
if (guestUser && guestUser.guestEmail) {
|
|
||||||
userId = guestUser.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return c.json({ error: 'Unauthorized' }, 401)
|
return c.json({ error: 'Unauthorized' }, 401)
|
||||||
}
|
}
|
||||||
|
|
||||||
const comment = await assetService.createComment({
|
const comment = await assetService.createComment(
|
||||||
assetId: targetFileId,
|
{
|
||||||
userId: userId,
|
assetId: targetFileId,
|
||||||
replyToId: req.replyToId,
|
userId,
|
||||||
message: req.message,
|
replyToId: req.replyToId,
|
||||||
annotations: req.annotations,
|
message: req.message,
|
||||||
second: req.second,
|
annotations: req.annotations,
|
||||||
attachmentIds: req.attachmentIds,
|
second: req.second,
|
||||||
})
|
attachmentIds: req.attachmentIds,
|
||||||
|
isInternal: false,
|
||||||
|
},
|
||||||
|
{ shareLinkId: shareId },
|
||||||
|
)
|
||||||
|
|
||||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,15 @@ import shareRoute from './share'
|
|||||||
import publicShareRoute from './public-share'
|
import publicShareRoute from './public-share'
|
||||||
import { authMiddleware } from './middleware/auth'
|
import { authMiddleware } from './middleware/auth'
|
||||||
import { shareService } from '@shumai/core/src/share/share'
|
import { shareService } from '@shumai/core/src/share/share'
|
||||||
|
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||||
|
import { HTTPException } from 'hono/http-exception'
|
||||||
import { assetService } from '@shumai/core/src/asset/asset'
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||||
import { ShareLinkPasswordInvalidError, ShareLinkExpiredError } from '@shumai/core/src/share/errors'
|
import {
|
||||||
|
ShareLinkPasswordInvalidError,
|
||||||
|
ShareLinkExpiredError,
|
||||||
|
ShareLinkNotFoundError,
|
||||||
|
} from '@shumai/core/src/share/errors'
|
||||||
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
|
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
|
||||||
import { userService } from '@shumai/core/src/user/user'
|
import { userService } from '@shumai/core/src/user/user'
|
||||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||||
@@ -93,6 +99,82 @@ describe('Share API', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// Public Routes
|
// Public Routes
|
||||||
|
describe('POST /shares/:shareId/views', () => {
|
||||||
|
test('attributes an authorized asset view to a verified guest', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
rootFolderId: 'folder1',
|
||||||
|
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||||
|
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('asset1')
|
||||||
|
vi.spyOn(userService, 'getUserById').mockResolvedValue({
|
||||||
|
id: 'guest1',
|
||||||
|
guestEmail: 'alice@example.com',
|
||||||
|
} as Awaited<ReturnType<typeof userService.getUserById>>)
|
||||||
|
const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined)
|
||||||
|
const token = createGuestToken({ userId: 'guest1', shareId: 'share1' })
|
||||||
|
|
||||||
|
const res = await app.request('/shares/share1/views', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'x-share-password': 'pass',
|
||||||
|
Cookie: `shumai_guest_share1=${token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ assetId: 'alias1', isShareEntry: true }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(204)
|
||||||
|
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'alias1', 'pass')
|
||||||
|
expect(record).toHaveBeenCalledWith('share1', {
|
||||||
|
assetId: 'asset1',
|
||||||
|
isShareEntry: true,
|
||||||
|
userId: 'guest1',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a rejected view leaves the counter and history alone', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue(
|
||||||
|
new ShareLinkPasswordInvalidError('Incorrect password'),
|
||||||
|
)
|
||||||
|
const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined)
|
||||||
|
const res = await app.request('/shares/share1/views', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: '{}',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(401)
|
||||||
|
expect(record).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('GET /shares/:shareId/activities', () => {
|
||||||
|
test('returns the requested page to a share reader', async () => {
|
||||||
|
const list = vi.spyOn(shareActivityService, 'list').mockResolvedValue({
|
||||||
|
data: [],
|
||||||
|
pageInfo: { total: 0 },
|
||||||
|
})
|
||||||
|
const res = await app.request('/shares/share1/activities?first=20')
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.json()).toEqual({ data: [], pageInfo: { total: 0 } })
|
||||||
|
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'share1',
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Share,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
expect(list).toHaveBeenCalledWith('share1', { first: 20 })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('denies access to activity without share read permission', async () => {
|
||||||
|
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new HTTPException(403))
|
||||||
|
const list = vi.spyOn(shareActivityService, 'list')
|
||||||
|
const res = await app.request('/shares/share1/activities')
|
||||||
|
expect(res.status).toBe(403)
|
||||||
|
expect(list).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('GET /shares/:shareId/info', () => {
|
describe('GET /shares/:shareId/info', () => {
|
||||||
test('Success', async () => {
|
test('Success', async () => {
|
||||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||||
@@ -101,6 +183,8 @@ describe('Share API', () => {
|
|||||||
isDisabled: false,
|
isDisabled: false,
|
||||||
allowDownload: false,
|
allowDownload: false,
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: true,
|
hasPassword: true,
|
||||||
rootFolderId: 'folder1',
|
rootFolderId: 'folder1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
@@ -134,6 +218,8 @@ describe('Share API', () => {
|
|||||||
isDisabled: false,
|
isDisabled: false,
|
||||||
allowDownload: false,
|
allowDownload: false,
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: true,
|
hasPassword: true,
|
||||||
rootFolderId: 'folder1',
|
rootFolderId: 'folder1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
@@ -161,6 +247,8 @@ describe('Share API', () => {
|
|||||||
isDisabled: false,
|
isDisabled: false,
|
||||||
allowDownload: false,
|
allowDownload: false,
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: true,
|
hasPassword: true,
|
||||||
rootFolderId: 'folder1',
|
rootFolderId: 'folder1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
@@ -217,6 +305,7 @@ describe('Share API', () => {
|
|||||||
sort: 'name',
|
sort: 'name',
|
||||||
order: 'asc',
|
order: 'asc',
|
||||||
}),
|
}),
|
||||||
|
{ excludeInternalComments: true },
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -350,6 +439,119 @@ describe('Share API', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('public share field values', () => {
|
||||||
|
const shareLinkWithFields = {
|
||||||
|
id: 'share1',
|
||||||
|
name: 'My Share',
|
||||||
|
isDisabled: false,
|
||||||
|
allowDownload: false,
|
||||||
|
rootFolderId: 'folder1',
|
||||||
|
projectId: 'project1',
|
||||||
|
password: null,
|
||||||
|
expireAt: null,
|
||||||
|
watermarkConfigId: null,
|
||||||
|
fieldVisibility: { status: true, internalNote: false },
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
} as any
|
||||||
|
|
||||||
|
const assetWithFields = {
|
||||||
|
id: 'file1',
|
||||||
|
name: 'a.png',
|
||||||
|
sizeByte: 1,
|
||||||
|
fileCount: 0,
|
||||||
|
type: 'file',
|
||||||
|
status: 'processed',
|
||||||
|
proxyType: 'pdf',
|
||||||
|
fieldValues: [
|
||||||
|
{ fieldId: 'status', value: 'Approved' },
|
||||||
|
{ fieldId: 'internalNote', value: 'not for guests' },
|
||||||
|
{ fieldId: 'rating', value: 3 },
|
||||||
|
],
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
} as any
|
||||||
|
|
||||||
|
test('children only include field values visible on the share', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields)
|
||||||
|
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||||
|
data: [assetWithFields],
|
||||||
|
pageInfo: { total: 1, cursor: undefined },
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('children with watermark only include field values visible on the share', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
...shareLinkWithFields,
|
||||||
|
watermarkConfigId: 'cfg1',
|
||||||
|
})
|
||||||
|
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||||
|
data: [assetWithFields],
|
||||||
|
pageInfo: { total: 1, cursor: undefined },
|
||||||
|
})
|
||||||
|
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementation(async (id) => id)
|
||||||
|
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||||
|
|
||||||
|
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('children include no field values when the share shows no fields', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
...shareLinkWithFields,
|
||||||
|
fieldVisibility: null,
|
||||||
|
})
|
||||||
|
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||||
|
data: [assetWithFields],
|
||||||
|
pageInfo: { total: 1, cursor: undefined },
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.data[0].fieldValues).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('file detail only includes field values visible on the share', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields)
|
||||||
|
vi.spyOn(assetService, 'getAsset').mockResolvedValue(assetWithFields)
|
||||||
|
|
||||||
|
const res = await app.request('/shares/share1/files/file1')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('file detail with watermark only includes field values visible on the share', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
...shareLinkWithFields,
|
||||||
|
watermarkConfigId: 'cfg1',
|
||||||
|
})
|
||||||
|
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
|
||||||
|
...assetWithFields,
|
||||||
|
proxyType: 'image',
|
||||||
|
media: { proxyType: 'image', videoTranscodes: [], imageTranscodes: [] },
|
||||||
|
})
|
||||||
|
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file1')
|
||||||
|
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||||
|
|
||||||
|
const res = await app.request('/shares/share1/files/file1')
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('GET /shares/:shareId/files/:fileId', () => {
|
describe('GET /shares/:shareId/files/:fileId', () => {
|
||||||
const shareLinkWithWatermark = {
|
const shareLinkWithWatermark = {
|
||||||
id: 'share1',
|
id: 'share1',
|
||||||
@@ -712,6 +914,8 @@ describe('Share API', () => {
|
|||||||
rootFolderId: 'root1',
|
rootFolderId: 'root1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: false,
|
hasPassword: false,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
@@ -756,6 +960,8 @@ describe('Share API', () => {
|
|||||||
rootFolderId: 'root1',
|
rootFolderId: 'root1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: false,
|
hasPassword: false,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
@@ -813,6 +1019,8 @@ describe('Share API', () => {
|
|||||||
rootFolderId: 'root1',
|
rootFolderId: 'root1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: false,
|
hasPassword: false,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
@@ -844,6 +1052,8 @@ describe('Share API', () => {
|
|||||||
rootFolderId: 'root1',
|
rootFolderId: 'root1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: false,
|
hasPassword: false,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
@@ -888,6 +1098,8 @@ describe('Share API', () => {
|
|||||||
rootFolderId: 'root1',
|
rootFolderId: 'root1',
|
||||||
projectId: 'project1',
|
projectId: 'project1',
|
||||||
isExpired: false,
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
hasPassword: false,
|
hasPassword: false,
|
||||||
watermarkStatus: 'processing',
|
watermarkStatus: 'processing',
|
||||||
watermarkConfigId: 'cfg1',
|
watermarkConfigId: 'cfg1',
|
||||||
@@ -976,12 +1188,60 @@ describe('Share API', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('POST /shares/:shareId/files/:fileId/download-url', () => {
|
describe('POST /shares/:shareId/files/:fileId/download-url', () => {
|
||||||
|
test('requires share access to the concrete asset selected for download', async () => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess')
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
allowDownload: true,
|
||||||
|
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||||
|
.mockRejectedValueOnce(new ShareLinkNotFoundError('Asset is not shared'))
|
||||||
|
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
|
||||||
|
url: 'https://s3.example.com/download',
|
||||||
|
assetId: 'unshared',
|
||||||
|
})
|
||||||
|
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
|
||||||
|
const res = await app.request('/shares/share1/files/file1/download-url', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ key: 'files/download.png' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(404)
|
||||||
|
expect(await res.json()).toEqual({ error: 'Asset is not shared' })
|
||||||
|
expect(record).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
test.each(['prepare', 'clipboard'])(
|
||||||
|
'does not count a URL requested for %s',
|
||||||
|
async (purpose) => {
|
||||||
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
|
allowDownload: true,
|
||||||
|
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||||
|
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
|
||||||
|
url: 'https://s3.example.com/download',
|
||||||
|
assetId: 'target1',
|
||||||
|
})
|
||||||
|
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
|
||||||
|
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ key: 'files/target1/fly.png', purpose }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(record).not.toHaveBeenCalled()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
test('Success for symlink asset in share', async () => {
|
test('Success for symlink asset in share', async () => {
|
||||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||||
allowDownload: true,
|
allowDownload: true,
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
} as any)
|
} as any)
|
||||||
vi.spyOn(assetService, 'getDownloadUrl').mockResolvedValue('https://s3.example.com/download')
|
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
|
||||||
|
url: 'https://s3.example.com/download',
|
||||||
|
assetId: 'target1',
|
||||||
|
})
|
||||||
|
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
|
||||||
|
|
||||||
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -993,7 +1253,15 @@ describe('Share API', () => {
|
|||||||
const body = await res.json()
|
const body = await res.json()
|
||||||
expect(body.url).toBe('https://s3.example.com/download')
|
expect(body.url).toBe('https://s3.example.com/download')
|
||||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined)
|
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined)
|
||||||
expect(assetService.getDownloadUrl).toHaveBeenCalledWith('symlink1', 'files/target1/fly.png')
|
expect(assetService.getDownloadUrlWithAsset).toHaveBeenCalledWith(
|
||||||
|
'symlink1',
|
||||||
|
'files/target1/fly.png',
|
||||||
|
)
|
||||||
|
expect(record).toHaveBeenCalledWith('share1', {
|
||||||
|
kind: 'asset_downloaded',
|
||||||
|
assetId: 'target1',
|
||||||
|
userId: undefined,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('Rejects when allowDownload is disabled', async () => {
|
test('Rejects when allowDownload is disabled', async () => {
|
||||||
@@ -1004,8 +1272,8 @@ describe('Share API', () => {
|
|||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
} as any)
|
} as any)
|
||||||
const getDownloadUrlSpy = vi
|
const getDownloadUrlSpy = vi
|
||||||
.spyOn(assetService, 'getDownloadUrl')
|
.spyOn(assetService, 'getDownloadUrlWithAsset')
|
||||||
.mockResolvedValue('https://s3.example.com/download')
|
.mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'target1' })
|
||||||
|
|
||||||
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -1173,6 +1441,7 @@ describe('Share API', () => {
|
|||||||
userId: 'guest1',
|
userId: 'guest1',
|
||||||
message: 'hello from alice',
|
message: 'hello from alice',
|
||||||
}),
|
}),
|
||||||
|
{ shareLinkId: 'share1' },
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ import { Hono } from 'hono'
|
|||||||
import { zValidator } from '@hono/zod-validator'
|
import { zValidator } from '@hono/zod-validator'
|
||||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||||
import { shareService } from '@shumai/core/src/share/share'
|
import { shareService } from '@shumai/core/src/share/share'
|
||||||
|
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||||
import { projectService } from '@shumai/core/src/project/project'
|
import { projectService } from '@shumai/core/src/project/project'
|
||||||
import {
|
import {
|
||||||
createShareLinkRequestSchema,
|
createShareLinkRequestSchema,
|
||||||
updateShareLinkRequestSchema,
|
updateShareLinkRequestSchema,
|
||||||
listShareLinksRequestSchema,
|
listShareLinksRequestSchema,
|
||||||
|
paginationParamsSchema,
|
||||||
addAssetToShareRequestSchema,
|
addAssetToShareRequestSchema,
|
||||||
updateShareLinkWatermarkRequestSchema,
|
updateShareLinkWatermarkRequestSchema,
|
||||||
AuditAction,
|
AuditAction,
|
||||||
@@ -90,6 +92,16 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
const shareLink = await shareService.getShareLink(shareId)
|
const shareLink = await shareService.getShareLink(shareId)
|
||||||
return c.json(shareLink)
|
return c.json(shareLink)
|
||||||
})
|
})
|
||||||
|
.get('/shares/:shareId/activities', zValidator('query', paginationParamsSchema), async (c) => {
|
||||||
|
const shareId = c.req.param('shareId')
|
||||||
|
await authzService.hasPermission({
|
||||||
|
user: c.get('user'),
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Share,
|
||||||
|
id: shareId,
|
||||||
|
})
|
||||||
|
return c.json(await shareActivityService.list(shareId, c.req.valid('query')))
|
||||||
|
})
|
||||||
.put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
|
.put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
|
||||||
const shareId = c.req.param('shareId')
|
const shareId = c.req.param('shareId')
|
||||||
const user = c.get('user')
|
const user = c.get('user')
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||||
import { prisma } from '@shumai/db'
|
import { getPrismaTestingHelper, prisma } from '@shumai/db'
|
||||||
import { setupTestDbHooks } from '@shumai/db/test'
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
import { HTTPException } from 'hono/http-exception'
|
import { HTTPException } from 'hono/http-exception'
|
||||||
|
|
||||||
@@ -941,7 +941,7 @@ describe('AssetService', () => {
|
|||||||
).resolves.not.toThrow()
|
).resolves.not.toThrow()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('deleteComment cleans up S3 attachment files and database records', async () => {
|
it('cleans up deleted comment attachments through the asset cleanup job', async () => {
|
||||||
const { user, project, assets } = await setupBasicAssets()
|
const { user, project, assets } = await setupBasicAssets()
|
||||||
|
|
||||||
// 1. Create StorageKey and Asset for attachment
|
// 1. Create StorageKey and Asset for attachment
|
||||||
@@ -949,15 +949,15 @@ describe('AssetService', () => {
|
|||||||
data: {
|
data: {
|
||||||
key: 'attachments/test-attachment-file.png',
|
key: 'attachments/test-attachment-file.png',
|
||||||
status: 'active',
|
status: 'active',
|
||||||
|
createdAt: new Date(Date.now() - 60_000),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const attachmentAsset = await prisma.asset.create({
|
const attachmentAsset = await prisma.asset.create({
|
||||||
data: {
|
data: {
|
||||||
name: 'test-attachment-file.png',
|
name: 'test-attachment-file.png',
|
||||||
type: AssetType.file,
|
type: AssetType.attachment,
|
||||||
projectId: project.id,
|
projectId: project.id,
|
||||||
parentId: assets.root.id,
|
|
||||||
creatorId: user.id,
|
creatorId: user.id,
|
||||||
storageKeyId: storageKey.id,
|
storageKeyId: storageKey.id,
|
||||||
sizeByte: 100,
|
sizeByte: 100,
|
||||||
@@ -988,18 +988,278 @@ describe('AssetService', () => {
|
|||||||
// 5. Verify the comment is deleted from DB
|
// 5. Verify the comment is deleted from DB
|
||||||
await expect(prisma.assetComment.findUnique({ where: { id: comment.id } })).resolves.toBeNull()
|
await expect(prisma.assetComment.findUnique({ where: { id: comment.id } })).resolves.toBeNull()
|
||||||
|
|
||||||
// 6. Verify that the attachment Asset and StorageKey are deleted from DB
|
// 6. The attachment is removed immediately; the storage cleanup owns object deletion.
|
||||||
await expect(prisma.asset.findUnique({ where: { id: attachmentAsset.id } })).resolves.toBeNull()
|
await expect(prisma.asset.findUnique({ where: { id: attachmentAsset.id } })).resolves.toBeNull()
|
||||||
|
expect(s3Service.deleteObject).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
await assetService.emptyTrash(project.id)
|
||||||
|
|
||||||
await expect(prisma.storageKey.findUnique({ where: { id: storageKey.id } })).resolves.toBeNull()
|
await expect(prisma.storageKey.findUnique({ where: { id: storageKey.id } })).resolves.toBeNull()
|
||||||
|
|
||||||
// 7. Verify S3 deletion was called
|
|
||||||
const { s3Service } = await import('@shumai/core/src/s3/s3')
|
|
||||||
expect(s3Service.deleteObject).toHaveBeenCalledWith(
|
expect(s3Service.deleteObject).toHaveBeenCalledWith(
|
||||||
'shumai',
|
'shumai',
|
||||||
'attachments/test-attachment-file.png',
|
'attachments/test-attachment-file.png',
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('comment attachments', () => {
|
||||||
|
const addProjectReviewer = async (teamId: string) => {
|
||||||
|
const reviewer = await prisma.user.create({
|
||||||
|
data: { name: 'Reviewer', type: 'human', email: `reviewer-${Date.now()}@example.com` },
|
||||||
|
})
|
||||||
|
await prisma.teamMember.create({
|
||||||
|
data: { teamId, userId: reviewer.id, role: 'reviewer' },
|
||||||
|
})
|
||||||
|
return reviewer
|
||||||
|
}
|
||||||
|
|
||||||
|
const createUpload = async (projectId: string, creatorId: string, name: string) => {
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: { key: `attachments/${name}`, status: 'active' },
|
||||||
|
})
|
||||||
|
return await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
type: AssetType.attachment,
|
||||||
|
projectId,
|
||||||
|
creatorId,
|
||||||
|
sizeByte: 1,
|
||||||
|
status: 'uploaded',
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
it('only attaches comment uploads made by the commenter', async () => {
|
||||||
|
const { user, project, assets } = await setupBasicAssets()
|
||||||
|
const reviewer = await addProjectReviewer(project.teamId)
|
||||||
|
const ownerUpload = await createUpload(project.id, user.id, 'owner-upload.png')
|
||||||
|
const reviewerUpload = await createUpload(project.id, reviewer.id, 'reviewer-upload.png')
|
||||||
|
|
||||||
|
const comment = await assetService.createComment({
|
||||||
|
assetId: assets.fileA1.id,
|
||||||
|
userId: reviewer.id,
|
||||||
|
message: 'looks good',
|
||||||
|
attachmentIds: [assets.fileA2.id, ownerUpload.id, reviewerUpload.id],
|
||||||
|
})
|
||||||
|
|
||||||
|
const links = await prisma.assetCommentAttachment.findMany({
|
||||||
|
where: { commentId: comment.id },
|
||||||
|
})
|
||||||
|
expect(links.map((l) => l.assetId)).toEqual([reviewerUpload.id])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not attach an upload that already belongs to another comment', async () => {
|
||||||
|
const { user, assets, project } = await setupBasicAssets()
|
||||||
|
const upload = await createUpload(project.id, user.id, 'shared.png')
|
||||||
|
|
||||||
|
await assetService.createComment({
|
||||||
|
assetId: assets.fileA1.id,
|
||||||
|
userId: user.id,
|
||||||
|
message: 'first',
|
||||||
|
attachmentIds: [upload.id],
|
||||||
|
})
|
||||||
|
const second = await assetService.createComment({
|
||||||
|
assetId: assets.fileA1.id,
|
||||||
|
userId: user.id,
|
||||||
|
message: 'second',
|
||||||
|
attachmentIds: [upload.id],
|
||||||
|
})
|
||||||
|
|
||||||
|
const links = await prisma.assetCommentAttachment.findMany({
|
||||||
|
where: { commentId: second.id },
|
||||||
|
})
|
||||||
|
expect(links).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows only one concurrent comment to claim an upload', async () => {
|
||||||
|
// The normal test proxy serializes transactions on a single connection.
|
||||||
|
const db = getPrismaTestingHelper().getUnderlyingClient() as typeof prisma
|
||||||
|
const service = new AssetService(db)
|
||||||
|
const { user, team, project, file, upload } = await db.$transaction(async (tx) => {
|
||||||
|
const user = await tx.user.create({
|
||||||
|
data: { name: 'Commenter', email: `attachment-race-${crypto.randomUUID()}@example.com` },
|
||||||
|
})
|
||||||
|
const team = await tx.team.create({ data: { name: 'Attachment race' } })
|
||||||
|
const project = await tx.project.create({ data: { name: 'Project', teamId: team.id } })
|
||||||
|
const file = await tx.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'File',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
projectId: project.id,
|
||||||
|
creatorId: user.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const upload = await tx.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'Upload',
|
||||||
|
type: AssetType.attachment,
|
||||||
|
status: AssetStatus.uploaded,
|
||||||
|
projectId: project.id,
|
||||||
|
creatorId: user.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return { user, team, project, file, upload }
|
||||||
|
})
|
||||||
|
|
||||||
|
let claims: Promise<PromiseSettledResult<unknown>[]> | undefined
|
||||||
|
try {
|
||||||
|
await db.$transaction(async (tx) => {
|
||||||
|
await tx.$queryRaw`SELECT id FROM assets WHERE id = ${upload.id} FOR UPDATE`
|
||||||
|
claims = Promise.allSettled(
|
||||||
|
['First comment', 'Second comment'].map((message) =>
|
||||||
|
service.createComment(
|
||||||
|
{ assetId: file.id, userId: user.id, message, attachmentIds: [upload.id] },
|
||||||
|
{ triggerAgents: false },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Release the upload only after both requests are waiting on its row lock.
|
||||||
|
await vi.waitFor(
|
||||||
|
async () => {
|
||||||
|
const [waiters] = await tx.$queryRaw<{ count: number }[]>`
|
||||||
|
WITH RECURSIVE waiters(pid) AS (
|
||||||
|
SELECT pg_backend_pid()
|
||||||
|
UNION
|
||||||
|
SELECT pending.pid
|
||||||
|
FROM waiters
|
||||||
|
JOIN (SELECT DISTINCT pid FROM pg_locks WHERE NOT granted) pending
|
||||||
|
ON waiters.pid = ANY(pg_blocking_pids(pending.pid))
|
||||||
|
)
|
||||||
|
SELECT count(*)::int - 1 AS count FROM waiters
|
||||||
|
`
|
||||||
|
expect(waiters.count).toBe(2)
|
||||||
|
},
|
||||||
|
{ timeout: 3_000 },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(await claims).toEqual([
|
||||||
|
expect.objectContaining({ status: 'fulfilled' }),
|
||||||
|
expect.objectContaining({ status: 'fulfilled' }),
|
||||||
|
])
|
||||||
|
await expect(
|
||||||
|
db.assetCommentAttachment.count({ where: { assetId: upload.id } }),
|
||||||
|
).resolves.toBe(1)
|
||||||
|
} finally {
|
||||||
|
await claims
|
||||||
|
await db.asset.deleteMany({ where: { projectId: project.id } })
|
||||||
|
await db.project.delete({ where: { id: project.id } })
|
||||||
|
await db.team.delete({ where: { id: team.id } })
|
||||||
|
await db.user.delete({ where: { id: user.id } })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deleteComment keeps project files that are linked to the comment', async () => {
|
||||||
|
const { project, assets } = await setupBasicAssets()
|
||||||
|
const reviewer = await addProjectReviewer(project.teamId)
|
||||||
|
const fileKey = await prisma.storageKey.create({
|
||||||
|
data: { key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov', status: 'active' },
|
||||||
|
})
|
||||||
|
await prisma.asset.update({
|
||||||
|
where: { id: assets.fileA2.id },
|
||||||
|
data: { storageKeyId: fileKey.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const comment = await assetService.createComment({
|
||||||
|
assetId: assets.fileA1.id,
|
||||||
|
userId: reviewer.id,
|
||||||
|
message: 'note',
|
||||||
|
attachmentIds: [],
|
||||||
|
})
|
||||||
|
// A link to a project file, as comments created before attachment checks could hold.
|
||||||
|
await prisma.assetCommentAttachment.create({
|
||||||
|
data: { commentId: comment.id, assetId: assets.fileA2.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
await assetService.deleteComment({ commentId: comment.id, userId: reviewer.id })
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
prisma.assetComment.findUnique({ where: { id: comment.id } }),
|
||||||
|
).resolves.toBeNull()
|
||||||
|
await expect(
|
||||||
|
prisma.asset.findUnique({ where: { id: assets.fileA2.id } }),
|
||||||
|
).resolves.not.toBeNull()
|
||||||
|
await expect(
|
||||||
|
prisma.storageKey.findUnique({ where: { id: fileKey.id } }),
|
||||||
|
).resolves.not.toBeNull()
|
||||||
|
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps an attachment object until the original and copied comments are deleted', async () => {
|
||||||
|
const { user, project, assets } = await setupBasicAssets()
|
||||||
|
const upload = await createUpload(project.id, user.id, 'copied-upload.png')
|
||||||
|
const originalComment = await assetService.createComment({
|
||||||
|
assetId: assets.fileA1.id,
|
||||||
|
userId: user.id,
|
||||||
|
message: 'Original comment',
|
||||||
|
attachmentIds: [upload.id],
|
||||||
|
})
|
||||||
|
const [copiedFileId] = await assetService.copyAssets({
|
||||||
|
assetIds: [assets.fileA1.id],
|
||||||
|
newParentId: assets.root3.id,
|
||||||
|
creatorId: user.id,
|
||||||
|
withComments: true,
|
||||||
|
})
|
||||||
|
const copiedComment = await prisma.assetComment.findFirstOrThrow({
|
||||||
|
where: { assetId: copiedFileId },
|
||||||
|
})
|
||||||
|
const storageKey = await prisma.storageKey.findFirstOrThrow({
|
||||||
|
where: { key: 'attachments/copied-upload.png' },
|
||||||
|
})
|
||||||
|
await prisma.storageKey.update({
|
||||||
|
where: { id: storageKey.id },
|
||||||
|
data: { createdAt: new Date(Date.now() - 60_000) },
|
||||||
|
})
|
||||||
|
|
||||||
|
await assetService.deleteComment({ commentId: copiedComment.id, userId: user.id })
|
||||||
|
await assetService.emptyTrash(project.id)
|
||||||
|
|
||||||
|
const survivingUpload = await prisma.asset.findUniqueOrThrow({ where: { id: upload.id } })
|
||||||
|
expect(survivingUpload.storageKeyId).toBe(storageKey.id)
|
||||||
|
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(expect.any(String), storageKey.key)
|
||||||
|
|
||||||
|
await assetService.deleteComment({ commentId: originalComment.id, userId: user.id })
|
||||||
|
await assetService.emptyTrash(project.id)
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
prisma.storageKey.findUnique({ where: { id: storageKey.id } }),
|
||||||
|
).resolves.toBeNull()
|
||||||
|
expect(s3Service.deleteObject).toHaveBeenCalledWith(expect.any(String), storageKey.key)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a legacy attachment asset while another comment still links to it', async () => {
|
||||||
|
const { user, project, assets } = await setupBasicAssets()
|
||||||
|
const upload = await createUpload(project.id, user.id, 'legacy-upload.png')
|
||||||
|
const first = await assetService.createComment({
|
||||||
|
assetId: assets.fileA1.id,
|
||||||
|
userId: user.id,
|
||||||
|
message: 'First comment',
|
||||||
|
attachmentIds: [upload.id],
|
||||||
|
})
|
||||||
|
const second = await assetService.createComment({
|
||||||
|
assetId: assets.fileA1.id,
|
||||||
|
userId: user.id,
|
||||||
|
message: 'Second comment',
|
||||||
|
attachmentIds: [],
|
||||||
|
})
|
||||||
|
await prisma.assetCommentAttachment.create({
|
||||||
|
data: { assetId: upload.id, commentId: second.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
await assetService.deleteComment({ commentId: first.id, userId: user.id })
|
||||||
|
await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.not.toBeNull()
|
||||||
|
|
||||||
|
await assetService.deleteComment({ commentId: second.id, userId: user.id })
|
||||||
|
await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('can create and retrieve comments with video timestamp', async () => {
|
it('can create and retrieve comments with video timestamp', async () => {
|
||||||
const { user, assets } = await setupBasicAssets()
|
const { user, assets } = await setupBasicAssets()
|
||||||
|
|
||||||
@@ -5704,4 +5964,367 @@ describe('AssetService — natural sort by name', () => {
|
|||||||
expect(variant).toContain('http://mock-s3-url')
|
expect(variant).toContain('http://mock-s3-url')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('internal comments and comment editing', () => {
|
||||||
|
async function setupCommentFixture() {
|
||||||
|
const team = await prisma.team.create({ data: { name: 'Comment Team' } })
|
||||||
|
const author = await prisma.user.create({
|
||||||
|
data: { name: 'Author', email: `author-${Date.now()}-${Math.random()}@test.com` },
|
||||||
|
})
|
||||||
|
const owner = await prisma.user.create({
|
||||||
|
data: { name: 'Owner', email: `owner-${Date.now()}-${Math.random()}@test.com` },
|
||||||
|
})
|
||||||
|
await prisma.teamMember.create({
|
||||||
|
data: { teamId: team.id, userId: author.id, role: 'editor' },
|
||||||
|
})
|
||||||
|
await prisma.teamMember.create({
|
||||||
|
data: { teamId: team.id, userId: owner.id, role: 'owner' },
|
||||||
|
})
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'Comment Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
const rootFolder = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'root',
|
||||||
|
type: AssetType.folder,
|
||||||
|
projectId: project.id,
|
||||||
|
status: AssetStatus.uploaded,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const file = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'clip.mp4',
|
||||||
|
type: AssetType.file,
|
||||||
|
projectId: project.id,
|
||||||
|
parentId: rootFolder.id,
|
||||||
|
creatorId: author.id,
|
||||||
|
status: AssetStatus.uploaded,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return { team, author, owner, project, rootFolder, file }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createAttachmentAsset(projectId: string, creatorId: string, name: string) {
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: { key: `files/attachments/${Date.now()}-${Math.random()}-${name}` },
|
||||||
|
})
|
||||||
|
return prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
type: AssetType.attachment,
|
||||||
|
projectId,
|
||||||
|
creatorId,
|
||||||
|
status: AssetStatus.uploaded,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
it('creates public (default) and internal comments, and enforces internal replies on internal parents', async () => {
|
||||||
|
const { author, owner, file } = await setupCommentFixture()
|
||||||
|
|
||||||
|
const pub = await assetService.createComment(
|
||||||
|
{ assetId: file.id, userId: author.id, message: 'Public feedback', attachmentIds: [] },
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
expect(pub.isInternal).toBe(false)
|
||||||
|
|
||||||
|
const internal = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: 'Internal note',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
expect(internal.isInternal).toBe(true)
|
||||||
|
|
||||||
|
// Replying to an internal parent forces isInternal: true even if false is passed
|
||||||
|
const replyToInternal = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: owner.id,
|
||||||
|
replyToId: internal.id,
|
||||||
|
message: 'Internal reply',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: false,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
expect(replyToInternal.isInternal).toBe(true)
|
||||||
|
|
||||||
|
// Replying internally to a public parent is allowed
|
||||||
|
const internalReplyOnPublic = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: owner.id,
|
||||||
|
replyToId: pub.id,
|
||||||
|
message: 'Private side note',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
expect(internalReplyOnPublic.isInternal).toBe(true)
|
||||||
|
|
||||||
|
const publicReplyOnPublic = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
replyToId: pub.id,
|
||||||
|
message: 'Public reply',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: false,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
expect(publicReplyOnPublic.isInternal).toBe(false)
|
||||||
|
|
||||||
|
// Authenticated list includes everything
|
||||||
|
const allListed = await assetService.listComments(file.id, { first: 20 }, author.id)
|
||||||
|
expect(allListed.data).toHaveLength(2)
|
||||||
|
expect(allListed.data[0].replies).toHaveLength(2)
|
||||||
|
expect(allListed.data[1].replies).toHaveLength(1)
|
||||||
|
|
||||||
|
// Public share list excludes internal comments and internal replies
|
||||||
|
const publicListed = await assetService.listComments(file.id, { first: 20 }, undefined, {
|
||||||
|
excludeInternal: true,
|
||||||
|
})
|
||||||
|
expect(publicListed.data).toHaveLength(1)
|
||||||
|
expect(publicListed.data[0].id).toBe(pub.id)
|
||||||
|
expect(publicListed.data[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
|
||||||
|
|
||||||
|
// listAllComments with excludeInternal matches
|
||||||
|
const publicAll = await assetService.listAllComments(file.id, undefined, {
|
||||||
|
excludeInternal: true,
|
||||||
|
})
|
||||||
|
expect(publicAll).toHaveLength(1)
|
||||||
|
expect(publicAll[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('excludes internal comments and replies under internal parents from public share commentsCount', async () => {
|
||||||
|
const { author, rootFolder, file } = await setupCommentFixture()
|
||||||
|
|
||||||
|
const pub = await assetService.createComment(
|
||||||
|
{ assetId: file.id, userId: author.id, message: 'Public', attachmentIds: [] },
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
replyToId: pub.id,
|
||||||
|
message: 'Internal reply on public',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
const internal = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: 'Internal root',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
replyToId: internal.id,
|
||||||
|
message: 'Reply on internal',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
|
||||||
|
const allChildren = await assetService.listChildren({
|
||||||
|
assetId: rootFolder.id,
|
||||||
|
assetType: 'file',
|
||||||
|
})
|
||||||
|
expect(allChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(4)
|
||||||
|
|
||||||
|
const publicChildren = await assetService.listChildren(
|
||||||
|
{ assetId: rootFolder.id, assetType: 'file' },
|
||||||
|
{ excludeInternalComments: true },
|
||||||
|
)
|
||||||
|
expect(publicChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(1)
|
||||||
|
|
||||||
|
const publicFile = await assetService.getAsset(
|
||||||
|
{ assetId: file.id },
|
||||||
|
{ excludeInternalComments: true },
|
||||||
|
)
|
||||||
|
expect(publicFile.commentsCount).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects replying to an internal comment from a public share link', async () => {
|
||||||
|
const { author, file } = await setupCommentFixture()
|
||||||
|
const internal = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: 'Internal only',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
replyToId: internal.id,
|
||||||
|
message: 'Guest reply attempt',
|
||||||
|
attachmentIds: [],
|
||||||
|
},
|
||||||
|
{ triggerAgents: false, shareLinkId: 'share-1' },
|
||||||
|
),
|
||||||
|
).rejects.toMatchObject({ status: 404 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows author to edit text, visibility, remove timestamp, and add/delete attachments', async () => {
|
||||||
|
const { author, project, file } = await setupCommentFixture()
|
||||||
|
const att1 = await createAttachmentAsset(project.id, author.id, 'old.png')
|
||||||
|
const att2 = await createAttachmentAsset(project.id, author.id, 'keep.pdf')
|
||||||
|
const att3 = await createAttachmentAsset(project.id, author.id, 'new.png')
|
||||||
|
|
||||||
|
const created = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: 'Original message',
|
||||||
|
second: 12.5,
|
||||||
|
attachmentIds: [att1.id, att2.id],
|
||||||
|
isInternal: false,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
|
||||||
|
const updated = await assetService.updateComment({
|
||||||
|
commentId: created.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: 'Updated message',
|
||||||
|
isInternal: true,
|
||||||
|
second: null,
|
||||||
|
attachmentIds: [att2.id, att3.id],
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updated.message).toBe('Updated message')
|
||||||
|
expect(updated.isInternal).toBe(true)
|
||||||
|
expect(updated.second).toBeNull()
|
||||||
|
expect(updated.attachments.map((a) => a.assetId).sort()).toEqual([att2.id, att3.id].sort())
|
||||||
|
|
||||||
|
// Removed attachment asset should be cleaned up since no comment references it anymore
|
||||||
|
expect(await prisma.asset.findUnique({ where: { id: att1.id } })).toBeNull()
|
||||||
|
expect(await prisma.asset.findUnique({ where: { id: att2.id } })).not.toBeNull()
|
||||||
|
expect(await prisma.asset.findUnique({ where: { id: att3.id } })).not.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('enforces author-only edit, parent-internal reply constraint, non-empty validation, and preserves reply flags', async () => {
|
||||||
|
const { author, owner, file } = await setupCommentFixture()
|
||||||
|
|
||||||
|
const parent = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: 'Parent comment',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
const reply = await assetService.createComment(
|
||||||
|
{
|
||||||
|
assetId: file.id,
|
||||||
|
userId: author.id,
|
||||||
|
replyToId: parent.id,
|
||||||
|
message: 'Internal reply',
|
||||||
|
attachmentIds: [],
|
||||||
|
isInternal: true,
|
||||||
|
},
|
||||||
|
{ triggerAgents: false },
|
||||||
|
)
|
||||||
|
|
||||||
|
// Non-author (even team owner) cannot edit
|
||||||
|
await expect(
|
||||||
|
assetService.updateComment({
|
||||||
|
commentId: parent.id,
|
||||||
|
userId: owner.id,
|
||||||
|
message: 'Owner edit attempt',
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({ status: 403 })
|
||||||
|
|
||||||
|
// Reply cannot be made public while parent is internal
|
||||||
|
await expect(
|
||||||
|
assetService.updateComment({
|
||||||
|
commentId: reply.id,
|
||||||
|
userId: author.id,
|
||||||
|
isInternal: false,
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({ status: 400 })
|
||||||
|
|
||||||
|
// Empty comment without attachments or annotations is rejected
|
||||||
|
await expect(
|
||||||
|
assetService.updateComment({
|
||||||
|
commentId: parent.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: ' ',
|
||||||
|
attachmentIds: [],
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({ status: 400 })
|
||||||
|
|
||||||
|
// Toggling parent Internal -> Public keeps reply's own isInternal flag intact
|
||||||
|
const toggledParent = await assetService.updateComment({
|
||||||
|
commentId: parent.id,
|
||||||
|
userId: author.id,
|
||||||
|
isInternal: false,
|
||||||
|
})
|
||||||
|
expect(toggledParent.isInternal).toBe(false)
|
||||||
|
expect(toggledParent.replies[0].isInternal).toBe(true)
|
||||||
|
|
||||||
|
// Agent comments cannot be edited
|
||||||
|
const agentUser = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
name: 'Bot',
|
||||||
|
email: `bot-${Date.now()}-${Math.random()}@test.com`,
|
||||||
|
type: 'agent',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const agent = await prisma.agent.create({
|
||||||
|
data: {
|
||||||
|
id: agentUser.id,
|
||||||
|
teamId: (await prisma.project.findUniqueOrThrow({ where: { id: file.projectId! } }))
|
||||||
|
.teamId,
|
||||||
|
type: 'chat',
|
||||||
|
config: { provider: 'openai', model: 'gpt-4' },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const session = await prisma.agentSession.create({
|
||||||
|
data: { agentId: agent.id, cwd: '/tmp' },
|
||||||
|
})
|
||||||
|
const agentComment = await prisma.assetComment.create({
|
||||||
|
data: {
|
||||||
|
assetId: file.id,
|
||||||
|
creatorId: author.id,
|
||||||
|
sessionId: session.id,
|
||||||
|
message: 'Agent generated reply',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await expect(
|
||||||
|
assetService.updateComment({
|
||||||
|
commentId: agentComment.id,
|
||||||
|
userId: author.id,
|
||||||
|
message: 'Try edit agent',
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({ status: 403 })
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ import { dedupeSymlinksToTarget } from './symlink'
|
|||||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||||
|
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||||
@@ -742,7 +743,10 @@ export class AssetService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async listChildren(req: ListChildrenRequest): Promise<PaginatedData<AssetInfo[]>> {
|
async listChildren(
|
||||||
|
req: ListChildrenRequest,
|
||||||
|
options?: { excludeInternalComments?: boolean },
|
||||||
|
): Promise<PaginatedData<AssetInfo[]>> {
|
||||||
let typesToQuery: AssetType[]
|
let typesToQuery: AssetType[]
|
||||||
if (req.assetType === 'file') {
|
if (req.assetType === 'file') {
|
||||||
typesToQuery = [AssetType.file, AssetType.version_stack]
|
typesToQuery = [AssetType.file, AssetType.version_stack]
|
||||||
@@ -830,6 +834,7 @@ export class AssetService {
|
|||||||
|
|
||||||
const infos = await this.toAssetInfos(assets, undefined, {
|
const infos = await this.toAssetInfos(assets, undefined, {
|
||||||
includeDeletedChildren: req.showDeleted,
|
includeDeletedChildren: req.showDeleted,
|
||||||
|
excludeInternalComments: options?.excludeInternalComments,
|
||||||
})
|
})
|
||||||
|
|
||||||
return { data: infos, pageInfo }
|
return { data: infos, pageInfo }
|
||||||
@@ -1106,7 +1111,10 @@ export class AssetService {
|
|||||||
return this.getAsset({ assetId: asset.id })
|
return this.getAsset({ assetId: asset.id })
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAsset(req: GetAssetRequest): Promise<AssetInfo> {
|
async getAsset(
|
||||||
|
req: GetAssetRequest,
|
||||||
|
options?: { excludeInternalComments?: boolean },
|
||||||
|
): Promise<AssetInfo> {
|
||||||
const a = await this.prismaClient.asset.findUnique({
|
const a = await this.prismaClient.asset.findUnique({
|
||||||
where: { id: req.assetId },
|
where: { id: req.assetId },
|
||||||
include: assetInclude,
|
include: assetInclude,
|
||||||
@@ -1129,7 +1137,9 @@ export class AssetService {
|
|||||||
afs.push({ id: row.id, name: row.name })
|
afs.push({ id: row.id, name: row.name })
|
||||||
}
|
}
|
||||||
|
|
||||||
const infos = await this.toAssetInfos([a])
|
const infos = await this.toAssetInfos([a], undefined, {
|
||||||
|
excludeInternalComments: options?.excludeInternalComments,
|
||||||
|
})
|
||||||
const info = infos[0]
|
const info = infos[0]
|
||||||
info.ancestorFolders = afs
|
info.ancestorFolders = afs
|
||||||
|
|
||||||
@@ -1957,6 +1967,27 @@ export class AssetService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async lockCommentAttachments(
|
||||||
|
tx: Prisma.TransactionClient,
|
||||||
|
attachmentIds: string[],
|
||||||
|
owner?: { projectId: string | null; userId: string },
|
||||||
|
): Promise<string[]> {
|
||||||
|
if (attachmentIds.length === 0) return []
|
||||||
|
|
||||||
|
// Lock the same rows in the same order when claiming or removing attachments.
|
||||||
|
const ownerFilter = owner
|
||||||
|
? Prisma.sql`AND project_id IS NOT DISTINCT FROM ${owner.projectId} AND creator_id = ${owner.userId}`
|
||||||
|
: Prisma.empty
|
||||||
|
const attachments = await tx.$queryRaw<{ id: string }[]>`
|
||||||
|
SELECT id FROM assets
|
||||||
|
WHERE id IN (${Prisma.join(attachmentIds)}) AND type = 'attachment'
|
||||||
|
${ownerFilter}
|
||||||
|
ORDER BY id
|
||||||
|
FOR NO KEY UPDATE
|
||||||
|
`
|
||||||
|
return attachments.map(({ id }) => id)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a comment or reply. Mentions of agents (`<@agentId>`) start a chat with them
|
* Creates a comment or reply. Mentions of agents (`<@agentId>`) start a chat with them
|
||||||
* unless `triggerAgents` is false, which keeps an agent's own comments from starting
|
* unless `triggerAgents` is false, which keeps an agent's own comments from starting
|
||||||
@@ -1964,7 +1995,7 @@ export class AssetService {
|
|||||||
*/
|
*/
|
||||||
async createComment(
|
async createComment(
|
||||||
req: CreateCommentRequest,
|
req: CreateCommentRequest,
|
||||||
options: { triggerAgents?: boolean } = {},
|
options: { triggerAgents?: boolean; shareLinkId?: string } = {},
|
||||||
): Promise<CommentInfo> {
|
): Promise<CommentInfo> {
|
||||||
const triggerAgents = options.triggerAgents ?? true
|
const triggerAgents = options.triggerAgents ?? true
|
||||||
let commentId = ''
|
let commentId = ''
|
||||||
@@ -1979,16 +2010,43 @@ export class AssetService {
|
|||||||
|
|
||||||
let actualReplyToId = req.replyToId
|
let actualReplyToId = req.replyToId
|
||||||
let parentComment = null
|
let parentComment = null
|
||||||
|
let parentIsInternal = false
|
||||||
if (req.replyToId) {
|
if (req.replyToId) {
|
||||||
parentComment = await tx.assetComment.findUnique({
|
parentComment = await tx.assetComment.findUnique({
|
||||||
where: { id: req.replyToId },
|
where: { id: req.replyToId },
|
||||||
include: { creator: true },
|
include: {
|
||||||
|
creator: true,
|
||||||
|
replyTo: { select: { id: true, isInternal: true } },
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
if (options.shareLinkId) {
|
||||||
|
if (
|
||||||
|
!parentComment ||
|
||||||
|
parentComment.assetId !== a.id ||
|
||||||
|
parentComment.isInternal ||
|
||||||
|
parentComment.replyTo?.isInternal
|
||||||
|
) {
|
||||||
|
throw new HTTPException(404, { message: 'Comment not found' })
|
||||||
|
}
|
||||||
|
}
|
||||||
if (parentComment?.replyToId) {
|
if (parentComment?.replyToId) {
|
||||||
actualReplyToId = parentComment.replyToId
|
actualReplyToId = parentComment.replyToId
|
||||||
|
parentIsInternal = Boolean(parentComment.isInternal || parentComment.replyTo?.isInternal)
|
||||||
|
} else if (parentComment) {
|
||||||
|
parentIsInternal = parentComment.isInternal
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isInternal = options.shareLinkId
|
||||||
|
? false
|
||||||
|
: parentIsInternal
|
||||||
|
? true
|
||||||
|
: Boolean(req.isInternal)
|
||||||
|
|
||||||
|
const attachmentIds = await this.lockCommentAttachments(tx, req.attachmentIds, {
|
||||||
|
projectId: a.projectId,
|
||||||
|
userId: req.userId,
|
||||||
|
})
|
||||||
const comment = await tx.assetComment.create({
|
const comment = await tx.assetComment.create({
|
||||||
data: {
|
data: {
|
||||||
assetId: a.id,
|
assetId: a.id,
|
||||||
@@ -1997,27 +2055,28 @@ export class AssetService {
|
|||||||
annotation: req.annotations,
|
annotation: req.annotations,
|
||||||
second: req.second,
|
second: req.second,
|
||||||
replyToId: actualReplyToId,
|
replyToId: actualReplyToId,
|
||||||
|
isInternal,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
commentId = comment.id
|
commentId = comment.id
|
||||||
|
|
||||||
for (const attachmentId of req.attachmentIds) {
|
if (attachmentIds.length > 0) {
|
||||||
const attachmentAsset = await tx.asset.findUnique({
|
// Read the links after acquiring the locks to see any claims that committed while waiting.
|
||||||
where: { id: attachmentId },
|
const unclaimed = await tx.asset.findMany({
|
||||||
|
where: { id: { in: attachmentIds }, commentAttachments: { none: {} } },
|
||||||
|
select: { id: true },
|
||||||
})
|
})
|
||||||
if (
|
await tx.assetCommentAttachment.createMany({
|
||||||
attachmentAsset &&
|
data: unclaimed.map(({ id }) => ({ assetId: id, commentId: comment.id })),
|
||||||
(attachmentAsset.type === AssetType.attachment ||
|
})
|
||||||
attachmentAsset.type === AssetType.file) &&
|
}
|
||||||
attachmentAsset.projectId === a.projectId
|
|
||||||
) {
|
if (options.shareLinkId) {
|
||||||
await tx.assetCommentAttachment.create({
|
await shareActivityService.recordEvent(
|
||||||
data: {
|
options.shareLinkId,
|
||||||
assetId: attachmentAsset.id,
|
{ kind: 'comment_created', assetId: a.id, userId: req.userId },
|
||||||
commentId: comment.id,
|
tx,
|
||||||
},
|
)
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!triggerAgents) return
|
if (!triggerAgents) return
|
||||||
@@ -2195,22 +2254,154 @@ export class AssetService {
|
|||||||
return this.getComment(commentId, userId)
|
return this.getComment(commentId, userId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateComment(params: {
|
||||||
|
commentId: string
|
||||||
|
userId: string
|
||||||
|
message?: string
|
||||||
|
isInternal?: boolean
|
||||||
|
second?: number | null
|
||||||
|
attachmentIds?: string[]
|
||||||
|
}): Promise<CommentInfo> {
|
||||||
|
await this.prismaClient.$transaction(async (tx) => {
|
||||||
|
const comment = await tx.assetComment.findUnique({
|
||||||
|
where: { id: params.commentId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
creatorId: true,
|
||||||
|
sessionId: true,
|
||||||
|
message: true,
|
||||||
|
annotation: true,
|
||||||
|
second: true,
|
||||||
|
isInternal: true,
|
||||||
|
attachments: { select: { assetId: true } },
|
||||||
|
replyTo: { select: { isInternal: true } },
|
||||||
|
asset: { select: { projectId: true } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!comment) {
|
||||||
|
throw new HTTPException(404, { message: 'Comment not found' })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (comment.sessionId !== null || comment.creatorId !== params.userId) {
|
||||||
|
throw new HTTPException(403, { message: 'Only the comment author can edit this comment' })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (comment.replyTo?.isInternal && params.isInternal === false) {
|
||||||
|
throw new HTTPException(400, {
|
||||||
|
message: 'Cannot make a reply public when its parent comment is internal',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingAttachmentIds = comment.attachments.map(({ assetId }) => assetId)
|
||||||
|
const existingSet = new Set(existingAttachmentIds)
|
||||||
|
|
||||||
|
let toAdd: string[] = []
|
||||||
|
let toRemove: string[] = []
|
||||||
|
let keptCount = existingAttachmentIds.length
|
||||||
|
|
||||||
|
if (params.attachmentIds !== undefined) {
|
||||||
|
const desiredIds = Array.from(new Set(params.attachmentIds))
|
||||||
|
const desiredSet = new Set(desiredIds)
|
||||||
|
toAdd = desiredIds.filter((id) => !existingSet.has(id))
|
||||||
|
toRemove = existingAttachmentIds.filter((id) => !desiredSet.has(id))
|
||||||
|
keptCount = existingAttachmentIds.filter((id) => desiredSet.has(id)).length
|
||||||
|
}
|
||||||
|
|
||||||
|
const idsToLock = Array.from(new Set([...toAdd, ...toRemove]))
|
||||||
|
let claimedToAdd: string[] = []
|
||||||
|
let lockedToRemove: string[] = []
|
||||||
|
|
||||||
|
if (idsToLock.length > 0) {
|
||||||
|
const lockedRows = await tx.$queryRaw<
|
||||||
|
{ id: string; projectId: string | null; creatorId: string | null }[]
|
||||||
|
>`
|
||||||
|
SELECT id, project_id AS "projectId", creator_id AS "creatorId" FROM assets
|
||||||
|
WHERE id IN (${Prisma.join(idsToLock)}) AND type = 'attachment'
|
||||||
|
ORDER BY id
|
||||||
|
FOR NO KEY UPDATE
|
||||||
|
`
|
||||||
|
const toAddSet = new Set(toAdd)
|
||||||
|
const toRemoveSet = new Set(toRemove)
|
||||||
|
const ownedToAdd = lockedRows
|
||||||
|
.filter(
|
||||||
|
(row) =>
|
||||||
|
toAddSet.has(row.id) &&
|
||||||
|
row.projectId === comment.asset.projectId &&
|
||||||
|
row.creatorId === params.userId,
|
||||||
|
)
|
||||||
|
.map((row) => row.id)
|
||||||
|
|
||||||
|
lockedToRemove = lockedRows.filter((row) => toRemoveSet.has(row.id)).map((row) => row.id)
|
||||||
|
|
||||||
|
if (ownedToAdd.length > 0) {
|
||||||
|
const unclaimed = await tx.asset.findMany({
|
||||||
|
where: { id: { in: ownedToAdd }, commentAttachments: { none: {} } },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
claimedToAdd = unclaimed.map(({ id }) => id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const finalMessage = params.message !== undefined ? params.message : (comment.message ?? '')
|
||||||
|
const hasAnnotations = Array.isArray(comment.annotation) && comment.annotation.length > 0
|
||||||
|
const finalAttachmentCount = keptCount + claimedToAdd.length
|
||||||
|
|
||||||
|
if (!finalMessage.trim() && finalAttachmentCount === 0 && !hasAnnotations) {
|
||||||
|
throw new HTTPException(400, { message: 'Comment cannot be empty' })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toRemove.length > 0) {
|
||||||
|
await tx.assetCommentAttachment.deleteMany({
|
||||||
|
where: {
|
||||||
|
commentId: params.commentId,
|
||||||
|
assetId: { in: toRemove },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (lockedToRemove.length > 0) {
|
||||||
|
await tx.asset.deleteMany({
|
||||||
|
where: { id: { in: lockedToRemove }, commentAttachments: { none: {} } },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (claimedToAdd.length > 0) {
|
||||||
|
await tx.assetCommentAttachment.createMany({
|
||||||
|
data: claimedToAdd.map((assetId) => ({ assetId, commentId: params.commentId })),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateData: Prisma.AssetCommentUpdateInput = {}
|
||||||
|
if (params.message !== undefined) {
|
||||||
|
updateData.message = params.message
|
||||||
|
}
|
||||||
|
if (params.isInternal !== undefined) {
|
||||||
|
updateData.isInternal = params.isInternal
|
||||||
|
}
|
||||||
|
if (params.second !== undefined) {
|
||||||
|
updateData.second = params.second
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(updateData).length > 0) {
|
||||||
|
await tx.assetComment.update({
|
||||||
|
where: { id: params.commentId },
|
||||||
|
data: updateData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return this.getComment(params.commentId, params.userId)
|
||||||
|
}
|
||||||
|
|
||||||
async deleteComment({ commentId, userId }: { commentId: string; userId: string }): Promise<void> {
|
async deleteComment({ commentId, userId }: { commentId: string; userId: string }): Promise<void> {
|
||||||
const comment = await this.prismaClient.assetComment.findUnique({
|
const comment = await this.prismaClient.assetComment.findUnique({
|
||||||
where: { id: commentId },
|
where: { id: commentId },
|
||||||
include: {
|
select: {
|
||||||
attachments: {
|
creatorId: true,
|
||||||
include: {
|
attachments: { select: { assetId: true } },
|
||||||
asset: {
|
|
||||||
include: {
|
|
||||||
storageKey: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
asset: {
|
asset: {
|
||||||
select: {
|
select: {
|
||||||
project: { select: { id: true, teamId: true } },
|
project: { select: { teamId: true } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -2248,75 +2439,70 @@ export class AssetService {
|
|||||||
throw new HTTPException(403, { message: 'You do not have permission to delete this comment' })
|
throw new HTTPException(403, { message: 'You do not have permission to delete this comment' })
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean up attachment files from S3/storage and delete their DB records
|
await this.prismaClient.$transaction(async (tx) => {
|
||||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
const attachmentIds = await this.lockCommentAttachments(
|
||||||
for (const att of comment.attachments) {
|
tx,
|
||||||
const asset = att.asset
|
comment.attachments.map(({ assetId }) => assetId),
|
||||||
if (asset.storageKey) {
|
)
|
||||||
try {
|
await tx.assetComment.delete({ where: { id: commentId } })
|
||||||
await s3Service.deleteObject(bucket, asset.storageKey.key)
|
|
||||||
} catch (err) {
|
if (attachmentIds.length > 0) {
|
||||||
logger.error({ err, assetId: asset.id }, 'Failed to delete attachment file from S3')
|
// The storage cleanup job removes objects once every asset using their storage key is gone.
|
||||||
}
|
await tx.asset.deleteMany({
|
||||||
|
where: { id: { in: attachmentIds }, commentAttachments: { none: {} } },
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.prismaClient.asset.delete({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
if (asset.storageKey) {
|
|
||||||
await this.prismaClient.storageKey
|
|
||||||
.delete({
|
|
||||||
where: { id: asset.storageKey.id },
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
// Silently ignore if already deleted
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.prismaClient.assetComment.delete({
|
|
||||||
where: { id: commentId },
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getCommentInclude(options?: { excludeInternal?: boolean }) {
|
||||||
|
return {
|
||||||
|
creator: true,
|
||||||
|
completionLastChangedBy: true,
|
||||||
|
asset: { include: { storageKey: true } },
|
||||||
|
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||||
|
reactions: {
|
||||||
|
include: {
|
||||||
|
user: { select: { id: true, name: true } },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' as const },
|
||||||
|
},
|
||||||
|
replies: {
|
||||||
|
...(options?.excludeInternal ? { where: { isInternal: false } } : {}),
|
||||||
|
include: {
|
||||||
|
creator: true,
|
||||||
|
completionLastChangedBy: true,
|
||||||
|
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||||
|
reactions: {
|
||||||
|
include: {
|
||||||
|
user: { select: { id: true, name: true } },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' as const },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { id: 'asc' as const },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async listComments(
|
async listComments(
|
||||||
assetId: string,
|
assetId: string,
|
||||||
params: PaginationParams,
|
params: PaginationParams,
|
||||||
requestingUserId?: string,
|
requestingUserId?: string,
|
||||||
|
options?: { excludeInternal?: boolean },
|
||||||
): Promise<PaginatedData<CommentInfo[]>> {
|
): Promise<PaginatedData<CommentInfo[]>> {
|
||||||
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
|
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
|
||||||
|
const where: Prisma.AssetCommentWhereInput = {
|
||||||
|
assetId: resolvedAssetId,
|
||||||
|
replyToId: null,
|
||||||
|
...(options?.excludeInternal ? { isInternal: false } : {}),
|
||||||
|
}
|
||||||
|
|
||||||
const { data: comments, pageInfo } = await paginateQuery(
|
const { data: comments, pageInfo } = await paginateQuery(
|
||||||
async (skip, take) => {
|
async (skip, take) => {
|
||||||
return this.prismaClient.assetComment.findMany({
|
return this.prismaClient.assetComment.findMany({
|
||||||
where: { assetId: resolvedAssetId, replyToId: null },
|
where,
|
||||||
include: {
|
include: this.getCommentInclude(options),
|
||||||
creator: true,
|
|
||||||
completionLastChangedBy: true,
|
|
||||||
asset: { include: { storageKey: true } },
|
|
||||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
|
||||||
reactions: {
|
|
||||||
include: {
|
|
||||||
user: { select: { id: true, name: true } },
|
|
||||||
},
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
},
|
|
||||||
replies: {
|
|
||||||
include: {
|
|
||||||
creator: true,
|
|
||||||
completionLastChangedBy: true,
|
|
||||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
|
||||||
reactions: {
|
|
||||||
include: {
|
|
||||||
user: { select: { id: true, name: true } },
|
|
||||||
},
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderBy: { id: 'asc' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
skip,
|
skip,
|
||||||
take,
|
take,
|
||||||
orderBy: { id: 'asc' },
|
orderBy: { id: 'asc' },
|
||||||
@@ -2324,7 +2510,7 @@ export class AssetService {
|
|||||||
},
|
},
|
||||||
async () =>
|
async () =>
|
||||||
this.prismaClient.assetComment.count({
|
this.prismaClient.assetComment.count({
|
||||||
where: { assetId: resolvedAssetId, replyToId: null },
|
where,
|
||||||
}),
|
}),
|
||||||
params,
|
params,
|
||||||
)
|
)
|
||||||
@@ -2334,6 +2520,36 @@ export class AssetService {
|
|||||||
return { data: infos, pageInfo }
|
return { data: infos, pageInfo }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async listAllComments(
|
||||||
|
assetId: string,
|
||||||
|
requestingUserId?: string,
|
||||||
|
options?: { excludeInternal?: boolean },
|
||||||
|
): Promise<CommentInfo[]> {
|
||||||
|
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
|
||||||
|
|
||||||
|
const comments = await this.prismaClient.assetComment.findMany({
|
||||||
|
where: {
|
||||||
|
assetId: resolvedAssetId,
|
||||||
|
replyToId: null,
|
||||||
|
...(options?.excludeInternal ? { isInternal: false } : {}),
|
||||||
|
},
|
||||||
|
include: this.getCommentInclude(options),
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
return Promise.all(comments.map((c) => this.toCommentInfo(c, requestingUserId)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async getProjectNameForAsset(assetId: string): Promise<string | null> {
|
||||||
|
const asset = await this.prismaClient.asset.findUnique({
|
||||||
|
where: { id: assetId },
|
||||||
|
select: {
|
||||||
|
project: { select: { name: true } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return asset?.project?.name ?? null
|
||||||
|
}
|
||||||
|
|
||||||
async exportComments(
|
async exportComments(
|
||||||
assetId: string,
|
assetId: string,
|
||||||
format: CommentExportFormat,
|
format: CommentExportFormat,
|
||||||
@@ -2432,9 +2648,10 @@ export class AssetService {
|
|||||||
async toAssetInfos(
|
async toAssetInfos(
|
||||||
assets: AssetWithIncludes[],
|
assets: AssetWithIncludes[],
|
||||||
previewFormat?: PreviewFormat,
|
previewFormat?: PreviewFormat,
|
||||||
options?: { includeDeletedChildren?: boolean },
|
options?: { includeDeletedChildren?: boolean; excludeInternalComments?: boolean },
|
||||||
): Promise<AssetInfo[]> {
|
): Promise<AssetInfo[]> {
|
||||||
const includeDeletedChildren = options?.includeDeletedChildren ?? false
|
const includeDeletedChildren = options?.includeDeletedChildren ?? false
|
||||||
|
const excludeInternalComments = options?.excludeInternalComments ?? false
|
||||||
const stackIds = new Set<string>()
|
const stackIds = new Set<string>()
|
||||||
|
|
||||||
for (const a of assets) {
|
for (const a of assets) {
|
||||||
@@ -2524,6 +2741,12 @@ export class AssetService {
|
|||||||
by: ['assetId'],
|
by: ['assetId'],
|
||||||
where: {
|
where: {
|
||||||
assetId: { in: Array.from(commentTargetIds) },
|
assetId: { in: Array.from(commentTargetIds) },
|
||||||
|
...(excludeInternalComments
|
||||||
|
? {
|
||||||
|
isInternal: false,
|
||||||
|
OR: [{ replyToId: null }, { replyTo: { isInternal: false } }],
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
_count: { _all: true },
|
_count: { _all: true },
|
||||||
})
|
})
|
||||||
@@ -3080,6 +3303,10 @@ export class AssetService {
|
|||||||
* that belong to an asset they have access to.
|
* that belong to an asset they have access to.
|
||||||
*/
|
*/
|
||||||
async getDownloadUrl(assetId: string, key: string): Promise<string> {
|
async getDownloadUrl(assetId: string, key: string): Promise<string> {
|
||||||
|
return (await this.getDownloadUrlWithAsset(assetId, key)).url
|
||||||
|
}
|
||||||
|
|
||||||
|
async getDownloadUrlWithAsset(assetId: string, key: string) {
|
||||||
const targetAssetId = await this.resolveLatestVersionId(assetId)
|
const targetAssetId = await this.resolveLatestVersionId(assetId)
|
||||||
const asset = await this.prismaClient.asset.findUnique({
|
const asset = await this.prismaClient.asset.findUnique({
|
||||||
where: { id: targetAssetId },
|
where: { id: targetAssetId },
|
||||||
@@ -3100,6 +3327,7 @@ export class AssetService {
|
|||||||
throw new Error('Key does not belong to this asset')
|
throw new Error('Key does not belong to this asset')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let signedAssetId = asset.id
|
||||||
let storageKey = asset.storageKey.key
|
let storageKey = asset.storageKey.key
|
||||||
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||||
let targetName = asset.name
|
let targetName = asset.name
|
||||||
@@ -3115,12 +3343,14 @@ export class AssetService {
|
|||||||
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
|
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
|
id: true,
|
||||||
name: true,
|
name: true,
|
||||||
status: true,
|
status: true,
|
||||||
storageKey: { select: { key: true, isArchived: true } },
|
storageKey: { select: { key: true, isArchived: true } },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
if (sibling?.storageKey?.key) {
|
if (sibling?.storageKey?.key) {
|
||||||
|
signedAssetId = sibling.id
|
||||||
storageKey = sibling.storageKey.key
|
storageKey = sibling.storageKey.key
|
||||||
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||||
targetStatus = sibling.status
|
targetStatus = sibling.status
|
||||||
@@ -3176,7 +3406,14 @@ export class AssetService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
|
const url = await s3Service.presign(
|
||||||
|
process.env.S3_BUCKET || 'shumai',
|
||||||
|
key,
|
||||||
|
'GET',
|
||||||
|
true,
|
||||||
|
downloadFilename,
|
||||||
|
)
|
||||||
|
return { url, assetId: signedAssetId }
|
||||||
}
|
}
|
||||||
|
|
||||||
async archiveAssets(
|
async archiveAssets(
|
||||||
@@ -3386,6 +3623,7 @@ export class AssetService {
|
|||||||
updatedAt: c.updatedAt.toISOString(),
|
updatedAt: c.updatedAt.toISOString(),
|
||||||
sessionId: c.sessionId,
|
sessionId: c.sessionId,
|
||||||
isCompleted: c.isCompleted,
|
isCompleted: c.isCompleted,
|
||||||
|
isInternal: c.isInternal,
|
||||||
completionLastChangedBy,
|
completionLastChangedBy,
|
||||||
reactionCounts,
|
reactionCounts,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -595,5 +595,70 @@ describe('AuthzService', () => {
|
|||||||
}),
|
}),
|
||||||
).rejects.toThrow('Permission denied')
|
).rejects.toThrow('Permission denied')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('limits Kanban task reads for project-scoped members to their projects and their own tasks', async () => {
|
||||||
|
const owner = await prisma.user.create({
|
||||||
|
data: { name: 'Owner User', email: 'owner-kanban-read@example.com', password: 'pass' },
|
||||||
|
})
|
||||||
|
const client = await prisma.user.create({
|
||||||
|
data: { name: 'Client User', email: 'client-kanban-read@example.com', password: 'pass' },
|
||||||
|
})
|
||||||
|
const teamReviewer = await prisma.user.create({
|
||||||
|
data: { name: 'Team Reviewer', email: 'rev-kanban-read@example.com', password: 'pass' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const team = await prisma.team.create({ data: { name: 'Kanban Read Team' } })
|
||||||
|
const ownProject = await prisma.project.create({
|
||||||
|
data: { name: 'Client Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
const otherProject = await prisma.project.create({
|
||||||
|
data: { name: 'Internal Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.teamMember.create({
|
||||||
|
data: { teamId: team.id, userId: owner.id, role: 'owner', scope: 'team' },
|
||||||
|
})
|
||||||
|
const clientMember = await prisma.teamMember.create({
|
||||||
|
data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' },
|
||||||
|
})
|
||||||
|
await prisma.projectMember.create({
|
||||||
|
data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' },
|
||||||
|
})
|
||||||
|
await prisma.teamMember.create({
|
||||||
|
data: { teamId: team.id, userId: teamReviewer.id, role: 'reviewer', scope: 'team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const createTask = (title: string, projectId?: string, assigneeId?: string) =>
|
||||||
|
prisma.kanbanTask.create({
|
||||||
|
data: {
|
||||||
|
teamId: team.id,
|
||||||
|
title,
|
||||||
|
projectId,
|
||||||
|
creatorId: owner.id,
|
||||||
|
reporterId: owner.id,
|
||||||
|
assigneeId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const ownTask = await createTask('Client task', ownProject.id)
|
||||||
|
const otherTask = await createTask('Internal task', otherProject.id)
|
||||||
|
const teamTask = await createTask('Team task')
|
||||||
|
const assignedTask = await createTask('Assigned task', otherProject.id, client.id)
|
||||||
|
|
||||||
|
const read = (user: { id: string }, id: string) =>
|
||||||
|
authzService.hasPermission({
|
||||||
|
type: ResourceType.KanbanTask,
|
||||||
|
id,
|
||||||
|
user,
|
||||||
|
permission: Permission.Read,
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(read(client, ownTask.id)).resolves.toBeUndefined()
|
||||||
|
await expect(read(client, assignedTask.id)).resolves.toBeUndefined()
|
||||||
|
await expect(read(client, otherTask.id)).rejects.toThrow('User has only project scope')
|
||||||
|
await expect(read(client, teamTask.id)).rejects.toThrow('User has only project scope')
|
||||||
|
|
||||||
|
await expect(read(teamReviewer, otherTask.id)).resolves.toBeUndefined()
|
||||||
|
await expect(read(teamReviewer, teamTask.id)).resolves.toBeUndefined()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -122,17 +122,16 @@ export class AuthzService {
|
|||||||
})
|
})
|
||||||
if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' })
|
if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' })
|
||||||
|
|
||||||
// If this is a KanbanTask and user is a team member, check if they are the assignee, reporter, or creator
|
// A project-scoped member can read or edit a KanbanTask outside their projects
|
||||||
|
// only when they are its assignee, reporter, or creator.
|
||||||
if (req.type === ResourceType.KanbanTask) {
|
if (req.type === ResourceType.KanbanTask) {
|
||||||
if (req.permission === Permission.Read) {
|
if (req.permission === Permission.Read || req.permission === Permission.Edit) {
|
||||||
return
|
|
||||||
}
|
|
||||||
if (req.permission === Permission.Edit) {
|
|
||||||
const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id)
|
const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id)
|
||||||
if (isParticipant) {
|
if (isParticipant) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
throw new HTTPException(403, { message: 'User has only project scope' })
|
||||||
}
|
}
|
||||||
|
|
||||||
// Project-scoped member on a team-level resource (no project context):
|
// Project-scoped member on a team-level resource (no project context):
|
||||||
|
|||||||
@@ -0,0 +1,738 @@
|
|||||||
|
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||||
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
import {
|
||||||
|
CommentFrameService,
|
||||||
|
FrameExtractionQueue,
|
||||||
|
selectBestVideoProxyKey,
|
||||||
|
type ExecFileFn,
|
||||||
|
} from './comment-frame'
|
||||||
|
import { execFileSync } from 'child_process'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import * as os from 'os'
|
||||||
|
import * as path from 'path'
|
||||||
|
import sharp from 'sharp'
|
||||||
|
|
||||||
|
async function createSamplePngBuffer(): Promise<Buffer> {
|
||||||
|
return sharp({
|
||||||
|
create: {
|
||||||
|
width: 32,
|
||||||
|
height: 18,
|
||||||
|
channels: 3,
|
||||||
|
background: { r: 20, g: 120, b: 220 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.png()
|
||||||
|
.toBuffer()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createSampleWebpBuffer(): Promise<Buffer> {
|
||||||
|
return sharp({
|
||||||
|
create: {
|
||||||
|
width: 32,
|
||||||
|
height: 18,
|
||||||
|
channels: 3,
|
||||||
|
background: { r: 220, g: 80, b: 40 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.webp()
|
||||||
|
.toBuffer()
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('FrameExtractionQueue', () => {
|
||||||
|
it('enforces maxConcurrency and processes queued tasks in FIFO order', async () => {
|
||||||
|
const queue = new FrameExtractionQueue(2)
|
||||||
|
let active = 0
|
||||||
|
let maxObserved = 0
|
||||||
|
const order: number[] = []
|
||||||
|
const resolvers: Array<() => void> = []
|
||||||
|
|
||||||
|
const makeTask = (id: number) =>
|
||||||
|
queue.enqueue(async () => {
|
||||||
|
active++
|
||||||
|
maxObserved = Math.max(maxObserved, active)
|
||||||
|
order.push(id)
|
||||||
|
await new Promise<void>((resolve) => resolvers.push(resolve))
|
||||||
|
active--
|
||||||
|
return id
|
||||||
|
})
|
||||||
|
|
||||||
|
const p1 = makeTask(1)
|
||||||
|
const p2 = makeTask(2)
|
||||||
|
const p3 = makeTask(3)
|
||||||
|
const p4 = makeTask(4)
|
||||||
|
|
||||||
|
expect(queue.activeCount).toBe(2)
|
||||||
|
expect(queue.queuedCount).toBe(2)
|
||||||
|
expect(maxObserved).toBe(2)
|
||||||
|
|
||||||
|
resolvers.shift()?.()
|
||||||
|
await p1
|
||||||
|
expect(queue.activeCount).toBe(2)
|
||||||
|
expect(queue.queuedCount).toBe(1)
|
||||||
|
|
||||||
|
resolvers.shift()?.()
|
||||||
|
await p2
|
||||||
|
expect(queue.activeCount).toBe(2)
|
||||||
|
expect(queue.queuedCount).toBe(0)
|
||||||
|
|
||||||
|
resolvers.shift()?.()
|
||||||
|
await p3
|
||||||
|
resolvers.shift()?.()
|
||||||
|
await p4
|
||||||
|
|
||||||
|
expect(order).toEqual([1, 2, 3, 4])
|
||||||
|
expect(maxObserved).toBe(2)
|
||||||
|
expect(queue.activeCount).toBe(0)
|
||||||
|
expect(queue.queuedCount).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cancels queued tasks when their AbortSignal fires before execution', async () => {
|
||||||
|
const queue = new FrameExtractionQueue(1)
|
||||||
|
let releaseFirst!: () => void
|
||||||
|
const first = queue.enqueue(
|
||||||
|
() =>
|
||||||
|
new Promise<string>((resolve) => {
|
||||||
|
releaseFirst = () => resolve('first')
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const controller = new AbortController()
|
||||||
|
const runSecond = vi.fn().mockResolvedValue('second')
|
||||||
|
const second = queue.enqueue(runSecond, controller.signal)
|
||||||
|
|
||||||
|
expect(queue.queuedCount).toBe(1)
|
||||||
|
controller.abort()
|
||||||
|
|
||||||
|
await expect(second).rejects.toThrow('Frame extraction aborted')
|
||||||
|
expect(queue.queuedCount).toBe(0)
|
||||||
|
expect(runSecond).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
releaseFirst()
|
||||||
|
await expect(first).resolves.toBe('first')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('selectBestVideoProxyKey', () => {
|
||||||
|
it('prefers SDR proxies over HDR and chooses lowest adequate resolution >= 360p', () => {
|
||||||
|
const key = selectBestVideoProxyKey([
|
||||||
|
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
|
||||||
|
{ key: 'sdr-1080.mp4', width: 1920, height: 1080, hdr: false, resolution: '1080p' },
|
||||||
|
{ key: 'sdr-540.mp4', width: 960, height: 540, hdr: false, resolution: '540p' },
|
||||||
|
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
|
||||||
|
])
|
||||||
|
expect(key).toBe('sdr-540.mp4')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to highest available SDR proxy if all are below 360p', () => {
|
||||||
|
const key = selectBestVideoProxyKey([
|
||||||
|
{ key: 'sdr-180.mp4', width: 320, height: 180, hdr: false, resolution: '180p' },
|
||||||
|
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
|
||||||
|
])
|
||||||
|
expect(key).toBe('sdr-240.mp4')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to HDR proxy if no SDR proxy exists', () => {
|
||||||
|
const key = selectBestVideoProxyKey([
|
||||||
|
{ key: 'hdr-1080.mp4', width: 1920, height: 1080, hdr: true, resolution: '1080p' },
|
||||||
|
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
|
||||||
|
])
|
||||||
|
expect(key).toBe('hdr-720.mp4')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns null when no valid keys exist', () => {
|
||||||
|
expect(selectBestVideoProxyKey([])).toBeNull()
|
||||||
|
expect(selectBestVideoProxyKey(null)).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('CommentFrameService & AssetService print helpers', () => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let userId: string
|
||||||
|
let teamId: string
|
||||||
|
let projectId: string
|
||||||
|
let rootFolderId: string
|
||||||
|
let subFolderId: string
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const user = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
name: 'Alice',
|
||||||
|
email: `alice-${Date.now()}-${Math.random()}@example.com`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
userId = user.id
|
||||||
|
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: {
|
||||||
|
name: 'Studio Team',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
teamId = team.id
|
||||||
|
|
||||||
|
const rootFolder = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'root',
|
||||||
|
type: AssetType.root,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
creatorId: userId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
rootFolderId = rootFolder.id
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: {
|
||||||
|
name: 'Commercial Cut',
|
||||||
|
teamId,
|
||||||
|
rootFolderId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
projectId = project.id
|
||||||
|
|
||||||
|
await prisma.asset.update({
|
||||||
|
where: { id: rootFolderId },
|
||||||
|
data: { projectId },
|
||||||
|
})
|
||||||
|
|
||||||
|
const subFolder = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'Dailies',
|
||||||
|
type: AssetType.folder,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
projectId,
|
||||||
|
parentId: rootFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
subFolderId = subFolder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips extraction when the request is aborted during asset lookup', async () => {
|
||||||
|
const storageKey = await prisma.storageKey.create({ data: { key: 'files/clip.mp4' } })
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'clip.mp4',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const controller = new AbortController()
|
||||||
|
const resolveLatestVersionId = assetService.resolveLatestVersionId.bind(assetService)
|
||||||
|
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementationOnce(async (assetId) => {
|
||||||
|
const resolvedId = await resolveLatestVersionId(assetId)
|
||||||
|
controller.abort()
|
||||||
|
return resolvedId
|
||||||
|
})
|
||||||
|
const resolveInput = vi.spyOn(s3Service, 'resolveInput').mockResolvedValue('/local/clip.mp4')
|
||||||
|
const execFileFn = vi.fn<ExecFileFn>().mockResolvedValue({ stdout: '', stderr: '' })
|
||||||
|
const service = new CommentFrameService({ execFileFn })
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.extractFrame({ assetId: asset.id, second: 0, signal: controller.signal }),
|
||||||
|
).rejects.toMatchObject({ name: 'AbortError' })
|
||||||
|
expect(resolveInput).not.toHaveBeenCalled()
|
||||||
|
expect(execFileFn).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('extracts a video frame using the lowest adequate SDR proxy and deduplicates concurrent requests', async () => {
|
||||||
|
const webpBuffer = await createSampleWebpBuffer()
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: { key: 'files/video-original.mp4' },
|
||||||
|
})
|
||||||
|
const videoAsset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'scene1.mp4',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
media: {
|
||||||
|
proxyType: 'video',
|
||||||
|
duration: 10,
|
||||||
|
filesize: 1000,
|
||||||
|
frames: 240,
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [
|
||||||
|
{ key: 'files/proxies/1080p.mp4', width: 1920, height: 1080, hdr: false },
|
||||||
|
{ key: 'files/proxies/540p.mp4', width: 960, height: 540, hdr: false },
|
||||||
|
{ key: 'files/proxies/720p-hdr.mp4', width: 1280, height: 720, hdr: true },
|
||||||
|
],
|
||||||
|
finishedAt: new Date().toISOString(),
|
||||||
|
metadata: null,
|
||||||
|
original: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const resolveInputSpy = vi
|
||||||
|
.spyOn(s3Service, 'resolveInput')
|
||||||
|
.mockResolvedValue('/local/files/proxies/540p.mp4')
|
||||||
|
|
||||||
|
let releaseExec!: () => void
|
||||||
|
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
releaseExec = resolve
|
||||||
|
})
|
||||||
|
const outPath = args[args.length - 1]
|
||||||
|
fs.writeFileSync(outPath, webpBuffer)
|
||||||
|
return { stdout: '', stderr: '' }
|
||||||
|
})
|
||||||
|
|
||||||
|
const service = new CommentFrameService({ maxConcurrency: 2, execFileFn: execFileMock })
|
||||||
|
|
||||||
|
const p1 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
|
||||||
|
const p2 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
|
||||||
|
|
||||||
|
// Let async DB lookup finish before releasing exec
|
||||||
|
await vi.waitFor(() => expect(execFileMock).toHaveBeenCalledTimes(1))
|
||||||
|
releaseExec()
|
||||||
|
|
||||||
|
const [r1, r2] = await Promise.all([p1, p2])
|
||||||
|
expect(r1.mimeType).toBe('image/webp')
|
||||||
|
expect(r1.buffer.equals(webpBuffer)).toBe(true)
|
||||||
|
expect(r2.buffer.equals(webpBuffer)).toBe(true)
|
||||||
|
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||||
|
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/proxies/540p.mp4')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('extracts a 3D model turntable frame and enforces watermark-only proxies when watermarkConfigId is set', async () => {
|
||||||
|
const webpBuffer = await createSampleWebpBuffer()
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: { key: 'files/chair.glb' },
|
||||||
|
})
|
||||||
|
const modelAsset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'chair.glb',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
mediaType: 'model/gltf-binary',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
media: {
|
||||||
|
proxyType: '3d',
|
||||||
|
duration: 24,
|
||||||
|
filesize: 2000,
|
||||||
|
frames: 24,
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [{ key: 'files/proxies/turntable.mp4', width: 1024, height: 1024 }],
|
||||||
|
finishedAt: new Date().toISOString(),
|
||||||
|
metadata: null,
|
||||||
|
original: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const watermarkSpy = vi
|
||||||
|
.spyOn(watermarkService, 'getCompletedWatermarkMediaMap')
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
new Map([
|
||||||
|
[
|
||||||
|
modelAsset.id,
|
||||||
|
{
|
||||||
|
proxyType: '3d',
|
||||||
|
duration: 24,
|
||||||
|
filesize: 2000,
|
||||||
|
frames: 24,
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [{ key: 'files/wm/turntable-wm.mp4', width: 1024, height: 1024 }],
|
||||||
|
finishedAt: new Date().toISOString(),
|
||||||
|
metadata: null,
|
||||||
|
original: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(new Map())
|
||||||
|
|
||||||
|
const resolveInputSpy = vi
|
||||||
|
.spyOn(s3Service, 'resolveInput')
|
||||||
|
.mockResolvedValue('/local/files/wm/turntable-wm.mp4')
|
||||||
|
|
||||||
|
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
|
||||||
|
const outPath = args[args.length - 1]
|
||||||
|
fs.writeFileSync(outPath, webpBuffer)
|
||||||
|
return { stdout: '', stderr: '' }
|
||||||
|
})
|
||||||
|
|
||||||
|
const service = new CommentFrameService({ execFileFn: execFileMock })
|
||||||
|
|
||||||
|
const res = await service.extractFrame({
|
||||||
|
assetId: modelAsset.id,
|
||||||
|
second: 3,
|
||||||
|
width: 400,
|
||||||
|
watermarkConfigId: 'wm-cfg-1',
|
||||||
|
})
|
||||||
|
expect(res.mimeType).toBe('image/webp')
|
||||||
|
expect(watermarkSpy).toHaveBeenCalledWith([modelAsset.id], 'wm-cfg-1')
|
||||||
|
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/wm/turntable-wm.mp4')
|
||||||
|
|
||||||
|
// Missing watermark proxy must reject with 422 rather than leaking unwatermarked media
|
||||||
|
await expect(
|
||||||
|
service.extractFrame({
|
||||||
|
assetId: modelAsset.id,
|
||||||
|
second: 3,
|
||||||
|
width: 400,
|
||||||
|
watermarkConfigId: 'wm-cfg-2',
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({ status: 422 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders a PDF page frame via pdftoppm and sharp', async () => {
|
||||||
|
const samplePng = await createSamplePngBuffer()
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: { key: 'files/deck.pdf' },
|
||||||
|
})
|
||||||
|
const pdfAsset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'deck.pdf',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
mediaType: 'application/pdf',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
media: {
|
||||||
|
proxyType: 'pdf',
|
||||||
|
duration: 0,
|
||||||
|
filesize: 5000,
|
||||||
|
frames: 5,
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [],
|
||||||
|
pdfTranscode: { key: 'files/proxies/deck.pdf' },
|
||||||
|
finishedAt: new Date().toISOString(),
|
||||||
|
metadata: null,
|
||||||
|
original: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const downloadSpy = vi
|
||||||
|
.spyOn(s3Service, 'downloadToFile')
|
||||||
|
.mockImplementation(async (_bucket, _key, dest) => {
|
||||||
|
fs.writeFileSync(dest, '%PDF-1.4 mock')
|
||||||
|
})
|
||||||
|
|
||||||
|
const execFileMock = vi.fn<ExecFileFn>(async (file, args) => {
|
||||||
|
expect(file).toBe('pdftoppm')
|
||||||
|
expect(args[args.indexOf('-scale-to') + 1]).toBe('400')
|
||||||
|
expect(args).toContain('-f')
|
||||||
|
expect(args).toContain('3')
|
||||||
|
const prefix = args[args.length - 1]
|
||||||
|
fs.writeFileSync(`${prefix}-3.png`, samplePng)
|
||||||
|
return { stdout: '', stderr: '' }
|
||||||
|
})
|
||||||
|
|
||||||
|
const service = new CommentFrameService({ execFileFn: execFileMock })
|
||||||
|
const res = await service.extractFrame({ assetId: pdfAsset.id, second: 3, width: 400 })
|
||||||
|
expect(downloadSpy).toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
'files/proxies/deck.pdf',
|
||||||
|
expect.stringContaining(path.sep),
|
||||||
|
)
|
||||||
|
expect(res.mimeType).toBe('image/webp')
|
||||||
|
expect(res.buffer.length).toBeGreaterThan(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects unsupported asset types with 400 and archived assets without proxy with 422', async () => {
|
||||||
|
const imgKey = await prisma.storageKey.create({
|
||||||
|
data: { key: 'files/photo.png' },
|
||||||
|
})
|
||||||
|
const imageAsset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'photo.png',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
mediaType: 'image/png',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: imgKey.id,
|
||||||
|
media: {
|
||||||
|
proxyType: 'image',
|
||||||
|
duration: 0,
|
||||||
|
filesize: 100,
|
||||||
|
frames: 1,
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [],
|
||||||
|
finishedAt: new Date().toISOString(),
|
||||||
|
metadata: null,
|
||||||
|
original: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const archivedKey = await prisma.storageKey.create({
|
||||||
|
data: { key: 'files/archived.mp4', isArchived: true },
|
||||||
|
})
|
||||||
|
const archivedVideo = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'archived.mp4',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.archived,
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: archivedKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const service = new CommentFrameService()
|
||||||
|
await expect(service.extractFrame({ assetId: imageAsset.id, second: 0 })).rejects.toMatchObject(
|
||||||
|
{ status: 400 },
|
||||||
|
)
|
||||||
|
await expect(
|
||||||
|
service.extractFrame({ assetId: archivedVideo.id, second: 1 }),
|
||||||
|
).rejects.toMatchObject({ status: 422 })
|
||||||
|
await expect(
|
||||||
|
service.extractFrame({ assetId: 'non-existent-id', second: 0 }),
|
||||||
|
).rejects.toMatchObject({ status: 404 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists all comments with replies, reactions, completion status, and fetches project name', async () => {
|
||||||
|
vi.spyOn(s3Service, 'presign').mockResolvedValue('http://mock-s3/file')
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: { key: 'files/cut.mp4' },
|
||||||
|
})
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'cut.mp4',
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const parent = await prisma.assetComment.create({
|
||||||
|
data: {
|
||||||
|
assetId: asset.id,
|
||||||
|
creatorId: userId,
|
||||||
|
message: 'Check lighting',
|
||||||
|
second: 1.5,
|
||||||
|
isCompleted: true,
|
||||||
|
completionLastChangedById: userId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await prisma.assetCommentReaction.create({
|
||||||
|
data: { commentId: parent.id, userId, code: '👍' },
|
||||||
|
})
|
||||||
|
await prisma.assetComment.create({
|
||||||
|
data: {
|
||||||
|
assetId: asset.id,
|
||||||
|
creatorId: userId,
|
||||||
|
replyToId: parent.id,
|
||||||
|
message: 'Fixed in v2',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const allComments = await assetService.listAllComments(asset.id, userId)
|
||||||
|
expect(allComments).toHaveLength(1)
|
||||||
|
expect(allComments[0].message).toBe('Check lighting')
|
||||||
|
expect(allComments[0].isCompleted).toBe(true)
|
||||||
|
expect(allComments[0].reactionCounts).toEqual([
|
||||||
|
expect.objectContaining({ code: '👍', count: 1, requestingUserReacted: true }),
|
||||||
|
])
|
||||||
|
expect(allComments[0].replies).toHaveLength(1)
|
||||||
|
expect(allComments[0].replies[0].message).toBe('Fixed in v2')
|
||||||
|
|
||||||
|
const projectName = await assetService.getProjectNameForAsset(asset.id)
|
||||||
|
expect(projectName).toBe('Commercial Cut')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('extracts exact frames with real ffmpeg for 30fps video, 23.976fps video, and 6fps 3D turntable', async () => {
|
||||||
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-frame-acc-'))
|
||||||
|
const w = 64
|
||||||
|
const h = 64
|
||||||
|
|
||||||
|
const createColorCodedVideo = (filename: string, rateArg: string, totalFrames: number) => {
|
||||||
|
const raw = Buffer.alloc(w * h * 3 * totalFrames)
|
||||||
|
for (let n = 0; n < totalFrames; n++) {
|
||||||
|
const r = (n * 9) & 255
|
||||||
|
const g = (n * 15) & 255
|
||||||
|
const off = n * w * h * 3
|
||||||
|
for (let i = 0; i < w * h; i++) {
|
||||||
|
raw[off + i * 3] = r
|
||||||
|
raw[off + i * 3 + 1] = g
|
||||||
|
raw[off + i * 3 + 2] = 120
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const rawPath = path.join(tmpDir, `${filename}.rgb`)
|
||||||
|
const mp4Path = path.join(tmpDir, `${filename}.mp4`)
|
||||||
|
fs.writeFileSync(rawPath, raw)
|
||||||
|
execFileSync('ffmpeg', [
|
||||||
|
'-y',
|
||||||
|
'-loglevel',
|
||||||
|
'error',
|
||||||
|
'-f',
|
||||||
|
'rawvideo',
|
||||||
|
'-pix_fmt',
|
||||||
|
'rgb24',
|
||||||
|
'-s',
|
||||||
|
`${w}x${h}`,
|
||||||
|
'-r',
|
||||||
|
rateArg,
|
||||||
|
'-i',
|
||||||
|
rawPath,
|
||||||
|
'-c:v',
|
||||||
|
'libx264',
|
||||||
|
'-pix_fmt',
|
||||||
|
'yuv420p',
|
||||||
|
'-g',
|
||||||
|
'12',
|
||||||
|
'-bf',
|
||||||
|
'2',
|
||||||
|
'-movflags',
|
||||||
|
'+faststart',
|
||||||
|
mp4Path,
|
||||||
|
])
|
||||||
|
return mp4Path
|
||||||
|
}
|
||||||
|
|
||||||
|
const identifyExtractedFrame = async (webpBuffer: Buffer, totalFrames: number) => {
|
||||||
|
const { data, info } = await sharp(webpBuffer).raw().toBuffer({ resolveWithObject: true })
|
||||||
|
const cx = Math.floor(info.width / 2)
|
||||||
|
const cy = Math.floor(info.height / 2)
|
||||||
|
const idx = (cy * info.width + cx) * info.channels
|
||||||
|
const r = data[idx]
|
||||||
|
const g = data[idx + 1]
|
||||||
|
let best = -1
|
||||||
|
let bestDist = Infinity
|
||||||
|
for (let n = 0; n < totalFrames; n++) {
|
||||||
|
const dr = r - ((n * 9) & 255)
|
||||||
|
const dg = g - ((n * 15) & 255)
|
||||||
|
const dist = dr * dr + dg * dg
|
||||||
|
if (dist < bestDist) {
|
||||||
|
bestDist = dist
|
||||||
|
best = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const mp4Fps30 = createColorCodedVideo('v30', '30', 24)
|
||||||
|
const mp4Fps23976 = createColorCodedVideo('v23976', '24000/1001', 24)
|
||||||
|
const mp4Turntable = createColorCodedVideo('turntable', '6', 24)
|
||||||
|
|
||||||
|
const keyMap: Record<string, string> = {
|
||||||
|
'files/proxies/v30.mp4': mp4Fps30,
|
||||||
|
'files/proxies/v23976.mp4': mp4Fps23976,
|
||||||
|
'files/proxies/turntable.mp4': mp4Turntable,
|
||||||
|
}
|
||||||
|
vi.spyOn(s3Service, 'resolveInput').mockImplementation(async (_bucket, key) => keyMap[key])
|
||||||
|
|
||||||
|
const createAsset = async (
|
||||||
|
name: string,
|
||||||
|
proxyType: 'video' | '3d',
|
||||||
|
proxyKey: string,
|
||||||
|
fps: number,
|
||||||
|
totalFrames: number,
|
||||||
|
) => {
|
||||||
|
const sk = await prisma.storageKey.create({ data: { key: `files/${name}` } })
|
||||||
|
return prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
type: AssetType.file,
|
||||||
|
status: AssetStatus.processed,
|
||||||
|
mediaType: proxyType === '3d' ? 'model/gltf-binary' : 'video/mp4',
|
||||||
|
projectId,
|
||||||
|
parentId: subFolderId,
|
||||||
|
creatorId: userId,
|
||||||
|
storageKeyId: sk.id,
|
||||||
|
media: {
|
||||||
|
proxyType,
|
||||||
|
duration: totalFrames / fps,
|
||||||
|
filesize: 1000,
|
||||||
|
frames: totalFrames,
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [{ key: proxyKey, width: 64, height: 64, hdr: false }],
|
||||||
|
finishedAt: new Date().toISOString(),
|
||||||
|
metadata: {
|
||||||
|
originalHeight: h,
|
||||||
|
originalWidth: w,
|
||||||
|
hasAudio: false,
|
||||||
|
bitRate: 100000,
|
||||||
|
frameRate: fps,
|
||||||
|
totalFrames,
|
||||||
|
duration: totalFrames / fps,
|
||||||
|
startTimecode: '00:00:00:00',
|
||||||
|
format: {},
|
||||||
|
},
|
||||||
|
original: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const asset30 = await createAsset('v30.mp4', 'video', 'files/proxies/v30.mp4', 30, 24)
|
||||||
|
const asset23976 = await createAsset(
|
||||||
|
'v23976.mp4',
|
||||||
|
'video',
|
||||||
|
'files/proxies/v23976.mp4',
|
||||||
|
24000 / 1001,
|
||||||
|
24,
|
||||||
|
)
|
||||||
|
const asset3d = await createAsset('chair.glb', '3d', 'files/proxies/turntable.mp4', 6, 24)
|
||||||
|
|
||||||
|
const realService = new CommentFrameService({ maxConcurrency: 2 })
|
||||||
|
|
||||||
|
// Frames where .toFixed(4) previously rounded UP and skipped to N+1:
|
||||||
|
// 30fps: frame 2 (0.06666... -> 0.0667), frame 5 (0.16666... -> 0.1667), frame 23 (last frame)
|
||||||
|
for (const frame of [0, 2, 5, 8, 17, 23]) {
|
||||||
|
const res = await realService.extractFrame({
|
||||||
|
assetId: asset30.id,
|
||||||
|
second: frame / 30,
|
||||||
|
width: 64,
|
||||||
|
})
|
||||||
|
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 23.976fps: frame 7 (0.291958 -> 0.2920), frame 8, frame 19, frame 23
|
||||||
|
for (const frame of [0, 7, 8, 19, 23]) {
|
||||||
|
const res = await realService.extractFrame({
|
||||||
|
assetId: asset23976.id,
|
||||||
|
second: frame / (24000 / 1001),
|
||||||
|
width: 64,
|
||||||
|
})
|
||||||
|
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3D 6fps turntable where model-viewer stores center times ((N + 0.5) / 6, last = (23 + 0.25) / 6)
|
||||||
|
for (const frame of [0, 1, 6, 12, 23]) {
|
||||||
|
const centerSec = frame === 23 ? (frame + 0.25) / 6 : (frame + 0.5) / 6
|
||||||
|
const res = await realService.extractFrame({
|
||||||
|
assetId: asset3d.id,
|
||||||
|
second: centerSec,
|
||||||
|
width: 64,
|
||||||
|
})
|
||||||
|
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,557 @@
|
|||||||
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
import { logger } from '@shumai/core/src/logger'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { secondToTurntableFrame, TURNTABLE_FPS } from '@shumai/core/src/utils/model3d'
|
||||||
|
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||||
|
import { prisma } from '@shumai/db'
|
||||||
|
import '@shumai/db/src/prisma-json-types'
|
||||||
|
import { execFile } from 'child_process'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import { HTTPException } from 'hono/http-exception'
|
||||||
|
import * as os from 'os'
|
||||||
|
import * as path from 'path'
|
||||||
|
import sharp from 'sharp'
|
||||||
|
import { ulid } from 'ulid'
|
||||||
|
import { promisify } from 'util'
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile)
|
||||||
|
|
||||||
|
const DEFAULT_CONCURRENCY = 4
|
||||||
|
const DEFAULT_FRAME_TIMEOUT_MS = 30_000
|
||||||
|
const MIN_PREFERRED_PROXY_HEIGHT = 360
|
||||||
|
|
||||||
|
export interface ExtractCommentFrameParams {
|
||||||
|
assetId: string
|
||||||
|
second: number
|
||||||
|
width?: number
|
||||||
|
watermarkConfigId?: string | null
|
||||||
|
signal?: AbortSignal
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExtractCommentFrameResult {
|
||||||
|
buffer: Buffer
|
||||||
|
mimeType: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ExecFileFn = (
|
||||||
|
file: string,
|
||||||
|
args: string[],
|
||||||
|
options?: { signal?: AbortSignal; timeout?: number },
|
||||||
|
) => Promise<{ stdout: string | Buffer; stderr: string | Buffer }>
|
||||||
|
|
||||||
|
interface QueuedTask<T> {
|
||||||
|
run: () => Promise<T>
|
||||||
|
resolve: (value: T) => void
|
||||||
|
reject: (err: unknown) => void
|
||||||
|
signal?: AbortSignal
|
||||||
|
onAbort?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bounded FIFO concurrency queue dedicated to on-demand comment frame extraction,
|
||||||
|
* isolated from background transcode workers so print requests stay fast without
|
||||||
|
* overloading the main API server.
|
||||||
|
*/
|
||||||
|
export class FrameExtractionQueue {
|
||||||
|
private running = 0
|
||||||
|
private readonly pending: QueuedTask<unknown>[] = []
|
||||||
|
|
||||||
|
constructor(private readonly maxConcurrency: number) {}
|
||||||
|
|
||||||
|
get activeCount(): number {
|
||||||
|
return this.running
|
||||||
|
}
|
||||||
|
|
||||||
|
get queuedCount(): number {
|
||||||
|
return this.pending.length
|
||||||
|
}
|
||||||
|
|
||||||
|
enqueue<T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||||
|
if (signal?.aborted) {
|
||||||
|
return Promise.reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
const task: QueuedTask<T> = { run, resolve, reject, signal }
|
||||||
|
|
||||||
|
if (signal) {
|
||||||
|
const onAbort = () => {
|
||||||
|
const idx = this.pending.indexOf(task as QueuedTask<unknown>)
|
||||||
|
if (idx !== -1) {
|
||||||
|
this.pending.splice(idx, 1)
|
||||||
|
signal.removeEventListener('abort', onAbort)
|
||||||
|
reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
task.onAbort = onAbort
|
||||||
|
signal.addEventListener('abort', onAbort, { once: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
this.pending.push(task as QueuedTask<unknown>)
|
||||||
|
this.drain()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private drain(): void {
|
||||||
|
while (this.running < this.maxConcurrency && this.pending.length > 0) {
|
||||||
|
const task = this.pending.shift()
|
||||||
|
if (!task) break
|
||||||
|
|
||||||
|
if (task.signal && task.onAbort) {
|
||||||
|
task.signal.removeEventListener('abort', task.onAbort)
|
||||||
|
}
|
||||||
|
if (task.signal?.aborted) {
|
||||||
|
task.reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
this.running++
|
||||||
|
task.run().then(
|
||||||
|
(result) => {
|
||||||
|
this.running--
|
||||||
|
this.drain()
|
||||||
|
task.resolve(result)
|
||||||
|
},
|
||||||
|
(err) => {
|
||||||
|
this.running--
|
||||||
|
this.drain()
|
||||||
|
task.reject(err)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks the fastest video proxy suitable for thumbnail extraction:
|
||||||
|
* 1. Prefer SDR proxies over HDR to avoid washed-out colors.
|
||||||
|
* 2. Among SDR proxies, pick the lowest resolution that is still >= 360p (fast seek + decode
|
||||||
|
* for a ~400px thumbnail). If none are >= 360p, pick the highest available SDR proxy.
|
||||||
|
*/
|
||||||
|
export function selectBestVideoProxyKey(
|
||||||
|
videoTranscodes?: PrismaJson.VideoTranscode[] | null,
|
||||||
|
): string | null {
|
||||||
|
if (!videoTranscodes || videoTranscodes.length === 0) return null
|
||||||
|
|
||||||
|
const valid = videoTranscodes.filter((t) => Boolean(t.key))
|
||||||
|
if (valid.length === 0) return null
|
||||||
|
|
||||||
|
const sdr = valid.filter((t) => !t.hdr)
|
||||||
|
const pool = sdr.length > 0 ? sdr : valid
|
||||||
|
|
||||||
|
const adequate = pool
|
||||||
|
.filter((t) => (t.height || 0) >= MIN_PREFERRED_PROXY_HEIGHT)
|
||||||
|
.sort((a, b) => (a.height || 0) - (b.height || 0))
|
||||||
|
if (adequate.length > 0) {
|
||||||
|
return adequate[0].key ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
const fallback = [...pool].sort((a, b) => (b.height || 0) - (a.height || 0))
|
||||||
|
return fallback[0]?.key ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves an ffmpeg `-ss` input seek timestamp that lands squarely on the exact
|
||||||
|
* target frame displayed by Shumai's video and 3D turntable players.
|
||||||
|
*
|
||||||
|
* `ffmpeg -ss T -i input -vframes 1` outputs the first frame with `PTS >= T`.
|
||||||
|
* Passing `N / fps` directly (especially after decimal rounding) or a frame center
|
||||||
|
* `(N + 0.5) / fps` causes ffmpeg to skip frame `N` and emit frame `N + 1` whenever
|
||||||
|
* `T` exceeds `PTS(N)` by even 1µs.
|
||||||
|
*
|
||||||
|
* Instead, we recover integer frame `N` with the exact player formula
|
||||||
|
* (`Math.floor(second * fps + 0.45)` for video, `secondToTurntableFrame` for 3D)
|
||||||
|
* and seek to the midpoint between frame `N - 1` and frame `N`: `(N - 0.5) / fps`,
|
||||||
|
* leaving a full ±0.5 frame tolerance margin on both sides.
|
||||||
|
*/
|
||||||
|
export function resolveFrameAccurateSeek(params: {
|
||||||
|
second: number
|
||||||
|
proxyType: 'video' | '3d'
|
||||||
|
frameRate?: number | null
|
||||||
|
totalFrames?: number | null
|
||||||
|
duration?: number | null
|
||||||
|
}): { seekTime: number; frameIndex: number | null } {
|
||||||
|
const safeSecond = Math.max(0, params.second)
|
||||||
|
|
||||||
|
if (params.proxyType === '3d') {
|
||||||
|
const frameIndex = secondToTurntableFrame(safeSecond)
|
||||||
|
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / TURNTABLE_FPS
|
||||||
|
return { seekTime, frameIndex }
|
||||||
|
}
|
||||||
|
|
||||||
|
const fps = params.frameRate && params.frameRate > 0 ? params.frameRate : null
|
||||||
|
if (fps) {
|
||||||
|
let frameIndex = Math.max(0, Math.floor(safeSecond * fps + 0.45))
|
||||||
|
if (params.totalFrames && params.totalFrames > 0) {
|
||||||
|
frameIndex = Math.min(frameIndex, params.totalFrames - 1)
|
||||||
|
} else if (params.duration && params.duration > 0) {
|
||||||
|
const maxFrame = Math.max(0, Math.round(params.duration * fps) - 1)
|
||||||
|
frameIndex = Math.min(frameIndex, maxFrame)
|
||||||
|
}
|
||||||
|
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / fps
|
||||||
|
return { seekTime, frameIndex }
|
||||||
|
}
|
||||||
|
|
||||||
|
const seekTime =
|
||||||
|
params.duration && params.duration > 0 && safeSecond >= params.duration
|
||||||
|
? Math.max(0, params.duration - 0.05)
|
||||||
|
: safeSecond
|
||||||
|
return { seekTime, frameIndex: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CommentFrameService {
|
||||||
|
private readonly queue: FrameExtractionQueue
|
||||||
|
private readonly inFlight = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
promise: Promise<ExtractCommentFrameResult>
|
||||||
|
controller: AbortController
|
||||||
|
waiters: number
|
||||||
|
}
|
||||||
|
>()
|
||||||
|
private readonly execFileFn: ExecFileFn
|
||||||
|
private readonly timeoutMs: number
|
||||||
|
|
||||||
|
constructor(options?: { maxConcurrency?: number; timeoutMs?: number; execFileFn?: ExecFileFn }) {
|
||||||
|
const envConcurrency = Number(process.env.PRINT_FRAME_CONCURRENCY)
|
||||||
|
const maxConcurrency =
|
||||||
|
options?.maxConcurrency ??
|
||||||
|
(Number.isInteger(envConcurrency) && envConcurrency > 0
|
||||||
|
? envConcurrency
|
||||||
|
: DEFAULT_CONCURRENCY)
|
||||||
|
this.queue = new FrameExtractionQueue(maxConcurrency)
|
||||||
|
this.timeoutMs = options?.timeoutMs ?? DEFAULT_FRAME_TIMEOUT_MS
|
||||||
|
this.execFileFn =
|
||||||
|
options?.execFileFn ??
|
||||||
|
((file, args, opts) =>
|
||||||
|
execFileAsync(file, args, {
|
||||||
|
signal: opts?.signal,
|
||||||
|
timeout: opts?.timeout,
|
||||||
|
maxBuffer: 10 * 1024 * 1024,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async extractFrame(params: ExtractCommentFrameParams): Promise<ExtractCommentFrameResult> {
|
||||||
|
if (params.signal?.aborted) {
|
||||||
|
throw new DOMException('Frame extraction aborted', 'AbortError')
|
||||||
|
}
|
||||||
|
|
||||||
|
const width = Math.max(64, Math.min(1280, Math.round(params.width ?? 400)))
|
||||||
|
const second = Math.max(0, params.second)
|
||||||
|
|
||||||
|
const targetAssetId = await assetService.resolveLatestVersionId(params.assetId)
|
||||||
|
const asset = await prisma.asset.findUnique({
|
||||||
|
where: { id: targetAssetId },
|
||||||
|
include: { storageKey: true },
|
||||||
|
})
|
||||||
|
params.signal?.throwIfAborted()
|
||||||
|
|
||||||
|
if (!asset || asset.isDeleted) {
|
||||||
|
throw new HTTPException(404, { message: 'Asset not found' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const media = asset.media as PrismaJson.MediaInfo | null
|
||||||
|
const proxyType = media?.proxyType ?? this.inferProxyType(asset.mediaType)
|
||||||
|
|
||||||
|
if (proxyType !== 'video' && proxyType !== '3d' && proxyType !== 'pdf') {
|
||||||
|
throw new HTTPException(400, {
|
||||||
|
message: 'Frame extraction is only supported for video, 3D model, and PDF assets',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const frameTarget =
|
||||||
|
proxyType === 'pdf'
|
||||||
|
? null
|
||||||
|
: resolveFrameAccurateSeek({
|
||||||
|
second,
|
||||||
|
proxyType,
|
||||||
|
frameRate: media?.metadata?.frameRate,
|
||||||
|
totalFrames: media?.metadata?.totalFrames ?? media?.frames,
|
||||||
|
duration: media?.duration ?? media?.metadata?.duration,
|
||||||
|
})
|
||||||
|
|
||||||
|
const normalizedKeyTime =
|
||||||
|
proxyType === 'pdf'
|
||||||
|
? `p${Math.max(1, Math.round(second))}`
|
||||||
|
: frameTarget!.frameIndex !== null
|
||||||
|
? `f${frameTarget!.frameIndex}`
|
||||||
|
: frameTarget!.seekTime.toFixed(6)
|
||||||
|
const dedupeKey = `${targetAssetId}:${params.watermarkConfigId ?? ''}:${normalizedKeyTime}:${width}`
|
||||||
|
|
||||||
|
let entry = this.inFlight.get(dedupeKey)
|
||||||
|
if (!entry) {
|
||||||
|
const controller = new AbortController()
|
||||||
|
const promise = this.queue
|
||||||
|
.enqueue(async () => {
|
||||||
|
if (proxyType === 'pdf') {
|
||||||
|
return this.extractPdfPageFrame({
|
||||||
|
asset,
|
||||||
|
media,
|
||||||
|
page: Math.max(1, Math.round(second)),
|
||||||
|
width,
|
||||||
|
signal: controller.signal,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return this.extractVideoFrame({
|
||||||
|
asset,
|
||||||
|
media,
|
||||||
|
second,
|
||||||
|
seekTime: frameTarget!.seekTime,
|
||||||
|
frameRate: proxyType === '3d' ? TURNTABLE_FPS : media?.metadata?.frameRate,
|
||||||
|
width,
|
||||||
|
watermarkConfigId: params.watermarkConfigId,
|
||||||
|
signal: controller.signal,
|
||||||
|
})
|
||||||
|
}, controller.signal)
|
||||||
|
.finally(() => {
|
||||||
|
if (this.inFlight.get(dedupeKey)?.promise === promise) {
|
||||||
|
this.inFlight.delete(dedupeKey)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
entry = { promise, controller, waiters: 0 }
|
||||||
|
this.inFlight.set(dedupeKey, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.waiters++
|
||||||
|
const currentEntry = entry
|
||||||
|
|
||||||
|
if (!params.signal) {
|
||||||
|
return currentEntry.promise.finally(() => {
|
||||||
|
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise<ExtractCommentFrameResult>((resolve, reject) => {
|
||||||
|
let settled = false
|
||||||
|
const cleanup = () => {
|
||||||
|
params.signal?.removeEventListener('abort', onAbort)
|
||||||
|
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||||
|
if (currentEntry.waiters === 0) {
|
||||||
|
currentEntry.controller.abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const onAbort = () => {
|
||||||
|
if (settled) return
|
||||||
|
settled = true
|
||||||
|
cleanup()
|
||||||
|
reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||||
|
}
|
||||||
|
|
||||||
|
params.signal!.addEventListener('abort', onAbort, { once: true })
|
||||||
|
|
||||||
|
currentEntry.promise.then(
|
||||||
|
(res) => {
|
||||||
|
if (settled) return
|
||||||
|
settled = true
|
||||||
|
params.signal?.removeEventListener('abort', onAbort)
|
||||||
|
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||||
|
resolve(res)
|
||||||
|
},
|
||||||
|
(err) => {
|
||||||
|
if (settled) return
|
||||||
|
settled = true
|
||||||
|
params.signal?.removeEventListener('abort', onAbort)
|
||||||
|
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||||
|
reject(err)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private inferProxyType(mediaType: string | null): PrismaJson.MediaInfo['proxyType'] | undefined {
|
||||||
|
const lower = (mediaType || '').toLowerCase()
|
||||||
|
if (lower.startsWith('video/')) return 'video'
|
||||||
|
if (lower === 'application/pdf') return 'pdf'
|
||||||
|
if (lower.startsWith('image/')) return 'image'
|
||||||
|
if (lower.startsWith('audio/')) return 'audio'
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
private async extractVideoFrame(params: {
|
||||||
|
asset: {
|
||||||
|
id: string
|
||||||
|
status: string
|
||||||
|
storageKey: { key: string; isArchived: boolean } | null
|
||||||
|
}
|
||||||
|
media: PrismaJson.MediaInfo | null
|
||||||
|
second: number
|
||||||
|
seekTime: number
|
||||||
|
frameRate?: number | null
|
||||||
|
width: number
|
||||||
|
watermarkConfigId?: string | null
|
||||||
|
signal?: AbortSignal
|
||||||
|
}): Promise<ExtractCommentFrameResult> {
|
||||||
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||||
|
let targetKey: string | null
|
||||||
|
|
||||||
|
if (params.watermarkConfigId) {
|
||||||
|
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
|
||||||
|
[params.asset.id],
|
||||||
|
params.watermarkConfigId,
|
||||||
|
)
|
||||||
|
const watermarkMedia = wfMap.get(params.asset.id) ?? null
|
||||||
|
targetKey = selectBestVideoProxyKey(watermarkMedia?.videoTranscodes)
|
||||||
|
if (!targetKey) {
|
||||||
|
throw new HTTPException(422, {
|
||||||
|
message: 'Watermarked proxy is not ready for this asset',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
targetKey = selectBestVideoProxyKey(params.media?.videoTranscodes)
|
||||||
|
if (!targetKey) {
|
||||||
|
const originalKey = params.asset.storageKey?.key
|
||||||
|
const isArchived =
|
||||||
|
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
|
||||||
|
if (!originalKey || isArchived) {
|
||||||
|
throw new HTTPException(422, {
|
||||||
|
message: 'Original video file is archived and no proxy is available',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
targetKey = originalKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputSource = await s3Service.resolveInput(bucket, targetKey)
|
||||||
|
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
|
||||||
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-frame-'))
|
||||||
|
|
||||||
|
try {
|
||||||
|
const outPath = path.join(tmpDir, `frame-${ulid()}.webp`)
|
||||||
|
const runFfmpeg = async (timestamp: number) => {
|
||||||
|
const args = [
|
||||||
|
'-y',
|
||||||
|
'-loglevel',
|
||||||
|
'warning',
|
||||||
|
...(isRemote
|
||||||
|
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
|
||||||
|
: []),
|
||||||
|
'-ss',
|
||||||
|
timestamp.toFixed(6),
|
||||||
|
'-i',
|
||||||
|
inputSource,
|
||||||
|
'-map',
|
||||||
|
'0:V:0',
|
||||||
|
'-vframes',
|
||||||
|
'1',
|
||||||
|
'-vf',
|
||||||
|
`scale=${params.width}:-2:force_original_aspect_ratio=decrease`,
|
||||||
|
'-c:v',
|
||||||
|
'libwebp',
|
||||||
|
'-q:v',
|
||||||
|
'80',
|
||||||
|
outPath,
|
||||||
|
]
|
||||||
|
await this.execFileFn('ffmpeg', args, {
|
||||||
|
signal: params.signal,
|
||||||
|
timeout: this.timeoutMs,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
await runFfmpeg(params.seekTime)
|
||||||
|
|
||||||
|
// If container metadata overestimated totalFrames at EOF, step back one frame and retry.
|
||||||
|
if ((!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) && params.seekTime > 0) {
|
||||||
|
const stepBack = params.frameRate && params.frameRate > 0 ? 1 / params.frameRate : 0.1
|
||||||
|
await runFfmpeg(Math.max(0, params.seekTime - stepBack))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) {
|
||||||
|
throw new HTTPException(404, { message: 'Could not extract frame at requested timestamp' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = fs.readFileSync(outPath)
|
||||||
|
return { buffer, mimeType: 'image/webp' }
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof HTTPException) throw err
|
||||||
|
if ((err as { name?: string })?.name === 'AbortError') throw err
|
||||||
|
logger.error(
|
||||||
|
{ assetId: params.asset.id, second: params.second, err },
|
||||||
|
'Failed to extract video comment frame',
|
||||||
|
)
|
||||||
|
throw new HTTPException(500, { message: 'Failed to extract video frame' })
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async extractPdfPageFrame(params: {
|
||||||
|
asset: {
|
||||||
|
id: string
|
||||||
|
status: string
|
||||||
|
storageKey: { key: string; isArchived: boolean } | null
|
||||||
|
}
|
||||||
|
media: PrismaJson.MediaInfo | null
|
||||||
|
page: number
|
||||||
|
width: number
|
||||||
|
signal?: AbortSignal
|
||||||
|
}): Promise<ExtractCommentFrameResult> {
|
||||||
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||||
|
const proxyKey = params.media?.pdfTranscode?.key
|
||||||
|
const originalKey = params.asset.storageKey?.key
|
||||||
|
const isArchived =
|
||||||
|
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
|
||||||
|
|
||||||
|
let targetKey: string | null = proxyKey || null
|
||||||
|
if (!targetKey) {
|
||||||
|
if (!originalKey || isArchived) {
|
||||||
|
throw new HTTPException(422, {
|
||||||
|
message: 'Original PDF file is archived and no proxy is available',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
targetKey = originalKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-pdf-'))
|
||||||
|
try {
|
||||||
|
const pdfPath = path.join(tmpDir, 'source.pdf')
|
||||||
|
await s3Service.downloadToFile(bucket, targetKey, pdfPath)
|
||||||
|
|
||||||
|
const pagePrefix = path.join(tmpDir, 'page')
|
||||||
|
await this.execFileFn(
|
||||||
|
'pdftoppm',
|
||||||
|
[
|
||||||
|
'-png',
|
||||||
|
'-scale-to',
|
||||||
|
String(params.width),
|
||||||
|
'-f',
|
||||||
|
String(params.page),
|
||||||
|
'-l',
|
||||||
|
String(params.page),
|
||||||
|
pdfPath,
|
||||||
|
pagePrefix,
|
||||||
|
],
|
||||||
|
{
|
||||||
|
signal: params.signal,
|
||||||
|
timeout: this.timeoutMs,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const pngFile = fs.readdirSync(tmpDir).find((f) => f.endsWith('.png'))
|
||||||
|
if (!pngFile) {
|
||||||
|
throw new HTTPException(404, { message: `PDF page ${params.page} not found` })
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = await sharp(path.join(tmpDir, pngFile), {
|
||||||
|
limitInputPixels: (params.width + 1) ** 2,
|
||||||
|
})
|
||||||
|
.toColorspace('srgb')
|
||||||
|
.webp({ quality: 82 })
|
||||||
|
.toBuffer()
|
||||||
|
|
||||||
|
return { buffer, mimeType: 'image/webp' }
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof HTTPException) throw err
|
||||||
|
if ((err as { name?: string })?.name === 'AbortError') throw err
|
||||||
|
logger.error(
|
||||||
|
{ assetId: params.asset.id, page: params.page, err },
|
||||||
|
'Failed to render PDF comment page frame',
|
||||||
|
)
|
||||||
|
throw new HTTPException(500, { message: 'Failed to render PDF page' })
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const commentFrameService = new CommentFrameService()
|
||||||
@@ -12,6 +12,8 @@ export interface PostCommentParams {
|
|||||||
/** Timecode in seconds (or the encoded viewing angle for 3D models). */
|
/** Timecode in seconds (or the encoded viewing angle for 3D models). */
|
||||||
second?: number
|
second?: number
|
||||||
attachmentIds?: string[]
|
attachmentIds?: string[]
|
||||||
|
/** Whether the comment is internal and hidden from public share links (default false). */
|
||||||
|
isInternal?: boolean
|
||||||
/** Whether mentions of agents start a chat with them (default true). */
|
/** Whether mentions of agents start a chat with them (default true). */
|
||||||
triggerAgents?: boolean
|
triggerAgents?: boolean
|
||||||
}
|
}
|
||||||
@@ -31,6 +33,7 @@ export class CommentService {
|
|||||||
annotations: params.annotations,
|
annotations: params.annotations,
|
||||||
second: params.second,
|
second: params.second,
|
||||||
attachmentIds: params.attachmentIds ?? [],
|
attachmentIds: params.attachmentIds ?? [],
|
||||||
|
isInternal: params.isInternal,
|
||||||
},
|
},
|
||||||
{ triggerAgents: params.triggerAgents },
|
{ triggerAgents: params.triggerAgents },
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ export * from './asset/auto-archive-job'
|
|||||||
export * from './auth/auth'
|
export * from './auth/auth'
|
||||||
export * from './authz/authz'
|
export * from './authz/authz'
|
||||||
export * from './collection/collection'
|
export * from './collection/collection'
|
||||||
|
export * from './comment/comment-frame'
|
||||||
export * from './invite/invite'
|
export * from './invite/invite'
|
||||||
export * from './metadata/metadata'
|
export * from './metadata/metadata'
|
||||||
export * from './notification/index'
|
export * from './notification/index'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { describe, it, expect } from 'vitest'
|
import { describe, it, expect } from 'vitest'
|
||||||
import { prisma } from '@shumai/db'
|
import { prisma } from '@shumai/db'
|
||||||
import { setupTestDbHooks } from '@shumai/db/test'
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
import { KanbanTaskStatus, KanbanTaskPriority, KanbanTaskEventType } from '@shumai/db/enums'
|
||||||
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||||
import { kanbanService } from './kanban'
|
import { kanbanService } from './kanban'
|
||||||
|
|
||||||
@@ -646,7 +646,7 @@ describe('KanbanService', () => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Create attachment
|
// Create attachment
|
||||||
const att = await kanbanService.createAttachment(team.id, {
|
const att = await kanbanService.createAttachment(team.id, editor.id, {
|
||||||
fileName: 'design.png',
|
fileName: 'design.png',
|
||||||
size: 1024,
|
size: 1024,
|
||||||
contentType: 'image/png',
|
contentType: 'image/png',
|
||||||
@@ -688,6 +688,119 @@ describe('KanbanService', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('Comment attachment keys', () => {
|
||||||
|
function payload(key: string) {
|
||||||
|
return [{ id: 'att-1', name: 'file.txt', key, sizeByte: 1, contentType: 'text/plain' }]
|
||||||
|
}
|
||||||
|
|
||||||
|
it('rejects attachment keys that were not issued to the author for the task team', async () => {
|
||||||
|
const { team, editor, reviewer } = await setupTeamAndUsers()
|
||||||
|
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
|
||||||
|
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
|
||||||
|
|
||||||
|
const foreignTeam = await kanbanService.createAttachment(otherTeam.id, editor.id, {
|
||||||
|
fileName: 'other.png',
|
||||||
|
size: 1,
|
||||||
|
})
|
||||||
|
const otherUser = await kanbanService.createAttachment(team.id, reviewer.id, {
|
||||||
|
fileName: 'theirs.png',
|
||||||
|
size: 1,
|
||||||
|
})
|
||||||
|
const own = await kanbanService.createAttachment(team.id, editor.id, {
|
||||||
|
fileName: 'own.png',
|
||||||
|
size: 1,
|
||||||
|
})
|
||||||
|
const ownDir = own.key.slice(0, own.key.lastIndexOf('/'))
|
||||||
|
|
||||||
|
for (const key of [
|
||||||
|
'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||||
|
'avatars/someone.png',
|
||||||
|
'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/old.png',
|
||||||
|
foreignTeam.key,
|
||||||
|
otherUser.key,
|
||||||
|
`${ownDir}/../../../../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov`,
|
||||||
|
`kanban/attachments/${team.id}/${editor.id}/not-a-ulid/own.png`,
|
||||||
|
]) {
|
||||||
|
await expect(
|
||||||
|
kanbanService.addComment(task.id, editor.id, 'see attached', payload(key)),
|
||||||
|
).rejects.toThrow(/Invalid attachment/)
|
||||||
|
}
|
||||||
|
|
||||||
|
const comments = await kanbanService.listComments(task.id)
|
||||||
|
expect(comments).toHaveLength(0)
|
||||||
|
|
||||||
|
const accepted = await kanbanService.addComment(
|
||||||
|
task.id,
|
||||||
|
editor.id,
|
||||||
|
'see attached',
|
||||||
|
payload(own.key),
|
||||||
|
)
|
||||||
|
expect(accepted.attachments.map((a) => a.id)).toEqual(['att-1'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not sign stored attachment keys outside kanban attachments', async () => {
|
||||||
|
const { team, editor } = await setupTeamAndUsers()
|
||||||
|
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
|
||||||
|
const legacyKey = 'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/notes.txt'
|
||||||
|
|
||||||
|
await prisma.kanbanTaskComment.create({
|
||||||
|
data: {
|
||||||
|
taskId: task.id,
|
||||||
|
authorId: editor.id,
|
||||||
|
body: 'stored before validation',
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
id: 'a',
|
||||||
|
name: 'secret',
|
||||||
|
key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||||
|
sizeByte: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'b',
|
||||||
|
name: 'escape',
|
||||||
|
key: 'kanban/attachments/../files/x/master.mov',
|
||||||
|
sizeByte: 1,
|
||||||
|
},
|
||||||
|
{ id: 'c', name: 'notes.txt', key: legacyKey, sizeByte: 1 },
|
||||||
|
{
|
||||||
|
id: 'd',
|
||||||
|
name: 'other-team.txt',
|
||||||
|
key: `kanban/attachments/other-team/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/x.txt`,
|
||||||
|
sizeByte: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'e',
|
||||||
|
name: 'current.txt',
|
||||||
|
key: `kanban/attachments/${team.id}/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/y.txt`,
|
||||||
|
sizeByte: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const [comment] = await kanbanService.listComments(task.id)
|
||||||
|
expect(comment.attachments.map((a) => a.id)).toEqual(['c', 'e'])
|
||||||
|
|
||||||
|
const detail = await kanbanService.getTask(task.id)
|
||||||
|
expect(detail.comments[0].attachments.map((a) => a.id)).toEqual(['c', 'e'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps attachment uploads inside the team attachment folder', async () => {
|
||||||
|
const { team, editor } = await setupTeamAndUsers()
|
||||||
|
|
||||||
|
const att = await kanbanService.createAttachment(team.id, editor.id, {
|
||||||
|
fileName: '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||||
|
size: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
const parts = att.key.split('/')
|
||||||
|
expect(parts.slice(0, 4)).toEqual(['kanban', 'attachments', team.id, editor.id])
|
||||||
|
expect(parts).toHaveLength(6)
|
||||||
|
expect(parts).not.toContain('..')
|
||||||
|
expect(att.name).toBe('../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
// Task Ordering & Fractional Indexing
|
// Task Ordering & Fractional Indexing
|
||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
@@ -1139,4 +1252,185 @@ describe('KanbanService', () => {
|
|||||||
expect(pdfDetail?.thumbnailUrl).toContain('posters/doc_poster.webp')
|
expect(pdfDetail?.thumbnailUrl).toContain('posters/doc_poster.webp')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// --------------------------------------------------------------------------
|
||||||
|
// Project membership
|
||||||
|
// --------------------------------------------------------------------------
|
||||||
|
describe('Project membership', () => {
|
||||||
|
async function setupProjectScopedMember() {
|
||||||
|
const { team, owner, reviewer } = await setupTeamAndUsers()
|
||||||
|
const client = await prisma.user.create({
|
||||||
|
data: { name: 'Client Reviewer', email: 'client@example.com' },
|
||||||
|
})
|
||||||
|
const ownProject = await prisma.project.create({
|
||||||
|
data: { name: 'Client Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
const otherProject = await prisma.project.create({
|
||||||
|
data: { name: 'Internal Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
const clientMember = await prisma.teamMember.create({
|
||||||
|
data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' },
|
||||||
|
})
|
||||||
|
await prisma.projectMember.create({
|
||||||
|
data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const ownTask = await kanbanService.createTask(
|
||||||
|
team.id,
|
||||||
|
{ title: 'Client task', projectId: ownProject.id },
|
||||||
|
owner.id,
|
||||||
|
'owner',
|
||||||
|
)
|
||||||
|
const otherTask = await kanbanService.createTask(
|
||||||
|
team.id,
|
||||||
|
{ title: 'Internal task', projectId: otherProject.id },
|
||||||
|
owner.id,
|
||||||
|
'owner',
|
||||||
|
)
|
||||||
|
const teamTask = await kanbanService.createTask(
|
||||||
|
team.id,
|
||||||
|
{ title: 'Team task' },
|
||||||
|
owner.id,
|
||||||
|
'owner',
|
||||||
|
)
|
||||||
|
const assignedTask = await kanbanService.createTask(
|
||||||
|
team.id,
|
||||||
|
{ title: 'Assigned internal task', projectId: otherProject.id, assigneeId: client.id },
|
||||||
|
owner.id,
|
||||||
|
'owner',
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
team,
|
||||||
|
owner,
|
||||||
|
reviewer,
|
||||||
|
client,
|
||||||
|
otherProject,
|
||||||
|
ownTask,
|
||||||
|
otherTask,
|
||||||
|
teamTask,
|
||||||
|
assignedTask,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
it('lists only tasks in their projects, or that they take part in, for project-scoped members', async () => {
|
||||||
|
const { team, client, otherProject, ownTask, assignedTask } = await setupProjectScopedMember()
|
||||||
|
|
||||||
|
const list = await kanbanService.listTasks(team.id, {}, client.id)
|
||||||
|
expect(list.data.map((t) => t.id).sort()).toEqual([ownTask.id, assignedTask.id].sort())
|
||||||
|
expect(list.pageInfo.total).toBe(2)
|
||||||
|
|
||||||
|
const filtered = await kanbanService.listTasks(
|
||||||
|
team.id,
|
||||||
|
{ projectId: otherProject.id },
|
||||||
|
client.id,
|
||||||
|
)
|
||||||
|
expect(filtered.data.map((t) => t.id)).toEqual([assignedTask.id])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists every team task for team-scoped members', async () => {
|
||||||
|
const { team, reviewer, ownTask, otherTask, teamTask, assignedTask } =
|
||||||
|
await setupProjectScopedMember()
|
||||||
|
|
||||||
|
const list = await kanbanService.listTasks(team.id, {}, reviewer.id)
|
||||||
|
expect(list.data.map((t) => t.id).sort()).toEqual(
|
||||||
|
[ownTask.id, otherTask.id, teamTask.id, assignedTask.id].sort(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows only readable dependencies, dependents, and dependency events', async () => {
|
||||||
|
const { owner, team, client, reviewer, ownTask, otherTask, teamTask, assignedTask } =
|
||||||
|
await setupProjectScopedMember()
|
||||||
|
|
||||||
|
await kanbanService.setDependencies(
|
||||||
|
ownTask.id,
|
||||||
|
[otherTask.id, assignedTask.id, teamTask.id],
|
||||||
|
owner.id,
|
||||||
|
)
|
||||||
|
await kanbanService.setDependencies(ownTask.id, [otherTask.id, assignedTask.id], owner.id)
|
||||||
|
await kanbanService.setDependencies(teamTask.id, [ownTask.id], owner.id)
|
||||||
|
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
|
||||||
|
|
||||||
|
const detail = await kanbanService.getTask(ownTask.id, client.id)
|
||||||
|
expect(detail.dependencies.map((task) => task.id)).toEqual([assignedTask.id])
|
||||||
|
expect(detail.dependents).toEqual([])
|
||||||
|
expect(detail.dependencyCount).toBe(1)
|
||||||
|
expect(detail.dependentCount).toBe(0)
|
||||||
|
|
||||||
|
const events = await kanbanService.listEvents(ownTask.id, client.id)
|
||||||
|
for (const history of [detail.events, events]) {
|
||||||
|
expect(
|
||||||
|
history.filter((event) => event.type === KanbanTaskEventType.DEPENDENCY_ADDED),
|
||||||
|
).toEqual([expect.objectContaining({ data: { parentId: assignedTask.id } })])
|
||||||
|
expect(history).toContainEqual(
|
||||||
|
expect.objectContaining({ type: KanbanTaskEventType.CREATED }),
|
||||||
|
)
|
||||||
|
expect(history).not.toContainEqual(
|
||||||
|
expect.objectContaining({ type: KanbanTaskEventType.DEPENDENCY_REMOVED }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const teamDetail = await kanbanService.getTask(ownTask.id, reviewer.id)
|
||||||
|
expect(teamDetail.dependencies.map((task) => task.id).sort()).toEqual(
|
||||||
|
[otherTask.id, assignedTask.id].sort(),
|
||||||
|
)
|
||||||
|
expect(teamDetail.dependents.map((task) => task.id)).toEqual([teamTask.id])
|
||||||
|
expect(teamDetail.events).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: KanbanTaskEventType.DEPENDENCY_REMOVED,
|
||||||
|
data: { parentId: teamTask.id },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const summary = await kanbanService.listTasks(team.id, {}, client.id)
|
||||||
|
expect(summary.data).toContainEqual(
|
||||||
|
expect.objectContaining({ id: ownTask.id, dependencyCount: 1, dependentCount: 0 }),
|
||||||
|
)
|
||||||
|
|
||||||
|
const updated = await kanbanService.updateTask(
|
||||||
|
assignedTask.id,
|
||||||
|
{ title: 'Updated assigned task' },
|
||||||
|
client.id,
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
expect(updated).toMatchObject({ dependencyCount: 0, dependentCount: 1 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists no tasks for users outside the team', async () => {
|
||||||
|
const { team } = await setupProjectScopedMember()
|
||||||
|
const outsider = await prisma.user.create({
|
||||||
|
data: { name: 'Outsider', email: 'outsider@example.com' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const list = await kanbanService.listTasks(team.id, {}, outsider.id)
|
||||||
|
expect(list.data).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists only readable tasks linked to an asset', async () => {
|
||||||
|
const { team, owner, client, reviewer, otherProject, otherTask, assignedTask } =
|
||||||
|
await setupProjectScopedMember()
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'internal.mp4',
|
||||||
|
type: 'file',
|
||||||
|
status: 'processed',
|
||||||
|
projectId: otherProject.id,
|
||||||
|
creatorId: owner.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await kanbanService.linkAsset(team.id, otherTask.id, asset.id)
|
||||||
|
await kanbanService.linkAsset(team.id, assignedTask.id, asset.id)
|
||||||
|
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
|
||||||
|
|
||||||
|
const forClient = await kanbanService.listTasksForAsset(team.id, asset.id, client.id)
|
||||||
|
expect(forClient.map((t) => t.id)).toEqual([assignedTask.id])
|
||||||
|
expect(forClient[0].dependencyCount).toBe(0)
|
||||||
|
|
||||||
|
const forReviewer = await kanbanService.listTasksForAsset(team.id, asset.id, reviewer.id)
|
||||||
|
expect(forReviewer.map((t) => t.id).sort()).toEqual([otherTask.id, assignedTask.id].sort())
|
||||||
|
expect(forReviewer).toContainEqual(
|
||||||
|
expect.objectContaining({ id: assignedTask.id, dependencyCount: 1 }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { paginateQuery } from '../pagination'
|
|||||||
import { getAvatarUrl } from '../user/avatar'
|
import { getAvatarUrl } from '../user/avatar'
|
||||||
import { s3Service } from '../s3/s3'
|
import { s3Service } from '../s3/s3'
|
||||||
import { getProxyType } from '../utils/mime'
|
import { getProxyType } from '../utils/mime'
|
||||||
|
import { sanitizeFilename } from '../utils/filename'
|
||||||
import { assetService } from '../asset/asset'
|
import { assetService } from '../asset/asset'
|
||||||
import type {
|
import type {
|
||||||
CreateKanbanGoalRequest,
|
CreateKanbanGoalRequest,
|
||||||
@@ -28,6 +29,73 @@ import type {
|
|||||||
} from '@shumai/dtos'
|
} from '@shumai/dtos'
|
||||||
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||||
|
|
||||||
|
type TaskEventWithActor = Prisma.KanbanTaskEventGetPayload<{ include: { actor: true } }>
|
||||||
|
|
||||||
|
function dependencyEventParentId(event: TaskEventWithActor): string | undefined {
|
||||||
|
if (
|
||||||
|
event.type === KanbanTaskEventType.DEPENDENCY_ADDED ||
|
||||||
|
event.type === KanbanTaskEventType.DEPENDENCY_REMOVED
|
||||||
|
) {
|
||||||
|
const parentId = event.data?.parentId
|
||||||
|
if (typeof parentId === 'string') return parentId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function taskRelationCountSelect(
|
||||||
|
taskFilter: Prisma.KanbanTaskWhereInput | undefined,
|
||||||
|
): Prisma.KanbanTaskCountOutputTypeSelect {
|
||||||
|
return {
|
||||||
|
comments: true,
|
||||||
|
assets: true,
|
||||||
|
dependencies: taskFilter ? { where: { parent: taskFilter } } : true,
|
||||||
|
dependents: taskFilter ? { where: { child: taskFilter } } : true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/
|
||||||
|
|
||||||
|
function isSafeKeySegment(segment: string): boolean {
|
||||||
|
// eslint-disable-next-line no-control-regex
|
||||||
|
return segment !== '' && segment !== '.' && segment !== '..' && !/[\\\x00-\x1f\x7f]/.test(segment)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a comment attachment key issued by `createAttachment`:
|
||||||
|
* `kanban/attachments/<teamId>/<uploaderId>/<ulid>/<file name>`.
|
||||||
|
*/
|
||||||
|
function parseAttachmentKey(key: string): { teamId: string; uploaderId: string } | null {
|
||||||
|
const parts = key.split('/')
|
||||||
|
if (
|
||||||
|
parts.length !== 6 ||
|
||||||
|
parts[0] !== 'kanban' ||
|
||||||
|
parts[1] !== 'attachments' ||
|
||||||
|
!isSafeKeySegment(parts[2]) ||
|
||||||
|
!isSafeKeySegment(parts[3]) ||
|
||||||
|
!ULID_PATTERN.test(parts[4]) ||
|
||||||
|
!isSafeKeySegment(parts[5])
|
||||||
|
) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return { teamId: parts[2], uploaderId: parts[3] }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keys of comment attachments stored before keys carried the team and uploader. */
|
||||||
|
function isLegacyAttachmentKey(key: string): boolean {
|
||||||
|
const parts = key.split('/')
|
||||||
|
return (
|
||||||
|
parts.length === 4 &&
|
||||||
|
parts[0] === 'kanban' &&
|
||||||
|
parts[1] === 'attachments' &&
|
||||||
|
ULID_PATTERN.test(parts[2]) &&
|
||||||
|
isSafeKeySegment(parts[3])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a stored attachment key may be signed for a comment on a task in `teamId`. */
|
||||||
|
function isReadableAttachmentKey(key: string, teamId: string): boolean {
|
||||||
|
return parseAttachmentKey(key)?.teamId === teamId || isLegacyAttachmentKey(key)
|
||||||
|
}
|
||||||
|
|
||||||
export class KanbanService {
|
export class KanbanService {
|
||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
// Goal CRUD
|
// Goal CRUD
|
||||||
@@ -314,7 +382,7 @@ export class KanbanService {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTask(taskId: string): Promise<KanbanTaskDetail> {
|
async getTask(taskId: string, viewerId?: string): Promise<KanbanTaskDetail> {
|
||||||
const task = await prisma.kanbanTask.findUnique({
|
const task = await prisma.kanbanTask.findUnique({
|
||||||
where: { id: taskId },
|
where: { id: taskId },
|
||||||
include: {
|
include: {
|
||||||
@@ -354,27 +422,38 @@ export class KanbanService {
|
|||||||
throw new HTTPException(404, { message: 'Task not found' })
|
throw new HTTPException(404, { message: 'Task not found' })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const readableIds = await this.readableRelatedTaskIds(task.teamId, viewerId, [
|
||||||
|
...task.dependencies.map((link) => link.parentId),
|
||||||
|
...task.dependents.map((link) => link.childId),
|
||||||
|
...task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
|
||||||
|
])
|
||||||
|
const dependencies = task.dependencies.filter(
|
||||||
|
(link) => !readableIds || readableIds.has(link.parentId),
|
||||||
|
)
|
||||||
|
const dependents = task.dependents.filter(
|
||||||
|
(link) => !readableIds || readableIds.has(link.childId),
|
||||||
|
)
|
||||||
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, task.status)
|
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, task.status)
|
||||||
const resolvedAssets = await this.resolveTaskAssetInfos(task.assets)
|
const resolvedAssets = await this.resolveTaskAssetInfos(task.assets)
|
||||||
|
|
||||||
const baseInfo = await this.toTaskInfo(task, {
|
const baseInfo = await this.toTaskInfo(task, {
|
||||||
latestStatusEvent,
|
latestStatusEvent,
|
||||||
dependencyCount: task.dependencies.length,
|
dependencyCount: dependencies.length,
|
||||||
dependentCount: task.dependents.length,
|
dependentCount: dependents.length,
|
||||||
commentCount: task.comments.length,
|
commentCount: task.comments.length,
|
||||||
assetCount: task.assets.length,
|
assetCount: task.assets.length,
|
||||||
})
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...baseInfo,
|
...baseInfo,
|
||||||
dependencies: task.dependencies.map((d) => ({
|
dependencies: dependencies.map((d) => ({
|
||||||
id: d.parent.id,
|
id: d.parent.id,
|
||||||
title: d.parent.title,
|
title: d.parent.title,
|
||||||
isAgentTask: d.parent.isAgentTask,
|
isAgentTask: d.parent.isAgentTask,
|
||||||
status: d.parent.status,
|
status: d.parent.status,
|
||||||
priority: d.parent.priority,
|
priority: d.parent.priority,
|
||||||
})),
|
})),
|
||||||
dependents: task.dependents.map((d) => ({
|
dependents: dependents.map((d) => ({
|
||||||
id: d.child.id,
|
id: d.child.id,
|
||||||
title: d.child.title,
|
title: d.child.title,
|
||||||
isAgentTask: d.child.isAgentTask,
|
isAgentTask: d.child.isAgentTask,
|
||||||
@@ -392,29 +471,12 @@ export class KanbanService {
|
|||||||
image: await getAvatarUrl(c.author.image),
|
image: await getAvatarUrl(c.author.image),
|
||||||
},
|
},
|
||||||
body: c.body,
|
body: c.body,
|
||||||
attachments: await this.resolveCommentAttachments(c.attachments),
|
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
|
||||||
createdAt: c.createdAt.toISOString(),
|
createdAt: c.createdAt.toISOString(),
|
||||||
updatedAt: c.updatedAt.toISOString(),
|
updatedAt: c.updatedAt.toISOString(),
|
||||||
})),
|
})),
|
||||||
),
|
),
|
||||||
events: await Promise.all(
|
events: await this.resolveTaskEvents(task.events, readableIds),
|
||||||
task.events.map(async (e) => ({
|
|
||||||
id: e.id,
|
|
||||||
taskId: e.taskId,
|
|
||||||
actor: e.actor
|
|
||||||
? {
|
|
||||||
id: e.actor.id,
|
|
||||||
name: e.actor.name,
|
|
||||||
image: await getAvatarUrl(e.actor.image),
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
type: e.type,
|
|
||||||
fromStatus: e.fromStatus,
|
|
||||||
toStatus: e.toStatus,
|
|
||||||
data: (e.data as Record<string, unknown>) ?? null,
|
|
||||||
createdAt: e.createdAt.toISOString(),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -659,7 +721,8 @@ export class KanbanService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, updated.status)
|
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, updated.status)
|
||||||
const counts = await this.getTaskCounts(taskId)
|
const taskFilter = await this.readableTaskFilter(updated.teamId, actorId)
|
||||||
|
const counts = await this.getTaskCounts(taskId, taskFilter)
|
||||||
|
|
||||||
return await this.toTaskInfo(updated, {
|
return await this.toTaskInfo(updated, {
|
||||||
latestStatusEvent,
|
latestStatusEvent,
|
||||||
@@ -704,10 +767,54 @@ export class KanbanService {
|
|||||||
return taskInfo
|
return taskInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Limits kanban tasks to those a user may read. Team-scoped members see every
|
||||||
|
* task in the team; project-scoped members see tasks in the projects they
|
||||||
|
* belong to and tasks they created, report, or are assigned to.
|
||||||
|
*/
|
||||||
|
private async readableTaskFilter(
|
||||||
|
teamId: string,
|
||||||
|
userId: string | undefined,
|
||||||
|
): Promise<Prisma.KanbanTaskWhereInput | undefined> {
|
||||||
|
if (!userId) return
|
||||||
|
const member = await prisma.teamMember.findUnique({
|
||||||
|
where: { teamIdUserId: { teamId, userId } },
|
||||||
|
})
|
||||||
|
if (!member) return { id: { in: [] } }
|
||||||
|
if (member.scope === 'team') return
|
||||||
|
return {
|
||||||
|
teamId,
|
||||||
|
OR: [
|
||||||
|
{ project: { members: { some: { teamMemberId: member.id } } } },
|
||||||
|
{ creatorId: userId },
|
||||||
|
{ reporterId: userId },
|
||||||
|
{ assigneeId: userId },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async readableRelatedTaskIds(
|
||||||
|
teamId: string,
|
||||||
|
viewerId: string | undefined,
|
||||||
|
relatedIds: string[],
|
||||||
|
): Promise<Set<string> | undefined> {
|
||||||
|
if (relatedIds.length === 0) return
|
||||||
|
const filter = await this.readableTaskFilter(teamId, viewerId)
|
||||||
|
if (!filter) return
|
||||||
|
|
||||||
|
const tasks = await prisma.kanbanTask.findMany({
|
||||||
|
where: { id: { in: [...new Set(relatedIds)] }, AND: [filter] },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
return new Set(tasks.map((task) => task.id))
|
||||||
|
}
|
||||||
|
|
||||||
async listTasks(
|
async listTasks(
|
||||||
teamId: string,
|
teamId: string,
|
||||||
params: ListKanbanTasksRequest,
|
params: ListKanbanTasksRequest,
|
||||||
|
viewerId?: string,
|
||||||
): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> {
|
): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> {
|
||||||
|
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
|
||||||
const where: Prisma.KanbanTaskWhereInput = {
|
const where: Prisma.KanbanTaskWhereInput = {
|
||||||
teamId,
|
teamId,
|
||||||
...(params.status && { status: params.status }),
|
...(params.status && { status: params.status }),
|
||||||
@@ -721,6 +828,7 @@ export class KanbanService {
|
|||||||
...(params.priority && { priority: params.priority }),
|
...(params.priority && { priority: params.priority }),
|
||||||
...(params.assigneeId && { assigneeId: params.assigneeId }),
|
...(params.assigneeId && { assigneeId: params.assigneeId }),
|
||||||
...(params.reporterId && { reporterId: params.reporterId }),
|
...(params.reporterId && { reporterId: params.reporterId }),
|
||||||
|
...(taskFilter && { AND: [taskFilter] }),
|
||||||
}
|
}
|
||||||
|
|
||||||
return await paginateQuery(
|
return await paginateQuery(
|
||||||
@@ -732,14 +840,7 @@ export class KanbanService {
|
|||||||
reporter: true,
|
reporter: true,
|
||||||
assignee: true,
|
assignee: true,
|
||||||
goal: true,
|
goal: true,
|
||||||
_count: {
|
_count: { select: taskRelationCountSelect(taskFilter) },
|
||||||
select: {
|
|
||||||
comments: true,
|
|
||||||
dependencies: true,
|
|
||||||
dependents: true,
|
|
||||||
assets: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }],
|
orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }],
|
||||||
skip,
|
skip,
|
||||||
@@ -869,9 +970,10 @@ export class KanbanService {
|
|||||||
|
|
||||||
async createAttachment(
|
async createAttachment(
|
||||||
teamId: string,
|
teamId: string,
|
||||||
|
uploaderId: string,
|
||||||
req: { fileName: string; size: number; contentType?: string },
|
req: { fileName: string; size: number; contentType?: string },
|
||||||
): Promise<PostKanbanAttachmentResponse> {
|
): Promise<PostKanbanAttachmentResponse> {
|
||||||
const key = `kanban/attachments/${ulid()}/${req.fileName}`
|
const key = `kanban/attachments/${teamId}/${uploaderId}/${ulid()}/${sanitizeFilename(req.fileName)}`
|
||||||
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
||||||
const proxyType = getProxyType(req.contentType, req.fileName)
|
const proxyType = getProxyType(req.contentType, req.fileName)
|
||||||
|
|
||||||
@@ -895,6 +997,16 @@ export class KanbanService {
|
|||||||
const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } })
|
const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } })
|
||||||
if (!task) throw new HTTPException(404, { message: 'Task not found' })
|
if (!task) throw new HTTPException(404, { message: 'Task not found' })
|
||||||
|
|
||||||
|
// Attachments are uploaded through createAttachment. Only keys it issued to the
|
||||||
|
// comment author for this task's team may be stored and signed later.
|
||||||
|
const isOwnUpload = (key: string) => {
|
||||||
|
const parsed = parseAttachmentKey(key)
|
||||||
|
return parsed?.teamId === task.teamId && parsed.uploaderId === authorId
|
||||||
|
}
|
||||||
|
if (attachments?.some((att) => !isOwnUpload(att.key))) {
|
||||||
|
throw new HTTPException(400, { message: 'Invalid attachment' })
|
||||||
|
}
|
||||||
|
|
||||||
const comment = await prisma.$transaction(async (tx) => {
|
const comment = await prisma.$transaction(async (tx) => {
|
||||||
const c = await tx.kanbanTaskComment.create({
|
const c = await tx.kanbanTaskComment.create({
|
||||||
data: {
|
data: {
|
||||||
@@ -917,7 +1029,10 @@ export class KanbanService {
|
|||||||
return c
|
return c
|
||||||
})
|
})
|
||||||
|
|
||||||
const resolvedAttachments = await this.resolveCommentAttachments(comment.attachments)
|
const resolvedAttachments = await this.resolveCommentAttachments(
|
||||||
|
comment.attachments,
|
||||||
|
task.teamId,
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: comment.id,
|
id: comment.id,
|
||||||
@@ -935,6 +1050,12 @@ export class KanbanService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async listComments(taskId: string): Promise<KanbanCommentInfo[]> {
|
async listComments(taskId: string): Promise<KanbanCommentInfo[]> {
|
||||||
|
const task = await prisma.kanbanTask.findUnique({
|
||||||
|
where: { id: taskId },
|
||||||
|
select: { teamId: true },
|
||||||
|
})
|
||||||
|
if (!task) throw new HTTPException(404, { message: 'Task not found' })
|
||||||
|
|
||||||
const comments = await prisma.kanbanTaskComment.findMany({
|
const comments = await prisma.kanbanTaskComment.findMany({
|
||||||
where: { taskId },
|
where: { taskId },
|
||||||
include: { author: true },
|
include: { author: true },
|
||||||
@@ -951,7 +1072,7 @@ export class KanbanService {
|
|||||||
image: await getAvatarUrl(c.author.image),
|
image: await getAvatarUrl(c.author.image),
|
||||||
},
|
},
|
||||||
body: c.body,
|
body: c.body,
|
||||||
attachments: await this.resolveCommentAttachments(c.attachments),
|
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
|
||||||
createdAt: c.createdAt.toISOString(),
|
createdAt: c.createdAt.toISOString(),
|
||||||
updatedAt: c.updatedAt.toISOString(),
|
updatedAt: c.updatedAt.toISOString(),
|
||||||
})),
|
})),
|
||||||
@@ -981,7 +1102,8 @@ export class KanbanService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async resolveCommentAttachments(
|
private async resolveCommentAttachments(
|
||||||
attachments?: PrismaJson.KanbanCommentAttachmentList | null,
|
attachments: PrismaJson.KanbanCommentAttachmentList | null | undefined,
|
||||||
|
teamId: string,
|
||||||
): Promise<KanbanAttachmentInfo[]> {
|
): Promise<KanbanAttachmentInfo[]> {
|
||||||
if (!attachments || !Array.isArray(attachments) || attachments.length === 0) {
|
if (!attachments || !Array.isArray(attachments) || attachments.length === 0) {
|
||||||
return []
|
return []
|
||||||
@@ -989,29 +1111,50 @@ export class KanbanService {
|
|||||||
|
|
||||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||||
return await Promise.all(
|
return await Promise.all(
|
||||||
attachments.map(async (att) => {
|
attachments
|
||||||
const url = await s3Service.presign(bucket, att.key, 'GET')
|
.filter((att) => typeof att.key === 'string' && isReadableAttachmentKey(att.key, teamId))
|
||||||
return {
|
.map(async (att) => {
|
||||||
id: att.id,
|
const url = await s3Service.presign(bucket, att.key, 'GET')
|
||||||
name: att.name,
|
return {
|
||||||
sizeByte: att.sizeByte,
|
id: att.id,
|
||||||
contentType: att.contentType,
|
name: att.name,
|
||||||
url,
|
sizeByte: att.sizeByte,
|
||||||
proxyType: att.proxyType,
|
contentType: att.contentType,
|
||||||
}
|
url,
|
||||||
}),
|
proxyType: att.proxyType,
|
||||||
|
}
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async listEvents(taskId: string): Promise<KanbanEventInfo[]> {
|
async listEvents(taskId: string, viewerId?: string): Promise<KanbanEventInfo[]> {
|
||||||
const events = await prisma.kanbanTaskEvent.findMany({
|
const task = await prisma.kanbanTask.findUnique({
|
||||||
where: { taskId },
|
where: { id: taskId },
|
||||||
include: { actor: true },
|
select: {
|
||||||
orderBy: { createdAt: 'desc' },
|
teamId: true,
|
||||||
|
events: { include: { actor: true }, orderBy: { createdAt: 'desc' } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (!task) return []
|
||||||
|
const readableIds = await this.readableRelatedTaskIds(
|
||||||
|
task.teamId,
|
||||||
|
viewerId,
|
||||||
|
task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
|
||||||
|
)
|
||||||
|
return await this.resolveTaskEvents(task.events, readableIds)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveTaskEvents(
|
||||||
|
events: TaskEventWithActor[],
|
||||||
|
readableIds: Set<string> | undefined,
|
||||||
|
): Promise<KanbanEventInfo[]> {
|
||||||
|
const visibleEvents = events.filter((event) => {
|
||||||
|
const parentId = dependencyEventParentId(event)
|
||||||
|
return !readableIds || parentId === undefined || readableIds.has(parentId)
|
||||||
})
|
})
|
||||||
|
|
||||||
return await Promise.all(
|
return await Promise.all(
|
||||||
events.map(async (e) => ({
|
visibleEvents.map(async (e) => ({
|
||||||
id: e.id,
|
id: e.id,
|
||||||
taskId: e.taskId,
|
taskId: e.taskId,
|
||||||
actor: e.actor
|
actor: e.actor
|
||||||
@@ -1024,7 +1167,7 @@ export class KanbanService {
|
|||||||
type: e.type,
|
type: e.type,
|
||||||
fromStatus: e.fromStatus,
|
fromStatus: e.fromStatus,
|
||||||
toStatus: e.toStatus,
|
toStatus: e.toStatus,
|
||||||
data: (e.data as Record<string, unknown>) ?? null,
|
data: e.data ?? null,
|
||||||
createdAt: e.createdAt.toISOString(),
|
createdAt: e.createdAt.toISOString(),
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
@@ -1115,9 +1258,17 @@ export class KanbanService {
|
|||||||
return await this.resolveTaskAssetInfos(links)
|
return await this.resolveTaskAssetInfos(links)
|
||||||
}
|
}
|
||||||
|
|
||||||
async listTasksForAsset(teamId: string, assetId: string): Promise<KanbanTaskInfo[]> {
|
async listTasksForAsset(
|
||||||
|
teamId: string,
|
||||||
|
assetId: string,
|
||||||
|
viewerId?: string,
|
||||||
|
): Promise<KanbanTaskInfo[]> {
|
||||||
|
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
|
||||||
const links = await prisma.kanbanTaskAsset.findMany({
|
const links = await prisma.kanbanTaskAsset.findMany({
|
||||||
where: { assetId },
|
where: {
|
||||||
|
assetId,
|
||||||
|
task: { teamId, ...taskFilter },
|
||||||
|
},
|
||||||
include: {
|
include: {
|
||||||
task: {
|
task: {
|
||||||
include: {
|
include: {
|
||||||
@@ -1125,24 +1276,15 @@ export class KanbanService {
|
|||||||
reporter: true,
|
reporter: true,
|
||||||
assignee: true,
|
assignee: true,
|
||||||
goal: true,
|
goal: true,
|
||||||
_count: {
|
_count: { select: taskRelationCountSelect(taskFilter) },
|
||||||
select: {
|
|
||||||
comments: true,
|
|
||||||
dependencies: true,
|
|
||||||
dependents: true,
|
|
||||||
assets: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
})
|
})
|
||||||
|
|
||||||
const matchingLinks = links.filter((l) => l.task && l.task.teamId === teamId)
|
|
||||||
|
|
||||||
return await Promise.all(
|
return await Promise.all(
|
||||||
matchingLinks.map(async (l) => {
|
links.map(async (l) => {
|
||||||
const t = l.task
|
const t = l.task
|
||||||
const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status)
|
const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status)
|
||||||
return await this.toTaskInfo(t, {
|
return await this.toTaskInfo(t, {
|
||||||
@@ -1195,19 +1337,25 @@ export class KanbanService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getTaskCounts(taskId: string): Promise<{
|
private async getTaskCounts(
|
||||||
|
taskId: string,
|
||||||
|
taskFilter?: Prisma.KanbanTaskWhereInput,
|
||||||
|
): Promise<{
|
||||||
commentCount: number
|
commentCount: number
|
||||||
dependencyCount: number
|
dependencyCount: number
|
||||||
dependentCount: number
|
dependentCount: number
|
||||||
assetCount: number
|
assetCount: number
|
||||||
}> {
|
}> {
|
||||||
const [commentCount, dependencyCount, dependentCount, assetCount] = await Promise.all([
|
const task = await prisma.kanbanTask.findUnique({
|
||||||
prisma.kanbanTaskComment.count({ where: { taskId } }),
|
where: { id: taskId },
|
||||||
prisma.kanbanTaskLink.count({ where: { childId: taskId } }),
|
select: { _count: { select: taskRelationCountSelect(taskFilter) } },
|
||||||
prisma.kanbanTaskLink.count({ where: { parentId: taskId } }),
|
})
|
||||||
prisma.kanbanTaskAsset.count({ where: { taskId } }),
|
return {
|
||||||
])
|
commentCount: task?._count.comments ?? 0,
|
||||||
return { commentCount, dependencyCount, dependentCount, assetCount }
|
dependencyCount: task?._count.dependencies ?? 0,
|
||||||
|
dependentCount: task?._count.dependents ?? 0,
|
||||||
|
assetCount: task?._count.assets ?? 0,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resolveTaskAssetInfos(
|
private async resolveTaskAssetInfos(
|
||||||
|
|||||||
@@ -240,7 +240,12 @@ describe('collaboration Operations', () => {
|
|||||||
message: 'Too dark at the start',
|
message: 'Too dark at the start',
|
||||||
second: 2.5,
|
second: 2.5,
|
||||||
})
|
})
|
||||||
expect(comment).toEqual({ id: expect.any(String), assetId: file, replyToId: null })
|
expect(comment).toEqual({
|
||||||
|
id: expect.any(String),
|
||||||
|
assetId: file,
|
||||||
|
replyToId: null,
|
||||||
|
isInternal: false,
|
||||||
|
})
|
||||||
|
|
||||||
const reply = await runOperation(createCommentOp, as(owner, 'agent', undefined), {
|
const reply = await runOperation(createCommentOp, as(owner, 'agent', undefined), {
|
||||||
assetId: file,
|
assetId: file,
|
||||||
@@ -248,9 +253,17 @@ describe('collaboration Operations', () => {
|
|||||||
replyToId: comment.id,
|
replyToId: comment.id,
|
||||||
})
|
})
|
||||||
expect(reply.replyToId).toBe(comment.id)
|
expect(reply.replyToId).toBe(comment.id)
|
||||||
|
expect(reply.isInternal).toBe(false)
|
||||||
|
|
||||||
|
const internalComment = await runOperation(createCommentOp, as(reviewer), {
|
||||||
|
assetId: file,
|
||||||
|
message: 'Internal budget note',
|
||||||
|
isInternal: true,
|
||||||
|
})
|
||||||
|
expect(internalComment.isInternal).toBe(true)
|
||||||
|
|
||||||
const listed = await runOperation(listCommentsOp, as(reviewer), { assetId: file })
|
const listed = await runOperation(listCommentsOp, as(reviewer), { assetId: file })
|
||||||
expect(listed.total).toBe(1)
|
expect(listed.total).toBe(2)
|
||||||
expect(listed.data).toEqual([
|
expect(listed.data).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
id: comment.id,
|
id: comment.id,
|
||||||
@@ -258,14 +271,21 @@ describe('collaboration Operations', () => {
|
|||||||
author: { id: reviewer.id, name: 'Reviewer' },
|
author: { id: reviewer.id, name: 'Reviewer' },
|
||||||
second: 2.5,
|
second: 2.5,
|
||||||
resolved: false,
|
resolved: false,
|
||||||
|
isInternal: false,
|
||||||
replies: [
|
replies: [
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
id: reply.id,
|
id: reply.id,
|
||||||
message: 'Brightened in v2',
|
message: 'Brightened in v2',
|
||||||
author: { id: owner.id, name: 'Owner' },
|
author: { id: owner.id, name: 'Owner' },
|
||||||
|
isInternal: false,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
id: internalComment.id,
|
||||||
|
message: 'Internal budget note',
|
||||||
|
isInternal: true,
|
||||||
|
}),
|
||||||
])
|
])
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
@@ -276,7 +296,7 @@ describe('collaboration Operations', () => {
|
|||||||
).resolves.toEqual({ commentId: comment.id, resolved: false })
|
).resolves.toEqual({ commentId: comment.id, resolved: false })
|
||||||
|
|
||||||
const created = await auditRows(AuditAction.comment_create)
|
const created = await auditRows(AuditAction.comment_create)
|
||||||
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id])
|
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id, internalComment.id])
|
||||||
expect(created.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
|
expect(created.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
|
||||||
const completed = await auditRows(AuditAction.comment_complete)
|
const completed = await auditRows(AuditAction.comment_complete)
|
||||||
expect(completed).toHaveLength(2)
|
expect(completed).toHaveLength(2)
|
||||||
|
|||||||
@@ -20,10 +20,16 @@ export const createCommentOp = implementOperation(createComment, {
|
|||||||
message: input.message,
|
message: input.message,
|
||||||
replyToId: input.replyToId,
|
replyToId: input.replyToId,
|
||||||
second: input.second,
|
second: input.second,
|
||||||
|
isInternal: input.isInternal,
|
||||||
// Mentions in comments written by Shumai's own agent must not start more agent runs.
|
// Mentions in comments written by Shumai's own agent must not start more agent runs.
|
||||||
triggerAgents: ctx.via !== 'agent',
|
triggerAgents: ctx.via !== 'agent',
|
||||||
})
|
})
|
||||||
return { id: comment.id, assetId: comment.assetId, replyToId: input.replyToId ?? null }
|
return {
|
||||||
|
id: comment.id,
|
||||||
|
assetId: comment.assetId,
|
||||||
|
replyToId: input.replyToId ?? null,
|
||||||
|
isInternal: comment.isInternal,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
audit: (input, output) => [
|
audit: (input, output) => [
|
||||||
{ action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId },
|
{ action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId },
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ function toCommentFields(comment: CommentInfo) {
|
|||||||
second: comment.second,
|
second: comment.second,
|
||||||
hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0,
|
hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0,
|
||||||
attachmentCount: comment.attachments.length,
|
attachmentCount: comment.attachments.length,
|
||||||
|
isInternal: comment.isInternal,
|
||||||
createdAt: comment.createdAt,
|
createdAt: comment.createdAt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -752,6 +752,18 @@ describe('S3Service implementations', () => {
|
|||||||
expect(size).toBe(11)
|
expect(size).toBe(11)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('rejects keys with parent directory segments', async () => {
|
||||||
|
await localS3.putObject('test-bucket', 'files/a/master.mov', 'original', 8)
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
localS3.putObject('test-bucket', 'attachments/x/../../files/a/master.mov', 'evil', 4),
|
||||||
|
).rejects.toThrow(/path traversal/)
|
||||||
|
await expect(
|
||||||
|
localS3.getObjectSize('test-bucket', 'attachments/x/..\\..\\files/a/master.mov'),
|
||||||
|
).rejects.toThrow(/path traversal/)
|
||||||
|
expect(await localS3.getObjectSize('test-bucket', 'files/a/master.mov')).toBe(8)
|
||||||
|
})
|
||||||
|
|
||||||
it('removes empty embedding chunk directories after deleting the last chunk', async () => {
|
it('removes empty embedding chunk directories after deleting the last chunk', async () => {
|
||||||
const key = 'files/asset-1/tmp-embedding-chunks/chunk.mp4'
|
const key = 'files/asset-1/tmp-embedding-chunks/chunk.mp4'
|
||||||
await localS3.putObject('test-bucket', key, 'chunk', 5)
|
await localS3.putObject('test-bucket', key, 'chunk', 5)
|
||||||
|
|||||||
@@ -850,6 +850,11 @@ export class LocalStorageService implements S3Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private getFilePath(bucket: string, key: string): string {
|
private getFilePath(bucket: string, key: string): string {
|
||||||
|
// Object keys are flat names: a `..` segment must not be resolved into another
|
||||||
|
// object's path (S3 keeps it literally).
|
||||||
|
if (key.split(/[\\/]/).includes('..') || bucket.split(/[\\/]/).includes('..')) {
|
||||||
|
throw new Error(`Invalid path: potential path traversal detected`)
|
||||||
|
}
|
||||||
const filePath = path.join(this.basePath, bucket, key)
|
const filePath = path.join(this.basePath, bucket, key)
|
||||||
if (!filePath.startsWith(this.basePath)) {
|
if (!filePath.startsWith(this.basePath)) {
|
||||||
throw new Error(`Invalid path: potential path traversal detected`)
|
throw new Error(`Invalid path: potential path traversal detected`)
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { beforeEach, describe, expect, it } from 'vitest'
|
||||||
|
import { prisma } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
import { shareActivityService } from './share-activity'
|
||||||
|
import { shareService } from './share'
|
||||||
|
|
||||||
|
describe('Share activity', () => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let shareId: string
|
||||||
|
let projectId: string
|
||||||
|
let assetId: string
|
||||||
|
let userId: string
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const user = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
name: 'Reviewer',
|
||||||
|
email: 'reviewer@example.com',
|
||||||
|
image: 'https://example.com/avatar',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const team = await prisma.team.create({ data: { name: 'Team' } })
|
||||||
|
const project = await prisma.project.create({ data: { name: 'Project', teamId: team.id } })
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: { name: 'Review Cut', projectId: project.id, type: 'file', status: 'processed' },
|
||||||
|
})
|
||||||
|
const share = await shareService.createShareLink(project.id, { name: 'Review' }, user.id)
|
||||||
|
shareId = share.id
|
||||||
|
projectId = project.id
|
||||||
|
assetId = asset.id
|
||||||
|
userId = user.id
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sets the last view and counts every visit, including a duplicate deep-link visit', async () => {
|
||||||
|
expect(await shareService.getShareLink(shareId)).toMatchObject({ views: 0, lastViewedAt: null })
|
||||||
|
await shareActivityService.recordView(shareId, { assetId, isShareEntry: true })
|
||||||
|
const first = await prisma.shareLink.findUniqueOrThrow({ where: { id: shareId } })
|
||||||
|
expect(first).toMatchObject({ views: 1, lastViewedAt: expect.any(Date) })
|
||||||
|
|
||||||
|
const prior = new Date('2020-01-01T00:00:00Z')
|
||||||
|
await prisma.shareLink.update({ where: { id: shareId }, data: { lastViewedAt: prior } })
|
||||||
|
await shareActivityService.recordView(shareId, { assetId, isShareEntry: true })
|
||||||
|
|
||||||
|
const share = await prisma.shareLink.findUniqueOrThrow({ where: { id: shareId } })
|
||||||
|
expect(share.views).toBe(2)
|
||||||
|
expect(share.lastViewedAt!.getTime()).toBeGreaterThan(prior.getTime())
|
||||||
|
expect(await prisma.shareActivity.findMany({ where: { shareLinkId: shareId } })).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({ kind: 'share_viewed', userId: null, assetId: null }),
|
||||||
|
expect.objectContaining({ kind: 'asset_viewed', userId: null, assetId }),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses a rolling window from the last recorded event and permits a match after 30 minutes', async () => {
|
||||||
|
const event = { kind: 'asset_downloaded', userId, assetId } as const
|
||||||
|
const record = await prisma.shareActivity.create({
|
||||||
|
data: {
|
||||||
|
...event,
|
||||||
|
shareLinkId: shareId,
|
||||||
|
createdAt: new Date(Date.now() - 29 * 60_000),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await shareActivityService.recordEvent(shareId, event)
|
||||||
|
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(1)
|
||||||
|
expect(await prisma.shareActivity.findUnique({ where: { id: record.id } })).toEqual(record)
|
||||||
|
|
||||||
|
await prisma.shareActivity.update({
|
||||||
|
where: { id: record.id },
|
||||||
|
data: { createdAt: new Date(Date.now() - 30 * 60_000) },
|
||||||
|
})
|
||||||
|
await shareActivityService.recordEvent(shareId, event)
|
||||||
|
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('scopes the deduplication identity to the share, event kind, user and asset', async () => {
|
||||||
|
const otherShare = await shareService.createShareLink(projectId, { name: 'Other' })
|
||||||
|
const otherAsset = await prisma.asset.create({
|
||||||
|
data: { name: 'Other Cut', projectId, type: 'file', status: 'processed' },
|
||||||
|
})
|
||||||
|
await shareActivityService.recordView(shareId, { assetId })
|
||||||
|
await shareActivityService.recordView(shareId, { assetId, userId })
|
||||||
|
await shareActivityService.recordView(shareId, { assetId: otherAsset.id, userId })
|
||||||
|
await shareActivityService.recordView(otherShare.id, { assetId, userId })
|
||||||
|
await shareActivityService.recordEvent(shareId, { kind: 'asset_downloaded', assetId, userId })
|
||||||
|
|
||||||
|
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(4)
|
||||||
|
expect(await prisma.shareActivity.count({ where: { shareLinkId: otherShare.id } })).toBe(1)
|
||||||
|
expect(await shareService.getShareLink(shareId)).toMatchObject({ views: 3 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('records a share comment in its transaction while preserving every comment', async () => {
|
||||||
|
const comment = { assetId, userId, message: 'Looks good', attachmentIds: [] }
|
||||||
|
await assetService.createComment(comment, { shareLinkId: shareId })
|
||||||
|
await assetService.createComment({ ...comment, message: 'Ready' }, { shareLinkId: shareId })
|
||||||
|
await assetService.createComment({ ...comment, message: 'Workspace comment' })
|
||||||
|
expect(await prisma.assetComment.count({ where: { assetId } })).toBe(3)
|
||||||
|
const events = await prisma.shareActivity.findMany({ where: { shareLinkId: shareId } })
|
||||||
|
expect(events).toMatchObject([{ kind: 'comment_created', assetId, userId }])
|
||||||
|
|
||||||
|
await expect(assetService.createComment(comment, { shareLinkId: 'missing' })).rejects.toThrow(
|
||||||
|
'Share link not found',
|
||||||
|
)
|
||||||
|
expect(await prisma.assetComment.count({ where: { assetId } })).toBe(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('paginates the feed and resolves current names and missing assets', async () => {
|
||||||
|
await shareActivityService.recordView(shareId, { assetId, userId, isShareEntry: true })
|
||||||
|
await prisma.asset.update({ where: { id: assetId }, data: { name: 'Renamed Cut' } })
|
||||||
|
const first = await shareActivityService.list(shareId, { first: 1 })
|
||||||
|
expect(first.pageInfo).toMatchObject({ total: 2, cursor: expect.any(String) })
|
||||||
|
const second = await shareActivityService.list(shareId, {
|
||||||
|
first: 1,
|
||||||
|
after: first.pageInfo.cursor,
|
||||||
|
})
|
||||||
|
expect(first.data).toHaveLength(1)
|
||||||
|
expect(second.data).toHaveLength(1)
|
||||||
|
expect(first.data[0].id > second.data[0].id).toBe(true)
|
||||||
|
expect([...first.data, ...second.data]).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
kind: 'asset_viewed',
|
||||||
|
user: { name: 'Reviewer', image: 'https://example.com/avatar' },
|
||||||
|
asset: { id: assetId, name: 'Renamed Cut' },
|
||||||
|
}),
|
||||||
|
expect.objectContaining({ kind: 'share_viewed', asset: null }),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
|
||||||
|
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
|
||||||
|
const getAssetEvent = async () =>
|
||||||
|
(await shareActivityService.list(shareId, {})).data.find(
|
||||||
|
(event) => event.kind === 'asset_viewed',
|
||||||
|
)
|
||||||
|
expect((await getAssetEvent())?.asset).toEqual({ id: assetId, name: null })
|
||||||
|
await prisma.asset.delete({ where: { id: assetId } })
|
||||||
|
expect((await getAssetEvent())?.asset).toEqual({ id: assetId, name: null })
|
||||||
|
await shareService.deleteShareLink(shareId)
|
||||||
|
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('checks that a share root is accessible before accepting a root view', async () => {
|
||||||
|
const share = await shareService.getShareLink(shareId)
|
||||||
|
await expect(shareService.verifyPublicAccess(shareId, undefined)).resolves.toMatchObject({
|
||||||
|
id: shareId,
|
||||||
|
})
|
||||||
|
await prisma.asset.update({
|
||||||
|
where: { id: share.rootFolderId },
|
||||||
|
data: { isDeleted: true },
|
||||||
|
})
|
||||||
|
await expect(shareService.verifyPublicAccess(shareId, undefined)).rejects.toThrow(
|
||||||
|
'Asset is not shared',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { prisma, type Prisma } from '@shumai/db'
|
||||||
|
import type { ShareActivityInfo, ShareActivityKind } from '@shumai/dtos'
|
||||||
|
import { paginateQuery, type PaginationParams } from '@shumai/core/src/pagination'
|
||||||
|
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||||
|
import { ShareLinkNotFoundError } from './errors'
|
||||||
|
|
||||||
|
const deduplicationWindowMs = 30 * 60 * 1000
|
||||||
|
|
||||||
|
type Activity = {
|
||||||
|
kind: ShareActivityKind
|
||||||
|
userId?: string
|
||||||
|
assetId?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
class ShareActivityService {
|
||||||
|
async recordView(
|
||||||
|
shareLinkId: string,
|
||||||
|
view: { userId?: string; assetId?: string; isShareEntry?: boolean },
|
||||||
|
): Promise<void> {
|
||||||
|
const events: Activity[] = []
|
||||||
|
if (!view.assetId || view.isShareEntry) {
|
||||||
|
events.push({ kind: 'share_viewed', userId: view.userId })
|
||||||
|
}
|
||||||
|
if (view.assetId) {
|
||||||
|
events.push({ kind: 'asset_viewed', userId: view.userId, assetId: view.assetId })
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
const now = await this.lockShare(tx, shareLinkId)
|
||||||
|
// A visit updates the counters independently of whether its events are duplicates.
|
||||||
|
await tx.$executeRaw`
|
||||||
|
UPDATE share_links
|
||||||
|
SET views = views + 1,
|
||||||
|
last_viewed_at = GREATEST(last_viewed_at, ${now.toISOString()}::timestamptz AT TIME ZONE 'UTC')
|
||||||
|
WHERE id = ${shareLinkId}
|
||||||
|
`
|
||||||
|
for (const event of events) {
|
||||||
|
await this.insertIfNew(tx, shareLinkId, event, now)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async recordEvent(
|
||||||
|
shareLinkId: string,
|
||||||
|
event: Activity,
|
||||||
|
tx?: Prisma.TransactionClient,
|
||||||
|
): Promise<void> {
|
||||||
|
if (!tx) {
|
||||||
|
await prisma.$transaction((client) => this.recordEvent(shareLinkId, event, client))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = await this.lockShare(tx, shareLinkId)
|
||||||
|
await this.insertIfNew(tx, shareLinkId, event, now)
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(shareLinkId: string, params: PaginationParams) {
|
||||||
|
const where = { shareLinkId }
|
||||||
|
const page = await paginateQuery(
|
||||||
|
(skip, take) => prisma.shareActivity.findMany({ where, orderBy: { id: 'desc' }, skip, take }),
|
||||||
|
() => prisma.shareActivity.count({ where }),
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
const userIds = page.data.flatMap(({ userId }) => (userId ? [userId] : []))
|
||||||
|
const assetIds = page.data.flatMap(({ assetId }) => (assetId ? [assetId] : []))
|
||||||
|
const [users, assets] = await Promise.all([
|
||||||
|
prisma.user.findMany({
|
||||||
|
where: { id: { in: userIds } },
|
||||||
|
select: { id: true, name: true, image: true },
|
||||||
|
}),
|
||||||
|
prisma.asset.findMany({
|
||||||
|
where: { id: { in: assetIds }, isDeleted: false },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
const usersById = new Map(
|
||||||
|
await Promise.all(
|
||||||
|
users.map(
|
||||||
|
async ({ id, name, image }) => [id, { name, image: await getAvatarUrl(image) }] as const,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
const namesById = new Map(assets.map(({ id, name }) => [id, name]))
|
||||||
|
const data: ShareActivityInfo[] = page.data.map((event) => ({
|
||||||
|
id: event.id,
|
||||||
|
kind: event.kind,
|
||||||
|
createdAt: event.createdAt.toISOString(),
|
||||||
|
user: event.userId ? (usersById.get(event.userId) ?? null) : null,
|
||||||
|
asset: event.assetId
|
||||||
|
? { id: event.assetId, name: namesById.get(event.assetId) ?? null }
|
||||||
|
: null,
|
||||||
|
}))
|
||||||
|
return { data, pageInfo: page.pageInfo }
|
||||||
|
}
|
||||||
|
|
||||||
|
private async lockShare(tx: Prisma.TransactionClient, shareLinkId: string) {
|
||||||
|
const rows = await tx.$queryRaw<{ id: string }[]>`
|
||||||
|
SELECT id FROM share_links WHERE id = ${shareLinkId} FOR UPDATE
|
||||||
|
`
|
||||||
|
if (rows.length === 0) throw new ShareLinkNotFoundError('Share link not found')
|
||||||
|
// Read time after acquiring the lock so a queued request uses its actual write time.
|
||||||
|
const [clock] = await tx.$queryRaw<{ now: Date }[]>`SELECT clock_timestamp() AS now`
|
||||||
|
return clock.now
|
||||||
|
}
|
||||||
|
|
||||||
|
private async insertIfNew(
|
||||||
|
tx: Prisma.TransactionClient,
|
||||||
|
shareLinkId: string,
|
||||||
|
event: Activity,
|
||||||
|
now: Date,
|
||||||
|
) {
|
||||||
|
const identity = {
|
||||||
|
shareLinkId,
|
||||||
|
kind: event.kind,
|
||||||
|
userId: event.userId ?? null,
|
||||||
|
assetId: event.assetId ?? null,
|
||||||
|
}
|
||||||
|
const recent = await tx.shareActivity.findFirst({
|
||||||
|
where: {
|
||||||
|
...identity,
|
||||||
|
createdAt: { gt: new Date(now.getTime() - deduplicationWindowMs) },
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
if (!recent) await tx.shareActivity.create({ data: { ...identity, createdAt: now } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const shareActivityService = new ShareActivityService()
|
||||||
@@ -6,6 +6,12 @@ import { assetService } from '@shumai/core/src/asset/asset'
|
|||||||
import { projectService } from '@shumai/core/src/project/project'
|
import { projectService } from '@shumai/core/src/project/project'
|
||||||
import { AssetType } from '@shumai/db'
|
import { AssetType } from '@shumai/db'
|
||||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { timingSafeEqual } from 'node:crypto'
|
||||||
|
|
||||||
|
vi.mock('node:crypto', async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import('node:crypto')>()
|
||||||
|
return { ...actual, timingSafeEqual: vi.fn(actual.timingSafeEqual) }
|
||||||
|
})
|
||||||
|
|
||||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||||
s3Service: {
|
s3Service: {
|
||||||
@@ -167,6 +173,69 @@ describe('ShareService', () => {
|
|||||||
).rejects.toThrow('expired')
|
).rejects.toThrow('expired')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('includes the saved password in share link settings', async () => {
|
||||||
|
const created = await shareService.createShareLink(projectId, {
|
||||||
|
name: 'Protected Share',
|
||||||
|
password: 'secret-password',
|
||||||
|
})
|
||||||
|
expect(created.hasPassword).toBe(true)
|
||||||
|
expect(created.password).toBe('secret-password')
|
||||||
|
|
||||||
|
const fetched = await shareService.getShareLink(created.id)
|
||||||
|
expect(fetched.hasPassword).toBe(true)
|
||||||
|
expect(fetched.password).toBe('secret-password')
|
||||||
|
|
||||||
|
const updated = await shareService.updateShareLink(created.id, { password: 'other' })
|
||||||
|
expect(updated.hasPassword).toBe(true)
|
||||||
|
expect(updated.password).toBe('other')
|
||||||
|
|
||||||
|
const list = await shareService.listProjectShareLinks({ projectId })
|
||||||
|
expect(list.data).toContainEqual(expect.objectContaining({ id: created.id, password: 'other' }))
|
||||||
|
|
||||||
|
const cleared = await shareService.updateShareLink(created.id, { password: null })
|
||||||
|
expect(cleared.hasPassword).toBe(false)
|
||||||
|
expect(cleared.password).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects missing or different-length share passwords', async () => {
|
||||||
|
const shareLink = await shareService.createShareLink(projectId, {
|
||||||
|
name: 'Protected Share',
|
||||||
|
password: 'secret-password',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId),
|
||||||
|
).rejects.toThrow('Invalid password')
|
||||||
|
await expect(
|
||||||
|
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, ''),
|
||||||
|
).rejects.toThrow('Invalid password')
|
||||||
|
await expect(
|
||||||
|
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'secret'),
|
||||||
|
).rejects.toThrow('Invalid password')
|
||||||
|
await expect(
|
||||||
|
shareService.verifyPublicAccess(
|
||||||
|
shareLink.id,
|
||||||
|
shareLink.rootFolderId,
|
||||||
|
'secret-password-and-more',
|
||||||
|
),
|
||||||
|
).rejects.toThrow('Invalid password')
|
||||||
|
await expect(
|
||||||
|
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'secret-password'),
|
||||||
|
).resolves.toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('compares share passwords in constant time', async () => {
|
||||||
|
const shareLink = await shareService.createShareLink(projectId, {
|
||||||
|
name: 'Protected Share',
|
||||||
|
password: 'secret-password',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'wrong'),
|
||||||
|
).rejects.toThrow('Invalid password')
|
||||||
|
expect(timingSafeEqual).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
it('traces deep ancestors for public access', async () => {
|
it('traces deep ancestors for public access', async () => {
|
||||||
const shareLink = await shareService.createShareLink(projectId, {
|
const shareLink = await shareService.createShareLink(projectId, {
|
||||||
name: 'Deep Share',
|
name: 'Deep Share',
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||||
import { prisma } from '@shumai/db'
|
import { prisma } from '@shumai/db'
|
||||||
import { AssetType, Prisma } from '@shumai/db'
|
import { AssetType, Prisma } from '@shumai/db'
|
||||||
import {
|
import {
|
||||||
@@ -18,6 +19,17 @@ import {
|
|||||||
ShareLinkPasswordInvalidError,
|
ShareLinkPasswordInvalidError,
|
||||||
} from './errors'
|
} from './errors'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compares a provided share password with the stored one in constant time.
|
||||||
|
* Both values are hashed first so the comparison does not depend on their lengths.
|
||||||
|
*/
|
||||||
|
function sharePasswordMatches(stored: string, provided: string | undefined): boolean {
|
||||||
|
if (provided === undefined) return false
|
||||||
|
const a = createHash('sha256').update(stored).digest()
|
||||||
|
const b = createHash('sha256').update(provided).digest()
|
||||||
|
return timingSafeEqual(a, b)
|
||||||
|
}
|
||||||
|
|
||||||
export class ShareService {
|
export class ShareService {
|
||||||
async createShareLink(
|
async createShareLink(
|
||||||
projectId: string,
|
projectId: string,
|
||||||
@@ -250,7 +262,7 @@ export class ShareService {
|
|||||||
|
|
||||||
async verifyPublicAccess(
|
async verifyPublicAccess(
|
||||||
shareLinkId: string,
|
shareLinkId: string,
|
||||||
assetId: string,
|
assetId: string | undefined,
|
||||||
providedPassword?: string,
|
providedPassword?: string,
|
||||||
): Promise<Prisma.ShareLinkGetPayload<true>> {
|
): Promise<Prisma.ShareLinkGetPayload<true>> {
|
||||||
const shareLink = await prisma.shareLink.findUnique({
|
const shareLink = await prisma.shareLink.findUnique({
|
||||||
@@ -269,15 +281,17 @@ export class ShareService {
|
|||||||
throw new ShareLinkExpiredError('Share link has expired')
|
throw new ShareLinkExpiredError('Share link has expired')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shareLink.password && shareLink.password !== providedPassword) {
|
if (shareLink.password && !sharePasswordMatches(shareLink.password, providedPassword)) {
|
||||||
throw new ShareLinkPasswordInvalidError('Invalid password for share link')
|
throw new ShareLinkPasswordInvalidError('Invalid password for share link')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const targetId = assetId ?? shareLink.rootFolderId
|
||||||
|
|
||||||
const rows = await prisma.$queryRaw<{ id: string }[]>`
|
const rows = await prisma.$queryRaw<{ id: string }[]>`
|
||||||
WITH RECURSIVE
|
WITH RECURSIVE
|
||||||
-- Trace ancestors in the real asset tree
|
-- Trace ancestors in the real asset tree
|
||||||
real_ancestors AS (
|
real_ancestors AS (
|
||||||
SELECT id, parent_id, type::text, target_id FROM assets WHERE id = ${assetId} AND is_deleted = false
|
SELECT id, parent_id, type::text, target_id FROM assets WHERE id = ${targetId} AND is_deleted = false
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT a.id, a.parent_id, a.type::text, a.target_id FROM assets a
|
SELECT a.id, a.parent_id, a.type::text, a.target_id FROM assets a
|
||||||
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
||||||
@@ -339,6 +353,8 @@ export class ShareService {
|
|||||||
rootFolderId: l.rootFolderId,
|
rootFolderId: l.rootFolderId,
|
||||||
projectId: l.projectId,
|
projectId: l.projectId,
|
||||||
isExpired,
|
isExpired,
|
||||||
|
views: l.views,
|
||||||
|
lastViewedAt: l.lastViewedAt?.toISOString() ?? null,
|
||||||
watermarkConfigId: l.watermarkConfigId,
|
watermarkConfigId: l.watermarkConfigId,
|
||||||
watermarkStatus: l.watermarkStatus || 'disabled',
|
watermarkStatus: l.watermarkStatus || 'disabled',
|
||||||
watermarkConfig: watermarkConfig
|
watermarkConfig: watermarkConfig
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "ShareActivityKind" AS ENUM ('share_viewed', 'asset_viewed', 'asset_downloaded', 'comment_created');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "share_links" ADD COLUMN "last_viewed_at" TIMESTAMP(3),
|
||||||
|
ADD COLUMN "views" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "share_activities" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"share_link_id" TEXT NOT NULL,
|
||||||
|
"kind" "ShareActivityKind" NOT NULL,
|
||||||
|
"user_id" TEXT,
|
||||||
|
"asset_id" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "share_activities_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "share_activities_dedup_idx" ON "share_activities"("share_link_id", "kind", "user_id", "asset_id", "created_at" DESC);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "share_activities_share_link_id_id_idx" ON "share_activities"("share_link_id", "id" DESC);
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "share_activities" ADD CONSTRAINT "share_activities_share_link_id_fkey" FOREIGN KEY ("share_link_id") REFERENCES "share_links"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "asset_comments" ADD COLUMN "is_internal" BOOLEAN NOT NULL DEFAULT false;
|
||||||
@@ -479,6 +479,8 @@ model ShareLink {
|
|||||||
viewMode String? @map("view_mode")
|
viewMode String? @map("view_mode")
|
||||||
/// [ShareLinkFieldVisibility]
|
/// [ShareLinkFieldVisibility]
|
||||||
fieldVisibility Json? @map("field_visibility")
|
fieldVisibility Json? @map("field_visibility")
|
||||||
|
views Int @default(0)
|
||||||
|
lastViewedAt DateTime? @map("last_viewed_at")
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
@@ -495,9 +497,33 @@ model ShareLink {
|
|||||||
watermarkStatus WatermarkStatus @default(disabled) @map("watermark_status")
|
watermarkStatus WatermarkStatus @default(disabled) @map("watermark_status")
|
||||||
watermarkConfig WatermarkConfig? @relation(fields: [watermarkConfigId], references: [id], onDelete: SetNull)
|
watermarkConfig WatermarkConfig? @relation(fields: [watermarkConfigId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
activities ShareActivity[]
|
||||||
|
|
||||||
@@map("share_links")
|
@@map("share_links")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum ShareActivityKind {
|
||||||
|
share_viewed
|
||||||
|
asset_viewed
|
||||||
|
asset_downloaded
|
||||||
|
comment_created
|
||||||
|
}
|
||||||
|
|
||||||
|
model ShareActivity {
|
||||||
|
id String @id @default(ulid())
|
||||||
|
shareLinkId String @map("share_link_id")
|
||||||
|
shareLink ShareLink @relation(fields: [shareLinkId], references: [id], onDelete: Cascade)
|
||||||
|
kind ShareActivityKind
|
||||||
|
// Historical references retained when the user or asset is deleted.
|
||||||
|
userId String? @map("user_id")
|
||||||
|
assetId String? @map("asset_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
@@index([shareLinkId, kind, userId, assetId, createdAt(sort: Desc)], map: "share_activities_dedup_idx")
|
||||||
|
@@index([shareLinkId, id(sort: Desc)])
|
||||||
|
@@map("share_activities")
|
||||||
|
}
|
||||||
|
|
||||||
model WatermarkConfig {
|
model WatermarkConfig {
|
||||||
id String @id @default(ulid())
|
id String @id @default(ulid())
|
||||||
/// [WatermarkConfigSpec]
|
/// [WatermarkConfigSpec]
|
||||||
@@ -683,6 +709,7 @@ model AssetComment {
|
|||||||
creator User? @relation("UserToAssetComment", fields: [creatorId], references: [id])
|
creator User? @relation("UserToAssetComment", fields: [creatorId], references: [id])
|
||||||
|
|
||||||
isCompleted Boolean @default(false) @map("is_completed")
|
isCompleted Boolean @default(false) @map("is_completed")
|
||||||
|
isInternal Boolean @default(false) @map("is_internal")
|
||||||
completionLastChangedById String? @map("completion_last_changed_by_id")
|
completionLastChangedById String? @map("completion_last_changed_by_id")
|
||||||
completionLastChangedBy User? @relation("UserToAssetCommentCompletionChanged", fields: [completionLastChangedById], references: [id])
|
completionLastChangedBy User? @relation("UserToAssetCommentCompletionChanged", fields: [completionLastChangedById], references: [id])
|
||||||
|
|
||||||
|
|||||||
+5
@@ -77,6 +77,11 @@ export type ProjectMember = Prisma.ProjectMemberModel
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
export type ShareLink = Prisma.ShareLinkModel
|
export type ShareLink = Prisma.ShareLinkModel
|
||||||
|
/**
|
||||||
|
* Model ShareActivity
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export type ShareActivity = Prisma.ShareActivityModel
|
||||||
/**
|
/**
|
||||||
* Model WatermarkConfig
|
* Model WatermarkConfig
|
||||||
*
|
*
|
||||||
|
|||||||
+5
@@ -101,6 +101,11 @@ export type ProjectMember = Prisma.ProjectMemberModel
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
export type ShareLink = Prisma.ShareLinkModel
|
export type ShareLink = Prisma.ShareLinkModel
|
||||||
|
/**
|
||||||
|
* Model ShareActivity
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export type ShareActivity = Prisma.ShareActivityModel
|
||||||
/**
|
/**
|
||||||
* Model WatermarkConfig
|
* Model WatermarkConfig
|
||||||
*
|
*
|
||||||
|
|||||||
+88
-54
@@ -267,6 +267,17 @@ export type EnumProjectMemberRoleWithAggregatesFilter<$PrismaModel = never> = {
|
|||||||
_max?: Prisma.NestedEnumProjectMemberRoleFilter<$PrismaModel>
|
_max?: Prisma.NestedEnumProjectMemberRoleFilter<$PrismaModel>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type IntFilter<$PrismaModel = never> = {
|
||||||
|
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||||
|
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedIntFilter<$PrismaModel> | number
|
||||||
|
}
|
||||||
|
|
||||||
export type EnumWatermarkStatusFilter<$PrismaModel = never> = {
|
export type EnumWatermarkStatusFilter<$PrismaModel = never> = {
|
||||||
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||||
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||||
@@ -274,6 +285,22 @@ export type EnumWatermarkStatusFilter<$PrismaModel = never> = {
|
|||||||
not?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel> | $Enums.WatermarkStatus
|
not?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel> | $Enums.WatermarkStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type IntWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||||
|
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
||||||
|
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
export type EnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
export type EnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||||
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||||
@@ -284,6 +311,23 @@ export type EnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
|||||||
_max?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel>
|
_max?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type EnumShareActivityKindFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnumShareActivityKindWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumShareActivityKindWithAggregatesFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
export type JsonFilter<$PrismaModel = never> =
|
export type JsonFilter<$PrismaModel = never> =
|
||||||
| Prisma.PatchUndefined<
|
| Prisma.PatchUndefined<
|
||||||
Prisma.Either<Required<JsonFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonFilterBase<$PrismaModel>>, 'path'>>,
|
Prisma.Either<Required<JsonFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonFilterBase<$PrismaModel>>, 'path'>>,
|
||||||
@@ -359,17 +403,6 @@ export type EnumAssetTypeFilter<$PrismaModel = never> = {
|
|||||||
not?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel> | $Enums.AssetType
|
not?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel> | $Enums.AssetType
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntFilter<$PrismaModel = never> = {
|
|
||||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
|
||||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
|
||||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
not?: Prisma.NestedIntFilter<$PrismaModel> | number
|
|
||||||
}
|
|
||||||
|
|
||||||
export type BigIntFilter<$PrismaModel = never> = {
|
export type BigIntFilter<$PrismaModel = never> = {
|
||||||
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
||||||
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
||||||
@@ -398,22 +431,6 @@ export type EnumAssetTypeWithAggregatesFilter<$PrismaModel = never> = {
|
|||||||
_max?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel>
|
_max?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel>
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntWithAggregatesFilter<$PrismaModel = never> = {
|
|
||||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
|
||||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
|
||||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
|
||||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
|
||||||
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type BigIntWithAggregatesFilter<$PrismaModel = never> = {
|
export type BigIntWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
||||||
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
||||||
@@ -1147,6 +1164,33 @@ export type NestedEnumWatermarkStatusFilter<$PrismaModel = never> = {
|
|||||||
not?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel> | $Enums.WatermarkStatus
|
not?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel> | $Enums.WatermarkStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type NestedIntWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||||
|
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
||||||
|
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedFloatFilter<$PrismaModel = never> = {
|
||||||
|
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||||
|
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
||||||
|
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||||
|
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||||
|
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||||
|
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedFloatFilter<$PrismaModel> | number
|
||||||
|
}
|
||||||
|
|
||||||
export type NestedEnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
export type NestedEnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||||
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||||
@@ -1157,6 +1201,23 @@ export type NestedEnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never>
|
|||||||
_max?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel>
|
_max?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type NestedEnumShareActivityKindFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedEnumShareActivityKindWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumShareActivityKindWithAggregatesFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
export type NestedJsonFilter<$PrismaModel = never> =
|
export type NestedJsonFilter<$PrismaModel = never> =
|
||||||
| Prisma.PatchUndefined<
|
| Prisma.PatchUndefined<
|
||||||
Prisma.Either<Required<NestedJsonFilterBase<$PrismaModel>>, Exclude<keyof Required<NestedJsonFilterBase<$PrismaModel>>, 'path'>>,
|
Prisma.Either<Required<NestedJsonFilterBase<$PrismaModel>>, Exclude<keyof Required<NestedJsonFilterBase<$PrismaModel>>, 'path'>>,
|
||||||
@@ -1233,33 +1294,6 @@ export type NestedEnumAssetTypeWithAggregatesFilter<$PrismaModel = never> = {
|
|||||||
_max?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel>
|
_max?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel>
|
||||||
}
|
}
|
||||||
|
|
||||||
export type NestedIntWithAggregatesFilter<$PrismaModel = never> = {
|
|
||||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
|
||||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
|
||||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
|
||||||
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
|
||||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
|
||||||
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type NestedFloatFilter<$PrismaModel = never> = {
|
|
||||||
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
|
||||||
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
|
||||||
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
|
||||||
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
|
||||||
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
|
||||||
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
|
||||||
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
|
||||||
not?: Prisma.NestedFloatFilter<$PrismaModel> | number
|
|
||||||
}
|
|
||||||
|
|
||||||
export type NestedBigIntWithAggregatesFilter<$PrismaModel = never> = {
|
export type NestedBigIntWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
||||||
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
||||||
|
|||||||
+10
@@ -268,6 +268,16 @@ export const KanbanTaskEventType = {
|
|||||||
export type KanbanTaskEventType = (typeof KanbanTaskEventType)[keyof typeof KanbanTaskEventType]
|
export type KanbanTaskEventType = (typeof KanbanTaskEventType)[keyof typeof KanbanTaskEventType]
|
||||||
|
|
||||||
|
|
||||||
|
export const ShareActivityKind = {
|
||||||
|
share_viewed: 'share_viewed',
|
||||||
|
asset_viewed: 'asset_viewed',
|
||||||
|
asset_downloaded: 'asset_downloaded',
|
||||||
|
comment_created: 'comment_created'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type ShareActivityKind = (typeof ShareActivityKind)[keyof typeof ShareActivityKind]
|
||||||
|
|
||||||
|
|
||||||
export const AgentType = {
|
export const AgentType = {
|
||||||
chat: 'chat',
|
chat: 'chat',
|
||||||
autofill: 'autofill',
|
autofill: 'autofill',
|
||||||
|
|||||||
+14
-4
File diff suppressed because one or more lines are too long
+120
-15
@@ -409,6 +409,7 @@ export const ModelName = {
|
|||||||
Project: 'Project',
|
Project: 'Project',
|
||||||
ProjectMember: 'ProjectMember',
|
ProjectMember: 'ProjectMember',
|
||||||
ShareLink: 'ShareLink',
|
ShareLink: 'ShareLink',
|
||||||
|
ShareActivity: 'ShareActivity',
|
||||||
WatermarkConfig: 'WatermarkConfig',
|
WatermarkConfig: 'WatermarkConfig',
|
||||||
WatermarkTemplate: 'WatermarkTemplate',
|
WatermarkTemplate: 'WatermarkTemplate',
|
||||||
WatermarkFile: 'WatermarkFile',
|
WatermarkFile: 'WatermarkFile',
|
||||||
@@ -473,7 +474,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
|||||||
omit: GlobalOmitOptions
|
omit: GlobalOmitOptions
|
||||||
}
|
}
|
||||||
meta: {
|
meta: {
|
||||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
|
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "shareActivity" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
|
||||||
txIsolationLevel: TransactionIsolationLevel
|
txIsolationLevel: TransactionIsolationLevel
|
||||||
}
|
}
|
||||||
model: {
|
model: {
|
||||||
@@ -1365,6 +1366,80 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ShareActivity: {
|
||||||
|
payload: Prisma.$ShareActivityPayload<ExtArgs>
|
||||||
|
fields: Prisma.ShareActivityFieldRefs
|
||||||
|
operations: {
|
||||||
|
findUnique: {
|
||||||
|
args: Prisma.ShareActivityFindUniqueArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload> | null
|
||||||
|
}
|
||||||
|
findUniqueOrThrow: {
|
||||||
|
args: Prisma.ShareActivityFindUniqueOrThrowArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||||
|
}
|
||||||
|
findFirst: {
|
||||||
|
args: Prisma.ShareActivityFindFirstArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload> | null
|
||||||
|
}
|
||||||
|
findFirstOrThrow: {
|
||||||
|
args: Prisma.ShareActivityFindFirstOrThrowArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||||
|
}
|
||||||
|
findMany: {
|
||||||
|
args: Prisma.ShareActivityFindManyArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>[]
|
||||||
|
}
|
||||||
|
create: {
|
||||||
|
args: Prisma.ShareActivityCreateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||||
|
}
|
||||||
|
createMany: {
|
||||||
|
args: Prisma.ShareActivityCreateManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
createManyAndReturn: {
|
||||||
|
args: Prisma.ShareActivityCreateManyAndReturnArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>[]
|
||||||
|
}
|
||||||
|
delete: {
|
||||||
|
args: Prisma.ShareActivityDeleteArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||||
|
}
|
||||||
|
update: {
|
||||||
|
args: Prisma.ShareActivityUpdateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||||
|
}
|
||||||
|
deleteMany: {
|
||||||
|
args: Prisma.ShareActivityDeleteManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
updateMany: {
|
||||||
|
args: Prisma.ShareActivityUpdateManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
updateManyAndReturn: {
|
||||||
|
args: Prisma.ShareActivityUpdateManyAndReturnArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>[]
|
||||||
|
}
|
||||||
|
upsert: {
|
||||||
|
args: Prisma.ShareActivityUpsertArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||||
|
}
|
||||||
|
aggregate: {
|
||||||
|
args: Prisma.ShareActivityAggregateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.AggregateShareActivity>
|
||||||
|
}
|
||||||
|
groupBy: {
|
||||||
|
args: Prisma.ShareActivityGroupByArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.ShareActivityGroupByOutputType>[]
|
||||||
|
}
|
||||||
|
count: {
|
||||||
|
args: Prisma.ShareActivityCountArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.ShareActivityCountAggregateOutputType> | number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
WatermarkConfig: {
|
WatermarkConfig: {
|
||||||
payload: Prisma.$WatermarkConfigPayload<ExtArgs>
|
payload: Prisma.$WatermarkConfigPayload<ExtArgs>
|
||||||
fields: Prisma.WatermarkConfigFieldRefs
|
fields: Prisma.WatermarkConfigFieldRefs
|
||||||
@@ -5198,6 +5273,8 @@ export const ShareLinkScalarFieldEnum = {
|
|||||||
defaultSortOrder: 'defaultSortOrder',
|
defaultSortOrder: 'defaultSortOrder',
|
||||||
viewMode: 'viewMode',
|
viewMode: 'viewMode',
|
||||||
fieldVisibility: 'fieldVisibility',
|
fieldVisibility: 'fieldVisibility',
|
||||||
|
views: 'views',
|
||||||
|
lastViewedAt: 'lastViewedAt',
|
||||||
createdAt: 'createdAt',
|
createdAt: 'createdAt',
|
||||||
updatedAt: 'updatedAt',
|
updatedAt: 'updatedAt',
|
||||||
projectId: 'projectId',
|
projectId: 'projectId',
|
||||||
@@ -5210,6 +5287,18 @@ export const ShareLinkScalarFieldEnum = {
|
|||||||
export type ShareLinkScalarFieldEnum = (typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
|
export type ShareLinkScalarFieldEnum = (typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
|
export const ShareActivityScalarFieldEnum = {
|
||||||
|
id: 'id',
|
||||||
|
shareLinkId: 'shareLinkId',
|
||||||
|
kind: 'kind',
|
||||||
|
userId: 'userId',
|
||||||
|
assetId: 'assetId',
|
||||||
|
createdAt: 'createdAt'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type ShareActivityScalarFieldEnum = (typeof ShareActivityScalarFieldEnum)[keyof typeof ShareActivityScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
export const WatermarkConfigScalarFieldEnum = {
|
export const WatermarkConfigScalarFieldEnum = {
|
||||||
id: 'id',
|
id: 'id',
|
||||||
config: 'config',
|
config: 'config',
|
||||||
@@ -5323,6 +5412,7 @@ export const AssetCommentScalarFieldEnum = {
|
|||||||
assetId: 'assetId',
|
assetId: 'assetId',
|
||||||
creatorId: 'creatorId',
|
creatorId: 'creatorId',
|
||||||
isCompleted: 'isCompleted',
|
isCompleted: 'isCompleted',
|
||||||
|
isInternal: 'isInternal',
|
||||||
completionLastChangedById: 'completionLastChangedById',
|
completionLastChangedById: 'completionLastChangedById',
|
||||||
replyToId: 'replyToId'
|
replyToId: 'replyToId'
|
||||||
} as const
|
} as const
|
||||||
@@ -6119,6 +6209,20 @@ export type ListEnumProjectMemberRoleFieldRefInput<$PrismaModel> = FieldRefInput
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'Int'
|
||||||
|
*/
|
||||||
|
export type IntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'Int[]'
|
||||||
|
*/
|
||||||
|
export type ListIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int[]'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reference to a field of type 'WatermarkStatus'
|
* Reference to a field of type 'WatermarkStatus'
|
||||||
*/
|
*/
|
||||||
@@ -6133,6 +6237,20 @@ export type ListEnumWatermarkStatusFieldRefInput<$PrismaModel> = FieldRefInputTy
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'ShareActivityKind'
|
||||||
|
*/
|
||||||
|
export type EnumShareActivityKindFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ShareActivityKind'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'ShareActivityKind[]'
|
||||||
|
*/
|
||||||
|
export type ListEnumShareActivityKindFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ShareActivityKind[]'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reference to a field of type 'WatermarkFileStatus'
|
* Reference to a field of type 'WatermarkFileStatus'
|
||||||
*/
|
*/
|
||||||
@@ -6161,20 +6279,6 @@ export type ListEnumAssetTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$Pr
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reference to a field of type 'Int'
|
|
||||||
*/
|
|
||||||
export type IntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int'>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reference to a field of type 'Int[]'
|
|
||||||
*/
|
|
||||||
export type ListIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int[]'>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reference to a field of type 'BigInt'
|
* Reference to a field of type 'BigInt'
|
||||||
*/
|
*/
|
||||||
@@ -6631,6 +6735,7 @@ export type GlobalOmitConfig = {
|
|||||||
project?: Prisma.ProjectOmit
|
project?: Prisma.ProjectOmit
|
||||||
projectMember?: Prisma.ProjectMemberOmit
|
projectMember?: Prisma.ProjectMemberOmit
|
||||||
shareLink?: Prisma.ShareLinkOmit
|
shareLink?: Prisma.ShareLinkOmit
|
||||||
|
shareActivity?: Prisma.ShareActivityOmit
|
||||||
watermarkConfig?: Prisma.WatermarkConfigOmit
|
watermarkConfig?: Prisma.WatermarkConfigOmit
|
||||||
watermarkTemplate?: Prisma.WatermarkTemplateOmit
|
watermarkTemplate?: Prisma.WatermarkTemplateOmit
|
||||||
watermarkFile?: Prisma.WatermarkFileOmit
|
watermarkFile?: Prisma.WatermarkFileOmit
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ export const ModelName = {
|
|||||||
Project: 'Project',
|
Project: 'Project',
|
||||||
ProjectMember: 'ProjectMember',
|
ProjectMember: 'ProjectMember',
|
||||||
ShareLink: 'ShareLink',
|
ShareLink: 'ShareLink',
|
||||||
|
ShareActivity: 'ShareActivity',
|
||||||
WatermarkConfig: 'WatermarkConfig',
|
WatermarkConfig: 'WatermarkConfig',
|
||||||
WatermarkTemplate: 'WatermarkTemplate',
|
WatermarkTemplate: 'WatermarkTemplate',
|
||||||
WatermarkFile: 'WatermarkFile',
|
WatermarkFile: 'WatermarkFile',
|
||||||
@@ -298,6 +299,8 @@ export const ShareLinkScalarFieldEnum = {
|
|||||||
defaultSortOrder: 'defaultSortOrder',
|
defaultSortOrder: 'defaultSortOrder',
|
||||||
viewMode: 'viewMode',
|
viewMode: 'viewMode',
|
||||||
fieldVisibility: 'fieldVisibility',
|
fieldVisibility: 'fieldVisibility',
|
||||||
|
views: 'views',
|
||||||
|
lastViewedAt: 'lastViewedAt',
|
||||||
createdAt: 'createdAt',
|
createdAt: 'createdAt',
|
||||||
updatedAt: 'updatedAt',
|
updatedAt: 'updatedAt',
|
||||||
projectId: 'projectId',
|
projectId: 'projectId',
|
||||||
@@ -310,6 +313,18 @@ export const ShareLinkScalarFieldEnum = {
|
|||||||
export type ShareLinkScalarFieldEnum = (typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
|
export type ShareLinkScalarFieldEnum = (typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
|
export const ShareActivityScalarFieldEnum = {
|
||||||
|
id: 'id',
|
||||||
|
shareLinkId: 'shareLinkId',
|
||||||
|
kind: 'kind',
|
||||||
|
userId: 'userId',
|
||||||
|
assetId: 'assetId',
|
||||||
|
createdAt: 'createdAt'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type ShareActivityScalarFieldEnum = (typeof ShareActivityScalarFieldEnum)[keyof typeof ShareActivityScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
export const WatermarkConfigScalarFieldEnum = {
|
export const WatermarkConfigScalarFieldEnum = {
|
||||||
id: 'id',
|
id: 'id',
|
||||||
config: 'config',
|
config: 'config',
|
||||||
@@ -423,6 +438,7 @@ export const AssetCommentScalarFieldEnum = {
|
|||||||
assetId: 'assetId',
|
assetId: 'assetId',
|
||||||
creatorId: 'creatorId',
|
creatorId: 'creatorId',
|
||||||
isCompleted: 'isCompleted',
|
isCompleted: 'isCompleted',
|
||||||
|
isInternal: 'isInternal',
|
||||||
completionLastChangedById: 'completionLastChangedById',
|
completionLastChangedById: 'completionLastChangedById',
|
||||||
replyToId: 'replyToId'
|
replyToId: 'replyToId'
|
||||||
} as const
|
} as const
|
||||||
|
|||||||
+1
@@ -20,6 +20,7 @@ export type * from './models/TeamMember.ts'
|
|||||||
export type * from './models/Project.ts'
|
export type * from './models/Project.ts'
|
||||||
export type * from './models/ProjectMember.ts'
|
export type * from './models/ProjectMember.ts'
|
||||||
export type * from './models/ShareLink.ts'
|
export type * from './models/ShareLink.ts'
|
||||||
|
export type * from './models/ShareActivity.ts'
|
||||||
export type * from './models/WatermarkConfig.ts'
|
export type * from './models/WatermarkConfig.ts'
|
||||||
export type * from './models/WatermarkTemplate.ts'
|
export type * from './models/WatermarkTemplate.ts'
|
||||||
export type * from './models/WatermarkFile.ts'
|
export type * from './models/WatermarkFile.ts'
|
||||||
|
|||||||
@@ -1143,14 +1143,6 @@ export type EnumAssetTypeFieldUpdateOperationsInput = {
|
|||||||
set?: $Enums.AssetType
|
set?: $Enums.AssetType
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntFieldUpdateOperationsInput = {
|
|
||||||
set?: number
|
|
||||||
increment?: number
|
|
||||||
decrement?: number
|
|
||||||
multiply?: number
|
|
||||||
divide?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export type BigIntFieldUpdateOperationsInput = {
|
export type BigIntFieldUpdateOperationsInput = {
|
||||||
set?: bigint | number
|
set?: bigint | number
|
||||||
increment?: bigint | number
|
increment?: bigint | number
|
||||||
|
|||||||
+72
-1
@@ -46,6 +46,7 @@ export type AssetCommentMinAggregateOutputType = {
|
|||||||
assetId: string | null
|
assetId: string | null
|
||||||
creatorId: string | null
|
creatorId: string | null
|
||||||
isCompleted: boolean | null
|
isCompleted: boolean | null
|
||||||
|
isInternal: boolean | null
|
||||||
completionLastChangedById: string | null
|
completionLastChangedById: string | null
|
||||||
replyToId: string | null
|
replyToId: string | null
|
||||||
}
|
}
|
||||||
@@ -60,6 +61,7 @@ export type AssetCommentMaxAggregateOutputType = {
|
|||||||
assetId: string | null
|
assetId: string | null
|
||||||
creatorId: string | null
|
creatorId: string | null
|
||||||
isCompleted: boolean | null
|
isCompleted: boolean | null
|
||||||
|
isInternal: boolean | null
|
||||||
completionLastChangedById: string | null
|
completionLastChangedById: string | null
|
||||||
replyToId: string | null
|
replyToId: string | null
|
||||||
}
|
}
|
||||||
@@ -75,6 +77,7 @@ export type AssetCommentCountAggregateOutputType = {
|
|||||||
assetId: number
|
assetId: number
|
||||||
creatorId: number
|
creatorId: number
|
||||||
isCompleted: number
|
isCompleted: number
|
||||||
|
isInternal: number
|
||||||
completionLastChangedById: number
|
completionLastChangedById: number
|
||||||
replyToId: number
|
replyToId: number
|
||||||
_all: number
|
_all: number
|
||||||
@@ -99,6 +102,7 @@ export type AssetCommentMinAggregateInputType = {
|
|||||||
assetId?: true
|
assetId?: true
|
||||||
creatorId?: true
|
creatorId?: true
|
||||||
isCompleted?: true
|
isCompleted?: true
|
||||||
|
isInternal?: true
|
||||||
completionLastChangedById?: true
|
completionLastChangedById?: true
|
||||||
replyToId?: true
|
replyToId?: true
|
||||||
}
|
}
|
||||||
@@ -113,6 +117,7 @@ export type AssetCommentMaxAggregateInputType = {
|
|||||||
assetId?: true
|
assetId?: true
|
||||||
creatorId?: true
|
creatorId?: true
|
||||||
isCompleted?: true
|
isCompleted?: true
|
||||||
|
isInternal?: true
|
||||||
completionLastChangedById?: true
|
completionLastChangedById?: true
|
||||||
replyToId?: true
|
replyToId?: true
|
||||||
}
|
}
|
||||||
@@ -128,6 +133,7 @@ export type AssetCommentCountAggregateInputType = {
|
|||||||
assetId?: true
|
assetId?: true
|
||||||
creatorId?: true
|
creatorId?: true
|
||||||
isCompleted?: true
|
isCompleted?: true
|
||||||
|
isInternal?: true
|
||||||
completionLastChangedById?: true
|
completionLastChangedById?: true
|
||||||
replyToId?: true
|
replyToId?: true
|
||||||
_all?: true
|
_all?: true
|
||||||
@@ -230,6 +236,7 @@ export type AssetCommentGroupByOutputType = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId: string | null
|
creatorId: string | null
|
||||||
isCompleted: boolean
|
isCompleted: boolean
|
||||||
|
isInternal: boolean
|
||||||
completionLastChangedById: string | null
|
completionLastChangedById: string | null
|
||||||
replyToId: string | null
|
replyToId: string | null
|
||||||
_count: AssetCommentCountAggregateOutputType | null
|
_count: AssetCommentCountAggregateOutputType | null
|
||||||
@@ -268,6 +275,7 @@ export type AssetCommentWhereInput = {
|
|||||||
assetId?: Prisma.StringFilter<"AssetComment"> | string
|
assetId?: Prisma.StringFilter<"AssetComment"> | string
|
||||||
creatorId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
creatorId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
isCompleted?: Prisma.BoolFilter<"AssetComment"> | boolean
|
isCompleted?: Prisma.BoolFilter<"AssetComment"> | boolean
|
||||||
|
isInternal?: Prisma.BoolFilter<"AssetComment"> | boolean
|
||||||
completionLastChangedById?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
completionLastChangedById?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
replyToId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
replyToId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
session?: Prisma.XOR<Prisma.AgentSessionNullableScalarRelationFilter, Prisma.AgentSessionWhereInput> | null
|
session?: Prisma.XOR<Prisma.AgentSessionNullableScalarRelationFilter, Prisma.AgentSessionWhereInput> | null
|
||||||
@@ -291,6 +299,7 @@ export type AssetCommentOrderByWithRelationInput = {
|
|||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
creatorId?: Prisma.SortOrderInput | Prisma.SortOrder
|
creatorId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
isCompleted?: Prisma.SortOrder
|
isCompleted?: Prisma.SortOrder
|
||||||
|
isInternal?: Prisma.SortOrder
|
||||||
completionLastChangedById?: Prisma.SortOrderInput | Prisma.SortOrder
|
completionLastChangedById?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
replyToId?: Prisma.SortOrderInput | Prisma.SortOrder
|
replyToId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
session?: Prisma.AgentSessionOrderByWithRelationInput
|
session?: Prisma.AgentSessionOrderByWithRelationInput
|
||||||
@@ -317,6 +326,7 @@ export type AssetCommentWhereUniqueInput = Prisma.AtLeast<{
|
|||||||
assetId?: Prisma.StringFilter<"AssetComment"> | string
|
assetId?: Prisma.StringFilter<"AssetComment"> | string
|
||||||
creatorId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
creatorId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
isCompleted?: Prisma.BoolFilter<"AssetComment"> | boolean
|
isCompleted?: Prisma.BoolFilter<"AssetComment"> | boolean
|
||||||
|
isInternal?: Prisma.BoolFilter<"AssetComment"> | boolean
|
||||||
completionLastChangedById?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
completionLastChangedById?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
replyToId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
replyToId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
session?: Prisma.XOR<Prisma.AgentSessionNullableScalarRelationFilter, Prisma.AgentSessionWhereInput> | null
|
session?: Prisma.XOR<Prisma.AgentSessionNullableScalarRelationFilter, Prisma.AgentSessionWhereInput> | null
|
||||||
@@ -340,6 +350,7 @@ export type AssetCommentOrderByWithAggregationInput = {
|
|||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
creatorId?: Prisma.SortOrderInput | Prisma.SortOrder
|
creatorId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
isCompleted?: Prisma.SortOrder
|
isCompleted?: Prisma.SortOrder
|
||||||
|
isInternal?: Prisma.SortOrder
|
||||||
completionLastChangedById?: Prisma.SortOrderInput | Prisma.SortOrder
|
completionLastChangedById?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
replyToId?: Prisma.SortOrderInput | Prisma.SortOrder
|
replyToId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
_count?: Prisma.AssetCommentCountOrderByAggregateInput
|
_count?: Prisma.AssetCommentCountOrderByAggregateInput
|
||||||
@@ -363,6 +374,7 @@ export type AssetCommentScalarWhereWithAggregatesInput = {
|
|||||||
assetId?: Prisma.StringWithAggregatesFilter<"AssetComment"> | string
|
assetId?: Prisma.StringWithAggregatesFilter<"AssetComment"> | string
|
||||||
creatorId?: Prisma.StringNullableWithAggregatesFilter<"AssetComment"> | string | null
|
creatorId?: Prisma.StringNullableWithAggregatesFilter<"AssetComment"> | string | null
|
||||||
isCompleted?: Prisma.BoolWithAggregatesFilter<"AssetComment"> | boolean
|
isCompleted?: Prisma.BoolWithAggregatesFilter<"AssetComment"> | boolean
|
||||||
|
isInternal?: Prisma.BoolWithAggregatesFilter<"AssetComment"> | boolean
|
||||||
completionLastChangedById?: Prisma.StringNullableWithAggregatesFilter<"AssetComment"> | string | null
|
completionLastChangedById?: Prisma.StringNullableWithAggregatesFilter<"AssetComment"> | string | null
|
||||||
replyToId?: Prisma.StringNullableWithAggregatesFilter<"AssetComment"> | string | null
|
replyToId?: Prisma.StringNullableWithAggregatesFilter<"AssetComment"> | string | null
|
||||||
}
|
}
|
||||||
@@ -375,6 +387,7 @@ export type AssetCommentCreateInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
@@ -396,6 +409,7 @@ export type AssetCommentUncheckedCreateInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
@@ -411,6 +425,7 @@ export type AssetCommentUpdateInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
@@ -432,6 +447,7 @@ export type AssetCommentUncheckedUpdateInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
@@ -450,6 +466,7 @@ export type AssetCommentCreateManyInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
}
|
}
|
||||||
@@ -462,6 +479,7 @@ export type AssetCommentUpdateManyMutationInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AssetCommentUncheckedUpdateManyInput = {
|
export type AssetCommentUncheckedUpdateManyInput = {
|
||||||
@@ -475,6 +493,7 @@ export type AssetCommentUncheckedUpdateManyInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
}
|
}
|
||||||
@@ -505,6 +524,7 @@ export type AssetCommentCountOrderByAggregateInput = {
|
|||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
creatorId?: Prisma.SortOrder
|
creatorId?: Prisma.SortOrder
|
||||||
isCompleted?: Prisma.SortOrder
|
isCompleted?: Prisma.SortOrder
|
||||||
|
isInternal?: Prisma.SortOrder
|
||||||
completionLastChangedById?: Prisma.SortOrder
|
completionLastChangedById?: Prisma.SortOrder
|
||||||
replyToId?: Prisma.SortOrder
|
replyToId?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
@@ -523,6 +543,7 @@ export type AssetCommentMaxOrderByAggregateInput = {
|
|||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
creatorId?: Prisma.SortOrder
|
creatorId?: Prisma.SortOrder
|
||||||
isCompleted?: Prisma.SortOrder
|
isCompleted?: Prisma.SortOrder
|
||||||
|
isInternal?: Prisma.SortOrder
|
||||||
completionLastChangedById?: Prisma.SortOrder
|
completionLastChangedById?: Prisma.SortOrder
|
||||||
replyToId?: Prisma.SortOrder
|
replyToId?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
@@ -537,6 +558,7 @@ export type AssetCommentMinOrderByAggregateInput = {
|
|||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
creatorId?: Prisma.SortOrder
|
creatorId?: Prisma.SortOrder
|
||||||
isCompleted?: Prisma.SortOrder
|
isCompleted?: Prisma.SortOrder
|
||||||
|
isInternal?: Prisma.SortOrder
|
||||||
completionLastChangedById?: Prisma.SortOrder
|
completionLastChangedById?: Prisma.SortOrder
|
||||||
replyToId?: Prisma.SortOrder
|
replyToId?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
@@ -812,6 +834,7 @@ export type AssetCommentCreateWithoutCreatorInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
completionLastChangedBy?: Prisma.UserCreateNestedOneWithoutCompletionChangedCommentsInput
|
completionLastChangedBy?: Prisma.UserCreateNestedOneWithoutCompletionChangedCommentsInput
|
||||||
@@ -831,6 +854,7 @@ export type AssetCommentUncheckedCreateWithoutCreatorInput = {
|
|||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
assetId: string
|
assetId: string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
@@ -856,6 +880,7 @@ export type AssetCommentCreateWithoutCompletionLastChangedByInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
@@ -876,6 +901,7 @@ export type AssetCommentUncheckedCreateWithoutCompletionLastChangedByInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
attachments?: Prisma.AssetCommentAttachmentUncheckedCreateNestedManyWithoutCommentInput
|
attachments?: Prisma.AssetCommentAttachmentUncheckedCreateNestedManyWithoutCommentInput
|
||||||
@@ -922,6 +948,7 @@ export type AssetCommentScalarWhereInput = {
|
|||||||
assetId?: Prisma.StringFilter<"AssetComment"> | string
|
assetId?: Prisma.StringFilter<"AssetComment"> | string
|
||||||
creatorId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
creatorId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
isCompleted?: Prisma.BoolFilter<"AssetComment"> | boolean
|
isCompleted?: Prisma.BoolFilter<"AssetComment"> | boolean
|
||||||
|
isInternal?: Prisma.BoolFilter<"AssetComment"> | boolean
|
||||||
completionLastChangedById?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
completionLastChangedById?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
replyToId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
replyToId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
|
||||||
}
|
}
|
||||||
@@ -950,6 +977,7 @@ export type AssetCommentCreateWithoutAssetInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
completionLastChangedBy?: Prisma.UserCreateNestedOneWithoutCompletionChangedCommentsInput
|
completionLastChangedBy?: Prisma.UserCreateNestedOneWithoutCompletionChangedCommentsInput
|
||||||
@@ -969,6 +997,7 @@ export type AssetCommentUncheckedCreateWithoutAssetInput = {
|
|||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
@@ -1010,6 +1039,7 @@ export type AssetCommentCreateWithoutRepliesInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
@@ -1030,6 +1060,7 @@ export type AssetCommentUncheckedCreateWithoutRepliesInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
attachments?: Prisma.AssetCommentAttachmentUncheckedCreateNestedManyWithoutCommentInput
|
attachments?: Prisma.AssetCommentAttachmentUncheckedCreateNestedManyWithoutCommentInput
|
||||||
@@ -1049,6 +1080,7 @@ export type AssetCommentCreateWithoutReplyToInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
@@ -1069,6 +1101,7 @@ export type AssetCommentUncheckedCreateWithoutReplyToInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
attachments?: Prisma.AssetCommentAttachmentUncheckedCreateNestedManyWithoutCommentInput
|
attachments?: Prisma.AssetCommentAttachmentUncheckedCreateNestedManyWithoutCommentInput
|
||||||
@@ -1104,6 +1137,7 @@ export type AssetCommentUpdateWithoutRepliesInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
@@ -1124,6 +1158,7 @@ export type AssetCommentUncheckedUpdateWithoutRepliesInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
|
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
|
||||||
@@ -1154,6 +1189,7 @@ export type AssetCommentCreateWithoutAttachmentsInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
@@ -1174,6 +1210,7 @@ export type AssetCommentUncheckedCreateWithoutAttachmentsInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
@@ -1204,6 +1241,7 @@ export type AssetCommentUpdateWithoutAttachmentsInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
@@ -1224,6 +1262,7 @@ export type AssetCommentUncheckedUpdateWithoutAttachmentsInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
@@ -1238,6 +1277,7 @@ export type AssetCommentCreateWithoutReactionsInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
@@ -1258,6 +1298,7 @@ export type AssetCommentUncheckedCreateWithoutReactionsInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
@@ -1288,6 +1329,7 @@ export type AssetCommentUpdateWithoutReactionsInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
@@ -1308,6 +1350,7 @@ export type AssetCommentUncheckedUpdateWithoutReactionsInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
@@ -1322,6 +1365,7 @@ export type AssetCommentCreateWithoutSessionInput = {
|
|||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
|
||||||
completionLastChangedBy?: Prisma.UserCreateNestedOneWithoutCompletionChangedCommentsInput
|
completionLastChangedBy?: Prisma.UserCreateNestedOneWithoutCompletionChangedCommentsInput
|
||||||
@@ -1341,6 +1385,7 @@ export type AssetCommentUncheckedCreateWithoutSessionInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
replies?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutReplyToInput
|
||||||
@@ -1384,6 +1429,7 @@ export type AssetCommentCreateManyCreatorInput = {
|
|||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
assetId: string
|
assetId: string
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
}
|
}
|
||||||
@@ -1399,6 +1445,7 @@ export type AssetCommentCreateManyCompletionLastChangedByInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1410,6 +1457,7 @@ export type AssetCommentUpdateWithoutCreatorInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
completionLastChangedBy?: Prisma.UserUpdateOneWithoutCompletionChangedCommentsNestedInput
|
completionLastChangedBy?: Prisma.UserUpdateOneWithoutCompletionChangedCommentsNestedInput
|
||||||
@@ -1429,6 +1477,7 @@ export type AssetCommentUncheckedUpdateWithoutCreatorInput = {
|
|||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
@@ -1446,6 +1495,7 @@ export type AssetCommentUncheckedUpdateManyWithoutCreatorInput = {
|
|||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
}
|
}
|
||||||
@@ -1458,6 +1508,7 @@ export type AssetCommentUpdateWithoutCompletionLastChangedByInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
@@ -1478,6 +1529,7 @@ export type AssetCommentUncheckedUpdateWithoutCompletionLastChangedByInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
|
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
|
||||||
@@ -1495,6 +1547,7 @@ export type AssetCommentUncheckedUpdateManyWithoutCompletionLastChangedByInput =
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1508,6 +1561,7 @@ export type AssetCommentCreateManyAssetInput = {
|
|||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
}
|
}
|
||||||
@@ -1520,6 +1574,7 @@ export type AssetCommentUpdateWithoutAssetInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
completionLastChangedBy?: Prisma.UserUpdateOneWithoutCompletionChangedCommentsNestedInput
|
completionLastChangedBy?: Prisma.UserUpdateOneWithoutCompletionChangedCommentsNestedInput
|
||||||
@@ -1539,6 +1594,7 @@ export type AssetCommentUncheckedUpdateWithoutAssetInput = {
|
|||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
@@ -1556,6 +1612,7 @@ export type AssetCommentUncheckedUpdateManyWithoutAssetInput = {
|
|||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
}
|
}
|
||||||
@@ -1571,6 +1628,7 @@ export type AssetCommentCreateManyReplyToInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1582,6 +1640,7 @@ export type AssetCommentUpdateWithoutReplyToInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
@@ -1602,6 +1661,7 @@ export type AssetCommentUncheckedUpdateWithoutReplyToInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
|
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
|
||||||
@@ -1619,6 +1679,7 @@ export type AssetCommentUncheckedUpdateManyWithoutReplyToInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1632,6 +1693,7 @@ export type AssetCommentCreateManySessionInput = {
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: string | null
|
completionLastChangedById?: string | null
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
}
|
}
|
||||||
@@ -1644,6 +1706,7 @@ export type AssetCommentUpdateWithoutSessionInput = {
|
|||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
|
||||||
completionLastChangedBy?: Prisma.UserUpdateOneWithoutCompletionChangedCommentsNestedInput
|
completionLastChangedBy?: Prisma.UserUpdateOneWithoutCompletionChangedCommentsNestedInput
|
||||||
@@ -1663,6 +1726,7 @@ export type AssetCommentUncheckedUpdateWithoutSessionInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
|
||||||
@@ -1680,6 +1744,7 @@ export type AssetCommentUncheckedUpdateManyWithoutSessionInput = {
|
|||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
isCompleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
isInternal?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
completionLastChangedById?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
}
|
}
|
||||||
@@ -1744,6 +1809,7 @@ export type AssetCommentSelect<ExtArgs extends runtime.Types.Extensions.Internal
|
|||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
creatorId?: boolean
|
creatorId?: boolean
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: boolean
|
completionLastChangedById?: boolean
|
||||||
replyToId?: boolean
|
replyToId?: boolean
|
||||||
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
||||||
@@ -1768,6 +1834,7 @@ export type AssetCommentSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
|
|||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
creatorId?: boolean
|
creatorId?: boolean
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: boolean
|
completionLastChangedById?: boolean
|
||||||
replyToId?: boolean
|
replyToId?: boolean
|
||||||
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
||||||
@@ -1788,6 +1855,7 @@ export type AssetCommentSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
|
|||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
creatorId?: boolean
|
creatorId?: boolean
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: boolean
|
completionLastChangedById?: boolean
|
||||||
replyToId?: boolean
|
replyToId?: boolean
|
||||||
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
||||||
@@ -1808,11 +1876,12 @@ export type AssetCommentSelectScalar = {
|
|||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
creatorId?: boolean
|
creatorId?: boolean
|
||||||
isCompleted?: boolean
|
isCompleted?: boolean
|
||||||
|
isInternal?: boolean
|
||||||
completionLastChangedById?: boolean
|
completionLastChangedById?: boolean
|
||||||
replyToId?: boolean
|
replyToId?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AssetCommentOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "message" | "annotation" | "second" | "sessionId" | "createdAt" | "updatedAt" | "assetId" | "creatorId" | "isCompleted" | "completionLastChangedById" | "replyToId", ExtArgs["result"]["assetComment"]>
|
export type AssetCommentOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "message" | "annotation" | "second" | "sessionId" | "createdAt" | "updatedAt" | "assetId" | "creatorId" | "isCompleted" | "isInternal" | "completionLastChangedById" | "replyToId", ExtArgs["result"]["assetComment"]>
|
||||||
export type AssetCommentInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type AssetCommentInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
session?: boolean | Prisma.AssetComment$sessionArgs<ExtArgs>
|
||||||
asset?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
asset?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
||||||
@@ -1865,6 +1934,7 @@ export type $AssetCommentPayload<ExtArgs extends runtime.Types.Extensions.Intern
|
|||||||
assetId: string
|
assetId: string
|
||||||
creatorId: string | null
|
creatorId: string | null
|
||||||
isCompleted: boolean
|
isCompleted: boolean
|
||||||
|
isInternal: boolean
|
||||||
completionLastChangedById: string | null
|
completionLastChangedById: string | null
|
||||||
replyToId: string | null
|
replyToId: string | null
|
||||||
}, ExtArgs["result"]["assetComment"]>
|
}, ExtArgs["result"]["assetComment"]>
|
||||||
@@ -2308,6 +2378,7 @@ export interface AssetCommentFieldRefs {
|
|||||||
readonly assetId: Prisma.FieldRef<"AssetComment", 'String'>
|
readonly assetId: Prisma.FieldRef<"AssetComment", 'String'>
|
||||||
readonly creatorId: Prisma.FieldRef<"AssetComment", 'String'>
|
readonly creatorId: Prisma.FieldRef<"AssetComment", 'String'>
|
||||||
readonly isCompleted: Prisma.FieldRef<"AssetComment", 'Boolean'>
|
readonly isCompleted: Prisma.FieldRef<"AssetComment", 'Boolean'>
|
||||||
|
readonly isInternal: Prisma.FieldRef<"AssetComment", 'Boolean'>
|
||||||
readonly completionLastChangedById: Prisma.FieldRef<"AssetComment", 'String'>
|
readonly completionLastChangedById: Prisma.FieldRef<"AssetComment", 'String'>
|
||||||
readonly replyToId: Prisma.FieldRef<"AssetComment", 'String'>
|
readonly replyToId: Prisma.FieldRef<"AssetComment", 'String'>
|
||||||
}
|
}
|
||||||
|
|||||||
+1386
File diff suppressed because it is too large
Load Diff
+356
-1
@@ -22,10 +22,20 @@ export type ShareLinkModel = runtime.Types.Result.DefaultSelection<Prisma.$Share
|
|||||||
|
|
||||||
export type AggregateShareLink = {
|
export type AggregateShareLink = {
|
||||||
_count: ShareLinkCountAggregateOutputType | null
|
_count: ShareLinkCountAggregateOutputType | null
|
||||||
|
_avg: ShareLinkAvgAggregateOutputType | null
|
||||||
|
_sum: ShareLinkSumAggregateOutputType | null
|
||||||
_min: ShareLinkMinAggregateOutputType | null
|
_min: ShareLinkMinAggregateOutputType | null
|
||||||
_max: ShareLinkMaxAggregateOutputType | null
|
_max: ShareLinkMaxAggregateOutputType | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ShareLinkAvgAggregateOutputType = {
|
||||||
|
views: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkSumAggregateOutputType = {
|
||||||
|
views: number | null
|
||||||
|
}
|
||||||
|
|
||||||
export type ShareLinkMinAggregateOutputType = {
|
export type ShareLinkMinAggregateOutputType = {
|
||||||
id: string | null
|
id: string | null
|
||||||
name: string | null
|
name: string | null
|
||||||
@@ -35,6 +45,8 @@ export type ShareLinkMinAggregateOutputType = {
|
|||||||
allowDownload: boolean | null
|
allowDownload: boolean | null
|
||||||
defaultSortOrder: string | null
|
defaultSortOrder: string | null
|
||||||
viewMode: string | null
|
viewMode: string | null
|
||||||
|
views: number | null
|
||||||
|
lastViewedAt: Date | null
|
||||||
createdAt: Date | null
|
createdAt: Date | null
|
||||||
updatedAt: Date | null
|
updatedAt: Date | null
|
||||||
projectId: string | null
|
projectId: string | null
|
||||||
@@ -53,6 +65,8 @@ export type ShareLinkMaxAggregateOutputType = {
|
|||||||
allowDownload: boolean | null
|
allowDownload: boolean | null
|
||||||
defaultSortOrder: string | null
|
defaultSortOrder: string | null
|
||||||
viewMode: string | null
|
viewMode: string | null
|
||||||
|
views: number | null
|
||||||
|
lastViewedAt: Date | null
|
||||||
createdAt: Date | null
|
createdAt: Date | null
|
||||||
updatedAt: Date | null
|
updatedAt: Date | null
|
||||||
projectId: string | null
|
projectId: string | null
|
||||||
@@ -72,6 +86,8 @@ export type ShareLinkCountAggregateOutputType = {
|
|||||||
defaultSortOrder: number
|
defaultSortOrder: number
|
||||||
viewMode: number
|
viewMode: number
|
||||||
fieldVisibility: number
|
fieldVisibility: number
|
||||||
|
views: number
|
||||||
|
lastViewedAt: number
|
||||||
createdAt: number
|
createdAt: number
|
||||||
updatedAt: number
|
updatedAt: number
|
||||||
projectId: number
|
projectId: number
|
||||||
@@ -83,6 +99,14 @@ export type ShareLinkCountAggregateOutputType = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export type ShareLinkAvgAggregateInputType = {
|
||||||
|
views?: true
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkSumAggregateInputType = {
|
||||||
|
views?: true
|
||||||
|
}
|
||||||
|
|
||||||
export type ShareLinkMinAggregateInputType = {
|
export type ShareLinkMinAggregateInputType = {
|
||||||
id?: true
|
id?: true
|
||||||
name?: true
|
name?: true
|
||||||
@@ -92,6 +116,8 @@ export type ShareLinkMinAggregateInputType = {
|
|||||||
allowDownload?: true
|
allowDownload?: true
|
||||||
defaultSortOrder?: true
|
defaultSortOrder?: true
|
||||||
viewMode?: true
|
viewMode?: true
|
||||||
|
views?: true
|
||||||
|
lastViewedAt?: true
|
||||||
createdAt?: true
|
createdAt?: true
|
||||||
updatedAt?: true
|
updatedAt?: true
|
||||||
projectId?: true
|
projectId?: true
|
||||||
@@ -110,6 +136,8 @@ export type ShareLinkMaxAggregateInputType = {
|
|||||||
allowDownload?: true
|
allowDownload?: true
|
||||||
defaultSortOrder?: true
|
defaultSortOrder?: true
|
||||||
viewMode?: true
|
viewMode?: true
|
||||||
|
views?: true
|
||||||
|
lastViewedAt?: true
|
||||||
createdAt?: true
|
createdAt?: true
|
||||||
updatedAt?: true
|
updatedAt?: true
|
||||||
projectId?: true
|
projectId?: true
|
||||||
@@ -129,6 +157,8 @@ export type ShareLinkCountAggregateInputType = {
|
|||||||
defaultSortOrder?: true
|
defaultSortOrder?: true
|
||||||
viewMode?: true
|
viewMode?: true
|
||||||
fieldVisibility?: true
|
fieldVisibility?: true
|
||||||
|
views?: true
|
||||||
|
lastViewedAt?: true
|
||||||
createdAt?: true
|
createdAt?: true
|
||||||
updatedAt?: true
|
updatedAt?: true
|
||||||
projectId?: true
|
projectId?: true
|
||||||
@@ -174,6 +204,18 @@ export type ShareLinkAggregateArgs<ExtArgs extends runtime.Types.Extensions.Inte
|
|||||||
* Count returned ShareLinks
|
* Count returned ShareLinks
|
||||||
**/
|
**/
|
||||||
_count?: true | ShareLinkCountAggregateInputType
|
_count?: true | ShareLinkCountAggregateInputType
|
||||||
|
/**
|
||||||
|
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||||
|
*
|
||||||
|
* Select which fields to average
|
||||||
|
**/
|
||||||
|
_avg?: ShareLinkAvgAggregateInputType
|
||||||
|
/**
|
||||||
|
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||||
|
*
|
||||||
|
* Select which fields to sum
|
||||||
|
**/
|
||||||
|
_sum?: ShareLinkSumAggregateInputType
|
||||||
/**
|
/**
|
||||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||||
*
|
*
|
||||||
@@ -207,6 +249,8 @@ export type ShareLinkGroupByArgs<ExtArgs extends runtime.Types.Extensions.Intern
|
|||||||
take?: number
|
take?: number
|
||||||
skip?: number
|
skip?: number
|
||||||
_count?: ShareLinkCountAggregateInputType | true
|
_count?: ShareLinkCountAggregateInputType | true
|
||||||
|
_avg?: ShareLinkAvgAggregateInputType
|
||||||
|
_sum?: ShareLinkSumAggregateInputType
|
||||||
_min?: ShareLinkMinAggregateInputType
|
_min?: ShareLinkMinAggregateInputType
|
||||||
_max?: ShareLinkMaxAggregateInputType
|
_max?: ShareLinkMaxAggregateInputType
|
||||||
}
|
}
|
||||||
@@ -221,6 +265,8 @@ export type ShareLinkGroupByOutputType = {
|
|||||||
defaultSortOrder: string | null
|
defaultSortOrder: string | null
|
||||||
viewMode: string | null
|
viewMode: string | null
|
||||||
fieldVisibility:PrismaJson.ShareLinkFieldVisibility | null
|
fieldVisibility:PrismaJson.ShareLinkFieldVisibility | null
|
||||||
|
views: number
|
||||||
|
lastViewedAt: Date | null
|
||||||
createdAt: Date
|
createdAt: Date
|
||||||
updatedAt: Date
|
updatedAt: Date
|
||||||
projectId: string
|
projectId: string
|
||||||
@@ -229,6 +275,8 @@ export type ShareLinkGroupByOutputType = {
|
|||||||
watermarkConfigId: string | null
|
watermarkConfigId: string | null
|
||||||
watermarkStatus: $Enums.WatermarkStatus
|
watermarkStatus: $Enums.WatermarkStatus
|
||||||
_count: ShareLinkCountAggregateOutputType | null
|
_count: ShareLinkCountAggregateOutputType | null
|
||||||
|
_avg: ShareLinkAvgAggregateOutputType | null
|
||||||
|
_sum: ShareLinkSumAggregateOutputType | null
|
||||||
_min: ShareLinkMinAggregateOutputType | null
|
_min: ShareLinkMinAggregateOutputType | null
|
||||||
_max: ShareLinkMaxAggregateOutputType | null
|
_max: ShareLinkMaxAggregateOutputType | null
|
||||||
}
|
}
|
||||||
@@ -261,6 +309,8 @@ export type ShareLinkWhereInput = {
|
|||||||
defaultSortOrder?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
defaultSortOrder?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
||||||
viewMode?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
viewMode?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
||||||
fieldVisibility?: Prisma.JsonNullableFilter<"ShareLink">
|
fieldVisibility?: Prisma.JsonNullableFilter<"ShareLink">
|
||||||
|
views?: Prisma.IntFilter<"ShareLink"> | number
|
||||||
|
lastViewedAt?: Prisma.DateTimeNullableFilter<"ShareLink"> | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
createdAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
updatedAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
||||||
projectId?: Prisma.StringFilter<"ShareLink"> | string
|
projectId?: Prisma.StringFilter<"ShareLink"> | string
|
||||||
@@ -272,6 +322,7 @@ export type ShareLinkWhereInput = {
|
|||||||
rootFolder?: Prisma.XOR<Prisma.AssetScalarRelationFilter, Prisma.AssetWhereInput>
|
rootFolder?: Prisma.XOR<Prisma.AssetScalarRelationFilter, Prisma.AssetWhereInput>
|
||||||
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
|
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
|
||||||
watermarkConfig?: Prisma.XOR<Prisma.WatermarkConfigNullableScalarRelationFilter, Prisma.WatermarkConfigWhereInput> | null
|
watermarkConfig?: Prisma.XOR<Prisma.WatermarkConfigNullableScalarRelationFilter, Prisma.WatermarkConfigWhereInput> | null
|
||||||
|
activities?: Prisma.ShareActivityListRelationFilter
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkOrderByWithRelationInput = {
|
export type ShareLinkOrderByWithRelationInput = {
|
||||||
@@ -284,6 +335,8 @@ export type ShareLinkOrderByWithRelationInput = {
|
|||||||
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
|
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
|
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
|
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
views?: Prisma.SortOrder
|
||||||
|
lastViewedAt?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
projectId?: Prisma.SortOrder
|
projectId?: Prisma.SortOrder
|
||||||
@@ -295,6 +348,7 @@ export type ShareLinkOrderByWithRelationInput = {
|
|||||||
rootFolder?: Prisma.AssetOrderByWithRelationInput
|
rootFolder?: Prisma.AssetOrderByWithRelationInput
|
||||||
creator?: Prisma.UserOrderByWithRelationInput
|
creator?: Prisma.UserOrderByWithRelationInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigOrderByWithRelationInput
|
watermarkConfig?: Prisma.WatermarkConfigOrderByWithRelationInput
|
||||||
|
activities?: Prisma.ShareActivityOrderByRelationAggregateInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkWhereUniqueInput = Prisma.AtLeast<{
|
export type ShareLinkWhereUniqueInput = Prisma.AtLeast<{
|
||||||
@@ -311,6 +365,8 @@ export type ShareLinkWhereUniqueInput = Prisma.AtLeast<{
|
|||||||
defaultSortOrder?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
defaultSortOrder?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
||||||
viewMode?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
viewMode?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
||||||
fieldVisibility?: Prisma.JsonNullableFilter<"ShareLink">
|
fieldVisibility?: Prisma.JsonNullableFilter<"ShareLink">
|
||||||
|
views?: Prisma.IntFilter<"ShareLink"> | number
|
||||||
|
lastViewedAt?: Prisma.DateTimeNullableFilter<"ShareLink"> | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
createdAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
updatedAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
||||||
projectId?: Prisma.StringFilter<"ShareLink"> | string
|
projectId?: Prisma.StringFilter<"ShareLink"> | string
|
||||||
@@ -321,6 +377,7 @@ export type ShareLinkWhereUniqueInput = Prisma.AtLeast<{
|
|||||||
rootFolder?: Prisma.XOR<Prisma.AssetScalarRelationFilter, Prisma.AssetWhereInput>
|
rootFolder?: Prisma.XOR<Prisma.AssetScalarRelationFilter, Prisma.AssetWhereInput>
|
||||||
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
|
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
|
||||||
watermarkConfig?: Prisma.XOR<Prisma.WatermarkConfigNullableScalarRelationFilter, Prisma.WatermarkConfigWhereInput> | null
|
watermarkConfig?: Prisma.XOR<Prisma.WatermarkConfigNullableScalarRelationFilter, Prisma.WatermarkConfigWhereInput> | null
|
||||||
|
activities?: Prisma.ShareActivityListRelationFilter
|
||||||
}, "id" | "rootFolderId">
|
}, "id" | "rootFolderId">
|
||||||
|
|
||||||
export type ShareLinkOrderByWithAggregationInput = {
|
export type ShareLinkOrderByWithAggregationInput = {
|
||||||
@@ -333,6 +390,8 @@ export type ShareLinkOrderByWithAggregationInput = {
|
|||||||
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
|
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
|
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
|
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
views?: Prisma.SortOrder
|
||||||
|
lastViewedAt?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
projectId?: Prisma.SortOrder
|
projectId?: Prisma.SortOrder
|
||||||
@@ -341,8 +400,10 @@ export type ShareLinkOrderByWithAggregationInput = {
|
|||||||
watermarkConfigId?: Prisma.SortOrderInput | Prisma.SortOrder
|
watermarkConfigId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
watermarkStatus?: Prisma.SortOrder
|
watermarkStatus?: Prisma.SortOrder
|
||||||
_count?: Prisma.ShareLinkCountOrderByAggregateInput
|
_count?: Prisma.ShareLinkCountOrderByAggregateInput
|
||||||
|
_avg?: Prisma.ShareLinkAvgOrderByAggregateInput
|
||||||
_max?: Prisma.ShareLinkMaxOrderByAggregateInput
|
_max?: Prisma.ShareLinkMaxOrderByAggregateInput
|
||||||
_min?: Prisma.ShareLinkMinOrderByAggregateInput
|
_min?: Prisma.ShareLinkMinOrderByAggregateInput
|
||||||
|
_sum?: Prisma.ShareLinkSumOrderByAggregateInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkScalarWhereWithAggregatesInput = {
|
export type ShareLinkScalarWhereWithAggregatesInput = {
|
||||||
@@ -358,6 +419,8 @@ export type ShareLinkScalarWhereWithAggregatesInput = {
|
|||||||
defaultSortOrder?: Prisma.StringNullableWithAggregatesFilter<"ShareLink"> | string | null
|
defaultSortOrder?: Prisma.StringNullableWithAggregatesFilter<"ShareLink"> | string | null
|
||||||
viewMode?: Prisma.StringNullableWithAggregatesFilter<"ShareLink"> | string | null
|
viewMode?: Prisma.StringNullableWithAggregatesFilter<"ShareLink"> | string | null
|
||||||
fieldVisibility?: Prisma.JsonNullableWithAggregatesFilter<"ShareLink">
|
fieldVisibility?: Prisma.JsonNullableWithAggregatesFilter<"ShareLink">
|
||||||
|
views?: Prisma.IntWithAggregatesFilter<"ShareLink"> | number
|
||||||
|
lastViewedAt?: Prisma.DateTimeNullableWithAggregatesFilter<"ShareLink"> | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<"ShareLink"> | Date | string
|
createdAt?: Prisma.DateTimeWithAggregatesFilter<"ShareLink"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"ShareLink"> | Date | string
|
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"ShareLink"> | Date | string
|
||||||
projectId?: Prisma.StringWithAggregatesFilter<"ShareLink"> | string
|
projectId?: Prisma.StringWithAggregatesFilter<"ShareLink"> | string
|
||||||
@@ -377,6 +440,8 @@ export type ShareLinkCreateInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
@@ -384,6 +449,7 @@ export type ShareLinkCreateInput = {
|
|||||||
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
||||||
|
activities?: Prisma.ShareActivityCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedCreateInput = {
|
export type ShareLinkUncheckedCreateInput = {
|
||||||
@@ -396,6 +462,8 @@ export type ShareLinkUncheckedCreateInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
projectId: string
|
projectId: string
|
||||||
@@ -403,6 +471,7 @@ export type ShareLinkUncheckedCreateInput = {
|
|||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
watermarkConfigId?: string | null
|
watermarkConfigId?: string | null
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUpdateInput = {
|
export type ShareLinkUpdateInput = {
|
||||||
@@ -415,6 +484,8 @@ export type ShareLinkUpdateInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
@@ -422,6 +493,7 @@ export type ShareLinkUpdateInput = {
|
|||||||
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
||||||
|
activities?: Prisma.ShareActivityUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateInput = {
|
export type ShareLinkUncheckedUpdateInput = {
|
||||||
@@ -434,6 +506,8 @@ export type ShareLinkUncheckedUpdateInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
@@ -441,6 +515,7 @@ export type ShareLinkUncheckedUpdateInput = {
|
|||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateManyInput = {
|
export type ShareLinkCreateManyInput = {
|
||||||
@@ -453,6 +528,8 @@ export type ShareLinkCreateManyInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
projectId: string
|
projectId: string
|
||||||
@@ -472,6 +549,8 @@ export type ShareLinkUpdateManyMutationInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
@@ -487,6 +566,8 @@ export type ShareLinkUncheckedUpdateManyInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
@@ -516,6 +597,8 @@ export type ShareLinkCountOrderByAggregateInput = {
|
|||||||
defaultSortOrder?: Prisma.SortOrder
|
defaultSortOrder?: Prisma.SortOrder
|
||||||
viewMode?: Prisma.SortOrder
|
viewMode?: Prisma.SortOrder
|
||||||
fieldVisibility?: Prisma.SortOrder
|
fieldVisibility?: Prisma.SortOrder
|
||||||
|
views?: Prisma.SortOrder
|
||||||
|
lastViewedAt?: Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
projectId?: Prisma.SortOrder
|
projectId?: Prisma.SortOrder
|
||||||
@@ -525,6 +608,10 @@ export type ShareLinkCountOrderByAggregateInput = {
|
|||||||
watermarkStatus?: Prisma.SortOrder
|
watermarkStatus?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ShareLinkAvgOrderByAggregateInput = {
|
||||||
|
views?: Prisma.SortOrder
|
||||||
|
}
|
||||||
|
|
||||||
export type ShareLinkMaxOrderByAggregateInput = {
|
export type ShareLinkMaxOrderByAggregateInput = {
|
||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
name?: Prisma.SortOrder
|
name?: Prisma.SortOrder
|
||||||
@@ -534,6 +621,8 @@ export type ShareLinkMaxOrderByAggregateInput = {
|
|||||||
allowDownload?: Prisma.SortOrder
|
allowDownload?: Prisma.SortOrder
|
||||||
defaultSortOrder?: Prisma.SortOrder
|
defaultSortOrder?: Prisma.SortOrder
|
||||||
viewMode?: Prisma.SortOrder
|
viewMode?: Prisma.SortOrder
|
||||||
|
views?: Prisma.SortOrder
|
||||||
|
lastViewedAt?: Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
projectId?: Prisma.SortOrder
|
projectId?: Prisma.SortOrder
|
||||||
@@ -552,6 +641,8 @@ export type ShareLinkMinOrderByAggregateInput = {
|
|||||||
allowDownload?: Prisma.SortOrder
|
allowDownload?: Prisma.SortOrder
|
||||||
defaultSortOrder?: Prisma.SortOrder
|
defaultSortOrder?: Prisma.SortOrder
|
||||||
viewMode?: Prisma.SortOrder
|
viewMode?: Prisma.SortOrder
|
||||||
|
views?: Prisma.SortOrder
|
||||||
|
lastViewedAt?: Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
projectId?: Prisma.SortOrder
|
projectId?: Prisma.SortOrder
|
||||||
@@ -561,6 +652,15 @@ export type ShareLinkMinOrderByAggregateInput = {
|
|||||||
watermarkStatus?: Prisma.SortOrder
|
watermarkStatus?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ShareLinkSumOrderByAggregateInput = {
|
||||||
|
views?: Prisma.SortOrder
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkScalarRelationFilter = {
|
||||||
|
is?: Prisma.ShareLinkWhereInput
|
||||||
|
isNot?: Prisma.ShareLinkWhereInput
|
||||||
|
}
|
||||||
|
|
||||||
export type ShareLinkNullableScalarRelationFilter = {
|
export type ShareLinkNullableScalarRelationFilter = {
|
||||||
is?: Prisma.ShareLinkWhereInput | null
|
is?: Prisma.ShareLinkWhereInput | null
|
||||||
isNot?: Prisma.ShareLinkWhereInput | null
|
isNot?: Prisma.ShareLinkWhereInput | null
|
||||||
@@ -650,10 +750,32 @@ export type ShareLinkUncheckedUpdateManyWithoutProjectNestedInput = {
|
|||||||
deleteMany?: Prisma.ShareLinkScalarWhereInput | Prisma.ShareLinkScalarWhereInput[]
|
deleteMany?: Prisma.ShareLinkScalarWhereInput | Prisma.ShareLinkScalarWhereInput[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type IntFieldUpdateOperationsInput = {
|
||||||
|
set?: number
|
||||||
|
increment?: number
|
||||||
|
decrement?: number
|
||||||
|
multiply?: number
|
||||||
|
divide?: number
|
||||||
|
}
|
||||||
|
|
||||||
export type EnumWatermarkStatusFieldUpdateOperationsInput = {
|
export type EnumWatermarkStatusFieldUpdateOperationsInput = {
|
||||||
set?: $Enums.WatermarkStatus
|
set?: $Enums.WatermarkStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ShareLinkCreateNestedOneWithoutActivitiesInput = {
|
||||||
|
create?: Prisma.XOR<Prisma.ShareLinkCreateWithoutActivitiesInput, Prisma.ShareLinkUncheckedCreateWithoutActivitiesInput>
|
||||||
|
connectOrCreate?: Prisma.ShareLinkCreateOrConnectWithoutActivitiesInput
|
||||||
|
connect?: Prisma.ShareLinkWhereUniqueInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkUpdateOneRequiredWithoutActivitiesNestedInput = {
|
||||||
|
create?: Prisma.XOR<Prisma.ShareLinkCreateWithoutActivitiesInput, Prisma.ShareLinkUncheckedCreateWithoutActivitiesInput>
|
||||||
|
connectOrCreate?: Prisma.ShareLinkCreateOrConnectWithoutActivitiesInput
|
||||||
|
upsert?: Prisma.ShareLinkUpsertWithoutActivitiesInput
|
||||||
|
connect?: Prisma.ShareLinkWhereUniqueInput
|
||||||
|
update?: Prisma.XOR<Prisma.XOR<Prisma.ShareLinkUpdateToOneWithWhereWithoutActivitiesInput, Prisma.ShareLinkUpdateWithoutActivitiesInput>, Prisma.ShareLinkUncheckedUpdateWithoutActivitiesInput>
|
||||||
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateNestedManyWithoutWatermarkConfigInput = {
|
export type ShareLinkCreateNestedManyWithoutWatermarkConfigInput = {
|
||||||
create?: Prisma.XOR<Prisma.ShareLinkCreateWithoutWatermarkConfigInput, Prisma.ShareLinkUncheckedCreateWithoutWatermarkConfigInput> | Prisma.ShareLinkCreateWithoutWatermarkConfigInput[] | Prisma.ShareLinkUncheckedCreateWithoutWatermarkConfigInput[]
|
create?: Prisma.XOR<Prisma.ShareLinkCreateWithoutWatermarkConfigInput, Prisma.ShareLinkUncheckedCreateWithoutWatermarkConfigInput> | Prisma.ShareLinkCreateWithoutWatermarkConfigInput[] | Prisma.ShareLinkUncheckedCreateWithoutWatermarkConfigInput[]
|
||||||
connectOrCreate?: Prisma.ShareLinkCreateOrConnectWithoutWatermarkConfigInput | Prisma.ShareLinkCreateOrConnectWithoutWatermarkConfigInput[]
|
connectOrCreate?: Prisma.ShareLinkCreateOrConnectWithoutWatermarkConfigInput | Prisma.ShareLinkCreateOrConnectWithoutWatermarkConfigInput[]
|
||||||
@@ -738,12 +860,15 @@ export type ShareLinkCreateWithoutCreatorInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
project: Prisma.ProjectCreateNestedOneWithoutShareLinksInput
|
project: Prisma.ProjectCreateNestedOneWithoutShareLinksInput
|
||||||
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
||||||
|
activities?: Prisma.ShareActivityCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedCreateWithoutCreatorInput = {
|
export type ShareLinkUncheckedCreateWithoutCreatorInput = {
|
||||||
@@ -756,12 +881,15 @@ export type ShareLinkUncheckedCreateWithoutCreatorInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
projectId: string
|
projectId: string
|
||||||
rootFolderId: string
|
rootFolderId: string
|
||||||
watermarkConfigId?: string | null
|
watermarkConfigId?: string | null
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateOrConnectWithoutCreatorInput = {
|
export type ShareLinkCreateOrConnectWithoutCreatorInput = {
|
||||||
@@ -803,6 +931,8 @@ export type ShareLinkScalarWhereInput = {
|
|||||||
defaultSortOrder?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
defaultSortOrder?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
||||||
viewMode?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
viewMode?: Prisma.StringNullableFilter<"ShareLink"> | string | null
|
||||||
fieldVisibility?: Prisma.JsonNullableFilter<"ShareLink">
|
fieldVisibility?: Prisma.JsonNullableFilter<"ShareLink">
|
||||||
|
views?: Prisma.IntFilter<"ShareLink"> | number
|
||||||
|
lastViewedAt?: Prisma.DateTimeNullableFilter<"ShareLink"> | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
createdAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
updatedAt?: Prisma.DateTimeFilter<"ShareLink"> | Date | string
|
||||||
projectId?: Prisma.StringFilter<"ShareLink"> | string
|
projectId?: Prisma.StringFilter<"ShareLink"> | string
|
||||||
@@ -822,12 +952,15 @@ export type ShareLinkCreateWithoutProjectInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
||||||
|
activities?: Prisma.ShareActivityCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedCreateWithoutProjectInput = {
|
export type ShareLinkUncheckedCreateWithoutProjectInput = {
|
||||||
@@ -840,12 +973,15 @@ export type ShareLinkUncheckedCreateWithoutProjectInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
rootFolderId: string
|
rootFolderId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
watermarkConfigId?: string | null
|
watermarkConfigId?: string | null
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateOrConnectWithoutProjectInput = {
|
export type ShareLinkCreateOrConnectWithoutProjectInput = {
|
||||||
@@ -874,6 +1010,106 @@ export type ShareLinkUpdateManyWithWhereWithoutProjectInput = {
|
|||||||
data: Prisma.XOR<Prisma.ShareLinkUpdateManyMutationInput, Prisma.ShareLinkUncheckedUpdateManyWithoutProjectInput>
|
data: Prisma.XOR<Prisma.ShareLinkUpdateManyMutationInput, Prisma.ShareLinkUncheckedUpdateManyWithoutProjectInput>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ShareLinkCreateWithoutActivitiesInput = {
|
||||||
|
id?: string
|
||||||
|
name: string
|
||||||
|
expireAt?: Date | string | null
|
||||||
|
password?: string | null
|
||||||
|
isDisabled?: boolean
|
||||||
|
allowDownload?: boolean
|
||||||
|
defaultSortOrder?: string | null
|
||||||
|
viewMode?: string | null
|
||||||
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
|
createdAt?: Date | string
|
||||||
|
updatedAt?: Date | string
|
||||||
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
|
project: Prisma.ProjectCreateNestedOneWithoutShareLinksInput
|
||||||
|
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
||||||
|
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
||||||
|
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkUncheckedCreateWithoutActivitiesInput = {
|
||||||
|
id?: string
|
||||||
|
name: string
|
||||||
|
expireAt?: Date | string | null
|
||||||
|
password?: string | null
|
||||||
|
isDisabled?: boolean
|
||||||
|
allowDownload?: boolean
|
||||||
|
defaultSortOrder?: string | null
|
||||||
|
viewMode?: string | null
|
||||||
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
|
createdAt?: Date | string
|
||||||
|
updatedAt?: Date | string
|
||||||
|
projectId: string
|
||||||
|
rootFolderId: string
|
||||||
|
creatorId?: string | null
|
||||||
|
watermarkConfigId?: string | null
|
||||||
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkCreateOrConnectWithoutActivitiesInput = {
|
||||||
|
where: Prisma.ShareLinkWhereUniqueInput
|
||||||
|
create: Prisma.XOR<Prisma.ShareLinkCreateWithoutActivitiesInput, Prisma.ShareLinkUncheckedCreateWithoutActivitiesInput>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkUpsertWithoutActivitiesInput = {
|
||||||
|
update: Prisma.XOR<Prisma.ShareLinkUpdateWithoutActivitiesInput, Prisma.ShareLinkUncheckedUpdateWithoutActivitiesInput>
|
||||||
|
create: Prisma.XOR<Prisma.ShareLinkCreateWithoutActivitiesInput, Prisma.ShareLinkUncheckedCreateWithoutActivitiesInput>
|
||||||
|
where?: Prisma.ShareLinkWhereInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkUpdateToOneWithWhereWithoutActivitiesInput = {
|
||||||
|
where?: Prisma.ShareLinkWhereInput
|
||||||
|
data: Prisma.XOR<Prisma.ShareLinkUpdateWithoutActivitiesInput, Prisma.ShareLinkUncheckedUpdateWithoutActivitiesInput>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkUpdateWithoutActivitiesInput = {
|
||||||
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
name?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
expireAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
|
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
allowDownload?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
|
project?: Prisma.ProjectUpdateOneRequiredWithoutShareLinksNestedInput
|
||||||
|
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
||||||
|
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
||||||
|
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkUncheckedUpdateWithoutActivitiesInput = {
|
||||||
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
name?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
expireAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
|
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
allowDownload?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||||
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateWithoutWatermarkConfigInput = {
|
export type ShareLinkCreateWithoutWatermarkConfigInput = {
|
||||||
id?: string
|
id?: string
|
||||||
name: string
|
name: string
|
||||||
@@ -884,12 +1120,15 @@ export type ShareLinkCreateWithoutWatermarkConfigInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
project: Prisma.ProjectCreateNestedOneWithoutShareLinksInput
|
project: Prisma.ProjectCreateNestedOneWithoutShareLinksInput
|
||||||
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
rootFolder: Prisma.AssetCreateNestedOneWithoutShareLinkRootFolderInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
||||||
|
activities?: Prisma.ShareActivityCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedCreateWithoutWatermarkConfigInput = {
|
export type ShareLinkUncheckedCreateWithoutWatermarkConfigInput = {
|
||||||
@@ -902,12 +1141,15 @@ export type ShareLinkUncheckedCreateWithoutWatermarkConfigInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
projectId: string
|
projectId: string
|
||||||
rootFolderId: string
|
rootFolderId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateOrConnectWithoutWatermarkConfigInput = {
|
export type ShareLinkCreateOrConnectWithoutWatermarkConfigInput = {
|
||||||
@@ -946,12 +1188,15 @@ export type ShareLinkCreateWithoutRootFolderInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
project: Prisma.ProjectCreateNestedOneWithoutShareLinksInput
|
project: Prisma.ProjectCreateNestedOneWithoutShareLinksInput
|
||||||
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
creator?: Prisma.UserCreateNestedOneWithoutShareLinksInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
watermarkConfig?: Prisma.WatermarkConfigCreateNestedOneWithoutShareLinksInput
|
||||||
|
activities?: Prisma.ShareActivityCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedCreateWithoutRootFolderInput = {
|
export type ShareLinkUncheckedCreateWithoutRootFolderInput = {
|
||||||
@@ -964,12 +1209,15 @@ export type ShareLinkUncheckedCreateWithoutRootFolderInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
projectId: string
|
projectId: string
|
||||||
creatorId?: string | null
|
creatorId?: string | null
|
||||||
watermarkConfigId?: string | null
|
watermarkConfigId?: string | null
|
||||||
watermarkStatus?: $Enums.WatermarkStatus
|
watermarkStatus?: $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedCreateNestedManyWithoutShareLinkInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateOrConnectWithoutRootFolderInput = {
|
export type ShareLinkCreateOrConnectWithoutRootFolderInput = {
|
||||||
@@ -998,12 +1246,15 @@ export type ShareLinkUpdateWithoutRootFolderInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
project?: Prisma.ProjectUpdateOneRequiredWithoutShareLinksNestedInput
|
project?: Prisma.ProjectUpdateOneRequiredWithoutShareLinksNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
||||||
|
activities?: Prisma.ShareActivityUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateWithoutRootFolderInput = {
|
export type ShareLinkUncheckedUpdateWithoutRootFolderInput = {
|
||||||
@@ -1016,12 +1267,15 @@ export type ShareLinkUncheckedUpdateWithoutRootFolderInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkCreateManyCreatorInput = {
|
export type ShareLinkCreateManyCreatorInput = {
|
||||||
@@ -1034,6 +1288,8 @@ export type ShareLinkCreateManyCreatorInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
projectId: string
|
projectId: string
|
||||||
@@ -1052,12 +1308,15 @@ export type ShareLinkUpdateWithoutCreatorInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
project?: Prisma.ProjectUpdateOneRequiredWithoutShareLinksNestedInput
|
project?: Prisma.ProjectUpdateOneRequiredWithoutShareLinksNestedInput
|
||||||
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
||||||
|
activities?: Prisma.ShareActivityUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateWithoutCreatorInput = {
|
export type ShareLinkUncheckedUpdateWithoutCreatorInput = {
|
||||||
@@ -1070,12 +1329,15 @@ export type ShareLinkUncheckedUpdateWithoutCreatorInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateManyWithoutCreatorInput = {
|
export type ShareLinkUncheckedUpdateManyWithoutCreatorInput = {
|
||||||
@@ -1088,6 +1350,8 @@ export type ShareLinkUncheckedUpdateManyWithoutCreatorInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
@@ -1106,6 +1370,8 @@ export type ShareLinkCreateManyProjectInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
rootFolderId: string
|
rootFolderId: string
|
||||||
@@ -1124,12 +1390,15 @@ export type ShareLinkUpdateWithoutProjectInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
||||||
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
watermarkConfig?: Prisma.WatermarkConfigUpdateOneWithoutShareLinksNestedInput
|
||||||
|
activities?: Prisma.ShareActivityUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateWithoutProjectInput = {
|
export type ShareLinkUncheckedUpdateWithoutProjectInput = {
|
||||||
@@ -1142,12 +1411,15 @@ export type ShareLinkUncheckedUpdateWithoutProjectInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
watermarkConfigId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateManyWithoutProjectInput = {
|
export type ShareLinkUncheckedUpdateManyWithoutProjectInput = {
|
||||||
@@ -1160,6 +1432,8 @@ export type ShareLinkUncheckedUpdateManyWithoutProjectInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
@@ -1178,6 +1452,8 @@ export type ShareLinkCreateManyWatermarkConfigInput = {
|
|||||||
defaultSortOrder?: string | null
|
defaultSortOrder?: string | null
|
||||||
viewMode?: string | null
|
viewMode?: string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: number
|
||||||
|
lastViewedAt?: Date | string | null
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
projectId: string
|
projectId: string
|
||||||
@@ -1196,12 +1472,15 @@ export type ShareLinkUpdateWithoutWatermarkConfigInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
project?: Prisma.ProjectUpdateOneRequiredWithoutShareLinksNestedInput
|
project?: Prisma.ProjectUpdateOneRequiredWithoutShareLinksNestedInput
|
||||||
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
rootFolder?: Prisma.AssetUpdateOneRequiredWithoutShareLinkRootFolderNestedInput
|
||||||
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
creator?: Prisma.UserUpdateOneWithoutShareLinksNestedInput
|
||||||
|
activities?: Prisma.ShareActivityUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateWithoutWatermarkConfigInput = {
|
export type ShareLinkUncheckedUpdateWithoutWatermarkConfigInput = {
|
||||||
@@ -1214,12 +1493,15 @@ export type ShareLinkUncheckedUpdateWithoutWatermarkConfigInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
rootFolderId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
watermarkStatus?: Prisma.EnumWatermarkStatusFieldUpdateOperationsInput | $Enums.WatermarkStatus
|
||||||
|
activities?: Prisma.ShareActivityUncheckedUpdateManyWithoutShareLinkNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkUncheckedUpdateManyWithoutWatermarkConfigInput = {
|
export type ShareLinkUncheckedUpdateManyWithoutWatermarkConfigInput = {
|
||||||
@@ -1232,6 +1514,8 @@ export type ShareLinkUncheckedUpdateManyWithoutWatermarkConfigInput = {
|
|||||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
fieldVisibility?:PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||||
|
views?: Prisma.IntFieldUpdateOperationsInput | number
|
||||||
|
lastViewedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
projectId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
@@ -1241,6 +1525,35 @@ export type ShareLinkUncheckedUpdateManyWithoutWatermarkConfigInput = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count Type ShareLinkCountOutputType
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type ShareLinkCountOutputType = {
|
||||||
|
activities: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShareLinkCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
|
activities?: boolean | ShareLinkCountOutputTypeCountActivitiesArgs
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ShareLinkCountOutputType without action
|
||||||
|
*/
|
||||||
|
export type ShareLinkCountOutputTypeDefaultArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
|
/**
|
||||||
|
* Select specific fields to fetch from the ShareLinkCountOutputType
|
||||||
|
*/
|
||||||
|
select?: Prisma.ShareLinkCountOutputTypeSelect<ExtArgs> | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ShareLinkCountOutputType without action
|
||||||
|
*/
|
||||||
|
export type ShareLinkCountOutputTypeCountActivitiesArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
|
where?: Prisma.ShareActivityWhereInput
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export type ShareLinkSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
export type ShareLinkSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
||||||
id?: boolean
|
id?: boolean
|
||||||
@@ -1252,6 +1565,8 @@ export type ShareLinkSelect<ExtArgs extends runtime.Types.Extensions.InternalArg
|
|||||||
defaultSortOrder?: boolean
|
defaultSortOrder?: boolean
|
||||||
viewMode?: boolean
|
viewMode?: boolean
|
||||||
fieldVisibility?: boolean
|
fieldVisibility?: boolean
|
||||||
|
views?: boolean
|
||||||
|
lastViewedAt?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
projectId?: boolean
|
projectId?: boolean
|
||||||
@@ -1263,6 +1578,8 @@ export type ShareLinkSelect<ExtArgs extends runtime.Types.Extensions.InternalArg
|
|||||||
rootFolder?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
rootFolder?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
||||||
creator?: boolean | Prisma.ShareLink$creatorArgs<ExtArgs>
|
creator?: boolean | Prisma.ShareLink$creatorArgs<ExtArgs>
|
||||||
watermarkConfig?: boolean | Prisma.ShareLink$watermarkConfigArgs<ExtArgs>
|
watermarkConfig?: boolean | Prisma.ShareLink$watermarkConfigArgs<ExtArgs>
|
||||||
|
activities?: boolean | Prisma.ShareLink$activitiesArgs<ExtArgs>
|
||||||
|
_count?: boolean | Prisma.ShareLinkCountOutputTypeDefaultArgs<ExtArgs>
|
||||||
}, ExtArgs["result"]["shareLink"]>
|
}, ExtArgs["result"]["shareLink"]>
|
||||||
|
|
||||||
export type ShareLinkSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
export type ShareLinkSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
||||||
@@ -1275,6 +1592,8 @@ export type ShareLinkSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Ext
|
|||||||
defaultSortOrder?: boolean
|
defaultSortOrder?: boolean
|
||||||
viewMode?: boolean
|
viewMode?: boolean
|
||||||
fieldVisibility?: boolean
|
fieldVisibility?: boolean
|
||||||
|
views?: boolean
|
||||||
|
lastViewedAt?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
projectId?: boolean
|
projectId?: boolean
|
||||||
@@ -1298,6 +1617,8 @@ export type ShareLinkSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Ext
|
|||||||
defaultSortOrder?: boolean
|
defaultSortOrder?: boolean
|
||||||
viewMode?: boolean
|
viewMode?: boolean
|
||||||
fieldVisibility?: boolean
|
fieldVisibility?: boolean
|
||||||
|
views?: boolean
|
||||||
|
lastViewedAt?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
projectId?: boolean
|
projectId?: boolean
|
||||||
@@ -1321,6 +1642,8 @@ export type ShareLinkSelectScalar = {
|
|||||||
defaultSortOrder?: boolean
|
defaultSortOrder?: boolean
|
||||||
viewMode?: boolean
|
viewMode?: boolean
|
||||||
fieldVisibility?: boolean
|
fieldVisibility?: boolean
|
||||||
|
views?: boolean
|
||||||
|
lastViewedAt?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
projectId?: boolean
|
projectId?: boolean
|
||||||
@@ -1330,12 +1653,14 @@ export type ShareLinkSelectScalar = {
|
|||||||
watermarkStatus?: boolean
|
watermarkStatus?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShareLinkOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "name" | "expireAt" | "password" | "isDisabled" | "allowDownload" | "defaultSortOrder" | "viewMode" | "fieldVisibility" | "createdAt" | "updatedAt" | "projectId" | "rootFolderId" | "creatorId" | "watermarkConfigId" | "watermarkStatus", ExtArgs["result"]["shareLink"]>
|
export type ShareLinkOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "name" | "expireAt" | "password" | "isDisabled" | "allowDownload" | "defaultSortOrder" | "viewMode" | "fieldVisibility" | "views" | "lastViewedAt" | "createdAt" | "updatedAt" | "projectId" | "rootFolderId" | "creatorId" | "watermarkConfigId" | "watermarkStatus", ExtArgs["result"]["shareLink"]>
|
||||||
export type ShareLinkInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type ShareLinkInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
project?: boolean | Prisma.ProjectDefaultArgs<ExtArgs>
|
project?: boolean | Prisma.ProjectDefaultArgs<ExtArgs>
|
||||||
rootFolder?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
rootFolder?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
||||||
creator?: boolean | Prisma.ShareLink$creatorArgs<ExtArgs>
|
creator?: boolean | Prisma.ShareLink$creatorArgs<ExtArgs>
|
||||||
watermarkConfig?: boolean | Prisma.ShareLink$watermarkConfigArgs<ExtArgs>
|
watermarkConfig?: boolean | Prisma.ShareLink$watermarkConfigArgs<ExtArgs>
|
||||||
|
activities?: boolean | Prisma.ShareLink$activitiesArgs<ExtArgs>
|
||||||
|
_count?: boolean | Prisma.ShareLinkCountOutputTypeDefaultArgs<ExtArgs>
|
||||||
}
|
}
|
||||||
export type ShareLinkIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type ShareLinkIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
project?: boolean | Prisma.ProjectDefaultArgs<ExtArgs>
|
project?: boolean | Prisma.ProjectDefaultArgs<ExtArgs>
|
||||||
@@ -1357,6 +1682,7 @@ export type $ShareLinkPayload<ExtArgs extends runtime.Types.Extensions.InternalA
|
|||||||
rootFolder: Prisma.$AssetPayload<ExtArgs>
|
rootFolder: Prisma.$AssetPayload<ExtArgs>
|
||||||
creator: Prisma.$UserPayload<ExtArgs> | null
|
creator: Prisma.$UserPayload<ExtArgs> | null
|
||||||
watermarkConfig: Prisma.$WatermarkConfigPayload<ExtArgs> | null
|
watermarkConfig: Prisma.$WatermarkConfigPayload<ExtArgs> | null
|
||||||
|
activities: Prisma.$ShareActivityPayload<ExtArgs>[]
|
||||||
}
|
}
|
||||||
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
||||||
id: string
|
id: string
|
||||||
@@ -1371,6 +1697,8 @@ export type $ShareLinkPayload<ExtArgs extends runtime.Types.Extensions.InternalA
|
|||||||
* [ShareLinkFieldVisibility]
|
* [ShareLinkFieldVisibility]
|
||||||
*/
|
*/
|
||||||
fieldVisibility:PrismaJson.ShareLinkFieldVisibility | null
|
fieldVisibility:PrismaJson.ShareLinkFieldVisibility | null
|
||||||
|
views: number
|
||||||
|
lastViewedAt: Date | null
|
||||||
createdAt: Date
|
createdAt: Date
|
||||||
updatedAt: Date
|
updatedAt: Date
|
||||||
projectId: string
|
projectId: string
|
||||||
@@ -1776,6 +2104,7 @@ export interface Prisma__ShareLinkClient<T, Null = never, ExtArgs extends runtim
|
|||||||
rootFolder<T extends Prisma.AssetDefaultArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AssetDefaultArgs<ExtArgs>>): Prisma.Prisma__AssetClient<runtime.Types.Result.GetResult<Prisma.$AssetPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | Null, Null, ExtArgs, GlobalOmitOptions>
|
rootFolder<T extends Prisma.AssetDefaultArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AssetDefaultArgs<ExtArgs>>): Prisma.Prisma__AssetClient<runtime.Types.Result.GetResult<Prisma.$AssetPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | Null, Null, ExtArgs, GlobalOmitOptions>
|
||||||
creator<T extends Prisma.ShareLink$creatorArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.ShareLink$creatorArgs<ExtArgs>>): Prisma.Prisma__UserClient<runtime.Types.Result.GetResult<Prisma.$UserPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
creator<T extends Prisma.ShareLink$creatorArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.ShareLink$creatorArgs<ExtArgs>>): Prisma.Prisma__UserClient<runtime.Types.Result.GetResult<Prisma.$UserPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||||
watermarkConfig<T extends Prisma.ShareLink$watermarkConfigArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.ShareLink$watermarkConfigArgs<ExtArgs>>): Prisma.Prisma__WatermarkConfigClient<runtime.Types.Result.GetResult<Prisma.$WatermarkConfigPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
watermarkConfig<T extends Prisma.ShareLink$watermarkConfigArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.ShareLink$watermarkConfigArgs<ExtArgs>>): Prisma.Prisma__WatermarkConfigClient<runtime.Types.Result.GetResult<Prisma.$WatermarkConfigPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||||
|
activities<T extends Prisma.ShareLink$activitiesArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.ShareLink$activitiesArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ShareActivityPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||||
/**
|
/**
|
||||||
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
||||||
* @param onfulfilled The callback to execute when the Promise is resolved.
|
* @param onfulfilled The callback to execute when the Promise is resolved.
|
||||||
@@ -1814,6 +2143,8 @@ export interface ShareLinkFieldRefs {
|
|||||||
readonly defaultSortOrder: Prisma.FieldRef<"ShareLink", 'String'>
|
readonly defaultSortOrder: Prisma.FieldRef<"ShareLink", 'String'>
|
||||||
readonly viewMode: Prisma.FieldRef<"ShareLink", 'String'>
|
readonly viewMode: Prisma.FieldRef<"ShareLink", 'String'>
|
||||||
readonly fieldVisibility: Prisma.FieldRef<"ShareLink", 'Json'>
|
readonly fieldVisibility: Prisma.FieldRef<"ShareLink", 'Json'>
|
||||||
|
readonly views: Prisma.FieldRef<"ShareLink", 'Int'>
|
||||||
|
readonly lastViewedAt: Prisma.FieldRef<"ShareLink", 'DateTime'>
|
||||||
readonly createdAt: Prisma.FieldRef<"ShareLink", 'DateTime'>
|
readonly createdAt: Prisma.FieldRef<"ShareLink", 'DateTime'>
|
||||||
readonly updatedAt: Prisma.FieldRef<"ShareLink", 'DateTime'>
|
readonly updatedAt: Prisma.FieldRef<"ShareLink", 'DateTime'>
|
||||||
readonly projectId: Prisma.FieldRef<"ShareLink", 'String'>
|
readonly projectId: Prisma.FieldRef<"ShareLink", 'String'>
|
||||||
@@ -2259,6 +2590,30 @@ export type ShareLink$watermarkConfigArgs<ExtArgs extends runtime.Types.Extensio
|
|||||||
where?: Prisma.WatermarkConfigWhereInput
|
where?: Prisma.WatermarkConfigWhereInput
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ShareLink.activities
|
||||||
|
*/
|
||||||
|
export type ShareLink$activitiesArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
|
/**
|
||||||
|
* Select specific fields to fetch from the ShareActivity
|
||||||
|
*/
|
||||||
|
select?: Prisma.ShareActivitySelect<ExtArgs> | null
|
||||||
|
/**
|
||||||
|
* Omit specific fields from the ShareActivity
|
||||||
|
*/
|
||||||
|
omit?: Prisma.ShareActivityOmit<ExtArgs> | null
|
||||||
|
/**
|
||||||
|
* Choose, which related nodes to fetch as well
|
||||||
|
*/
|
||||||
|
include?: Prisma.ShareActivityInclude<ExtArgs> | null
|
||||||
|
where?: Prisma.ShareActivityWhereInput
|
||||||
|
orderBy?: Prisma.ShareActivityOrderByWithRelationInput | Prisma.ShareActivityOrderByWithRelationInput[]
|
||||||
|
cursor?: Prisma.ShareActivityWhereUniqueInput
|
||||||
|
take?: number
|
||||||
|
skip?: number
|
||||||
|
distinct?: Prisma.ShareActivityScalarFieldEnum | Prisma.ShareActivityScalarFieldEnum[]
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ShareLink without action
|
* ShareLink without action
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -217,6 +217,10 @@ export class PrismaTestingHelper<
|
|||||||
return this.proxyClient
|
return this.proxyClient
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public getUnderlyingClient(): T {
|
||||||
|
return this.prismaClient
|
||||||
|
}
|
||||||
|
|
||||||
public async startNewTransaction(opts?: { timeout?: number; maxWait?: number }): Promise<void> {
|
public async startNewTransaction(opts?: { timeout?: number; maxWait?: number }): Promise<void> {
|
||||||
if (this.endCurrentTransactionPromise != null) {
|
if (this.endCurrentTransactionPromise != null) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|||||||
@@ -238,9 +238,18 @@ export const createCommentRequestSchema = z.object({
|
|||||||
annotations: z.any().optional(),
|
annotations: z.any().optional(),
|
||||||
second: z.number().optional(),
|
second: z.number().optional(),
|
||||||
attachmentIds: z.array(z.string()),
|
attachmentIds: z.array(z.string()),
|
||||||
|
isInternal: z.boolean().optional(),
|
||||||
})
|
})
|
||||||
export type CreateCommentRequest = z.infer<typeof createCommentRequestSchema>
|
export type CreateCommentRequest = z.infer<typeof createCommentRequestSchema>
|
||||||
|
|
||||||
|
export const updateCommentRequestSchema = z.object({
|
||||||
|
message: z.string().optional(),
|
||||||
|
isInternal: z.boolean().optional(),
|
||||||
|
second: z.number().min(0).nullable().optional(),
|
||||||
|
attachmentIds: z.array(z.string()).optional(),
|
||||||
|
})
|
||||||
|
export type UpdateCommentRequest = z.infer<typeof updateCommentRequestSchema>
|
||||||
|
|
||||||
export const attachmentInfoSchema = z.object({
|
export const attachmentInfoSchema = z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
assetId: z.string(),
|
assetId: z.string(),
|
||||||
@@ -282,6 +291,7 @@ export type CommentInfo = {
|
|||||||
updatedAt: string
|
updatedAt: string
|
||||||
sessionId: string | null
|
sessionId: string | null
|
||||||
isCompleted: boolean
|
isCompleted: boolean
|
||||||
|
isInternal: boolean
|
||||||
completionLastChangedBy: AssetUserInfo | null
|
completionLastChangedBy: AssetUserInfo | null
|
||||||
reactionCounts: CommentReactionCount[]
|
reactionCounts: CommentReactionCount[]
|
||||||
}
|
}
|
||||||
@@ -301,6 +311,7 @@ export const commentInfoSchema: z.ZodType<CommentInfo> = z.object({
|
|||||||
updatedAt: z.string(),
|
updatedAt: z.string(),
|
||||||
sessionId: z.string().nullable(),
|
sessionId: z.string().nullable(),
|
||||||
isCompleted: z.boolean(),
|
isCompleted: z.boolean(),
|
||||||
|
isInternal: z.boolean(),
|
||||||
completionLastChangedBy: assetUserInfoSchema.nullable(),
|
completionLastChangedBy: assetUserInfoSchema.nullable(),
|
||||||
reactionCounts: z.array(commentReactionCountSchema),
|
reactionCounts: z.array(commentReactionCountSchema),
|
||||||
})
|
})
|
||||||
@@ -485,3 +496,18 @@ export type ExportCommentsRequest = z.infer<typeof exportCommentsRequestSchema>
|
|||||||
export const exportCommentsQuerySchema = exportCommentsRequestSchema
|
export const exportCommentsQuerySchema = exportCommentsRequestSchema
|
||||||
/** @deprecated Use ExportCommentsRequest */
|
/** @deprecated Use ExportCommentsRequest */
|
||||||
export type ExportCommentsQuery = ExportCommentsRequest
|
export type ExportCommentsQuery = ExportCommentsRequest
|
||||||
|
|
||||||
|
export const commentFrameQuerySchema = z.object({
|
||||||
|
second: z.coerce.number().refine((val) => Number.isFinite(val) && val >= 0, {
|
||||||
|
message: 'second must be a non-negative finite number',
|
||||||
|
}),
|
||||||
|
width: z.coerce.number().int().min(64).max(1280).optional().default(400),
|
||||||
|
})
|
||||||
|
export type CommentFrameQuery = z.infer<typeof commentFrameQuerySchema>
|
||||||
|
|
||||||
|
export const printCommentsResponseSchema = z.object({
|
||||||
|
asset: assetInfoSchema,
|
||||||
|
breadcrumbs: z.array(z.string()),
|
||||||
|
comments: z.array(commentInfoSchema),
|
||||||
|
})
|
||||||
|
export type PrintCommentsResponse = z.infer<typeof printCommentsResponseSchema>
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ export interface ShareLinkInfo {
|
|||||||
rootFolderId: string
|
rootFolderId: string
|
||||||
projectId: string
|
projectId: string
|
||||||
isExpired: boolean
|
isExpired: boolean
|
||||||
|
views: number
|
||||||
|
lastViewedAt: string | null
|
||||||
watermarkConfigId?: string | null
|
watermarkConfigId?: string | null
|
||||||
watermarkStatus?: 'disabled' | 'processing' | 'ready' | 'failed'
|
watermarkStatus?: 'disabled' | 'processing' | 'ready' | 'failed'
|
||||||
watermarkConfig?: {
|
watermarkConfig?: {
|
||||||
@@ -28,6 +30,22 @@ export interface ShareLinkInfo {
|
|||||||
creator?: { id: string; name: string; image?: string | null } | null
|
creator?: { id: string; name: string; image?: string | null } | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ShareActivityKind =
|
||||||
|
'share_viewed' | 'asset_viewed' | 'asset_downloaded' | 'comment_created'
|
||||||
|
|
||||||
|
export interface ShareActivityInfo {
|
||||||
|
id: string
|
||||||
|
kind: ShareActivityKind
|
||||||
|
createdAt: string
|
||||||
|
user: { name: string; image?: string } | null
|
||||||
|
asset: { id: string; name: string | null } | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export const recordShareViewRequestSchema = z.object({
|
||||||
|
assetId: z.string().min(1).optional(),
|
||||||
|
isShareEntry: z.boolean().optional(),
|
||||||
|
})
|
||||||
|
|
||||||
export const createShareLinkRequestSchema = z.object({
|
export const createShareLinkRequestSchema = z.object({
|
||||||
name: z.string().min(1),
|
name: z.string().min(1),
|
||||||
expireAt: z.string().datetime().optional(),
|
expireAt: z.string().datetime().optional(),
|
||||||
|
|||||||
@@ -22,11 +22,18 @@ export const createComment = defineOperation({
|
|||||||
.min(0)
|
.min(0)
|
||||||
.optional()
|
.optional()
|
||||||
.describe('Timecode in seconds on a video or audio file. Omit for other files.'),
|
.describe('Timecode in seconds on a video or audio file. Omit for other files.'),
|
||||||
|
isInternal: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Whether this is an internal comment hidden from public share links. Defaults to false.',
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
output: z.object({
|
output: z.object({
|
||||||
id: z.string().describe('The new comment ID.'),
|
id: z.string().describe('The new comment ID.'),
|
||||||
assetId: z.string().describe('The file the comment is on (the latest version for a stack).'),
|
assetId: z.string().describe('The file the comment is on (the latest version for a stack).'),
|
||||||
replyToId: z.string().nullable().describe('The thread it replies to, if any.'),
|
replyToId: z.string().nullable().describe('The thread it replies to, if any.'),
|
||||||
|
isInternal: z.boolean().describe('Whether the created comment is internal.'),
|
||||||
}),
|
}),
|
||||||
surfaces: ['agent', 'mcp', 'cli'],
|
surfaces: ['agent', 'mcp', 'cli'],
|
||||||
annotations: { readOnly: false, destructive: false },
|
annotations: { readOnly: false, destructive: false },
|
||||||
@@ -34,7 +41,7 @@ export const createComment = defineOperation({
|
|||||||
command: ['comment', 'add'],
|
command: ['comment', 'add'],
|
||||||
description: 'Comment on a file, or reply to a comment with --reply-to.',
|
description: 'Comment on a file, or reply to a comment with --reply-to.',
|
||||||
positional: ['assetId', 'message'],
|
positional: ['assetId', 'message'],
|
||||||
flags: { replyToId: ['--reply-to'], second: ['-t', '--at'] },
|
flags: { replyToId: ['--reply-to'], second: ['-t', '--at'], isInternal: ['--internal'] },
|
||||||
format: (output) => `Posted comment ${output.id}`,
|
format: (output) => `Posted comment ${output.id}`,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ const commentFields = {
|
|||||||
/** Whether markup was drawn on the frame or page. */
|
/** Whether markup was drawn on the frame or page. */
|
||||||
hasMarkup: z.boolean(),
|
hasMarkup: z.boolean(),
|
||||||
attachmentCount: z.number(),
|
attachmentCount: z.number(),
|
||||||
|
isInternal: z
|
||||||
|
.boolean()
|
||||||
|
.describe('Whether this comment is internal (hidden from public share links).'),
|
||||||
createdAt: z.string(),
|
createdAt: z.string(),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,9 +71,13 @@ export const listComments = defineOperation({
|
|||||||
for (const thread of output.data) {
|
for (const thread of output.data) {
|
||||||
const at = thread.second !== null ? ` @${thread.second}s` : ''
|
const at = thread.second !== null ? ` @${thread.second}s` : ''
|
||||||
const status = thread.resolved ? ' [resolved]' : ''
|
const status = thread.resolved ? ' [resolved]' : ''
|
||||||
lines.push(`${thread.id}${at}${status} ${thread.author.name}: ${thread.message}`)
|
const visibility = thread.isInternal ? ' [internal]' : ''
|
||||||
|
lines.push(
|
||||||
|
`${thread.id}${at}${status}${visibility} ${thread.author.name}: ${thread.message}`,
|
||||||
|
)
|
||||||
for (const reply of thread.replies) {
|
for (const reply of thread.replies) {
|
||||||
lines.push(` ↳ ${reply.id} ${reply.author.name}: ${reply.message}`)
|
const replyVisibility = reply.isInternal ? ' [internal]' : ''
|
||||||
|
lines.push(` ↳ ${reply.id}${replyVisibility} ${reply.author.name}: ${reply.message}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return lines.join('\n')
|
return lines.join('\n')
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { client } from './client'
|
||||||
|
|
||||||
|
export function requestShareDownload(
|
||||||
|
shareId: string,
|
||||||
|
fileId: string,
|
||||||
|
key: string,
|
||||||
|
purpose?: 'download' | 'prepare' | 'clipboard',
|
||||||
|
) {
|
||||||
|
const password = localStorage.getItem(`share_pwd_${shareId}`)
|
||||||
|
const postDownload = client.api.shares[':shareId'].files[':fileId']['download-url'].$post
|
||||||
|
const input = { param: { shareId, fileId }, json: { key, purpose } }
|
||||||
|
return password
|
||||||
|
? postDownload(input, { headers: { 'x-share-password': password } })
|
||||||
|
: postDownload(input)
|
||||||
|
}
|
||||||
@@ -392,4 +392,105 @@ describe('BreadcrumbNav component', () => {
|
|||||||
expect(screen.queryByText('Archived')).toBeNull()
|
expect(screen.queryByText('Archived')).toBeNull()
|
||||||
expect(screen.queryByText('已归档')).toBeNull()
|
expect(screen.queryByText('已归档')).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('renders Create Share Link and Add to Share Links at top of dropdown above Download for editors', () => {
|
||||||
|
const editorQueryClient = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false } },
|
||||||
|
})
|
||||||
|
editorQueryClient.setQueryData(['projects', 'proj-1', 'me'], { role: 'owner' })
|
||||||
|
const onCreateShareLink = vi.fn()
|
||||||
|
const onAddToShareLink = vi.fn()
|
||||||
|
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={editorQueryClient}>
|
||||||
|
<BreadcrumbNav
|
||||||
|
{...baseProps}
|
||||||
|
fileId="file-share"
|
||||||
|
currentAsset={{ id: 'file-share', name: 'review.mp4', type: 'file', version: 1 }}
|
||||||
|
allowDownload={true}
|
||||||
|
downloadInfo={{ originalKey: 'review.mp4' }}
|
||||||
|
shareLinks={[
|
||||||
|
{
|
||||||
|
id: 'share-1',
|
||||||
|
name: 'Client Cut',
|
||||||
|
isDisabled: false,
|
||||||
|
allowDownload: true,
|
||||||
|
hasPassword: false,
|
||||||
|
rootFolderId: 'rf-1',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
|
createdAt: '2026-11-24T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-11-24T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
onCreateShareLink={onCreateShareLink}
|
||||||
|
onAddToShareLink={onAddToShareLink}
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const triggerButton = screen.getByRole('button', { name: 'review.mp4' })
|
||||||
|
fireEvent.pointerDown(triggerButton, { button: 0, ctrlKey: false })
|
||||||
|
|
||||||
|
const items = screen.getAllByRole('menuitem')
|
||||||
|
expect(items[0].textContent).toContain('Create Share Link')
|
||||||
|
expect(items[1].textContent).toContain('Add to Share Links')
|
||||||
|
expect(items[2].textContent).toContain('Download')
|
||||||
|
|
||||||
|
fireEvent.click(items[0])
|
||||||
|
expect(onCreateShareLink).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
fireEvent.pointerDown(triggerButton, { button: 0, ctrlKey: false })
|
||||||
|
fireEvent.click(screen.getByText('Add to Share Links'))
|
||||||
|
fireEvent.click(screen.getByText('Client Cut'))
|
||||||
|
expect(onAddToShareLink).toHaveBeenCalledWith('share-1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hides share link options when public or when user lacks edit permission', () => {
|
||||||
|
const reviewerQueryClient = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false } },
|
||||||
|
})
|
||||||
|
reviewerQueryClient.setQueryData(['projects', 'proj-1', 'me'], { role: 'reviewer' })
|
||||||
|
|
||||||
|
const { rerender } = render(
|
||||||
|
<QueryClientProvider client={reviewerQueryClient}>
|
||||||
|
<BreadcrumbNav
|
||||||
|
{...baseProps}
|
||||||
|
fileId="file-share"
|
||||||
|
currentAsset={{ id: 'file-share', name: 'review.mp4', type: 'file' }}
|
||||||
|
onCreateShareLink={vi.fn()}
|
||||||
|
onAddToShareLink={vi.fn()}
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
fireEvent.pointerDown(screen.getByRole('button', { name: 'review.mp4' }), {
|
||||||
|
button: 0,
|
||||||
|
ctrlKey: false,
|
||||||
|
})
|
||||||
|
expect(screen.queryByText('Create Share Link')).toBeNull()
|
||||||
|
expect(screen.queryByText('Add to Share Links')).toBeNull()
|
||||||
|
|
||||||
|
const ownerQueryClient = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false } },
|
||||||
|
})
|
||||||
|
ownerQueryClient.setQueryData(['projects', 'proj-1', 'me'], { role: 'owner' })
|
||||||
|
|
||||||
|
rerender(
|
||||||
|
<QueryClientProvider client={ownerQueryClient}>
|
||||||
|
<BreadcrumbNav
|
||||||
|
{...baseProps}
|
||||||
|
isPublic={true}
|
||||||
|
fileId="file-share"
|
||||||
|
currentAsset={{ id: 'file-share', name: 'review.mp4', type: 'file' }}
|
||||||
|
onCreateShareLink={vi.fn()}
|
||||||
|
onAddToShareLink={vi.fn()}
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.queryByText('Create Share Link')).toBeNull()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { client } from '@/ui/api/client'
|
import { client } from '@/ui/api/client'
|
||||||
|
import { requestShareDownload } from '@/ui/api/share-download'
|
||||||
import { Badge } from '@/ui/components/ui/badge'
|
import { Badge } from '@/ui/components/ui/badge'
|
||||||
import { Button } from '@/ui/components/ui/button'
|
import { Button } from '@/ui/components/ui/button'
|
||||||
import {
|
import {
|
||||||
@@ -29,7 +30,7 @@ import {
|
|||||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||||
import { cn } from '@/ui/lib/utils'
|
import { cn } from '@/ui/lib/utils'
|
||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
import type { AncestorFolder } from '@shumai/dtos'
|
import type { AncestorFolder, ShareLinkInfo } from '@shumai/dtos'
|
||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
@@ -84,6 +85,10 @@ interface BreadcrumbNavProps {
|
|||||||
onDelete?: () => void
|
onDelete?: () => void
|
||||||
onArchive?: () => void
|
onArchive?: () => void
|
||||||
onRestoreArchive?: () => void
|
onRestoreArchive?: () => void
|
||||||
|
shareLinks?: ShareLinkInfo[]
|
||||||
|
onCreateShareLink?: () => void
|
||||||
|
onAddToShareLink?: (shareId: string) => void
|
||||||
|
isShareActionPending?: boolean
|
||||||
fileId?: string
|
fileId?: string
|
||||||
downloadInfo?: {
|
downloadInfo?: {
|
||||||
originalKey?: string
|
originalKey?: string
|
||||||
@@ -131,6 +136,10 @@ export function BreadcrumbNav({
|
|||||||
onDelete,
|
onDelete,
|
||||||
onArchive,
|
onArchive,
|
||||||
onRestoreArchive,
|
onRestoreArchive,
|
||||||
|
shareLinks,
|
||||||
|
onCreateShareLink,
|
||||||
|
onAddToShareLink,
|
||||||
|
isShareActionPending = false,
|
||||||
fileId,
|
fileId,
|
||||||
shareId,
|
shareId,
|
||||||
allowDownload = true,
|
allowDownload = true,
|
||||||
@@ -198,10 +207,7 @@ export function BreadcrumbNav({
|
|||||||
if (!fileId) return
|
if (!fileId) return
|
||||||
try {
|
try {
|
||||||
const res = shareId
|
const res = shareId
|
||||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
? await requestShareDownload(shareId, fileId, key)
|
||||||
param: { shareId, fileId },
|
|
||||||
json: { key },
|
|
||||||
})
|
|
||||||
: await client.api.files['download-url'].$post({
|
: await client.api.files['download-url'].$post({
|
||||||
json: { key, assetId: fileId },
|
json: { key, assetId: fileId },
|
||||||
})
|
})
|
||||||
@@ -318,6 +324,31 @@ export function BreadcrumbNav({
|
|||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
</div>
|
</div>
|
||||||
<DropdownMenuContent className="w-56" align="center">
|
<DropdownMenuContent className="w-56" align="center">
|
||||||
|
{canEdit && !isPublic && onCreateShareLink && (
|
||||||
|
<>
|
||||||
|
<DropdownMenuItem onClick={onCreateShareLink} disabled={isShareActionPending}>
|
||||||
|
{m.create_share_link()}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{shareLinks && shareLinks.length > 0 && onAddToShareLink && (
|
||||||
|
<DropdownMenuSub>
|
||||||
|
<DropdownMenuSubTrigger>{m.add_to_share_links()}</DropdownMenuSubTrigger>
|
||||||
|
<DropdownMenuPortal>
|
||||||
|
<DropdownMenuSubContent className="w-52">
|
||||||
|
{shareLinks.map((share) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={share.id}
|
||||||
|
disabled={isShareActionPending}
|
||||||
|
onClick={() => onAddToShareLink(share.id)}
|
||||||
|
>
|
||||||
|
<span className="truncate">{share.name}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuSubContent>
|
||||||
|
</DropdownMenuPortal>
|
||||||
|
</DropdownMenuSub>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{allowDownload &&
|
{allowDownload &&
|
||||||
(hasVideoTranscodes ? (
|
(hasVideoTranscodes ? (
|
||||||
<DropdownMenuSub>
|
<DropdownMenuSub>
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import { Check, ChevronDown, Globe, Lock } from 'lucide-react'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '../ui/dropdown-menu'
|
||||||
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
|
||||||
|
|
||||||
|
export interface CommentVisibilitySelectorProps {
|
||||||
|
isInternal: boolean
|
||||||
|
onChange: (isInternal: boolean) => void
|
||||||
|
disabled?: boolean
|
||||||
|
disabledTooltip?: string
|
||||||
|
align?: 'start' | 'center' | 'end'
|
||||||
|
side?: 'top' | 'bottom'
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CommentVisibilitySelector: React.FC<CommentVisibilitySelectorProps> = ({
|
||||||
|
isInternal,
|
||||||
|
onChange,
|
||||||
|
disabled = false,
|
||||||
|
disabledTooltip,
|
||||||
|
align = 'end',
|
||||||
|
side = 'top',
|
||||||
|
}) => {
|
||||||
|
const pillClasses = `inline-flex h-7 items-center gap-1 rounded-md border px-2 text-xs font-medium transition-colors shrink-0 select-none ${
|
||||||
|
isInternal
|
||||||
|
? 'border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300'
|
||||||
|
: 'border-border bg-muted/40 text-muted-foreground hover:text-foreground hover:bg-muted/80'
|
||||||
|
} ${disabled ? 'opacity-70 cursor-not-allowed' : 'cursor-pointer'}`
|
||||||
|
|
||||||
|
const pillContent = (
|
||||||
|
<>
|
||||||
|
{isInternal ? <Lock className="w-3 h-3 shrink-0" /> : <Globe className="w-3 h-3 shrink-0" />}
|
||||||
|
<span>{isInternal ? m.internal_comment_label() : m.public_comment_label()}</span>
|
||||||
|
{!disabled && <ChevronDown className="w-3 h-3 shrink-0 opacity-70" />}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
|
||||||
|
if (disabled) {
|
||||||
|
const button = (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled
|
||||||
|
data-testid="comment-visibility-trigger"
|
||||||
|
className={pillClasses}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{pillContent}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!disabledTooltip) return button
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className="inline-flex shrink-0">{button}</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">
|
||||||
|
<p className="text-xs">{disabledTooltip}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DropdownMenu modal={false}>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="comment-visibility-trigger"
|
||||||
|
className={pillClasses}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{pillContent}
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent
|
||||||
|
align={align}
|
||||||
|
side={side}
|
||||||
|
className="w-60"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<DropdownMenuItem
|
||||||
|
data-testid="comment-visibility-public"
|
||||||
|
className="flex items-start gap-2.5 py-2 cursor-pointer"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
onChange(false)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Globe className="w-4 h-4 mt-0.5 shrink-0 text-muted-foreground" />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-xs font-medium text-foreground">{m.public_comment()}</div>
|
||||||
|
<div className="text-[11px] text-muted-foreground leading-snug">
|
||||||
|
{m.public_comment_description()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{!isInternal && <Check className="w-4 h-4 mt-0.5 shrink-0 text-primary" />}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
data-testid="comment-visibility-internal"
|
||||||
|
className="flex items-start gap-2.5 py-2 cursor-pointer"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
onChange(true)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Lock className="w-4 h-4 mt-0.5 shrink-0 text-amber-600 dark:text-amber-400" />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-xs font-medium text-foreground">{m.internal_comment()}</div>
|
||||||
|
<div className="text-[11px] text-muted-foreground leading-snug">
|
||||||
|
{m.internal_comment_description()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{isInternal && <Check className="w-4 h-4 mt-0.5 shrink-0 text-primary" />}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
export const MENTION_CHIP_CLASS =
|
||||||
|
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
|
||||||
|
|
||||||
|
export function createMentionNode(user: { id: string; name: string }): HTMLSpanElement {
|
||||||
|
const mentionNode = document.createElement('span')
|
||||||
|
mentionNode.contentEditable = 'false'
|
||||||
|
mentionNode.dataset.type = 'mention'
|
||||||
|
mentionNode.dataset.id = user.id
|
||||||
|
mentionNode.className = MENTION_CHIP_CLASS
|
||||||
|
mentionNode.innerText = `@${user.name}`
|
||||||
|
return mentionNode
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeChildNodes(parent: Node): string {
|
||||||
|
let result = ''
|
||||||
|
parent.childNodes.forEach((node) => {
|
||||||
|
if (node.nodeType === Node.TEXT_NODE) {
|
||||||
|
result += node.textContent ?? ''
|
||||||
|
} else if (node.nodeType === Node.ELEMENT_NODE) {
|
||||||
|
const el = node as HTMLElement
|
||||||
|
if (el.dataset.type === 'mention') {
|
||||||
|
result += `<@${el.dataset.id}>`
|
||||||
|
} else if (el.tagName === 'BR') {
|
||||||
|
result += '\n'
|
||||||
|
} else if (el.tagName === 'DIV' || el.tagName === 'P') {
|
||||||
|
result += '\n' + serializeChildNodes(el)
|
||||||
|
} else {
|
||||||
|
result += serializeChildNodes(el)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeEditableContent(editor: HTMLElement): string {
|
||||||
|
return serializeChildNodes(editor)
|
||||||
|
.replace(/\u00A0/g, ' ')
|
||||||
|
.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hydrateEditableWithMentions(
|
||||||
|
editor: HTMLElement,
|
||||||
|
text: string,
|
||||||
|
resolveUserName: (userId: string) => string,
|
||||||
|
): void {
|
||||||
|
editor.innerHTML = ''
|
||||||
|
if (!text) return
|
||||||
|
|
||||||
|
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
|
||||||
|
for (const part of parts) {
|
||||||
|
if (!part) continue
|
||||||
|
if (/^<@[a-zA-Z0-9_-]+>$/.test(part)) {
|
||||||
|
const userId = part.slice(2, -1)
|
||||||
|
editor.appendChild(createMentionNode({ id: userId, name: resolveUserName(userId) }))
|
||||||
|
} else {
|
||||||
|
editor.appendChild(document.createTextNode(part))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,19 @@ vi.mock('@/ui/api/client', () => ({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
projects: {
|
||||||
|
':projectId': {
|
||||||
|
attachments: {
|
||||||
|
$post: vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
id: 'att-new-asset',
|
||||||
|
uploadUrl: 'https://upload.example.com/new.txt',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
comments: {
|
comments: {
|
||||||
':commentId': {
|
':commentId': {
|
||||||
complete: {
|
complete: {
|
||||||
@@ -39,6 +52,10 @@ vi.mock('@/ui/api/client', () => ({
|
|||||||
json: async () => ({ success: true }),
|
json: async () => ({ success: true }),
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
$patch: vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ id: 'msg-edit', message: 'Updated text', isInternal: true }),
|
||||||
|
}),
|
||||||
$delete: vi.fn().mockResolvedValue({
|
$delete: vi.fn().mockResolvedValue({
|
||||||
ok: true,
|
ok: true,
|
||||||
json: async () => ({ success: true }),
|
json: async () => ({ success: true }),
|
||||||
@@ -98,6 +115,7 @@ describe('MessageCard component', () => {
|
|||||||
updatedAt: '2026-08-20T10:30:00.000Z',
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
}
|
}
|
||||||
@@ -158,6 +176,7 @@ describe('MessageCard component', () => {
|
|||||||
updatedAt: '2026-08-20T10:30:00.000Z',
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [
|
reactionCounts: [
|
||||||
{
|
{
|
||||||
@@ -234,6 +253,7 @@ describe('MessageCard component', () => {
|
|||||||
updatedAt: '2026-08-20T10:30:00.000Z',
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [
|
reactionCounts: [
|
||||||
{
|
{
|
||||||
@@ -262,4 +282,189 @@ describe('MessageCard component', () => {
|
|||||||
fireEvent.click(partyBadge!)
|
fireEvent.click(partyBadge!)
|
||||||
expect(client.api.comments[':commentId'].reactions.$post).not.toHaveBeenCalled()
|
expect(client.api.comments[':commentId'].reactions.$post).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('displays lock icon for internal comments and hides it for public comments', () => {
|
||||||
|
const baseMessage: CommentInfo = {
|
||||||
|
id: 'msg-internal',
|
||||||
|
assetId: 'asset-1',
|
||||||
|
message: 'Private review note',
|
||||||
|
annotations: null,
|
||||||
|
second: null,
|
||||||
|
creator: { id: 'u-1', name: 'Bob Reviewer' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: true,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rerender } = render(
|
||||||
|
<MessageCard
|
||||||
|
teamId="team-1"
|
||||||
|
projectId="proj-1"
|
||||||
|
message={baseMessage}
|
||||||
|
getUser={() => ({ id: 'u-1', name: 'Bob Reviewer', role: 'reviewer' })}
|
||||||
|
onReply={vi.fn()}
|
||||||
|
/>,
|
||||||
|
{ wrapper: createWrapper() },
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.getByTestId('internal-comment-icon')).toBeDefined()
|
||||||
|
|
||||||
|
rerender(
|
||||||
|
<MessageCard
|
||||||
|
teamId="team-1"
|
||||||
|
projectId="proj-1"
|
||||||
|
message={{ ...baseMessage, isInternal: false }}
|
||||||
|
getUser={() => ({ id: 'u-1', name: 'Bob Reviewer', role: 'reviewer' })}
|
||||||
|
onReply={vi.fn()}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.queryByTestId('internal-comment-icon')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows author to edit text (preserving mentions), remove timestamp, remove attachment, toggle internal, and save', async () => {
|
||||||
|
const mockMessage: CommentInfo = {
|
||||||
|
id: 'msg-edit',
|
||||||
|
assetId: 'asset-1',
|
||||||
|
message: 'Hey <@u-2> check this frame',
|
||||||
|
annotations: null,
|
||||||
|
second: 5,
|
||||||
|
creator: { id: 'u-1', name: 'Bob Reviewer' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
id: 'join-1',
|
||||||
|
assetId: 'att-asset-1',
|
||||||
|
url: 'https://example.com/spec.pdf',
|
||||||
|
proxyType: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'join-2',
|
||||||
|
assetId: 'att-asset-2',
|
||||||
|
url: 'https://example.com/keep.png',
|
||||||
|
proxyType: 'image',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
mentions: [{ id: 'u-2', name: 'Alice' }],
|
||||||
|
createdAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
}
|
||||||
|
|
||||||
|
render(
|
||||||
|
<MessageCard
|
||||||
|
teamId="team-1"
|
||||||
|
projectId="proj-1"
|
||||||
|
message={mockMessage}
|
||||||
|
frameRate={30}
|
||||||
|
getUser={(id) =>
|
||||||
|
id === 'u-2'
|
||||||
|
? { id: 'u-2', name: 'Alice', role: 'editor' }
|
||||||
|
: { id, name: 'Unknown', role: 'unknown' }
|
||||||
|
}
|
||||||
|
onReply={vi.fn()}
|
||||||
|
/>,
|
||||||
|
{ wrapper: createWrapper() },
|
||||||
|
)
|
||||||
|
|
||||||
|
// Wait for team me query so author menu renders
|
||||||
|
const moreBtn = await screen.findByRole('button', { name: /more options/i })
|
||||||
|
fireEvent.pointerDown(moreBtn)
|
||||||
|
fireEvent.click(moreBtn)
|
||||||
|
|
||||||
|
const editMenuItem = await screen.findByText('Edit')
|
||||||
|
fireEvent.click(editMenuItem)
|
||||||
|
|
||||||
|
// Edit form should appear with hydrated mention chip, timestamp badge, and 2 attachments
|
||||||
|
expect(screen.getByTestId('comment-edit-form')).toBeDefined()
|
||||||
|
const mentionSpan = document.querySelector(
|
||||||
|
'[data-testid="edit-comment-input"] span[data-type="mention"]',
|
||||||
|
)
|
||||||
|
expect(mentionSpan?.getAttribute('data-id')).toBe('u-2')
|
||||||
|
expect(mentionSpan?.textContent).toBe('@Alice')
|
||||||
|
|
||||||
|
// Remove timestamp
|
||||||
|
fireEvent.click(screen.getByTestId('edit-comment-remove-timestamp'))
|
||||||
|
expect(screen.queryByTestId('edit-comment-timestamp')).toBeNull()
|
||||||
|
|
||||||
|
// Remove first attachment
|
||||||
|
fireEvent.click(screen.getByTestId('edit-remove-attachment-att-asset-1'))
|
||||||
|
expect(screen.getAllByTestId('edit-existing-attachment')).toHaveLength(1)
|
||||||
|
|
||||||
|
// Toggle Public -> Internal
|
||||||
|
const visTrigger = screen.getByTestId('comment-visibility-trigger')
|
||||||
|
fireEvent.pointerDown(visTrigger)
|
||||||
|
fireEvent.click(visTrigger)
|
||||||
|
fireEvent.click(await screen.findByTestId('comment-visibility-internal'))
|
||||||
|
|
||||||
|
// Save
|
||||||
|
fireEvent.click(screen.getByTestId('edit-comment-save'))
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(client.api.comments[':commentId'].$patch).toHaveBeenCalledWith({
|
||||||
|
param: { commentId: 'msg-edit' },
|
||||||
|
json: {
|
||||||
|
message: 'Hey <@u-2> check this frame',
|
||||||
|
isInternal: true,
|
||||||
|
second: null,
|
||||||
|
attachmentIds: ['att-asset-2'],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not show Edit menu item to non-author even if they are team owner', async () => {
|
||||||
|
vi.mocked(client.api.teams[':teamId'].me.$get).mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ id: 'u-owner', name: 'Owner', role: 'owner' }),
|
||||||
|
} as never)
|
||||||
|
|
||||||
|
const mockMessage: CommentInfo = {
|
||||||
|
id: 'msg-other',
|
||||||
|
assetId: 'asset-1',
|
||||||
|
message: 'Another user comment',
|
||||||
|
annotations: null,
|
||||||
|
second: null,
|
||||||
|
creator: { id: 'u-1', name: 'Bob Reviewer' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
}
|
||||||
|
|
||||||
|
render(
|
||||||
|
<MessageCard
|
||||||
|
teamId="team-1"
|
||||||
|
projectId="proj-1"
|
||||||
|
message={mockMessage}
|
||||||
|
getUser={() => ({ id: 'u-1', name: 'Bob Reviewer', role: 'reviewer' })}
|
||||||
|
onReply={vi.fn()}
|
||||||
|
/>,
|
||||||
|
{ wrapper: createWrapper() },
|
||||||
|
)
|
||||||
|
|
||||||
|
const moreBtn = await screen.findByRole('button', { name: /more options/i })
|
||||||
|
fireEvent.pointerDown(moreBtn)
|
||||||
|
fireEvent.click(moreBtn)
|
||||||
|
|
||||||
|
await screen.findByText('Delete')
|
||||||
|
expect(screen.queryByText('Edit')).toBeNull()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/component
|
|||||||
import type { CommentInfo, CommentReactionCount, UserInfo } from '@shumai/dtos'
|
import type { CommentInfo, CommentReactionCount, UserInfo } from '@shumai/dtos'
|
||||||
import type { MemberInfo } from '@/ui/stores/members'
|
import type { MemberInfo } from '@/ui/stores/members'
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { Download, FileText, MoreHorizontal, Smile, Trash2 } from 'lucide-react'
|
import { Download, FileText, Lock, MoreHorizontal, Pencil, Smile, Trash2 } from 'lucide-react'
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
import Markdown from 'react-markdown'
|
import Markdown from 'react-markdown'
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
|
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
|
||||||
@@ -33,11 +33,14 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/
|
|||||||
import { AgentSessionLogsDialog } from '../agent/agent-session-logs-dialog'
|
import { AgentSessionLogsDialog } from '../agent/agent-session-logs-dialog'
|
||||||
import { isImageFileName } from '@/ui/lib/media'
|
import { isImageFileName } from '@/ui/lib/media'
|
||||||
import { EmojiPickerPopover } from '../ui/emoji-picker'
|
import { EmojiPickerPopover } from '../ui/emoji-picker'
|
||||||
|
import { MessageEditForm } from './message-edit-form'
|
||||||
|
|
||||||
interface MessageCardProps {
|
interface MessageCardProps {
|
||||||
teamId?: string
|
teamId?: string
|
||||||
|
projectId?: string
|
||||||
message: CommentInfo
|
message: CommentInfo
|
||||||
isReply?: boolean
|
isReply?: boolean
|
||||||
|
parentIsInternal?: boolean
|
||||||
hasReplies?: boolean
|
hasReplies?: boolean
|
||||||
isLastReply?: boolean
|
isLastReply?: boolean
|
||||||
getUser: (id: string) => MemberInfo | UserInfo
|
getUser: (id: string) => MemberInfo | UserInfo
|
||||||
@@ -186,8 +189,10 @@ function updateCommentTreeReactions(
|
|||||||
|
|
||||||
export const MessageCard: React.FC<MessageCardProps> = ({
|
export const MessageCard: React.FC<MessageCardProps> = ({
|
||||||
teamId,
|
teamId,
|
||||||
|
projectId,
|
||||||
message: initialMessage,
|
message: initialMessage,
|
||||||
isReply,
|
isReply,
|
||||||
|
parentIsInternal,
|
||||||
hasReplies,
|
hasReplies,
|
||||||
isLastReply,
|
isLastReply,
|
||||||
getUser,
|
getUser,
|
||||||
@@ -210,6 +215,7 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
|||||||
const loadingText = (message.message && AI_PLACEHOLDERS[message.message]) || 'Generating...'
|
const loadingText = (message.message && AI_PLACEHOLDERS[message.message]) || 'Generating...'
|
||||||
|
|
||||||
const [isLogsOpen, setIsLogsOpen] = React.useState(false)
|
const [isLogsOpen, setIsLogsOpen] = React.useState(false)
|
||||||
|
const [isEditing, setIsEditing] = React.useState(false)
|
||||||
const [previewImage, setPreviewImage] = React.useState<{ url: string; name: string } | null>(null)
|
const [previewImage, setPreviewImage] = React.useState<{ url: string; name: string } | null>(null)
|
||||||
|
|
||||||
const { videoTimeDisplayMode } = useUiStore()
|
const { videoTimeDisplayMode } = useUiStore()
|
||||||
@@ -377,12 +383,17 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const canEdit = React.useMemo(() => {
|
||||||
|
if (isReadOnly || !me || message.sessionId) return false
|
||||||
|
return message.creator?.id === me.id
|
||||||
|
}, [isReadOnly, me, message.creator?.id, message.sessionId])
|
||||||
|
|
||||||
const canDelete = React.useMemo(() => {
|
const canDelete = React.useMemo(() => {
|
||||||
if (!me) return false
|
if (isReadOnly || !me) return false
|
||||||
if (me.role === 'owner') return true
|
if (me.role === 'owner') return true
|
||||||
if (message.creator?.id === me.id) return true
|
if (message.creator?.id === me.id) return true
|
||||||
return false
|
return false
|
||||||
}, [me, message.creator?.id])
|
}, [isReadOnly, me, message.creator?.id])
|
||||||
|
|
||||||
const renderFormattedMessage = (text: string) => {
|
const renderFormattedMessage = (text: string) => {
|
||||||
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
|
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
|
||||||
@@ -410,7 +421,9 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
onClick={onSelect}
|
onClick={() => {
|
||||||
|
if (!isEditing) onSelect?.()
|
||||||
|
}}
|
||||||
className={`relative flex gap-4 ${isReply ? 'mt-[-1px]' : 'mt-3'} mr-3 group p-3 py-4 border transition-all duration-200 cursor-pointer ${
|
className={`relative flex gap-4 ${isReply ? 'mt-[-1px]' : 'mt-3'} mr-3 group p-3 py-4 border transition-all duration-200 cursor-pointer ${
|
||||||
isReply
|
isReply
|
||||||
? isLastReply
|
? isLastReply
|
||||||
@@ -458,8 +471,26 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
|||||||
minute: '2-digit',
|
minute: '2-digit',
|
||||||
})}
|
})}
|
||||||
</span>
|
</span>
|
||||||
|
{message.isInternal && (
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center text-muted-foreground"
|
||||||
|
data-testid="internal-comment-icon"
|
||||||
|
aria-label={m.internal_comment_tooltip()}
|
||||||
|
>
|
||||||
|
<Lock className="w-3.5 h-3.5" />
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
<p className="text-xs">{m.internal_comment_tooltip()}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{canDelete && (
|
{(canEdit || canDelete) && !isEditing && (
|
||||||
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
|
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
|
||||||
<DropdownMenu modal={false}>
|
<DropdownMenu modal={false}>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
@@ -468,231 +499,262 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="h-6 w-6 cursor-pointer"
|
className="h-6 w-6 cursor-pointer"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
aria-label={m.more_options()}
|
||||||
>
|
>
|
||||||
<MoreHorizontal className="h-4 w-4 text-foreground/70" />
|
<MoreHorizontal className="h-4 w-4 text-foreground/70" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
|
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
|
||||||
<DropdownMenuItem
|
{canEdit && (
|
||||||
className="text-destructive focus:text-destructive cursor-pointer"
|
<DropdownMenuItem
|
||||||
onClick={(e) => {
|
className="cursor-pointer"
|
||||||
e.stopPropagation()
|
onClick={(e) => {
|
||||||
setIsDeleteDialogOpen(true)
|
e.stopPropagation()
|
||||||
}}
|
setIsEditing(true)
|
||||||
>
|
}}
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
>
|
||||||
<span>{m.delete()}</span>
|
<Pencil className="mr-2 h-4 w-4" />
|
||||||
</DropdownMenuItem>
|
<span>{m.edit()}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
{canDelete && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="text-destructive focus:text-destructive cursor-pointer"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
setIsDeleteDialogOpen(true)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
<span>{m.delete()}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flow-root mt-1">
|
{isEditing ? (
|
||||||
{message.second !== null && message.second !== undefined && frameRate && (
|
<MessageEditForm
|
||||||
<div className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-mono font-bold flex items-center gap-1">
|
projectId={projectId}
|
||||||
{displayTime}
|
teamId={teamId}
|
||||||
</div>
|
message={message}
|
||||||
)}
|
parentIsInternal={parentIsInternal}
|
||||||
|
getUser={getUser}
|
||||||
{hasDrawInfo && (
|
displayTime={displayTime}
|
||||||
<div
|
hasDrawInfo={hasDrawInfo}
|
||||||
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-bold flex items-center gap-1"
|
onCancel={() => setIsEditing(false)}
|
||||||
title="Contains drawing annotations"
|
onSaved={() => setIsEditing(false)}
|
||||||
>
|
/>
|
||||||
<DrawAnnotation className="w-3.5 h-3.5" />
|
) : (
|
||||||
</div>
|
<>
|
||||||
)}
|
<div className="flow-root mt-1">
|
||||||
|
{message.second !== null && message.second !== undefined && frameRate && (
|
||||||
{showSkeleton ? (
|
<div className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-mono font-bold flex items-center gap-1">
|
||||||
<div className="space-y-2">
|
{displayTime}
|
||||||
<Skeleton className="h-4 w-3/4" />
|
|
||||||
<Skeleton className="h-4 w-1/2" />
|
|
||||||
<span className="text-xs text-muted-foreground animate-pulse">{loadingText}</span>
|
|
||||||
</div>
|
|
||||||
) : message.sessionId ? (
|
|
||||||
<div className="text-sm leading-[1.8] prose prose-sm dark:prose-invert max-w-none break-words">
|
|
||||||
<Markdown>{preprocessMarkdown(message.message!)}</Markdown>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="text-sm leading-[1.8] whitespace-pre-wrap break-words text-wrap break-all">
|
|
||||||
{renderFormattedMessage(message.message!)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Attachments */}
|
|
||||||
{message.attachments && message.attachments.length > 0 && (
|
|
||||||
<div className="flex flex-col gap-1.5 mt-3 w-full max-w-full overflow-hidden">
|
|
||||||
{message.attachments.map((att) => {
|
|
||||||
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
|
|
||||||
const name = decodeURIComponent(rawName)
|
|
||||||
const isImage = isImageFileName(name)
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={att.id}
|
|
||||||
className={`group relative flex items-center w-full max-w-full rounded-lg border border-border bg-card hover:bg-muted/40 transition-colors overflow-hidden ${
|
|
||||||
isImage ? 'h-18 p-1.5 gap-2.5 cursor-pointer' : 'h-9 px-2.5 gap-2.5'
|
|
||||||
}`}
|
|
||||||
onClick={() => {
|
|
||||||
if (isImage) {
|
|
||||||
setPreviewImage({ url: att.url, name })
|
|
||||||
} else {
|
|
||||||
window.open(att.url, '_blank', 'noreferrer')
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isImage ? (
|
|
||||||
<div className="h-full aspect-square rounded-md overflow-hidden bg-muted/40 shrink-0">
|
|
||||||
<img
|
|
||||||
src={att.url}
|
|
||||||
alt={name}
|
|
||||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<FileText className="w-4 h-4 text-muted-foreground shrink-0" />
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="min-w-0 flex-1 overflow-hidden">
|
|
||||||
<p
|
|
||||||
className="text-xs font-medium text-foreground truncate block w-full"
|
|
||||||
title={name}
|
|
||||||
>
|
|
||||||
{name}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<a
|
|
||||||
href={att.url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noreferrer"
|
|
||||||
download={name}
|
|
||||||
className="p-1 text-muted-foreground hover:text-foreground shrink-0 rounded-md hover:bg-muted transition-colors opacity-0 group-hover:opacity-100"
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
title={m.download()}
|
|
||||||
>
|
|
||||||
<Download className="w-3.5 h-3.5" />
|
|
||||||
</a>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)}
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Agent Footer */}
|
{hasDrawInfo && (
|
||||||
{message.sessionId && (
|
<div
|
||||||
<div className="mt-3 pt-2 border-t border-foreground/5 flex items-center justify-between text-xs text-muted-foreground/60">
|
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-bold flex items-center gap-1"
|
||||||
<span className="flex items-center gap-1.5 font-medium text-muted-foreground/80">
|
title="Contains drawing annotations"
|
||||||
Created by Agent
|
>
|
||||||
</span>
|
<DrawAnnotation className="w-3.5 h-3.5" />
|
||||||
{isAdmin && (
|
</div>
|
||||||
<Button
|
)}
|
||||||
variant="outline"
|
|
||||||
size="xs"
|
{showSkeleton ? (
|
||||||
onClick={() => setIsLogsOpen(true)}
|
<div className="space-y-2">
|
||||||
className="cursor-pointer border-violet-500/20 text-violet-600 dark:text-violet-400 hover:bg-violet-500/10 hover:text-violet-700 hover:border-violet-500/30 font-semibold"
|
<Skeleton className="h-4 w-3/4" />
|
||||||
>
|
<Skeleton className="h-4 w-1/2" />
|
||||||
Logs
|
<span className="text-xs text-muted-foreground animate-pulse">{loadingText}</span>
|
||||||
</Button>
|
</div>
|
||||||
|
) : message.sessionId ? (
|
||||||
|
<div className="text-sm leading-[1.8] prose prose-sm dark:prose-invert max-w-none break-words">
|
||||||
|
<Markdown>{preprocessMarkdown(message.message!)}</Markdown>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-sm leading-[1.8] whitespace-pre-wrap break-words text-wrap break-all">
|
||||||
|
{renderFormattedMessage(message.message!)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Attachments */}
|
||||||
|
{message.attachments && message.attachments.length > 0 && (
|
||||||
|
<div className="flex flex-col gap-1.5 mt-3 w-full max-w-full overflow-hidden">
|
||||||
|
{message.attachments.map((att) => {
|
||||||
|
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
|
||||||
|
const name = decodeURIComponent(rawName)
|
||||||
|
const isImage = isImageFileName(name)
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={att.id}
|
||||||
|
className={`group relative flex items-center w-full max-w-full rounded-lg border border-border bg-card hover:bg-muted/40 transition-colors overflow-hidden ${
|
||||||
|
isImage ? 'h-18 p-1.5 gap-2.5 cursor-pointer' : 'h-9 px-2.5 gap-2.5'
|
||||||
|
}`}
|
||||||
|
onClick={() => {
|
||||||
|
if (isImage) {
|
||||||
|
setPreviewImage({ url: att.url, name })
|
||||||
|
} else {
|
||||||
|
window.open(att.url, '_blank', 'noreferrer')
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isImage ? (
|
||||||
|
<div className="h-full aspect-square rounded-md overflow-hidden bg-muted/40 shrink-0">
|
||||||
|
<img
|
||||||
|
src={att.url}
|
||||||
|
alt={name}
|
||||||
|
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<FileText className="w-4 h-4 text-muted-foreground shrink-0" />
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1 overflow-hidden">
|
||||||
|
<p
|
||||||
|
className="text-xs font-medium text-foreground truncate block w-full"
|
||||||
|
title={name}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a
|
||||||
|
href={att.url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
download={name}
|
||||||
|
className="p-1 text-muted-foreground hover:text-foreground shrink-0 rounded-md hover:bg-muted transition-colors opacity-0 group-hover:opacity-100"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
title={m.download()}
|
||||||
|
>
|
||||||
|
<Download className="w-3.5 h-3.5" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Reactions */}
|
{/* Agent Footer */}
|
||||||
{message.reactionCounts && message.reactionCounts.length > 0 && (
|
{message.sessionId && (
|
||||||
<div className="flex flex-wrap items-center gap-1.5 mt-2">
|
<div className="mt-3 pt-2 border-t border-foreground/5 flex items-center justify-between text-xs text-muted-foreground/60">
|
||||||
{message.reactionCounts.map((reaction) => {
|
<span className="flex items-center gap-1.5 font-medium text-muted-foreground/80">
|
||||||
const tooltipText = getReactionTooltip(reaction)
|
Created by Agent
|
||||||
return (
|
</span>
|
||||||
<TooltipProvider key={reaction.code}>
|
{isAdmin && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="xs"
|
||||||
|
onClick={() => setIsLogsOpen(true)}
|
||||||
|
className="cursor-pointer border-violet-500/20 text-violet-600 dark:text-violet-400 hover:bg-violet-500/10 hover:text-violet-700 hover:border-violet-500/30 font-semibold"
|
||||||
|
>
|
||||||
|
Logs
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Reactions */}
|
||||||
|
{message.reactionCounts && message.reactionCounts.length > 0 && (
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5 mt-2">
|
||||||
|
{message.reactionCounts.map((reaction) => {
|
||||||
|
const tooltipText = getReactionTooltip(reaction)
|
||||||
|
return (
|
||||||
|
<TooltipProvider key={reaction.code}>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={isReadOnly}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
handleToggleReaction(reaction.code)
|
||||||
|
}}
|
||||||
|
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-colors select-none ${
|
||||||
|
isReadOnly ? 'cursor-default' : 'cursor-pointer'
|
||||||
|
} ${
|
||||||
|
reaction.requestingUserReacted
|
||||||
|
? 'border-primary/40 bg-primary/10 font-medium'
|
||||||
|
: 'border-border/60 bg-muted/40 hover:bg-muted'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="text-sm leading-none">{reaction.code}</span>
|
||||||
|
<span className="text-xs font-semibold text-foreground">
|
||||||
|
{reaction.count}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>{tooltipText}</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<div className="mt-2 flex items-center justify-between w-full">
|
||||||
|
<button
|
||||||
|
onClick={handleReply}
|
||||||
|
className="text-xs font-medium text-gray-500 hover:text-blue-600 flex items-center gap-1 cursor-pointer"
|
||||||
|
>
|
||||||
|
{m.reply()}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{!isReadOnly && (
|
||||||
|
<EmojiPickerPopover
|
||||||
|
onEmojiSelect={(emoji) => handleToggleReaction(emoji)}
|
||||||
|
align="end"
|
||||||
|
side="top"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
className="flex items-center justify-center p-1 rounded-full text-gray-400 hover:text-foreground hover:bg-muted/80 transition-colors cursor-pointer"
|
||||||
|
title={m.add_reaction()}
|
||||||
|
>
|
||||||
|
<Smile className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
</EmojiPickerPopover>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<TooltipProvider>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
disabled={isReadOnly}
|
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
handleToggleReaction(reaction.code)
|
toggleComplete()
|
||||||
}}
|
}}
|
||||||
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-colors select-none ${
|
className={`flex items-center justify-center p-1 rounded-full transition-colors cursor-pointer ${
|
||||||
isReadOnly ? 'cursor-default' : 'cursor-pointer'
|
message.isCompleted
|
||||||
} ${
|
? 'text-green-500 hover:text-green-600 hover:bg-green-500/10'
|
||||||
reaction.requestingUserReacted
|
: 'text-gray-400 hover:text-green-500 hover:bg-green-500/10'
|
||||||
? 'border-primary/40 bg-primary/10 font-medium'
|
|
||||||
: 'border-border/60 bg-muted/40 hover:bg-muted'
|
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<span className="text-sm leading-none">{reaction.code}</span>
|
{message.isCompleted ? (
|
||||||
<span className="text-xs font-semibold text-foreground">
|
<FilledCircleCheck className="w-5 h-5" />
|
||||||
{reaction.count}
|
) : (
|
||||||
</span>
|
<UnfilledCircleCheck className="w-5 h-5" />
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>{tooltipText}</TooltipContent>
|
<TooltipContent>
|
||||||
|
{message.isCompleted ? m.mark_as_incomplete() : m.mark_as_complete()}
|
||||||
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
)
|
</div>
|
||||||
})}
|
</div>
|
||||||
</div>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
<div className="mt-2 flex items-center justify-between w-full">
|
|
||||||
<button
|
|
||||||
onClick={handleReply}
|
|
||||||
className="text-xs font-medium text-gray-500 hover:text-blue-600 flex items-center gap-1 cursor-pointer"
|
|
||||||
>
|
|
||||||
{m.reply()}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-1">
|
|
||||||
{!isReadOnly && (
|
|
||||||
<EmojiPickerPopover
|
|
||||||
onEmojiSelect={(emoji) => handleToggleReaction(emoji)}
|
|
||||||
align="end"
|
|
||||||
side="top"
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
className="flex items-center justify-center p-1 rounded-full text-gray-400 hover:text-foreground hover:bg-muted/80 transition-colors cursor-pointer"
|
|
||||||
title={m.add_reaction()}
|
|
||||||
>
|
|
||||||
<Smile className="w-5 h-5" />
|
|
||||||
</button>
|
|
||||||
</EmojiPickerPopover>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<button
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
toggleComplete()
|
|
||||||
}}
|
|
||||||
className={`flex items-center justify-center p-1 rounded-full transition-colors cursor-pointer ${
|
|
||||||
message.isCompleted
|
|
||||||
? 'text-green-500 hover:text-green-600 hover:bg-green-500/10'
|
|
||||||
: 'text-gray-400 hover:text-green-500 hover:bg-green-500/10'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{message.isCompleted ? (
|
|
||||||
<FilledCircleCheck className="w-5 h-5" />
|
|
||||||
) : (
|
|
||||||
<UnfilledCircleCheck className="w-5 h-5" />
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
{message.isCompleted ? m.mark_as_incomplete() : m.mark_as_complete()}
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Logs Dialog */}
|
{/* Logs Dialog */}
|
||||||
|
|||||||
@@ -0,0 +1,644 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react'
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type {
|
||||||
|
AttachmentInfo,
|
||||||
|
CommentInfo,
|
||||||
|
PostAttachmentRequest,
|
||||||
|
PostAttachmentResponse,
|
||||||
|
UserInfo,
|
||||||
|
} from '@shumai/dtos'
|
||||||
|
import { FileIcon, FileText, Paperclip, XIcon } from 'lucide-react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
import { client } from '@/ui/api/client'
|
||||||
|
import { isImageFileName } from '@/ui/lib/media'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import { useMemberStore, type MemberInfo } from '@/ui/stores/members'
|
||||||
|
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
|
||||||
|
import { Button } from '../ui/button'
|
||||||
|
import { DrawAnnotation } from '../ui/icons'
|
||||||
|
import { ProgressCircle } from '../ui/progress-circle'
|
||||||
|
import { Skeleton } from '../ui/skeleton'
|
||||||
|
import { CommentVisibilitySelector } from './comment-visibility-selector'
|
||||||
|
import {
|
||||||
|
createMentionNode,
|
||||||
|
hydrateEditableWithMentions,
|
||||||
|
serializeEditableContent,
|
||||||
|
} from './mention-utils'
|
||||||
|
import type { UploadingFile } from './message-input'
|
||||||
|
|
||||||
|
export interface MessageEditFormProps {
|
||||||
|
projectId?: string
|
||||||
|
teamId?: string
|
||||||
|
message: CommentInfo
|
||||||
|
parentIsInternal?: boolean
|
||||||
|
getUser: (id: string) => MemberInfo | UserInfo
|
||||||
|
displayTime: string
|
||||||
|
hasDrawInfo: boolean
|
||||||
|
onCancel: () => void
|
||||||
|
onSaved: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
type MentionEntity = { type: 'user'; data: MemberInfo }
|
||||||
|
|
||||||
|
export const MessageEditForm: React.FC<MessageEditFormProps> = ({
|
||||||
|
projectId,
|
||||||
|
teamId: propTeamId,
|
||||||
|
message,
|
||||||
|
parentIsInternal = false,
|
||||||
|
getUser,
|
||||||
|
displayTime,
|
||||||
|
hasDrawInfo,
|
||||||
|
onCancel,
|
||||||
|
onSaved,
|
||||||
|
}) => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const editorRef = useRef<HTMLDivElement>(null)
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
const mentionRangeRef = useRef<Range | null>(null)
|
||||||
|
const mentionListRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
const [editedIsInternal, setEditedIsInternal] = useState<boolean>(
|
||||||
|
parentIsInternal ? true : Boolean(message.isInternal),
|
||||||
|
)
|
||||||
|
const [editedSecond, setEditedSecond] = useState<number | null>(message.second ?? null)
|
||||||
|
const [keptAttachments, setKeptAttachments] = useState<AttachmentInfo[]>(
|
||||||
|
() => message.attachments ?? [],
|
||||||
|
)
|
||||||
|
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
|
||||||
|
const [hasText, setHasText] = useState<boolean>(() => Boolean((message.message ?? '').trim()))
|
||||||
|
|
||||||
|
const [showMentionList, setShowMentionList] = useState(false)
|
||||||
|
const [mentionQuery, setMentionQuery] = useState('')
|
||||||
|
const [highlightedIndex, setHighlightedIndex] = useState(0)
|
||||||
|
|
||||||
|
const { teamId: storeTeamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||||
|
const effectiveTeamId = propTeamId || storeTeamId
|
||||||
|
const {
|
||||||
|
members: storeMembers,
|
||||||
|
loading: membersLoading,
|
||||||
|
fetchMembers,
|
||||||
|
fetchProjectMembers,
|
||||||
|
} = useMemberStore()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (projectId && !effectiveTeamId) {
|
||||||
|
ensureTeamIdForProject(projectId)
|
||||||
|
}
|
||||||
|
}, [projectId, effectiveTeamId, ensureTeamIdForProject])
|
||||||
|
|
||||||
|
// Hydrate editor once on mount so background comment polling never overwrites draft edits.
|
||||||
|
useEffect(() => {
|
||||||
|
const editor = editorRef.current
|
||||||
|
if (!editor) return
|
||||||
|
|
||||||
|
const resolveUserName = (userId: string) => {
|
||||||
|
const fromMentions = message.mentions?.find((u) => u.id === userId)
|
||||||
|
if (fromMentions?.name) return fromMentions.name
|
||||||
|
const fromStore = getUser(userId)
|
||||||
|
return fromStore?.name || 'Unknown'
|
||||||
|
}
|
||||||
|
|
||||||
|
hydrateEditableWithMentions(editor, message.message ?? '', resolveUserName)
|
||||||
|
setHasText(Boolean(serializeEditableContent(editor)))
|
||||||
|
|
||||||
|
editor.focus()
|
||||||
|
const range = document.createRange()
|
||||||
|
const sel = window.getSelection()
|
||||||
|
range.selectNodeContents(editor)
|
||||||
|
range.collapse(false)
|
||||||
|
sel?.removeAllRanges()
|
||||||
|
sel?.addRange(range)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const { mutateAsync: uploadAttachment } = useMutation({
|
||||||
|
mutationFn: async ({
|
||||||
|
targetProjectId,
|
||||||
|
data,
|
||||||
|
}: {
|
||||||
|
targetProjectId: string
|
||||||
|
data: PostAttachmentRequest
|
||||||
|
}) => {
|
||||||
|
const res = await client.api.projects[':projectId'].attachments.$post({
|
||||||
|
param: { projectId: targetProjectId },
|
||||||
|
json: data,
|
||||||
|
})
|
||||||
|
if (!res.ok) throw new Error('Failed to create attachment')
|
||||||
|
return (await res.json()) as PostAttachmentResponse
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const { mutate: updateComment, isPending: isSaving } = useMutation({
|
||||||
|
mutationFn: async (payload: {
|
||||||
|
message: string
|
||||||
|
isInternal: boolean
|
||||||
|
second: number | null
|
||||||
|
attachmentIds: string[]
|
||||||
|
}) => {
|
||||||
|
const res = await client.api.comments[':commentId'].$patch({
|
||||||
|
param: { commentId: message.id },
|
||||||
|
json: payload,
|
||||||
|
})
|
||||||
|
if (!res.ok) throw new Error('Failed to update comment')
|
||||||
|
return await res.json()
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
predicate: (query) => query.queryKey.includes('comments'),
|
||||||
|
})
|
||||||
|
onSaved()
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error(m.failed_to_update_comment())
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const filteredEntities: MentionEntity[] = storeMembers
|
||||||
|
.filter((u) => u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()))
|
||||||
|
.map((u) => ({ type: 'user' as const, data: u }))
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setHighlightedIndex(0)
|
||||||
|
}, [mentionQuery, showMentionList])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mentionListRef.current
|
||||||
|
?.querySelector<HTMLElement>(`[data-index="${highlightedIndex}"]`)
|
||||||
|
?.scrollIntoView({ block: 'nearest' })
|
||||||
|
}, [highlightedIndex])
|
||||||
|
|
||||||
|
const getInitials = (name: string) =>
|
||||||
|
name
|
||||||
|
.split(' ')
|
||||||
|
.map((n) => n[0])
|
||||||
|
.slice(0, 2)
|
||||||
|
.join('')
|
||||||
|
.toUpperCase()
|
||||||
|
|
||||||
|
const handleInput = () => {
|
||||||
|
if (!editorRef.current) return
|
||||||
|
setHasText(Boolean(serializeEditableContent(editorRef.current)))
|
||||||
|
|
||||||
|
const sel = window.getSelection()
|
||||||
|
if (!sel || sel.rangeCount === 0) return
|
||||||
|
|
||||||
|
const range = sel.getRangeAt(0)
|
||||||
|
const node = range.startContainer
|
||||||
|
const offset = range.startOffset
|
||||||
|
|
||||||
|
if (node.nodeType === Node.TEXT_NODE) {
|
||||||
|
const textContent = node.textContent || ''
|
||||||
|
const textBeforeCursor = textContent.slice(0, offset)
|
||||||
|
const lastAtPos = textBeforeCursor.lastIndexOf('@')
|
||||||
|
|
||||||
|
if (lastAtPos !== -1) {
|
||||||
|
const isStartOfLine = lastAtPos === 0
|
||||||
|
const charBeforeAt = textBeforeCursor[lastAtPos - 1]
|
||||||
|
const hasSpaceBefore = isStartOfLine || /\s/.test(charBeforeAt)
|
||||||
|
|
||||||
|
if (hasSpaceBefore) {
|
||||||
|
const query = textBeforeCursor.slice(lastAtPos + 1)
|
||||||
|
if (!/\s/.test(query)) {
|
||||||
|
setMentionQuery(query)
|
||||||
|
setShowMentionList(true)
|
||||||
|
|
||||||
|
if (projectId) {
|
||||||
|
fetchProjectMembers(projectId, true, true)
|
||||||
|
} else if (effectiveTeamId) {
|
||||||
|
fetchMembers(effectiveTeamId, true, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const mentionRange = document.createRange()
|
||||||
|
mentionRange.setStart(node, lastAtPos)
|
||||||
|
mentionRange.setEnd(node, offset)
|
||||||
|
mentionRangeRef.current = mentionRange
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setShowMentionList(false)
|
||||||
|
mentionRangeRef.current = null
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSelectEntity = (entity: MentionEntity) => {
|
||||||
|
if (!mentionRangeRef.current || !editorRef.current) return
|
||||||
|
|
||||||
|
const range = mentionRangeRef.current
|
||||||
|
range.deleteContents()
|
||||||
|
|
||||||
|
const mentionNode = createMentionNode({ id: entity.data.id, name: entity.data.name })
|
||||||
|
range.insertNode(mentionNode)
|
||||||
|
|
||||||
|
const spaceNode = document.createTextNode('\u00A0')
|
||||||
|
mentionNode.after(spaceNode)
|
||||||
|
|
||||||
|
const newRange = document.createRange()
|
||||||
|
const sel = window.getSelection()
|
||||||
|
newRange.setStartAfter(spaceNode)
|
||||||
|
newRange.collapse(true)
|
||||||
|
sel?.removeAllRanges()
|
||||||
|
sel?.addRange(newRange)
|
||||||
|
|
||||||
|
setShowMentionList(false)
|
||||||
|
mentionRangeRef.current = null
|
||||||
|
setHasText(true)
|
||||||
|
editorRef.current.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
|
||||||
|
e.preventDefault()
|
||||||
|
const text = e.clipboardData.getData('text/plain')
|
||||||
|
if (!text) return
|
||||||
|
|
||||||
|
const success =
|
||||||
|
typeof document.execCommand === 'function' &&
|
||||||
|
document.queryCommandSupported?.('insertText') &&
|
||||||
|
document.execCommand('insertText', false, text)
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
const sel = window.getSelection()
|
||||||
|
if (sel && sel.rangeCount > 0) {
|
||||||
|
const range = sel.getRangeAt(0)
|
||||||
|
range.deleteContents()
|
||||||
|
const textNode = document.createTextNode(text)
|
||||||
|
range.insertNode(textNode)
|
||||||
|
range.setStartAfter(textNode)
|
||||||
|
range.collapse(true)
|
||||||
|
sel.removeAllRanges()
|
||||||
|
sel.addRange(range)
|
||||||
|
} else if (editorRef.current) {
|
||||||
|
editorRef.current.innerText += text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleInput()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFileSelect = useCallback(
|
||||||
|
async (e: ChangeEvent<HTMLInputElement>) => {
|
||||||
|
if (!e.target.files || !projectId) return
|
||||||
|
const newFiles = Array.from(e.target.files)
|
||||||
|
|
||||||
|
for (const file of newFiles) {
|
||||||
|
const tempId = `${Date.now()}-${Math.random()}-${file.name}`
|
||||||
|
setUploadingFiles((prev) => [...prev, { id: tempId, file, progress: 0 }])
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await uploadAttachment({
|
||||||
|
targetProjectId: projectId,
|
||||||
|
data: {
|
||||||
|
fileName: file.name,
|
||||||
|
contentType: file.type,
|
||||||
|
size: file.size,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (data.uploadUrl && data.id) {
|
||||||
|
await fetch(data.uploadUrl, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: file,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': file.type,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
setUploadingFiles((prev) =>
|
||||||
|
prev.map((uf) =>
|
||||||
|
uf.id === tempId ? { ...uf, progress: 100, attachmentId: data.id } : uf,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setUploadingFiles((prev) =>
|
||||||
|
prev.map((uf) =>
|
||||||
|
uf.id === tempId
|
||||||
|
? {
|
||||||
|
...uf,
|
||||||
|
error: error instanceof Error ? error.message : 'Upload failed',
|
||||||
|
}
|
||||||
|
: uf,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = ''
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[projectId, uploadAttachment],
|
||||||
|
)
|
||||||
|
|
||||||
|
const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error)
|
||||||
|
const uploadedAttachmentIds = uploadingFiles
|
||||||
|
.map((f) => f.attachmentId)
|
||||||
|
.filter((id): id is string => Boolean(id))
|
||||||
|
|
||||||
|
const effectiveIsInternal = parentIsInternal ? true : editedIsInternal
|
||||||
|
const canSave =
|
||||||
|
!isSaving &&
|
||||||
|
!isUploading &&
|
||||||
|
(hasText || keptAttachments.length > 0 || uploadedAttachmentIds.length > 0 || hasDrawInfo)
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
if (!editorRef.current || !canSave) return
|
||||||
|
const serialized = serializeEditableContent(editorRef.current)
|
||||||
|
const attachmentIds = [...keptAttachments.map((att) => att.assetId), ...uploadedAttachmentIds]
|
||||||
|
|
||||||
|
if (!serialized && attachmentIds.length === 0 && !hasDrawInfo) return
|
||||||
|
|
||||||
|
updateComment({
|
||||||
|
message: serialized,
|
||||||
|
isInternal: effectiveIsInternal,
|
||||||
|
second: editedSecond,
|
||||||
|
attachmentIds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||||
|
if (e.nativeEvent.isComposing) return
|
||||||
|
|
||||||
|
if (showMentionList && filteredEntities.length > 0) {
|
||||||
|
if (e.key === 'ArrowUp') {
|
||||||
|
e.preventDefault()
|
||||||
|
setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : filteredEntities.length - 1))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (e.key === 'ArrowDown') {
|
||||||
|
e.preventDefault()
|
||||||
|
setHighlightedIndex((prev) => (prev < filteredEntities.length - 1 ? prev + 1 : 0))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||||
|
e.preventDefault()
|
||||||
|
handleSelectEntity(filteredEntities[highlightedIndex])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
e.preventDefault()
|
||||||
|
setShowMentionList(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
e.preventDefault()
|
||||||
|
onCancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey) {
|
||||||
|
e.preventDefault()
|
||||||
|
handleSave()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="relative mt-1.5 flex flex-col gap-2"
|
||||||
|
data-testid="comment-edit-form"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{/* Mention dropdown */}
|
||||||
|
{showMentionList && (membersLoading || filteredEntities.length > 0) && (
|
||||||
|
<div
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
className="absolute bottom-full left-0 mb-2 w-60 rounded-xl shadow-lg border border-border overflow-hidden z-30 bg-popover text-popover-foreground"
|
||||||
|
>
|
||||||
|
<div ref={mentionListRef} className="max-h-48 overflow-y-auto">
|
||||||
|
{membersLoading ? (
|
||||||
|
<div className="p-2 space-y-2 animate-pulse">
|
||||||
|
<div className="flex items-center gap-2 px-2 py-1">
|
||||||
|
<Skeleton className="w-6 h-6 rounded-full" />
|
||||||
|
<Skeleton className="h-4 w-28" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
filteredEntities.map((item, index) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
key={item.data.id}
|
||||||
|
data-index={index}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={() => handleSelectEntity(item)}
|
||||||
|
onMouseEnter={() => setHighlightedIndex(index)}
|
||||||
|
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left cursor-pointer ${
|
||||||
|
index === highlightedIndex
|
||||||
|
? 'bg-accent text-accent-foreground'
|
||||||
|
: 'hover:bg-accent/50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Avatar className="w-6 h-6">
|
||||||
|
{item.data.image && (
|
||||||
|
<AvatarImage
|
||||||
|
src={item.data.image}
|
||||||
|
alt={item.data.name}
|
||||||
|
className="object-cover"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<AvatarFallback className="text-[10px] bg-purple-400 text-black font-semibold">
|
||||||
|
{getInitials(item.data.name)}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<span className="text-sm truncate">{item.data.name}</span>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Timestamp & Draw badges */}
|
||||||
|
{((editedSecond !== null && displayTime) || hasDrawInfo) && (
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
{editedSecond !== null && displayTime && (
|
||||||
|
<div
|
||||||
|
data-testid="edit-comment-timestamp"
|
||||||
|
className="inline-flex items-center gap-1 select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 pl-2 pr-1 py-0.5 rounded-sm text-xs leading-none font-mono font-bold"
|
||||||
|
>
|
||||||
|
<span>{displayTime}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setEditedSecond(null)}
|
||||||
|
className="p-0.5 rounded hover:bg-blue-200/70 dark:hover:bg-blue-800/70 cursor-pointer"
|
||||||
|
title={m.remove_timestamp()}
|
||||||
|
aria-label={m.remove_timestamp()}
|
||||||
|
data-testid="edit-comment-remove-timestamp"
|
||||||
|
>
|
||||||
|
<XIcon className="w-3 h-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{hasDrawInfo && (
|
||||||
|
<div
|
||||||
|
className="inline-flex items-center bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-0.5 rounded-sm text-xs leading-none font-bold"
|
||||||
|
title={m.contains_drawing_annotations()}
|
||||||
|
>
|
||||||
|
<DrawAnnotation className="w-3.5 h-3.5" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Editable text box */}
|
||||||
|
<div
|
||||||
|
ref={editorRef}
|
||||||
|
contentEditable={!isSaving}
|
||||||
|
suppressContentEditableWarning
|
||||||
|
onInput={handleInput}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
onPaste={handlePaste}
|
||||||
|
data-testid="edit-comment-input"
|
||||||
|
className="w-full min-h-[56px] max-h-48 overflow-y-auto rounded-lg border border-border bg-background px-2.5 py-2 text-sm leading-relaxed focus:outline-none focus:ring-1 focus:ring-ring whitespace-pre-wrap break-words"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Existing & Newly Uploaded Attachments */}
|
||||||
|
{(keptAttachments.length > 0 || uploadingFiles.length > 0) && (
|
||||||
|
<div className="flex flex-col gap-1.5 w-full max-w-full overflow-hidden">
|
||||||
|
{keptAttachments.map((att) => {
|
||||||
|
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
|
||||||
|
const name = decodeURIComponent(rawName)
|
||||||
|
const isImage = isImageFileName(name)
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={att.id}
|
||||||
|
data-testid="edit-existing-attachment"
|
||||||
|
className="flex items-center gap-2 rounded-lg border border-border bg-card px-2 py-1.5"
|
||||||
|
>
|
||||||
|
{isImage ? (
|
||||||
|
<img
|
||||||
|
src={att.url}
|
||||||
|
alt={name}
|
||||||
|
className="w-8 h-8 rounded object-cover shrink-0 bg-muted/40"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<FileText className="w-4 h-4 text-muted-foreground shrink-0" />
|
||||||
|
)}
|
||||||
|
<span className="text-xs font-medium text-foreground truncate flex-1 min-w-0">
|
||||||
|
{name}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
setKeptAttachments((prev) => prev.filter((item) => item.id !== att.id))
|
||||||
|
}
|
||||||
|
className="p-1 text-muted-foreground hover:text-destructive rounded hover:bg-muted transition-colors cursor-pointer shrink-0"
|
||||||
|
aria-label={`${m.delete()} ${name}`}
|
||||||
|
data-testid={`edit-remove-attachment-${att.assetId}`}
|
||||||
|
>
|
||||||
|
<XIcon className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
|
||||||
|
{uploadingFiles.map((upload) => (
|
||||||
|
<div
|
||||||
|
key={upload.id}
|
||||||
|
data-testid="edit-new-attachment"
|
||||||
|
className="flex items-center gap-2 rounded-lg border border-border bg-card px-2 py-1.5"
|
||||||
|
>
|
||||||
|
{upload.file.type.startsWith('image/') ? (
|
||||||
|
<div className="relative w-8 h-8 rounded overflow-hidden shrink-0 bg-muted/40">
|
||||||
|
<img
|
||||||
|
src={URL.createObjectURL(upload.file)}
|
||||||
|
alt={upload.file.name}
|
||||||
|
className={`w-full h-full object-cover ${!upload.attachmentId ? 'opacity-50' : ''}`}
|
||||||
|
/>
|
||||||
|
{!upload.attachmentId && !upload.error && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center bg-black/40">
|
||||||
|
<ProgressCircle progress={upload.progress} className="w-5 h-5" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<FileIcon className="w-4 h-4 text-muted-foreground shrink-0" />
|
||||||
|
)}
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<span className="text-xs font-medium text-foreground truncate block">
|
||||||
|
{upload.file.name}
|
||||||
|
</span>
|
||||||
|
{upload.error && (
|
||||||
|
<span className="text-[10px] text-destructive block truncate">
|
||||||
|
{upload.error}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
setUploadingFiles((prev) => prev.filter((item) => item.id !== upload.id))
|
||||||
|
}
|
||||||
|
className="p-1 text-muted-foreground hover:text-destructive rounded hover:bg-muted transition-colors cursor-pointer shrink-0"
|
||||||
|
aria-label={`${m.delete()} ${upload.file.name}`}
|
||||||
|
>
|
||||||
|
<XIcon className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Action bar: attach + visibility on left, cancel + save on right */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
{projectId && (
|
||||||
|
<>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
ref={fileInputRef}
|
||||||
|
className="hidden"
|
||||||
|
multiple
|
||||||
|
onChange={handleFileSelect}
|
||||||
|
data-testid="edit-comment-file-input"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-xs"
|
||||||
|
className="h-7 w-7 rounded-full cursor-pointer"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
title={m.attach_files()}
|
||||||
|
aria-label={m.attach_files()}
|
||||||
|
>
|
||||||
|
<Paperclip className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<CommentVisibilitySelector
|
||||||
|
isInternal={effectiveIsInternal}
|
||||||
|
onChange={setEditedIsInternal}
|
||||||
|
disabled={parentIsInternal}
|
||||||
|
disabledTooltip={m.internal_reply_locked_tooltip()}
|
||||||
|
align="start"
|
||||||
|
side="bottom"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="xs"
|
||||||
|
disabled={isSaving}
|
||||||
|
onClick={onCancel}
|
||||||
|
className="cursor-pointer"
|
||||||
|
>
|
||||||
|
{m.cancel()}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="xs"
|
||||||
|
disabled={!canSave}
|
||||||
|
onClick={handleSave}
|
||||||
|
className="cursor-pointer"
|
||||||
|
data-testid="edit-comment-save"
|
||||||
|
>
|
||||||
|
{m.save()}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -44,6 +44,7 @@ describe('ChatInput auto-mention on reply', () => {
|
|||||||
updatedAt: '2026-08-20T10:30:00.000Z',
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
}
|
}
|
||||||
@@ -89,6 +90,7 @@ describe('ChatInput auto-mention on reply', () => {
|
|||||||
updatedAt: '2026-08-20T10:30:00.000Z',
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
}
|
}
|
||||||
@@ -124,6 +126,7 @@ describe('ChatInput auto-mention on reply', () => {
|
|||||||
updatedAt: '2026-08-20T10:30:00.000Z',
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
}
|
}
|
||||||
@@ -142,6 +145,7 @@ describe('ChatInput auto-mention on reply', () => {
|
|||||||
updatedAt: '2026-08-20T10:31:00.000Z',
|
updatedAt: '2026-08-20T10:31:00.000Z',
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
completionLastChangedBy: null,
|
completionLastChangedBy: null,
|
||||||
reactionCounts: [],
|
reactionCounts: [],
|
||||||
}
|
}
|
||||||
@@ -164,4 +168,110 @@ describe('ChatInput auto-mention on reply', () => {
|
|||||||
expect(mentionSpans).toHaveLength(2)
|
expect(mentionSpans).toHaveLength(2)
|
||||||
expect(mentionSpans[1].getAttribute('data-id')).toBe('user-bob')
|
expect(mentionSpans[1].getAttribute('data-id')).toBe('user-bob')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('hides visibility selector when allowInternalComments is false', () => {
|
||||||
|
const onSendMessage = vi.fn()
|
||||||
|
render(<ChatInput projectId="proj-1" onSendMessage={onSendMessage} />, {
|
||||||
|
wrapper: createWrapper(),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(document.querySelector('[data-testid="comment-visibility-trigger"]')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('defaults to Public, switches to Internal via dropdown pill, and resets after send', () => {
|
||||||
|
const onSendMessage = vi.fn()
|
||||||
|
render(
|
||||||
|
<ChatInput projectId="proj-1" onSendMessage={onSendMessage} allowInternalComments={true} />,
|
||||||
|
{ wrapper: createWrapper() },
|
||||||
|
)
|
||||||
|
|
||||||
|
const trigger = document.querySelector(
|
||||||
|
'[data-testid="comment-visibility-trigger"]',
|
||||||
|
) as HTMLButtonElement
|
||||||
|
expect(trigger).not.toBeNull()
|
||||||
|
expect(trigger.textContent).toContain('Public')
|
||||||
|
|
||||||
|
// Open dropdown and choose Internal
|
||||||
|
fireEvent.pointerDown(trigger)
|
||||||
|
fireEvent.click(trigger)
|
||||||
|
const internalOption = document.querySelector(
|
||||||
|
'[data-testid="comment-visibility-internal"]',
|
||||||
|
) as HTMLElement
|
||||||
|
expect(internalOption).not.toBeNull()
|
||||||
|
fireEvent.click(internalOption)
|
||||||
|
|
||||||
|
expect(trigger.textContent).toContain('Internal')
|
||||||
|
|
||||||
|
// Type message and send
|
||||||
|
const editor = document.querySelector('[contenteditable="true"]') as HTMLDivElement
|
||||||
|
editor.innerText = 'Internal discussion'
|
||||||
|
fireEvent.input(editor)
|
||||||
|
|
||||||
|
const sendButton = document.querySelector('button .lucide-arrow-up')?.closest('button')
|
||||||
|
fireEvent.click(sendButton as HTMLButtonElement)
|
||||||
|
|
||||||
|
expect(onSendMessage).toHaveBeenCalledWith(
|
||||||
|
'Internal discussion',
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
[],
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
// Resets back to Public default after send
|
||||||
|
expect(trigger.textContent).toContain('Public')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('locks visibility to Internal when replying to an internal comment', () => {
|
||||||
|
const internalComment: CommentInfo = {
|
||||||
|
id: 'comment-int',
|
||||||
|
assetId: 'asset-1',
|
||||||
|
message: 'Private thread',
|
||||||
|
annotations: null,
|
||||||
|
second: null,
|
||||||
|
creator: { id: 'user-alice', name: 'Alice Smith' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
updatedAt: '2026-08-20T10:30:00.000Z',
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: true,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSendMessage = vi.fn()
|
||||||
|
render(
|
||||||
|
<ChatInput
|
||||||
|
projectId="proj-1"
|
||||||
|
onSendMessage={onSendMessage}
|
||||||
|
replyingTo={internalComment}
|
||||||
|
allowInternalComments={true}
|
||||||
|
/>,
|
||||||
|
{ wrapper: createWrapper() },
|
||||||
|
)
|
||||||
|
|
||||||
|
const trigger = document.querySelector(
|
||||||
|
'[data-testid="comment-visibility-trigger"]',
|
||||||
|
) as HTMLButtonElement
|
||||||
|
expect(trigger).not.toBeNull()
|
||||||
|
expect(trigger.textContent).toContain('Internal')
|
||||||
|
expect(trigger.disabled).toBe(true)
|
||||||
|
|
||||||
|
const sendButton = document.querySelector('button .lucide-arrow-up')?.closest('button')
|
||||||
|
fireEvent.click(sendButton as HTMLButtonElement)
|
||||||
|
|
||||||
|
expect(onSendMessage).toHaveBeenCalledWith(
|
||||||
|
'<@user-alice>',
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
'comment-int',
|
||||||
|
undefined,
|
||||||
|
[],
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/
|
|||||||
import { formatTimecode } from '../viewers/video/utils'
|
import { formatTimecode } from '../viewers/video/utils'
|
||||||
import { useUiStore } from '@/ui/stores/ui'
|
import { useUiStore } from '@/ui/stores/ui'
|
||||||
import { isImageFileName } from '@/ui/lib/media'
|
import { isImageFileName } from '@/ui/lib/media'
|
||||||
|
import { CommentVisibilitySelector } from './comment-visibility-selector'
|
||||||
|
import { createMentionNode, serializeEditableContent } from './mention-utils'
|
||||||
|
|
||||||
export type UploadingFile = {
|
export type UploadingFile = {
|
||||||
id: string // A unique ID for the file, e.g., timestamp + name
|
id: string // A unique ID for the file, e.g., timestamp + name
|
||||||
@@ -59,6 +61,7 @@ export interface ChatInputProps {
|
|||||||
replyToId?: string | null,
|
replyToId?: string | null,
|
||||||
second?: number | null,
|
second?: number | null,
|
||||||
attachedFilesMeta?: AttachedFileMeta[],
|
attachedFilesMeta?: AttachedFileMeta[],
|
||||||
|
isInternal?: boolean,
|
||||||
) => void
|
) => void
|
||||||
|
|
||||||
placeholder?: string
|
placeholder?: string
|
||||||
@@ -95,6 +98,9 @@ export interface ChatInputProps {
|
|||||||
replyingTo?: CommentInfo | null
|
replyingTo?: CommentInfo | null
|
||||||
onCancelReply?: () => void
|
onCancelReply?: () => void
|
||||||
|
|
||||||
|
// Internal Comments (hidden from public share links)
|
||||||
|
allowInternalComments?: boolean
|
||||||
|
|
||||||
// Bottom action bar extras (e.g. Agent Selector)
|
// Bottom action bar extras (e.g. Agent Selector)
|
||||||
bottomLeftExtra?: React.ReactNode
|
bottomLeftExtra?: React.ReactNode
|
||||||
|
|
||||||
@@ -127,6 +133,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
onSendMessage,
|
onSendMessage,
|
||||||
replyingTo,
|
replyingTo,
|
||||||
onCancelReply,
|
onCancelReply,
|
||||||
|
allowInternalComments = false,
|
||||||
placeholder,
|
placeholder,
|
||||||
initialText = '',
|
initialText = '',
|
||||||
value,
|
value,
|
||||||
@@ -156,6 +163,14 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
|
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
|
||||||
const [viewingFile, setViewingFile] = useState<File | null>(null)
|
const [viewingFile, setViewingFile] = useState<File | null>(null)
|
||||||
const [isTimestampEnabled, setIsTimestampEnabled] = useState(true)
|
const [isTimestampEnabled, setIsTimestampEnabled] = useState(true)
|
||||||
|
const [isInternal, setIsInternal] = useState(false)
|
||||||
|
|
||||||
|
const isReplyLockedInternal = Boolean(allowInternalComments && replyingTo?.isInternal)
|
||||||
|
const effectiveIsInternal = allowInternalComments
|
||||||
|
? isReplyLockedInternal
|
||||||
|
? true
|
||||||
|
: isInternal
|
||||||
|
: false
|
||||||
|
|
||||||
const effectiveAllowMentions = allowMentions ?? !disableMentions
|
const effectiveAllowMentions = allowMentions ?? !disableMentions
|
||||||
const effectiveAllowMarkup = allowMarkup ?? !hideAnnotationControl
|
const effectiveAllowMarkup = allowMarkup ?? !hideAnnotationControl
|
||||||
@@ -285,14 +300,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
(user: { id: string; name: string }) => {
|
(user: { id: string; name: string }) => {
|
||||||
if (!editorRef.current) return
|
if (!editorRef.current) return
|
||||||
|
|
||||||
const mentionNode = document.createElement('span')
|
const mentionNode = createMentionNode(user)
|
||||||
mentionNode.contentEditable = 'false'
|
|
||||||
mentionNode.dataset.type = 'mention'
|
|
||||||
mentionNode.dataset.id = user.id
|
|
||||||
mentionNode.className =
|
|
||||||
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
|
|
||||||
mentionNode.innerText = `@${user.name}`
|
|
||||||
|
|
||||||
const spaceNode = document.createTextNode('\u00A0')
|
const spaceNode = document.createTextNode('\u00A0')
|
||||||
|
|
||||||
editorRef.current.appendChild(mentionNode)
|
editorRef.current.appendChild(mentionNode)
|
||||||
@@ -457,13 +465,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
const range = mentionRangeRef.current
|
const range = mentionRangeRef.current
|
||||||
range.deleteContents()
|
range.deleteContents()
|
||||||
|
|
||||||
const mentionNode = document.createElement('span')
|
const mentionNode = createMentionNode({ id: entity.data.id, name: entity.data.name })
|
||||||
mentionNode.contentEditable = 'false'
|
|
||||||
mentionNode.dataset.type = 'mention'
|
|
||||||
mentionNode.dataset.id = entity.data.id
|
|
||||||
mentionNode.className =
|
|
||||||
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
|
|
||||||
mentionNode.innerText = `@${entity.data.name}`
|
|
||||||
|
|
||||||
range.insertNode(mentionNode)
|
range.insertNode(mentionNode)
|
||||||
|
|
||||||
@@ -652,26 +654,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
// Serialize content
|
// Serialize content
|
||||||
let processedText = ''
|
const processedText = serializeEditableContent(editorRef.current)
|
||||||
editorRef.current.childNodes.forEach((node) => {
|
|
||||||
if (node.nodeType === Node.TEXT_NODE) {
|
|
||||||
processedText += node.textContent
|
|
||||||
} else if (node.nodeType === Node.ELEMENT_NODE) {
|
|
||||||
const el = node as HTMLElement
|
|
||||||
if (el.dataset.type === 'mention') {
|
|
||||||
processedText += `<@${el.dataset.id}>`
|
|
||||||
} else if (el.tagName === 'BR') {
|
|
||||||
processedText += '\n'
|
|
||||||
} else if (el.tagName === 'DIV' || el.tagName === 'P') {
|
|
||||||
// contentEditable often uses div/p for new lines
|
|
||||||
processedText += '\n' + el.innerText
|
|
||||||
} else {
|
|
||||||
processedText += el.innerText
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
processedText = processedText.trim()
|
|
||||||
|
|
||||||
const hasWorkspaceAssets = (workspaceAssets?.length ?? 0) > 0
|
const hasWorkspaceAssets = (workspaceAssets?.length ?? 0) > 0
|
||||||
|
|
||||||
@@ -684,14 +667,26 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
onSendMessage(
|
if (allowInternalComments) {
|
||||||
processedText,
|
onSendMessage(
|
||||||
successfulAttachmentIds,
|
processedText,
|
||||||
annotations,
|
successfulAttachmentIds,
|
||||||
replyingTo?.id,
|
annotations,
|
||||||
effectiveAllowTimestamp && isTimestampEnabled ? currentTime : undefined,
|
replyingTo?.id,
|
||||||
successfulAttachedFilesMeta,
|
effectiveAllowTimestamp && isTimestampEnabled ? currentTime : undefined,
|
||||||
)
|
successfulAttachedFilesMeta,
|
||||||
|
effectiveIsInternal,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
onSendMessage(
|
||||||
|
processedText,
|
||||||
|
successfulAttachmentIds,
|
||||||
|
annotations,
|
||||||
|
replyingTo?.id,
|
||||||
|
effectiveAllowTimestamp && isTimestampEnabled ? currentTime : undefined,
|
||||||
|
successfulAttachedFilesMeta,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Reset editor
|
// Reset editor
|
||||||
editorRef.current.innerHTML = ''
|
editorRef.current.innerHTML = ''
|
||||||
@@ -703,6 +698,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
setIsDrawing(false)
|
setIsDrawing(false)
|
||||||
resetAnnotations()
|
resetAnnotations()
|
||||||
setShowMentionList(false)
|
setShowMentionList(false)
|
||||||
|
setIsInternal(false)
|
||||||
if (onCancelReply) onCancelReply()
|
if (onCancelReply) onCancelReply()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1177,17 +1173,27 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
|||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
) : (
|
) : (
|
||||||
<button
|
<div className="flex items-center gap-1.5 shrink-0">
|
||||||
onClick={handleSend}
|
{allowInternalComments && !isDrawing && (
|
||||||
disabled={!canSend || isUploading}
|
<CommentVisibilitySelector
|
||||||
className={`p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 ${
|
isInternal={effectiveIsInternal}
|
||||||
canSend && !isUploading
|
onChange={setIsInternal}
|
||||||
? 'bg-blue-600 text-white shadow-md hover:bg-blue-700 hover:shadow-lg transform hover:-translate-y-0.5 cursor-pointer'
|
disabled={isReplyLockedInternal}
|
||||||
: 'bg-gray-400 cursor-not-allowed opacity-50'
|
disabledTooltip={m.internal_reply_locked_tooltip()}
|
||||||
}`}
|
/>
|
||||||
>
|
)}
|
||||||
<ArrowUp className="w-4 h-4" />
|
<button
|
||||||
</button>
|
onClick={handleSend}
|
||||||
|
disabled={!canSend || isUploading}
|
||||||
|
className={`h-7 w-7 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 ${
|
||||||
|
canSend && !isUploading
|
||||||
|
? 'bg-blue-600 text-white shadow-md hover:bg-blue-700 hover:shadow-lg transform hover:-translate-y-0.5 cursor-pointer'
|
||||||
|
: 'bg-gray-400 cursor-not-allowed opacity-50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<ArrowUp className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ interface DateTimePickerProps {
|
|||||||
placeholder?: string
|
placeholder?: string
|
||||||
disabled?: boolean
|
disabled?: boolean
|
||||||
className?: string
|
className?: string
|
||||||
|
modal?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DateTimePicker({
|
export function DateTimePicker({
|
||||||
@@ -24,6 +25,7 @@ export function DateTimePicker({
|
|||||||
placeholder = 'Pick a date',
|
placeholder = 'Pick a date',
|
||||||
disabled,
|
disabled,
|
||||||
className,
|
className,
|
||||||
|
modal = false,
|
||||||
}: DateTimePickerProps) {
|
}: DateTimePickerProps) {
|
||||||
const [isOpen, setIsOpen] = React.useState(false)
|
const [isOpen, setIsOpen] = React.useState(false)
|
||||||
const [tempValue, setTempValue] = React.useState<Date | undefined>(value)
|
const [tempValue, setTempValue] = React.useState<Date | undefined>(value)
|
||||||
@@ -78,7 +80,7 @@ export function DateTimePicker({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
<Popover modal={modal} open={isOpen} onOpenChange={setIsOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import type { InferRequestType, InferResponseType } from 'hono/client'
|
|||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
|
||||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||||
|
import { useShareLinkActions } from '@/ui/hooks/use-share-link-actions'
|
||||||
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||||
import { formatSize } from '@/ui/lib/format'
|
import { formatSize } from '@/ui/lib/format'
|
||||||
import { useFieldStore } from '@/ui/stores/fields'
|
import { useFieldStore } from '@/ui/stores/fields'
|
||||||
@@ -15,9 +16,8 @@ import type {
|
|||||||
CreateUploadTaskRequest,
|
CreateUploadTaskRequest,
|
||||||
SearchCondition,
|
SearchCondition,
|
||||||
SearchSort,
|
SearchSort,
|
||||||
ShareLinkInfo,
|
|
||||||
} from '@shumai/dtos'
|
} from '@shumai/dtos'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { AlertTriangle, Download, FolderClock, Loader2 } from 'lucide-react'
|
import { AlertTriangle, Download, FolderClock, Loader2 } from 'lucide-react'
|
||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
@@ -27,6 +27,7 @@ import type { DragState } from '../dnd-types'
|
|||||||
import { MoveCopyDialog } from '../move-copy-dialog'
|
import { MoveCopyDialog } from '../move-copy-dialog'
|
||||||
import { ManageVersionsDialog } from '../manage-versions-dialog'
|
import { ManageVersionsDialog } from '../manage-versions-dialog'
|
||||||
import { FilePreviewDialog } from '../file-preview-dialog'
|
import { FilePreviewDialog } from '../file-preview-dialog'
|
||||||
|
import { ShareLinkCreatedDialog } from '../share-link-created-dialog'
|
||||||
import { FileBrowserContentSkeleton } from '../loading-skeletons'
|
import { FileBrowserContentSkeleton } from '../loading-skeletons'
|
||||||
import { FileBrowserContextMenu } from './context-menu'
|
import { FileBrowserContextMenu } from './context-menu'
|
||||||
import { FindSimilarDialog } from '../search/find-similar-dialog'
|
import { FindSimilarDialog } from '../search/find-similar-dialog'
|
||||||
@@ -309,18 +310,11 @@ export function FileBrowser({
|
|||||||
}
|
}
|
||||||
}, [isPreviewOpen, selectedIds.size, activePreviewItem])
|
}, [isPreviewOpen, selectedIds.size, activePreviewItem])
|
||||||
|
|
||||||
const { data: shareLinksData } = useQuery({
|
const { shareLinks, createShareLink, addToShareLink, createdShareLink, clearCreatedShareLink } =
|
||||||
queryKey: ['shares', projectId, 'list'],
|
useShareLinkActions({
|
||||||
queryFn: async () => {
|
projectId,
|
||||||
const res = await client.api.projects[':projectId'].shares.$get({
|
enabled: !isPublic,
|
||||||
param: { projectId },
|
})
|
||||||
query: { first: '100' },
|
|
||||||
})
|
|
||||||
if (!res.ok) throw new Error('Failed to fetch share links')
|
|
||||||
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
|
|
||||||
},
|
|
||||||
enabled: !!projectId && !isPublic,
|
|
||||||
})
|
|
||||||
|
|
||||||
const $reparent = client.api.projects[':projectId'].reparent.$post
|
const $reparent = client.api.projects[':projectId'].reparent.$post
|
||||||
const { mutate: reparentAssets } = useMutation<
|
const { mutate: reparentAssets } = useMutation<
|
||||||
@@ -413,71 +407,6 @@ export function FileBrowser({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const { mutate: createShareLink } = useMutation({
|
|
||||||
mutationFn: async (items: AssetInfo[]) => {
|
|
||||||
const name =
|
|
||||||
items.length === 1
|
|
||||||
? items[0].name
|
|
||||||
: new Date().toLocaleDateString('en-US', {
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
})
|
|
||||||
|
|
||||||
const res = await client.api.projects[':projectId'].shares.$post({
|
|
||||||
param: { projectId },
|
|
||||||
json: { name },
|
|
||||||
})
|
|
||||||
if (!res.ok) throw new Error('Failed to create share link')
|
|
||||||
const share = await res.json()
|
|
||||||
|
|
||||||
// Add assets to the new share link
|
|
||||||
const assetsRes = await client.api.shares[':shareId'].assets.$post({
|
|
||||||
param: { shareId: share.id },
|
|
||||||
json: { assetIds: items.map((i) => i.id!) },
|
|
||||||
})
|
|
||||||
if (!assetsRes.ok) throw new Error('Failed to add assets to share link')
|
|
||||||
|
|
||||||
return share
|
|
||||||
},
|
|
||||||
onSuccess: (share) => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
|
|
||||||
toast.success('Share link created', {
|
|
||||||
action: {
|
|
||||||
label: 'View',
|
|
||||||
onClick: () =>
|
|
||||||
navigate({
|
|
||||||
to: '/projects/$projectId/shares/$shareId',
|
|
||||||
params: { projectId, shareId: share.id },
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const { mutate: addToShareLink } = useMutation({
|
|
||||||
mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => {
|
|
||||||
const res = await client.api.shares[':shareId'].assets.$post({
|
|
||||||
param: { shareId },
|
|
||||||
json: { assetIds: items.map((i) => i.id!) },
|
|
||||||
})
|
|
||||||
if (!res.ok) throw new Error('Failed to add assets')
|
|
||||||
return { shareId }
|
|
||||||
},
|
|
||||||
onSuccess: ({ shareId }) => {
|
|
||||||
toast.success('Added to share link', {
|
|
||||||
action: {
|
|
||||||
label: 'View',
|
|
||||||
onClick: () =>
|
|
||||||
navigate({
|
|
||||||
to: '/projects/$projectId/shares/$shareId',
|
|
||||||
params: { projectId, shareId },
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const handleCreateShareLink = (items: AssetInfo[]) => {
|
const handleCreateShareLink = (items: AssetInfo[]) => {
|
||||||
createShareLink(items)
|
createShareLink(items)
|
||||||
}
|
}
|
||||||
@@ -1210,7 +1139,7 @@ export function FileBrowser({
|
|||||||
allowDownload={allowDownload}
|
allowDownload={allowDownload}
|
||||||
isRecentlyDeleted={isRecentlyDeleted}
|
isRecentlyDeleted={isRecentlyDeleted}
|
||||||
isRecents={isRecents}
|
isRecents={isRecents}
|
||||||
shareLinks={shareLinksData?.data ?? []}
|
shareLinks={shareLinks}
|
||||||
onCreateShareLink={handleCreateShareLink}
|
onCreateShareLink={handleCreateShareLink}
|
||||||
onAddToShareLink={handleAddToShareLink}
|
onAddToShareLink={handleAddToShareLink}
|
||||||
canEdit={canEdit}
|
canEdit={canEdit}
|
||||||
@@ -1411,6 +1340,15 @@ export function FileBrowser({
|
|||||||
isPublic={isPublic}
|
isPublic={isPublic}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<ShareLinkCreatedDialog
|
||||||
|
open={!!createdShareLink}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) clearCreatedShareLink()
|
||||||
|
}}
|
||||||
|
shareLink={createdShareLink}
|
||||||
|
projectId={projectId}
|
||||||
|
/>
|
||||||
|
|
||||||
<ArchiveConfirmDialog
|
<ArchiveConfirmDialog
|
||||||
open={archiveConfirmState.open}
|
open={archiveConfirmState.open}
|
||||||
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
|
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
|
||||||
|
|||||||
@@ -118,9 +118,10 @@ export function FileBrowserGridView({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let resizeFrame = 0
|
let resizeFrame = 0
|
||||||
|
const observeTarget = scrollContainerRef.current ?? containerRef.current
|
||||||
const updateCols = () => {
|
const updateCols = () => {
|
||||||
if (!containerRef.current) return
|
const width = containerRef.current?.offsetWidth ?? scrollContainerRef.current?.clientWidth
|
||||||
const width = containerRef.current.offsetWidth
|
if (!width) return
|
||||||
if (width < 640) setCols(2)
|
if (width < 640) setCols(2)
|
||||||
else if (width < 768) setCols(2)
|
else if (width < 768) setCols(2)
|
||||||
else if (width < 1024) setCols(3)
|
else if (width < 1024) setCols(3)
|
||||||
@@ -134,12 +135,12 @@ export function FileBrowserGridView({
|
|||||||
cancelAnimationFrame(resizeFrame)
|
cancelAnimationFrame(resizeFrame)
|
||||||
resizeFrame = requestAnimationFrame(updateCols)
|
resizeFrame = requestAnimationFrame(updateCols)
|
||||||
})
|
})
|
||||||
if (containerRef.current) observer.observe(containerRef.current)
|
if (observeTarget) observer.observe(observeTarget)
|
||||||
return () => {
|
return () => {
|
||||||
observer.disconnect()
|
observer.disconnect()
|
||||||
cancelAnimationFrame(resizeFrame)
|
cancelAnimationFrame(resizeFrame)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [scrollContainerRef])
|
||||||
|
|
||||||
const rows = useMemo(() => {
|
const rows = useMemo(() => {
|
||||||
const list: (
|
const list: (
|
||||||
@@ -191,6 +192,7 @@ export function FileBrowserGridView({
|
|||||||
),
|
),
|
||||||
overscan: 5,
|
overscan: 5,
|
||||||
paddingEnd: 240,
|
paddingEnd: 240,
|
||||||
|
useFlushSync: false,
|
||||||
})
|
})
|
||||||
|
|
||||||
const virtualItems = rowVirtualizer.getVirtualItems()
|
const virtualItems = rowVirtualizer.getVirtualItems()
|
||||||
|
|||||||
@@ -333,6 +333,7 @@ export function FileBrowserListView({
|
|||||||
),
|
),
|
||||||
overscan: 10,
|
overscan: 10,
|
||||||
paddingEnd: 240,
|
paddingEnd: 240,
|
||||||
|
useFlushSync: false,
|
||||||
})
|
})
|
||||||
|
|
||||||
const virtualItems = rowVirtualizer.getVirtualItems()
|
const virtualItems = rowVirtualizer.getVirtualItems()
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { client } from '@/ui/api/client'
|
import { client } from '@/ui/api/client'
|
||||||
|
import { requestShareDownload } from '@/ui/api/share-download'
|
||||||
import type { AssetInfo } from '@shumai/dtos'
|
import type { AssetInfo } from '@shumai/dtos'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard'
|
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard'
|
||||||
@@ -39,18 +40,7 @@ export function useCopyActions({
|
|||||||
if (transcode?.url) return transcode.url
|
if (transcode?.url) return transcode.url
|
||||||
if (transcode?.key && item.id) {
|
if (transcode?.key && item.id) {
|
||||||
if (isPublic && shareId) {
|
if (isPublic && shareId) {
|
||||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
const res = await requestShareDownload(shareId, item.id, transcode.key, 'clipboard')
|
||||||
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
|
|
||||||
{
|
|
||||||
param: { shareId, fileId: item.id },
|
|
||||||
json: { key: transcode.key },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'x-share-password': password,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const { url } = await res.json()
|
const { url } = await res.json()
|
||||||
return url
|
return url
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { client } from '@/ui/api/client'
|
import { client } from '@/ui/api/client'
|
||||||
|
import { requestShareDownload } from '@/ui/api/share-download'
|
||||||
import type { AssetInfo } from '@shumai/dtos'
|
import type { AssetInfo } from '@shumai/dtos'
|
||||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||||
@@ -20,6 +21,18 @@ interface UseFileActionsProps {
|
|||||||
shareId?: string
|
shareId?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function requestShareDownloadUrl(
|
||||||
|
shareId: string,
|
||||||
|
fileId: string,
|
||||||
|
key: string,
|
||||||
|
purpose: 'prepare' | 'download',
|
||||||
|
) {
|
||||||
|
const response = await requestShareDownload(shareId, fileId, key, purpose)
|
||||||
|
if (response.ok) return (await response.json()).url
|
||||||
|
}
|
||||||
|
|
||||||
|
type DownloadFile = { id: string; name: string; url: string; shareDownloadKey?: string }
|
||||||
|
|
||||||
export function useFileActions({
|
export function useFileActions({
|
||||||
teamId,
|
teamId,
|
||||||
projectId,
|
projectId,
|
||||||
@@ -35,9 +48,7 @@ export function useFileActions({
|
|||||||
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
|
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
|
||||||
const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false)
|
const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false)
|
||||||
const [isLoadingLinks, setIsLoadingLinks] = useState(false)
|
const [isLoadingLinks, setIsLoadingLinks] = useState(false)
|
||||||
const [resolvedFiles, setResolvedFiles] = useState<
|
const [resolvedFiles, setResolvedFiles] = useState<DownloadFile[]>([])
|
||||||
Array<{ id: string; name: string; url: string }>
|
|
||||||
>([])
|
|
||||||
const [skippedArchivedCount, setSkippedArchivedCount] = useState(0)
|
const [skippedArchivedCount, setSkippedArchivedCount] = useState(0)
|
||||||
const [archiveConfirmState, setArchiveConfirmState] = useState<{
|
const [archiveConfirmState, setArchiveConfirmState] = useState<{
|
||||||
open: boolean
|
open: boolean
|
||||||
@@ -257,8 +268,7 @@ export function useFileActions({
|
|||||||
setSkippedArchivedCount(0)
|
setSkippedArchivedCount(0)
|
||||||
try {
|
try {
|
||||||
if (isPublic && shareId) {
|
if (isPublic && shareId) {
|
||||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
const links: DownloadFile[] = []
|
||||||
const links: Array<{ id: string; name: string; url: string }> = []
|
|
||||||
let skipped = 0
|
let skipped = 0
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
if (
|
if (
|
||||||
@@ -271,20 +281,9 @@ export function useFileActions({
|
|||||||
}
|
}
|
||||||
const key = item.media?.original?.key
|
const key = item.media?.original?.key
|
||||||
if (!key || !item.id) continue
|
if (!key || !item.id) continue
|
||||||
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
|
const url = await requestShareDownloadUrl(shareId, item.id, key, 'prepare')
|
||||||
{
|
if (url) {
|
||||||
param: { shareId, fileId: item.id },
|
links.push({ id: item.id, name: item.name || 'download', url, shareDownloadKey: key })
|
||||||
json: { key },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'x-share-password': password,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if (res.ok) {
|
|
||||||
const { url } = await res.json()
|
|
||||||
links.push({ id: item.id, name: item.name || 'download', url })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setSkippedArchivedCount(skipped)
|
setSkippedArchivedCount(skipped)
|
||||||
@@ -407,9 +406,21 @@ export function useFileActions({
|
|||||||
|
|
||||||
const runQueue = async () => {
|
const runQueue = async () => {
|
||||||
const batchSize = 5
|
const batchSize = 5
|
||||||
|
let failed = 0
|
||||||
for (let i = 0; i < files.length; i += batchSize) {
|
for (let i = 0; i < files.length; i += batchSize) {
|
||||||
const chunk = files.slice(i, i + batchSize)
|
const chunk = files.slice(i, i + batchSize)
|
||||||
for (const file of chunk) {
|
const urls = await Promise.allSettled(
|
||||||
|
chunk.map((file) =>
|
||||||
|
shareId && file.shareDownloadKey
|
||||||
|
? requestShareDownloadUrl(shareId, file.id, file.shareDownloadKey, 'download')
|
||||||
|
: file.url,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for (const result of urls) {
|
||||||
|
if (result.status !== 'fulfilled' || !result.value) {
|
||||||
|
failed++
|
||||||
|
continue
|
||||||
|
}
|
||||||
// Use a hidden iframe instead of an anchor with target="_blank".
|
// Use a hidden iframe instead of an anchor with target="_blank".
|
||||||
// Download URLs respond with Content-Disposition: attachment, so the
|
// Download URLs respond with Content-Disposition: attachment, so the
|
||||||
// browser starts the download in the background: no flash of a tab
|
// browser starts the download in the background: no flash of a tab
|
||||||
@@ -417,7 +428,7 @@ export function useFileActions({
|
|||||||
// the hidden iframe instead of navigating the SPA tab away.
|
// the hidden iframe instead of navigating the SPA tab away.
|
||||||
const iframe = document.createElement('iframe')
|
const iframe = document.createElement('iframe')
|
||||||
iframe.style.display = 'none'
|
iframe.style.display = 'none'
|
||||||
iframe.src = file.url
|
iframe.src = result.value
|
||||||
document.body.appendChild(iframe)
|
document.body.appendChild(iframe)
|
||||||
// Remove the iframe once the download has had time to start.
|
// Remove the iframe once the download has had time to start.
|
||||||
window.setTimeout(() => iframe.remove(), 60_000)
|
window.setTimeout(() => iframe.remove(), 60_000)
|
||||||
@@ -426,7 +437,8 @@ export function useFileActions({
|
|||||||
await delay(600)
|
await delay(600)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
toast.success('All downloads initiated successfully')
|
if (failed > 0) toast.error(m.share_download_start_failed())
|
||||||
|
else toast.success('All downloads initiated successfully')
|
||||||
}
|
}
|
||||||
|
|
||||||
runQueue().catch((err) => {
|
runQueue().catch((err) => {
|
||||||
|
|||||||
@@ -154,7 +154,8 @@ describe('FileViewerRightSidebar - Comments Export', () => {
|
|||||||
expect(screen.getByRole('button', { name: 'More options' })).toBeDefined()
|
expect(screen.getByRole('button', { name: 'More options' })).toBeDefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('does NOT render "All comments" header row in public share view', async () => {
|
it('renders "All comments" header with Print Comments (and without Export Comments) in public share view', async () => {
|
||||||
|
const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||||
render(
|
render(
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<FileViewerRightSidebar
|
<FileViewerRightSidebar
|
||||||
@@ -169,8 +170,49 @@ describe('FileViewerRightSidebar - Comments Export', () => {
|
|||||||
</QueryClientProvider>,
|
</QueryClientProvider>,
|
||||||
)
|
)
|
||||||
|
|
||||||
expect(screen.queryByText('All comments')).toBeNull()
|
expect(screen.getByText('All comments')).toBeDefined()
|
||||||
expect(screen.queryByRole('button', { name: 'More options' })).toBeNull()
|
const moreButton = screen.getByRole('button', { name: 'More options' })
|
||||||
|
fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false })
|
||||||
|
|
||||||
|
const printItem = await screen.findByText('Print Comments')
|
||||||
|
expect(printItem).toBeDefined()
|
||||||
|
expect(screen.queryByText('Export Comments')).toBeNull()
|
||||||
|
|
||||||
|
fireEvent.click(printItem)
|
||||||
|
expect(windowOpenSpy).toHaveBeenCalledWith(
|
||||||
|
'/print/comments/file-123?shareId=share-123',
|
||||||
|
'_blank',
|
||||||
|
'noopener,noreferrer',
|
||||||
|
)
|
||||||
|
windowOpenSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('opens printable comments page from authenticated sidebar menu', async () => {
|
||||||
|
const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<FileViewerRightSidebar
|
||||||
|
teamId="team-1"
|
||||||
|
projectId="proj-1"
|
||||||
|
file={mockFile}
|
||||||
|
onSaveField={vi.fn()}
|
||||||
|
members={[{ id: 'user-1', name: 'User One', role: 'owner' }]}
|
||||||
|
isPublic={false}
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const moreButton = screen.getByRole('button', { name: 'More options' })
|
||||||
|
fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false })
|
||||||
|
|
||||||
|
const printItem = await screen.findByText('Print Comments')
|
||||||
|
fireEvent.click(printItem)
|
||||||
|
expect(windowOpenSpy).toHaveBeenCalledWith(
|
||||||
|
'/print/comments/file-123',
|
||||||
|
'_blank',
|
||||||
|
'noopener,noreferrer',
|
||||||
|
)
|
||||||
|
windowOpenSpy.mockRestore()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('opens dropdown menu with Export Comments and the 4 NLE options', async () => {
|
it('opens dropdown menu with Export Comments and the 4 NLE options', async () => {
|
||||||
|
|||||||
@@ -88,6 +88,15 @@ export function FileViewerRightSidebar({
|
|||||||
second?: number | null
|
second?: number | null
|
||||||
} | null>(null)
|
} | null>(null)
|
||||||
|
|
||||||
|
const handlePrintComments = () => {
|
||||||
|
if (!file?.id) return
|
||||||
|
const url =
|
||||||
|
isPublic && shareId
|
||||||
|
? `/print/comments/${encodeURIComponent(file.id)}?shareId=${encodeURIComponent(shareId)}`
|
||||||
|
: `/print/comments/${encodeURIComponent(file.id)}`
|
||||||
|
window.open(url, '_blank', 'noopener,noreferrer')
|
||||||
|
}
|
||||||
|
|
||||||
const handleExportComments = async (format: CommentExportFormat) => {
|
const handleExportComments = async (format: CommentExportFormat) => {
|
||||||
if (!file?.id || isExporting) return
|
if (!file?.id || isExporting) return
|
||||||
try {
|
try {
|
||||||
@@ -200,12 +209,14 @@ export function FileViewerRightSidebar({
|
|||||||
annotations,
|
annotations,
|
||||||
replyToId,
|
replyToId,
|
||||||
second,
|
second,
|
||||||
|
isInternal,
|
||||||
}: {
|
}: {
|
||||||
text: string
|
text: string
|
||||||
attachmentIds: string[]
|
attachmentIds: string[]
|
||||||
annotations?: Annotation[]
|
annotations?: Annotation[]
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
second?: number | null
|
second?: number | null
|
||||||
|
isInternal?: boolean
|
||||||
}) => {
|
}) => {
|
||||||
if (isPublic) {
|
if (isPublic) {
|
||||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||||
@@ -237,6 +248,7 @@ export function FileViewerRightSidebar({
|
|||||||
replyToId: replyToId ?? undefined,
|
replyToId: replyToId ?? undefined,
|
||||||
annotations: annotations,
|
annotations: annotations,
|
||||||
second: second ?? undefined,
|
second: second ?? undefined,
|
||||||
|
isInternal: isInternal ?? false,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
if (!res.ok) throw new Error('Failed to create comment')
|
if (!res.ok) throw new Error('Failed to create comment')
|
||||||
@@ -288,6 +300,8 @@ export function FileViewerRightSidebar({
|
|||||||
annotations?: Annotation[],
|
annotations?: Annotation[],
|
||||||
replyToId?: string | null,
|
replyToId?: string | null,
|
||||||
second?: number | null,
|
second?: number | null,
|
||||||
|
_attachedFilesMeta?: unknown,
|
||||||
|
isInternal?: boolean,
|
||||||
) => {
|
) => {
|
||||||
if (!file?.id) return
|
if (!file?.id) return
|
||||||
|
|
||||||
@@ -312,7 +326,7 @@ export function FileViewerRightSidebar({
|
|||||||
createComment({ text, attachmentIds, annotations, replyToId, second })
|
createComment({ text, attachmentIds, annotations, replyToId, second })
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
createComment({ text, attachmentIds, annotations, replyToId, second })
|
createComment({ text, attachmentIds, annotations, replyToId, second, isInternal })
|
||||||
}
|
}
|
||||||
setReplyingTo(null)
|
setReplyingTo(null)
|
||||||
}
|
}
|
||||||
@@ -361,21 +375,21 @@ export function FileViewerRightSidebar({
|
|||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
|
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
|
||||||
{!isPublic && (
|
<div className="flex items-center justify-between px-1 py-1.5 shrink-0 border-b border-border/50">
|
||||||
<div className="flex items-center justify-between px-1 py-1.5 shrink-0 border-b border-border/50">
|
<span className="text-xs font-semibold text-foreground">{m.all_comments()}</span>
|
||||||
<span className="text-xs font-semibold text-foreground">{m.all_comments()}</span>
|
<DropdownMenu modal={false}>
|
||||||
<DropdownMenu modal={false}>
|
<DropdownMenuTrigger asChild>
|
||||||
<DropdownMenuTrigger asChild>
|
<Button
|
||||||
<Button
|
variant="ghost"
|
||||||
variant="ghost"
|
size="icon"
|
||||||
size="icon"
|
className="h-6 w-6 text-muted-foreground hover:text-foreground cursor-pointer"
|
||||||
className="h-6 w-6 text-muted-foreground hover:text-foreground cursor-pointer"
|
aria-label={m.more_options()}
|
||||||
aria-label={m.more_options()}
|
>
|
||||||
>
|
<MoreHorizontal className="size-4" />
|
||||||
<MoreHorizontal className="size-4" />
|
</Button>
|
||||||
</Button>
|
</DropdownMenuTrigger>
|
||||||
</DropdownMenuTrigger>
|
<DropdownMenuContent align="end" className="w-48">
|
||||||
<DropdownMenuContent align="end" className="w-48">
|
{!isPublic && (
|
||||||
<DropdownMenuSub>
|
<DropdownMenuSub>
|
||||||
<DropdownMenuSubTrigger className="cursor-pointer">
|
<DropdownMenuSubTrigger className="cursor-pointer">
|
||||||
<span>{m.export_comments()}</span>
|
<span>{m.export_comments()}</span>
|
||||||
@@ -396,16 +410,20 @@ export function FileViewerRightSidebar({
|
|||||||
))}
|
))}
|
||||||
</DropdownMenuSubContent>
|
</DropdownMenuSubContent>
|
||||||
</DropdownMenuSub>
|
</DropdownMenuSub>
|
||||||
</DropdownMenuContent>
|
)}
|
||||||
</DropdownMenu>
|
<DropdownMenuItem className="cursor-pointer" onClick={handlePrintComments}>
|
||||||
</div>
|
<span>{m.print_comments()}</span>
|
||||||
)}
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
||||||
<div className="space-y-4 pt-2">
|
<div className="space-y-4 pt-2">
|
||||||
{comments.map((comment) => (
|
{comments.map((comment) => (
|
||||||
<div key={comment.id}>
|
<div key={comment.id}>
|
||||||
<MessageCard
|
<MessageCard
|
||||||
teamId={teamId}
|
teamId={teamId}
|
||||||
|
projectId={projectId}
|
||||||
message={comment}
|
message={comment}
|
||||||
getUser={getUser}
|
getUser={getUser}
|
||||||
onReply={setReplyingTo}
|
onReply={setReplyingTo}
|
||||||
@@ -432,7 +450,9 @@ export function FileViewerRightSidebar({
|
|||||||
<div key={reply.id}>
|
<div key={reply.id}>
|
||||||
<MessageCard
|
<MessageCard
|
||||||
teamId={teamId}
|
teamId={teamId}
|
||||||
|
projectId={projectId}
|
||||||
isReply={true}
|
isReply={true}
|
||||||
|
parentIsInternal={comment.isInternal}
|
||||||
message={reply}
|
message={reply}
|
||||||
getUser={getUser}
|
getUser={getUser}
|
||||||
onReply={setReplyingTo}
|
onReply={setReplyingTo}
|
||||||
@@ -476,6 +496,7 @@ export function FileViewerRightSidebar({
|
|||||||
onSendMessage={handleSendMessage}
|
onSendMessage={handleSendMessage}
|
||||||
replyingTo={replyingTo}
|
replyingTo={replyingTo}
|
||||||
onCancelReply={() => setReplyingTo(null)}
|
onCancelReply={() => setReplyingTo(null)}
|
||||||
|
allowInternalComments={!isPublic}
|
||||||
hideAnnotationControl={hideAnnotationControl}
|
hideAnnotationControl={hideAnnotationControl}
|
||||||
disableMentions={isPublic}
|
disableMentions={isPublic}
|
||||||
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
|
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
|
||||||
|
|||||||
@@ -171,12 +171,14 @@ export function MobileFileBottomSheet({
|
|||||||
annotations,
|
annotations,
|
||||||
replyToId,
|
replyToId,
|
||||||
second,
|
second,
|
||||||
|
isInternal,
|
||||||
}: {
|
}: {
|
||||||
text: string
|
text: string
|
||||||
attachmentIds: string[]
|
attachmentIds: string[]
|
||||||
annotations?: Annotation[]
|
annotations?: Annotation[]
|
||||||
replyToId?: string | null
|
replyToId?: string | null
|
||||||
second?: number | null
|
second?: number | null
|
||||||
|
isInternal?: boolean
|
||||||
}) => {
|
}) => {
|
||||||
if (isPublic) {
|
if (isPublic) {
|
||||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||||
@@ -208,6 +210,7 @@ export function MobileFileBottomSheet({
|
|||||||
replyToId: replyToId ?? undefined,
|
replyToId: replyToId ?? undefined,
|
||||||
annotations: annotations,
|
annotations: annotations,
|
||||||
second: second ?? undefined,
|
second: second ?? undefined,
|
||||||
|
isInternal: isInternal ?? false,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
if (!res.ok) throw new Error('Failed to create comment')
|
if (!res.ok) throw new Error('Failed to create comment')
|
||||||
@@ -267,6 +270,8 @@ export function MobileFileBottomSheet({
|
|||||||
annotations: Annotation[] = [],
|
annotations: Annotation[] = [],
|
||||||
replyToId?: string | null,
|
replyToId?: string | null,
|
||||||
second?: number | null,
|
second?: number | null,
|
||||||
|
_attachedFilesMeta?: unknown,
|
||||||
|
isInternal?: boolean,
|
||||||
) => {
|
) => {
|
||||||
if (!text.trim() && attachmentIds.length === 0 && annotations.length === 0) return
|
if (!text.trim() && attachmentIds.length === 0 && annotations.length === 0) return
|
||||||
|
|
||||||
@@ -286,7 +291,14 @@ export function MobileFileBottomSheet({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
createComment({ text, attachmentIds, annotations, replyToId: actualReplyToId, second })
|
createComment({
|
||||||
|
text,
|
||||||
|
attachmentIds,
|
||||||
|
annotations,
|
||||||
|
replyToId: actualReplyToId,
|
||||||
|
second,
|
||||||
|
isInternal,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
setReplyingTo(null)
|
setReplyingTo(null)
|
||||||
}
|
}
|
||||||
@@ -372,6 +384,7 @@ export function MobileFileBottomSheet({
|
|||||||
<div key={comment.id}>
|
<div key={comment.id}>
|
||||||
<MessageCard
|
<MessageCard
|
||||||
teamId={teamId}
|
teamId={teamId}
|
||||||
|
projectId={projectId}
|
||||||
message={comment}
|
message={comment}
|
||||||
getUser={getUser}
|
getUser={getUser}
|
||||||
onReply={setReplyingTo}
|
onReply={setReplyingTo}
|
||||||
@@ -398,7 +411,9 @@ export function MobileFileBottomSheet({
|
|||||||
<div key={reply.id}>
|
<div key={reply.id}>
|
||||||
<MessageCard
|
<MessageCard
|
||||||
teamId={teamId}
|
teamId={teamId}
|
||||||
|
projectId={projectId}
|
||||||
isReply={true}
|
isReply={true}
|
||||||
|
parentIsInternal={comment.isInternal}
|
||||||
message={reply}
|
message={reply}
|
||||||
getUser={getUser}
|
getUser={getUser}
|
||||||
onReply={setReplyingTo}
|
onReply={setReplyingTo}
|
||||||
@@ -445,6 +460,7 @@ export function MobileFileBottomSheet({
|
|||||||
onSendMessage={handleSendMessage}
|
onSendMessage={handleSendMessage}
|
||||||
replyingTo={replyingTo}
|
replyingTo={replyingTo}
|
||||||
onCancelReply={() => setReplyingTo(null)}
|
onCancelReply={() => setReplyingTo(null)}
|
||||||
|
allowInternalComments={!isPublic}
|
||||||
hideAnnotationControl={hideAnnotationControl}
|
hideAnnotationControl={hideAnnotationControl}
|
||||||
disableMentions={isPublic}
|
disableMentions={isPublic}
|
||||||
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
|
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
|||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
import { useMemberStore } from '@/ui/stores/members'
|
import { useMemberStore } from '@/ui/stores/members'
|
||||||
import type { Annotation } from '@/ui/types'
|
import type { Annotation } from '@/ui/types'
|
||||||
import type { AncestorFolder, AssetInfo, CommentInfo, FieldInfo } from '@shumai/dtos'
|
import type { AncestorFolder, AssetInfo, CommentInfo, FieldInfo, ShareLinkInfo } from '@shumai/dtos'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
@@ -61,6 +61,10 @@ export interface MobileFileDetailProps {
|
|||||||
onDeleteFile?: () => Promise<void>
|
onDeleteFile?: () => Promise<void>
|
||||||
onArchiveFile?: () => void
|
onArchiveFile?: () => void
|
||||||
onRestoreArchiveFile?: () => void
|
onRestoreArchiveFile?: () => void
|
||||||
|
shareLinks?: ShareLinkInfo[]
|
||||||
|
onCreateShareLink?: () => void
|
||||||
|
onAddToShareLink?: (shareId: string) => void
|
||||||
|
isShareActionPending?: boolean
|
||||||
onSaveField: (fieldId: string, value: unknown) => void
|
onSaveField: (fieldId: string, value: unknown) => void
|
||||||
onSelectVersion?: (versionId: string) => void
|
onSelectVersion?: (versionId: string) => void
|
||||||
}
|
}
|
||||||
@@ -86,6 +90,10 @@ export function MobileFileDetail({
|
|||||||
onDeleteFile,
|
onDeleteFile,
|
||||||
onArchiveFile,
|
onArchiveFile,
|
||||||
onRestoreArchiveFile,
|
onRestoreArchiveFile,
|
||||||
|
shareLinks,
|
||||||
|
onCreateShareLink,
|
||||||
|
onAddToShareLink,
|
||||||
|
isShareActionPending = false,
|
||||||
onSaveField,
|
onSaveField,
|
||||||
onSelectVersion,
|
onSelectVersion,
|
||||||
}: MobileFileDetailProps) {
|
}: MobileFileDetailProps) {
|
||||||
@@ -240,6 +248,10 @@ export function MobileFileDetail({
|
|||||||
onDelete={() => setIsDeleteDialogOpen(true)}
|
onDelete={() => setIsDeleteDialogOpen(true)}
|
||||||
onArchive={onArchiveFile}
|
onArchive={onArchiveFile}
|
||||||
onRestoreArchive={onRestoreArchiveFile}
|
onRestoreArchive={onRestoreArchiveFile}
|
||||||
|
shareLinks={shareLinks}
|
||||||
|
onCreateShareLink={onCreateShareLink}
|
||||||
|
onAddToShareLink={onAddToShareLink}
|
||||||
|
isShareActionPending={isShareActionPending}
|
||||||
onLinkedTasks={!isPublic ? () => setIsLinkedTasksOpen(true) : undefined}
|
onLinkedTasks={!isPublic ? () => setIsLinkedTasksOpen(true) : undefined}
|
||||||
linkedTaskCount={linkedTaskCount}
|
linkedTaskCount={linkedTaskCount}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -216,4 +216,85 @@ describe('MobileFileHeader', () => {
|
|||||||
expect(screen.queryByText('Restoring...')).toBeNull()
|
expect(screen.queryByText('Restoring...')).toBeNull()
|
||||||
expect(screen.queryByText('恢复中...')).toBeNull()
|
expect(screen.queryByText('恢复中...')).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('renders Create Share Link and Add to Share Links at top of three-dot menu above Download for editors', () => {
|
||||||
|
const onCreateShareLink = vi.fn()
|
||||||
|
const onAddToShareLink = vi.fn()
|
||||||
|
|
||||||
|
render(
|
||||||
|
<MobileFileHeader
|
||||||
|
fileName="clip.mp4"
|
||||||
|
activeFileId="file-1"
|
||||||
|
canEdit={true}
|
||||||
|
allowDownload={true}
|
||||||
|
downloadInfo={{ originalKey: 'clip.mp4' }}
|
||||||
|
shareLinks={[
|
||||||
|
{
|
||||||
|
id: 'share-1',
|
||||||
|
name: 'Client Review',
|
||||||
|
isDisabled: false,
|
||||||
|
allowDownload: true,
|
||||||
|
hasPassword: false,
|
||||||
|
rootFolderId: 'rf-1',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
|
createdAt: '2026-11-24T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-11-24T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
onCreateShareLink={onCreateShareLink}
|
||||||
|
onAddToShareLink={onAddToShareLink}
|
||||||
|
onBack={vi.fn()}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const menuBtn = screen.getByLabelText(/More options/i)
|
||||||
|
fireEvent.pointerDown(menuBtn, { button: 0, ctrlKey: false })
|
||||||
|
|
||||||
|
const items = screen.getAllByRole('menuitem')
|
||||||
|
expect(items[0].textContent).toContain('Create Share Link')
|
||||||
|
expect(items[1].textContent).toContain('Add to Share Links')
|
||||||
|
expect(items[2].textContent).toContain('Download')
|
||||||
|
|
||||||
|
fireEvent.click(items[0])
|
||||||
|
expect(onCreateShareLink).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
fireEvent.pointerDown(menuBtn, { button: 0, ctrlKey: false })
|
||||||
|
fireEvent.click(screen.getByText('Add to Share Links'))
|
||||||
|
fireEvent.click(screen.getByText('Client Review'))
|
||||||
|
expect(onAddToShareLink).toHaveBeenCalledWith('share-1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hides share link options when public or when canEdit is false', () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<MobileFileHeader
|
||||||
|
fileName="clip.mp4"
|
||||||
|
activeFileId="file-1"
|
||||||
|
canEdit={false}
|
||||||
|
onCreateShareLink={vi.fn()}
|
||||||
|
onAddToShareLink={vi.fn()}
|
||||||
|
onBack={vi.fn()}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const menuBtn = screen.getByLabelText(/More options/i)
|
||||||
|
fireEvent.pointerDown(menuBtn, { button: 0, ctrlKey: false })
|
||||||
|
expect(screen.queryByText('Create Share Link')).toBeNull()
|
||||||
|
|
||||||
|
rerender(
|
||||||
|
<MobileFileHeader
|
||||||
|
fileName="clip.mp4"
|
||||||
|
activeFileId="file-1"
|
||||||
|
canEdit={true}
|
||||||
|
isPublic={true}
|
||||||
|
onCreateShareLink={vi.fn()}
|
||||||
|
onAddToShareLink={vi.fn()}
|
||||||
|
onBack={vi.fn()}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.queryByText('Create Share Link')).toBeNull()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { client } from '@/ui/api/client'
|
import { client } from '@/ui/api/client'
|
||||||
|
import { requestShareDownload } from '@/ui/api/share-download'
|
||||||
import { Badge } from '@/ui/components/ui/badge'
|
import { Badge } from '@/ui/components/ui/badge'
|
||||||
import { Button } from '@/ui/components/ui/button'
|
import { Button } from '@/ui/components/ui/button'
|
||||||
import {
|
import {
|
||||||
@@ -15,6 +16,7 @@ import {
|
|||||||
} from '@/ui/components/ui/dropdown-menu'
|
} from '@/ui/components/ui/dropdown-menu'
|
||||||
import { cn } from '@/ui/lib/utils'
|
import { cn } from '@/ui/lib/utils'
|
||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||||
import {
|
import {
|
||||||
Archive,
|
Archive,
|
||||||
ArchiveRestore,
|
ArchiveRestore,
|
||||||
@@ -22,9 +24,11 @@ import {
|
|||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Download,
|
Download,
|
||||||
|
Link as LinkIcon,
|
||||||
Loader2,
|
Loader2,
|
||||||
MoreVertical,
|
MoreVertical,
|
||||||
Pencil,
|
Pencil,
|
||||||
|
Plus,
|
||||||
SquareKanban,
|
SquareKanban,
|
||||||
Trash2,
|
Trash2,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
@@ -67,6 +71,10 @@ export interface MobileFileHeaderProps {
|
|||||||
onDelete?: () => void
|
onDelete?: () => void
|
||||||
onArchive?: () => void
|
onArchive?: () => void
|
||||||
onRestoreArchive?: () => void
|
onRestoreArchive?: () => void
|
||||||
|
shareLinks?: ShareLinkInfo[]
|
||||||
|
onCreateShareLink?: () => void
|
||||||
|
onAddToShareLink?: (shareId: string) => void
|
||||||
|
isShareActionPending?: boolean
|
||||||
onLinkedTasks?: () => void
|
onLinkedTasks?: () => void
|
||||||
linkedTaskCount?: number
|
linkedTaskCount?: number
|
||||||
}
|
}
|
||||||
@@ -93,6 +101,10 @@ export function MobileFileHeader({
|
|||||||
onDelete,
|
onDelete,
|
||||||
onArchive,
|
onArchive,
|
||||||
onRestoreArchive,
|
onRestoreArchive,
|
||||||
|
shareLinks,
|
||||||
|
onCreateShareLink,
|
||||||
|
onAddToShareLink,
|
||||||
|
isShareActionPending = false,
|
||||||
onLinkedTasks,
|
onLinkedTasks,
|
||||||
linkedTaskCount = 0,
|
linkedTaskCount = 0,
|
||||||
}: MobileFileHeaderProps) {
|
}: MobileFileHeaderProps) {
|
||||||
@@ -102,10 +114,7 @@ export function MobileFileHeader({
|
|||||||
try {
|
try {
|
||||||
const res =
|
const res =
|
||||||
isPublic && shareId
|
isPublic && shareId
|
||||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
? await requestShareDownload(shareId, activeFileId, key)
|
||||||
param: { shareId, fileId: activeFileId },
|
|
||||||
json: { key },
|
|
||||||
})
|
|
||||||
: await client.api.files['download-url'].$post({
|
: await client.api.files['download-url'].$post({
|
||||||
json: { key, assetId: activeFileId },
|
json: { key, assetId: activeFileId },
|
||||||
})
|
})
|
||||||
@@ -279,6 +288,42 @@ export function MobileFileHeader({
|
|||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" className="w-52 z-40">
|
<DropdownMenuContent align="end" className="w-52 z-40">
|
||||||
|
{/* Share Links */}
|
||||||
|
{canEdit && !isPublic && onCreateShareLink && (
|
||||||
|
<>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={onCreateShareLink}
|
||||||
|
disabled={isShareActionPending}
|
||||||
|
className="flex items-center gap-2 text-xs cursor-pointer"
|
||||||
|
>
|
||||||
|
<Plus className="h-3.5 w-3.5" />
|
||||||
|
<span>{m.create_share_link()}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{shareLinks && shareLinks.length > 0 && onAddToShareLink && (
|
||||||
|
<DropdownMenuSub>
|
||||||
|
<DropdownMenuSubTrigger className="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<LinkIcon className="h-3.5 w-3.5" />
|
||||||
|
<span>{m.add_to_share_links()}</span>
|
||||||
|
</DropdownMenuSubTrigger>
|
||||||
|
<DropdownMenuPortal>
|
||||||
|
<DropdownMenuSubContent className="w-48 z-50">
|
||||||
|
{shareLinks.map((share) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={share.id}
|
||||||
|
disabled={isShareActionPending}
|
||||||
|
onClick={() => onAddToShareLink(share.id)}
|
||||||
|
className="text-xs cursor-pointer"
|
||||||
|
>
|
||||||
|
<span className="truncate">{share.name}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuSubContent>
|
||||||
|
</DropdownMenuPortal>
|
||||||
|
</DropdownMenuSub>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Download */}
|
{/* Download */}
|
||||||
{allowDownload &&
|
{allowDownload &&
|
||||||
(hasVideoTranscodes ? (
|
(hasVideoTranscodes ? (
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import type { Annotation } from '@/ui/types'
|
||||||
|
import React from 'react'
|
||||||
|
|
||||||
|
export function parseAnnotations(raw: unknown): Annotation[] {
|
||||||
|
if (!Array.isArray(raw)) return []
|
||||||
|
const valid: Annotation[] = []
|
||||||
|
for (const item of raw) {
|
||||||
|
if (!item || typeof item !== 'object') continue
|
||||||
|
const rec = item as Record<string, unknown>
|
||||||
|
const type = rec.type
|
||||||
|
const color = rec.color
|
||||||
|
const points = rec.points
|
||||||
|
if (
|
||||||
|
(type === 'box' || type === 'line' || type === 'arrow' || type === 'freehand') &&
|
||||||
|
typeof color === 'string' &&
|
||||||
|
Array.isArray(points) &&
|
||||||
|
points.length >= 2 &&
|
||||||
|
points.every(
|
||||||
|
(pt) =>
|
||||||
|
Array.isArray(pt) &&
|
||||||
|
pt.length >= 2 &&
|
||||||
|
typeof pt[0] === 'number' &&
|
||||||
|
typeof pt[1] === 'number',
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
valid.push({
|
||||||
|
type,
|
||||||
|
color,
|
||||||
|
points: points as [number, number][],
|
||||||
|
} as Annotation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return valid
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnnotationOverlaySvgProps {
|
||||||
|
annotations: Annotation[]
|
||||||
|
width: number
|
||||||
|
height: number
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFreehandPath(points: [number, number][], w: number, h: number): string {
|
||||||
|
if (points.length === 0) return ''
|
||||||
|
const scaled = points.map(([nx, ny]) => [nx * w, ny * h] as const)
|
||||||
|
if (scaled.length === 2) {
|
||||||
|
return `M ${scaled[0][0]} ${scaled[0][1]} L ${scaled[1][0]} ${scaled[1][1]}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Smooth quadratic path matching Konva's tension ~0.5 appearance
|
||||||
|
let d = `M ${scaled[0][0]} ${scaled[0][1]}`
|
||||||
|
for (let i = 1; i < scaled.length - 1; i++) {
|
||||||
|
const midX = (scaled[i][0] + scaled[i + 1][0]) / 2
|
||||||
|
const midY = (scaled[i][1] + scaled[i + 1][1]) / 2
|
||||||
|
d += ` Q ${scaled[i][0]} ${scaled[i][1]} ${midX} ${midY}`
|
||||||
|
}
|
||||||
|
const last = scaled[scaled.length - 1]
|
||||||
|
d += ` L ${last[0]} ${last[1]}`
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vector SVG overlay for normalized [0..1] comment annotations.
|
||||||
|
* Using inline SVG instead of rasterized canvas ensures sharp markups when
|
||||||
|
* printing or exporting to PDF and avoids browser canvas limits on long lists.
|
||||||
|
*/
|
||||||
|
export const AnnotationOverlaySvg: React.FC<AnnotationOverlaySvgProps> = ({
|
||||||
|
annotations,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
className,
|
||||||
|
}) => {
|
||||||
|
if (annotations.length === 0 || width <= 0 || height <= 0) return null
|
||||||
|
|
||||||
|
// Keep stroke visually consistent with DrawingCanvas regardless of image dimensions
|
||||||
|
const baseDim = Math.max(width, height)
|
||||||
|
const strokeWidth = Math.max(1.5, baseDim * 0.014)
|
||||||
|
const headLength = strokeWidth * 3.8
|
||||||
|
const headHalfWidth = strokeWidth * 2.1
|
||||||
|
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
viewBox={`0 0 ${width} ${height}`}
|
||||||
|
preserveAspectRatio="none"
|
||||||
|
className={className}
|
||||||
|
data-testid="print-annotation-overlay"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
{annotations.map((ann, idx) => {
|
||||||
|
if (ann.type === 'box') {
|
||||||
|
const [start, end] = ann.points
|
||||||
|
const x = Math.min(start[0], end[0]) * width
|
||||||
|
const y = Math.min(start[1], end[1]) * height
|
||||||
|
const boxW = Math.abs(end[0] - start[0]) * width
|
||||||
|
const boxH = Math.abs(end[1] - start[1]) * height
|
||||||
|
return (
|
||||||
|
<rect
|
||||||
|
key={idx}
|
||||||
|
x={x}
|
||||||
|
y={y}
|
||||||
|
width={boxW}
|
||||||
|
height={boxH}
|
||||||
|
fill="none"
|
||||||
|
stroke={ann.color}
|
||||||
|
strokeWidth={strokeWidth}
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ann.type === 'line') {
|
||||||
|
const [start, end] = ann.points
|
||||||
|
return (
|
||||||
|
<line
|
||||||
|
key={idx}
|
||||||
|
x1={start[0] * width}
|
||||||
|
y1={start[1] * height}
|
||||||
|
x2={end[0] * width}
|
||||||
|
y2={end[1] * height}
|
||||||
|
stroke={ann.color}
|
||||||
|
strokeWidth={strokeWidth}
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ann.type === 'arrow') {
|
||||||
|
const [start, end] = ann.points
|
||||||
|
const x1 = start[0] * width
|
||||||
|
const y1 = start[1] * height
|
||||||
|
const x2 = end[0] * width
|
||||||
|
const y2 = end[1] * height
|
||||||
|
const angle = Math.atan2(y2 - y1, x2 - x1)
|
||||||
|
const lineLen = Math.hypot(x2 - x1, y2 - y1)
|
||||||
|
const clampedHeadLen = Math.min(headLength, lineLen * 0.65)
|
||||||
|
const clampedHalfW = (clampedHeadLen / headLength) * headHalfWidth
|
||||||
|
const baseX = x2 - clampedHeadLen * Math.cos(angle)
|
||||||
|
const baseY = y2 - clampedHeadLen * Math.sin(angle)
|
||||||
|
const leftX = baseX - clampedHalfW * Math.sin(angle)
|
||||||
|
const leftY = baseY + clampedHalfW * Math.cos(angle)
|
||||||
|
const rightX = baseX + clampedHalfW * Math.sin(angle)
|
||||||
|
const rightY = baseY - clampedHalfW * Math.cos(angle)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<g key={idx}>
|
||||||
|
<line
|
||||||
|
x1={x1}
|
||||||
|
y1={y1}
|
||||||
|
x2={baseX}
|
||||||
|
y2={baseY}
|
||||||
|
stroke={ann.color}
|
||||||
|
strokeWidth={strokeWidth}
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>
|
||||||
|
<polygon
|
||||||
|
points={`${x2},${y2} ${leftX},${leftY} ${rightX},${rightY}`}
|
||||||
|
fill={ann.color}
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ann.type === 'freehand') {
|
||||||
|
const d = buildFreehandPath(ann.points, width, height)
|
||||||
|
return (
|
||||||
|
<path
|
||||||
|
key={idx}
|
||||||
|
d={d}
|
||||||
|
fill="none"
|
||||||
|
stroke={ann.color}
|
||||||
|
strokeWidth={strokeWidth}
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import type { Annotation } from '@/ui/types'
|
||||||
|
import { ImageOff, Loader2 } from 'lucide-react'
|
||||||
|
import React, { useEffect, useRef, useState } from 'react'
|
||||||
|
import { AnnotationOverlaySvg } from './annotation-overlay-svg'
|
||||||
|
import { computeCommentFrameBox, ERROR_MIN_HEIGHT, type Dimensions } from './sizing'
|
||||||
|
|
||||||
|
interface CommentFrameThumbnailProps {
|
||||||
|
src: string
|
||||||
|
annotations: Annotation[]
|
||||||
|
initialDimensions?: Dimensions | null
|
||||||
|
alt?: string
|
||||||
|
onStatusChange?: (status: 'loaded' | 'error') => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CommentFrameThumbnail: React.FC<CommentFrameThumbnailProps> = ({
|
||||||
|
src,
|
||||||
|
annotations,
|
||||||
|
initialDimensions = null,
|
||||||
|
alt = '',
|
||||||
|
onStatusChange,
|
||||||
|
}) => {
|
||||||
|
const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading')
|
||||||
|
const [naturalSize, setNaturalSize] = useState<Dimensions | null>(initialDimensions)
|
||||||
|
const imgRef = useRef<HTMLImageElement>(null)
|
||||||
|
const onStatusChangeRef = useRef(onStatusChange)
|
||||||
|
onStatusChangeRef.current = onStatusChange
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setStatus('loading')
|
||||||
|
setNaturalSize(initialDimensions)
|
||||||
|
const img = imgRef.current
|
||||||
|
if (img && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||||
|
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||||
|
setStatus('loaded')
|
||||||
|
onStatusChangeRef.current?.('loaded')
|
||||||
|
}
|
||||||
|
}, [src, initialDimensions])
|
||||||
|
|
||||||
|
const handleLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
|
||||||
|
const img = e.currentTarget
|
||||||
|
if (img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||||
|
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||||
|
}
|
||||||
|
setStatus('loaded')
|
||||||
|
onStatusChangeRef.current?.('loaded')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleError = () => {
|
||||||
|
setStatus('error')
|
||||||
|
onStatusChangeRef.current?.('error')
|
||||||
|
}
|
||||||
|
|
||||||
|
const { width: boxWidth, height: boxHeight } = computeCommentFrameBox(naturalSize)
|
||||||
|
const containerHeight = status === 'error' ? Math.max(boxHeight, ERROR_MIN_HEIGHT) : boxHeight
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="relative flex items-center justify-center overflow-hidden rounded-sm border border-border transparency-checkerboard shrink-0"
|
||||||
|
style={{ width: boxWidth, height: containerHeight }}
|
||||||
|
data-testid="print-comment-frame"
|
||||||
|
>
|
||||||
|
{status === 'loading' && (
|
||||||
|
<div
|
||||||
|
className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-1.5 bg-muted/95 text-muted-foreground"
|
||||||
|
data-testid="print-frame-loading"
|
||||||
|
>
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
<span className="text-[11px] leading-none">{m.print_comments_frame_loading()}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'error' ? (
|
||||||
|
<div
|
||||||
|
className="flex flex-col items-center justify-center gap-1.5 px-2 text-center text-muted-foreground"
|
||||||
|
data-testid="print-frame-error"
|
||||||
|
>
|
||||||
|
<ImageOff className="h-4 w-4" />
|
||||||
|
<span className="text-[11px] leading-tight">{m.print_comments_frame_unavailable()}</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<img
|
||||||
|
ref={imgRef}
|
||||||
|
src={src}
|
||||||
|
alt={alt}
|
||||||
|
onLoad={handleLoad}
|
||||||
|
onError={handleError}
|
||||||
|
className={`block h-full w-full ${status === 'loaded' ? 'opacity-100' : 'opacity-0'}`}
|
||||||
|
/>
|
||||||
|
{status === 'loaded' && annotations.length > 0 && (
|
||||||
|
<AnnotationOverlaySvg
|
||||||
|
annotations={annotations}
|
||||||
|
width={boxWidth}
|
||||||
|
height={boxHeight}
|
||||||
|
className="pointer-events-none absolute inset-0 h-full w-full z-10"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,527 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||||
|
import React from 'react'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import type { AssetInfo, CommentInfo } from '@shumai/dtos'
|
||||||
|
import { PrintCommentsView } from './print-comments-view'
|
||||||
|
import {
|
||||||
|
computeCommentFrameBox,
|
||||||
|
fitHeaderThumbnailBox,
|
||||||
|
resolveAssetDisplayDimensions,
|
||||||
|
} from './sizing'
|
||||||
|
|
||||||
|
function makeComment(overrides: Partial<CommentInfo> = {}): CommentInfo {
|
||||||
|
return {
|
||||||
|
id: 'c-1',
|
||||||
|
assetId: 'asset-1',
|
||||||
|
message: 'Check the color grade here',
|
||||||
|
annotations: null,
|
||||||
|
second: 1.5,
|
||||||
|
creator: { id: 'u-1', name: 'Alice' },
|
||||||
|
replies: [],
|
||||||
|
attachments: [],
|
||||||
|
mentions: [],
|
||||||
|
createdAt: '2026-11-25T14:53:00.000Z',
|
||||||
|
updatedAt: '2026-11-25T14:53:00.000Z',
|
||||||
|
sessionId: null,
|
||||||
|
isCompleted: false,
|
||||||
|
isInternal: false,
|
||||||
|
completionLastChangedBy: null,
|
||||||
|
reactionCounts: [],
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('PrintCommentsView', () => {
|
||||||
|
let printMock: ReturnType<typeof vi.fn>
|
||||||
|
const originalPrint = window.print
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
printMock = vi.fn()
|
||||||
|
Object.defineProperty(window, 'print', {
|
||||||
|
value: printMock,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup()
|
||||||
|
Object.defineProperty(window, 'print', {
|
||||||
|
value: originalPrint,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const videoAsset: AssetInfo = {
|
||||||
|
id: 'asset-video-1',
|
||||||
|
name: '3D_printer_building_model_20261017121617.mp4',
|
||||||
|
type: 'file',
|
||||||
|
status: 'processed',
|
||||||
|
sizeByte: 1024,
|
||||||
|
fileCount: 1,
|
||||||
|
proxyType: 'video',
|
||||||
|
preview: { thumbnailUrl: 'https://example.com/thumb.jpg' },
|
||||||
|
creator: { id: 'u-1', name: 'Alice' },
|
||||||
|
createdAt: '2026-11-06T10:00:00.000Z',
|
||||||
|
updatedAt: '2026-11-06T10:00:00.000Z',
|
||||||
|
media: {
|
||||||
|
proxyType: 'video',
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [],
|
||||||
|
metadata: { frameRate: 24 },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
it('renders video comments sorted by timecode with frames, SVG annotations, replies, completed status, reactions, and attachments without auto-printing', () => {
|
||||||
|
const comments: CommentInfo[] = [
|
||||||
|
makeComment({
|
||||||
|
id: 'c-2',
|
||||||
|
second: 5,
|
||||||
|
message: 'Second comment later in timeline',
|
||||||
|
}),
|
||||||
|
makeComment({
|
||||||
|
id: 'c-1',
|
||||||
|
second: 1.5,
|
||||||
|
message: 'First comment <@u-2>',
|
||||||
|
mentions: [{ id: 'u-2', name: 'Bob' }],
|
||||||
|
isCompleted: true,
|
||||||
|
annotations: [
|
||||||
|
{
|
||||||
|
type: 'box',
|
||||||
|
color: '#ef4444',
|
||||||
|
points: [
|
||||||
|
[0.1, 0.1],
|
||||||
|
[0.5, 0.5],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'arrow',
|
||||||
|
color: '#22c55e',
|
||||||
|
points: [
|
||||||
|
[0.2, 0.2],
|
||||||
|
[0.8, 0.8],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'line',
|
||||||
|
color: '#3b82f6',
|
||||||
|
points: [
|
||||||
|
[0.1, 0.9],
|
||||||
|
[0.9, 0.1],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'freehand',
|
||||||
|
color: '#eab308',
|
||||||
|
points: [
|
||||||
|
[0.1, 0.2],
|
||||||
|
[0.2, 0.3],
|
||||||
|
[0.4, 0.35],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
attachments: [
|
||||||
|
{ id: 'att-1', assetId: 'a-1', url: 'https://example.com/ref-frame.png' },
|
||||||
|
{ id: 'att-2', assetId: 'a-2', url: 'https://example.com/notes.pdf' },
|
||||||
|
],
|
||||||
|
reactionCounts: [
|
||||||
|
{ code: '👍', count: 2, requestingUserReacted: true, creatorNames: ['Bob'] },
|
||||||
|
],
|
||||||
|
replies: [
|
||||||
|
makeComment({
|
||||||
|
id: 'r-1',
|
||||||
|
second: null,
|
||||||
|
message: 'Updated in v2!',
|
||||||
|
creator: { id: 'u-2', name: 'Bob' },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
|
||||||
|
const { container } = render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={videoAsset}
|
||||||
|
breadcrumbs={['Untitled Project', 'Dailies']}
|
||||||
|
comments={comments}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Never auto-trigger print
|
||||||
|
expect(printMock).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
// Header breadcrumbs & creator
|
||||||
|
expect(screen.getByText('Untitled Project')).toBeDefined()
|
||||||
|
expect(screen.getByText('Dailies')).toBeDefined()
|
||||||
|
expect(screen.getByText('Sorted by timecode')).toBeDefined()
|
||||||
|
|
||||||
|
// Progress indicator while thumbnails are loading
|
||||||
|
expect(screen.getByTestId('print-frames-progress')).toBeDefined()
|
||||||
|
expect(screen.getAllByTestId('print-frame-loading')).toHaveLength(2)
|
||||||
|
|
||||||
|
// Sorted by timecode: c-1 (1.5s) appears before c-2 (5s)
|
||||||
|
const threads = screen.getAllByTestId('print-comment-thread')
|
||||||
|
expect(threads).toHaveLength(2)
|
||||||
|
expect(threads[0].textContent).toContain('First comment')
|
||||||
|
expect(threads[0].textContent).toContain('@Bob')
|
||||||
|
expect(threads[0].textContent).toContain('Updated in v2!')
|
||||||
|
expect(threads[1].textContent).toContain('Second comment later in timeline')
|
||||||
|
|
||||||
|
// Completed badge, reactions, and attachments
|
||||||
|
expect(screen.getByTestId('print-comment-completed').textContent).toContain('Completed')
|
||||||
|
expect(screen.getByTestId('print-comment-reactions').textContent).toContain('👍')
|
||||||
|
expect(screen.getByTestId('print-comment-reactions').textContent).toContain('2')
|
||||||
|
expect(screen.getByTestId('print-comment-attachments').textContent).toContain('ref-frame.png')
|
||||||
|
expect(screen.getByTestId('print-comment-attachments').textContent).toContain('notes.pdf')
|
||||||
|
|
||||||
|
// Frame image requests point to backend frame endpoint
|
||||||
|
const frameImgs = container.querySelectorAll('[data-testid="print-comment-frame"] img')
|
||||||
|
expect(frameImgs).toHaveLength(2)
|
||||||
|
expect(frameImgs[0].getAttribute('src')).toBe(
|
||||||
|
'/api/files/asset-video-1/comments/frame?second=1.5&width=400',
|
||||||
|
)
|
||||||
|
|
||||||
|
// Simulate frame image load -> SVG overlay renders all 4 annotation shapes
|
||||||
|
Object.defineProperty(frameImgs[0], 'naturalWidth', { value: 400, configurable: true })
|
||||||
|
Object.defineProperty(frameImgs[0], 'naturalHeight', { value: 225, configurable: true })
|
||||||
|
fireEvent.load(frameImgs[0])
|
||||||
|
fireEvent.load(frameImgs[1])
|
||||||
|
|
||||||
|
expect(screen.queryByTestId('print-frames-progress')).toBeNull()
|
||||||
|
const overlay = screen.getByTestId('print-annotation-overlay')
|
||||||
|
expect(overlay.querySelector('rect')).not.toBeNull()
|
||||||
|
expect(overlay.querySelector('polygon')).not.toBeNull()
|
||||||
|
expect(overlay.querySelector('path')).not.toBeNull()
|
||||||
|
|
||||||
|
// Clicking Print button invokes window.print()
|
||||||
|
fireEvent.click(screen.getByTestId('print-comments-button'))
|
||||||
|
expect(printMock).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses public share frame endpoint with password query param when shareId is set', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={videoAsset}
|
||||||
|
breadcrumbs={['Client Share']}
|
||||||
|
comments={[makeComment({ id: 'c-1', second: 3.25 })]}
|
||||||
|
shareId="share-99"
|
||||||
|
sharePassword="pw!"
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const img = container.querySelector('[data-testid="print-comment-frame"] img')
|
||||||
|
expect(img?.getAttribute('src')).toBe(
|
||||||
|
'/api/shares/share-99/files/asset-video-1/comments/frame?second=3.25&width=400&p=pw%21',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders an annotated reply at its own timestamp and waits for it before printing', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={videoAsset}
|
||||||
|
breadcrumbs={[]}
|
||||||
|
comments={[
|
||||||
|
makeComment({
|
||||||
|
second: 1,
|
||||||
|
replies: [
|
||||||
|
makeComment({
|
||||||
|
id: 'reply',
|
||||||
|
message: '',
|
||||||
|
second: 2,
|
||||||
|
annotations: [
|
||||||
|
{
|
||||||
|
type: 'box',
|
||||||
|
color: 'red',
|
||||||
|
points: [
|
||||||
|
[0.1, 0.1],
|
||||||
|
[0.5, 0.5],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const [commentFrame, replyFrame] = container.querySelectorAll(
|
||||||
|
'[data-testid="print-comment-frame"] img',
|
||||||
|
)
|
||||||
|
expect(replyFrame?.getAttribute('src')).toContain('second=2&')
|
||||||
|
fireEvent.load(commentFrame)
|
||||||
|
|
||||||
|
const printButton = screen.getByRole<HTMLButtonElement>('button', { name: 'Print' })
|
||||||
|
expect(printButton.disabled).toBe(true)
|
||||||
|
expect(screen.getByTestId('print-frames-progress').textContent).toContain('1/2')
|
||||||
|
fireEvent.load(replyFrame)
|
||||||
|
|
||||||
|
expect(screen.getByTestId('print-reply-item').querySelector('svg rect')).not.toBeNull()
|
||||||
|
expect(printButton.disabled).toBe(false)
|
||||||
|
fireEvent.click(printButton)
|
||||||
|
expect(printMock).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reuses image proxy URL directly for image assets without calling frame API', () => {
|
||||||
|
const imageAsset = {
|
||||||
|
...videoAsset,
|
||||||
|
id: 'asset-img-1',
|
||||||
|
name: 'poster.png',
|
||||||
|
proxyType: 'image',
|
||||||
|
media: {
|
||||||
|
proxyType: 'image',
|
||||||
|
imageTranscodes: [
|
||||||
|
{
|
||||||
|
id: 't1',
|
||||||
|
key: 'k1',
|
||||||
|
url: 'https://cdn.example.com/poster-600.webp',
|
||||||
|
width: 600,
|
||||||
|
height: 400,
|
||||||
|
size: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
videoTranscodes: [],
|
||||||
|
},
|
||||||
|
} as unknown as AssetInfo
|
||||||
|
|
||||||
|
const { container } = render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={imageAsset}
|
||||||
|
breadcrumbs={['Design']}
|
||||||
|
comments={[makeComment({ id: 'c-img', second: null, message: 'Adjust logo spacing' })]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.getByText('Sorted by oldest')).toBeDefined()
|
||||||
|
const img = container.querySelector('[data-testid="print-comment-frame"] img')
|
||||||
|
expect(img?.getAttribute('src')).toBe('https://cdn.example.com/poster-600.webp')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('supports PDF page formatting, 3D angle formatting, and audio without frame column', () => {
|
||||||
|
const pdfAsset = {
|
||||||
|
...videoAsset,
|
||||||
|
id: 'asset-pdf-1',
|
||||||
|
name: 'script.pdf',
|
||||||
|
proxyType: 'pdf',
|
||||||
|
media: { proxyType: 'pdf', imageTranscodes: [], videoTranscodes: [] },
|
||||||
|
} as unknown as AssetInfo
|
||||||
|
|
||||||
|
const { rerender } = render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={pdfAsset}
|
||||||
|
breadcrumbs={['Docs']}
|
||||||
|
comments={[makeComment({ id: 'c-pdf', second: 3, message: 'Fix typo on page 3' })]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
expect(screen.getByText('Sorted by page')).toBeDefined()
|
||||||
|
expect(screen.getByTestId('print-comment-timestamp').textContent).toBe('P3')
|
||||||
|
|
||||||
|
const modelAsset = {
|
||||||
|
...videoAsset,
|
||||||
|
id: 'asset-3d-1',
|
||||||
|
name: 'chair.glb',
|
||||||
|
proxyType: '3d',
|
||||||
|
media: { proxyType: '3d', imageTranscodes: [], videoTranscodes: [] },
|
||||||
|
} as unknown as AssetInfo
|
||||||
|
|
||||||
|
rerender(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={modelAsset}
|
||||||
|
breadcrumbs={['Models']}
|
||||||
|
comments={[makeComment({ id: 'c-3d', second: 3, message: 'Smooth bevel' })]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
expect(screen.getByText('Sorted by angle')).toBeDefined()
|
||||||
|
expect(screen.getByTestId('print-comment-timestamp').textContent).toBe('270°')
|
||||||
|
|
||||||
|
const audioAsset = {
|
||||||
|
...videoAsset,
|
||||||
|
id: 'asset-audio-1',
|
||||||
|
name: 'mix.wav',
|
||||||
|
proxyType: 'audio',
|
||||||
|
preview: null,
|
||||||
|
media: {
|
||||||
|
proxyType: 'audio',
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [],
|
||||||
|
metadata: { frameRate: 30 },
|
||||||
|
},
|
||||||
|
} as unknown as AssetInfo
|
||||||
|
|
||||||
|
rerender(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={audioAsset}
|
||||||
|
breadcrumbs={['Audio']}
|
||||||
|
comments={[makeComment({ id: 'c-aud', second: 2, message: 'Reduce reverb' })]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
expect(screen.queryByTestId('print-comment-frame')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows friendly fallback when a frame fails to load', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={videoAsset}
|
||||||
|
breadcrumbs={['Project']}
|
||||||
|
comments={[makeComment({ id: 'c-err', second: 2 })]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const img = container.querySelector('[data-testid="print-comment-frame"] img')!
|
||||||
|
fireEvent.error(img)
|
||||||
|
|
||||||
|
expect(screen.getByTestId('print-frame-error').textContent).toContain('Frame unavailable')
|
||||||
|
expect(screen.queryByTestId('print-frames-progress')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sizes header and comment frame containers tightly with zero padding across aspect ratios', () => {
|
||||||
|
const cases: Array<{
|
||||||
|
label: string
|
||||||
|
w: number
|
||||||
|
h: number
|
||||||
|
headerW: number
|
||||||
|
headerH: number
|
||||||
|
frameW: number
|
||||||
|
frameH: number
|
||||||
|
}> = [
|
||||||
|
{ label: '16:9', w: 1920, h: 1080, headerW: 96, headerH: 54, frameW: 200, frameH: 113 },
|
||||||
|
{ label: '9:16', w: 1080, h: 1920, headerW: 30, headerH: 54, frameW: 200, frameH: 356 },
|
||||||
|
{
|
||||||
|
label: '9:16 (704x1280)',
|
||||||
|
w: 704,
|
||||||
|
h: 1280,
|
||||||
|
headerW: 30,
|
||||||
|
headerH: 54,
|
||||||
|
frameW: 200,
|
||||||
|
frameH: 364,
|
||||||
|
},
|
||||||
|
{ label: '4:3', w: 1440, h: 1080, headerW: 72, headerH: 54, frameW: 200, frameH: 150 },
|
||||||
|
{ label: '3:4', w: 1080, h: 1440, headerW: 41, headerH: 54, frameW: 200, frameH: 267 },
|
||||||
|
{ label: '1:1', w: 1080, h: 1080, headerW: 54, headerH: 54, frameW: 200, frameH: 200 },
|
||||||
|
{ label: '21:9', w: 2560, h: 1080, headerW: 96, headerH: 41, frameW: 200, frameH: 84 },
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const c of cases) {
|
||||||
|
expect(fitHeaderThumbnailBox({ width: c.w, height: c.h })).toEqual({
|
||||||
|
width: c.headerW,
|
||||||
|
height: c.headerH,
|
||||||
|
})
|
||||||
|
expect(computeCommentFrameBox({ width: c.w, height: c.h })).toEqual({
|
||||||
|
width: c.frameW,
|
||||||
|
height: c.frameH,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotation metadata swaps raw dimensions when transcodes are absent
|
||||||
|
const rotatedAsset: AssetInfo = {
|
||||||
|
...videoAsset,
|
||||||
|
preview: {
|
||||||
|
thumbnailUrl: 'https://example.com/thumb.jpg',
|
||||||
|
originalWidth: 1920,
|
||||||
|
originalHeight: 1080,
|
||||||
|
rotation: 90,
|
||||||
|
},
|
||||||
|
media: {
|
||||||
|
proxyType: 'video',
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
expect(resolveAssetDisplayDimensions(rotatedAsset)).toEqual({ width: 1080, height: 1920 })
|
||||||
|
|
||||||
|
// Verify DOM container styles & SVG viewBox on a 9:16 portrait video
|
||||||
|
const portraitAsset: AssetInfo = {
|
||||||
|
...videoAsset,
|
||||||
|
preview: {
|
||||||
|
thumbnailUrl: 'https://example.com/portrait-thumb.jpg',
|
||||||
|
originalWidth: 704,
|
||||||
|
originalHeight: 1280,
|
||||||
|
},
|
||||||
|
media: {
|
||||||
|
proxyType: 'video',
|
||||||
|
imageTranscodes: [],
|
||||||
|
videoTranscodes: [
|
||||||
|
{
|
||||||
|
id: 'v1',
|
||||||
|
key: 'k1',
|
||||||
|
url: 'https://example.com/v.mp4',
|
||||||
|
width: 704,
|
||||||
|
height: 1280,
|
||||||
|
size: 1000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
metadata: { frameRate: 24 },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const { container } = render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={portraitAsset}
|
||||||
|
breadcrumbs={['Project']}
|
||||||
|
comments={[
|
||||||
|
makeComment({
|
||||||
|
id: 'c-portrait',
|
||||||
|
second: 1.2,
|
||||||
|
annotations: [
|
||||||
|
{
|
||||||
|
type: 'box',
|
||||||
|
color: '#ef4444',
|
||||||
|
points: [
|
||||||
|
[0.1, 0.1],
|
||||||
|
[0.9, 0.9],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Before image loads, containers already size to metadata aspect ratio (no layout shift)
|
||||||
|
const headerBox = screen.getByTestId('print-header-thumbnail')
|
||||||
|
expect(headerBox.style.width).toBe('30px')
|
||||||
|
expect(headerBox.style.height).toBe('54px')
|
||||||
|
|
||||||
|
const frameBox = screen.getByTestId('print-comment-frame')
|
||||||
|
expect(frameBox.style.width).toBe('200px')
|
||||||
|
expect(frameBox.style.height).toBe('364px')
|
||||||
|
|
||||||
|
// When a frame loads with different actual dimensions (e.g. a 3:4 page), container & SVG update
|
||||||
|
const frameImg = container.querySelector('[data-testid="print-comment-frame"] img')!
|
||||||
|
Object.defineProperty(frameImg, 'naturalWidth', { value: 300, configurable: true })
|
||||||
|
Object.defineProperty(frameImg, 'naturalHeight', { value: 400, configurable: true })
|
||||||
|
fireEvent.load(frameImg)
|
||||||
|
|
||||||
|
expect(frameBox.style.width).toBe('200px')
|
||||||
|
expect(frameBox.style.height).toBe('267px')
|
||||||
|
expect(screen.getByTestId('print-annotation-overlay').getAttribute('viewBox')).toBe(
|
||||||
|
'0 0 200 267',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders a lock indicator for internal comments', () => {
|
||||||
|
render(
|
||||||
|
<PrintCommentsView
|
||||||
|
asset={{
|
||||||
|
id: 'asset-1',
|
||||||
|
name: 'video.mp4',
|
||||||
|
sizeByte: 100,
|
||||||
|
fileCount: 1,
|
||||||
|
type: 'file',
|
||||||
|
status: 'processed',
|
||||||
|
proxyType: 'video',
|
||||||
|
createdAt: '2026-11-25T14:53:00.000Z',
|
||||||
|
updatedAt: '2026-11-25T14:53:00.000Z',
|
||||||
|
}}
|
||||||
|
breadcrumbs={['Project']}
|
||||||
|
comments={[
|
||||||
|
makeComment({ id: 'c-pub', isInternal: false }),
|
||||||
|
makeComment({ id: 'c-int', isInternal: true }),
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.getAllByTestId('print-comment-internal')).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,699 @@
|
|||||||
|
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||||
|
import { Button } from '@/ui/components/ui/button'
|
||||||
|
import { DrawAnnotation, ShumaiLogo } from '@/ui/components/ui/icons'
|
||||||
|
import { getViewerForFile } from '@/ui/components/viewers/registry'
|
||||||
|
import { formatFrame, formatTimecode } from '@/ui/components/viewers/video/utils'
|
||||||
|
import { isImageFileName } from '@/ui/lib/media'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import { useUiStore } from '@/ui/stores/ui'
|
||||||
|
import type { AssetInfo, CommentInfo } from '@shumai/dtos'
|
||||||
|
import {
|
||||||
|
ArrowDownWideNarrow,
|
||||||
|
CheckCircle2,
|
||||||
|
FileAudio,
|
||||||
|
FileIcon,
|
||||||
|
FileText,
|
||||||
|
Loader2,
|
||||||
|
Lock,
|
||||||
|
Printer,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import Markdown from 'react-markdown'
|
||||||
|
import { parseAnnotations } from './annotation-overlay-svg'
|
||||||
|
import { CommentFrameThumbnail } from './comment-frame-thumbnail'
|
||||||
|
import {
|
||||||
|
fitHeaderThumbnailBox,
|
||||||
|
HEADER_MAX_HEIGHT,
|
||||||
|
resolveAssetDisplayDimensions,
|
||||||
|
type Dimensions,
|
||||||
|
} from './sizing'
|
||||||
|
|
||||||
|
export type PrintSortMode = 'position' | 'oldest' | 'newest'
|
||||||
|
|
||||||
|
export interface PrintCommentsViewProps {
|
||||||
|
asset: AssetInfo
|
||||||
|
breadcrumbs: string[]
|
||||||
|
comments: CommentInfo[]
|
||||||
|
shareId?: string
|
||||||
|
sharePassword?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function getHeaderThumbnailUrl(asset: AssetInfo): string | null {
|
||||||
|
if (asset.preview?.thumbnailUrl) return asset.preview.thumbnailUrl
|
||||||
|
if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) {
|
||||||
|
const sorted = [...asset.media.imageTranscodes]
|
||||||
|
.filter((t) => Boolean(t.url))
|
||||||
|
.sort((a, b) => (a.width || 0) - (b.width || 0))
|
||||||
|
if (sorted[0]?.url) return sorted[0].url
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function getImageCommentThumbnailUrl(asset: AssetInfo): string | null {
|
||||||
|
if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) {
|
||||||
|
const valid = asset.media.imageTranscodes.filter((t) => Boolean(t.url))
|
||||||
|
const adequate = valid
|
||||||
|
.filter((t) => (t.width || 0) >= 400)
|
||||||
|
.sort((a, b) => (a.width || 0) - (b.width || 0))
|
||||||
|
if (adequate[0]?.url) return adequate[0].url
|
||||||
|
const largest = [...valid].sort((a, b) => (b.width || 0) - (a.width || 0))
|
||||||
|
if (largest[0]?.url) return largest[0].url
|
||||||
|
}
|
||||||
|
return asset.preview?.thumbnailUrl || null
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFrameEndpointUrl(params: {
|
||||||
|
assetId: string
|
||||||
|
second: number
|
||||||
|
width?: number
|
||||||
|
shareId?: string
|
||||||
|
sharePassword?: string
|
||||||
|
}): string {
|
||||||
|
const qs = new URLSearchParams({
|
||||||
|
second: String(params.second),
|
||||||
|
width: String(params.width ?? 400),
|
||||||
|
})
|
||||||
|
if (params.shareId) {
|
||||||
|
if (params.sharePassword) {
|
||||||
|
qs.set('p', params.sharePassword)
|
||||||
|
}
|
||||||
|
return `/api/shares/${encodeURIComponent(params.shareId)}/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}`
|
||||||
|
}
|
||||||
|
return `/api/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatShortDate(iso?: string | null): string {
|
||||||
|
if (!iso) return ''
|
||||||
|
const date = new Date(iso)
|
||||||
|
if (Number.isNaN(date.getTime())) return ''
|
||||||
|
return new Intl.DateTimeFormat(undefined, {
|
||||||
|
month: 'numeric',
|
||||||
|
day: 'numeric',
|
||||||
|
year: '2-digit',
|
||||||
|
}).format(date)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCommentDateTime(iso?: string | null): string {
|
||||||
|
if (!iso) return ''
|
||||||
|
const date = new Date(iso)
|
||||||
|
if (Number.isNaN(date.getTime())) return ''
|
||||||
|
const datePart = new Intl.DateTimeFormat(undefined, {
|
||||||
|
month: 'numeric',
|
||||||
|
day: 'numeric',
|
||||||
|
year: '2-digit',
|
||||||
|
}).format(date)
|
||||||
|
const timePart = new Intl.DateTimeFormat(undefined, {
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: '2-digit',
|
||||||
|
}).format(date)
|
||||||
|
return `${datePart} · ${timePart}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitMiddleTruncate(name: string): { head: string; tail: string } {
|
||||||
|
if (name.length <= 16) return { head: name, tail: '' }
|
||||||
|
const tailLen = 10
|
||||||
|
return {
|
||||||
|
head: name.slice(0, name.length - tailLen),
|
||||||
|
tail: name.slice(name.length - tailLen),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function preprocessMarkdown(text: string): string {
|
||||||
|
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPlainCommentText(comment: CommentInfo): React.ReactNode {
|
||||||
|
const text = comment.message ?? ''
|
||||||
|
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
|
||||||
|
return parts.map((part, index) => {
|
||||||
|
if (part.match(/^<@[a-zA-Z0-9_-]+>$/)) {
|
||||||
|
const userId = part.slice(2, -1)
|
||||||
|
const mentionedUser = comment.mentions?.find((u) => u.id === userId)
|
||||||
|
return (
|
||||||
|
<span key={index} className="font-medium text-primary">
|
||||||
|
@{mentionedUser?.name || 'Unknown'}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return <React.Fragment key={index}>{part}</React.Fragment>
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HeaderThumbnailProps {
|
||||||
|
url: string | null
|
||||||
|
proxyType: string | null
|
||||||
|
initialDimensions: Dimensions | null
|
||||||
|
}
|
||||||
|
|
||||||
|
const HeaderThumbnail: React.FC<HeaderThumbnailProps> = ({ url, proxyType, initialDimensions }) => {
|
||||||
|
const [naturalSize, setNaturalSize] = useState<Dimensions | null>(initialDimensions)
|
||||||
|
const imgRef = useRef<HTMLImageElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setNaturalSize(initialDimensions)
|
||||||
|
const img = imgRef.current
|
||||||
|
if (img && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||||
|
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||||
|
}
|
||||||
|
}, [url, initialDimensions])
|
||||||
|
|
||||||
|
if (!url) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="flex shrink-0 items-center justify-center overflow-hidden rounded-sm border border-border bg-muted/40"
|
||||||
|
style={{ width: HEADER_MAX_HEIGHT, height: HEADER_MAX_HEIGHT }}
|
||||||
|
data-testid="print-header-thumbnail"
|
||||||
|
>
|
||||||
|
{proxyType === 'audio' ? (
|
||||||
|
<FileAudio className="h-5 w-5 text-muted-foreground" />
|
||||||
|
) : proxyType === 'pdf' ? (
|
||||||
|
<FileText className="h-5 w-5 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<FileIcon className="h-5 w-5 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { width, height } = fitHeaderThumbnailBox(naturalSize)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="flex shrink-0 items-center justify-center overflow-hidden rounded-sm border border-border transparency-checkerboard"
|
||||||
|
style={{ width, height }}
|
||||||
|
data-testid="print-header-thumbnail"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
ref={imgRef}
|
||||||
|
src={url}
|
||||||
|
alt=""
|
||||||
|
onLoad={(e) => {
|
||||||
|
const img = e.currentTarget
|
||||||
|
if (img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||||
|
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="block h-full w-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PrintCommentsView: React.FC<PrintCommentsViewProps> = ({
|
||||||
|
asset,
|
||||||
|
breadcrumbs,
|
||||||
|
comments,
|
||||||
|
shareId,
|
||||||
|
sharePassword,
|
||||||
|
}) => {
|
||||||
|
const { videoTimeDisplayMode } = useUiStore()
|
||||||
|
const viewerDef = useMemo(() => getViewerForFile(asset), [asset])
|
||||||
|
const proxyType = asset.proxyType ?? asset.media?.proxyType ?? null
|
||||||
|
|
||||||
|
const hasPositionSort = Boolean(viewerDef.commentsConfig?.hasTimestamp)
|
||||||
|
const [sortMode, setSortMode] = useState<PrintSortMode>(hasPositionSort ? 'position' : 'oldest')
|
||||||
|
const [settledFrameUrls, setSettledFrameUrls] = useState<Record<string, string>>({})
|
||||||
|
|
||||||
|
const frameRate = viewerDef.commentsConfig?.hasTimestamp
|
||||||
|
? asset.media?.metadata?.frameRate || 30
|
||||||
|
: undefined
|
||||||
|
const startTimecode = viewerDef.commentsConfig?.hasTimestamp
|
||||||
|
? asset.media?.metadata?.startTimecode
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
const formatCommentTimestamp = useCallback(
|
||||||
|
(second: number | null | undefined): string => {
|
||||||
|
if (second === null || second === undefined) return ''
|
||||||
|
if (viewerDef.commentsConfig?.formatTimestamp) {
|
||||||
|
return viewerDef.commentsConfig.formatTimestamp(second)
|
||||||
|
}
|
||||||
|
if (!frameRate) return ''
|
||||||
|
const frameIndex = formatFrame(second, frameRate)
|
||||||
|
return formatTimecode(frameIndex, frameRate, videoTimeDisplayMode, startTimecode)
|
||||||
|
},
|
||||||
|
[viewerDef, frameRate, videoTimeDisplayMode, startTimecode],
|
||||||
|
)
|
||||||
|
|
||||||
|
const sortedComments = useMemo(() => {
|
||||||
|
const list = [...comments]
|
||||||
|
if (sortMode === 'position') {
|
||||||
|
list.sort((a, b) => {
|
||||||
|
const aHas = a.second !== null && a.second !== undefined
|
||||||
|
const bHas = b.second !== null && b.second !== undefined
|
||||||
|
if (aHas && bHas) {
|
||||||
|
if (a.second! !== b.second!) return a.second! - b.second!
|
||||||
|
return a.id.localeCompare(b.id)
|
||||||
|
}
|
||||||
|
if (aHas) return -1
|
||||||
|
if (bHas) return 1
|
||||||
|
return a.id.localeCompare(b.id)
|
||||||
|
})
|
||||||
|
} else if (sortMode === 'newest') {
|
||||||
|
list.sort((a, b) => b.id.localeCompare(a.id))
|
||||||
|
} else {
|
||||||
|
list.sort((a, b) => a.id.localeCompare(b.id))
|
||||||
|
}
|
||||||
|
return list
|
||||||
|
}, [comments, sortMode])
|
||||||
|
|
||||||
|
const hasVisualThumbnailColumn =
|
||||||
|
proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf' || proxyType === 'image'
|
||||||
|
|
||||||
|
const getCommentFrameUrl = useCallback(
|
||||||
|
(comment: CommentInfo): string | null => {
|
||||||
|
if (!hasVisualThumbnailColumn) return null
|
||||||
|
if (proxyType === 'image') {
|
||||||
|
return getImageCommentThumbnailUrl(asset)
|
||||||
|
}
|
||||||
|
if (proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf') {
|
||||||
|
if (comment.second !== null && comment.second !== undefined) {
|
||||||
|
return buildFrameEndpointUrl({
|
||||||
|
assetId: asset.id,
|
||||||
|
second: comment.second,
|
||||||
|
width: 400,
|
||||||
|
shareId,
|
||||||
|
sharePassword,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// If an untimestamped comment still carries visual annotations, show the asset poster/thumbnail
|
||||||
|
const anns = parseAnnotations(comment.annotations)
|
||||||
|
if (anns.length > 0) {
|
||||||
|
return getHeaderThumbnailUrl(asset)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
},
|
||||||
|
[hasVisualThumbnailColumn, proxyType, asset, shareId, sharePassword],
|
||||||
|
)
|
||||||
|
|
||||||
|
const frameUrls = useMemo(() => {
|
||||||
|
const urls = new Map<string, string>()
|
||||||
|
for (const comment of comments) {
|
||||||
|
const url = getCommentFrameUrl(comment)
|
||||||
|
if (url) urls.set(comment.id, url)
|
||||||
|
|
||||||
|
for (const reply of comment.replies ?? []) {
|
||||||
|
if (parseAnnotations(reply.annotations).length === 0) continue
|
||||||
|
const replyUrl = getCommentFrameUrl(reply)
|
||||||
|
if (replyUrl) urls.set(reply.id, replyUrl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return urls
|
||||||
|
}, [comments, getCommentFrameUrl])
|
||||||
|
|
||||||
|
const settledFrameCount = Array.from(frameUrls).filter(
|
||||||
|
([id, url]) => settledFrameUrls[id] === url,
|
||||||
|
).length
|
||||||
|
const isLoadingFrames = settledFrameCount < frameUrls.size
|
||||||
|
|
||||||
|
const sortIndicatorLabel = useMemo(() => {
|
||||||
|
if (sortMode === 'oldest') return m.print_comments_sorted_by_oldest()
|
||||||
|
if (sortMode === 'newest') return m.print_comments_sorted_by_newest()
|
||||||
|
if (proxyType === 'pdf') return m.print_comments_sorted_by_page()
|
||||||
|
if (proxyType === '3d') return m.print_comments_sorted_by_angle()
|
||||||
|
return m.print_comments_sorted_by_timecode()
|
||||||
|
}, [sortMode, proxyType])
|
||||||
|
|
||||||
|
const positionSortOptionLabel = useMemo(() => {
|
||||||
|
if (proxyType === 'pdf') return m.print_comments_sort_page()
|
||||||
|
if (proxyType === '3d') return m.print_comments_sort_angle()
|
||||||
|
return m.print_comments_sort_timecode()
|
||||||
|
}, [proxyType])
|
||||||
|
|
||||||
|
const headerThumbUrl = useMemo(() => getHeaderThumbnailUrl(asset), [asset])
|
||||||
|
const assetDimensions = useMemo(() => resolveAssetDisplayDimensions(asset), [asset])
|
||||||
|
const { head: nameHead, tail: nameTail } = splitMiddleTruncate(asset.name || '')
|
||||||
|
const creatorAndDate = [asset.creator?.name, formatShortDate(asset.createdAt)]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ')
|
||||||
|
|
||||||
|
const commentCountLabel =
|
||||||
|
comments.length === 1
|
||||||
|
? m.print_comments_count_one()
|
||||||
|
: m.print_comments_count({ count: String(comments.length) })
|
||||||
|
|
||||||
|
const renderFrame = (commentId: string, annotations: ReturnType<typeof parseAnnotations>) => {
|
||||||
|
const url = frameUrls.get(commentId)
|
||||||
|
if (!url) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CommentFrameThumbnail
|
||||||
|
key={url}
|
||||||
|
src={url}
|
||||||
|
annotations={annotations}
|
||||||
|
initialDimensions={assetDimensions}
|
||||||
|
onStatusChange={() =>
|
||||||
|
setSettledFrameUrls((prev) =>
|
||||||
|
prev[commentId] === url ? prev : { ...prev, [commentId]: url },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderCommentEntry = (
|
||||||
|
comment: CommentInfo,
|
||||||
|
options: {
|
||||||
|
indexNumber?: number
|
||||||
|
isReply: boolean
|
||||||
|
hasReplies: boolean
|
||||||
|
isLastReply: boolean
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const timestamp = formatCommentTimestamp(comment.second)
|
||||||
|
const annotations = parseAnnotations(comment.annotations)
|
||||||
|
const hasAnnotations = annotations.length > 0
|
||||||
|
const creatorName = comment.creator?.name || 'Unknown'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={comment.id}
|
||||||
|
className={`relative flex gap-2.5 ${options.isReply ? 'pt-3' : ''}`}
|
||||||
|
data-testid={options.isReply ? 'print-reply-item' : 'print-comment-item'}
|
||||||
|
>
|
||||||
|
{/* Avatar + vertical thread connector matching Frame.io / Shumai threads */}
|
||||||
|
<div className="relative flex w-6 shrink-0 flex-col items-center">
|
||||||
|
{options.isReply && (
|
||||||
|
<div className="absolute -top-3 left-1/2 h-3.5 w-px -translate-x-1/2 bg-border" />
|
||||||
|
)}
|
||||||
|
{((options.hasReplies && !options.isReply) ||
|
||||||
|
(options.isReply && !options.isLastReply)) && (
|
||||||
|
<div className="absolute top-6 bottom-[-12px] left-1/2 w-px -translate-x-1/2 bg-border" />
|
||||||
|
)}
|
||||||
|
<Avatar className="relative z-10 h-6 w-6">
|
||||||
|
{comment.creator?.image && (
|
||||||
|
<AvatarImage src={comment.creator.image} alt={creatorName} className="object-cover" />
|
||||||
|
)}
|
||||||
|
<AvatarFallback className="bg-muted text-[10px] font-semibold text-foreground">
|
||||||
|
{creatorName[0]?.toUpperCase() || 'U'}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Entry content */}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
{/* Author + timestamp + #index + completed status */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
|
||||||
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
|
<span className="truncate text-sm font-semibold text-foreground">{creatorName}</span>
|
||||||
|
<span className="whitespace-nowrap text-xs text-muted-foreground">
|
||||||
|
{formatCommentDateTime(comment.createdAt)}
|
||||||
|
</span>
|
||||||
|
{comment.isInternal && (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center text-muted-foreground"
|
||||||
|
title={m.internal_comment_tooltip()}
|
||||||
|
aria-label={m.internal_comment_tooltip()}
|
||||||
|
data-testid="print-comment-internal"
|
||||||
|
>
|
||||||
|
<Lock className="h-3.5 w-3.5" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex shrink-0 items-center gap-2">
|
||||||
|
{comment.isCompleted && (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700"
|
||||||
|
data-testid="print-comment-completed"
|
||||||
|
>
|
||||||
|
<CheckCircle2 className="h-3 w-3" />
|
||||||
|
<span>{m.print_comments_completed()}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{options.indexNumber !== undefined && (
|
||||||
|
<span className="text-xs font-medium text-muted-foreground">
|
||||||
|
<span className="opacity-70">#</span>
|
||||||
|
{options.indexNumber}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Prefix (timecode / page / angle + annotation indicator) + Comment text */}
|
||||||
|
<div className="mt-1 text-sm leading-relaxed text-foreground">
|
||||||
|
{(timestamp || hasAnnotations) && (
|
||||||
|
<span className="mr-2 inline-flex items-center gap-1.5 align-middle">
|
||||||
|
{timestamp && (
|
||||||
|
<span
|
||||||
|
className="inline-block rounded bg-muted px-1.5 py-0.5 font-mono text-xs font-semibold leading-none text-foreground"
|
||||||
|
data-testid="print-comment-timestamp"
|
||||||
|
>
|
||||||
|
{timestamp}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{hasAnnotations && (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center text-muted-foreground"
|
||||||
|
title={m.print_comments_has_annotations()}
|
||||||
|
aria-label={m.print_comments_has_annotations()}
|
||||||
|
>
|
||||||
|
<DrawAnnotation className="h-3.5 w-3.5" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{comment.sessionId && comment.message ? (
|
||||||
|
<div className="prose prose-sm mt-0.5 max-w-none break-words text-foreground">
|
||||||
|
<Markdown>{preprocessMarkdown(comment.message)}</Markdown>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="whitespace-pre-wrap break-words">
|
||||||
|
{renderPlainCommentText(comment)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{options.isReply && frameUrls.has(comment.id) && (
|
||||||
|
<div className="mt-2">{renderFrame(comment.id, annotations)}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Attachments */}
|
||||||
|
{comment.attachments && comment.attachments.length > 0 && (
|
||||||
|
<div className="mt-2 flex flex-wrap gap-2" data-testid="print-comment-attachments">
|
||||||
|
{comment.attachments.map((att) => {
|
||||||
|
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
|
||||||
|
const name = decodeURIComponent(rawName)
|
||||||
|
const isImage = isImageFileName(name)
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={att.id}
|
||||||
|
className="inline-flex max-w-full items-center gap-2 rounded-md border border-border bg-card px-2 py-1"
|
||||||
|
>
|
||||||
|
{isImage ? (
|
||||||
|
<img
|
||||||
|
src={att.url}
|
||||||
|
alt={name}
|
||||||
|
className="h-10 w-10 shrink-0 rounded object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
<span className="max-w-[220px] truncate text-xs font-medium text-foreground">
|
||||||
|
{name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Emoji reactions */}
|
||||||
|
{comment.reactionCounts && comment.reactionCounts.length > 0 && (
|
||||||
|
<div
|
||||||
|
className="mt-2 flex flex-wrap items-center gap-1.5"
|
||||||
|
data-testid="print-comment-reactions"
|
||||||
|
>
|
||||||
|
{comment.reactionCounts.map((reaction) => (
|
||||||
|
<span
|
||||||
|
key={reaction.code}
|
||||||
|
className="inline-flex items-center gap-1 rounded-full border border-border bg-card px-2 py-0.5 text-xs text-foreground"
|
||||||
|
>
|
||||||
|
<span className="leading-none">{reaction.code}</span>
|
||||||
|
<span className="font-semibold">{reaction.count}</span>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="print-sheet min-h-screen bg-background text-foreground">
|
||||||
|
{/* Non-printable action toolbar */}
|
||||||
|
<div className="sticky top-0 z-20 border-b border-border bg-background/95 backdrop-blur-sm print:hidden">
|
||||||
|
<div className="mx-auto flex max-w-[860px] flex-wrap items-center justify-between gap-3 px-6 py-3">
|
||||||
|
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
{isLoadingFrames ? (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center gap-2 font-medium text-foreground"
|
||||||
|
data-testid="print-frames-progress"
|
||||||
|
>
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />
|
||||||
|
<span>
|
||||||
|
{m.print_comments_loading_frames({
|
||||||
|
loaded: String(settledFrameCount),
|
||||||
|
total: String(frameUrls.size),
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span>{commentCountLabel}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="inline-flex items-center rounded-md border border-border bg-card p-0.5 text-xs">
|
||||||
|
{hasPositionSort && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSortMode('position')}
|
||||||
|
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||||
|
sortMode === 'position'
|
||||||
|
? 'bg-background text-foreground shadow-xs'
|
||||||
|
: 'text-muted-foreground hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{positionSortOptionLabel}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSortMode('oldest')}
|
||||||
|
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||||
|
sortMode === 'oldest'
|
||||||
|
? 'bg-background text-foreground shadow-xs'
|
||||||
|
: 'text-muted-foreground hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{m.print_comments_sort_oldest()}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSortMode('newest')}
|
||||||
|
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||||
|
sortMode === 'newest'
|
||||||
|
? 'bg-background text-foreground shadow-xs'
|
||||||
|
: 'text-muted-foreground hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{m.print_comments_sort_newest()}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
disabled={isLoadingFrames}
|
||||||
|
onClick={() => window.print()}
|
||||||
|
className="gap-1.5 cursor-pointer"
|
||||||
|
data-testid="print-comments-button"
|
||||||
|
>
|
||||||
|
<Printer className="h-3.5 w-3.5" />
|
||||||
|
<span>{m.print()}</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Printable document body */}
|
||||||
|
<div className="mx-auto max-w-[860px] px-6 py-8 print:max-w-none print:px-0 print:py-0">
|
||||||
|
{/* Document Header */}
|
||||||
|
<header className="flex items-center gap-4 pb-5">
|
||||||
|
<HeaderThumbnail
|
||||||
|
url={headerThumbUrl}
|
||||||
|
proxyType={proxyType}
|
||||||
|
initialDimensions={assetDimensions}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col justify-between gap-1.5">
|
||||||
|
{/* Top row: Breadcrumbs + Shumai Logo */}
|
||||||
|
<div className="flex items-center justify-between gap-4">
|
||||||
|
<nav
|
||||||
|
aria-label="Breadcrumb"
|
||||||
|
className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
|
||||||
|
>
|
||||||
|
{breadcrumbs.map((segment, i) => (
|
||||||
|
<React.Fragment key={`${segment}-${i}`}>
|
||||||
|
{i > 0 && <span className="shrink-0 opacity-60">/</span>}
|
||||||
|
<span className="truncate">{segment}</span>
|
||||||
|
</React.Fragment>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<ShumaiLogo className="h-4 w-4 shrink-0 text-foreground" aria-label="Shumai" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bottom row: Filename + Creator & Date */}
|
||||||
|
<div className="flex items-baseline justify-between gap-4">
|
||||||
|
<h1
|
||||||
|
className="flex min-w-0 text-base font-semibold leading-tight text-foreground"
|
||||||
|
title={asset.name}
|
||||||
|
>
|
||||||
|
<span className="truncate">{nameHead}</span>
|
||||||
|
{nameTail && <span className="shrink-0">{nameTail}</span>}
|
||||||
|
</h1>
|
||||||
|
{creatorAndDate && (
|
||||||
|
<span className="shrink-0 whitespace-nowrap text-xs text-muted-foreground">
|
||||||
|
{creatorAndDate}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="border-b border-border" />
|
||||||
|
|
||||||
|
{/* Sort Indicator */}
|
||||||
|
<div className="flex items-center gap-1.5 py-4 text-xs font-medium text-muted-foreground">
|
||||||
|
<ArrowDownWideNarrow className="h-4 w-4" />
|
||||||
|
<span>{sortIndicatorLabel}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Comments List */}
|
||||||
|
{sortedComments.length === 0 ? (
|
||||||
|
<div className="py-12 text-center text-sm text-muted-foreground">
|
||||||
|
{m.print_comments_empty()}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="divide-y divide-border">
|
||||||
|
{sortedComments.map((comment, idx) => {
|
||||||
|
const annotations = parseAnnotations(comment.annotations)
|
||||||
|
const replies = comment.replies ?? []
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article
|
||||||
|
key={comment.id}
|
||||||
|
className="flex gap-5 py-5 break-inside-avoid"
|
||||||
|
data-testid="print-comment-thread"
|
||||||
|
>
|
||||||
|
{hasVisualThumbnailColumn && (
|
||||||
|
<div className="w-[200px] shrink-0">{renderFrame(comment.id, annotations)}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
{renderCommentEntry(comment, {
|
||||||
|
indexNumber: idx + 1,
|
||||||
|
isReply: false,
|
||||||
|
hasReplies: replies.length > 0,
|
||||||
|
isLastReply: false,
|
||||||
|
})}
|
||||||
|
{replies.map((reply, replyIdx) =>
|
||||||
|
renderCommentEntry(reply, {
|
||||||
|
isReply: true,
|
||||||
|
hasReplies: false,
|
||||||
|
isLastReply: replyIdx === replies.length - 1,
|
||||||
|
}),
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import type { AssetInfo } from '@shumai/dtos'
|
||||||
|
|
||||||
|
export const HEADER_MAX_WIDTH = 96
|
||||||
|
export const HEADER_MAX_HEIGHT = 54
|
||||||
|
export const FRAME_FIXED_WIDTH = 200
|
||||||
|
export const DEFAULT_FRAME_HEIGHT = 112
|
||||||
|
export const ERROR_MIN_HEIGHT = 112
|
||||||
|
|
||||||
|
export interface Dimensions {
|
||||||
|
width: number
|
||||||
|
height: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidDimensions(w?: number | null, h?: number | null): boolean {
|
||||||
|
return (
|
||||||
|
typeof w === 'number' &&
|
||||||
|
typeof h === 'number' &&
|
||||||
|
Number.isFinite(w) &&
|
||||||
|
Number.isFinite(h) &&
|
||||||
|
w > 0 &&
|
||||||
|
h > 0
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the asset's display dimensions from transcode/preview/metadata info so
|
||||||
|
* thumbnail containers can size accurately before images finish loading.
|
||||||
|
*/
|
||||||
|
export function resolveAssetDisplayDimensions(asset: AssetInfo): Dimensions | null {
|
||||||
|
const videoTranscode = asset.media?.videoTranscodes?.find((t) =>
|
||||||
|
isValidDimensions(t.width, t.height),
|
||||||
|
)
|
||||||
|
if (videoTranscode) {
|
||||||
|
return { width: videoTranscode.width, height: videoTranscode.height }
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageTranscode = asset.media?.imageTranscodes?.find((t) =>
|
||||||
|
isValidDimensions(t.width, t.height),
|
||||||
|
)
|
||||||
|
if (imageTranscode) {
|
||||||
|
return { width: imageTranscode.width, height: imageTranscode.height }
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawWidth = asset.preview?.originalWidth ?? asset.media?.metadata?.originalWidth
|
||||||
|
const rawHeight = asset.preview?.originalHeight ?? asset.media?.metadata?.originalHeight
|
||||||
|
if (isValidDimensions(rawWidth, rawHeight)) {
|
||||||
|
const rotation = asset.preview?.rotation ?? asset.media?.metadata?.rotation ?? 0
|
||||||
|
const isQuarterTurn = Math.abs(Math.round(rotation)) % 180 === 90
|
||||||
|
return isQuarterTurn
|
||||||
|
? { width: rawHeight!, height: rawWidth! }
|
||||||
|
: { width: rawWidth!, height: rawHeight! }
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fits the header thumbnail inside a 96x54 bounding box and shrink-wraps to the
|
||||||
|
* media's exact aspect ratio so there is zero empty padding.
|
||||||
|
*/
|
||||||
|
export function fitHeaderThumbnailBox(dimensions: Dimensions | null): Dimensions {
|
||||||
|
if (!dimensions || !isValidDimensions(dimensions.width, dimensions.height)) {
|
||||||
|
return { width: HEADER_MAX_WIDTH, height: HEADER_MAX_HEIGHT }
|
||||||
|
}
|
||||||
|
const scale = Math.min(HEADER_MAX_WIDTH / dimensions.width, HEADER_MAX_HEIGHT / dimensions.height)
|
||||||
|
return {
|
||||||
|
width: Math.max(1, Math.round(dimensions.width * scale)),
|
||||||
|
height: Math.max(1, Math.round(dimensions.height * scale)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes the comment screenshot container with fixed 200px width and dynamic
|
||||||
|
* height matching the media's exact aspect ratio (zero letterboxing/pillarboxing).
|
||||||
|
*/
|
||||||
|
export function computeCommentFrameBox(dimensions: Dimensions | null): Dimensions {
|
||||||
|
if (!dimensions || !isValidDimensions(dimensions.width, dimensions.height)) {
|
||||||
|
return { width: FRAME_FIXED_WIDTH, height: DEFAULT_FRAME_HEIGHT }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
width: FRAME_FIXED_WIDTH,
|
||||||
|
height: Math.max(1, Math.round(FRAME_FIXED_WIDTH * (dimensions.height / dimensions.width))),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import { m } from '@/ui/paraglide/messages.js'
|
|||||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
||||||
import { useEffect, useState, useMemo, useRef } from 'react'
|
import { useEffect, useState, useMemo, useRef } from 'react'
|
||||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||||
|
import { usePublicShareView } from '@/ui/hooks/use-public-share-view'
|
||||||
import { TopNav } from './top-nav'
|
import { TopNav } from './top-nav'
|
||||||
import { FileBrowser } from './file-browser/file-browser'
|
import { FileBrowser } from './file-browser/file-browser'
|
||||||
import { MobileFileBrowser } from './file-browser/mobile-file-browser'
|
import { MobileFileBrowser } from './file-browser/mobile-file-browser'
|
||||||
@@ -127,6 +128,7 @@ export function PublicShareManager({
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
if (res.status === 401) throw new Error('Unauthorized')
|
if (res.status === 401) throw new Error('Unauthorized')
|
||||||
|
if (!res.ok) throw new Error('Failed to fetch shared asset')
|
||||||
return (await res.json()) as unknown as AssetInfo
|
return (await res.json()) as unknown as AssetInfo
|
||||||
},
|
},
|
||||||
enabled: !!shareInfo && !!currentFolderId,
|
enabled: !!shareInfo && !!currentFolderId,
|
||||||
@@ -258,6 +260,7 @@ export function PublicShareManager({
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
if (res.status === 401) throw new Error('Unauthorized')
|
if (res.status === 401) throw new Error('Unauthorized')
|
||||||
|
if (!res.ok) throw new Error('Failed to fetch shared asset')
|
||||||
return (await res.json()) as unknown as AssetInfo
|
return (await res.json()) as unknown as AssetInfo
|
||||||
},
|
},
|
||||||
enabled: !!viewingFileId && !!shareInfo,
|
enabled: !!viewingFileId && !!shareInfo,
|
||||||
@@ -277,6 +280,7 @@ export function PublicShareManager({
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
if (res.status === 401) throw new Error('Unauthorized')
|
if (res.status === 401) throw new Error('Unauthorized')
|
||||||
|
if (!res.ok) throw new Error('Failed to fetch shared asset')
|
||||||
return (await res.json()) as unknown as AssetInfo
|
return (await res.json()) as unknown as AssetInfo
|
||||||
},
|
},
|
||||||
enabled: !!versionId && !!shareInfo,
|
enabled: !!versionId && !!shareInfo,
|
||||||
@@ -286,6 +290,12 @@ export function PublicShareManager({
|
|||||||
// or the stack itself) is what we actually display.
|
// or the stack itself) is what we actually display.
|
||||||
const viewingFileData = versionId ? versionFileData : stackFileData
|
const viewingFileData = versionId ? versionFileData : stackFileData
|
||||||
const isViewingFileLoading = isStackFileLoading || (!!versionId && isVersionFileLoading)
|
const isViewingFileLoading = isStackFileLoading || (!!versionId && isVersionFileLoading)
|
||||||
|
usePublicShareView({
|
||||||
|
shareId,
|
||||||
|
assetId: activeFileId ?? initialFolderId,
|
||||||
|
password,
|
||||||
|
ready: !!shareInfo && (viewingFileId ? !!viewingFileData : !initialFolderId || !!folderInfo),
|
||||||
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (foldersError?.message === 'Unauthorized') {
|
if (foldersError?.message === 'Unauthorized') {
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import type { ShareActivityKind } from '@shumai/dtos'
|
||||||
|
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||||
|
import { isToday, isYesterday } from 'date-fns'
|
||||||
|
import { CircleUserRound } from 'lucide-react'
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { useInView } from 'react-intersection-observer'
|
||||||
|
import { client } from '@/ui/api/client'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import { getLocale } from '@/ui/paraglide/runtime.js'
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
|
||||||
|
import { Button } from './ui/button'
|
||||||
|
import { ScrollArea } from './ui/scroll-area'
|
||||||
|
|
||||||
|
function activityLabel(kind: ShareActivityKind) {
|
||||||
|
switch (kind) {
|
||||||
|
case 'share_viewed':
|
||||||
|
return m.share_activity_opened_share_link()
|
||||||
|
case 'asset_viewed':
|
||||||
|
return m.share_activity_viewed_asset()
|
||||||
|
case 'asset_downloaded':
|
||||||
|
return m.share_activity_downloaded()
|
||||||
|
case 'comment_created':
|
||||||
|
return m.share_activity_commented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDay(date: Date) {
|
||||||
|
if (isToday(date)) return m.today()
|
||||||
|
if (isYesterday(date)) return m.yesterday()
|
||||||
|
return date.toLocaleDateString(getLocale(), { dateStyle: 'medium' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShareActivityList({ shareId }: { shareId: string }) {
|
||||||
|
const query = useInfiniteQuery({
|
||||||
|
queryKey: ['share-activities', shareId],
|
||||||
|
queryFn: async ({ pageParam, signal }) => {
|
||||||
|
const response = await client.api.shares[':shareId'].activities.$get(
|
||||||
|
{ param: { shareId }, query: { first: '20', after: pageParam } },
|
||||||
|
{ init: { signal } },
|
||||||
|
)
|
||||||
|
if (!response.ok) throw new Error(m.share_activity_load_failed())
|
||||||
|
return response.json()
|
||||||
|
},
|
||||||
|
initialPageParam: '',
|
||||||
|
getNextPageParam: (page) => page.pageInfo.cursor || undefined,
|
||||||
|
})
|
||||||
|
const { ref, inView } = useInView()
|
||||||
|
const { fetchNextPage, hasNextPage, isFetching, isError } = query
|
||||||
|
useEffect(() => {
|
||||||
|
if (inView && hasNextPage && !isFetching && !isError) void fetchNextPage()
|
||||||
|
}, [fetchNextPage, hasNextPage, inView, isError, isFetching])
|
||||||
|
|
||||||
|
const events = new Map(
|
||||||
|
query.data?.pages.flatMap((page) => page.data.map((event) => [event.id, event] as const)),
|
||||||
|
)
|
||||||
|
const days = Map.groupBy(events.values(), (event) => new Date(event.createdAt).toDateString())
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
|
<div className="space-y-4 p-3">
|
||||||
|
{query.isPending && <p className="text-sm text-muted-foreground">{m.loading()}</p>}
|
||||||
|
{query.isSuccess && events.size === 0 && (
|
||||||
|
<p className="text-sm text-muted-foreground">{m.no_activity_yet()}</p>
|
||||||
|
)}
|
||||||
|
{[...days].map(([day, entries]) => (
|
||||||
|
<section key={day} className="space-y-2">
|
||||||
|
<h3 className="text-xs font-medium text-muted-foreground">
|
||||||
|
{formatDay(new Date(entries[0].createdAt))}
|
||||||
|
</h3>
|
||||||
|
<ul className="space-y-2">
|
||||||
|
{entries.map((event) => (
|
||||||
|
<li
|
||||||
|
key={event.id}
|
||||||
|
className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 px-2 py-2"
|
||||||
|
>
|
||||||
|
{event.user ? (
|
||||||
|
<Avatar className="size-8">
|
||||||
|
<AvatarImage src={event.user.image} alt="" />
|
||||||
|
<AvatarFallback>{event.user.name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
) : (
|
||||||
|
<CircleUserRound aria-hidden="true" className="size-8 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="truncate text-sm font-medium">
|
||||||
|
{event.user?.name || m.someone()}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline gap-x-2 text-xs text-muted-foreground">
|
||||||
|
{event.asset && (
|
||||||
|
<span className="min-w-0 truncate" title={event.asset.name ?? undefined}>
|
||||||
|
{event.asset.name ?? m.share_activity_deleted_asset()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<time dateTime={event.createdAt} className="shrink-0 whitespace-nowrap">
|
||||||
|
{new Date(event.createdAt).toLocaleTimeString(getLocale(), {
|
||||||
|
timeStyle: 'short',
|
||||||
|
})}
|
||||||
|
</time>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="max-w-24 text-right text-xs">{activityLabel(event.kind)}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
{query.isError && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-sm text-muted-foreground">{m.share_activity_load_failed()}</p>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => void (query.isFetchNextPageError ? fetchNextPage() : query.refetch())}
|
||||||
|
>
|
||||||
|
{m.retry()}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{hasNextPage && <div ref={ref}>{query.isFetchingNextPage && m.loading()}</div>}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
import React from 'react'
|
||||||
|
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||||
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||||
|
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { ShareLinkCreatedDialog } from './share-link-created-dialog'
|
||||||
|
|
||||||
|
const mockNavigate = vi.fn()
|
||||||
|
const mockCopyToClipboard = vi.fn().mockResolvedValue(true)
|
||||||
|
const mockGetShare = vi.fn()
|
||||||
|
const mockPutShare = vi.fn()
|
||||||
|
const mockGetWatermark = vi.fn()
|
||||||
|
const mockPutWatermark = vi.fn()
|
||||||
|
|
||||||
|
vi.mock('@tanstack/react-router', () => ({
|
||||||
|
useNavigate: () => mockNavigate,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/ui/lib/clipboard', () => ({
|
||||||
|
copyToClipboard: (...args: unknown[]) => mockCopyToClipboard(...args),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/ui/components/watermark-editor-dialog', () => ({
|
||||||
|
WatermarkEditorDialog: () => null,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/ui/api/client', () => ({
|
||||||
|
client: {
|
||||||
|
api: {
|
||||||
|
shares: {
|
||||||
|
':shareId': {
|
||||||
|
$get: (...args: unknown[]) => mockGetShare(...args),
|
||||||
|
$put: (...args: unknown[]) => mockPutShare(...args),
|
||||||
|
watermark: {
|
||||||
|
$get: (...args: unknown[]) => mockGetWatermark(...args),
|
||||||
|
$put: (...args: unknown[]) => mockPutWatermark(...args),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
const sampleShare: ShareLinkInfo = {
|
||||||
|
id: 'share-1',
|
||||||
|
name: 'hero-cut.mp4',
|
||||||
|
isDisabled: false,
|
||||||
|
allowDownload: true,
|
||||||
|
hasPassword: false,
|
||||||
|
password: null,
|
||||||
|
rootFolderId: 'folder-share-1',
|
||||||
|
projectId: 'proj-1',
|
||||||
|
isExpired: false,
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
|
watermarkConfigId: null,
|
||||||
|
watermarkStatus: 'disabled',
|
||||||
|
watermarkConfig: null,
|
||||||
|
createdAt: '2026-11-24T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-11-24T00:00:00.000Z',
|
||||||
|
creator: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
function createQueryClient() {
|
||||||
|
return new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: { retry: false },
|
||||||
|
mutations: { retry: false },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ShareLinkCreatedDialog', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mockGetShare.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => sampleShare,
|
||||||
|
})
|
||||||
|
mockGetWatermark.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ watermarkStatus: 'disabled', watermarkConfig: null }),
|
||||||
|
})
|
||||||
|
mockPutShare.mockImplementation(async ({ json }: { json: Record<string, unknown> }) => ({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ ...sampleShare, ...json }),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders share name, URL, all 4 expanded security controls, and footer buttons', () => {
|
||||||
|
const queryClient = createQueryClient()
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ShareLinkCreatedDialog
|
||||||
|
open={true}
|
||||||
|
onOpenChange={vi.fn()}
|
||||||
|
shareLink={sampleShare}
|
||||||
|
projectId="proj-1"
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.getByText('hero-cut.mp4')).toBeDefined()
|
||||||
|
expect(screen.getByRole('button', { name: 'Rename Share Link' })).toBeDefined()
|
||||||
|
|
||||||
|
const urlInput = screen.getByRole('textbox', { name: /share link/i }) as HTMLInputElement
|
||||||
|
expect(urlInput.value).toBe(`${window.location.origin}/share/share-1`)
|
||||||
|
|
||||||
|
// All 4 security settings rendered directly without needing an accordion
|
||||||
|
expect(screen.getByText('Password')).toBeDefined()
|
||||||
|
expect(screen.getByText('Expiration Date')).toBeDefined()
|
||||||
|
expect(screen.getByText('Allow download')).toBeDefined()
|
||||||
|
expect(screen.getByText('Watermark')).toBeDefined()
|
||||||
|
|
||||||
|
// Footer buttons
|
||||||
|
expect(screen.getByRole('button', { name: 'Advanced settings' })).toBeDefined()
|
||||||
|
expect(screen.getAllByRole('button', { name: 'Copy Link' }).length).toBe(2)
|
||||||
|
expect(screen.getByRole('button', { name: 'Done' })).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('supports inline renaming via pen icon and cancels on Escape', async () => {
|
||||||
|
const queryClient = createQueryClient()
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ShareLinkCreatedDialog
|
||||||
|
open={true}
|
||||||
|
onOpenChange={vi.fn()}
|
||||||
|
shareLink={sampleShare}
|
||||||
|
projectId="proj-1"
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Enter edit mode and cancel with Escape
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Rename Share Link' }))
|
||||||
|
const input = screen.getByRole('textbox', { name: 'Rename Share Link' }) as HTMLInputElement
|
||||||
|
expect(input.value).toBe('hero-cut.mp4')
|
||||||
|
fireEvent.change(input, { target: { value: 'Temporary Name' } })
|
||||||
|
fireEvent.keyDown(input, { key: 'Escape' })
|
||||||
|
expect(mockPutShare).not.toHaveBeenCalled()
|
||||||
|
expect(screen.getByText('hero-cut.mp4')).toBeDefined()
|
||||||
|
|
||||||
|
// Re-enter edit mode and save with Enter
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Rename Share Link' }))
|
||||||
|
const input2 = screen.getByRole('textbox', { name: 'Rename Share Link' }) as HTMLInputElement
|
||||||
|
fireEvent.change(input2, { target: { value: 'Client Delivery v2' } })
|
||||||
|
fireEvent.keyDown(input2, { key: 'Enter' })
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockPutShare).toHaveBeenCalledWith({
|
||||||
|
param: { shareId: 'share-1' },
|
||||||
|
json: { name: 'Client Delivery v2' },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates security settings via PUT /shares/:shareId', async () => {
|
||||||
|
const queryClient = createQueryClient()
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ShareLinkCreatedDialog
|
||||||
|
open={true}
|
||||||
|
onOpenChange={vi.fn()}
|
||||||
|
shareLink={sampleShare}
|
||||||
|
projectId="proj-1"
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const switches = screen.getAllByRole('switch')
|
||||||
|
// Switches order: Password (0), Expiration Date (1), Allow Download (2), Watermark (3)
|
||||||
|
fireEvent.click(switches[2])
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockPutShare).toHaveBeenCalledWith({
|
||||||
|
param: { shareId: 'share-1' },
|
||||||
|
json: { allowDownload: false },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Enable password and save
|
||||||
|
fireEvent.click(switches[0])
|
||||||
|
const passwordInput = screen.getByPlaceholderText('Enter password')
|
||||||
|
fireEvent.change(passwordInput, { target: { value: 'pass123' } })
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockPutShare).toHaveBeenCalledWith({
|
||||||
|
param: { shareId: 'share-1' },
|
||||||
|
json: { password: 'pass123' },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('copies link while staying open, closes on Done, and navigates on Advanced settings', async () => {
|
||||||
|
const onOpenChange = vi.fn()
|
||||||
|
const queryClient = createQueryClient()
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ShareLinkCreatedDialog
|
||||||
|
open={true}
|
||||||
|
onOpenChange={onOpenChange}
|
||||||
|
shareLink={sampleShare}
|
||||||
|
projectId="proj-1"
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
const copyButtons = screen.getAllByRole('button', { name: 'Copy Link' })
|
||||||
|
fireEvent.click(copyButtons[copyButtons.length - 1])
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockCopyToClipboard).toHaveBeenCalledWith(`${window.location.origin}/share/share-1`)
|
||||||
|
})
|
||||||
|
expect(onOpenChange).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Advanced settings' }))
|
||||||
|
expect(onOpenChange).toHaveBeenCalledWith(false)
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith({
|
||||||
|
to: '/projects/$projectId/shares/$shareId',
|
||||||
|
params: { projectId: 'proj-1', shareId: 'share-1' },
|
||||||
|
})
|
||||||
|
|
||||||
|
onOpenChange.mockClear()
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Done' }))
|
||||||
|
expect(onOpenChange).toHaveBeenCalledWith(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
import { client } from '@/ui/api/client'
|
||||||
|
import { ShareSecuritySettings } from '@/ui/components/share-security-settings'
|
||||||
|
import { Button } from '@/ui/components/ui/button'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/ui/components/ui/dialog'
|
||||||
|
import { Input } from '@/ui/components/ui/input'
|
||||||
|
import { copyToClipboard } from '@/ui/lib/clipboard'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
import { ArrowUpRight, Check, Copy, Pencil } from 'lucide-react'
|
||||||
|
import React, { useEffect, useRef, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
interface ShareLinkCreatedDialogProps {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
shareLink: ShareLinkInfo | null
|
||||||
|
projectId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShareLinkCreatedDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
shareLink,
|
||||||
|
projectId,
|
||||||
|
}: ShareLinkCreatedDialogProps) {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [isEditingName, setIsEditingName] = useState(false)
|
||||||
|
const [nameInput, setNameInput] = useState('')
|
||||||
|
const [copied, setCopied] = useState(false)
|
||||||
|
const nameInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
const cancelEditRef = useRef(false)
|
||||||
|
const copiedTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
|
|
||||||
|
const shareId = shareLink?.id
|
||||||
|
|
||||||
|
const { data: liveShareLink } = useQuery({
|
||||||
|
queryKey: ['share', shareId],
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!shareId) return null
|
||||||
|
const res = await client.api.shares[':shareId'].$get({
|
||||||
|
param: { shareId },
|
||||||
|
})
|
||||||
|
if (!res.ok) throw new Error(m.failed_fetch_share_link())
|
||||||
|
return (await res.json()) as unknown as ShareLinkInfo
|
||||||
|
},
|
||||||
|
initialData: shareLink ?? undefined,
|
||||||
|
enabled: open && !!shareId,
|
||||||
|
})
|
||||||
|
|
||||||
|
const activeShare = liveShareLink ?? shareLink
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) {
|
||||||
|
setIsEditingName(false)
|
||||||
|
setCopied(false)
|
||||||
|
if (copiedTimeoutRef.current) {
|
||||||
|
clearTimeout(copiedTimeoutRef.current)
|
||||||
|
copiedTimeoutRef.current = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (copiedTimeoutRef.current) {
|
||||||
|
clearTimeout(copiedTimeoutRef.current)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditingName) {
|
||||||
|
nameInputRef.current?.focus()
|
||||||
|
nameInputRef.current?.select()
|
||||||
|
}
|
||||||
|
}, [isEditingName])
|
||||||
|
|
||||||
|
const { mutate: renameShare, isPending: isRenaming } = useMutation({
|
||||||
|
mutationFn: async (name: string) => {
|
||||||
|
if (!activeShare) throw new Error(m.failed_rename_share_link())
|
||||||
|
const res = await client.api.shares[':shareId'].$put({
|
||||||
|
param: { shareId: activeShare.id },
|
||||||
|
json: { name },
|
||||||
|
})
|
||||||
|
if (!res.ok) throw new Error(m.failed_rename_share_link())
|
||||||
|
return (await res.json()) as unknown as ShareLinkInfo
|
||||||
|
},
|
||||||
|
onSuccess: (updated) => {
|
||||||
|
queryClient.setQueryData(['share', updated.id], updated)
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['share', updated.id] })
|
||||||
|
toast.success(m.share_link_renamed())
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error(m.failed_rename_share_link())
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!activeShare) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const shareUrl = `${window.location.origin}/share/${activeShare.id}`
|
||||||
|
|
||||||
|
const startEditingName = () => {
|
||||||
|
cancelEditRef.current = false
|
||||||
|
setNameInput(activeShare.name)
|
||||||
|
setIsEditingName(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const commitRename = () => {
|
||||||
|
if (cancelEditRef.current) {
|
||||||
|
cancelEditRef.current = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const trimmed = nameInput.trim()
|
||||||
|
setIsEditingName(false)
|
||||||
|
if (!trimmed || trimmed === activeShare.name) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
renameShare(trimmed)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCopyLink = async () => {
|
||||||
|
const ok = await copyToClipboard(shareUrl)
|
||||||
|
if (ok) {
|
||||||
|
toast.success(m.copied_to_clipboard())
|
||||||
|
setCopied(true)
|
||||||
|
if (copiedTimeoutRef.current) {
|
||||||
|
clearTimeout(copiedTimeoutRef.current)
|
||||||
|
}
|
||||||
|
copiedTimeoutRef.current = setTimeout(() => {
|
||||||
|
setCopied(false)
|
||||||
|
copiedTimeoutRef.current = null
|
||||||
|
}, 2000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAdvancedSettings = () => {
|
||||||
|
onOpenChange(false)
|
||||||
|
navigate({
|
||||||
|
to: '/projects/$projectId/shares/$shareId',
|
||||||
|
params: { projectId, shareId: activeShare.id },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-md overflow-hidden">
|
||||||
|
<DialogHeader className="min-w-0">
|
||||||
|
{isEditingName ? (
|
||||||
|
<>
|
||||||
|
<DialogTitle className="sr-only">{m.rename_share_link()}</DialogTitle>
|
||||||
|
<div className="flex min-w-0 items-center gap-1.5 pr-8">
|
||||||
|
<Input
|
||||||
|
ref={nameInputRef}
|
||||||
|
value={nameInput}
|
||||||
|
disabled={isRenaming}
|
||||||
|
onChange={(e) => setNameInput(e.target.value)}
|
||||||
|
onBlur={commitRename}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
commitRename()
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
cancelEditRef.current = true
|
||||||
|
setIsEditingName(false)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
aria-label={m.rename_share_link()}
|
||||||
|
className="h-8 min-w-0 flex-1 text-sm font-semibold"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
aria-label={m.save()}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={commitRename}
|
||||||
|
>
|
||||||
|
<Check className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<DialogTitle className="flex w-full min-w-0 items-center gap-1.5 pr-8">
|
||||||
|
<span
|
||||||
|
className="min-w-0 truncate cursor-pointer hover:text-foreground/80"
|
||||||
|
onClick={startEditingName}
|
||||||
|
title={activeShare.name}
|
||||||
|
>
|
||||||
|
{activeShare.name}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-7 w-7 shrink-0 text-muted-foreground hover:text-foreground"
|
||||||
|
aria-label={m.rename_share_link()}
|
||||||
|
onClick={startEditingName}
|
||||||
|
>
|
||||||
|
<Pencil className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
</DialogTitle>
|
||||||
|
)}
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="min-w-0 space-y-4 py-1">
|
||||||
|
<div className="relative w-full min-w-0">
|
||||||
|
<Input
|
||||||
|
value={shareUrl}
|
||||||
|
readOnly
|
||||||
|
aria-label={m.share_link()}
|
||||||
|
className="pr-10 bg-muted/50 text-xs"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="absolute right-0 top-0 h-full"
|
||||||
|
aria-label={m.copy_link()}
|
||||||
|
onClick={handleCopyLink}
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<Check className="h-4 w-4 text-emerald-500" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="min-w-0 rounded-lg border border-border bg-muted/20 p-3.5">
|
||||||
|
<ShareSecuritySettings shareLink={activeShare} inDialog />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter className="min-w-0 flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="w-fit gap-1 px-2 text-muted-foreground hover:text-foreground"
|
||||||
|
onClick={handleAdvancedSettings}
|
||||||
|
>
|
||||||
|
<span>{m.advanced_settings()}</span>
|
||||||
|
<ArrowUpRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
<Button type="button" variant="outline" onClick={handleCopyLink} className="gap-2">
|
||||||
|
{copied ? (
|
||||||
|
<Check className="h-4 w-4 text-emerald-500" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
<span>{m.copy_link()}</span>
|
||||||
|
</Button>
|
||||||
|
<Button type="button" onClick={() => onOpenChange(false)}>
|
||||||
|
{m.done()}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -9,6 +9,8 @@ import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tansta
|
|||||||
import { useEffect, useState, useMemo } from 'react'
|
import { useEffect, useState, useMemo } from 'react'
|
||||||
import { FileBrowser } from './file-browser/file-browser'
|
import { FileBrowser } from './file-browser/file-browser'
|
||||||
import { ShareSettingsSidebar } from './share-settings-sidebar'
|
import { ShareSettingsSidebar } from './share-settings-sidebar'
|
||||||
|
import { ShareActivityList } from './share-activity-list'
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs'
|
||||||
import { FolderTree } from './folder-tree'
|
import { FolderTree } from './folder-tree'
|
||||||
import { ResizeHandle } from './resize-handle'
|
import { ResizeHandle } from './resize-handle'
|
||||||
import { useFileSystemDnd } from './use-file-system-dnd'
|
import { useFileSystemDnd } from './use-file-system-dnd'
|
||||||
@@ -354,13 +356,30 @@ export default function ShareManager({
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0 h-full">
|
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0 h-full">
|
||||||
<ShareSettingsSidebar
|
<Tabs defaultValue="settings" className="flex h-full min-h-0 flex-col px-2 py-1">
|
||||||
shareLink={shareLink}
|
<TabsList className="w-full shrink-0">
|
||||||
viewMode={displayStyle}
|
<TabsTrigger value="settings" className="flex-1">
|
||||||
onViewModeChange={(mode) => updateShare({ viewMode: mode })}
|
{m.settings()}
|
||||||
defaultSortOrder={defaultSortOrder}
|
</TabsTrigger>
|
||||||
onSortOrderChange={(sortOrder) => updateShare({ defaultSortOrder: sortOrder })}
|
<TabsTrigger value="activity" className="flex-1">
|
||||||
/>
|
{m.activity()}
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent value="settings" className="min-h-0 flex-1 overflow-hidden">
|
||||||
|
<ShareSettingsSidebar
|
||||||
|
shareLink={shareLink}
|
||||||
|
viewMode={displayStyle}
|
||||||
|
onViewModeChange={(mode) => updateShare({ viewMode: mode })}
|
||||||
|
defaultSortOrder={defaultSortOrder}
|
||||||
|
onSortOrderChange={(sortOrder) =>
|
||||||
|
updateShare({ defaultSortOrder: sortOrder })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="activity" className="flex min-h-0 flex-1 flex-col">
|
||||||
|
<ShareActivityList shareId={shareId} />
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,223 @@
|
|||||||
|
import { client } from '@/ui/api/client'
|
||||||
|
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
||||||
|
import { Button } from '@/ui/components/ui/button'
|
||||||
|
import { Input } from '@/ui/components/ui/input'
|
||||||
|
import { Label } from '@/ui/components/ui/label'
|
||||||
|
import { Switch } from '@/ui/components/ui/switch'
|
||||||
|
import { WatermarkEditorDialog } from '@/ui/components/watermark-editor-dialog'
|
||||||
|
import { cn } from '@/ui/lib/utils'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import type { ShareLinkInfo, UpdateShareLinkRequest } from '@shumai/dtos'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { Loader2 } from 'lucide-react'
|
||||||
|
import React, { useEffect, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
interface ShareSecuritySettingsProps {
|
||||||
|
shareLink: ShareLinkInfo
|
||||||
|
inDialog?: boolean
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShareSecuritySettings({
|
||||||
|
shareLink,
|
||||||
|
inDialog = false,
|
||||||
|
className,
|
||||||
|
}: ShareSecuritySettingsProps) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [password, setPassword] = useState(shareLink.password || '')
|
||||||
|
const [expireAt, setExpireAt] = useState<Date | undefined>(
|
||||||
|
shareLink.expireAt ? new Date(shareLink.expireAt) : undefined,
|
||||||
|
)
|
||||||
|
const [isPasswordEnabled, setIsPasswordEnabled] = useState(shareLink.hasPassword)
|
||||||
|
const [isExpireEnabled, setIsExpireEnabled] = useState(!!shareLink.expireAt)
|
||||||
|
const [isWatermarkEditorOpen, setIsWatermarkEditorOpen] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPassword(shareLink.password || '')
|
||||||
|
}, [shareLink.password])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIsPasswordEnabled(shareLink.hasPassword)
|
||||||
|
setExpireAt(shareLink.expireAt ? new Date(shareLink.expireAt) : undefined)
|
||||||
|
setIsExpireEnabled(!!shareLink.expireAt)
|
||||||
|
}, [shareLink.id, shareLink.hasPassword, shareLink.expireAt])
|
||||||
|
|
||||||
|
const { data: watermarkInfo, refetch: refetchWatermark } = useQuery({
|
||||||
|
queryKey: ['share-watermark', shareLink.id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await client.api.shares[':shareId'].watermark.$get({
|
||||||
|
param: { shareId: shareLink.id },
|
||||||
|
})
|
||||||
|
if (!res.ok) return null
|
||||||
|
return await res.json()
|
||||||
|
},
|
||||||
|
refetchInterval: (query) => {
|
||||||
|
const status = query.state.data?.watermarkStatus || shareLink.watermarkStatus
|
||||||
|
return status === 'processing' ? 3000 : false
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const $updateWatermark = client.api.shares[':shareId'].watermark.$put
|
||||||
|
const { mutate: disableWatermark } = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const res = await $updateWatermark({
|
||||||
|
param: { shareId: shareLink.id },
|
||||||
|
json: { enabled: false },
|
||||||
|
})
|
||||||
|
if (!res.ok) throw new Error(m.failed_update())
|
||||||
|
return await res.json()
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['share-watermark', shareLink.id] })
|
||||||
|
toast.success(m.watermark_disabled_msg())
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const $updateShare = client.api.shares[':shareId'].$put
|
||||||
|
const { mutate: updateShare } = useMutation({
|
||||||
|
mutationFn: async (json: UpdateShareLinkRequest) => {
|
||||||
|
const res = await $updateShare({
|
||||||
|
param: { shareId: shareLink.id },
|
||||||
|
json,
|
||||||
|
})
|
||||||
|
if (!res.ok) throw new Error(m.failed_update())
|
||||||
|
return await res.json()
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
|
||||||
|
toast.success(m.settings_updated())
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const watermarkStatus =
|
||||||
|
watermarkInfo?.watermarkStatus ??
|
||||||
|
shareLink.watermarkStatus ??
|
||||||
|
(shareLink.watermarkConfigId ? 'ready' : 'disabled')
|
||||||
|
const watermarkConfig =
|
||||||
|
watermarkInfo?.watermarkConfig?.config ?? shareLink.watermarkConfig?.config ?? null
|
||||||
|
const isWatermarkEnabled = watermarkConfig !== null && watermarkStatus !== 'disabled'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className={cn('space-y-4', className)}>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label className="text-xs">{m.password()}</Label>
|
||||||
|
<Switch
|
||||||
|
checked={isPasswordEnabled}
|
||||||
|
onCheckedChange={(checked) => {
|
||||||
|
setIsPasswordEnabled(checked)
|
||||||
|
if (!checked) updateShare({ password: null })
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{isPasswordEnabled && (
|
||||||
|
<div className="flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
placeholder={m.enter_password()}
|
||||||
|
className="text-xs"
|
||||||
|
/>
|
||||||
|
<Button size="sm" onClick={() => updateShare({ password })}>
|
||||||
|
{m.save()}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label className="text-xs">{m.expiration_date()}</Label>
|
||||||
|
<Switch
|
||||||
|
checked={isExpireEnabled}
|
||||||
|
onCheckedChange={(checked) => {
|
||||||
|
setIsExpireEnabled(checked)
|
||||||
|
if (!checked) {
|
||||||
|
setExpireAt(undefined)
|
||||||
|
updateShare({ expireAt: null })
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{isExpireEnabled && (
|
||||||
|
<div className="animate-in fade-in slide-in-from-top-1 duration-200">
|
||||||
|
<DateTimePicker
|
||||||
|
modal={inDialog}
|
||||||
|
value={expireAt}
|
||||||
|
onChange={(date) => {
|
||||||
|
setExpireAt(date)
|
||||||
|
updateShare({ expireAt: date ? date.toISOString() : null })
|
||||||
|
}}
|
||||||
|
className="text-xs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label className="text-xs">{m.allow_download()}</Label>
|
||||||
|
<Switch
|
||||||
|
checked={shareLink.allowDownload}
|
||||||
|
onCheckedChange={(checked) => updateShare({ allowDownload: checked })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">{m.allow_download_description()}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 pt-2 border-t border-border/50">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label className="text-xs">{m.watermark()}</Label>
|
||||||
|
<Switch
|
||||||
|
checked={isWatermarkEnabled}
|
||||||
|
disabled={watermarkStatus === 'processing'}
|
||||||
|
onCheckedChange={(checked) => {
|
||||||
|
if (!checked) {
|
||||||
|
disableWatermark()
|
||||||
|
} else {
|
||||||
|
setIsWatermarkEditorOpen(true)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isWatermarkEnabled && watermarkStatus === 'processing' && (
|
||||||
|
<div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400 font-medium py-1 animate-pulse">
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
<span>{m.watermark_transcoding_processing()}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isWatermarkEnabled && watermarkStatus !== 'processing' && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="w-full text-xs gap-1.5 mt-1"
|
||||||
|
onClick={() => setIsWatermarkEditorOpen(true)}
|
||||||
|
>
|
||||||
|
{m.edit_watermark()}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<WatermarkEditorDialog
|
||||||
|
open={isWatermarkEditorOpen}
|
||||||
|
onOpenChange={setIsWatermarkEditorOpen}
|
||||||
|
initialConfig={watermarkConfig}
|
||||||
|
shareId={shareLink.id}
|
||||||
|
onSaveSuccess={() => {
|
||||||
|
refetchWatermark()
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||||
|
import React from 'react'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||||
|
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||||
|
import { client } from '@/ui/api/client'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import { ShareSettingsSidebar } from './share-settings-sidebar'
|
||||||
|
|
||||||
|
vi.mock('@/ui/api/client', () => ({
|
||||||
|
client: {
|
||||||
|
api: {
|
||||||
|
shares: {
|
||||||
|
':shareId': {
|
||||||
|
$put: vi.fn(),
|
||||||
|
watermark: {
|
||||||
|
$get: vi.fn(),
|
||||||
|
$put: vi.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
projects: {
|
||||||
|
':projectId': {
|
||||||
|
fields: {
|
||||||
|
$get: vi.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/ui/components/watermark-editor-dialog', () => ({
|
||||||
|
WatermarkEditorDialog: () => null,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('sonner', () => ({
|
||||||
|
toast: { success: vi.fn(), error: vi.fn() },
|
||||||
|
}))
|
||||||
|
|
||||||
|
const shareLink: ShareLinkInfo = {
|
||||||
|
id: 'share-1',
|
||||||
|
name: 'Client review',
|
||||||
|
isDisabled: false,
|
||||||
|
allowDownload: true,
|
||||||
|
hasPassword: true,
|
||||||
|
password: 'saved-secret',
|
||||||
|
rootFolderId: 'folder-1',
|
||||||
|
projectId: 'project-1',
|
||||||
|
isExpired: false,
|
||||||
|
watermarkStatus: 'disabled',
|
||||||
|
views: 0,
|
||||||
|
lastViewedAt: null,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSidebar(link: ShareLinkInfo) {
|
||||||
|
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ShareSettingsSidebar
|
||||||
|
shareLink={link}
|
||||||
|
viewMode="card"
|
||||||
|
onViewModeChange={() => {}}
|
||||||
|
defaultSortOrder={null}
|
||||||
|
onSortOrderChange={() => {}}
|
||||||
|
/>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function openSecuritySection() {
|
||||||
|
fireEvent.click(screen.getByText(m.security()))
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ShareSettingsSidebar password', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.mocked(client.api.shares[':shareId'].watermark.$get).mockResolvedValue({
|
||||||
|
ok: false,
|
||||||
|
} as never)
|
||||||
|
vi.mocked(client.api.projects[':projectId'].fields.$get).mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => [],
|
||||||
|
} as never)
|
||||||
|
vi.mocked(client.api.shares[':shareId'].$put).mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ ...shareLink }),
|
||||||
|
} as never)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup()
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows the saved password when password protection is enabled', () => {
|
||||||
|
renderSidebar(shareLink)
|
||||||
|
openSecuritySection()
|
||||||
|
|
||||||
|
const input = screen.getByPlaceholderText(m.enter_password())
|
||||||
|
expect(input).toHaveProperty('value', 'saved-secret')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('saves and displays a replacement password', async () => {
|
||||||
|
renderSidebar(shareLink)
|
||||||
|
openSecuritySection()
|
||||||
|
|
||||||
|
const input = screen.getByPlaceholderText(m.enter_password())
|
||||||
|
fireEvent.change(input, { target: { value: 'new-secret' } })
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: m.save() }))
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(client.api.shares[':shareId'].$put).toHaveBeenCalledWith({
|
||||||
|
param: { shareId: 'share-1' },
|
||||||
|
json: { password: 'new-secret' },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
expect(input).toHaveProperty('value', 'new-secret')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('turning the password off clears it', async () => {
|
||||||
|
renderSidebar(shareLink)
|
||||||
|
openSecuritySection()
|
||||||
|
|
||||||
|
const toggles = screen.getAllByRole('switch')
|
||||||
|
const passwordToggle = toggles.find(
|
||||||
|
(el) =>
|
||||||
|
el.getAttribute('aria-checked') === 'true' &&
|
||||||
|
el.closest('div')?.textContent?.includes(m.password()),
|
||||||
|
)
|
||||||
|
expect(passwordToggle).toBeDefined()
|
||||||
|
fireEvent.click(passwordToggle!)
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(client.api.shares[':shareId'].$put).toHaveBeenCalledWith({
|
||||||
|
param: { shareId: 'share-1' },
|
||||||
|
json: { password: null },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { client } from '@/ui/api/client'
|
import { client } from '@/ui/api/client'
|
||||||
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
import { ShareSecuritySettings } from '@/ui/components/share-security-settings'
|
||||||
import { Button } from '@/ui/components/ui/button'
|
import { Button } from '@/ui/components/ui/button'
|
||||||
import { Input } from '@/ui/components/ui/input'
|
import { Input } from '@/ui/components/ui/input'
|
||||||
import { Label } from '@/ui/components/ui/label'
|
import { Label } from '@/ui/components/ui/label'
|
||||||
@@ -11,7 +11,6 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/ui/components/ui/select'
|
} from '@/ui/components/ui/select'
|
||||||
import { Switch } from '@/ui/components/ui/switch'
|
import { Switch } from '@/ui/components/ui/switch'
|
||||||
import { WatermarkEditorDialog } from '@/ui/components/watermark-editor-dialog'
|
|
||||||
import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard'
|
import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard'
|
||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
import {
|
import {
|
||||||
@@ -28,7 +27,6 @@ import {
|
|||||||
LayoutGrid,
|
LayoutGrid,
|
||||||
List,
|
List,
|
||||||
ListFilter,
|
ListFilter,
|
||||||
Loader2,
|
|
||||||
Palette,
|
Palette,
|
||||||
Shield,
|
Shield,
|
||||||
SortAsc,
|
SortAsc,
|
||||||
@@ -52,58 +50,6 @@ export function ShareSettingsSidebar({
|
|||||||
onSortOrderChange,
|
onSortOrderChange,
|
||||||
}: ShareSettingsSidebarProps) {
|
}: ShareSettingsSidebarProps) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [password, setPassword] = useState(shareLink.password || '')
|
|
||||||
const [expireAt, setExpireAt] = useState<Date | undefined>(
|
|
||||||
shareLink.expireAt ? new Date(shareLink.expireAt) : undefined,
|
|
||||||
)
|
|
||||||
const [isWatermarkEditorOpen, setIsWatermarkEditorOpen] = useState(false)
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
setPassword(shareLink.password || '')
|
|
||||||
}, [shareLink.password])
|
|
||||||
const [isPasswordEnabled, setIsPasswordEnabled] = useState(shareLink.hasPassword)
|
|
||||||
const [isExpireEnabled, setIsExpireEnabled] = useState(!!shareLink.expireAt)
|
|
||||||
|
|
||||||
const { data: watermarkInfo, refetch: refetchWatermark } = useQuery({
|
|
||||||
queryKey: ['share-watermark', shareLink.id],
|
|
||||||
queryFn: async () => {
|
|
||||||
const res = await client.api.shares[':shareId'].watermark.$get({
|
|
||||||
param: { shareId: shareLink.id },
|
|
||||||
})
|
|
||||||
if (!res.ok) return null
|
|
||||||
return await res.json()
|
|
||||||
},
|
|
||||||
refetchInterval: (query) => {
|
|
||||||
const status = query.state.data?.watermarkStatus || shareLink.watermarkStatus
|
|
||||||
return status === 'processing' ? 3000 : false
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const $updateWatermark = client.api.shares[':shareId'].watermark.$put
|
|
||||||
const { mutate: disableWatermark } = useMutation({
|
|
||||||
mutationFn: async () => {
|
|
||||||
const res = await $updateWatermark({
|
|
||||||
param: { shareId: shareLink.id },
|
|
||||||
json: { enabled: false },
|
|
||||||
})
|
|
||||||
if (!res.ok) throw new Error(m.failed_update())
|
|
||||||
return await res.json()
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['share-watermark', shareLink.id] })
|
|
||||||
toast.success(m.watermark_disabled_msg())
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const watermarkStatus =
|
|
||||||
watermarkInfo?.watermarkStatus ??
|
|
||||||
shareLink.watermarkStatus ??
|
|
||||||
(shareLink.watermarkConfigId ? 'ready' : 'disabled')
|
|
||||||
const watermarkConfig =
|
|
||||||
watermarkInfo?.watermarkConfig?.config ?? shareLink.watermarkConfig?.config ?? null
|
|
||||||
const isWatermarkEnabled = watermarkConfig !== null && watermarkStatus !== 'disabled'
|
|
||||||
|
|
||||||
const { data: fields } = useQuery({
|
const { data: fields } = useQuery({
|
||||||
queryKey: ['fields', shareLink.projectId],
|
queryKey: ['fields', shareLink.projectId],
|
||||||
@@ -186,107 +132,7 @@ export function ShareSettingsSidebar({
|
|||||||
|
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<SidebarAccordionItem title={m.security()} icon={<Shield className="h-4 w-4" />}>
|
<SidebarAccordionItem title={m.security()} icon={<Shield className="h-4 w-4" />}>
|
||||||
<div className="p-3 space-y-4 pt-2">
|
<ShareSecuritySettings shareLink={shareLink} className="p-3 pt-2" />
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<Label className="text-xs">{m.password()}</Label>
|
|
||||||
<Switch
|
|
||||||
checked={isPasswordEnabled}
|
|
||||||
onCheckedChange={(checked) => {
|
|
||||||
setIsPasswordEnabled(checked)
|
|
||||||
if (!checked) updateShare({ password: null })
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{isPasswordEnabled && (
|
|
||||||
<div className="flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
placeholder={m.enter_password()}
|
|
||||||
className="text-xs"
|
|
||||||
/>
|
|
||||||
<Button size="sm" onClick={() => updateShare({ password })}>
|
|
||||||
{m.save()}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<Label className="text-xs">{m.expiration_date()}</Label>
|
|
||||||
<Switch
|
|
||||||
checked={isExpireEnabled}
|
|
||||||
onCheckedChange={(checked) => {
|
|
||||||
setIsExpireEnabled(checked)
|
|
||||||
if (!checked) {
|
|
||||||
setExpireAt(undefined)
|
|
||||||
updateShare({ expireAt: null })
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{isExpireEnabled && (
|
|
||||||
<div className="animate-in fade-in slide-in-from-top-1 duration-200">
|
|
||||||
<DateTimePicker
|
|
||||||
value={expireAt}
|
|
||||||
onChange={(date) => {
|
|
||||||
setExpireAt(date)
|
|
||||||
updateShare({ expireAt: date ? date.toISOString() : null })
|
|
||||||
}}
|
|
||||||
className="text-xs"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<Label className="text-xs">{m.allow_download()}</Label>
|
|
||||||
<Switch
|
|
||||||
checked={shareLink.allowDownload}
|
|
||||||
onCheckedChange={(checked) => updateShare({ allowDownload: checked })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground">{m.allow_download_description()}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2 pt-2 border-t border-border/50">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<Label className="text-xs">{m.watermark()}</Label>
|
|
||||||
<Switch
|
|
||||||
checked={isWatermarkEnabled}
|
|
||||||
disabled={watermarkStatus === 'processing'}
|
|
||||||
onCheckedChange={(checked) => {
|
|
||||||
if (!checked) {
|
|
||||||
disableWatermark()
|
|
||||||
} else {
|
|
||||||
setIsWatermarkEditorOpen(true)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isWatermarkEnabled && watermarkStatus === 'processing' && (
|
|
||||||
<div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400 font-medium py-1 animate-pulse">
|
|
||||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
|
||||||
<span>{m.watermark_transcoding_processing()}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isWatermarkEnabled && watermarkStatus !== 'processing' && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="w-full text-xs gap-1.5 mt-1"
|
|
||||||
onClick={() => setIsWatermarkEditorOpen(true)}
|
|
||||||
>
|
|
||||||
{m.edit_watermark()}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</SidebarAccordionItem>
|
</SidebarAccordionItem>
|
||||||
<SidebarAccordionItem title={m.appearance()} icon={<Palette className="h-4 w-4" />}>
|
<SidebarAccordionItem title={m.appearance()} icon={<Palette className="h-4 w-4" />}>
|
||||||
<div className="p-3 space-y-3 pt-2 flex gap-2">
|
<div className="p-3 space-y-3 pt-2 flex gap-2">
|
||||||
@@ -403,18 +249,6 @@ export function ShareSettingsSidebar({
|
|||||||
{m.copy_link()}
|
{m.copy_link()}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<WatermarkEditorDialog
|
|
||||||
open={isWatermarkEditorOpen}
|
|
||||||
onOpenChange={setIsWatermarkEditorOpen}
|
|
||||||
initialConfig={watermarkConfig}
|
|
||||||
shareId={shareLink.id}
|
|
||||||
onSaveSuccess={() => {
|
|
||||||
refetchWatermark()
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,6 +66,10 @@ export function TopNav() {
|
|||||||
onDelete,
|
onDelete,
|
||||||
onArchive,
|
onArchive,
|
||||||
onRestoreArchive,
|
onRestoreArchive,
|
||||||
|
shareLinks,
|
||||||
|
onCreateShareLink,
|
||||||
|
onAddToShareLink,
|
||||||
|
isShareActionPending,
|
||||||
compareMode,
|
compareMode,
|
||||||
canCompareVersions,
|
canCompareVersions,
|
||||||
onCompareVersions,
|
onCompareVersions,
|
||||||
@@ -166,6 +170,10 @@ export function TopNav() {
|
|||||||
onDelete={onDelete}
|
onDelete={onDelete}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
onRestoreArchive={onRestoreArchive}
|
onRestoreArchive={onRestoreArchive}
|
||||||
|
shareLinks={shareLinks}
|
||||||
|
onCreateShareLink={onCreateShareLink}
|
||||||
|
onAddToShareLink={onAddToShareLink}
|
||||||
|
isShareActionPending={isShareActionPending}
|
||||||
compareMode={compareMode}
|
compareMode={compareMode}
|
||||||
canCompareVersions={canCompareVersions}
|
canCompareVersions={canCompareVersions}
|
||||||
onCompareVersions={onCompareVersions}
|
onCompareVersions={onCompareVersions}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { client } from '@/ui/api/client'
|
import { client } from '@/ui/api/client'
|
||||||
|
import { requestShareDownload } from '@/ui/api/share-download'
|
||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
import { Download, AlertCircle } from 'lucide-react'
|
import { Download, AlertCircle } from 'lucide-react'
|
||||||
import React, { useImperativeHandle } from 'react'
|
import React, { useImperativeHandle } from 'react'
|
||||||
@@ -18,10 +19,7 @@ export const DefaultViewer = React.forwardRef<MediaController, FileViewerProps>(
|
|||||||
if (!key || !file.id) return
|
if (!key || !file.id) return
|
||||||
try {
|
try {
|
||||||
const res = shareId
|
const res = shareId
|
||||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
? await requestShareDownload(shareId, file.id, key)
|
||||||
param: { shareId, fileId: file.id },
|
|
||||||
json: { key },
|
|
||||||
})
|
|
||||||
: await client.api.files['download-url'].$post({
|
: await client.api.files['download-url'].$post({
|
||||||
json: { key, assetId: file.id },
|
json: { key, assetId: file.id },
|
||||||
})
|
})
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user