create-erxes 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +23 -2
  2. package/dist/index.js +481 -0
  3. package/dist/templates/base/.agents/skills/endpoint/SKILL.md +20 -0
  4. package/dist/templates/base/.agents/skills/schema-change/SKILL.md +28 -0
  5. package/dist/templates/base/.agents/skills/verify/SKILL.md +24 -0
  6. package/dist/templates/base/.github/workflows/ci.yml +44 -0
  7. package/dist/templates/base/AGENTS.md +59 -0
  8. package/dist/templates/base/CLAUDE.md +1 -0
  9. package/dist/templates/base/Dockerfile +13 -0
  10. package/dist/templates/base/_dockerignore +4 -0
  11. package/dist/templates/base/_env.example +15 -0
  12. package/dist/templates/base/_gitignore +11 -0
  13. package/dist/templates/base/_node-version +1 -0
  14. package/dist/templates/base/api/AGENTS.md +22 -0
  15. package/dist/templates/base/api/drizzle/0000_items.sql +13 -0
  16. package/dist/templates/base/api/drizzle/meta/0000_snapshot.json +126 -0
  17. package/dist/templates/base/api/drizzle/meta/_journal.json +13 -0
  18. package/dist/templates/base/api/drizzle.config.ts +16 -0
  19. package/dist/templates/base/api/package.json +47 -0
  20. package/dist/templates/base/api/src/__tests__/server.test.ts +51 -0
  21. package/dist/templates/base/api/src/config.ts +43 -0
  22. package/dist/templates/base/api/src/core.ts +37 -0
  23. package/dist/templates/base/api/src/db/client.ts +30 -0
  24. package/dist/templates/base/api/src/db/migrate.ts +80 -0
  25. package/dist/templates/base/api/src/db/schema.ts +34 -0
  26. package/dist/templates/base/api/src/db/table.ts +8 -0
  27. package/dist/templates/base/api/src/logger.ts +5 -0
  28. package/dist/templates/base/api/src/main.ts +23 -0
  29. package/dist/templates/base/api/src/migrate.ts +9 -0
  30. package/dist/templates/base/api/src/modules/items/__tests__/items.test.ts +92 -0
  31. package/dist/templates/base/api/src/modules/items/items.ts +127 -0
  32. package/dist/templates/base/api/src/orpc.ts +25 -0
  33. package/dist/templates/base/api/src/router.ts +10 -0
  34. package/dist/templates/base/api/src/server.ts +58 -0
  35. package/dist/templates/base/api/src/telemetry.ts +27 -0
  36. package/dist/templates/base/api/src/test/core-functions.sql +18 -0
  37. package/dist/templates/base/api/src/test/setup.ts +68 -0
  38. package/dist/templates/base/api/tsconfig.json +9 -0
  39. package/dist/templates/base/knip.ts +21 -0
  40. package/dist/templates/base/package.json +30 -0
  41. package/dist/templates/base/pnpm-workspace.yaml +20 -0
  42. package/dist/templates/base/tools/check-generated.ts +70 -0
  43. package/dist/templates/base/tools/check-rls.sh +30 -0
  44. package/dist/templates/base/tools/check-rls.sql +109 -0
  45. package/dist/templates/base/tools/no-org-id.sql +5 -0
  46. package/dist/templates/base/tools/test/no-skips.ts +58 -0
  47. package/dist/templates/base/tsconfig.base.json +16 -0
  48. package/dist/templates/base/tsconfig.json +9 -0
  49. package/dist/templates/base/ui/AGENTS.md +34 -0
  50. package/dist/templates/base/ui/package.json +35 -0
  51. package/dist/templates/base/ui/rsbuild.config.ts +39 -0
  52. package/dist/templates/base/ui/src/__Pascal__.tsx +14 -0
  53. package/dist/templates/base/ui/src/config.tsx +11 -0
  54. package/dist/templates/base/ui/src/index.ts +3 -0
  55. package/dist/templates/base/ui/src/items/ItemSheet.tsx +107 -0
  56. package/dist/templates/base/ui/src/items/ItemsPage.tsx +143 -0
  57. package/dist/templates/base/ui/src/items/useItems.ts +79 -0
  58. package/dist/templates/base/ui/src/orpc.ts +32 -0
  59. package/dist/templates/base/ui/src/styles.css +8 -0
  60. package/dist/templates/base/ui/tsconfig.json +11 -0
  61. package/dist/templates/base/vite.config.ts +62 -0
  62. package/dist/templates/migrate/.agents/skills/plugin-migrate/SKILL.md +66 -0
  63. package/dist/templates/migrate/migration/checklist.ts +429 -0
  64. package/dist/templates/migrate/migration/core-map.ts +150 -0
  65. package/dist/templates/migrate/migration/import-map.ts +4 -0
  66. package/dist/templates/migrate/migration/inventory.ts +881 -0
  67. package/dist/templates/migrate/package.json +15 -0
  68. package/dist/templates/migrate/scripts/import-mongo.ts +143 -0
  69. package/package.json +32 -3
