create-erxes 0.1.10 → 0.1.12

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.
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { mkdir, readFile, readdir, symlink, writeFile } from "node:fs/promises";
9
9
  import { homedir } from "node:os";
10
10
  import { fileURLToPath } from "node:url";
11
11
  // package.json
12
- var version = "0.1.10";
12
+ var version = "0.1.12";
13
13
  // src/existing-plugins.ts
14
14
  /** The old erxes plugins a new-core plugin can be migrated from (`backend/plugins/<name>_api`). */
15
15
  const OLD_PLUGINS = [
@@ -50,7 +50,7 @@ what erxes-ui already has, and the screen each kind of page copies.
50
50
  ## Filter
51
51
 
52
52
  erxes-ui's `ListFilter` is core's own filter bar; `ui/src/modules/items/ItemsPage.tsx`
53
- gives it its fields, and `api/src/modules/items/itemFilter.ts` applies them.
53
+ gives it its fields, and `FILTER_FIELDS` in `api/src/modules/items/items.ts` applies them.
54
54
 
55
55
  - Give it every field the list can be narrowed by: `{ path: 'subject.<column>',
56
56
  label, type, options?, icon? }`, type `text`, `number`, `date`, `boolean`,
@@ -59,8 +59,9 @@ gives it its fields, and `api/src/modules/items/itemFilter.ts` applies them.
59
59
  - The conditions (core's `ConditionGroup`, rules on those paths; a `member`
60
60
  rule's `me` is the member asking) and the search live in the address.
61
61
  `useListFilterParams()` gives them to the list's query as `filter` (JSON) and
62
- `search`; the API parses `filter` with `ConditionGroup` from
63
- `@erxes/core-contract` and refuses a path it has no column for.
62
+ `search`; the API parses `filter` with `FilterParam` and compiles it with
63
+ `compileFilter` from `@erxes/plugin-sdk/filter`, which refuses a path it has
64
+ no column for.
64
65
  - Never: a search box, toggle buttons ("Mine", "Archived"), status tabs, a
65
66
  ToggleGroup for table and board, or a row of pickers above the table. Each of
66
67
  those is a field in the menu or the Display menu.
@@ -54,8 +54,9 @@ without line-by-line review.
54
54
  through `@erxes/core-contract/client` with the member's session. Neither reads
55
55
  `core_*` tables or imports core's app code.
56
56
  - Members are signed in by core: the UI sends a session token, the API checks it
57
- with `verifyPluginSession`. There is no public route yet, because core can't
58
- tell a public request's organisation.
57
+ with `verifyPluginSession`. A caller outside erxes (a webhook) reaches a path
58
+ the manifest's `publicPaths` lists through core, which names the organisation:
59
+ check it with `verifyPublicCall` (`@erxes/plugin-sdk`'s overview has the route).
59
60
  - Skills in `.agents/skills/`: `endpoint` for a procedure, `schema-change` for a
60
61
  table or column, `ui-patterns` for any page (lists, filters, forms, record
61
62
  details look like core's), `verify` before calling a change done.__migrationSkill__
@@ -9,7 +9,5 @@ PLUGIN_SECRET=change-me-to-the-secret-in-core-plugin-keys
9
9
  PUBLIC_URL=http://localhost:__apiPort__
10
10
  # `pnpm dev:ui` serves the remote here; in the image the API serves it at /ui.
11
11
  UI_ENTRY_URL=http://localhost:__uiPort__/remoteEntry.js
12
- # web's address, which calls this API from the browser.
13
- CORE_UI_URL=http://localhost:3500
14
12
  # Traces go to an OTLP collector when this is set.
15
13
  # OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
@@ -7,7 +7,9 @@ Node 26 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`.
7
7
  (`PLUGINS_AUTO_INSTALL`).
8
8
  - `src/core.ts` holds the core client and the manifest. Every permission, event
9
9
  and kind in the manifest starts with `__id__.`. A new scope waits for the
10
- owner's approval, so ask for one only when a procedure needs it.
10
+ owner's approval, so ask for one only when a procedure needs it. Owners and
11
+ admins hold every permission; a permission set with `defaultRoles: ['member']`
12
+ is what members get on install, and owners change it from there.
11
13
  - `src/server.ts` verifies the session token on `/api/rpc/*` and hands
12
14
  procedures `context.member` (`PluginMember`: `orgId`, `userId`, `can()`,
13
15
  `canChange()`).
@@ -22,20 +24,36 @@ Node 26 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`.
22
24
  a flat payload, `entityType` (a type in the manifest's `timelines`) and
23
25
  `entityId`. It appears on the record's Activity tab, and on the customer's or
24
26
  company's too when it names `subjectType` and `subjectId`. A retried event
25
- adds nothing. `activities.create` is for entries that are not events.
27
+ adds nothing. `activities.create` is for entries that are not events. Tests
28
+ run on core's own `core_publish_event` (`src/test/core-calls.sql`): assert an
29
+ event by reading `core_events` in `withOrg`, and an audit entry in `core_audit_logs`.
26
30
  - Background work is a job in `src/jobs.ts`, which the manifest declares
27
- (`jobs`, with an optional `cron` in UTC and `retry`). Queue one inside the
31
+ (`jobs`, with an optional `cron` in UTC, `onInstall` and `retry`). Queue one inside the
28
32
  change that needs it, `enqueueJob(context.tx, { orgId, name, payload })` from
29
33
  `@erxes/plugin-sdk`, so it exists only if the change commits. Core POSTs it
30
34
  to `/api/jobs/<name>`, which `src/server.ts` checks with `verifyCoreJob`, and
31
35
  retries until it answers 2xx. A job may run twice: key its effect by `jobId`.
36
+ - An automation action is an entry in the manifest's `actions`; core POSTs
37
+ each run to `/api/automations/actions/<type>`, checked with `verifyCoreCall`.
38
+ A field that picks one of the plugin's records is
39
+ `{ key: 'pipelineId', label: 'Pipeline', type: 'plugin_record', recordType: 'pipeline' }`,
40
+ and `dependsOn: 'pipelineId'` on another narrows it to that pipeline's. Web
41
+ fills the list from `GET /api/automations/records/<recordType>?parent=<value>`,
42
+ sent with the member's session token like `/api/rpc/*`; answer
43
+ `[{ value, label }]` with the records that member may see. Never ask a member
44
+ to type an id. Name what the action answers in `outputs`
45
+ (`[{ key: 'dealId', label: 'Deal', type: 'text' }]`) and what an event's
46
+ payload holds in its `fields`: later steps insert them from "Insert data".
32
47
  - A fact the plugin computes about a customer or company (total spent, last
33
48
  order) is a field in the manifest's `fields` (`code`, `contentType`, `label`,
34
49
  `type`: number, date, text, select or multiselect). Core shows it read-only
35
50
  and members filter and save views by it. Write values with
36
51
  `core.forOrg(orgId).fields.setPluginValues({ contentType, values })` (scope
37
52
  `fields:write`, up to 500, `value: null` clears) after the change commits; it
38
- adds nothing to the timeline and sends no event.
53
+ adds nothing to the timeline and sends no event. Members see the fields only
54
+ while the plugin has `fields:write` there, so fill the values that existed
55
+ before in a job with `onInstall: true`: core runs it once when an
56
+ organisation installs the plugin or approves its new scopes.
39
57
  - A segment (a price list's audience, a campaign's) is a shared view members
40
58
  build in core. Store its id; `views.list({ recordType })` lists the shared
41
59
  ones and `views.matches({ viewId, recordIds })` says which records it
@@ -21,8 +21,8 @@
21
21
  "db:check": "drizzle-kit check"
22
22
  },
23
23
  "dependencies": {
24
- "@erxes/core-contract": "0.1.0-v2.8",
25
- "@erxes/plugin-sdk": "0.1.0-v2.7",
24
+ "@erxes/core-contract": "0.1.0-v2.11",
25
+ "@erxes/plugin-sdk": "0.1.0-v2.10",
26
26
  "@opentelemetry/instrumentation-express": "^0.73.0",
27
27
  "@opentelemetry/instrumentation-http": "^0.301.1",
28
28
  "@opentelemetry/instrumentation-pg": "^0.78.0",
@@ -1,5 +1,4 @@
1
1
  import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
2
- import { config } from '#/config.ts';
3
2
  import { createApp } from '#/server.ts';
4
3
 
5
4
  let base = '';
@@ -46,17 +45,18 @@ describe('server', () => {
46
45
  expect(response.status).toBe(401);
47
46
  });
48
47
 
49
- it('lets web call it from the browser', async () => {
48
+ it('lets web call it from any organisation address', async () => {
50
49
  const response = await fetch(`${base}/api/rpc/items/list`, {
51
50
  method: 'OPTIONS',
52
51
  headers: {
53
- origin: config.coreUiOrigin,
52
+ origin: 'https://acme.app.erxes.io',
54
53
  'access-control-request-method': 'POST',
55
54
  'access-control-request-headers': 'authorization,content-type',
56
55
  },
57
56
  });
58
57
 
59
- expect(response.headers.get('access-control-allow-origin')).toBe(config.coreUiOrigin);
58
+ expect(response.headers.get('access-control-allow-origin')).toBe('https://acme.app.erxes.io');
59
+ expect(response.headers.get('access-control-allow-credentials')).toBeNull();
60
60
  expect(response.headers.get('access-control-allow-headers')).toContain('authorization');
61
61
  });
62
62
  });
@@ -18,8 +18,6 @@ const Env = z.object({
18
18
  UI_ENTRY_URL: z.url().optional(),
19
19
  /** The built UI to serve at `/ui` (the image sets it). */
20
20
  UI_DIR: z.string().optional(),
21
- /** web's origin, which calls this API from the browser. Defaults to CORE_URL's origin. */
22
- CORE_UI_URL: z.url().optional(),
23
21
  LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),
24
22
  VERSION: z.string().default('0.1.0'),
25
23
  /** Traces go to this OTLP collector; the SDK reads the other OTEL_* variables itself. */
@@ -36,7 +34,6 @@ export const config = {
36
34
  publicUrl: env.PUBLIC_URL.replace(/\/+$/, ''),
37
35
  uiEntryUrl: env.UI_ENTRY_URL ?? `${env.PUBLIC_URL.replace(/\/+$/, '')}/ui/remoteEntry.js`,
38
36
  uiDir: env.UI_DIR,
39
- coreUiOrigin: new URL(env.CORE_UI_URL ?? env.CORE_URL).origin,
40
37
  logLevel: env.LOG_LEVEL,
41
38
  version: env.VERSION,
42
39
  tracing: Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT),
@@ -36,5 +36,15 @@ export const manifest = {
36
36
  { action: PERMISSIONS.view, label: 'View items', group: '__title__' },
37
37
  { action: PERMISSIONS.manage, label: 'Create and change items', group: '__title__' },
38
38
  ],
39
+ // Ready-made sets owners add to roles; core gives Members this one when the plugin is installed.
40
+ permissionSets: [
41
+ {
42
+ key: 'member',
43
+ label: '__title__ member',
44
+ description: 'Views, creates and changes items',
45
+ permissions: [PERMISSIONS.view, PERMISSIONS.manage],
46
+ defaultRoles: ['member'],
47
+ },
48
+ ],
39
49
  jobs: manifestJobs,
40
50
  } satisfies PluginManifest;
@@ -1,3 +1,9 @@
1
+ import {
2
+ compileFilter,
3
+ escapeLike,
4
+ type FilterFields,
5
+ FilterParam,
6
+ } from '@erxes/plugin-sdk/filter';
1
7
  import { type ORPCErrorConstructorMap, ORPCError } from '@orpc/server';
2
8
  import { and, desc, eq, getTableColumns, ilike, sql } from 'drizzle-orm';
3
9
  import { createSelectSchema } from 'drizzle-zod';
@@ -6,11 +12,19 @@ import { PERMISSIONS } from '#/core.ts';
6
12
  import { uniqueViolation } from '#/db/client.ts';
7
13
  import { ITEM_NAME_INDEX, items } from '#/db/schema.ts';
8
14
  import { reads, writes } from '#/orpc.ts';
9
- import { escapeLike, filterSql, ItemFilter } from './itemFilter.ts';
10
15
 
11
16
  /** What a procedure returns: the row without `org_id`, which the caller already knows. */
12
17
  const { orgId, ...columns } = getTableColumns(items);
13
18
 
19
+ /**
20
+ * What the list's filter bar can filter by: the paths and types of the UI's `ListFilter` fields
21
+ * (`ItemsPage.tsx`), with the column each compares. A rule on another path answers 400.
22
+ */
23
+ const FILTER_FIELDS = {
24
+ 'subject.name': { type: 'text', expr: items.name },
25
+ 'subject.createdBy': { type: 'member', expr: items.createdBy },
26
+ } satisfies FilterFields;
27
+
14
28
  const Name = z.string().trim().min(1).max(200);
15
29
  const Description = z.string().trim().max(5000);
16
30
 
@@ -47,7 +61,7 @@ const list = reads(PERMISSIONS.view)
47
61
  .input(
48
62
  z.object({
49
63
  search: z.string().trim().max(200).optional(),
50
- filter: ItemFilter.optional(),
64
+ filter: FilterParam.optional(),
51
65
  cursor: z.string().optional(),
52
66
  limit: z.number().int().min(1).max(100).default(50),
53
67
  }),
@@ -64,7 +78,7 @@ const list = reads(PERMISSIONS.view)
64
78
  .where(
65
79
  and(
66
80
  input.search ? ilike(items.name, `%${escapeLike(input.search)}%`) : undefined,
67
- input.filter ? filterSql(input.filter, member.userId) : undefined,
81
+ compileFilter(FILTER_FIELDS, input.filter, { me: member.userId }),
68
82
  after,
69
83
  ),
70
84
  )
@@ -31,8 +31,11 @@ export const createApp = () => {
31
31
 
32
32
  app.disable('x-powered-by');
33
33
  app.use(pinoHttp({ logger }));
34
- // The plugin UI runs inside web and calls this API from web's origin.
35
- app.use(cors({ origin: config.coreUiOrigin, maxAge: 600 }));
34
+ // The plugin UI calls this API from web, at whatever address the organisation
35
+ // uses (acme.app.erxes.io, its own domain). Any origin may: access is the
36
+ // Bearer session token core issues, never a cookie, so CORS guards nothing here.
37
+ // Routes for websites (an API key, customer tokens) set their own CORS.
38
+ app.use(['/api/rpc', '/ui'], cors({ origin: true, credentials: false, maxAge: 600 }));
36
39
 
37
40
  app.get('/health', (_req, res) => {
38
41
  res.json({ ok: true });
@@ -0,0 +1,167 @@
1
+ -- Core's functions a plugin calls in its own transactions (core_publish_event,
2
+ -- core_record_audit, core_live_signal), as erxes packages/db/drizzle defines
3
+ -- them, and the core tables they write. Tests install them, so a procedure that
4
+ -- publishes runs, and a test reads its events back from core_events.
5
+ CREATE OR REPLACE FUNCTION core_publish_event(
6
+ p_org_id text,
7
+ p_source text,
8
+ p_type text,
9
+ p_payload jsonb DEFAULT '{}'::jsonb,
10
+ p_subject_type text DEFAULT NULL,
11
+ p_subject_id text DEFAULT NULL,
12
+ p_summary text DEFAULT NULL,
13
+ p_link text DEFAULT NULL,
14
+ p_notify jsonb DEFAULT NULL,
15
+ p_dedupe_key text DEFAULT NULL,
16
+ p_actor_user_id text DEFAULT NULL,
17
+ p_entity_type text DEFAULT NULL,
18
+ p_entity_id text DEFAULT NULL,
19
+ p_occurred_at timestamptz DEFAULT NULL
20
+ ) RETURNS text
21
+ LANGUAGE plpgsql AS $$
22
+ DECLARE
23
+ v_id text;
24
+ BEGIN
25
+ IF p_type NOT LIKE p_source || '.%' THEN
26
+ RAISE EXCEPTION 'core_publish_event: the type must start with "%."', p_source;
27
+ END IF;
28
+ IF p_subject_type IS NOT NULL AND p_subject_type NOT IN ('customer', 'company') THEN
29
+ RAISE EXCEPTION 'core_publish_event: subject type must be customer or company';
30
+ END IF;
31
+ PERFORM core_enter_org(p_org_id, p_source);
32
+ INSERT INTO core_events (
33
+ id, org_id, source, type, payload, subject_type, subject_id, summary, link, notify, dedupe_key,
34
+ actor_type, actor_id, entity_type, entity_id, occurred_at
35
+ ) VALUES (
36
+ replace(gen_random_uuid()::text, '-', ''), p_org_id, p_source, p_type, coalesce(p_payload, '{}'::jsonb),
37
+ p_subject_type, p_subject_id, p_summary, p_link, p_notify, p_dedupe_key,
38
+ CASE WHEN p_actor_user_id IS NULL THEN 'plugin' ELSE 'user' END, coalesce(p_actor_user_id, p_source),
39
+ p_entity_type, p_entity_id, coalesce(p_occurred_at, now())
40
+ )
41
+ ON CONFLICT (org_id, source, dedupe_key) WHERE dedupe_key IS NOT NULL DO NOTHING
42
+ RETURNING id INTO v_id;
43
+ RETURN v_id;
44
+ END $$;
45
+ CREATE OR REPLACE FUNCTION core_record_audit(
46
+ p_org_id text,
47
+ p_source text,
48
+ p_action text,
49
+ p_actor_user_id text DEFAULT NULL,
50
+ p_target_type text DEFAULT NULL,
51
+ p_target_id text DEFAULT NULL,
52
+ p_target_label text DEFAULT NULL,
53
+ p_changes jsonb DEFAULT NULL,
54
+ p_metadata jsonb DEFAULT NULL,
55
+ p_ip text DEFAULT NULL,
56
+ p_user_agent text DEFAULT NULL
57
+ ) RETURNS text
58
+ LANGUAGE plpgsql AS $$
59
+ DECLARE
60
+ v_id text := replace(gen_random_uuid()::text, '-', '');
61
+ BEGIN
62
+ IF p_action NOT LIKE p_source || '.%' THEN
63
+ RAISE EXCEPTION 'core_record_audit: the action must start with "%."', p_source;
64
+ END IF;
65
+ PERFORM core_enter_org(p_org_id, p_source);
66
+ INSERT INTO core_audit_logs (
67
+ id, org_id, source, actor_type, actor_id, action, target_type, target_id, target_label, changes, metadata, ip, user_agent
68
+ ) VALUES (
69
+ v_id, p_org_id, p_source, CASE WHEN p_actor_user_id IS NULL THEN 'plugin' ELSE 'user' END,
70
+ coalesce(p_actor_user_id, p_source), p_action, p_target_type, p_target_id, p_target_label,
71
+ p_changes, p_metadata, p_ip, p_user_agent
72
+ );
73
+ RETURN v_id;
74
+ END $$;
75
+ CREATE OR REPLACE FUNCTION core_live_signal(p_org_id text, p_plugin text, p_topic text, p_user_ids text[] DEFAULT NULL)
76
+ RETURNS void LANGUAGE plpgsql AS $$
77
+ DECLARE
78
+ chunk text[];
79
+ total int := coalesce(array_length(p_user_ids, 1), 0);
80
+ i int := 1;
81
+ BEGIN
82
+ IF p_plugin !~ '^[a-z][a-z0-9_]{0,39}$' OR p_topic !~ '^[a-z0-9][a-z0-9._:-]{0,99}$' THEN
83
+ RAISE EXCEPTION 'core_live_signal: invalid plugin or topic';
84
+ END IF;
85
+ PERFORM core_enter_org(p_org_id, p_plugin);
86
+ IF total = 0 THEN
87
+ PERFORM pg_notify('core_live', json_build_object('o', p_org_id, 'k', 'plugin', 'p', p_plugin, 't', p_topic)::text);
88
+ RETURN;
89
+ END IF;
90
+ WHILE i <= total LOOP
91
+ chunk := p_user_ids[i:i + 99];
92
+ PERFORM pg_notify('core_live', json_build_object('o', p_org_id, 'k', 'plugin', 'p', p_plugin, 't', p_topic, 'u', chunk)::text);
93
+ i := i + 100;
94
+ END LOOP;
95
+ END $$;
96
+ CREATE OR REPLACE FUNCTION core_enter_org(p_org_id text, p_plugin text) RETURNS void
97
+ LANGUAGE plpgsql AS $$
98
+ DECLARE
99
+ v_current text := nullif(current_setting('app.org_id', true), '');
100
+ BEGIN
101
+ IF v_current IS NULL THEN
102
+ PERFORM set_config('app.org_id', p_org_id, true);
103
+ ELSIF v_current <> p_org_id THEN
104
+ RAISE EXCEPTION 'this transaction works for organisation %, not %', v_current, p_org_id;
105
+ END IF;
106
+ END $$;
107
+ CREATE TABLE "core_events" (
108
+ "id" text PRIMARY KEY NOT NULL,
109
+ "seq" bigserial NOT NULL,
110
+ "tx_id" "xid8" DEFAULT pg_current_xact_id() NOT NULL,
111
+ "org_id" text NOT NULL,
112
+ "source" text NOT NULL,
113
+ "type" text NOT NULL,
114
+ "version" integer DEFAULT 1 NOT NULL,
115
+ "subject_type" text,
116
+ "subject_id" text,
117
+ "entity_type" text,
118
+ "entity_id" text,
119
+ "actor_type" text NOT NULL,
120
+ "actor_id" text,
121
+ "payload" jsonb DEFAULT '{}'::jsonb NOT NULL,
122
+ "summary" text,
123
+ "link" text,
124
+ "notify" jsonb,
125
+ "dedupe_key" text,
126
+ "occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
127
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
128
+ );
129
+ CREATE UNIQUE INDEX "core_events_seq_key" ON "core_events" USING btree ("seq");
130
+ CREATE INDEX "core_events_commit_order_idx" ON "core_events" USING btree ("tx_id","seq");
131
+ CREATE INDEX "core_events_org_created_idx" ON "core_events" USING btree ("org_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);
132
+ CREATE INDEX "core_events_subject_idx" ON "core_events" USING btree ("org_id","subject_type","subject_id");
133
+ CREATE UNIQUE INDEX "core_events_dedupe_key" ON "core_events" USING btree ("org_id","source","dedupe_key") WHERE "core_events"."dedupe_key" IS NOT NULL;
134
+ ALTER TABLE "core_events" ADD COLUMN "caused_by_run" text;
135
+ ALTER TABLE "core_events" ADD COLUMN "depth" integer DEFAULT 0 NOT NULL;
136
+ ALTER TABLE "core_events" ALTER COLUMN "org_id" SET DEFAULT nullif(current_setting('app.org_id', true), '');
137
+ ALTER TABLE "core_events" DROP COLUMN "seq";
138
+ ALTER TABLE "core_events" DROP COLUMN "tx_id";
139
+ SELECT core_enable_tenant_rls('core_events');
140
+ GRANT SELECT, INSERT ON core_events TO PUBLIC;
141
+ CREATE TABLE "core_audit_logs" (
142
+ "id" text PRIMARY KEY NOT NULL,
143
+ "org_id" text NOT NULL,
144
+ "actor_type" text NOT NULL,
145
+ "actor_id" text,
146
+ "action" text NOT NULL,
147
+ "target_type" text,
148
+ "target_id" text,
149
+ "target_label" text,
150
+ "changes" jsonb,
151
+ "metadata" jsonb,
152
+ "ip" text,
153
+ "user_agent" text,
154
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
155
+ );
156
+ CREATE INDEX "core_audit_logs_org_created_idx" ON "core_audit_logs" USING btree ("org_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);
157
+ CREATE INDEX "core_audit_logs_target_idx" ON "core_audit_logs" USING btree ("org_id","target_type","target_id");
158
+ CREATE INDEX "core_audit_logs_actor_idx" ON "core_audit_logs" USING btree ("org_id","actor_id");
159
+ ALTER TABLE "core_audit_logs" ADD COLUMN "source" text DEFAULT 'core' NOT NULL;
160
+ ALTER TABLE "core_audit_logs" ADD COLUMN "chain_seq" bigint;
161
+ ALTER TABLE "core_audit_logs" ADD COLUMN "prev_hash" text;
162
+ ALTER TABLE "core_audit_logs" ADD COLUMN "hash" text;
163
+ CREATE INDEX "core_audit_logs_org_source_idx" ON "core_audit_logs" USING btree ("org_id","source","created_at" DESC NULLS LAST);
164
+ CREATE UNIQUE INDEX "core_audit_logs_chain_key" ON "core_audit_logs" USING btree ("org_id","chain_seq");
165
+ ALTER TABLE "core_audit_logs" ALTER COLUMN "org_id" SET DEFAULT nullif(current_setting('app.org_id', true), '');
166
+ SELECT core_enable_tenant_rls('core_audit_logs');
167
+ GRANT SELECT, INSERT ON core_audit_logs TO PUBLIC;
@@ -16,8 +16,11 @@ if (!adminUrl) {
16
16
  const ROLE = '__id___test';
17
17
  const database = `__id___test_${randomBytes(4).toString('hex')}`;
18
18
 
19
- // Core's tenant functions, which plugin migrations call.
20
- const CORE_FUNCTIONS = readFileSync(new URL('./core-functions.sql', import.meta.url), 'utf8');
19
+ // Core's tenant functions, which plugin migrations call, and the functions the plugin's code
20
+ // calls with the core tables they write: a test reads its events back from core_events.
21
+ const CORE_FUNCTIONS = ['./core-functions.sql', './core-calls.sql']
22
+ .map((file) => readFileSync(new URL(file, import.meta.url), 'utf8'))
23
+ .join('\n');
21
24
 
22
25
  const urlOf = (name: string, role?: string) => {
23
26
  const url = new URL(adminUrl);
@@ -41,9 +41,11 @@ and renders `./__id__` (the `__Pascal__` export) under `/__id__/*`.
41
41
  - Pages look and behave like core's: follow the `ui-patterns` skill.
42
42
  - Lists have core's bar (`src/modules/items/ItemsPage.tsx`): erxes-ui's `ViewBar` with
43
43
  `ListFilter`, given the list's fields and, for `member` fields, `members={memberQueries}`
44
- (a `tags` query for `tags` fields). It draws the bar itself, in erxes or on its own. Its conditions and search live in the
44
+ (a `tags` query for `tags` fields, `contacts={contactSearchQueries}` for `customer` and
45
+ `company` fields). It draws the bar itself, in erxes or on its own. Its conditions and search live in the
45
46
  address; `useListFilterParams()` hands them to the list's query, and the API
46
- applies them (`api/src/modules/items/itemFilter.ts`). No search boxes, toggle
47
+ applies them with `@erxes/plugin-sdk/filter`'s `compileFilter`, core's own compiler, on a map
48
+ of the same paths to columns (`FILTER_FIELDS` in `api/src/modules/items/items.ts`). No search boxes, toggle
47
49
  tabs or pickers in a row above the table. Give both the record type
48
50
  (`recordType={ITEM_TYPE}`): in erxes the bar then shows the member's saved
49
51
  views as tabs, and the filter offers to save one, as on core's customers.
@@ -51,12 +53,26 @@ and renders `./__id__` (the `__Pascal__` export) under `/__id__/*`.
51
53
  `CONFIG.recordTypes` (`src/config.tsx`) fills its slots, the item's `Title`,
52
54
  `Detail` and `New` (`src/modules/items/ItemPanel.tsx`). `useOpenRecord()`
53
55
  opens them, and `/__id__/:id` renders erxes-ui's `RecordPage` for the expanded
54
- record. A plugin's records of other records' customers are `relationTabs`
55
- (the `ui-patterns` skill). Forms are core's
56
+ record; its `listPath` is the list a deleted or closed record goes back to, when
57
+ that isn't the plugin's first page. A plugin's records of other records' customers are `relationTabs`
58
+ (the `ui-patterns` skill). A settings page is a route of the plugin's
59
+ (`/__id__/settings/<page>`) that `CONFIG.settings` lists (`{ path, label, icon }`):
60
+ core links it from its settings sidebar, under the plugin's name. Custom fields
61
+ on a record type are its `properties` (`type: '__id__.item'`, `values(id)`,
62
+ `save(id, patch)`): core keeps the fields and draws their settings page and the
63
+ Properties tab; the API keeps the values in a jsonb column and checks a patch
64
+ with core's `fields.check` before saving. Tiles for core's
65
+ home dashboard are `CONFIG.dashboardWidgets`: `name`, `title`, `icon`, `preview`,
66
+ `size` and a `lazy` `component`, which core draws as the tile's body under the
67
+ title. Forms are core's
56
68
  `PanelFormRow` rows with Cancel and Save at the bottom; nothing saves until
57
69
  Save. Dialogs are for confirmations, not forms.
70
+ - Something that must outlive a page, such as a softphone during a call, is
71
+ `CONFIG.floatingWidget`: one component core mounts once on every page and keeps
72
+ across navigation, in the bottom-right corner above the page. Load it lazily,
73
+ like the slots.
58
74
  - Text uses `t(key, 'English default')` from `react-i18next`. Core shows the config's words (the
59
- app's name, tab labels, section titles) in the member's language by looking them up in the
75
+ app's name, tab labels, section and widget titles) in the member's language by looking them up in the
60
76
  plugin's namespace, its `name`, with the English as the key. Add them from `src/config.tsx`
61
77
  with react-i18next's getI18n and i18next's addResourceBundle, so they are there before core
62
78
  draws them.
@@ -8,12 +8,12 @@
8
8
  "build": "rsbuild build"
9
9
  },
10
10
  "dependencies": {
11
- "@erxes/core-contract": "0.1.0-v2.8",
11
+ "@erxes/core-contract": "0.1.0-v2.11",
12
12
  "@orpc/client": "1.16.2",
13
13
  "@orpc/tanstack-query": "1.16.2",
14
14
  "@tabler/icons-react": "3.34.0",
15
15
  "@tanstack/react-query": "^5.107.1",
16
- "erxes-ui": "npm:@erxes/ui@4.0.0-v2.13",
16
+ "erxes-ui": "npm:@erxes/ui@4.0.0-v2.16",
17
17
  "jotai": "^3.0.2",
18
18
  "nuqs": "^2.10.3",
19
19
  "react": "19.3.1",
@@ -97,7 +97,7 @@ const columns: RecordTableColumnDef<Item>[] = [
97
97
 
98
98
  /**
99
99
  * The item list, newest first, under core's list bar: its one view, then the filter (`F`) on
100
- * the fields below, whose rules the API applies (`api/src/modules/items/itemFilter.ts`). Each
100
+ * the fields below, whose rules the API applies (`FILTER_FIELDS` in `api/src/modules/items/items.ts`). Each
101
101
  * item opens in core's side panel; Add opens a new one there.
102
102
  */
103
103
  export const ItemsPage = () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-erxes",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "private": false,
5
5
  "description": "Create an erxes plugin for the new core, or migrate an old erxes plugin onto it: pnpm create erxes",
6
6
  "license": "MIT",
@@ -1,61 +0,0 @@
1
- import { ConditionGroup, type ConditionRule } from '@erxes/core-contract';
2
- import { ORPCError } from '@orpc/server';
3
- import { and, ilike, inArray, or, type SQL } from 'drizzle-orm';
4
- import { z } from 'zod';
5
- import { items } from '#/db/schema.ts';
6
-
7
- export const escapeLike = (text: string) => text.replaceAll(/[\\%_]/g, '\\$&');
8
-
9
- /**
10
- * The list's filter bar (erxes-ui's `ListFilter`) sends core's condition group as JSON, its
11
- * rules on the fields the UI gives it: `subject.name` and `subject.createdBy`.
12
- */
13
- export const ItemFilter = z
14
- .string()
15
- .transform((text, context) => {
16
- try {
17
- const parsed: unknown = JSON.parse(text);
18
-
19
- return parsed;
20
- } catch {
21
- context.addIssue({ code: 'custom', message: 'filter is not JSON' });
22
-
23
- return z.NEVER;
24
- }
25
- })
26
- .pipe(ConditionGroup);
27
-
28
- const Values = z.array(z.string());
29
-
30
- /** One rule as SQL; `me` is the member asking. A rule the list has no field for is refused. */
31
- const ruleSql = (rule: ConditionRule, userId: string): SQL | undefined => {
32
- if (rule.path === 'subject.name' && rule.op === 'contains' && typeof rule.value === 'string') {
33
- return ilike(items.name, `%${escapeLike(rule.value)}%`);
34
- }
35
-
36
- const picked = Values.safeParse(rule.op === 'in' ? rule.value : [rule.value]);
37
-
38
- if (
39
- rule.path === 'subject.createdBy' &&
40
- (rule.op === 'in' || rule.op === 'eq') &&
41
- picked.success
42
- ) {
43
- return inArray(
44
- items.createdBy,
45
- picked.data.map((id) => (id === 'me' ? userId : id)),
46
- );
47
- }
48
-
49
- throw new ORPCError('BAD_REQUEST', {
50
- message: `Items can't be filtered by ${rule.path} ${rule.op}`,
51
- });
52
- };
53
-
54
- /** The filter's rules as SQL: all of them, or any (a group from the advanced filter). */
55
- export const filterSql = (group: ConditionGroup, userId: string): SQL | undefined => {
56
- const parts = group.rules.map((part) =>
57
- 'rules' in part ? filterSql(part, userId) : ruleSql(part, userId),
58
- );
59
-
60
- return group.match === 'any' ? or(...parts) : and(...parts);
61
- };