@erxes/core-contract 0.1.0-v2.0 → 0.1.0-v2.2

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 (102) hide show
  1. package/dist/activities.d.ts +1394 -139
  2. package/dist/activities.js +96 -40
  3. package/dist/audit.d.ts +1092 -48
  4. package/dist/audit.js +37 -23
  5. package/dist/auth.d.ts +2867 -61
  6. package/dist/auth.js +55 -25
  7. package/dist/automationRuns.d.ts +12 -13
  8. package/dist/automationRuns.js +15 -30
  9. package/dist/automations.d.ts +2474 -93
  10. package/dist/automations.js +56 -44
  11. package/dist/client.d.ts +30704 -0
  12. package/dist/client.js +62 -0
  13. package/dist/common.d.ts +28 -16
  14. package/dist/common.js +30 -22
  15. package/dist/companies.d.ts +1154 -44
  16. package/dist/companies.js +33 -17
  17. package/dist/contract/routes.json.js +1810 -0
  18. package/dist/customerAuth.d.ts +1661 -0
  19. package/dist/customerAuth.js +197 -0
  20. package/dist/customers.d.ts +1283 -65
  21. package/dist/customers.js +35 -25
  22. package/dist/{automationDefinition.d.ts → db/src/automationDefinition.d.ts} +4 -3
  23. package/dist/{automationDefinition.js → db/src/automationDefinition.js} +10 -32
  24. package/dist/db/src/enums.d.ts +8 -0
  25. package/dist/db/src/enums.js +334 -0
  26. package/dist/db/src/schema/auditStreams.js +6 -14
  27. package/dist/db/src/schema/authTokens.js +4 -6
  28. package/dist/db/src/schema/automations.d.ts +1 -0
  29. package/dist/db/src/schema/automations.js +15 -31
  30. package/dist/db/src/schema/common.d.ts +2 -6
  31. package/dist/db/src/schema/common.js +1 -24
  32. package/dist/db/src/schema/companies.js +6 -5
  33. package/dist/db/src/schema/customerAuth.js +101 -0
  34. package/dist/db/src/schema/customers.js +6 -6
  35. package/dist/db/src/schema/events.js +12 -60
  36. package/dist/db/src/schema/fieldValues.js +2 -2
  37. package/dist/db/src/schema/fields.js +10 -28
  38. package/dist/db/src/schema/index.d.ts +3 -0
  39. package/dist/db/src/schema/index.js +22 -20
  40. package/dist/db/src/schema/leadStages.js +5 -10
  41. package/dist/db/src/schema/leads.js +6 -11
  42. package/dist/db/src/schema/notes.js +92 -0
  43. package/dist/db/src/schema/oauth.js +3 -3
  44. package/dist/db/src/schema/payments.js +13 -23
  45. package/dist/db/src/schema/platform.js +11 -31
  46. package/dist/db/src/schema/plugins.js +10 -5
  47. package/dist/db/src/schema/products.js +7 -8
  48. package/dist/db/src/schema/rateLimits.js +7 -0
  49. package/dist/db/src/schema/saas.js +3 -9
  50. package/dist/db/src/schema/tags.js +6 -5
  51. package/dist/db/src/schema/transfer.js +13 -33
  52. package/dist/db/src/schema/trash.js +6 -7
  53. package/dist/db/src/schema/users.js +6 -10
  54. package/dist/db/src/schema/views.js +5 -13
  55. package/dist/db/src/schema/webhooks.js +7 -14
  56. package/dist/db/src/table.js +16 -2
  57. package/dist/errors.d.ts +516 -0
  58. package/dist/errors.js +218 -0
  59. package/dist/events.d.ts +585 -140
  60. package/dist/events.js +57 -42
  61. package/dist/fields.d.ts +1478 -66
  62. package/dist/fields.js +33 -47
  63. package/dist/files.d.ts +766 -62
  64. package/dist/files.js +34 -22
  65. package/dist/index.d.ts +25707 -902
  66. package/dist/index.js +22 -20
  67. package/dist/leads.d.ts +1108 -22
  68. package/dist/leads.js +39 -20
  69. package/dist/notifications.d.ts +691 -94
  70. package/dist/notifications.js +45 -91
  71. package/dist/organizations.d.ts +263 -5
  72. package/dist/organizations.js +21 -2
  73. package/dist/payments.d.ts +1794 -120
  74. package/dist/payments.js +58 -60
  75. package/dist/platform.d.ts +12 -20
  76. package/dist/platform.js +8 -21
  77. package/dist/plugins.d.ts +808 -71
  78. package/dist/plugins.js +66 -35
  79. package/dist/products.d.ts +1411 -53
  80. package/dist/products.js +40 -23
  81. package/dist/roles.d.ts +560 -8
  82. package/dist/roles.js +25 -11
  83. package/dist/routes.d.ts +8 -0
  84. package/dist/routes.js +13 -0
  85. package/dist/saas.d.ts +164 -8
  86. package/dist/saas.js +14 -29
  87. package/dist/tags.d.ts +344 -8
  88. package/dist/tags.js +16 -8
  89. package/dist/transfer.d.ts +1361 -36
  90. package/dist/transfer.js +47 -49
  91. package/dist/trash.d.ts +299 -23
  92. package/dist/trash.js +27 -20
  93. package/dist/users.d.ts +1233 -59
  94. package/dist/users.js +48 -39
  95. package/dist/values.d.ts +150 -0
  96. package/dist/values.js +139 -0
  97. package/dist/views.d.ts +404 -13
  98. package/dist/views.js +18 -28
  99. package/dist/webhooks.d.ts +791 -29
  100. package/dist/webhooks.js +36 -21
  101. package/package.json +9 -2
  102. package/dist/db/src/schema/jobs.js +0 -44