@@ -0,0 +1,109 @@
1
+ -- The tenancy guard, run by tools/check-rls.sh on a freshly migrated database.
2
+ -- Every row it returns is a problem; no rows means the schema passes.
3
+ -- It checks one scope's database, core's or a plugin's: psql sets :scope (`core`,
4
+ -- or the plugin's name) and :policy, the tenant policy's name (core's tables
5
+ -- have core_tenant, core_enable_tenant_rls gives a plugin's tables `tenant`).
6
+ -- create-erxes copies this file into every plugin unchanged; what differs per
7
+ -- scope is in tools/no-org-id.sql next to it.
8
+ --
9
+ -- 1. A tenant table (one with org_id, or a listed one with a tenant key) has
10
+ -- row level security enabled and forced, and the :policy policy:
11
+ -- permissive, for all commands, USING and WITH CHECK
12
+ -- core_tenant_visible(<key>). Any other permissive policy would let more
13
+ -- rows through, so it fails too. This is what lets withOrg() isolate
14
+ -- organisations with no filter in the query.
15
+ -- 2. A table without org_id is in tools/no-org-id.sql, with the reason.
16
+ -- 3. Every table, index, sequence and view, and every table constraint,
17
+ -- starts with <scope>_: core and plugins share the database. Drizzle's
18
+ -- migration log is __drizzle_migrations_<scope>.
19
+ -- 4. The core_queue schema is pg-boss's (core's modules/jobs), outside these
20
+ -- checks: its tables have no row level security, a job carries its
21
+ -- organisation in its data, and failed jobs are read by the scope's
22
+ -- organisation. So no plugin role and not PUBLIC may use it; plugins queue
23
+ -- work through core_events and its insert trigger.
24
+ create temp table no_org_id (table_name text primary key, tenant_key text, reason text not null);
25
+ insert into no_org_id values (format('__drizzle_migrations_%s', :'scope'), null, 'The migration log.');
26
+ \ir no-org-id.sql
27
+
28
+ with relations as (
29
+ select c.oid, n.nspname, c.relname, c.relkind, c.relrowsecurity, c.relforcerowsecurity
30
+ from pg_class c
31
+ join pg_namespace n on n.oid = c.relnamespace
32
+ where n.nspname not in ('pg_catalog', 'information_schema', 'core_queue')
33
+ and n.nspname not like 'pg\_toast%' and n.nspname not like 'pg\_temp%'
34
+ ),
35
+ tables as (
36
+ select r.*,
37
+ exists (
38
+ select 1 from pg_attribute a where a.attrelid = r.oid and a.attname = 'org_id' and not a.attisdropped
39
+ ) as has_org_id,
40
+ l.table_name is not null as listed,
41
+ l.tenant_key
42
+ from relations r
43
+ left join no_org_id l on r.nspname = 'public' and l.table_name = r.relname
44
+ where r.relkind in ('r', 'p', 'f')
45
+ ),
46
+ tenant_tables as (
47
+ select t.*, case when t.has_org_id then 'org_id' else t.tenant_key end as key
48
+ from tables t
49
+ where t.has_org_id or t.tenant_key is not null
50
+ ),
51
+ policies as (
52
+ select tt.oid, p.policyname,
53
+ p.permissive = 'PERMISSIVE' as permissive,
54
+ p.policyname = :'policy' and p.cmd = 'ALL'
55
+ and p.qual = format('core_tenant_visible(%s)', tt.key)
56
+ and p.with_check = format('core_tenant_visible(%s)', tt.key) as is_tenant_policy
57
+ from tenant_tables tt
58
+ join pg_policies p on p.schemaname = tt.nspname and p.tablename = tt.relname
59
+ ),
60
+ log (relname) as (
61
+ select format('__drizzle_migrations_%s%s', :'scope', suffix) from unnest(array['', '_pkey', '_id_seq']) as suffix
62
+ )
63
+ select format('%s: %s', relname, concat_ws(', ',
64
+ case when not relrowsecurity then 'row level security is off' end,
65
+ case when not relforcerowsecurity then 'row level security is not forced' end,
66
+ case when not exists (select 1 from policies p where p.oid = tt.oid and p.permissive and p.is_tenant_policy)
67
+ then format('no %s policy on core_tenant_visible(%s)', :'policy', key) end))
68
+ from tenant_tables tt
69
+ where not (relrowsecurity and relforcerowsecurity
70
+ and exists (select 1 from policies p where p.oid = tt.oid and p.permissive and p.is_tenant_policy))
71
+ union all
72
+ select format('%s: permissive policy %s is not the %s check, so it lets more rows through', tt.relname, p.policyname, :'policy')
73
+ from tenant_tables tt
74
+ join policies p on p.oid = tt.oid
75
+ where p.permissive and not p.is_tenant_policy
76
+ union all
77
+ select format('%s has no org_id: add it, or list the table in tools/no-org-id.sql with the reason', relname)
78
+ from tables
79
+ where not has_org_id and not listed
80
+ union all
81
+ select format('tools/no-org-id.sql lists %s, which %s', l.table_name,
82
+ case when t.relname is null then 'does not exist' else 'has org_id' end)
83
+ from no_org_id l
84
+ left join tables t on t.nspname = 'public' and t.relname = l.table_name
85
+ where t.relname is null or t.has_org_id
86
+ union all
87
+ select format('%s %s does not start with %s_',
88
+ case relkind when 'i' then 'index' when 'I' then 'index' when 'S' then 'sequence' when 'v' then 'view'
89
+ when 'm' then 'materialized view' else 'table' end, relname, :'scope')
90
+ from relations
91
+ where relkind in ('r', 'p', 'i', 'I', 'S', 'v', 'm', 'f')
92
+ and not starts_with(relname, :'scope' || '_')
93
+ and relname not in (select relname from log)
94
+ union all
95
+ select format('constraint %s on %s does not start with %s_', co.conname, co.conrelid::regclass, :'scope')
96
+ from pg_constraint co
97
+ join relations r on r.oid = co.conrelid
98
+ where not starts_with(co.conname, :'scope' || '_')
99
+ and co.conrelid is distinct from to_regclass(format('public.__drizzle_migrations_%s', :'scope'))
100
+ union all
101
+ -- The oid forms return null when the schema doesn't exist, as in a plugin's own database.
102
+ select format('%s may use schema core_queue (the job queue): only the API''s roles may', grantee)
103
+ from (
104
+ select 'PUBLIC' as grantee where has_schema_privilege('public', to_regnamespace('core_queue')::oid, 'USAGE')
105
+ union all
106
+ select rolname from pg_roles
107
+ where rolname like 'erxes\_plugin\_%' and has_schema_privilege(oid, to_regnamespace('core_queue')::oid, 'USAGE')
108
+ ) as users
109
+ order by 1;
@@ -0,0 +1,5 @@
1
+ -- The plugin's tables without org_id, each with the reason; tools/check-rls.sql
2
+ -- reads them. A tenant_key names the column the table's tenant policy keys on
3
+ -- (core_enable_tenant_rls's second argument). None yet:
4
+ -- insert into no_org_id (table_name, tenant_key, reason) values
5
+ -- ('__id___currencies', null, 'One list for every organisation.');
@@ -0,0 +1,58 @@
1
+ import type { Reporter, TestModule, Vitest } from 'vite-plus/test/node';
2
+
3
+ /** Skipped, pending or todo suites and tests in the modules that ran. */
4
+ const skippedIn = (modules: readonly TestModule[]) =>
5
+ modules.flatMap((module) => [
6
+ ...[...module.children.allSuites()]
7
+ .filter((suite) => suite.state() === 'skipped' || suite.state() === 'pending')
8
+ .map((suite) => `${suite.state()} suite: ${suite.fullName} (${module.relativeModuleId})`),
9
+ ...[...module.children.allTests()]
10
+ .filter((test) => ['skipped', 'pending'].includes(test.result().state))
11
+ .map((test) => `${test.result().state} test: ${test.fullName} (${module.relativeModuleId})`),
12
+ ]);
13
+
14
+ /** Projects whose files all ran without running a test. */
15
+ const emptyProjects = async (vitest: Vitest, modules: readonly TestModule[]) => {
16
+ const problems: string[] = [];
17
+
18
+ for (const project of vitest.projects) {
19
+ const ran = modules.filter((module) => module.project.name === project.name);
20
+ const { testFiles } = await project.globTestFiles();
21
+ const tests = ran.flatMap((module) => [...module.children.allTests()]);
22
+
23
+ if (ran.length === testFiles.length && !tests.some((test) => test.result().state !== 'skipped'))
24
+ problems.push(`project ${project.name} ran no tests`);
25
+ }
26
+
27
+ return problems;
28
+ };
29
+
30
+ /**
31
+ * A skipped test passes in Vitest, so this reporter fails the run on any
32
+ * skipped, pending or todo test or suite (`.skip`, `skipIf`, `ctx.skip()`,
33
+ * `.todo`), and on a project whose files all ran without a test. A run
34
+ * filtered with `-t` skips what it doesn't match, so only the project rule
35
+ * applies then; a run of some files never checks the other projects.
36
+ */
37
+ export const noSkips = (): Reporter => {
38
+ let vitest: Vitest | undefined;
39
+
40
+ return {
41
+ onInit(ctx) {
42
+ vitest = ctx;
43
+ },
44
+ async onTestRunEnd(modules) {
45
+ if (!vitest) return;
46
+
47
+ const problems = [
48
+ ...(vitest.config.testNamePattern ? [] : skippedIn(modules)),
49
+ ...(await emptyProjects(vitest, modules)),
50
+ ];
51
+
52
+ if (problems.length) {
53
+ process.exitCode = 1;
54
+ vitest.logger.error(['Tests must run, not skip:', ...problems].join('\n '));
55
+ }
56
+ },
57
+ };
58
+ };
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2024",
4
+ "lib": ["es2024"],
5
+ "strict": true,
6
+ "noUncheckedIndexedAccess": true,
7
+ "noImplicitOverride": true,
8
+ "noImplicitReturns": true,
9
+ "verbatimModuleSyntax": true,
10
+ "erasableSyntaxOnly": true,
11
+ "allowImportingTsExtensions": true,
12
+ "isolatedModules": true,
13
+ "skipLibCheck": true,
14
+ "noEmit": true
15
+ }
16
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "module": "nodenext",
5
+ "moduleResolution": "nodenext",
6
+ "types": ["node"]
7
+ },
8
+ "include": ["*.ts", "tools", "migration", "scripts"]
9
+ }
@@ -0,0 +1,34 @@
1
+ # ui
2
+
3
+ The Module Federation remote `__id___ui`. web loads `./config` (`CONFIG`)
4
+ and renders `./__id__` (the `__Pascal__` export) under `/__id__/*`.
5
+
6
+ - `rsbuild.config.ts` declares web's shared singletons with `import: false`,
7
+ reading the list from `erxes-ui/federation`, so it follows the installed
8
+ erxes-ui. A missing name bundles a second copy and breaks at runtime.
9
+ - Build pages from `erxes-ui` components and its root export. The host provides
10
+ React, the router, the query client and erxes-ui, and web's stylesheet styles
11
+ erxes-ui's components.
12
+ - Any Tailwind class works, on erxes-ui's tokens (`bg-muted`, `text-sm`,
13
+ `md:grid-cols-2`). `src/styles.css` builds the plugin's own utilities, and
14
+ `src/__Pascal__.tsx` passes them to `addPluginStyles`, which adds only the
15
+ classes web's stylesheet lacks. erxes-ui's design rules hold here too (its
16
+ `AGENTS.md`, enforced by `vp run check`): no inline styles or raw colours.
17
+ - The plugin's API goes through `src/orpc.ts`:
18
+ `useQuery(orpc.items.list.queryOptions(...))`,
19
+ `useMutation(orpc.items.create.mutationOptions(...))`. Types come from
20
+ `api/src/router.ts`; after a mutation, invalidate `orpc.<group>.key()`.
21
+ - Core's API goes through `orpc` from `@erxes/core-contract/client`, the client
22
+ web uses, with the member's own session; import it as `core` beside the
23
+ plugin's `orpc`: `useQuery(core.users.get.queryOptions({ input: { id } }))`.
24
+ It shares web's query cache, and the member needs the core permission the
25
+ procedure asks for (`team.view` for team members).
26
+ - Members: `SelectMember.Field`, `SelectMember.InlineCell`, `MemberInline` and
27
+ `useMembersById` from erxes-ui, given `members={memberQueries}` from
28
+ `@erxes/core-contract/client`. `src/items/ItemsPage.tsx` has a member filter
29
+ and a "Created by" column. erxes-ui's `EntityPicker` is the searchable list
30
+ under them, for a picker of the plugin's own records.
31
+ - Text uses `t(key, 'English default')` from `react-i18next`.
32
+ - Development: `pnpm dev:ui` serves `http://localhost:__uiPort__/remoteEntry.js`;
33
+ web loads it from the manifest's `UI_ENTRY_URL` or from its own
34
+ `PUBLIC_PLUGINS=__id___ui@http://localhost:__uiPort__/remoteEntry.js`.
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@__id__/ui",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "rsbuild dev",
8
+ "build": "rsbuild build"
9
+ },
10
+ "dependencies": {
11
+ "@erxes/core-contract": "0.1.0-v2.2",
12
+ "@orpc/client": "1.16.2",
13
+ "@orpc/tanstack-query": "1.16.2",
14
+ "@tabler/icons-react": "3.34.0",
15
+ "@tanstack/react-query": "^5.107.1",
16
+ "erxes-ui": "npm:@erxes/ui@4.0.0-v2.2",
17
+ "jotai": "^3.0.2",
18
+ "react": "19.3.1",
19
+ "react-dom": "19.3.1",
20
+ "react-i18next": "^18.0.1",
21
+ "react-router-dom": "^7.18.5"
22
+ },
23
+ "devDependencies": {
24
+ "@__id__/api": "workspace:*",
25
+ "@module-federation/rsbuild-plugin": "2.9.3",
26
+ "@rsbuild/core": "^2.3.2",
27
+ "@rsbuild/plugin-babel": "^2.1.0",
28
+ "@rsbuild/plugin-react": "^2.1.1",
29
+ "@tailwindcss/postcss": "^4.3.5",
30
+ "@types/react": "19.3.0",
31
+ "@types/react-dom": "19.3.0",
32
+ "babel-plugin-react-compiler": "^1.0.0",
33
+ "tailwindcss": "^4.3.5"
34
+ }
35
+ }
@@ -0,0 +1,39 @@
1
+ import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
2
+ import { defineConfig } from '@rsbuild/core';
3
+ import { pluginBabel } from '@rsbuild/plugin-babel';
4
+ import { pluginReact } from '@rsbuild/plugin-react';
5
+ import tailwindcss from '@tailwindcss/postcss';
6
+ import reactCompiler from 'babel-plugin-react-compiler';
7
+ // What web shares. The host provides each one (`import: false`), so the plugin
8
+ // never bundles a second React, router, query client or erxes-ui.
9
+ import { SHARED } from 'erxes-ui/federation';
10
+
11
+ export default defineConfig({
12
+ plugins: [
13
+ pluginReact(),
14
+ // The React Compiler memoizes components and hooks; it runs on our source before SWC.
15
+ pluginBabel({
16
+ include: /[\\/]src[\\/]/,
17
+ babelLoaderOptions: (options) => {
18
+ options.plugins ??= [];
19
+ options.plugins.unshift(reactCompiler);
20
+ },
21
+ }),
22
+ pluginModuleFederation({
23
+ name: '__id___ui',
24
+ filename: 'remoteEntry.js',
25
+ exposes: { './config': './src/config.tsx', './__id__': './src/__Pascal__.tsx' },
26
+ dts: false,
27
+ shared: Object.fromEntries(
28
+ SHARED.map((name) => [name, { singleton: true, requiredVersion: false, import: false }]),
29
+ ),
30
+ }),
31
+ ],
32
+ source: { entry: { index: './src/index.ts' } },
33
+ // Chunks load from wherever remoteEntry.js came from, not from web's origin.
34
+ output: { assetPrefix: 'auto' },
35
+ dev: { assetPrefix: true, lazyCompilation: false },
36
+ server: { port: Number(process.env.UI_PORT) || __uiPort__, cors: { origin: '*' } },
37
+ // src/styles.css: the plugin's own Tailwind utilities.
38
+ tools: { postcss: (_options, { addPlugins }) => addPlugins(tailwindcss()) },
39
+ });
@@ -0,0 +1,14 @@
1
+ import { addPluginStyles } from 'erxes-ui';
2
+ import { Route, Routes } from 'react-router-dom';
3
+ import { ItemsPage } from './items/ItemsPage.tsx';
4
+ import { PLUGIN } from './orpc.ts';
5
+ import css from './styles.css?inline';
6
+
7
+ addPluginStyles(PLUGIN, css);
8
+
9
+ /** The page module web renders under `/__id__/*` (loaded as `__id___ui/__id__`). */
10
+ export const __Pascal__ = () => (
11
+ <Routes>
12
+ <Route index element={<ItemsPage />} />
13
+ </Routes>
14
+ );
@@ -0,0 +1,11 @@
1
+ import { IconBox } from '@tabler/icons-react';
2
+ import type { IUIConfig } from 'erxes-ui';
3
+ import { PLUGIN } from './orpc.ts';
4
+
5
+ /** What web reads from `./config`: the app tab and the page module under `/__id__/*`. */
6
+ export const CONFIG: IUIConfig = {
7
+ name: PLUGIN,
8
+ path: PLUGIN,
9
+ icon: IconBox,
10
+ modules: [{ name: PLUGIN, path: PLUGIN, icon: IconBox }],
11
+ };
@@ -0,0 +1,3 @@
1
+ // The remote has no page of its own: web loads ./config and ./__id__.
2
+ // Module Federation needs an async boundary before shared modules load.
3
+ void import('./config.tsx');
@@ -0,0 +1,107 @@
1
+ import { isDefinedError } from '@orpc/client';
2
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
3
+ import { Button, Input, Label, Sheet, Textarea } from 'erxes-ui';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { orpc } from '../orpc.ts';
6
+ import { type Item, useOpenItem } from './useItems.ts';
7
+
8
+ const textOf = (value: FormDataEntryValue | null) => (typeof value === 'string' ? value : '');
9
+
10
+ /** A new item (`item` undefined) or a change to one. ITEM_NAME_TAKEN shows on the name field. */
11
+ const ItemForm = ({ item, onSaved }: { item?: Item; onSaved: () => void }) => {
12
+ const { t } = useTranslation('__id__');
13
+ const queryClient = useQueryClient();
14
+
15
+ const onSuccess = () => {
16
+ void queryClient.invalidateQueries({ queryKey: orpc.items.key() });
17
+ onSaved();
18
+ };
19
+
20
+ const create = useMutation(orpc.items.create.mutationOptions({ onSuccess }));
21
+ const update = useMutation(orpc.items.update.mutationOptions({ onSuccess }));
22
+ const { error, isPending } = item ? update : create;
23
+
24
+ const takenName =
25
+ isDefinedError(error) && error.code === 'ITEM_NAME_TAKEN' ? error.data.name : null;
26
+
27
+ const save = (form: FormData) => {
28
+ const fields = {
29
+ name: textOf(form.get('name')),
30
+ description: textOf(form.get('description')),
31
+ };
32
+
33
+ if (item) update.mutate({ id: item.id, ...fields });
34
+ else create.mutate(fields);
35
+ };
36
+
37
+ return (
38
+ <form action={save} className="flex flex-1 flex-col">
39
+ <Sheet.Content>
40
+ <div className="flex flex-col gap-4">
41
+ <div className="flex flex-col gap-2">
42
+ <Label htmlFor="item-name">{t('name', 'Name')}</Label>
43
+ <Input
44
+ id="item-name"
45
+ name="name"
46
+ required
47
+ defaultValue={item?.name}
48
+ aria-invalid={takenName !== null}
49
+ aria-describedby={takenName === null ? undefined : 'item-name-error'}
50
+ />
51
+ {takenName !== null && (
52
+ <p id="item-name-error" className="text-sm text-destructive">
53
+ {t('name-taken', 'Another item is already called {{name}}.', { name: takenName })}
54
+ </p>
55
+ )}
56
+ </div>
57
+ <div className="flex flex-col gap-2">
58
+ <Label htmlFor="item-description">{t('description', 'Description')}</Label>
59
+ <Textarea id="item-description" name="description" defaultValue={item?.description} />
60
+ </div>
61
+ {error && !isDefinedError(error) && (
62
+ <p role="alert" className="text-sm text-destructive">
63
+ {error.message}
64
+ </p>
65
+ )}
66
+ </div>
67
+ </Sheet.Content>
68
+ <Sheet.Footer>
69
+ <Button type="submit" disabled={isPending}>
70
+ {t('save', 'Save')}
71
+ </Button>
72
+ </Sheet.Footer>
73
+ </form>
74
+ );
75
+ };
76
+
77
+ /** The side panel: a new item, or one from the list to change. */
78
+ export const ItemSheet = ({ items }: { items: Item[] }) => {
79
+ const { t } = useTranslation('__id__');
80
+ const { openId, close } = useOpenItem();
81
+ const item = items.find((candidate) => candidate.id === openId);
82
+
83
+ return (
84
+ <Sheet open={Boolean(openId)} onOpenChange={(open) => !open && close()}>
85
+ <Sheet.View className="sm:max-w-md">
86
+ <Sheet.Header>
87
+ <Sheet.Title>{item ? item.name : t('new-item', 'New item')}</Sheet.Title>
88
+ <Sheet.Description className="sr-only">
89
+ {item
90
+ ? t('edit-item-hint', 'Change the name or the description.')
91
+ : t('new-item-hint', 'Give it a name. The description is optional.')}
92
+ </Sheet.Description>
93
+ <Sheet.Close />
94
+ </Sheet.Header>
95
+ {openId === 'new' || item ? (
96
+ <ItemForm key={item?.id ?? 'new'} item={item} onSaved={close} />
97
+ ) : (
98
+ <Sheet.Content>
99
+ <p className="text-sm text-muted-foreground">
100
+ {t('not-found', 'This item is not in the list.')}
101
+ </p>
102
+ </Sheet.Content>
103
+ )}
104
+ </Sheet.View>
105
+ </Sheet>
106
+ );
107
+ };
@@ -0,0 +1,143 @@
1
+ import { memberQueries } from '@erxes/core-contract/client';
2
+ import { IconBox, IconPlus, IconTrash } from '@tabler/icons-react';
3
+ import {
4
+ Button,
5
+ Empty,
6
+ MemberInline,
7
+ PageContainer,
8
+ PageHeader,
9
+ RecordTable,
10
+ type RecordTableColumnDef,
11
+ RecordTableInlineCell,
12
+ SelectMember,
13
+ } from 'erxes-ui';
14
+ import { useState } from 'react';
15
+ import { useTranslation } from 'react-i18next';
16
+ import { ItemSheet } from './ItemSheet.tsx';
17
+ import { type Item, useItems, useOpenItem, useRemoveItem } from './useItems.ts';
18
+
19
+ const NameCell = ({ item }: { item: Item }) => {
20
+ const { open } = useOpenItem();
21
+
22
+ return (
23
+ <Button variant="ghost" className="w-full justify-start" onClick={() => open(item.id)}>
24
+ {item.name}
25
+ </Button>
26
+ );
27
+ };
28
+
29
+ /** Where RecordTable keeps this list's column settings. */
30
+ const TABLE_ID = '__id___items';
31
+
32
+ const DeleteCell = ({ item }: { item: Item }) => {
33
+ const { t } = useTranslation('__id__');
34
+ const remove = useRemoveItem();
35
+
36
+ return (
37
+ <Button
38
+ variant="ghost"
39
+ size="icon"
40
+ aria-label={t('delete-item', 'Delete {{name}}', { name: item.name })}
41
+ onClick={() => remove.mutate({ id: item.id })}
42
+ >
43
+ <IconTrash />
44
+ </Button>
45
+ );
46
+ };
47
+
48
+ const columns: RecordTableColumnDef<Item>[] = [
49
+ {
50
+ id: 'name',
51
+ header: 'Name',
52
+ size: 280,
53
+ cell: ({ row }) => <NameCell item={row.original} />,
54
+ },
55
+ {
56
+ id: 'description',
57
+ header: 'Description',
58
+ size: 360,
59
+ cell: ({ row }) => <span className="truncate px-2">{row.original.description}</span>,
60
+ },
61
+ {
62
+ // The member's name and avatar come from core, through the core client.
63
+ id: 'createdBy',
64
+ header: 'Created by',
65
+ size: 200,
66
+ cell: ({ row }) => (
67
+ <RecordTableInlineCell>
68
+ <MemberInline memberId={row.original.createdBy} members={memberQueries} />
69
+ </RecordTableInlineCell>
70
+ ),
71
+ },
72
+ {
73
+ id: 'updatedAt',
74
+ header: 'Updated',
75
+ size: 200,
76
+ cell: ({ row }) => <span className="px-2">{row.original.updatedAt.toLocaleString()}</span>,
77
+ },
78
+ {
79
+ id: 'delete',
80
+ header: '',
81
+ size: 48,
82
+ cell: ({ row }) => <DeleteCell item={row.original} />,
83
+ },
84
+ ];
85
+
86
+ /** The item list, newest first, with each item opening in the side panel. */
87
+ export const ItemsPage = () => {
88
+ const { t } = useTranslation('__id__');
89
+ const { open } = useOpenItem();
90
+ const [createdBy, setCreatedBy] = useState<string | null>(null);
91
+ const { data, isPending, error, hasNextPage, fetchNextPage } = useItems(createdBy);
92
+ const list = data?.pages.flatMap((page) => page.items) ?? [];
93
+
94
+ return (
95
+ <PageContainer>
96
+ <PageHeader>
97
+ <PageHeader.Start>
98
+ <IconBox />
99
+ <h1 className="text-sm font-semibold">{t('items', 'Items')}</h1>
100
+ </PageHeader.Start>
101
+ <PageHeader.End>
102
+ {/* md:w-64 is in no class web uses: the plugin's own stylesheet brings it. */}
103
+ <SelectMember.Field
104
+ aria-label={t('created-by', 'Created by')}
105
+ className="w-40 md:w-64"
106
+ value={createdBy}
107
+ onValueChange={setCreatedBy}
108
+ members={memberQueries}
109
+ placeholder={t('anyone', 'Created by anyone')}
110
+ noneLabel={t('anyone', 'Created by anyone')}
111
+ />
112
+ <Button onClick={() => open('new')}>
113
+ <IconPlus />
114
+ {t('add', 'Add item')}
115
+ </Button>
116
+ </PageHeader.End>
117
+ </PageHeader>
118
+ {error ? (
119
+ <p className="m-3 text-sm text-destructive">{error.message}</p>
120
+ ) : (
121
+ <RecordTable.Provider columns={columns} data={list} className="m-3" tableId={TABLE_ID}>
122
+ <RecordTable.CursorProvider dataLength={list.length} hasNextPage={hasNextPage}>
123
+ <RecordTable>
124
+ <RecordTable.Header />
125
+ <RecordTable.Body>
126
+ {isPending ? <RecordTable.RowSkeleton rows={8} /> : <RecordTable.RowList />}
127
+ <RecordTable.CursorForwardSkeleton handleFetchMore={() => void fetchNextPage()} />
128
+ </RecordTable.Body>
129
+ </RecordTable>
130
+ </RecordTable.CursorProvider>
131
+ {!isPending && !list.length && (
132
+ <Empty className="absolute inset-x-0 top-1/4">
133
+ <Empty.Header>
134
+ <Empty.Title>{t('empty', 'No items yet')}</Empty.Title>
135
+ </Empty.Header>
136
+ </Empty>
137
+ )}
138
+ </RecordTable.Provider>
139
+ )}
140
+ <ItemSheet items={list} />
141
+ </PageContainer>
142
+ );
143
+ };