create-erxes 0.1.8 → 0.1.10

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.8";
12
+ var version = "0.1.10";
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 = [
@@ -96,13 +96,14 @@ gives it its fields, and `api/src/modules/items/itemFilter.ts` applies them.
96
96
  draft with `openNew(contentType, defaults)`. `detailPath(id)` is a route of
97
97
  the plugin's that renders `<RecordPage contentType contentId />`
98
98
  (`ui/src/__Pascal__.tsx`): the expanded record.
99
- - A plugin whose records belong to customers or companies lists them on other
100
- records with `CONFIG.relationTabs`: `{ name, title, icon, hosts?, component }`.
101
- The component gets the host record and its `customerIds` and `companyIds`;
102
- a record clicked there opens with `useOpenRecord().open` on top in the same
103
- panel, and Back returns. It shows on core's customers and companies and on
104
- plugin records that give `contacts`, never on the plugin's own records
105
- unless `hosts` names them.
99
+ - A plugin whose records belong to customers or companies lists them on those
100
+ customers' and companies' panels with `CONFIG.relationTabs`:
101
+ `{ name, title, icon, hosts?, component }`. The component gets the host record
102
+ and its `customerIds` and `companyIds`; a record clicked there opens with
103
+ `useOpenRecord().open` on top in the same panel, and Back returns. Another
104
+ plugin's record (an order, a task) shows the tab only when `hosts` names its
105
+ type and the type gives `contacts`: name it only when a member working on that
106
+ record needs the list, never by default.
106
107
 
107
108
  ## Forms
108
109
 
@@ -112,6 +113,9 @@ gives it its fields, and `api/src/modules/items/itemFilter.ts` applies them.
112
113
  and Save at the bottom. Nothing saves until Save; a field's error shows
113
114
  under that field. Call `onCreated(id)` after Save, and the record takes the
114
115
  draft's place.
116
+ - `PanelFormRow` takes `htmlFor` (the control's id, so the label focuses it
117
+ and toggles a switch) and `hint` (a line under the control). Long labels wrap
118
+ to two lines; never draw a row of your own with `grid-cols-field`.
115
119
  - A form gets its own page only when it has several sections or a live
116
120
  preview (a product editor, a page builder). That page is laid out like a
117
121
  settings page (below), not with the side panel's rows: cards with a title
@@ -23,6 +23,23 @@ Node 26 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`.
23
23
  `entityId`. It appears on the record's Activity tab, and on the customer's or
24
24
  company's too when it names `subjectType` and `subjectId`. A retried event
25
25
  adds nothing. `activities.create` is for entries that are not events.
26
+ - 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
28
+ change that needs it, `enqueueJob(context.tx, { orgId, name, payload })` from
29
+ `@erxes/plugin-sdk`, so it exists only if the change commits. Core POSTs it
30
+ to `/api/jobs/<name>`, which `src/server.ts` checks with `verifyCoreJob`, and
31
+ retries until it answers 2xx. A job may run twice: key its effect by `jobId`.
32
+ - A fact the plugin computes about a customer or company (total spent, last
33
+ order) is a field in the manifest's `fields` (`code`, `contentType`, `label`,
34
+ `type`: number, date, text, select or multiselect). Core shows it read-only
35
+ and members filter and save views by it. Write values with
36
+ `core.forOrg(orgId).fields.setPluginValues({ contentType, values })` (scope
37
+ `fields:write`, up to 500, `value: null` clears) after the change commits; it
38
+ adds nothing to the timeline and sends no event.
39
+ - A segment (a price list's audience, a campaign's) is a shared view members
40
+ build in core. Store its id; `views.list({ recordType })` lists the shared
41
+ ones and `views.matches({ viewId, recordIds })` says which records it
42
+ matches now (scope `views:read`, up to 500 ids).
26
43
  - Tests: `vite-plus/test`, run with `call(procedure, input, { context: { member } })`.
27
44
  `src/test/setup.ts` gives each file its own database, owned by a role without
28
45
  BYPASSRLS, so row-level security is real in tests.
@@ -21,8 +21,8 @@
21
21
  "db:check": "drizzle-kit check"
22
22
  },
23
23
  "dependencies": {
24
- "@erxes/core-contract": "0.1.0-v2.6",
25
- "@erxes/plugin-sdk": "0.1.0-v2.5",
24
+ "@erxes/core-contract": "0.1.0-v2.8",
25
+ "@erxes/plugin-sdk": "0.1.0-v2.7",
26
26
  "@opentelemetry/instrumentation-express": "^0.73.0",
27
27
  "@opentelemetry/instrumentation-http": "^0.301.1",
28
28
  "@opentelemetry/instrumentation-pg": "^0.78.0",
@@ -35,6 +35,17 @@ describe('server', () => {
35
35
  ).toBe(401);
36
36
  });
37
37
 
38
+ it("refuses a job without core's token", async () => {
39
+ const job = { jobId: 'j1', orgId: 'o1', name: 'items.count', attempt: 1, payload: {} };
40
+
41
+ const response = await fetch(`${base}/api/jobs/items.count`, {
42
+ method: 'POST',
43
+ body: JSON.stringify(job),
44
+ });
45
+
46
+ expect(response.status).toBe(401);
47
+ });
48
+
38
49
  it('lets web call it from the browser', async () => {
39
50
  const response = await fetch(`${base}/api/rpc/items/list`, {
40
51
  method: 'OPTIONS',
@@ -1,6 +1,7 @@
1
1
  import type { PluginManifest } from '@erxes/core-contract';
2
2
  import { createCoreClient } from '@erxes/plugin-sdk';
3
3
  import { config, PLUGIN } from '#/config.ts';
4
+ import { manifestJobs } from '#/jobs.ts';
4
5
 
5
6
  /**
6
7
  * Core, called as this plugin: `core.forOrg(orgId).customers.get({ id })`.
@@ -20,8 +21,9 @@ export const PERMISSIONS = {
20
21
  } as const;
21
22
 
22
23
  /**
23
- * What the plugin adds to core, sent on every start. Everything it names
24
- * starts with `__id__.`. A new scope waits for the owner's approval.
24
+ * What the plugin adds to core, sent on every start. Every permission,
25
+ * event and kind it names starts with `__id__.`; job names are its own.
26
+ * A new scope waits for the owner's approval.
25
27
  */
26
28
  export const manifest = {
27
29
  title: '__title__',
@@ -34,4 +36,5 @@ export const manifest = {
34
36
  { action: PERMISSIONS.view, label: 'View items', group: '__title__' },
35
37
  { action: PERMISSIONS.manage, label: 'Create and change items', group: '__title__' },
36
38
  ],
39
+ jobs: manifestJobs,
37
40
  } satisfies PluginManifest;
@@ -0,0 +1,40 @@
1
+ import type { PluginJobDelivery } from '@erxes/core-contract';
2
+ import { withOrg } from '#/db/client.ts';
3
+ import { items } from '#/db/schema.ts';
4
+ import { logger } from '#/logger.ts';
5
+
6
+ interface Job {
7
+ /** A cron schedule in UTC: core runs the job for each organisation that has the plugin. */
8
+ cron?: string;
9
+ /** Throws to retry. A job can run more than once, so make it safe to repeat. */
10
+ run: (job: PluginJobDelivery) => Promise<void>;
11
+ }
12
+
13
+ /**
14
+ * The plugin's jobs, by name. Core POSTs each to `/api/jobs/<name>` and
15
+ * retries until it answers 2xx. Queue one in a procedure's transaction:
16
+ * `await enqueueJob(context.tx, { orgId, name: 'items.count', payload: {} })`.
17
+ */
18
+ const JOBS: Record<string, Job> = {
19
+ 'items.count': {
20
+ cron: '0 3 * * *',
21
+ run: async (job) => {
22
+ const count = await withOrg(job.orgId, (tx) => tx.$count(items));
23
+
24
+ logger.info({ orgId: job.orgId, count }, 'items counted');
25
+ },
26
+ },
27
+ };
28
+
29
+ /** The manifest's `jobs`. */
30
+ export const manifestJobs = Object.entries(JOBS).map(([name, { cron }]) =>
31
+ cron ? { name, cron } : { name },
32
+ );
33
+
34
+ export const runJob = async (job: PluginJobDelivery) => {
35
+ const found = JOBS[job.name];
36
+
37
+ if (!found) throw new Error(`No job ${job.name}`);
38
+
39
+ await found.run(job);
40
+ };
@@ -1,10 +1,11 @@
1
- import { bearerOf, verifyPluginSession } from '@erxes/plugin-sdk';
1
+ import { bearerOf, verifyCoreJob, verifyPluginSession } from '@erxes/plugin-sdk';
2
2
  import { onError, ORPCError } from '@orpc/server';
3
3
  import { RPCHandler } from '@orpc/server/node';
4
4
  import cors from 'cors';
5
5
  import express from 'express';
6
6
  import { pinoHttp } from 'pino-http';
7
7
  import { config, PLUGIN } from '#/config.ts';
8
+ import { runJob } from '#/jobs.ts';
8
9
  import { logger } from '#/logger.ts';
9
10
  import { router } from '#/router.ts';
10
11
 
@@ -52,6 +53,26 @@ export const createApp = () => {
52
53
  if (!matched) next();
53
54
  });
54
55
 
56
+ // Core's jobs (`api/src/jobs.ts`). The token signs the raw body, so it stays text.
57
+ app.post('/api/jobs/:name', express.text({ type: '*/*' }), async (req, res) => {
58
+ const body = typeof req.body === 'string' ? req.body : '';
59
+
60
+ const job = await verifyCoreJob(req.headers.authorization, body, {
61
+ coreUrl: config.coreUrl,
62
+ plugin: PLUGIN,
63
+ }).catch(() => null);
64
+
65
+ if (!job) {
66
+ res.sendStatus(401);
67
+
68
+ return;
69
+ }
70
+
71
+ // A throw answers 500 and core retries it.
72
+ await runJob(job);
73
+ res.sendStatus(204);
74
+ });
75
+
55
76
  if (config.uiDir) app.use('/ui', express.static(config.uiDir));
56
77
 
57
78
  return app;
@@ -20,7 +20,8 @@
20
20
  -- checks: its tables have no row level security, a job carries its
21
21
  -- organisation in its data, and failed jobs are read by the scope's
22
22
  -- organisation. So no plugin role and not PUBLIC may use it; plugins queue
23
- -- work through core_events and its insert trigger.
23
+ -- work through core_events and its insert trigger, and their own jobs
24
+ -- through core_enqueue_job().
24
25
  create temp table no_org_id (table_name text primary key, tenant_key text, reason text not null);
25
26
  insert into no_org_id values (format('__drizzle_migrations_%s', :'scope'), null, 'The migration log.');
26
27
  \ir no-org-id.sql
@@ -24,7 +24,10 @@ and renders `./__id__` (the `__Pascal__` export) under `/__id__/*`.
24
24
  - The plugin's API goes through `src/orpc.ts`:
25
25
  `useQuery(orpc.items.list.queryOptions(...))`,
26
26
  `useMutation(orpc.items.create.mutationOptions(...))`. Types come from
27
- `api/src/router.ts`; after a mutation, invalidate `orpc.<group>.key()`.
27
+ `api/src/router.ts`; after a mutation, invalidate `orpc.<group>.key()`. Its query
28
+ keys start with the plugin's name, because every plugin shares web's query cache:
29
+ without it, two plugins' `me` procedures answer each other. A key written by hand
30
+ starts with `PLUGIN` too.
28
31
  - Core's API goes through `orpc` from `@erxes/core-contract/client`, the client
29
32
  web uses, with the member's own session; import it as `core` beside the
30
33
  plugin's `orpc`: `useQuery(core.users.get.queryOptions({ input: { id } }))`.
@@ -41,7 +44,9 @@ and renders `./__id__` (the `__Pascal__` export) under `/__id__/*`.
41
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
42
45
  address; `useListFilterParams()` hands them to the list's query, and the API
43
46
  applies them (`api/src/modules/items/itemFilter.ts`). No search boxes, toggle
44
- tabs or pickers in a row above the table.
47
+ tabs or pickers in a row above the table. Give both the record type
48
+ (`recordType={ITEM_TYPE}`): in erxes the bar then shows the member's saved
49
+ views as tabs, and the filter offers to save one, as on core's customers.
45
50
  - Records open in core's side panel, like a customer: core draws the panel and
46
51
  `CONFIG.recordTypes` (`src/config.tsx`) fills its slots, the item's `Title`,
47
52
  `Detail` and `New` (`src/modules/items/ItemPanel.tsx`). `useOpenRecord()`
@@ -50,7 +55,16 @@ and renders `./__id__` (the `__Pascal__` export) under `/__id__/*`.
50
55
  (the `ui-patterns` skill). Forms are core's
51
56
  `PanelFormRow` rows with Cancel and Save at the bottom; nothing saves until
52
57
  Save. Dialogs are for confirmations, not forms.
53
- - Text uses `t(key, 'English default')` from `react-i18next`.
58
+ - 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
60
+ plugin's namespace, its `name`, with the English as the key. Add them from `src/config.tsx`
61
+ with react-i18next's getI18n and i18next's addResourceBundle, so they are there before core
62
+ draws them.
63
+ - To pick a segment (a shared customer or company view), list
64
+ `orpc.views.list({ recordType: 'customer' })` and offer only the ones with
65
+ `shared: true`: the member's own views are in the answer too, and the API's
66
+ `views.matches` refuses them. The fields the manifest declares need no UI:
67
+ core shows them on records, in columns and in the filter.
54
68
  - Development: `pnpm dev:ui` serves `http://localhost:__uiPort__/remoteEntry.js`;
55
69
  web loads it from the manifest's `UI_ENTRY_URL` or from its own
56
70
  `PUBLIC_PLUGINS=__id___ui@http://localhost:__uiPort__/remoteEntry.js`.
@@ -8,12 +8,12 @@
8
8
  "build": "rsbuild build"
9
9
  },
10
10
  "dependencies": {
11
- "@erxes/core-contract": "0.1.0-v2.6",
11
+ "@erxes/core-contract": "0.1.0-v2.8",
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.10",
16
+ "erxes-ui": "npm:@erxes/ui@4.0.0-v2.13",
17
17
  "jotai": "^3.0.2",
18
18
  "nuqs": "^2.10.3",
19
19
  "react": "19.3.1",
@@ -125,9 +125,10 @@ export const ItemsPage = () => {
125
125
  </Button>
126
126
  </PageHeader.End>
127
127
  </PageHeader>
128
- <ViewBar allLabel={t('all-items', 'All items')}>
128
+ <ViewBar recordType={ITEM_TYPE} allLabel={t('all-items', 'All items')}>
129
129
  <ListFilter
130
130
  id="__id__-items"
131
+ recordType={ITEM_TYPE}
131
132
  fields={fields}
132
133
  members={memberQueries}
133
134
  totalCount={isPending ? undefined : list.length}
@@ -28,5 +28,9 @@ const link = new RPCLink({
28
28
  /** The API, typed from api/src/router.ts: `await client.items.list({})`. */
29
29
  const client: Client = createORPCClient(link);
30
30
 
31
- /** TanStack Query options per procedure: `useQuery(orpc.items.list.queryOptions({ input }))`. */
32
- export const orpc = createTanstackQueryUtils(client);
31
+ /**
32
+ * TanStack Query options per procedure: `useQuery(orpc.items.list.queryOptions({ input }))`.
33
+ * Keys start with the plugin name: plugins share web's query cache, so another plugin's `me`
34
+ * or `list` never answers this one's.
35
+ */
36
+ export const orpc = createTanstackQueryUtils(client, { path: [PLUGIN] });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-erxes",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
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",