@@ -1,17 +1,16 @@
1
- import { pgTable } from "../table.js";
1
+ import { AUTH_TOKEN_PURPOSES } from "../enums.js";
2
+ import { inList, orgIdColumn, pgTable } from "../table.js";
2
3
  import { createdAt } from "./common.js";
3
4
  import { organizations } from "./organizations.js";
4
5
  import { check, foreignKey, index, text, timestamp } from "drizzle-orm/pg-core";
5
- import { sql } from "drizzle-orm";
6
6
  // ../db/src/schema/authTokens.ts
7
7
  const timestamptz = () => timestamp({
8
8
  withTimezone: true,
9
9
  mode: "date"
10
10
  });
11
- const AUTH_TOKEN_PURPOSES = ["invite", "password_reset"];
12
11
  pgTable("auth_tokens", {
13
12
  id: text().primaryKey(),
14
- orgId: text().notNull(),
13
+ orgId: orgIdColumn(),
15
14
  userId: text().notNull(),
16
15
  purpose: text({ enum: AUTH_TOKEN_PURPOSES }).notNull(),
17
16
  secretHash: text().notNull(),
@@ -20,11 +19,10 @@ pgTable("auth_tokens", {
20
19
  createdAt: createdAt()
21
20
  }, (table) => [
22
21
  index("core_auth_tokens_user_idx").on(table.orgId, table.userId, table.purpose),
23
- check("core_auth_tokens_purpose_check", sql`${table.purpose} IN ('invite', 'password_reset')`),
22
+ check("core_auth_tokens_purpose_check", inList(table.purpose, AUTH_TOKEN_PURPOSES)),
24
23
  foreignKey({
25
24
  columns: [table.orgId],
26
25
  foreignColumns: [organizations.id],
27
26
  name: "core_auth_tokens_org_id_fkey"
28
27
  }).onDelete("cascade")
29
28
  ]);
30
- export { AUTH_TOKEN_PURPOSES };
@@ -0,0 +1 @@
1
+ import "../automationDefinition.js";
@@ -1,5 +1,6 @@
1
- import { pgTable } from "../table.js";
2
- import { CONTENT_TYPES, createdAt, updatedAt } from "./common.js";
1
+ import { AUTOMATION_STATUSES, CONTENT_TYPES, FINISHED_RUN_STATUSES, RUN_STATUSES, RUN_STEP_STATUSES } from "../enums.js";
2
+ import { inList, orgIdColumn, pgTable } from "../table.js";
3
+ import { createdAt, updatedAt } from "./common.js";
3
4
  import { organizations } from "./organizations.js";
4
5
  import { check, foreignKey, index, integer, jsonb, primaryKey, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
5
6
  import { sql } from "drizzle-orm";
@@ -8,31 +9,14 @@ const timestamptz = () => timestamp({
8
9
  withTimezone: true,
9
10
  mode: "date"
10
11
  });
11
- const AUTOMATION_STATUSES = [
12
- "draft",
13
- "active",
14
- "paused"
15
- ];
16
- const RUN_STATUSES = [
17
- "running",
18
- "waiting",
19
- "succeeded",
20
- "failed",
21
- "cancelled"
22
- ];
23
- const RUN_STEP_STATUSES = [
24
- "succeeded",
25
- "failed",
26
- "skipped"
27
- ];
28
12
  /**
29
- * An automation: a trigger (event type + conditions) and steps, validated by
30
- * the contract's `AutomationDefinition`. `definition` is the working copy;
13
+ * An automation: a trigger (event type + conditions) and steps, in the shape of
14
+ * `AutomationDefinition` (`../automationDefinition`), which the contract checks on the way in. `definition` is the working copy;
31
15
  * activating publishes it as a numbered version runs start from.
32
16
  */
33
17
  const automations = pgTable("automations", {
34
18
  id: text().primaryKey(),
35
- orgId: text().notNull(),
19
+ orgId: orgIdColumn(),
36
20
  name: text().notNull(),
37
21
  description: text(),
38
22
  status: text({ enum: AUTOMATION_STATUSES }).default("draft").notNull(),
@@ -41,7 +25,7 @@ const automations = pgTable("automations", {
41
25
  triggerEvent: text().notNull(),
42
26
  /** Scheduled and date triggers: when the next tick is due. */
43
27
  nextRunAt: timestamptz(),
44
- /** Working state: round-robin positions, runs skipped by the hourly limit. */
28
+ /** Working state: round-robin positions per step, runs skipped by the hourly limit. */
45
29
  state: jsonb().$type().default({}).notNull(),
46
30
  activeVersion: integer(),
47
31
  /** The member it acts as: its actions need their permissions, checked at run time. */
@@ -53,7 +37,7 @@ const automations = pgTable("automations", {
53
37
  index("core_automations_trigger_idx").on(table.orgId, table.triggerEvent).where(sql`${table.status} = 'active'`),
54
38
  index("core_automations_due_idx").on(table.nextRunAt).where(sql`${table.status} = 'active'`),
55
39
  uniqueIndex("core_automations_org_id_id_key").on(table.orgId, table.id),
56
- check("core_automations_status_check", sql`${table.status} IN ('draft', 'active', 'paused')`),
40
+ check("core_automations_status_check", inList(table.status, AUTOMATION_STATUSES)),
57
41
  foreignKey({
58
42
  columns: [table.orgId],
59
43
  foreignColumns: [organizations.id],
@@ -61,7 +45,7 @@ const automations = pgTable("automations", {
61
45
  }).onDelete("cascade")
62
46
  ]);
63
47
  pgTable("automation_versions", {
64
- orgId: text().notNull(),
48
+ orgId: orgIdColumn(),
65
49
  automationId: text().notNull(),
66
50
  version: integer().notNull(),
67
51
  definition: jsonb().$type().notNull(),
@@ -78,7 +62,7 @@ pgTable("automation_versions", {
78
62
  /** One trip of a customer or company (or none) through an automation. */
79
63
  const automationRuns = pgTable("automation_runs", {
80
64
  id: text().primaryKey(),
81
- orgId: text().notNull(),
65
+ orgId: orgIdColumn(),
82
66
  automationId: text().notNull(),
83
67
  version: integer().notNull(),
84
68
  eventId: text().notNull(),
@@ -106,9 +90,9 @@ const automationRuns = pgTable("automation_runs", {
106
90
  index("core_automation_runs_automation_idx").on(table.orgId, table.automationId, table.startedAt.desc()),
107
91
  index("core_automation_runs_subject_idx").on(table.automationId, table.subjectId, table.startedAt.desc()),
108
92
  index("core_automation_runs_waiting_idx").on(table.orgId, table.subjectId).where(sql`${table.status} = 'waiting'`),
109
- index("core_automation_runs_prunable_idx").on(table.finishedAt).where(sql`${table.status} IN ('succeeded', 'failed', 'cancelled') AND ${table.context} <> '{}'::jsonb`),
93
+ index("core_automation_runs_prunable_idx").on(table.finishedAt).where(sql`${inList(table.status, FINISHED_RUN_STATUSES)} AND ${table.context} <> '{}'::jsonb`),
110
94
  uniqueIndex("core_automation_runs_org_id_id_key").on(table.orgId, table.id),
111
- check("core_automation_runs_status_check", sql`${table.status} IN ('running', 'waiting', 'succeeded', 'failed', 'cancelled')`),
95
+ check("core_automation_runs_status_check", inList(table.status, RUN_STATUSES)),
112
96
  foreignKey({
113
97
  columns: [table.orgId, table.automationId],
114
98
  foreignColumns: [automations.orgId, automations.id],
@@ -118,7 +102,7 @@ const automationRuns = pgTable("automation_runs", {
118
102
  /** What each step of a run did: input, output or error. */
119
103
  const automationRunSteps = pgTable("automation_run_steps", {
120
104
  id: text().primaryKey(),
121
- orgId: text().notNull(),
105
+ orgId: orgIdColumn(),
122
106
  runId: text().notNull(),
123
107
  stepId: text().notNull(),
124
108
  type: text().notNull(),
@@ -131,11 +115,11 @@ const automationRunSteps = pgTable("automation_run_steps", {
131
115
  finishedAt: timestamptz().defaultNow().notNull()
132
116
  }, (table) => [
133
117
  index("core_automation_run_steps_run_idx").on(table.runId, table.finishedAt),
134
- check("core_automation_run_steps_status_check", sql`${table.status} IN ('succeeded', 'failed', 'skipped')`),
118
+ check("core_automation_run_steps_status_check", inList(table.status, RUN_STEP_STATUSES)),
135
119
  foreignKey({
136
120
  columns: [table.orgId, table.runId],
137
121
  foreignColumns: [automationRuns.orgId, automationRuns.id],
138
122
  name: "core_automation_run_steps_run_fkey"
139
123
  }).onDelete("cascade")
140
124
  ]);
141
- export { AUTOMATION_STATUSES, RUN_STATUSES, RUN_STEP_STATUSES, automationRunSteps, automationRuns, automations };
125
+ export { automationRunSteps, automationRuns, automations };
@@ -1,8 +1,4 @@
1
- export declare const CONDITION_OPERATORS: readonly ['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'contains', 'not_contains', 'starts_with', 'in', 'not_in', 'exists', 'not_exists',
2
- /** Dates relative to now; the value is `{ amount, unit }` (days, weeks, months). */
3
- 'within_last', 'more_than_ago', 'within_next',
4
- /** The day and month fall within the next `amount` days (birthdays, anniversaries), whatever the year. */
5
- 'anniversary_within'];
1
+ import { CONDITION_MATCHES, CONDITION_OPERATORS } from "../enums.js";
6
2
  export type ConditionOperator = (typeof CONDITION_OPERATORS)[number];
7
3
  /** One rule of the condition language that view filters and automations store. */
8
4
  export interface ConditionRule {
@@ -13,6 +9,6 @@ export interface ConditionRule {
13
9
  }
14
10
  /** Rules (or nested groups) that must all, or any, hold. */
15
11
  export interface ConditionGroup {
16
- match: 'all' | 'any';
12
+ match: (typeof CONDITION_MATCHES)[number];
17
13
  rules: (ConditionRule | ConditionGroup)[];
18
14
  }
@@ -1,28 +1,5 @@
1
1
  import { timestamp } from "drizzle-orm/pg-core";
2
2
  // ../db/src/schema/common.ts
3
- /** Records that tags and custom fields attach to. */
4
- const CONTENT_TYPES = ["customer", "company"];
5
- /** Records custom fields attach to: contacts, and the shared product catalog. */
6
- const FIELD_CONTENT_TYPES = [...CONTENT_TYPES, "product"];
7
- const CONDITION_OPERATORS = [
8
- "eq",
9
- "neq",
10
- "gt",
11
- "gte",
12
- "lt",
13
- "lte",
14
- "contains",
15
- "not_contains",
16
- "starts_with",
17
- "in",
18
- "not_in",
19
- "exists",
20
- "not_exists",
21
- "within_last",
22
- "more_than_ago",
23
- "within_next",
24
- "anniversary_within"
25
- ];
26
3
  const createdAt = () => timestamp({
27
4
  withTimezone: true,
28
5
  mode: "date"
@@ -31,4 +8,4 @@ const updatedAt = () => timestamp({
31
8
  withTimezone: true,
32
9
  mode: "date"
33
10
  }).defaultNow().notNull();
34
- export { CONDITION_OPERATORS, CONTENT_TYPES, FIELD_CONTENT_TYPES, createdAt, updatedAt };
11
+ export { createdAt, updatedAt };
@@ -1,6 +1,7 @@
1
- import { pgTable } from "../table.js";
1
+ import { CUSTOMER_STATES } from "../enums.js";
2
+ import { inList, orgIdColumn, pgTable } from "../table.js";
2
3
  import { createdAt, updatedAt } from "./common.js";
3
- import { CUSTOMER_STATES, customers } from "./customers.js";
4
+ import { customers } from "./customers.js";
4
5
  import { leadStages } from "./leadStages.js";
5
6
  import { organizations } from "./organizations.js";
6
7
  import { users } from "./users.js";
@@ -10,7 +11,7 @@ import { sql } from "drizzle-orm";
10
11
  /** Organisations the organisation works with, shared by every plugin. */
11
12
  const companies = pgTable("companies", {
12
13
  id: text().primaryKey(),
13
- orgId: text().notNull(),
14
+ orgId: orgIdColumn(),
14
15
  primaryName: text().notNull(),
15
16
  /** `lead`: not a customer yet; companies go through the same lead stages as people. */
16
17
  state: text({ enum: CUSTOMER_STATES }).default("customer").notNull(),
@@ -66,7 +67,7 @@ const companies = pgTable("companies", {
66
67
  foreignColumns: [leadStages.id],
67
68
  name: "core_companies_lead_stage_id_fkey"
68
69
  }).onDelete("set null"),
69
- check("core_companies_state_check", sql`${table.state} IN ('lead', 'customer')`),
70
+ check("core_companies_state_check", inList(table.state, CUSTOMER_STATES)),
70
71
  index("core_companies_org_owner_idx").on(table.orgId, table.ownerId),
71
72
  index("core_companies_org_industry_idx").on(table.orgId, sql`lower(${table.industry})`),
72
73
  index("core_companies_search_trgm_idx").using("gin", table.searchText.op("gin_trgm_ops")),
@@ -88,7 +89,7 @@ const companies = pgTable("companies", {
88
89
  * and since when they are not there any more (the link stays, as history).
89
90
  */
90
91
  const customerCompanies = pgTable("customer_companies", {
91
- orgId: text().notNull(),
92
+ orgId: orgIdColumn(),
92
93
  customerId: text().notNull(),
93
94
  companyId: text().notNull(),
94
95
  /** "CEO", "Buyer", "Accountant" … */
@@ -0,0 +1,101 @@
1
+ import { CUSTOMER_CODE_PURPOSES, CUSTOMER_LOGIN_KINDS } from "../enums.js";
2
+ import { inList, orgIdColumn, pgTable } from "../table.js";
3
+ import { createdAt } from "./common.js";
4
+ import { customers } from "./customers.js";
5
+ import { organizations } from "./organizations.js";
6
+ import { check, foreignKey, index, integer, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
7
+ // ../db/src/schema/customerAuth.ts
8
+ const timestamptz = () => timestamp({
9
+ withTimezone: true,
10
+ mode: "date"
11
+ });
12
+ /**
13
+ * An email address or phone a customer proved with a code: they sign in with
14
+ * it. One per address in an organisation (decision 42).
15
+ */
16
+ const customerLogins = pgTable("customer_logins", {
17
+ id: text().primaryKey(),
18
+ orgId: orgIdColumn(),
19
+ customerId: text().notNull(),
20
+ kind: text({ enum: CUSTOMER_LOGIN_KINDS }).notNull(),
21
+ /** Normalised: lower-case email, phone without formatting. */
22
+ value: text().notNull(),
23
+ createdAt: createdAt(),
24
+ lastUsedAt: timestamptz()
25
+ }, (table) => [
26
+ uniqueIndex("core_customer_logins_org_kind_value_key").on(table.orgId, table.kind, table.value),
27
+ index("core_customer_logins_org_customer_idx").on(table.orgId, table.customerId),
28
+ foreignKey({
29
+ columns: [table.orgId],
30
+ foreignColumns: [organizations.id],
31
+ name: "core_customer_logins_org_id_fkey"
32
+ }).onDelete("cascade"),
33
+ foreignKey({
34
+ columns: [table.customerId],
35
+ foreignColumns: [customers.id],
36
+ name: "core_customer_logins_customer_id_fkey"
37
+ }).onDelete("cascade"),
38
+ check("core_customer_logins_kind_check", inList(table.kind, CUSTOMER_LOGIN_KINDS))
39
+ ]);
40
+ pgTable("customer_codes", {
41
+ id: text().primaryKey(),
42
+ orgId: orgIdColumn(),
43
+ kind: text({ enum: CUSTOMER_LOGIN_KINDS }).notNull(),
44
+ value: text().notNull(),
45
+ purpose: text({ enum: CUSTOMER_CODE_PURPOSES }).notNull(),
46
+ /** `add_login`: the signed-in customer the address will belong to. */
47
+ customerId: text(),
48
+ codeHash: text().notNull(),
49
+ attempts: integer().default(0).notNull(),
50
+ ip: text(),
51
+ expiresAt: timestamptz().notNull(),
52
+ usedAt: timestamptz(),
53
+ createdAt: createdAt()
54
+ }, (table) => [
55
+ index("core_customer_codes_org_address_idx").on(table.orgId, table.kind, table.value, table.createdAt.desc()),
56
+ foreignKey({
57
+ columns: [table.orgId],
58
+ foreignColumns: [organizations.id],
59
+ name: "core_customer_codes_org_id_fkey"
60
+ }).onDelete("cascade"),
61
+ foreignKey({
62
+ columns: [table.customerId],
63
+ foreignColumns: [customers.id],
64
+ name: "core_customer_codes_customer_id_fkey"
65
+ }).onDelete("cascade"),
66
+ check("core_customer_codes_kind_check", inList(table.kind, CUSTOMER_LOGIN_KINDS)),
67
+ check("core_customer_codes_purpose_check", inList(table.purpose, CUSTOMER_CODE_PURPOSES))
68
+ ]);
69
+ /**
70
+ * A customer signed in to a plugin's app, held as a refresh token. The token
71
+ * rotates on every use; the previous one is kept, so using it again (it
72
+ * leaked) ends the session.
73
+ */
74
+ const customerSessions = pgTable("customer_sessions", {
75
+ id: text().primaryKey(),
76
+ orgId: orgIdColumn(),
77
+ customerId: text().notNull(),
78
+ /** The plugin whose app holds it. */
79
+ clientId: text().notNull(),
80
+ tokenHash: text().notNull(),
81
+ previousTokenHash: text(),
82
+ userAgent: text(),
83
+ ip: text(),
84
+ createdAt: createdAt(),
85
+ lastUsedAt: timestamptz().defaultNow().notNull(),
86
+ expiresAt: timestamptz().notNull(),
87
+ revokedAt: timestamptz()
88
+ }, (table) => [
89
+ index("core_customer_sessions_org_customer_idx").on(table.orgId, table.customerId),
90
+ foreignKey({
91
+ columns: [table.orgId],
92
+ foreignColumns: [organizations.id],
93
+ name: "core_customer_sessions_org_id_fkey"
94
+ }).onDelete("cascade"),
95
+ foreignKey({
96
+ columns: [table.customerId],
97
+ foreignColumns: [customers.id],
98
+ name: "core_customer_sessions_customer_id_fkey"
99
+ }).onDelete("cascade")
100
+ ]);
101
+ export { customerLogins, customerSessions };
@@ -1,15 +1,15 @@
1
- import { pgTable } from "../table.js";
1
+ import { CUSTOMER_SEXES, CUSTOMER_STATES } from "../enums.js";
2
+ import { inList, orgIdColumn, pgTable } from "../table.js";
2
3
  import { leadStages } from "./leadStages.js";
3
4
  import { organizations } from "./organizations.js";
4
5
  import { users } from "./users.js";
5
6
  import { check, date, foreignKey, index, jsonb, smallint, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
6
7
  import { sql } from "drizzle-orm";
7
8
  // ../db/src/schema/customers.ts
8
- const CUSTOMER_STATES = ["lead", "customer"];
9
9
  /** People the organisation works with, shared by every plugin. */
10
10
  const customers = pgTable("customers", {
11
11
  id: text().primaryKey(),
12
- orgId: text().notNull(),
12
+ orgId: orgIdColumn(),
13
13
  state: text({ enum: CUSTOMER_STATES }).default("customer").notNull(),
14
14
  firstName: text(),
15
15
  middleName: text(),
@@ -101,7 +101,7 @@ const customers = pgTable("customers", {
101
101
  foreignColumns: [users.id],
102
102
  name: "core_customers_owner_id_fkey"
103
103
  }).onDelete("set null"),
104
- check("core_customers_state_check", sql`${table.state} IN ('lead', 'customer')`),
105
- check("core_customers_sex_check", sql`${table.sex} IN (0, 1, 2, 9)`)
104
+ check("core_customers_state_check", inList(table.state, CUSTOMER_STATES)),
105
+ check("core_customers_sex_check", inList(table.sex, CUSTOMER_SEXES))
106
106
  ]);
107
- export { CUSTOMER_STATES, customers };
107
+ export { customers };
@@ -1,30 +1,25 @@
1
- import { pgTable } from "../table.js";
2
- import { CONTENT_TYPES, createdAt, updatedAt } from "./common.js";
1
+ import { ACTOR_TYPES, CONTENT_TYPES } from "../enums.js";
2
+ import { orgIdColumn, pgTable } from "../table.js";
3
+ import { createdAt } from "./common.js";
3
4
  import { organizations } from "./organizations.js";
4
- import { ACTOR_TYPES } from "./platform.js";
5
- import { bigint, bigserial, customType, foreignKey, index, integer, jsonb, primaryKey, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
5
+ import { foreignKey, index, integer, jsonb, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
6
6
  import { sql } from "drizzle-orm";
7
7
  // ../db/src/schema/events.ts
8
8
  const timestamptz = () => timestamp({
9
9
  withTimezone: true,
10
10
  mode: "date"
11
11
  });
12
- /** Postgres `xid8`: the id of the transaction that wrote a row. */
13
- const xid8 = customType({ dataType: () => "xid8" });
14
12
  /**
15
- * Every domain event, from core and plugins: the transactional outbox.
16
- * Written in the same transaction as the change (`core_publish_event()` for
17
- * plugins on this database, `POST /events` otherwise), so an event exists if
18
- * and only if its change was committed. Consumers read in commit order
19
- * (`tx_id`, `seq`) and turn events into timeline entries, notifications,
20
- * automation runs and webhooks.
13
+ * Every domain event, from core and plugins. Written in the same transaction
14
+ * as the change (`core_publish_event()` for plugins on this database,
15
+ * `POST /events` otherwise), so an event exists if and only if its change was
16
+ * committed. The insert trigger queues one job per consumer in that
17
+ * transaction too (`modules/events/consumers.ts`): timeline entries,
18
+ * notifications, automation runs, webhooks and plugin deliveries.
21
19
  */
22
20
  const events = pgTable("events", {
23
21
  id: text().primaryKey(),
24
- seq: bigserial({ mode: "number" }).notNull(),
25
- /** Transaction that wrote it: consumers only read finished transactions. */
26
- txId: xid8().default(sql`pg_current_xact_id()`).notNull(),
27
- orgId: text().notNull(),
22
+ orgId: orgIdColumn(),
28
23
  /** `core` or the plugin that published it. */
29
24
  source: text().notNull(),
30
25
  /** Namespaced by source: `core.customer.created`, `hr.leave.approved`. */
@@ -50,8 +45,6 @@ const events = pgTable("events", {
50
45
  depth: integer().default(0).notNull(),
51
46
  createdAt: createdAt()
52
47
  }, (table) => [
53
- uniqueIndex("core_events_seq_key").on(table.seq),
54
- index("core_events_commit_order_idx").on(table.txId, table.seq),
55
48
  index("core_events_org_created_idx").on(table.orgId, table.createdAt.desc(), table.id.desc()),
56
49
  index("core_events_subject_idx").on(table.orgId, table.subjectType, table.subjectId),
57
50
  uniqueIndex("core_events_dedupe_key").on(table.orgId, table.source, table.dedupeKey).where(sql`${table.dedupeKey} IS NOT NULL`),
@@ -61,45 +54,4 @@ const events = pgTable("events", {
61
54
  name: "core_events_org_id_fkey"
62
55
  }).onDelete("cascade")
63
56
  ]);
64
- pgTable("event_consumers", {
65
- name: text().primaryKey(),
66
- lastTxId: xid8().default(sql`'0'::xid8`).notNull(),
67
- lastSeq: bigint({ mode: "number" }).default(0).notNull(),
68
- updatedAt: updatedAt()
69
- });
70
- const EVENT_FAILURE_STATUSES = ["retrying", "dead"];
71
- /**
72
- * Events a consumer could not handle. The consumer's cursor moves on (one bad
73
- * event never blocks the stream); the event is retried here with backoff and,
74
- * after the last attempt, kept as `dead` until someone retries it by hand.
75
- */
76
- const eventFailures = pgTable("event_failures", {
77
- consumer: text().notNull(),
78
- eventId: text().notNull(),
79
- orgId: text().notNull(),
80
- status: text({ enum: EVENT_FAILURE_STATUSES }).default("retrying").notNull(),
81
- attempts: integer().default(1).notNull(),
82
- lastError: text().notNull(),
83
- /** When to try again; null once dead. */
84
- nextAttemptAt: timestamptz(),
85
- firstFailedAt: timestamptz().defaultNow().notNull(),
86
- updatedAt: updatedAt()
87
- }, (table) => [
88
- primaryKey({
89
- columns: [table.consumer, table.eventId],
90
- name: "core_event_failures_pkey"
91
- }),
92
- index("core_event_failures_due_idx").on(table.nextAttemptAt).where(sql`${table.status} = 'retrying'`),
93
- index("core_event_failures_org_idx").on(table.orgId, table.updatedAt.desc()),
94
- foreignKey({
95
- columns: [table.eventId],
96
- foreignColumns: [events.id],
97
- name: "core_event_failures_event_id_fkey"
98
- }).onDelete("cascade"),
99
- foreignKey({
100
- columns: [table.orgId],
101
- foreignColumns: [organizations.id],
102
- name: "core_event_failures_org_id_fkey"
103
- }).onDelete("cascade")
104
- ]);
105
- export { EVENT_FAILURE_STATUSES, eventFailures, events };
57
+ export { events };
@@ -1,4 +1,4 @@
1
- import { pgTable } from "../table.js";
1
+ import { orgIdColumn, pgTable } from "../table.js";
2
2
  import { companies } from "./companies.js";
3
3
  import { customers } from "./customers.js";
4
4
  import { fields } from "./fields.js";
@@ -24,7 +24,7 @@ const fieldValues = (name) => {
24
24
  const records = RECORDS[name];
25
25
  const t = `core_${name}`;
26
26
  return pgTable(name, {
27
- orgId: text().notNull(),
27
+ orgId: orgIdColumn(),
28
28
  recordId: text().notNull(),
29
29
  fieldId: text().notNull(),
30
30
  position: smallint().default(0).notNull(),
@@ -1,35 +1,17 @@
1
- import { pgTable } from "../table.js";
2
- import { FIELD_CONTENT_TYPES, createdAt, updatedAt } from "./common.js";
1
+ import { FIELD_CONTENT_TYPES, FIELD_TYPES, FIELD_VALIDATIONS } from "../enums.js";
2
+ import { inList, orgIdColumn, pgTable } from "../table.js";
3
+ import { createdAt, updatedAt } from "./common.js";
3
4
  import { organizations } from "./organizations.js";
4
5
  import { boolean, check, foreignKey, index, integer, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
5
6
  import { sql } from "drizzle-orm";
6
7
  // ../db/src/schema/fields.ts
7
- const FIELD_TYPES = [
8
- "text",
9
- "textarea",
10
- "number",
11
- "date",
12
- "boolean",
13
- "select",
14
- "multiselect",
15
- "radio",
16
- "check",
17
- "phone",
18
- "list"
19
- ];
20
- /** Formats a text field's values must have. */
21
- const FIELD_VALIDATIONS = [
22
- "number",
23
- "email",
24
- "date"
25
- ];
26
8
  /**
27
9
  * Groups that properties of a record type are organised in (old erxes field
28
10
  * groups). Archiving a group hides it and its fields; values stay.
29
11
  */
30
12
  const fieldGroups = pgTable("field_groups", {
31
13
  id: text().primaryKey(),
32
- orgId: text().notNull(),
14
+ orgId: orgIdColumn(),
33
15
  contentType: text({ enum: FIELD_CONTENT_TYPES }).notNull(),
34
16
  name: text().notNull(),
35
17
  code: text().notNull(),
@@ -49,7 +31,7 @@ const fieldGroups = pgTable("field_groups", {
49
31
  foreignColumns: [organizations.id],
50
32
  name: "core_field_groups_org_id_fkey"
51
33
  }).onDelete("cascade"),
52
- check("core_field_groups_content_type_check", sql`${table.contentType} IN ('customer', 'company', 'product')`)
34
+ check("core_field_groups_content_type_check", inList(table.contentType, FIELD_CONTENT_TYPES))
53
35
  ]);
54
36
  /**
55
37
  * Custom fields ("properties") an organisation adds to customers, companies
@@ -57,7 +39,7 @@ const fieldGroups = pgTable("field_groups", {
57
39
  */
58
40
  const fields = pgTable("fields", {
59
41
  id: text().primaryKey(),
60
- orgId: text().notNull(),
42
+ orgId: orgIdColumn(),
61
43
  contentType: text({ enum: FIELD_CONTENT_TYPES }).notNull(),
62
44
  /** The group it is listed in; fields made before groups have none. */
63
45
  groupId: text(),
@@ -96,8 +78,8 @@ const fields = pgTable("fields", {
96
78
  foreignColumns: [fieldGroups.id],
97
79
  name: "core_fields_group_id_fkey"
98
80
  }).onDelete("set null"),
99
- check("core_fields_content_type_check", sql`${table.contentType} IN ('customer', 'company', 'product')`),
100
- check("core_fields_type_check", sql`${table.type} IN ('text', 'textarea', 'number', 'date', 'boolean', 'select', 'multiselect', 'radio', 'check', 'phone', 'list')`),
101
- check("core_fields_validation_check", sql`${table.validation} IS NULL OR ${table.validation} IN ('number', 'email', 'date')`)
81
+ check("core_fields_content_type_check", inList(table.contentType, FIELD_CONTENT_TYPES)),
82
+ check("core_fields_type_check", inList(table.type, FIELD_TYPES)),
83
+ check("core_fields_validation_check", sql`${table.validation} IS NULL OR ${inList(table.validation, FIELD_VALIDATIONS)}`)
102
84
  ]);
103
- export { FIELD_TYPES, FIELD_VALIDATIONS, fieldGroups, fields };
85
+ export { fieldGroups, fields };
@@ -0,0 +1,3 @@
1
+ import { ConditionGroup, ConditionOperator, ConditionRule } from "./common.js";
2
+ import "./automations.js";
3
+ export { ConditionGroup, ConditionOperator, ConditionRule };
@@ -1,26 +1,28 @@
1
- import { CONDITION_OPERATORS, CONTENT_TYPES, FIELD_CONTENT_TYPES, createdAt, updatedAt } from "./common.js";
1
+ import { createdAt, updatedAt } from "./common.js";
2
2
  import { companies, customerCompanies } from "./companies.js";
3
- import { CUSTOMER_STATES, customers } from "./customers.js";
4
- import { FIELD_TYPES, FIELD_VALIDATIONS, fieldGroups, fields } from "./fields.js";
3
+ import { customers } from "./customers.js";
4
+ import { fieldGroups, fields } from "./fields.js";
5
5
  import { organizations } from "./organizations.js";
6
6
  import { tags } from "./tags.js";
7
- import { USER_STATUSES, roles, users } from "./users.js";
8
- import { ACTOR_TYPES, FILE_STATUSES, NOTIFICATION_PRIORITIES, activities, auditLogs, files, notifications } from "./platform.js";
9
- import { EVENT_FAILURE_STATUSES, eventFailures, events } from "./events.js";
10
- import { PLUGIN_STATUSES, plugins } from "./plugins.js";
11
- import { JOB_STATUSES } from "./jobs.js";
12
- import { WEBHOOK_DELIVERY_STATUSES, WEBHOOK_STATUSES, webhookDeliveries, webhooks } from "./webhooks.js";
13
- import { AUTOMATION_STATUSES, RUN_STATUSES, RUN_STEP_STATUSES, automationRunSteps, automationRuns, automations } from "./automations.js";
14
- import { AUTH_TOKEN_PURPOSES } from "./authTokens.js";
7
+ import { roles, users } from "./users.js";
8
+ import { activities, auditLogs, files, notifications } from "./platform.js";
9
+ import { noteVersions, notes } from "./notes.js";
10
+ import { events } from "./events.js";
11
+ import { pluginInstallations, plugins } from "./plugins.js";
12
+ import { webhookDeliveries, webhooks } from "./webhooks.js";
13
+ import { automationRunSteps, automationRuns, automations } from "./automations.js";
14
+ import "./authTokens.js";
15
15
  import "./oauth.js";
16
- import { INVOICE_STATUSES, PAYMENT_GATEWAY_KINDS, REFUND_METHODS, REFUND_STATUSES, paymentGateways, paymentInvoices, paymentPluginSettings, paymentRefunds } from "./payments.js";
16
+ import { paymentGateways, paymentInvoices, paymentPluginSettings, paymentRefunds } from "./payments.js";
17
17
  import { trash } from "./trash.js";
18
- import { AUDIT_STREAM_FORMATS, AUDIT_STREAM_STATUSES, auditStreams } from "./auditStreams.js";
19
- import { ORGANIZATION_STATUSES } from "./saas.js";
20
- import { VIEW_RECORD_TYPES, views } from "./views.js";
21
- import { EXPORT_STATUSES, IMPORT_STATUSES, TRANSFER_RECORD_TYPES, exports, importRows, imports } from "./transfer.js";
18
+ import { auditStreams } from "./auditStreams.js";
19
+ import "./saas.js";
20
+ import { views } from "./views.js";
21
+ import { exports, importRows, imports } from "./transfer.js";
22
22
  import "./fieldValues.js";
23
- import { LEAD_STAGE_KINDS, leadStages } from "./leadStages.js";
24
- import { LEAD_EVENTS, leadEvents } from "./leads.js";
25
- import { PRODUCT_KINDS, PRODUCT_STATUSES, productCategories, products } from "./products.js";
26
- export { ACTOR_TYPES, AUDIT_STREAM_FORMATS, AUDIT_STREAM_STATUSES, AUTH_TOKEN_PURPOSES, AUTOMATION_STATUSES, CONDITION_OPERATORS, CONTENT_TYPES, CUSTOMER_STATES, EVENT_FAILURE_STATUSES, EXPORT_STATUSES, FIELD_CONTENT_TYPES, FIELD_TYPES, FIELD_VALIDATIONS, FILE_STATUSES, IMPORT_STATUSES, INVOICE_STATUSES, JOB_STATUSES, LEAD_EVENTS, LEAD_STAGE_KINDS, NOTIFICATION_PRIORITIES, ORGANIZATION_STATUSES, PAYMENT_GATEWAY_KINDS, PLUGIN_STATUSES, PRODUCT_KINDS, PRODUCT_STATUSES, REFUND_METHODS, REFUND_STATUSES, RUN_STATUSES, RUN_STEP_STATUSES, TRANSFER_RECORD_TYPES, USER_STATUSES, VIEW_RECORD_TYPES, WEBHOOK_DELIVERY_STATUSES, WEBHOOK_STATUSES, activities, auditLogs, auditStreams, automationRunSteps, automationRuns, automations, companies, createdAt, customerCompanies, customers, eventFailures, events, exports, fieldGroups, fields, files, importRows, imports, leadEvents, leadStages, notifications, organizations, paymentGateways, paymentInvoices, paymentPluginSettings, paymentRefunds, plugins, productCategories, products, roles, tags, trash, updatedAt, users, views, webhookDeliveries, webhooks };
23
+ import { leadStages } from "./leadStages.js";
24
+ import { leadEvents } from "./leads.js";
25
+ import { productCategories, products } from "./products.js";
26
+ import { customerLogins, customerSessions } from "./customerAuth.js";
27
+ import "./rateLimits.js";
28
+ export { activities, auditLogs, auditStreams, automationRunSteps, automationRuns, automations, companies, createdAt, customerCompanies, customerLogins, customerSessions, customers, events, exports, fieldGroups, fields, files, importRows, imports, leadEvents, leadStages, noteVersions, notes, notifications, organizations, paymentGateways, paymentInvoices, paymentPluginSettings, paymentRefunds, pluginInstallations, plugins, productCategories, products, roles, tags, trash, updatedAt, users, views, webhookDeliveries, webhooks };
@@ -1,22 +1,17 @@
1
- import { pgTable } from "../table.js";
1
+ import { LEAD_STAGE_KINDS } from "../enums.js";
2
+ import { inList, orgIdColumn, pgTable } from "../table.js";
2
3
  import { createdAt, updatedAt } from "./common.js";
3
4
  import { organizations } from "./organizations.js";
4
5
  import { check, foreignKey, index, integer, text, uniqueIndex } from "drizzle-orm/pg-core";
5
6
  import { sql } from "drizzle-orm";
6
7
  // ../db/src/schema/leadStages.ts
7
- /** `open`: still being worked; `qualified`: ready to become a customer; `disqualified`: not a fit (lost). */
8
- const LEAD_STAGE_KINDS = [
9
- "open",
10
- "qualified",
11
- "disqualified"
12
- ];
13
8
  /**
14
9
  * The stages a lead moves through, the organisation's own (New → Contacted →
15
10
  * Qualified …), in order. Every organisation starts with a default set.
16
11
  */
17
12
  const leadStages = pgTable("lead_stages", {
18
13
  id: text().primaryKey(),
19
- orgId: text().notNull(),
14
+ orgId: orgIdColumn(),
20
15
  name: text().notNull(),
21
16
  kind: text({ enum: LEAD_STAGE_KINDS }).default("open").notNull(),
22
17
  /** `#rrggbb` */
@@ -32,6 +27,6 @@ const leadStages = pgTable("lead_stages", {
32
27
  foreignColumns: [organizations.id],
33
28
  name: "core_lead_stages_org_id_fkey"
34
29
  }).onDelete("cascade"),
35
- check("core_lead_stages_kind_check", sql`${table.kind} IN ('open', 'qualified', 'disqualified')`)
30
+ check("core_lead_stages_kind_check", inList(table.kind, LEAD_STAGE_KINDS))
36
31
  ]);
37
- export { LEAD_STAGE_KINDS, leadStages };
32
+ export { leadStages };