mirror of
https://github.com/documenso/documenso.git
synced 2026-07-21 23:43:43 +10:00
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6b8eb9fc6a | |||
| 40472bc26c | |||
| 12d44e1c59 | |||
| 9dc66afc7b | |||
| 7a13be6bf2 | |||
| 1032028395 | |||
| 2396d0d5d0 | |||
| dac262edc9 | |||
| 25eb4ffedf | |||
| ee0ea82635 | |||
| 5f7f6698fd | |||
| 402809c809 | |||
| 733e273c05 | |||
| 7c7933c2d4 | |||
| bb120d65dd | |||
| 9c14aa6297 | |||
| 6387e809a8 | |||
| 5b2b1591a4 | |||
| e5cb4c6bfd | |||
| 8185f916d3 | |||
| c308dbf257 |
@@ -0,0 +1,222 @@
|
||||
---
|
||||
date: 2026-05-07
|
||||
title: Pdf Placeholder Selection Fields
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Extend PDF placeholders so radio and dropdown fields can be configured from the existing Documenso placeholder syntax:
|
||||
|
||||
```text
|
||||
{{FIELD_TYPE, RECIPIENT, key=value, key=value}}
|
||||
```
|
||||
|
||||
Do not introduce a new delimiter style. Existing applications may already generate placeholders in this format, so the new selection-field behavior should fit into it.
|
||||
|
||||
## Goals
|
||||
|
||||
- Keep the current placeholder grammar unchanged.
|
||||
- Support checkbox placeholders with option lists, checked values, validation, direction, required, read-only, and font size.
|
||||
- Support radio placeholders with option lists, default/preselected values, direction, required, read-only, and font size.
|
||||
- Support dropdown placeholders with option lists, default value, required, read-only, and font size.
|
||||
- Use `options` as the only public list key in PDF placeholders.
|
||||
- Convert `options` into internal `fieldMeta.values` during parsing.
|
||||
- Make generated fields usable immediately in the editor, signing UI, preview renderer, and final PDF export.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No semicolon placeholder syntax.
|
||||
- No `values` alias in PDF placeholder syntax.
|
||||
- No database migration.
|
||||
- No behavior change for existing placeholders such as `{{text, r1, required=true}}`.
|
||||
|
||||
## Placeholder Syntax
|
||||
|
||||
Use the existing comma-separated placeholder format:
|
||||
|
||||
```text
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
{{radio, r1, options=Card|Bank transfer|Check, defaultValue=Check}}
|
||||
{{radio, r1, options=Basic|Pro|Enterprise, selected=Pro, direction=horizontal}}
|
||||
{{dropdown, r1, options=United States|Canada|United Kingdom}}
|
||||
{{dropdown, r2, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
Use `|` inside `options` because `,` is already the top-level placeholder delimiter.
|
||||
|
||||
Parsing rules:
|
||||
|
||||
- Split top-level placeholder tokens on unescaped commas.
|
||||
- Split metadata tokens on the first unescaped equals sign.
|
||||
- Split `options` on unescaped pipes.
|
||||
- Trim option values and drop empty values.
|
||||
- Preserve option order.
|
||||
- Support escaped delimiters: `\,`, `\=`, and `\|`.
|
||||
- Treat field type values case-insensitively.
|
||||
|
||||
## Field Type Mapping
|
||||
|
||||
- `checkbox` maps to `FieldType.CHECKBOX`.
|
||||
- `radio` maps to `FieldType.RADIO`.
|
||||
- `dropdown` maps to `FieldType.DROPDOWN`.
|
||||
|
||||
## Metadata Mapping
|
||||
|
||||
### Checkbox
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.CHECKBOX,
|
||||
fieldMeta: {
|
||||
type: 'checkbox',
|
||||
validationRule: 'Select at least',
|
||||
validationLength: 1,
|
||||
values: [
|
||||
{ id: 1, value: 'Email', checked: true },
|
||||
{ id: 2, value: 'SMS', checked: false },
|
||||
{ id: 3, value: 'Phone', checked: true },
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `checked`
|
||||
- `direction=vertical|horizontal`
|
||||
- `validationRule=atLeast|exactly|atMost`
|
||||
- `validationLength=1`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
Map checkbox validation aliases internally: `atLeast` -> `Select at least`, `exactly` -> `Select exactly`, `atMost` -> `Select at most`.
|
||||
|
||||
Checkbox placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
### Radio
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{radio, r1, options=Card|Bank transfer|Check, selected=Bank transfer}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.RADIO,
|
||||
fieldMeta: {
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, value: 'Card', checked: false },
|
||||
{ id: 2, value: 'Bank transfer', checked: true },
|
||||
{ id: 3, value: 'Check', checked: false },
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `selected`, `default`, or `defaultValue`
|
||||
- `direction=vertical|horizontal`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
Radio placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
### Dropdown
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{dropdown, r1, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.DROPDOWN,
|
||||
fieldMeta: {
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'Sales' }, { value: 'Legal' }, { value: 'Finance' }],
|
||||
defaultValue: 'Legal',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `selected`, `default`, or `defaultValue`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
`defaultValue` should only be set if it matches one parsed option.
|
||||
|
||||
Dropdown placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
## Code Touchpoints
|
||||
|
||||
- `packages/lib/server-only/pdf/helpers.ts`
|
||||
- Extend `parseFieldMetaFromPlaceholder` so `options` normalizes into checkbox/radio/dropdown `fieldMeta.values`.
|
||||
- Add delimiter-aware helpers for commas, equals signs, and pipes.
|
||||
- `packages/lib/server-only/pdf/auto-place-fields.ts`
|
||||
- Replace plain comma splitting with delimiter-aware splitting.
|
||||
- Preserve the existing positional structure: field type, recipient, metadata.
|
||||
- `packages/lib/types/field-meta.ts`
|
||||
- Keep current internal schemas: checkbox/radio/dropdown still store options as `fieldMeta.values`.
|
||||
- `packages/ui/primitives/document-flow/field-content.tsx`
|
||||
- Display a radio fallback when a placeholder-created radio has no options.
|
||||
- Docs:
|
||||
- `apps/docs/content/docs/users/documents/advanced/pdf-placeholders.mdx`
|
||||
- `apps/docs/content/docs/developers/api/fields.mdx`
|
||||
|
||||
## Test Plan
|
||||
|
||||
Unit tests:
|
||||
|
||||
- `options=Yes|No|Maybe` becomes stable radio values.
|
||||
- `selected=No` marks only the matching radio option checked.
|
||||
- Checkbox `options`, `checked`, `validationRule`, and `validationLength` normalize correctly.
|
||||
- Dropdown `options` and `defaultValue` normalize correctly.
|
||||
- Escaped delimiters parse correctly, for example `options=Sales\|Ops|Legal\, Compliance|A\=B`.
|
||||
|
||||
E2E/API tests:
|
||||
|
||||
- Add a PDF fixture with checkbox, radio, and dropdown placeholders using the current syntax.
|
||||
- Verify created fields have schema-compatible metadata and expected options/defaults.
|
||||
|
||||
Suggested verification:
|
||||
|
||||
```bash
|
||||
npm run test -w @documenso/lib -- server-only/pdf/helpers.test.ts
|
||||
npm run test:dev -w @documenso/app-tests -- e2e/auto-placing-fields/auto-place-fields-document.spec.ts
|
||||
npm run test:dev -w @documenso/app-tests -- e2e/envelope-editor-v2/envelope-fields.spec.ts
|
||||
npx tsc --noEmit -p packages/lib/tsconfig.json
|
||||
npx tsc --noEmit -p apps/remix/tsconfig.json
|
||||
```
|
||||
|
||||
Do not use `npm run build` for routine verification unless explicitly requested.
|
||||
|
||||
## Decisions
|
||||
|
||||
- Keep the existing placeholder format.
|
||||
- Use only `options` publicly.
|
||||
- Keep `values` as an internal metadata field only.
|
||||
- Use `|` as the option delimiter inside `options`.
|
||||
@@ -109,6 +109,37 @@ You can customize fields by adding options after the recipient identifier:
|
||||
| `maxValue` | Number | Maximum allowed value |
|
||||
| `numberFormat` | Format string | Number display format |
|
||||
|
||||
### Selection Field Options
|
||||
|
||||
Checkbox, radio, and dropdown placeholders can define their selectable choices via the `options` property.
|
||||
Separate choices with pipe (`|`) characters.
|
||||
Checkbox, radio, and dropdown placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
| Option | Applies To | Values | Description |
|
||||
| ------------------ | ------------------------- | ------------------------ | ---------------------------------------- |
|
||||
| `options` | Checkbox, Radio, Dropdown | `Option 1|Option 2` | Selectable choices |
|
||||
| `checked` | Checkbox | `Option 1|Option 2` | Pre-checked choices |
|
||||
| `selected` | Radio, Dropdown | One option value | Pre-selected/default choice |
|
||||
| `default` | Radio, Dropdown | One option value | Alias for `selected` |
|
||||
| `defaultValue` | Radio, Dropdown | One option value | Alias for `selected` |
|
||||
| `direction` | Checkbox, Radio | `vertical`, `horizontal` | Option layout |
|
||||
| `validationRule` | Checkbox | `atLeast`, `exactly`, `atMost` | Checkbox selection validation rule |
|
||||
| `validationLength` | Checkbox | Number (e.g., `1`) | Checkbox validation option count |
|
||||
| `required` | Checkbox, Radio, Dropdown | `true`, `false` | Whether the field must be completed |
|
||||
| `readOnly` | Checkbox, Radio, Dropdown | `true`, `false` | Whether the pre-selected value is locked |
|
||||
| `fontSize` | Checkbox, Radio, Dropdown | Number (e.g., `12`) | Field text size |
|
||||
|
||||
For checkbox validation, `validationLength` defines the option count:
|
||||
- `atLeast` means at least that many options must be selected
|
||||
- `exactly` means exactly that many options must be selected
|
||||
- `atMost` means at most that many options must be selected
|
||||
|
||||
If an option needs a literal delimiter, escape it with a backslash:
|
||||
|
||||
```
|
||||
{{dropdown, r1, options=Sales\|Ops|Legal\, Compliance|A\=B}}
|
||||
```
|
||||
|
||||
### Examples with Options
|
||||
|
||||
```
|
||||
@@ -116,6 +147,10 @@ You can customize fields by adding options after the recipient identifier:
|
||||
{{number, r1, minValue=0, maxValue=100, value=50}}
|
||||
{{name, r1, fontSize=14}}
|
||||
{{text, r2, readOnly=true, text=Contract #12345}}
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
{{radio, r1, options=Card|Bank transfer|Check, selected=Check}}
|
||||
{{dropdown, r1, options=United States|Canada|United Kingdom}}
|
||||
{{dropdown, r2, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,36 +0,0 @@
|
||||
import type { MessageDescriptor } from '@lingui/core';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
|
||||
export type PromptItem = {
|
||||
id: string;
|
||||
label: string | MessageDescriptor;
|
||||
sublabel?: string;
|
||||
path?: string;
|
||||
onAction?: () => void;
|
||||
icon?: LucideIcon;
|
||||
initials?: string;
|
||||
shortcut?: string;
|
||||
isChecked?: boolean;
|
||||
};
|
||||
|
||||
export type PromptCategory = {
|
||||
id: string;
|
||||
label: MessageDescriptor;
|
||||
items: PromptItem[];
|
||||
/**
|
||||
* The number of actual results, excluding utility rows such as the
|
||||
* "View all results" link.
|
||||
*/
|
||||
count: number;
|
||||
/**
|
||||
* The count shown on the category chip, or null to not show a chip at all.
|
||||
* Categories which only contain hardcoded page links have no chip.
|
||||
*/
|
||||
chipCount: number | null;
|
||||
isCapped: boolean;
|
||||
/**
|
||||
* Global admin categories are marked with a globe icon to distinguish them
|
||||
* from the equally named personal categories.
|
||||
*/
|
||||
isGlobal: boolean;
|
||||
};
|
||||
@@ -1,144 +0,0 @@
|
||||
import { useSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION, SKIP_QUERY_BATCH_META } from '@documenso/lib/constants/trpc';
|
||||
import { isAdmin } from '@documenso/lib/utils/is-admin';
|
||||
import { extractInitials } from '@documenso/lib/utils/recipient-formatter';
|
||||
import { trpc as trpcReact } from '@documenso/trpc/react';
|
||||
import type { TAdminSearchResultType } from '@documenso/trpc/server/admin-router/admin-search.types';
|
||||
import { ADMIN_SEARCH_MAX_QUERY_LENGTH } from '@documenso/trpc/server/admin-router/admin-search.types';
|
||||
|
||||
import type { MessageDescriptor } from '@lingui/core';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { keepPreviousData } from '@tanstack/react-query';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { ArrowRightIcon, Building2Icon, CreditCardIcon, FileTextIcon, UserIcon, UsersIcon } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import type { PromptCategory, PromptItem } from './app-command-menu.types';
|
||||
|
||||
/**
|
||||
* The maximum number of results the admin search returns per resource type.
|
||||
*/
|
||||
const ADMIN_SEARCH_RESULTS_CAP = 5;
|
||||
|
||||
const ADMIN_GROUP_LABELS: Record<TAdminSearchResultType, MessageDescriptor> = {
|
||||
document: msg`Documents`,
|
||||
user: msg`Users`,
|
||||
organisation: msg`Organisations`,
|
||||
team: msg`Teams`,
|
||||
recipient: msg`Recipients`,
|
||||
subscription: msg`Subscriptions`,
|
||||
};
|
||||
|
||||
const ADMIN_GROUP_ICONS: Record<TAdminSearchResultType, LucideIcon> = {
|
||||
document: FileTextIcon,
|
||||
user: UserIcon,
|
||||
organisation: Building2Icon,
|
||||
team: UsersIcon,
|
||||
recipient: UserIcon,
|
||||
subscription: CreditCardIcon,
|
||||
};
|
||||
|
||||
/**
|
||||
* Admin list pages which support prefilling their search from the URL, used
|
||||
* for the "View all results" links on capped groups. Teams, recipients and
|
||||
* subscriptions have no admin list pages.
|
||||
*/
|
||||
const ADMIN_GROUP_LIST_PATHS: Partial<Record<TAdminSearchResultType, (_query: string) => string>> = {
|
||||
document: (query) => `/admin/documents?term=${encodeURIComponent(query)}`,
|
||||
user: (query) => `/admin/users?search=${encodeURIComponent(query)}`,
|
||||
organisation: (query) => `/admin/organisations?query=${encodeURIComponent(query)}`,
|
||||
};
|
||||
|
||||
export type UseAdminSearchCategoriesOptions = {
|
||||
/**
|
||||
* The trimmed, debounced search query.
|
||||
*/
|
||||
query: string;
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The isolated admin portion of the command prompt: searches every admin
|
||||
* resource and maps the results to prompt categories marked as global.
|
||||
*
|
||||
* Returns no categories and never queries for non admin users. The admin
|
||||
* search endpoint is additionally guarded server side by the admin procedure.
|
||||
*/
|
||||
export const useAdminSearchCategories = ({ query, open }: UseAdminSearchCategoriesOptions) => {
|
||||
const { user } = useSession();
|
||||
|
||||
const isUserAdmin = isAdmin(user);
|
||||
|
||||
// Admin searches hit every resource table, so require a longer query unless
|
||||
// it is a number, which could be a resource ID of any length. Queries over
|
||||
// the endpoint's length limit are skipped entirely instead of being sent
|
||||
// and rejected.
|
||||
const hasValidAdminSearch =
|
||||
isUserAdmin && query.length <= ADMIN_SEARCH_MAX_QUERY_LENGTH && (query.length > 3 || /^\d+$/.test(query));
|
||||
|
||||
const {
|
||||
data: adminSearchData,
|
||||
isFetching,
|
||||
isError,
|
||||
} = trpcReact.admin.search.useQuery(
|
||||
{
|
||||
query,
|
||||
},
|
||||
{
|
||||
enabled: open && hasValidAdminSearch,
|
||||
placeholderData: keepPreviousData,
|
||||
// Retyping is the retry in a search-as-you-type flow: fail fast so the
|
||||
// prompt can surface an honest error state instead of retrying.
|
||||
retry: false,
|
||||
...SKIP_QUERY_BATCH_META,
|
||||
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
|
||||
},
|
||||
);
|
||||
|
||||
const categories = useMemo((): PromptCategory[] => {
|
||||
if (!hasValidAdminSearch || !adminSearchData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return adminSearchData.groups.map((group) => {
|
||||
const isCapped = group.results.length >= ADMIN_SEARCH_RESULTS_CAP;
|
||||
const buildListPath = ADMIN_GROUP_LIST_PATHS[group.type];
|
||||
|
||||
const items: PromptItem[] = group.results.map((result) => ({
|
||||
id: `admin-${group.type}-${result.value}`,
|
||||
label: result.label,
|
||||
sublabel: result.sublabel,
|
||||
path: result.path,
|
||||
icon: ADMIN_GROUP_ICONS[group.type],
|
||||
initials: group.type === 'user' || group.type === 'recipient' ? extractInitials(result.label) : undefined,
|
||||
}));
|
||||
|
||||
// Capped groups link to the full admin list page with the search
|
||||
// prefilled so the cap is never a dead end.
|
||||
if (isCapped && buildListPath) {
|
||||
items.push({
|
||||
id: `admin-${group.type}-view-all`,
|
||||
label: msg`View all results`,
|
||||
path: buildListPath(query),
|
||||
icon: ArrowRightIcon,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
id: `admin-${group.type}`,
|
||||
label: ADMIN_GROUP_LABELS[group.type],
|
||||
items,
|
||||
count: group.results.length,
|
||||
chipCount: group.results.length,
|
||||
isCapped,
|
||||
isGlobal: true,
|
||||
};
|
||||
});
|
||||
}, [hasValidAdminSearch, adminSearchData, query]);
|
||||
|
||||
return {
|
||||
isUserAdmin,
|
||||
categories,
|
||||
isFetching,
|
||||
isError,
|
||||
};
|
||||
};
|
||||
@@ -3,27 +3,32 @@ import { dynamicActivate } from '@documenso/lib/utils/i18n';
|
||||
import { i18n } from '@lingui/core';
|
||||
import { detect, fromHtmlTag } from '@lingui/detect-locale';
|
||||
import { I18nProvider } from '@lingui/react';
|
||||
import { StrictMode, startTransition, useEffect } from 'react';
|
||||
import { StrictMode, startTransition } from 'react';
|
||||
import { hydrateRoot } from 'react-dom/client';
|
||||
import { HydratedRouter } from 'react-router/dom';
|
||||
|
||||
import './utils/polyfills/promise-with-resolvers';
|
||||
|
||||
function PosthogInit() {
|
||||
/**
|
||||
* Initialised imperatively (not as a component inside `hydrateRoot`) because
|
||||
* rendering extra client-only siblings changes the React tree structure
|
||||
* relative to the server render in `entry.server.tsx`. That shifts every
|
||||
* `useId` value (used by Radix for `id`/`htmlFor`/`aria-*`), causing hydration
|
||||
* mismatches which can abort hydration entirely when the user interacts with
|
||||
* the page early, leaving dead event handlers (broken dropdowns, native form
|
||||
* submits).
|
||||
*/
|
||||
function initPosthog() {
|
||||
const postHogConfig = extractPostHogConfig();
|
||||
|
||||
useEffect(() => {
|
||||
if (postHogConfig) {
|
||||
void import('posthog-js').then(({ default: posthog }) => {
|
||||
posthog.init(postHogConfig.key, {
|
||||
api_host: postHogConfig.host,
|
||||
capture_exceptions: true,
|
||||
});
|
||||
if (postHogConfig) {
|
||||
void import('posthog-js').then(({ default: posthog }) => {
|
||||
posthog.init(postHogConfig.key, {
|
||||
api_host: postHogConfig.host,
|
||||
capture_exceptions: true,
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
@@ -38,11 +43,11 @@ async function main() {
|
||||
<I18nProvider i18n={i18n}>
|
||||
<HydratedRouter />
|
||||
</I18nProvider>
|
||||
|
||||
<PosthogInit />
|
||||
</StrictMode>,
|
||||
);
|
||||
});
|
||||
|
||||
void initPosthog();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
|
||||
+10
-2
@@ -119,7 +119,11 @@ export function LayoutContent({ children }: { children: React.ReactNode }) {
|
||||
const isRecipientRoute = matches.some((m) => m.id?.startsWith('routes/_recipient+'));
|
||||
|
||||
return (
|
||||
<html translate="no" lang={lang} data-theme={theme} className={theme ?? ''}>
|
||||
// `suppressHydrationWarning` because `remix-themes` intentionally mutates
|
||||
// `data-theme`/`class` on <html> before hydration (PreventFlashOnWrongTheme),
|
||||
// so the server-rendered attributes never match the client render when the
|
||||
// theme is resolved from the system preference. Attribute-only, one level deep.
|
||||
<html translate="no" lang={lang} data-theme={theme} className={theme ?? ''} suppressHydrationWarning>
|
||||
<head>
|
||||
<meta charSet="utf-8" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
|
||||
@@ -173,7 +177,11 @@ export function LayoutContent({ children }: { children: React.ReactNode }) {
|
||||
<script
|
||||
nonce={nonce(cspNonce)}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `window.__ENV__ = ${JSON.stringify(publicEnv)}`,
|
||||
// `__webpack_nonce__` is read by `get-nonce` (used by
|
||||
// react-remove-scroll / react-style-singleton inside Radix menus and
|
||||
// dialogs) to stamp runtime-injected <style> elements. Without it the
|
||||
// strict `style-src-elem` CSP blocks the scroll-lock styles.
|
||||
__html: `window.__ENV__ = ${JSON.stringify(publicEnv)}; window.__webpack_nonce__ = ${JSON.stringify(cspNonce ?? '')}`,
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,439 +0,0 @@
|
||||
import { seedPendingDocument } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import { openCommandMenu } from '../fixtures/command-menu';
|
||||
|
||||
test.describe.configure({ mode: 'parallel' });
|
||||
|
||||
const nanoid = customAlphabet('1234567890abcdef', 10);
|
||||
|
||||
const ADMIN_PROMPT_PLACEHOLDER = 'Search documents, users, organisations…';
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: numeric query shows verified user result and navigates', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: targetUser } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(String(targetUser.id));
|
||||
|
||||
await expect(page.getByText('Global Users', { exact: true })).toBeVisible();
|
||||
|
||||
// The category chips include the admin groups with their result counts.
|
||||
await expect(page.getByRole('button', { name: /Global Users/ })).toBeVisible();
|
||||
|
||||
const userOption = page.getByRole('option').filter({ hasText: targetUser.email }).first();
|
||||
|
||||
// Admin results are real links so they support native link behaviour such
|
||||
// as opening in a new tab.
|
||||
await expect(userOption.getByRole('link')).toHaveAttribute('href', `/admin/users/${targetUser.id}`);
|
||||
|
||||
await userOption.click();
|
||||
|
||||
await page.waitForURL(`/admin/users/${targetUser.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: numeric query shows verified team result and navigates', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { team: targetTeam } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(String(targetTeam.id));
|
||||
|
||||
await expect(page.getByText('Global Teams', { exact: true })).toBeVisible();
|
||||
|
||||
await page.getByRole('option').filter({ hasText: targetTeam.url }).first().click();
|
||||
|
||||
await page.waitForURL(`/admin/teams/${targetTeam.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: text query shows document result and navigates', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `admin-ui-search-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(document.title);
|
||||
|
||||
await expect(page.getByText('Global Documents', { exact: true })).toBeVisible();
|
||||
|
||||
await page.getByRole('option').filter({ hasText: document.secondaryId }).first().click();
|
||||
|
||||
await page.waitForURL(`/admin/documents/${document.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: envelope_ prefixed query resolves exact document', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `admin-ui-search-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(document.id);
|
||||
|
||||
await expect(page.getByText('Global Documents', { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: document.title }).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: admin search requires more than 3 characters unless numeric', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const adminSearchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('admin.search')) {
|
||||
adminSearchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
const input = page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first();
|
||||
|
||||
// A 3 character non-numeric query must not trigger the admin search. The
|
||||
// personal document search fires for any non-empty query, so its response
|
||||
// is the synchronization anchor proving the debounced queries have fired.
|
||||
const documentSearchResponse = page.waitForResponse((response) => response.url().includes('document.search'));
|
||||
|
||||
await input.fill('abc');
|
||||
|
||||
await documentSearchResponse;
|
||||
|
||||
await expect(page.getByText(/^Global /)).toHaveCount(0);
|
||||
expect(adminSearchRequests).toHaveLength(0);
|
||||
|
||||
// A numeric query fires regardless of length.
|
||||
const adminSearchRequest = page.waitForRequest((request) => request.url().includes('admin.search'));
|
||||
|
||||
await input.fill('7');
|
||||
|
||||
await adminSearchRequest;
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: search bar position stays fixed while searching', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: targetUser } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
const input = page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first();
|
||||
|
||||
const initialY = (await input.boundingBox())?.y;
|
||||
|
||||
expect(initialY).toBeGreaterThan(0);
|
||||
|
||||
// The height of the prompt may change as results come and go, but the
|
||||
// search bar must never move.
|
||||
await input.fill(String(targetUser.id));
|
||||
|
||||
await expect(page.getByText('Global Users', { exact: true })).toBeVisible();
|
||||
|
||||
const resultsY = (await input.boundingBox())?.y;
|
||||
|
||||
expect(resultsY).toBe(initialY);
|
||||
|
||||
// The search bar must not move when there are no results at all.
|
||||
await input.fill('zzzz-no-such-thing-9x7q');
|
||||
|
||||
await expect(page.getByText('No results for')).toBeVisible();
|
||||
|
||||
const emptyY = (await input.boundingBox())?.y;
|
||||
|
||||
expect(emptyY).toBe(initialY);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: default view shows the document page links outside a team context', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Admin pages have no current team, the page links must still show.
|
||||
await page.goto('/admin/stats');
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: 'All documents' })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Draft documents' })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'All templates' })).toBeVisible();
|
||||
|
||||
// Chips only show for categories with actual results, not for the
|
||||
// hardcoded page links.
|
||||
await expect(page.getByRole('button', { name: /^Documents/ })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: /^Templates/ })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: /^Settings/ })).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: theme can be changed from the prompt', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByRole('option').filter({ hasText: 'Change theme' }).first().click();
|
||||
|
||||
// The sub page has a contextual placeholder and a back option.
|
||||
await expect(page.getByPlaceholder('Search themes…')).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Back' }).first()).toBeVisible();
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Dark Mode' })).toBeVisible();
|
||||
|
||||
await page.getByRole('option').filter({ hasText: 'Dark Mode' }).first().click();
|
||||
|
||||
await expect(page.locator('html')).toHaveClass(/dark/);
|
||||
|
||||
// The back option returns to the root view.
|
||||
await page.getByRole('option').filter({ hasText: 'Back' }).first().click();
|
||||
|
||||
await expect(page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: capped admin groups offer a view all link', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const namePrefix = `viewall-${nanoid()}`;
|
||||
|
||||
// Seed enough users sharing a name prefix to hit the 5 result cap.
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await seedUser({ name: `${namePrefix}-${i}` });
|
||||
}
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(namePrefix);
|
||||
|
||||
await expect(page.getByText('Global Users', { exact: true })).toBeVisible();
|
||||
|
||||
const viewAllOption = page.getByRole('option').filter({ hasText: 'View all results' }).first();
|
||||
|
||||
await expect(viewAllOption.getByRole('link')).toHaveAttribute(
|
||||
'href',
|
||||
`/admin/users?search=${encodeURIComponent(namePrefix)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: first result is highlighted after every search', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: firstUser } = await seedUser();
|
||||
const { user: secondUser } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
const input = page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first();
|
||||
|
||||
// First search selects the first result.
|
||||
await input.fill(String(firstUser.id));
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: firstUser.email }).first()).toBeVisible();
|
||||
await expect(page.locator('[cmdk-item]').first()).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
// A subsequent search with entirely new results must select the first
|
||||
// result again.
|
||||
await input.fill(String(secondUser.id));
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: secondUser.email }).first()).toBeVisible();
|
||||
await expect(page.locator('[cmdk-item]').first()).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: static items match fuzzy queries', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
// "setg" is a non-contiguous abbreviation of "Settings".
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill('setg');
|
||||
|
||||
// Wait for the debounced filter to apply first, "Draft documents" can
|
||||
// never match "setg" under either matching strategy.
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Draft documents' })).toHaveCount(0);
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Settings' }).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: page scrollbar is hidden while the prompt is open', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await expect
|
||||
.poll(async () => await page.evaluate(() => getComputedStyle(document.documentElement).overflow))
|
||||
.toBe('hidden');
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
await expect
|
||||
.poll(async () => await page.evaluate(() => getComputedStyle(document.documentElement).overflow))
|
||||
.toBe('visible');
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: non-admin gets the prompt without the admin search', async ({ page }) => {
|
||||
const { user, team } = await seedUser({ isAdmin: false });
|
||||
|
||||
const document = await seedPendingDocument(user, team.id, []);
|
||||
|
||||
const adminSearchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('admin.search')) {
|
||||
adminSearchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: user.email });
|
||||
|
||||
// Non-admins get the same prompt with a non-admin placeholder.
|
||||
await openCommandMenu(page, 'Type a command or search...');
|
||||
|
||||
await expect(page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER)).toHaveCount(0);
|
||||
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(document.title);
|
||||
|
||||
// Wait for the regular (non-admin) search to resolve so we know the
|
||||
// debounced queries have fired.
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
|
||||
await expect(page.getByText(/^Global /)).toHaveCount(0);
|
||||
expect(adminSearchRequests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: typing on a sub page fires no search requests', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const searchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (/api\/trpc\/(document|template|admin)\.search/.test(request.url())) {
|
||||
searchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByRole('option').filter({ hasText: 'Change theme' }).first().click();
|
||||
|
||||
const input = page.getByPlaceholder('Search themes…');
|
||||
|
||||
await expect(input).toBeVisible();
|
||||
|
||||
// Long enough to pass the admin search threshold if it were enabled.
|
||||
await input.fill('dark');
|
||||
|
||||
// The client-side filter applying proves the typing registered.
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Dark Mode' })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Light Mode' })).toHaveCount(0);
|
||||
|
||||
// Wait out the 200ms search debounce with a wide margin before asserting
|
||||
// that no requests fired: there is no response to anchor on when the
|
||||
// desired behaviour is "no requests at all".
|
||||
await page.waitForTimeout(750);
|
||||
|
||||
expect(searchRequests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: failed searches show an error state instead of no results', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await page.route(/api\/trpc\/(document|template|admin)\.search/, async (route) => {
|
||||
await route.fulfill({ status: 500, contentType: 'application/json', body: '{}' });
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill('zzzz-no-such-thing-9x7q');
|
||||
|
||||
// A failed search must be honest about it, not claim there are no results.
|
||||
await expect(page.getByText('Something went wrong')).toBeVisible();
|
||||
await expect(page.getByText('No results for')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: partial search failure still shows results with a notice', async ({ page }) => {
|
||||
const { user: adminUser, team } = await seedUser({ isAdmin: true });
|
||||
|
||||
const document = await seedPendingDocument(adminUser, team.id, [], {
|
||||
createDocumentOptions: { title: `partial-fail-${nanoid()}` },
|
||||
});
|
||||
|
||||
// Only the admin search fails: the personal searches succeed.
|
||||
await page.route(/api\/trpc\/admin\.search/, async (route) => {
|
||||
await route.fulfill({ status: 500, contentType: 'application/json', body: '{}' });
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(document.title);
|
||||
|
||||
// The successful personal document search must still render its results.
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
|
||||
// The failed admin search must be flagged rather than silently dropped.
|
||||
await expect(page.getByText('Some searches failed')).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: over-length query skips the admin search without erroring', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const adminSearchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('admin.search')) {
|
||||
adminSearchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
// The admin search endpoint rejects queries longer than 100 characters, so
|
||||
// the client must not send them. The personal searches accept up to 1024
|
||||
// characters and still run, anchoring the debounced query flush.
|
||||
const documentSearchResponse = page.waitForResponse((response) => response.url().includes('document.search'));
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill('a'.repeat(150));
|
||||
|
||||
await documentSearchResponse;
|
||||
|
||||
// The personal searches ran and found nothing: the honest empty state, with
|
||||
// no error in sight.
|
||||
await expect(page.getByText('No results for')).toBeVisible();
|
||||
await expect(page.getByText('Something went wrong')).toHaveCount(0);
|
||||
|
||||
expect(adminSearchRequests).toHaveLength(0);
|
||||
});
|
||||
@@ -1,249 +0,0 @@
|
||||
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
|
||||
import { seedPendingDocument } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
|
||||
import { apiSignin } from '../../../fixtures/authentication';
|
||||
|
||||
const nanoid = customAlphabet('1234567890abcdef', 10);
|
||||
|
||||
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
|
||||
|
||||
test.describe.configure({ mode: 'parallel' });
|
||||
|
||||
type AdminSearchGroup = {
|
||||
type: string;
|
||||
results: Array<{ label: string; sublabel?: string; path: string; value: string }>;
|
||||
};
|
||||
|
||||
const callAdminSearch = async (page: Page, query: string) => {
|
||||
const inputParam = encodeURIComponent(JSON.stringify({ json: { query } }));
|
||||
const url = `${WEBAPP_BASE_URL}/api/trpc/admin.search?input=${inputParam}`;
|
||||
|
||||
const res = await page.context().request.get(url);
|
||||
|
||||
return {
|
||||
res,
|
||||
groups: res.ok()
|
||||
? // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||
((await res.json()).result.data.json.groups as AdminSearchGroup[])
|
||||
: null,
|
||||
};
|
||||
};
|
||||
|
||||
const findGroup = (groups: AdminSearchGroup[] | null, type: string) =>
|
||||
(groups ?? []).find((group) => group.type === type);
|
||||
|
||||
// ─── Access control ──────────────────────────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: unauthenticated request is rejected with 401', async ({ page }) => {
|
||||
const { res } = await callAdminSearch(page, 'anything');
|
||||
|
||||
expect(res.ok()).toBeFalsy();
|
||||
expect(res.status()).toBe(401);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: non-admin authenticated user is rejected with 401', async ({ page }) => {
|
||||
const { user: nonAdminUser } = await seedUser({ isAdmin: false });
|
||||
|
||||
await apiSignin({ page, email: nonAdminUser.email });
|
||||
|
||||
const { res } = await callAdminSearch(page, 'anything');
|
||||
|
||||
expect(res.ok()).toBeFalsy();
|
||||
expect(res.status()).toBe(401);
|
||||
});
|
||||
|
||||
// ─── Numeric queries: verified ID lookups ────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: numeric query returns verified user and team rows', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: targetUser, team: targetTeam } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Search by user ID.
|
||||
const userSearch = await callAdminSearch(page, String(targetUser.id));
|
||||
|
||||
expect(userSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const userGroup = findGroup(userSearch.groups, 'user');
|
||||
expect(userGroup).toBeDefined();
|
||||
expect(userGroup?.results).toHaveLength(1);
|
||||
expect(userGroup?.results[0].path).toBe(`/admin/users/${targetUser.id}`);
|
||||
expect(userGroup?.results[0].sublabel).toContain(targetUser.email);
|
||||
|
||||
// The cmdk `value` contract: value must contain the raw query.
|
||||
expect(userGroup?.results[0].value).toContain(String(targetUser.id));
|
||||
|
||||
// Search by team ID.
|
||||
const teamSearch = await callAdminSearch(page, String(targetTeam.id));
|
||||
|
||||
expect(teamSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const teamGroup = findGroup(teamSearch.groups, 'team');
|
||||
expect(teamGroup).toBeDefined();
|
||||
expect(teamGroup?.results).toHaveLength(1);
|
||||
expect(teamGroup?.results[0].path).toBe(`/admin/teams/${targetTeam.id}`);
|
||||
expect(teamGroup?.results[0].label).toBe(targetTeam.name);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: numeric query returns verified document and recipient rows', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
const { user: recipientUser } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [recipientUser]);
|
||||
const legacyDocumentId = document.secondaryId.replace('document_', '');
|
||||
const recipient = document.recipients[0];
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Search by legacy document ID (bare number).
|
||||
const documentSearch = await callAdminSearch(page, legacyDocumentId);
|
||||
|
||||
expect(documentSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(documentSearch.groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results).toHaveLength(1);
|
||||
expect(documentGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
expect(documentGroup?.results[0].label).toBe(document.title);
|
||||
|
||||
// Search by recipient ID: links to the parent document.
|
||||
const recipientSearch = await callAdminSearch(page, String(recipient.id));
|
||||
|
||||
expect(recipientSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const recipientGroup = findGroup(recipientSearch.groups, 'recipient');
|
||||
expect(recipientGroup).toBeDefined();
|
||||
expect(recipientGroup?.results).toHaveLength(1);
|
||||
expect(recipientGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
expect(recipientGroup?.results[0].label).toBe(recipient.email);
|
||||
expect(recipientGroup?.results[0].sublabel).toBe(`#${recipient.id} · ${recipient.name} · ${document.title}`);
|
||||
|
||||
// Search by the full document_<id> secondary ID: exercises the prefix branch.
|
||||
const secondaryIdSearch = await callAdminSearch(page, document.secondaryId);
|
||||
|
||||
expect(secondaryIdSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const secondaryIdGroup = findGroup(secondaryIdSearch.groups, 'document');
|
||||
expect(secondaryIdGroup).toBeDefined();
|
||||
expect(secondaryIdGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: numeric query with no matches returns no groups', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
const { res, groups } = await callAdminSearch(page, '999999999');
|
||||
|
||||
expect(res.ok()).toBeTruthy();
|
||||
expect(groups).toEqual([]);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: oversized number does not error and falls back to text search', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
// 99999999999999 exceeds Int4, so it cannot be an ID lookup: it must be
|
||||
// treated as text (and must not 500).
|
||||
const oversizedNumber = '99999999999999';
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `${oversizedNumber}-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
const { res, groups } = await callAdminSearch(page, oversizedNumber);
|
||||
|
||||
expect(res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results.map((result) => result.path)).toContain(`/admin/documents/${document.id}`);
|
||||
});
|
||||
|
||||
// ─── Prefixed ID queries: exact lookups ──────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: envelope_ and org_ prefixes resolve exact matches', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, organisation, team } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, []);
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// envelope_<id> resolves the document.
|
||||
const envelopeSearch = await callAdminSearch(page, document.id);
|
||||
|
||||
expect(envelopeSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(envelopeSearch.groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
|
||||
// Only the document group is returned for a recognized prefix.
|
||||
expect(envelopeSearch.groups).toHaveLength(1);
|
||||
|
||||
// org_<id> resolves the organisation.
|
||||
const orgSearch = await callAdminSearch(page, organisation.id);
|
||||
|
||||
expect(orgSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const orgGroup = findGroup(orgSearch.groups, 'organisation');
|
||||
expect(orgGroup).toBeDefined();
|
||||
expect(orgGroup?.results[0].path).toBe(`/admin/organisations/${organisation.id}`);
|
||||
expect(orgGroup?.results[0].label).toBe(organisation.name);
|
||||
|
||||
// Only the organisation group is returned for a recognized prefix.
|
||||
expect(orgSearch.groups).toHaveLength(1);
|
||||
});
|
||||
|
||||
// ─── Free text queries ───────────────────────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: text query matches documents by title and users by email', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
// A unique title: the default seeded title is shared across the whole suite,
|
||||
// and global search only returns the newest few matches.
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `admin-search-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Search by document title.
|
||||
const titleSearch = await callAdminSearch(page, document.title);
|
||||
|
||||
expect(titleSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(titleSearch.groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results.map((result) => result.path)).toContain(`/admin/documents/${document.id}`);
|
||||
|
||||
// Search by user email (emails are unique nanoid-based, so this is specific).
|
||||
const emailSearch = await callAdminSearch(page, sender.email);
|
||||
|
||||
expect(emailSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const userGroup = findGroup(emailSearch.groups, 'user');
|
||||
expect(userGroup).toBeDefined();
|
||||
expect(userGroup?.results[0].path).toBe(`/admin/users/${sender.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: gibberish query returns no groups', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
const { res, groups } = await callAdminSearch(page, 'zzzz-no-such-thing-9x7q');
|
||||
|
||||
expect(res.ok()).toBeTruthy();
|
||||
expect(groups).toEqual([]);
|
||||
});
|
||||
@@ -3,9 +3,6 @@ import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import { openCommandMenu } from '../fixtures/command-menu';
|
||||
|
||||
const COMMAND_MENU_PLACEHOLDER = 'Type a command or search...';
|
||||
|
||||
test('[COMMAND_MENU]: should see sent documents', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
@@ -17,9 +14,9 @@ test('[COMMAND_MENU]: should see sent documents', async ({ page }) => {
|
||||
email: user.email,
|
||||
});
|
||||
|
||||
await openCommandMenu(page, COMMAND_MENU_PLACEHOLDER);
|
||||
await page.keyboard.press('Meta+K');
|
||||
|
||||
await page.getByPlaceholder(COMMAND_MENU_PLACEHOLDER).first().fill(document.title);
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(document.title);
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -33,9 +30,9 @@ test('[COMMAND_MENU]: should see received documents', async ({ page }) => {
|
||||
email: recipient.email,
|
||||
});
|
||||
|
||||
await openCommandMenu(page, COMMAND_MENU_PLACEHOLDER);
|
||||
await page.keyboard.press('Meta+K');
|
||||
|
||||
await page.getByPlaceholder(COMMAND_MENU_PLACEHOLDER).first().fill(document.title);
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(document.title);
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -49,8 +46,8 @@ test('[COMMAND_MENU]: should be able to search by recipient', async ({ page }) =
|
||||
email: user.email,
|
||||
});
|
||||
|
||||
await openCommandMenu(page, COMMAND_MENU_PLACEHOLDER);
|
||||
await page.keyboard.press('Meta+K');
|
||||
|
||||
await page.getByPlaceholder(COMMAND_MENU_PLACEHOLDER).first().fill(recipient.email);
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(recipient.email);
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Opens the app command menu via the keyboard shortcut.
|
||||
*
|
||||
* Retries the shortcut until the menu appears since the keypress is a no-op
|
||||
* when it happens before the page has hydrated.
|
||||
*
|
||||
* @param placeholder The search input placeholder to wait for, which differs
|
||||
* between admin and non-admin users.
|
||||
*/
|
||||
export const openCommandMenu = async (page: Page, placeholder: string) => {
|
||||
await expect(async () => {
|
||||
await page.keyboard.press('Meta+K');
|
||||
await expect(page.getByPlaceholder(placeholder).first()).toBeVisible({ timeout: 1_000 });
|
||||
}).toPass({ timeout: 15_000 });
|
||||
};
|
||||
@@ -1,372 +0,0 @@
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { EnvelopeType } from '@prisma/client';
|
||||
|
||||
export const ADMIN_SEARCH_RESULTS_PER_TYPE = 5;
|
||||
|
||||
const MAX_POSTGRES_INT = 2147483647;
|
||||
|
||||
const GROUP_ORDER = ['document', 'user', 'organisation', 'team', 'recipient', 'subscription'] as const;
|
||||
|
||||
export type AdminGlobalSearchResultType = (typeof GROUP_ORDER)[number];
|
||||
|
||||
export type AdminGlobalSearchResult = {
|
||||
label: string;
|
||||
sublabel?: string;
|
||||
path: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type AdminGlobalSearchGroup = {
|
||||
type: AdminGlobalSearchResultType;
|
||||
results: AdminGlobalSearchResult[];
|
||||
};
|
||||
|
||||
export type AdminGlobalSearchOptions = {
|
||||
query: string;
|
||||
};
|
||||
|
||||
type PartialResults = Partial<Record<AdminGlobalSearchResultType, AdminGlobalSearchResult[]>>;
|
||||
|
||||
export const adminGlobalSearch = async ({ query }: AdminGlobalSearchOptions): Promise<AdminGlobalSearchGroup[]> => {
|
||||
const trimmedQuery = query.trim();
|
||||
|
||||
if (trimmedQuery.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const resultsByType = await resolveSearch(trimmedQuery);
|
||||
|
||||
return GROUP_ORDER.map((type) => ({
|
||||
type,
|
||||
results: (resultsByType[type] ?? []).map((result) => ({
|
||||
...result,
|
||||
// Append the raw query so cmdk's client-side filter never hides
|
||||
// server-verified results.
|
||||
value: `${result.value} ${trimmedQuery}`,
|
||||
})),
|
||||
})).filter((group) => group.results.length > 0);
|
||||
};
|
||||
|
||||
const resolveSearch = async (query: string): Promise<PartialResults> => {
|
||||
// Recognized ID prefixes resolve to a single exact lookup.
|
||||
if (query.startsWith('envelope_')) {
|
||||
return { document: await findDocumentsByExactId({ id: query }) };
|
||||
}
|
||||
|
||||
if (query.startsWith('document_')) {
|
||||
return { document: await findDocumentsByExactId({ secondaryId: query }) };
|
||||
}
|
||||
|
||||
if (query.startsWith('org_')) {
|
||||
return { organisation: await findOrganisationsByIdOrUrl(query) };
|
||||
}
|
||||
|
||||
// Bare numbers are treated as verified ID lookups only. Oversized numbers
|
||||
// fall through to text search.
|
||||
const numericId = Number(query);
|
||||
|
||||
if (/^\d+$/.test(query) && numericId <= MAX_POSTGRES_INT) {
|
||||
const [document, user, team, recipient, subscription] = await Promise.all([
|
||||
findDocumentsByExactId({ secondaryId: `document_${numericId}` }),
|
||||
findUsersById(numericId),
|
||||
findTeamsById(numericId),
|
||||
findRecipientsById(numericId),
|
||||
findSubscriptionsById(numericId),
|
||||
]);
|
||||
|
||||
return { document, user, team, recipient, subscription };
|
||||
}
|
||||
|
||||
// Free text searches all resource types in parallel.
|
||||
const [document, user, organisation, team, recipient, subscription] = await Promise.all([
|
||||
findDocumentsByText(query),
|
||||
findUsersByText(query),
|
||||
findOrganisationsByText(query),
|
||||
findTeamsByText(query),
|
||||
findRecipientsByText(query),
|
||||
findSubscriptionsByText(query),
|
||||
]);
|
||||
|
||||
return {
|
||||
document,
|
||||
user,
|
||||
organisation,
|
||||
team,
|
||||
recipient,
|
||||
subscription,
|
||||
};
|
||||
};
|
||||
|
||||
const joinSublabel = (parts: Array<string | null | undefined>) =>
|
||||
parts.filter((part) => part && part.length > 0).join(' · ') || undefined;
|
||||
|
||||
// ─── Documents ────────────────────────────────────────────────────────────────
|
||||
|
||||
const documentSelect = {
|
||||
id: true,
|
||||
title: true,
|
||||
secondaryId: true,
|
||||
user: { select: { email: true } },
|
||||
} as const;
|
||||
|
||||
type DocumentRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
secondaryId: string;
|
||||
user: { email: string };
|
||||
};
|
||||
|
||||
const mapDocument = (envelope: DocumentRow): AdminGlobalSearchResult => ({
|
||||
label: envelope.title,
|
||||
sublabel: joinSublabel([envelope.secondaryId, envelope.user.email]),
|
||||
path: `/admin/documents/${envelope.id}`,
|
||||
value: `document ${envelope.id} ${envelope.secondaryId} ${envelope.title} ${envelope.user.email}`,
|
||||
});
|
||||
|
||||
const findDocumentsByExactId = async (where: { id: string } | { secondaryId: string }) => {
|
||||
const envelope = await prisma.envelope.findFirst({
|
||||
where: { ...where, type: EnvelopeType.DOCUMENT },
|
||||
select: documentSelect,
|
||||
});
|
||||
|
||||
return envelope ? [mapDocument(envelope)] : [];
|
||||
};
|
||||
|
||||
const findDocumentsByText = async (query: string) => {
|
||||
const envelopes = await prisma.envelope.findMany({
|
||||
where: {
|
||||
type: EnvelopeType.DOCUMENT,
|
||||
title: { contains: query, mode: 'insensitive' },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: documentSelect,
|
||||
});
|
||||
|
||||
return envelopes.map(mapDocument);
|
||||
};
|
||||
|
||||
// ─── Users ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const userSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
} as const;
|
||||
|
||||
type UserRow = { id: number; name: string | null; email: string };
|
||||
|
||||
const mapUser = (user: UserRow): AdminGlobalSearchResult => ({
|
||||
label: user.name || user.email,
|
||||
sublabel: joinSublabel([`#${user.id}`, user.email]),
|
||||
path: `/admin/users/${user.id}`,
|
||||
value: `user ${user.id} ${user.name ?? ''} ${user.email}`,
|
||||
});
|
||||
|
||||
const findUsersById = async (id: number) => {
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { id },
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return user ? [mapUser(user)] : [];
|
||||
};
|
||||
|
||||
const findUsersByText = async (query: string) => {
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
OR: [{ name: { contains: query, mode: 'insensitive' } }, { email: { contains: query, mode: 'insensitive' } }],
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return users.map(mapUser);
|
||||
};
|
||||
|
||||
// ─── Organisations ────────────────────────────────────────────────────────────
|
||||
|
||||
const organisationSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
owner: { select: { email: true } },
|
||||
} as const;
|
||||
|
||||
type OrganisationRow = { id: string; name: string; owner: { email: string } };
|
||||
|
||||
const mapOrganisation = (organisation: OrganisationRow): AdminGlobalSearchResult => ({
|
||||
label: organisation.name,
|
||||
sublabel: joinSublabel([organisation.id, organisation.owner.email]),
|
||||
path: `/admin/organisations/${organisation.id}`,
|
||||
value: `organisation ${organisation.id} ${organisation.name} ${organisation.owner.email}`,
|
||||
});
|
||||
|
||||
const findOrganisationsByIdOrUrl = async (query: string) => {
|
||||
const organisations = await prisma.organisation.findMany({
|
||||
where: {
|
||||
OR: [{ id: query }, { url: query }],
|
||||
},
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: organisationSelect,
|
||||
});
|
||||
|
||||
return organisations.map(mapOrganisation);
|
||||
};
|
||||
|
||||
const findOrganisationsByText = async (query: string) => {
|
||||
const organisations = await prisma.organisation.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ name: { contains: query, mode: 'insensitive' } },
|
||||
{ url: { contains: query, mode: 'insensitive' } },
|
||||
{ customerId: { contains: query, mode: 'insensitive' } },
|
||||
{ owner: { email: { contains: query, mode: 'insensitive' } } },
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: organisationSelect,
|
||||
});
|
||||
|
||||
return organisations.map(mapOrganisation);
|
||||
};
|
||||
|
||||
// ─── Teams ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const teamSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
url: true,
|
||||
organisation: { select: { name: true } },
|
||||
} as const;
|
||||
|
||||
type TeamRow = { id: number; name: string; url: string; organisation: { name: string } };
|
||||
|
||||
const mapTeam = (team: TeamRow): AdminGlobalSearchResult => ({
|
||||
label: team.name,
|
||||
sublabel: joinSublabel([`#${team.id}`, `/${team.url}`, team.organisation.name]),
|
||||
path: `/admin/teams/${team.id}`,
|
||||
value: `team ${team.id} ${team.name} ${team.url} ${team.organisation.name}`,
|
||||
});
|
||||
|
||||
const findTeamsById = async (id: number) => {
|
||||
const team = await prisma.team.findFirst({
|
||||
where: { id },
|
||||
select: teamSelect,
|
||||
});
|
||||
|
||||
return team ? [mapTeam(team)] : [];
|
||||
};
|
||||
|
||||
const findTeamsByText = async (query: string) => {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: {
|
||||
OR: [{ name: { contains: query, mode: 'insensitive' } }, { url: { contains: query, mode: 'insensitive' } }],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: teamSelect,
|
||||
});
|
||||
|
||||
return teams.map(mapTeam);
|
||||
};
|
||||
|
||||
// ─── Recipients ───────────────────────────────────────────────────────────────
|
||||
|
||||
const recipientSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
envelope: { select: { id: true, title: true } },
|
||||
} as const;
|
||||
|
||||
type RecipientRow = {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
envelope: { id: string; title: string };
|
||||
};
|
||||
|
||||
const mapRecipient = (recipient: RecipientRow): AdminGlobalSearchResult => ({
|
||||
label: recipient.email,
|
||||
sublabel: joinSublabel([`#${recipient.id}`, recipient.name, recipient.envelope.title]),
|
||||
path: `/admin/documents/${recipient.envelope.id}`,
|
||||
value: `recipient ${recipient.id} ${recipient.name} ${recipient.email} ${recipient.envelope.title}`,
|
||||
});
|
||||
|
||||
const findRecipientsById = async (id: number) => {
|
||||
const recipient = await prisma.recipient.findFirst({
|
||||
where: {
|
||||
id,
|
||||
envelope: { type: EnvelopeType.DOCUMENT },
|
||||
},
|
||||
select: recipientSelect,
|
||||
});
|
||||
|
||||
return recipient ? [mapRecipient(recipient)] : [];
|
||||
};
|
||||
|
||||
const findRecipientsByText = async (query: string) => {
|
||||
const recipients = await prisma.recipient.findMany({
|
||||
where: {
|
||||
envelope: { type: EnvelopeType.DOCUMENT },
|
||||
OR: [{ email: { contains: query, mode: 'insensitive' } }, { name: { contains: query, mode: 'insensitive' } }],
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: recipientSelect,
|
||||
});
|
||||
|
||||
return recipients.map(mapRecipient);
|
||||
};
|
||||
|
||||
// ─── Subscriptions ────────────────────────────────────────────────────────────
|
||||
|
||||
const subscriptionSelect = {
|
||||
id: true,
|
||||
status: true,
|
||||
planId: true,
|
||||
customerId: true,
|
||||
organisationId: true,
|
||||
} as const;
|
||||
|
||||
type SubscriptionRow = {
|
||||
id: number;
|
||||
status: string;
|
||||
planId: string;
|
||||
customerId: string;
|
||||
organisationId: string;
|
||||
};
|
||||
|
||||
const mapSubscription = (subscription: SubscriptionRow): AdminGlobalSearchResult => ({
|
||||
label: `Subscription #${subscription.id}`,
|
||||
sublabel: joinSublabel([subscription.status, subscription.planId]),
|
||||
path: `/admin/organisations/${subscription.organisationId}`,
|
||||
value: `subscription ${subscription.id} ${subscription.planId} ${subscription.customerId}`,
|
||||
});
|
||||
|
||||
const findSubscriptionsById = async (id: number) => {
|
||||
const subscription = await prisma.subscription.findFirst({
|
||||
where: { id },
|
||||
select: subscriptionSelect,
|
||||
});
|
||||
|
||||
return subscription ? [mapSubscription(subscription)] : [];
|
||||
};
|
||||
|
||||
const findSubscriptionsByText = async (query: string) => {
|
||||
const subscriptions = await prisma.subscription.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ planId: { contains: query, mode: 'insensitive' } },
|
||||
{ customerId: { contains: query, mode: 'insensitive' } },
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: subscriptionSelect,
|
||||
});
|
||||
|
||||
return subscriptions.map(mapSubscription);
|
||||
};
|
||||
@@ -57,7 +57,10 @@ export const UNSAFE_createEnvelopeItems = async ({
|
||||
flattenForm: envelope.type !== 'TEMPLATE',
|
||||
});
|
||||
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
envelopeId: envelope.id,
|
||||
fileName: file.name,
|
||||
});
|
||||
|
||||
const { documentData } = await putPdfFileServerSide({
|
||||
name: file.name,
|
||||
|
||||
@@ -85,7 +85,10 @@ export const UNSAFE_replaceEnvelopeItemPdf = async ({
|
||||
flattenForm: envelope.type !== 'TEMPLATE',
|
||||
});
|
||||
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
envelopeId: envelope.id,
|
||||
fileName: data.file.name,
|
||||
});
|
||||
|
||||
// Upload the new PDF and get a new DocumentData record.
|
||||
const { documentData: newDocumentData, filePageCount } = await putPdfFileServerSide({
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { type TFieldAndMeta, ZEnvelopeFieldAndMetaSchema } from '@documenso/lib/types/field-meta';
|
||||
import { logger } from '@documenso/lib/utils/logger';
|
||||
import { PDF, rgb } from '@libpdf/core';
|
||||
import type { FieldType, Recipient } from '@prisma/client';
|
||||
|
||||
import { parseFieldMetaFromPlaceholder, parseFieldTypeFromPlaceholder } from './helpers';
|
||||
import {
|
||||
parseFieldMetaFromPlaceholder,
|
||||
parseFieldTypeFromPlaceholder,
|
||||
parsePlaceholderData,
|
||||
parseRawFieldMetaFromPlaceholder,
|
||||
} from './helpers';
|
||||
|
||||
const PLACEHOLDER_REGEX = /\{\{([^}]+)\}\}/g;
|
||||
const DEFAULT_FIELD_HEIGHT_PERCENT = 2;
|
||||
@@ -61,7 +68,15 @@ export type FieldToCreate = TFieldAndMeta & {
|
||||
height: number;
|
||||
};
|
||||
|
||||
export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<PlaceholderInfo[]> => {
|
||||
type ExtractPlaceholdersLogContext = {
|
||||
envelopeId?: string;
|
||||
fileName?: string;
|
||||
};
|
||||
|
||||
export const extractPlaceholdersFromPDF = async (
|
||||
pdf: Buffer,
|
||||
logContext?: ExtractPlaceholdersLogContext,
|
||||
): Promise<PlaceholderInfo[]> => {
|
||||
const pdfDoc = await PDF.load(new Uint8Array(pdf));
|
||||
|
||||
const placeholders: PlaceholderInfo[] = [];
|
||||
@@ -85,7 +100,7 @@ export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<Placehold
|
||||
continue;
|
||||
}
|
||||
|
||||
const placeholderData = innerMatch[1].split(',').map((property) => property.trim());
|
||||
const placeholderData = parsePlaceholderData(innerMatch[1]);
|
||||
const [fieldTypeString, recipientOrMeta, ...fieldMetaData] = placeholderData;
|
||||
|
||||
let fieldType: FieldType;
|
||||
@@ -109,14 +124,51 @@ export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<Placehold
|
||||
|
||||
const recipient = recipientOrMeta;
|
||||
|
||||
const rawFieldMeta = Object.fromEntries(fieldMetaData.map((property) => property.split('=')));
|
||||
/*
|
||||
Parse and validate the field metadata. A malformed selection placeholder
|
||||
(e.g. an unknown validation rule or a default value that doesn't match an
|
||||
option) is skipped like an invalid field type rather than aborting the whole
|
||||
upload, which may contain other valid placeholders and files.
|
||||
*/
|
||||
let fieldAndMeta: TFieldAndMeta;
|
||||
|
||||
const parsedFieldMeta = parseFieldMetaFromPlaceholder(rawFieldMeta, fieldType);
|
||||
try {
|
||||
const rawFieldMeta = parseRawFieldMetaFromPlaceholder(fieldMetaData);
|
||||
const parsedFieldMeta = parseFieldMetaFromPlaceholder(rawFieldMeta, fieldType);
|
||||
|
||||
const fieldAndMeta: TFieldAndMeta = ZEnvelopeFieldAndMetaSchema.parse({
|
||||
type: fieldType,
|
||||
fieldMeta: parsedFieldMeta,
|
||||
});
|
||||
const parsedFieldAndMeta = ZEnvelopeFieldAndMetaSchema.safeParse({
|
||||
type: fieldType,
|
||||
fieldMeta: parsedFieldMeta,
|
||||
});
|
||||
|
||||
/*
|
||||
Surface schema failures as INVALID_BODY (400) instead of letting the raw
|
||||
ZodError bubble up to the caller as an INTERNAL_SERVER_ERROR (500).
|
||||
*/
|
||||
if (!parsedFieldAndMeta.success) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Invalid field metadata for placeholder "${placeholder}": ${parsedFieldAndMeta.error.message}`,
|
||||
});
|
||||
}
|
||||
|
||||
fieldAndMeta = parsedFieldAndMeta.data;
|
||||
} catch (error) {
|
||||
const appError = AppError.parseError(error);
|
||||
|
||||
logger.warn(
|
||||
{
|
||||
envelopeId: logContext?.envelopeId,
|
||||
fileName: logContext?.fileName,
|
||||
placeholder,
|
||||
page: page.index + 1,
|
||||
code: appError.code,
|
||||
message: appError.message,
|
||||
},
|
||||
'Skipping placeholder with invalid field metadata',
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
LibPDF returns bbox in points with bottom-left origin.
|
||||
@@ -182,8 +234,9 @@ export const removePlaceholdersFromPDF = async (pdf: Buffer, placeholders?: Plac
|
||||
*/
|
||||
export const extractPdfPlaceholders = async (
|
||||
pdf: Buffer,
|
||||
logContext?: ExtractPlaceholdersLogContext,
|
||||
): Promise<{ cleanedPdf: Buffer; placeholders: PlaceholderInfo[] }> => {
|
||||
const placeholders = await extractPlaceholdersFromPDF(pdf);
|
||||
const placeholders = await extractPlaceholdersFromPDF(pdf, logContext);
|
||||
|
||||
if (placeholders.length === 0) {
|
||||
return { cleanedPdf: pdf, placeholders: [] };
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { FieldType } from '@prisma/client';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
import {
|
||||
parseFieldMetaFromPlaceholder,
|
||||
parseFieldTypeFromPlaceholder,
|
||||
parsePlaceholderData,
|
||||
parseRawFieldMetaFromPlaceholder,
|
||||
} from './helpers';
|
||||
|
||||
const expectInvalidBody = (fn: () => unknown) => {
|
||||
try {
|
||||
fn();
|
||||
expect.unreachable('Expected an AppError to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AppError);
|
||||
expect((error as AppError).code).toBe(AppErrorCode.INVALID_BODY);
|
||||
}
|
||||
};
|
||||
|
||||
describe('parseFieldTypeFromPlaceholder function', () => {
|
||||
it('maps known field type strings to the FieldType enum', () => {
|
||||
expect(parseFieldTypeFromPlaceholder('signature')).toBe(FieldType.SIGNATURE);
|
||||
expect(parseFieldTypeFromPlaceholder('radio')).toBe(FieldType.RADIO);
|
||||
expect(parseFieldTypeFromPlaceholder('checkbox')).toBe(FieldType.CHECKBOX);
|
||||
expect(parseFieldTypeFromPlaceholder('dropdown')).toBe(FieldType.DROPDOWN);
|
||||
});
|
||||
|
||||
it('is case-insensitive and trims surrounding whitespace', () => {
|
||||
expect(parseFieldTypeFromPlaceholder(' SiGnAtUrE ')).toBe(FieldType.SIGNATURE);
|
||||
expect(parseFieldTypeFromPlaceholder('RADIO')).toBe(FieldType.RADIO);
|
||||
});
|
||||
|
||||
it('throws INVALID_BODY for an unknown field type', () => {
|
||||
expectInvalidBody(() => parseFieldTypeFromPlaceholder('FILE'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('parsePlaceholderData function', () => {
|
||||
it('splits top-level parts on commas and trims each token', () => {
|
||||
expect(parsePlaceholderData('SIGNATURE, r1, required=true')).toEqual(['SIGNATURE', 'r1', 'required=true']);
|
||||
});
|
||||
|
||||
it('does not split on escaped commas', () => {
|
||||
expect(parsePlaceholderData('dropdown, r1, options=Legal\\, Compliance|Sales')).toEqual([
|
||||
'dropdown',
|
||||
'r1',
|
||||
'options=Legal\\, Compliance|Sales',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseRawFieldMetaFromPlaceholder function', () => {
|
||||
it('splits each token into a key/value entry', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['required=true', 'fontSize=12'])).toEqual({
|
||||
required: 'true',
|
||||
fontSize: '12',
|
||||
});
|
||||
});
|
||||
|
||||
it('only splits on the first unescaped equals sign', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['label=a=b'])).toEqual({ label: 'a=b' });
|
||||
});
|
||||
|
||||
it('drops tokens without a value and overwrites duplicate keys with the last', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['required', 'fontSize=12', 'fontSize=14'])).toEqual({
|
||||
fontSize: '14',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseFieldMetaFromPlaceholder function', () => {
|
||||
describe('non-field-meta cases', () => {
|
||||
it('returns undefined for signature and free signature fields', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ required: 'true' }, FieldType.SIGNATURE)).toBeUndefined();
|
||||
expect(parseFieldMetaFromPlaceholder({}, FieldType.FREE_SIGNATURE)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when there is no metadata', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({}, FieldType.TEXT)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generic metadata', () => {
|
||||
it('coerces required/readOnly to booleans (case-insensitive)', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ required: 'TRUE', readOnly: 'false' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
required: true,
|
||||
readOnly: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('coerces numeric properties to numbers', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ fontSize: '14' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
fontSize: 14,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops numeric properties that are not a number', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder({ fontSize: 'abc' }, FieldType.TEXT);
|
||||
|
||||
expect(parsed).toEqual({ type: 'text' });
|
||||
expect(parsed).not.toHaveProperty('fontSize');
|
||||
});
|
||||
|
||||
it('keeps label/placeholder for non-selection fields', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ label: 'Company Name', placeholder: 'Acme' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
label: 'Company Name',
|
||||
placeholder: 'Acme',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('radio fields', () => {
|
||||
it('builds stable values from options', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ options: 'Yes|No|Maybe' }, FieldType.RADIO)).toEqual({
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, checked: false, value: 'Yes' },
|
||||
{ id: 2, checked: false, value: 'No' },
|
||||
{ id: 3, checked: false, value: 'Maybe' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('marks only the selected option as checked', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder({ options: 'Yes|No|Maybe', selected: 'No' }, FieldType.RADIO);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, checked: false, value: 'Yes' },
|
||||
{ id: 2, checked: true, value: 'No' },
|
||||
{ id: 3, checked: false, value: 'Maybe' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when a default value is provided without options', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ selected: 'No' }, FieldType.RADIO));
|
||||
});
|
||||
|
||||
it('throws when the default value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'Yes|No', selected: 'Maybe' }, FieldType.RADIO));
|
||||
});
|
||||
|
||||
it('throws when options is empty', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: '' }, FieldType.RADIO));
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkbox fields', () => {
|
||||
it('builds values with checked state, validation rule alias and length', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder(
|
||||
{
|
||||
options: 'Email|SMS|Phone',
|
||||
checked: 'Email|Phone',
|
||||
validationRule: 'atLeast',
|
||||
validationLength: '1',
|
||||
},
|
||||
FieldType.CHECKBOX,
|
||||
);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'checkbox',
|
||||
validationRule: 'Select at least',
|
||||
validationLength: 1,
|
||||
values: [
|
||||
{ id: 1, checked: true, value: 'Email' },
|
||||
{ id: 2, checked: false, value: 'SMS' },
|
||||
{ id: 3, checked: true, value: 'Phone' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('throws for an unknown validation rule', () => {
|
||||
expectInvalidBody(() =>
|
||||
parseFieldMetaFromPlaceholder({ options: 'A|B', validationRule: 'nope' }, FieldType.CHECKBOX),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when checked values are provided without options', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ checked: 'A' }, FieldType.CHECKBOX));
|
||||
});
|
||||
|
||||
it('throws when a checked value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'A|B', checked: 'C' }, FieldType.CHECKBOX));
|
||||
});
|
||||
});
|
||||
|
||||
describe('dropdown fields', () => {
|
||||
it('builds values and sets a matching default value', () => {
|
||||
expect(
|
||||
parseFieldMetaFromPlaceholder(
|
||||
{ options: 'United States|Canada|United Kingdom', defaultValue: 'Canada' },
|
||||
FieldType.DROPDOWN,
|
||||
),
|
||||
).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'United States' }, { value: 'Canada' }, { value: 'United Kingdom' }],
|
||||
defaultValue: 'Canada',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when the default value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'A|B', defaultValue: 'C' }, FieldType.DROPDOWN));
|
||||
});
|
||||
});
|
||||
|
||||
describe('selection field options parsing', () => {
|
||||
it('trims option values and drops empty entries', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ options: ' A || B ' }, FieldType.DROPDOWN)).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'A' }, { value: 'B' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('parses escaped delimiters through the full placeholder pipeline', () => {
|
||||
const [, , ...fieldMetaData] = parsePlaceholderData(
|
||||
'dropdown, r1, options=Sales\\|Ops|Legal\\, Compliance|A\\=B',
|
||||
);
|
||||
|
||||
const rawFieldMeta = parseRawFieldMetaFromPlaceholder(fieldMetaData);
|
||||
const parsed = parseFieldMetaFromPlaceholder(rawFieldMeta, FieldType.DROPDOWN);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'Sales|Ops' }, { value: 'Legal, Compliance' }, { value: 'A=B' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -45,6 +45,134 @@ type RecipientPlaceholderInfo = {
|
||||
recipientIndex: number;
|
||||
};
|
||||
|
||||
const CHECKBOX_VALIDATION_RULE_BY_ALIAS: Record<string, string> = {
|
||||
atLeast: 'Select at least',
|
||||
exactly: 'Select exactly',
|
||||
atMost: 'Select at most',
|
||||
};
|
||||
|
||||
/*
|
||||
Split a string on a delimiter, treating `\` as an escape for the next character.
|
||||
Delimiters preceded by `\` are kept in the output instead of splitting (e.g. `\,`, `\=`, `\|`).
|
||||
|
||||
With delimiter ',' (top-level placeholder parts):
|
||||
'radio, r1, options=Card/Check|Bank Transfer, selected=Bank Transfer'
|
||||
-> ['radio', ' r1', ' options=Card/Check|Bank Transfer', ' selected=Bank Transfer']
|
||||
|
||||
With delimiter '=' (split one field metadata token into key + value):
|
||||
'options=Card/Check|Bank Transfer'
|
||||
-> ['options', 'Card/Check|Bank Transfer']
|
||||
|
||||
With delimiter '|' (split option list inside 'options='):
|
||||
'Card/Check|Bank Transfer'
|
||||
-> ['Card/Check', 'Bank Transfer']
|
||||
*/
|
||||
const splitPlaceholderToken = (value: string, delimiter: string): string[] => {
|
||||
const parts: string[] = [];
|
||||
let currentPart = '';
|
||||
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
const char = value[index];
|
||||
const nextChar = value[index + 1];
|
||||
|
||||
if (char === '\\' && nextChar) {
|
||||
currentPart += char + nextChar;
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === delimiter) {
|
||||
parts.push(currentPart);
|
||||
currentPart = '';
|
||||
continue;
|
||||
}
|
||||
|
||||
currentPart += char;
|
||||
}
|
||||
|
||||
parts.push(currentPart);
|
||||
|
||||
return parts;
|
||||
};
|
||||
|
||||
/*
|
||||
Removes the escape backslashes left over after splitting, so \,=, \|, \\ become their literal characters.
|
||||
|
||||
E.g.
|
||||
'Legal\, Compliance' -> 'Legal, Compliance'
|
||||
'Card\|Check' -> 'Card|Check'
|
||||
'A\=B' -> 'A=B'
|
||||
'C\D' -> 'C\D'
|
||||
*/
|
||||
const unescapePlaceholderValue = (value: string): string => {
|
||||
return value.replace(/\\([,=|\\])/g, '$1');
|
||||
};
|
||||
|
||||
/*
|
||||
Cleans up a selection option/default after splitting:
|
||||
unescapes literal delimiters, collapses repeated whitespace, and trims the ends.
|
||||
|
||||
E.g.
|
||||
' Legal\, Compliance ' -> 'Legal, Compliance'
|
||||
*/
|
||||
const normalizePlaceholderSelectionValue = (value: string): string => {
|
||||
return unescapePlaceholderValue(value).replace(/\s+/g, ' ').trim();
|
||||
};
|
||||
|
||||
/*
|
||||
Split an options string into individual choices.
|
||||
Splits on unescaped '|', then unescapes, trims, and drops empty entries.
|
||||
|
||||
E.g.
|
||||
'Card/Check|Bank Transfer' -> ['Card/Check', 'Bank Transfer']
|
||||
'Card\\|Check|Bank Transfer' -> ['Card|Check', 'Bank Transfer']
|
||||
*/
|
||||
const parsePlaceholderOptions = (value: string): string[] => {
|
||||
return splitPlaceholderToken(value, '|')
|
||||
.map((option) => normalizePlaceholderSelectionValue(option))
|
||||
.filter((option) => option.length > 0);
|
||||
};
|
||||
|
||||
/*
|
||||
Split a placeholder string into top-level parts (field type, recipient, metadata).
|
||||
Splits on unescaped commas, then trims whitespace.
|
||||
|
||||
E.g.
|
||||
'SIGNATURE, r1, required=true'
|
||||
-> ['SIGNATURE', 'r1', 'required=true']
|
||||
*/
|
||||
export const parsePlaceholderData = (value: string): string[] => {
|
||||
return splitPlaceholderToken(value, ',').map((token) => token.trim());
|
||||
};
|
||||
|
||||
/*
|
||||
Transforms the field metadata string array into a record of key/value pairs.
|
||||
Each token is split on the first unescaped '='; tokens with no key or no '=' are dropped.
|
||||
|
||||
E.g.
|
||||
['required=true', 'fontSize=12', 'label=a=b']
|
||||
-> { required: 'true', fontSize: '12', label: 'a=b' }
|
||||
*/
|
||||
export const parseRawFieldMetaFromPlaceholder = (fieldMetaData: string[]): Record<string, string> => {
|
||||
const rawFieldMeta: Record<string, string> = {};
|
||||
|
||||
for (const fieldMeta of fieldMetaData) {
|
||||
// Split on the first '=' only; any further '=' stays part of the value (e.g. 'label=a=b').
|
||||
const [rawKey, ...valueParts] = splitPlaceholderToken(fieldMeta, '=');
|
||||
|
||||
if (!rawKey || valueParts.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = rawKey.trim();
|
||||
const value = valueParts.join('=').trim();
|
||||
|
||||
rawFieldMeta[key] = value;
|
||||
}
|
||||
|
||||
return rawFieldMeta;
|
||||
};
|
||||
|
||||
/*
|
||||
Parse field type string to FieldType enum.
|
||||
Normalizes the input (uppercase, trim) and validates it's a valid field type.
|
||||
@@ -72,6 +200,169 @@ export const parseFieldTypeFromPlaceholder = (fieldTypeString: string): FieldTyp
|
||||
});
|
||||
};
|
||||
|
||||
const getDefaultFieldMetaValue = (rawFieldMeta: Record<string, string>) => {
|
||||
const defaultValue = rawFieldMeta.defaultValue ?? rawFieldMeta.default ?? rawFieldMeta.selected;
|
||||
|
||||
return defaultValue ? normalizePlaceholderSelectionValue(defaultValue) : undefined;
|
||||
};
|
||||
|
||||
const parseCheckboxValidationRule = (value: string): string => {
|
||||
const validationRule = CHECKBOX_VALIDATION_RULE_BY_ALIAS[value];
|
||||
|
||||
if (!validationRule) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Invalid checkbox placeholder validation rule: ${value}`,
|
||||
});
|
||||
}
|
||||
|
||||
return validationRule;
|
||||
};
|
||||
|
||||
const parseSelectionFieldOptions = (
|
||||
rawFieldMeta: Record<string, string>,
|
||||
fieldType: FieldType,
|
||||
): string[] | undefined => {
|
||||
const rawOptions = rawFieldMeta.options;
|
||||
|
||||
if (rawOptions === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedOptions = parsePlaceholderOptions(rawOptions);
|
||||
|
||||
if (parsedOptions.length === 0) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `${fieldType} placeholder options must contain at least one value`,
|
||||
});
|
||||
}
|
||||
|
||||
return parsedOptions;
|
||||
};
|
||||
|
||||
const applyRadioFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.RADIO);
|
||||
const defaultValue = getDefaultFieldMetaValue(rawFieldMeta);
|
||||
|
||||
if (!options && defaultValue) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Radio placeholder default value requires options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedOptionIndex = defaultValue ? options.findIndex((option) => option === defaultValue) : -1;
|
||||
|
||||
if (defaultValue && selectedOptionIndex === -1) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Radio placeholder default value "${defaultValue}" must match one of the options`,
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option, index) => ({
|
||||
id: index + 1,
|
||||
checked: index === selectedOptionIndex,
|
||||
value: option,
|
||||
}));
|
||||
};
|
||||
|
||||
const applyCheckboxFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.CHECKBOX);
|
||||
const checkedValues = rawFieldMeta.checked ? parsePlaceholderOptions(rawFieldMeta.checked) : [];
|
||||
|
||||
if (!options && checkedValues.length > 0) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Checkbox placeholder checked values require options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const unmatchedCheckedValues = checkedValues.filter((checkedValue) => !options.includes(checkedValue));
|
||||
|
||||
if (unmatchedCheckedValues.length > 0) {
|
||||
const unmatchedCheckedValue = unmatchedCheckedValues[0];
|
||||
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: [`Checkbox placeholder checked value "${unmatchedCheckedValue}"`, 'must match one of the options'].join(
|
||||
' ',
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option, index) => ({
|
||||
id: index + 1,
|
||||
checked: checkedValues.includes(option),
|
||||
value: option,
|
||||
}));
|
||||
};
|
||||
|
||||
const applyDropdownFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.DROPDOWN);
|
||||
const defaultValue = getDefaultFieldMetaValue(rawFieldMeta);
|
||||
|
||||
if (!options && defaultValue) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Dropdown placeholder default value requires options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (defaultValue && !options.includes(defaultValue)) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Dropdown placeholder default value "${defaultValue}" must match one of the options`,
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option) => ({
|
||||
value: option,
|
||||
}));
|
||||
|
||||
if (defaultValue) {
|
||||
parsedFieldMeta.defaultValue = defaultValue;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
Generic field metadata properties are simple properties consisting of a key and a value.
|
||||
E.g. 'required=true', 'fontSize=12', 'textAlign=left'
|
||||
They don't require special handling.
|
||||
|
||||
Special field metadata properties are complex properties consisting of a key and a value with multiple parts.
|
||||
E.g. 'options=Card/Check|Bank Transfer', 'checked=Card|Check', 'selected=Bank Transfer'
|
||||
They require special handling.
|
||||
*/
|
||||
const shouldSkipGenericFieldMetaParsing = (property: string, fieldType: FieldType): boolean => {
|
||||
if (property === 'options' || property === 'default' || property === 'selected') {
|
||||
return true;
|
||||
}
|
||||
|
||||
const isSelectionField =
|
||||
fieldType === FieldType.CHECKBOX || fieldType === FieldType.RADIO || fieldType === FieldType.DROPDOWN;
|
||||
|
||||
if (!isSelectionField) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
property === 'label' ||
|
||||
property === 'placeholder' ||
|
||||
property === 'defaultValue' ||
|
||||
(fieldType === FieldType.CHECKBOX && property === 'checked')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/*
|
||||
Transform raw field metadata from placeholder format to schema format.
|
||||
Users should provide properly capitalized property names (e.g., readOnly, fontSize, textAlign).
|
||||
@@ -91,7 +382,7 @@ export const parseFieldMetaFromPlaceholder = (
|
||||
|
||||
const fieldTypeString = String(fieldType).toLowerCase();
|
||||
|
||||
const parsedFieldMeta: Record<string, boolean | number | string> = {
|
||||
const parsedFieldMeta: Record<string, unknown> = {
|
||||
type: fieldTypeString,
|
||||
};
|
||||
|
||||
@@ -104,24 +395,39 @@ export const parseFieldMetaFromPlaceholder = (
|
||||
const rawFieldMetaEntries = Object.entries(rawFieldMeta);
|
||||
|
||||
for (const [property, value] of rawFieldMetaEntries) {
|
||||
if (shouldSkipGenericFieldMetaParsing(property, fieldType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const unescapedValue = unescapePlaceholderValue(value);
|
||||
|
||||
if (property === 'readOnly' || property === 'required') {
|
||||
parsedFieldMeta[property] = value === 'true';
|
||||
parsedFieldMeta[property] = unescapedValue.toLowerCase() === 'true';
|
||||
} else if (property === 'validationRule' && fieldType === FieldType.CHECKBOX) {
|
||||
parsedFieldMeta[property] = parseCheckboxValidationRule(unescapedValue);
|
||||
} else if (
|
||||
property === 'fontSize' ||
|
||||
property === 'maxValue' ||
|
||||
property === 'minValue' ||
|
||||
property === 'characterLimit'
|
||||
property === 'characterLimit' ||
|
||||
property === 'validationLength'
|
||||
) {
|
||||
const numValue = Number(value);
|
||||
const numValue = Number(unescapedValue);
|
||||
|
||||
if (!Number.isNaN(numValue)) {
|
||||
parsedFieldMeta[property] = numValue;
|
||||
}
|
||||
} else {
|
||||
parsedFieldMeta[property] = value;
|
||||
parsedFieldMeta[property] = unescapedValue;
|
||||
}
|
||||
}
|
||||
|
||||
match(fieldType)
|
||||
.with(FieldType.RADIO, () => applyRadioFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.with(FieldType.CHECKBOX, () => applyCheckboxFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.with(FieldType.DROPDOWN, () => applyDropdownFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.otherwise(() => undefined);
|
||||
|
||||
return parsedFieldMeta;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { adminGlobalSearch } from '@documenso/lib/server-only/admin/admin-global-search';
|
||||
|
||||
import { adminProcedure } from '../trpc';
|
||||
import { ZAdminSearchRequestSchema, ZAdminSearchResponseSchema } from './admin-search.types';
|
||||
|
||||
export const adminSearchRoute = adminProcedure
|
||||
.input(ZAdminSearchRequestSchema)
|
||||
.output(ZAdminSearchResponseSchema)
|
||||
.query(async ({ input }) => {
|
||||
const { query } = input;
|
||||
|
||||
const groups = await adminGlobalSearch({ query });
|
||||
|
||||
return { groups };
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const ZAdminSearchResultTypeSchema = z.enum([
|
||||
'document',
|
||||
'user',
|
||||
'organisation',
|
||||
'team',
|
||||
'recipient',
|
||||
'subscription',
|
||||
]);
|
||||
|
||||
export const ZAdminSearchResultSchema = z.object({
|
||||
label: z.string(),
|
||||
sublabel: z.string().optional(),
|
||||
path: z.string(),
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
export const ADMIN_SEARCH_MAX_QUERY_LENGTH = 100;
|
||||
|
||||
export const ZAdminSearchRequestSchema = z.object({
|
||||
query: z.string().trim().min(1).max(ADMIN_SEARCH_MAX_QUERY_LENGTH),
|
||||
});
|
||||
|
||||
export const ZAdminSearchResponseSchema = z.object({
|
||||
groups: z.array(
|
||||
z.object({
|
||||
type: ZAdminSearchResultTypeSchema,
|
||||
results: ZAdminSearchResultSchema.array(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export type TAdminSearchResultType = z.infer<typeof ZAdminSearchResultTypeSchema>;
|
||||
export type TAdminSearchResult = z.infer<typeof ZAdminSearchResultSchema>;
|
||||
export type TAdminSearchRequest = z.infer<typeof ZAdminSearchRequestSchema>;
|
||||
export type TAdminSearchResponse = z.infer<typeof ZAdminSearchResponseSchema>;
|
||||
@@ -1,5 +1,4 @@
|
||||
import { router } from '../trpc';
|
||||
import { adminSearchRoute } from './admin-search';
|
||||
import { createAdminOrganisationRoute } from './create-admin-organisation';
|
||||
import { createStripeCustomerRoute } from './create-stripe-customer';
|
||||
import { createSubscriptionClaimRoute } from './create-subscription-claim';
|
||||
@@ -119,6 +118,5 @@ export const adminRouter = router({
|
||||
teamMember: {
|
||||
delete: deleteAdminTeamMemberRoute,
|
||||
},
|
||||
search: adminSearchRoute,
|
||||
updateSiteSetting: updateSiteSettingRoute,
|
||||
});
|
||||
|
||||
@@ -124,7 +124,9 @@ export const createEnvelopeRouteCaller = async ({
|
||||
});
|
||||
|
||||
// Todo: Embeds - Might need to add this for client-side embeds in the future.
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
fileName: file.name,
|
||||
});
|
||||
|
||||
const { documentData } = await putPdfFileServerSide({
|
||||
name: file.name,
|
||||
|
||||
Reference in New Issue
Block a user