adula 0.0.0 → 2.0.0
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/LICENSE.md +10 -0
- package/README.md +38 -2
- package/build/agent/AGENTS.template.md +28 -0
- package/build/agent/capabilities.md +60 -0
- package/build/agent/skills/adula-frontend-design/SKILL.md +59 -0
- package/build/agent/skills/idea-review/SKILL.md +31 -0
- package/build/agent/skills/module-review/SKILL.md +22 -0
- package/build/agent/skills/perf-review/SKILL.md +24 -0
- package/build/agent/skills/schema-review/SKILL.md +22 -0
- package/build/agent/skills/security-review/SKILL.md +24 -0
- package/build/agent/skills/ui-review/SKILL.md +22 -0
- package/build/commands/capabilities.d.ts +10 -0
- package/build/commands/capabilities.js +40 -0
- package/build/commands/doctor.d.ts +9 -0
- package/build/commands/doctor.js +72 -0
- package/build/commands/gaps.d.ts +12 -0
- package/build/commands/gaps.js +62 -0
- package/build/commands/install.d.ts +9 -0
- package/build/commands/install.js +105 -0
- package/build/commands/main.d.ts +8 -0
- package/build/commands/main.js +33 -0
- package/build/commands/module_add.d.ts +8 -0
- package/build/commands/module_add.js +57 -0
- package/build/commands/module_remove.d.ts +10 -0
- package/build/commands/module_remove.js +94 -0
- package/build/commands/resource.d.ts +8 -0
- package/build/commands/resource.js +29 -0
- package/build/commands/resource_snapshot.d.ts +15 -0
- package/build/commands/resource_snapshot.js +61 -0
- package/build/commands/storage_migrate.d.ts +12 -0
- package/build/commands/storage_migrate.js +39 -0
- package/build/commands/ui.d.ts +11 -0
- package/build/commands/ui.js +210 -0
- package/build/commands/upgrade.d.ts +15 -0
- package/build/commands/upgrade.js +34 -0
- package/build/configure.d.ts +2 -0
- package/build/configure.js +79 -0
- package/build/database/migrations/1770000000000_core.d.ts +5 -0
- package/build/database/migrations/1770000000000_core.js +10 -0
- package/build/database/migrations/1770000000001_attachments.d.ts +5 -0
- package/build/database/migrations/1770000000001_attachments.js +10 -0
- package/build/database/migrations/1770000000002_saved_views.d.ts +5 -0
- package/build/database/migrations/1770000000002_saved_views.js +10 -0
- package/build/database/migrations/1770000000003_user_invitations.d.ts +5 -0
- package/build/database/migrations/1770000000003_user_invitations.js +18 -0
- package/build/database/migrations/1770000000004_collaboration.d.ts +5 -0
- package/build/database/migrations/1770000000004_collaboration.js +10 -0
- package/build/database/migrations/1770000000005_assignments.d.ts +5 -0
- package/build/database/migrations/1770000000005_assignments.js +10 -0
- package/build/database/migrations/1770000000006_messaging.d.ts +5 -0
- package/build/database/migrations/1770000000006_messaging.js +10 -0
- package/build/database/migrations/1770000000007_webhooks.d.ts +5 -0
- package/build/database/migrations/1770000000007_webhooks.js +10 -0
- package/build/database/migrations/1770000000008_imports.d.ts +5 -0
- package/build/database/migrations/1770000000008_imports.js +10 -0
- package/build/database/migrations/1770000000010_workflows.d.ts +5 -0
- package/build/database/migrations/1770000000010_workflows.js +10 -0
- package/build/database/migrations/1770000000011_managed_assignments.d.ts +5 -0
- package/build/database/migrations/1770000000011_managed_assignments.js +10 -0
- package/build/database/migrations/1770000000012_role_keys.d.ts +5 -0
- package/build/database/migrations/1770000000012_role_keys.js +10 -0
- package/build/database/migrations/1770000000013_notification_targets.d.ts +5 -0
- package/build/database/migrations/1770000000013_notification_targets.js +10 -0
- package/build/database/migrations/1770000000014_upload_grants.d.ts +5 -0
- package/build/database/migrations/1770000000014_upload_grants.js +10 -0
- package/build/database/migrations/1770000000015_inbound_webhooks.d.ts +5 -0
- package/build/database/migrations/1770000000015_inbound_webhooks.js +10 -0
- package/build/database/migrations/1770000000016_adulajs_names.d.ts +6 -0
- package/build/database/migrations/1770000000016_adulajs_names.js +11 -0
- package/build/index.d.ts +80 -0
- package/build/index.js +49 -0
- package/build/providers/adula_provider.d.ts +6 -0
- package/build/providers/adula_provider.js +10 -0
- package/build/src/admin/contracts.d.ts +19 -0
- package/build/src/admin/contracts.js +115 -0
- package/build/src/admin/controller.d.ts +32 -0
- package/build/src/admin/controller.js +167 -0
- package/build/src/admin/errors.d.ts +5 -0
- package/build/src/admin/errors.js +9 -0
- package/build/src/admin/presentation.d.ts +28 -0
- package/build/src/admin/presentation.js +1 -0
- package/build/src/admin/record_title.d.ts +14 -0
- package/build/src/admin/record_title.js +50 -0
- package/build/src/admin/resource_service.d.ts +376 -0
- package/build/src/admin/resource_service.js +1448 -0
- package/build/src/attachments/attachment_service.d.ts +100 -0
- package/build/src/attachments/attachment_service.js +270 -0
- package/build/src/attachments/doctor.d.ts +4 -0
- package/build/src/attachments/doctor.js +28 -0
- package/build/src/attachments/storage_migrate.d.ts +39 -0
- package/build/src/attachments/storage_migrate.js +64 -0
- package/build/src/attachments/upload_grants.d.ts +44 -0
- package/build/src/attachments/upload_grants.js +105 -0
- package/build/src/auth/ability.d.ts +24 -0
- package/build/src/auth/ability.js +34 -0
- package/build/src/auth/actor_store.d.ts +14 -0
- package/build/src/auth/actor_store.js +70 -0
- package/build/src/auth/conditions.d.ts +26 -0
- package/build/src/auth/conditions.js +117 -0
- package/build/src/auth/packed_rules.d.ts +4 -0
- package/build/src/auth/packed_rules.js +13 -0
- package/build/src/auth/sql.d.ts +11 -0
- package/build/src/auth/sql.js +118 -0
- package/build/src/collaboration/assignments.d.ts +129 -0
- package/build/src/collaboration/assignments.js +333 -0
- package/build/src/collaboration/record_collaboration.d.ts +86 -0
- package/build/src/collaboration/record_collaboration.js +348 -0
- package/build/src/commands/agent_assets.d.ts +7 -0
- package/build/src/commands/agent_assets.js +66 -0
- package/build/src/commands/capabilities.d.ts +19 -0
- package/build/src/commands/capabilities.js +179 -0
- package/build/src/commands/doctor.d.ts +42 -0
- package/build/src/commands/doctor.js +375 -0
- package/build/src/commands/gap_report.d.ts +56 -0
- package/build/src/commands/gap_report.js +110 -0
- package/build/src/commands/generator.d.ts +1 -0
- package/build/src/commands/generator.js +70 -0
- package/build/src/commands/snapshot.d.ts +28 -0
- package/build/src/commands/snapshot.js +48 -0
- package/build/src/commands/source_markers.d.ts +11 -0
- package/build/src/commands/source_markers.js +41 -0
- package/build/src/core/activity.d.ts +43 -0
- package/build/src/core/activity.js +77 -0
- package/build/src/core/administration_guard.d.ts +3 -0
- package/build/src/core/administration_guard.js +39 -0
- package/build/src/core/health.d.ts +42 -0
- package/build/src/core/health.js +44 -0
- package/build/src/core/mail_test.d.ts +18 -0
- package/build/src/core/mail_test.js +88 -0
- package/build/src/core/message_templates.d.ts +83 -0
- package/build/src/core/message_templates.js +293 -0
- package/build/src/core/module_seed.d.ts +15 -0
- package/build/src/core/module_seed.js +31 -0
- package/build/src/core/notifications.d.ts +42 -0
- package/build/src/core/notifications.js +91 -0
- package/build/src/core/org_units.d.ts +30 -0
- package/build/src/core/org_units.js +123 -0
- package/build/src/core/roles.d.ts +98 -0
- package/build/src/core/roles.js +447 -0
- package/build/src/core/saved_views.d.ts +37 -0
- package/build/src/core/saved_views.js +164 -0
- package/build/src/core/settings.d.ts +29 -0
- package/build/src/core/settings.js +113 -0
- package/build/src/core/setup.d.ts +14 -0
- package/build/src/core/setup.js +89 -0
- package/build/src/core/ui_preferences.d.ts +12 -0
- package/build/src/core/ui_preferences.js +30 -0
- package/build/src/core/user_invitations.d.ts +23 -0
- package/build/src/core/user_invitations.js +144 -0
- package/build/src/core/users.d.ts +44 -0
- package/build/src/core/users.js +182 -0
- package/build/src/database/configure.d.ts +3 -0
- package/build/src/database/configure.js +41 -0
- package/build/src/database/schema.d.ts +52 -0
- package/build/src/database/schema.js +538 -0
- package/build/src/eslint/index.d.ts +3 -0
- package/build/src/eslint/index.js +90 -0
- package/build/src/events/adonis_jobs.d.ts +9 -0
- package/build/src/events/adonis_jobs.js +13 -0
- package/build/src/events/outbox.d.ts +19 -0
- package/build/src/events/outbox.js +33 -0
- package/build/src/events/record_mutation.d.ts +24 -0
- package/build/src/events/record_mutation.js +62 -0
- package/build/src/integrations/imports.d.ts +74 -0
- package/build/src/integrations/imports.js +333 -0
- package/build/src/integrations/inbound_webhooks.d.ts +94 -0
- package/build/src/integrations/inbound_webhooks.js +276 -0
- package/build/src/integrations/openapi.d.ts +39 -0
- package/build/src/integrations/openapi.js +323 -0
- package/build/src/integrations/print.d.ts +37 -0
- package/build/src/integrations/print.js +124 -0
- package/build/src/integrations/webhooks.d.ts +98 -0
- package/build/src/integrations/webhooks.js +298 -0
- package/build/src/mcp/tools.d.ts +8 -0
- package/build/src/mcp/tools.js +156 -0
- package/build/src/org/org_service.d.ts +2 -0
- package/build/src/org/org_service.js +16 -0
- package/build/src/resource/define_resource.d.ts +5 -0
- package/build/src/resource/define_resource.js +68 -0
- package/build/src/resource/registry.d.ts +12 -0
- package/build/src/resource/registry.js +101 -0
- package/build/src/resource/types.d.ts +155 -0
- package/build/src/resource/types.js +1 -0
- package/build/src/resource/values.d.ts +5 -0
- package/build/src/resource/values.js +88 -0
- package/build/src/services/backup.d.ts +14 -0
- package/build/src/services/backup.js +59 -0
- package/build/src/services/settings.d.ts +21 -0
- package/build/src/services/settings.js +30 -0
- package/build/src/upgrade/legacy.d.ts +27 -0
- package/build/src/upgrade/legacy.js +58 -0
- package/build/src/upgrade/rename.d.ts +17 -0
- package/build/src/upgrade/rename.js +94 -0
- package/build/src/version.d.ts +1 -0
- package/build/src/version.js +2 -0
- package/build/src/workflows/define_workflow.d.ts +124 -0
- package/build/src/workflows/define_workflow.js +123 -0
- package/build/src/workflows/engine.d.ts +141 -0
- package/build/src/workflows/engine.js +752 -0
- package/build/stubs/README.md +6 -0
- package/build/stubs/controller.stub +8 -0
- package/build/stubs/main.d.ts +5 -0
- package/build/stubs/main.js +5 -0
- package/build/stubs/main.ts +5 -0
- package/build/stubs/modules.stub +6 -0
- package/build/stubs/resource_contract.stub +1 -0
- package/build/stubs/resource_contract.txt +452 -0
- package/build/stubs/routes.stub +16 -0
- package/build/stubs/service.stub +9 -0
- package/package.json +95 -6
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { AdulaError } from '../admin/errors.js';
|
|
2
|
+
import { targetColumns } from '../services/settings.js';
|
|
3
|
+
/**
|
|
4
|
+
* Package-owned defaults. Projects edit wording in the message_templates table;
|
|
5
|
+
* an upgrade can change a default without overwriting a project's edit.
|
|
6
|
+
*/
|
|
7
|
+
export const DEFAULT_TEMPLATES = {
|
|
8
|
+
'comment.mentioned': {
|
|
9
|
+
label: 'إشارة في تعليق',
|
|
10
|
+
subject: 'أشار إليك {{author}}',
|
|
11
|
+
body: 'في {{resource}} #{{id}}: {{excerpt}}',
|
|
12
|
+
variables: ['author', 'resource', 'id', 'excerpt'],
|
|
13
|
+
mail: true,
|
|
14
|
+
},
|
|
15
|
+
'comment.created': {
|
|
16
|
+
label: 'تعليق على سجل تتابعه',
|
|
17
|
+
subject: 'تعليق جديد على {{resource}} #{{id}}',
|
|
18
|
+
body: '{{author}}: {{excerpt}}',
|
|
19
|
+
variables: ['author', 'resource', 'id', 'excerpt'],
|
|
20
|
+
mail: false,
|
|
21
|
+
},
|
|
22
|
+
'record.changed': {
|
|
23
|
+
label: 'تغيير سجل تتابعه',
|
|
24
|
+
subject: '{{change}} {{resource}} #{{id}}',
|
|
25
|
+
body: 'سجل تتابعه تغيّر.',
|
|
26
|
+
variables: ['change', 'resource', 'id'],
|
|
27
|
+
mail: false,
|
|
28
|
+
},
|
|
29
|
+
'assignment.created': {
|
|
30
|
+
label: 'مهمة جديدة',
|
|
31
|
+
subject: 'مهمة جديدة مسندة إليك',
|
|
32
|
+
body: '{{title}} — {{resource}} #{{id}}',
|
|
33
|
+
variables: ['title', 'resource', 'id', 'due'],
|
|
34
|
+
mail: true,
|
|
35
|
+
},
|
|
36
|
+
'assignment.approval': {
|
|
37
|
+
label: 'طلب موافقة',
|
|
38
|
+
subject: 'موافقة مطلوبة منك',
|
|
39
|
+
body: '{{title}} — {{resource}} #{{id}}',
|
|
40
|
+
variables: ['title', 'resource', 'id', 'due'],
|
|
41
|
+
mail: true,
|
|
42
|
+
},
|
|
43
|
+
'assignment.done': {
|
|
44
|
+
label: 'إنجاز مهمة أسندتها',
|
|
45
|
+
subject: 'أُنجزت مهمة أسندتها',
|
|
46
|
+
body: '{{title}} — {{resource}} #{{id}}',
|
|
47
|
+
variables: ['title', 'resource', 'id'],
|
|
48
|
+
mail: false,
|
|
49
|
+
},
|
|
50
|
+
'assignment.cancelled': {
|
|
51
|
+
label: 'إلغاء مهمة مسندة إليك',
|
|
52
|
+
subject: 'أُلغيت مهمة مسندة إليك',
|
|
53
|
+
body: '{{title}} — {{resource}} #{{id}}',
|
|
54
|
+
variables: ['title', 'resource', 'id'],
|
|
55
|
+
mail: false,
|
|
56
|
+
},
|
|
57
|
+
'workflow.decided': {
|
|
58
|
+
label: 'نتيجة تدفق عمل',
|
|
59
|
+
subject: '{{outcome}}: {{resource}} #{{id}}',
|
|
60
|
+
body: '{{workflow}} — {{step}}',
|
|
61
|
+
variables: ['outcome', 'resource', 'id', 'workflow', 'step'],
|
|
62
|
+
mail: true,
|
|
63
|
+
},
|
|
64
|
+
'workflow.failed': {
|
|
65
|
+
label: 'فشل خطوة تدفق',
|
|
66
|
+
subject: 'فشلت خطوة في تدفق {{workflow}}',
|
|
67
|
+
body: '{{resource}} #{{id}} — {{error}}',
|
|
68
|
+
variables: ['workflow', 'resource', 'id', 'error'],
|
|
69
|
+
mail: true,
|
|
70
|
+
},
|
|
71
|
+
'webhook.failed': {
|
|
72
|
+
label: 'تعطل Webhook',
|
|
73
|
+
subject: 'تعذّر تسليم Webhook: {{name}}',
|
|
74
|
+
body: '{{event}} — {{error}}',
|
|
75
|
+
variables: ['name', 'event', 'error'],
|
|
76
|
+
mail: true,
|
|
77
|
+
},
|
|
78
|
+
'import.finished': {
|
|
79
|
+
label: 'اكتمال استيراد',
|
|
80
|
+
subject: 'اكتمل استيراد {{resource}}',
|
|
81
|
+
body: 'نجح {{created}} صفاً، وفشل {{failed}}.',
|
|
82
|
+
variables: ['resource', 'created', 'failed'],
|
|
83
|
+
mail: false,
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
const PLACEHOLDER = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
|
|
87
|
+
const SUBJECT_LIMIT = 200;
|
|
88
|
+
const BODY_LIMIT = 4000;
|
|
89
|
+
export function renderTemplate(text, variables) {
|
|
90
|
+
return text.replace(PLACEHOLDER, (_, name) => {
|
|
91
|
+
const value = variables[name];
|
|
92
|
+
return value === null || value === undefined ? '' : String(value);
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** Message templates: package defaults plus per-deployment overrides edited by administrators. */
|
|
96
|
+
export class MessageTemplates {
|
|
97
|
+
db;
|
|
98
|
+
definitions;
|
|
99
|
+
constructor(db, definitions = DEFAULT_TEMPLATES) {
|
|
100
|
+
this.db = db;
|
|
101
|
+
this.definitions = definitions;
|
|
102
|
+
}
|
|
103
|
+
async list() {
|
|
104
|
+
const rows = await this.db('message_templates').select('*');
|
|
105
|
+
const overrides = new Map(rows.map((row) => [String(row.key), row]));
|
|
106
|
+
return Object.entries(this.definitions).map(([key, definition]) => {
|
|
107
|
+
const row = overrides.get(key);
|
|
108
|
+
return {
|
|
109
|
+
key,
|
|
110
|
+
...definition,
|
|
111
|
+
subject: row ? String(row.subject) : definition.subject,
|
|
112
|
+
body: row ? String(row.body) : definition.body,
|
|
113
|
+
mail: row ? Boolean(row.mail) : definition.mail,
|
|
114
|
+
customized: Boolean(row),
|
|
115
|
+
updatedAt: row ? new Date(row.updated_at).toISOString() : null,
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
async render(key, variables, db = this.db) {
|
|
120
|
+
const definition = this.definition(key);
|
|
121
|
+
const row = await db('message_templates').where('key', key).first();
|
|
122
|
+
return {
|
|
123
|
+
subject: renderTemplate(row ? String(row.subject) : definition.subject, variables).slice(0, 255),
|
|
124
|
+
body: renderTemplate(row ? String(row.body) : definition.body, variables),
|
|
125
|
+
mail: row ? Boolean(row.mail) : definition.mail,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
async update(key, input, actorId) {
|
|
129
|
+
const definition = this.definition(key);
|
|
130
|
+
const subject = typeof input.subject === 'string' ? input.subject.trim() : '';
|
|
131
|
+
const body = typeof input.body === 'string' ? input.body.trim() : '';
|
|
132
|
+
if (!subject || subject.length > SUBJECT_LIMIT)
|
|
133
|
+
throw new AdulaError(422, 'E_TEMPLATE_SUBJECT', 'العنوان مطلوب ولا يتجاوز 200 حرف');
|
|
134
|
+
if (!body || body.length > BODY_LIMIT)
|
|
135
|
+
throw new AdulaError(422, 'E_TEMPLATE_BODY', 'نص الرسالة مطلوب ولا يتجاوز 4000 حرف');
|
|
136
|
+
for (const text of [subject, body])
|
|
137
|
+
for (const [, name] of text.matchAll(PLACEHOLDER))
|
|
138
|
+
if (!definition.variables.includes(name))
|
|
139
|
+
throw new AdulaError(422, 'E_TEMPLATE_VARIABLE', `متغير غير معروف في القالب: ${name}`);
|
|
140
|
+
const mail = input.mail === undefined ? definition.mail : input.mail === true;
|
|
141
|
+
await this.db('message_templates')
|
|
142
|
+
.insert({ key, subject, body, mail, updated_by: actorId, updated_at: this.db.fn.now() })
|
|
143
|
+
.onConflict('key')
|
|
144
|
+
.merge(['subject', 'body', 'mail', 'updated_by', 'updated_at']);
|
|
145
|
+
}
|
|
146
|
+
async reset(key) {
|
|
147
|
+
this.definition(key);
|
|
148
|
+
await this.db('message_templates').where('key', key).del();
|
|
149
|
+
}
|
|
150
|
+
/** Example output with sample values, for the editor preview. */
|
|
151
|
+
preview(key, input) {
|
|
152
|
+
const definition = this.definition(key);
|
|
153
|
+
const sample = Object.fromEntries(definition.variables.map((name) => [name, `‹${name}›`]));
|
|
154
|
+
return {
|
|
155
|
+
subject: renderTemplate(input.subject, sample),
|
|
156
|
+
body: renderTemplate(input.body, sample),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
definition(key) {
|
|
160
|
+
const definition = Object.hasOwn(this.definitions, key) ? this.definitions[key] : undefined;
|
|
161
|
+
if (!definition)
|
|
162
|
+
throw new AdulaError(404, 'E_TEMPLATE_NOT_FOUND', 'القالب غير موجود');
|
|
163
|
+
return definition;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Inserts a templated notification in the caller's transaction. Templates with
|
|
168
|
+
* mail enabled mark the row for the mail delivery worker (deliverNotificationMail).
|
|
169
|
+
*/
|
|
170
|
+
export async function notifyWithTemplate(db, userId, key, variables, templates = new MessageTemplates(db), target) {
|
|
171
|
+
const message = await templates.render(key, variables, db);
|
|
172
|
+
await db('notifications').insert({
|
|
173
|
+
user_id: userId,
|
|
174
|
+
title: message.subject,
|
|
175
|
+
body: message.body,
|
|
176
|
+
template_key: key,
|
|
177
|
+
mail_state: message.mail ? 'pending' : null,
|
|
178
|
+
...targetColumns(target),
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Delivers pending notification e-mails. Rows are claimed with SKIP LOCKED so
|
|
183
|
+
* several workers never send the same message; failures are retried three times.
|
|
184
|
+
*/
|
|
185
|
+
export async function deliverNotificationMail(db, send, limit = 50) {
|
|
186
|
+
let sent = 0;
|
|
187
|
+
let failed = 0;
|
|
188
|
+
await db.transaction(async (trx) => {
|
|
189
|
+
const rows = await trx('notifications as n')
|
|
190
|
+
.join('users as u', 'u.id', 'n.user_id')
|
|
191
|
+
.where('n.mail_state', 'pending')
|
|
192
|
+
.orderBy('n.id')
|
|
193
|
+
.limit(limit)
|
|
194
|
+
.forUpdate('n')
|
|
195
|
+
.skipLocked()
|
|
196
|
+
.select('n.id', 'n.title', 'n.body', 'n.mail_attempts', 'n.resource', 'n.record_id', 'u.email', 'u.full_name', 'u.disabled_at');
|
|
197
|
+
for (const row of rows) {
|
|
198
|
+
if (row.disabled_at) {
|
|
199
|
+
await trx('notifications').where('id', row.id).update({ mail_state: 'skipped' });
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
await send({
|
|
204
|
+
to: String(row.email),
|
|
205
|
+
name: row.full_name ? String(row.full_name) : null,
|
|
206
|
+
subject: String(row.title),
|
|
207
|
+
text: String(row.body),
|
|
208
|
+
target: row.resource && row.record_id !== null
|
|
209
|
+
? { resource: String(row.resource), recordId: Number(row.record_id) }
|
|
210
|
+
: null,
|
|
211
|
+
});
|
|
212
|
+
await trx('notifications')
|
|
213
|
+
.where('id', row.id)
|
|
214
|
+
.update({ mail_state: 'sent', mailed_at: trx.fn.now() });
|
|
215
|
+
sent++;
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
const attempts = Number(row.mail_attempts ?? 0) + 1;
|
|
219
|
+
await trx('notifications')
|
|
220
|
+
.where('id', row.id)
|
|
221
|
+
.update({
|
|
222
|
+
mail_state: attempts >= 3 ? 'failed' : 'pending',
|
|
223
|
+
mail_attempts: attempts,
|
|
224
|
+
mail_error: String(error.message ?? error).slice(0, 500),
|
|
225
|
+
});
|
|
226
|
+
failed++;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
return { sent, failed };
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Holds one database connection that LISTENs for committed notifications and
|
|
234
|
+
* calls onSignal for each. Reconnects after connection loss. Returns a stop function.
|
|
235
|
+
*/
|
|
236
|
+
export function listenForNotifications(db, onSignal, options = {}) {
|
|
237
|
+
let stopped = false;
|
|
238
|
+
let connection;
|
|
239
|
+
let timer;
|
|
240
|
+
const connect = async () => {
|
|
241
|
+
try {
|
|
242
|
+
connection = await db.client.acquireConnection();
|
|
243
|
+
connection.on('notification', (message) => {
|
|
244
|
+
if (message.channel !== 'adula_notifications' || !message.payload)
|
|
245
|
+
return;
|
|
246
|
+
try {
|
|
247
|
+
const parsed = JSON.parse(message.payload);
|
|
248
|
+
if (Number.isSafeInteger(parsed.userId) && Number.isSafeInteger(parsed.id))
|
|
249
|
+
onSignal({ userId: parsed.userId, id: parsed.id });
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
options.onError?.(error);
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
connection.once('error', (error) => {
|
|
256
|
+
options.onError?.(error);
|
|
257
|
+
void reconnect();
|
|
258
|
+
});
|
|
259
|
+
await connection.query('LISTEN adula_notifications');
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
options.onError?.(error);
|
|
263
|
+
void reconnect();
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
const release = async () => {
|
|
267
|
+
const current = connection;
|
|
268
|
+
connection = undefined;
|
|
269
|
+
if (!current)
|
|
270
|
+
return;
|
|
271
|
+
current.removeAllListeners('notification');
|
|
272
|
+
try {
|
|
273
|
+
await current.query('UNLISTEN *');
|
|
274
|
+
}
|
|
275
|
+
catch { }
|
|
276
|
+
// A broken connection is destroyed rather than returned to the pool.
|
|
277
|
+
await db.client.releaseConnection(current).catch(() => { });
|
|
278
|
+
};
|
|
279
|
+
const reconnect = async () => {
|
|
280
|
+
await release();
|
|
281
|
+
if (stopped)
|
|
282
|
+
return;
|
|
283
|
+
timer = setTimeout(() => void connect(), options.retryMs ?? 2000);
|
|
284
|
+
timer.unref?.();
|
|
285
|
+
};
|
|
286
|
+
void connect();
|
|
287
|
+
return async () => {
|
|
288
|
+
stopped = true;
|
|
289
|
+
if (timer)
|
|
290
|
+
clearTimeout(timer);
|
|
291
|
+
await release();
|
|
292
|
+
};
|
|
293
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
import type { ResourceRegistry } from '../resource/registry.js';
|
|
3
|
+
export type ModuleSeedResult = {
|
|
4
|
+
/** Lookup rows inserted now; rows that already existed are left as they are. */
|
|
5
|
+
lookups: number;
|
|
6
|
+
created: string[];
|
|
7
|
+
adopted: string[];
|
|
8
|
+
kept: string[];
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Applies the lookups and default roles declared by registered modules. It is
|
|
12
|
+
* idempotent and additive: existing lookup rows and roles are never changed, so
|
|
13
|
+
* administrator edits survive every later installation (adula:install runs it).
|
|
14
|
+
*/
|
|
15
|
+
export declare function seedModules(db: Knex, registry: ResourceRegistry, actorId: number): Promise<ModuleSeedResult>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { RolesAdmin } from './roles.js';
|
|
2
|
+
/**
|
|
3
|
+
* Applies the lookups and default roles declared by registered modules. It is
|
|
4
|
+
* idempotent and additive: existing lookup rows and roles are never changed, so
|
|
5
|
+
* administrator edits survive every later installation (adula:install runs it).
|
|
6
|
+
*/
|
|
7
|
+
export async function seedModules(db, registry, actorId) {
|
|
8
|
+
return db.transaction(async (trx) => {
|
|
9
|
+
await trx.raw('SELECT pg_advisory_xact_lock(717012)');
|
|
10
|
+
let lookups = 0;
|
|
11
|
+
for (const module of registry.modules())
|
|
12
|
+
for (const [group, rows] of Object.entries(module.lookups ?? {}))
|
|
13
|
+
for (const [index, row] of rows.entries()) {
|
|
14
|
+
const inserted = await trx('lookups')
|
|
15
|
+
.insert({
|
|
16
|
+
group,
|
|
17
|
+
key: row.key,
|
|
18
|
+
label_ar: row.label.ar,
|
|
19
|
+
label_en: row.label.en,
|
|
20
|
+
sort: row.sort ?? index,
|
|
21
|
+
active: true,
|
|
22
|
+
})
|
|
23
|
+
.onConflict(['group', 'key'])
|
|
24
|
+
.ignore()
|
|
25
|
+
.returning('id');
|
|
26
|
+
lookups += inserted.length;
|
|
27
|
+
}
|
|
28
|
+
const roles = await new RolesAdmin(trx, registry).ensureDefaults(actorId, registry.modules().flatMap((module) => [...(module.defaultRoles ?? [])]));
|
|
29
|
+
return { lookups, ...roles };
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
import type { ResourceRegistry } from '../resource/registry.js';
|
|
3
|
+
export type Notification = {
|
|
4
|
+
id: number;
|
|
5
|
+
title: string;
|
|
6
|
+
body: string;
|
|
7
|
+
readAt: string | null;
|
|
8
|
+
createdAt: string;
|
|
9
|
+
/**
|
|
10
|
+
* The record the notification is about, while its resource is still registered.
|
|
11
|
+
* The record page authorizes the reader when the link is opened.
|
|
12
|
+
*/
|
|
13
|
+
target: {
|
|
14
|
+
resource: string;
|
|
15
|
+
recordId: number;
|
|
16
|
+
href: string;
|
|
17
|
+
} | null;
|
|
18
|
+
};
|
|
19
|
+
export type NotificationPage = {
|
|
20
|
+
data: Notification[];
|
|
21
|
+
nextCursor: string | null;
|
|
22
|
+
unread: number;
|
|
23
|
+
};
|
|
24
|
+
export declare class NotificationsAdmin {
|
|
25
|
+
private db;
|
|
26
|
+
/** Without a registry, stored targets are returned as they are. */
|
|
27
|
+
private registry?;
|
|
28
|
+
constructor(db: Knex,
|
|
29
|
+
/** Without a registry, stored targets are returned as they are. */
|
|
30
|
+
registry?: Pick<ResourceRegistry, "has"> | undefined);
|
|
31
|
+
private target;
|
|
32
|
+
/** Unread first, newest first; the cursor remembers which of the two segments it is in. */
|
|
33
|
+
list(userId: number, options?: {
|
|
34
|
+
cursor?: string;
|
|
35
|
+
limit?: number;
|
|
36
|
+
}): Promise<NotificationPage>;
|
|
37
|
+
markRead(userId: number, id: number): Promise<void>;
|
|
38
|
+
/** Marks the notification read and returns where it points (null without a target). */
|
|
39
|
+
open(userId: number, id: number): Promise<string | null>;
|
|
40
|
+
markAllRead(userId: number): Promise<number>;
|
|
41
|
+
unreadCount(userId: number): Promise<number>;
|
|
42
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { AdulaError } from '../admin/errors.js';
|
|
2
|
+
import { pageLimit } from './activity.js';
|
|
3
|
+
export class NotificationsAdmin {
|
|
4
|
+
db;
|
|
5
|
+
registry;
|
|
6
|
+
constructor(db,
|
|
7
|
+
/** Without a registry, stored targets are returned as they are. */
|
|
8
|
+
registry) {
|
|
9
|
+
this.db = db;
|
|
10
|
+
this.registry = registry;
|
|
11
|
+
}
|
|
12
|
+
target(row) {
|
|
13
|
+
if (!row.resource || row.record_id === null || row.record_id === undefined)
|
|
14
|
+
return null;
|
|
15
|
+
const resource = String(row.resource);
|
|
16
|
+
if (this.registry && !this.registry.has(resource))
|
|
17
|
+
return null;
|
|
18
|
+
const recordId = Number(row.record_id);
|
|
19
|
+
return { resource, recordId, href: `/resources/${resource}/${recordId}` };
|
|
20
|
+
}
|
|
21
|
+
/** Unread first, newest first; the cursor remembers which of the two segments it is in. */
|
|
22
|
+
async list(userId, options = {}) {
|
|
23
|
+
const limit = pageLimit(options.limit);
|
|
24
|
+
const query = this.db('notifications')
|
|
25
|
+
.where('user_id', userId)
|
|
26
|
+
.orderByRaw('(read_at IS NULL) DESC, id DESC')
|
|
27
|
+
.limit(limit + 1);
|
|
28
|
+
if (options.cursor) {
|
|
29
|
+
const match = /^([ur]):(\d{1,18})$/.exec(options.cursor);
|
|
30
|
+
if (!match)
|
|
31
|
+
throw new AdulaError(422, 'E_NOTIFICATION_CURSOR', 'مؤشر الصفحة غير صالح');
|
|
32
|
+
const id = Number(match[2]);
|
|
33
|
+
if (match[1] === 'u')
|
|
34
|
+
query.where((where) => where
|
|
35
|
+
.where((unread) => unread.whereNull('read_at').where('id', '<', id))
|
|
36
|
+
.orWhereNotNull('read_at'));
|
|
37
|
+
else
|
|
38
|
+
query.whereNotNull('read_at').where('id', '<', id);
|
|
39
|
+
}
|
|
40
|
+
const rows = await query;
|
|
41
|
+
const page = rows.slice(0, limit);
|
|
42
|
+
const last = page[page.length - 1];
|
|
43
|
+
return {
|
|
44
|
+
data: page.map((row) => ({
|
|
45
|
+
id: row.id,
|
|
46
|
+
title: row.title,
|
|
47
|
+
body: row.body,
|
|
48
|
+
readAt: row.read_at ? new Date(row.read_at).toISOString() : null,
|
|
49
|
+
createdAt: new Date(row.created_at).toISOString(),
|
|
50
|
+
target: this.target(row),
|
|
51
|
+
})),
|
|
52
|
+
nextCursor: rows.length > limit ? `${last.read_at ? 'r' : 'u'}:${last.id}` : null,
|
|
53
|
+
unread: await this.unreadCount(userId),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
async markRead(userId, id) {
|
|
57
|
+
const owned = await this.db('notifications').where({ id, user_id: userId }).first('id');
|
|
58
|
+
if (!owned)
|
|
59
|
+
throw new AdulaError(404, 'E_NOTIFICATION_NOT_FOUND', 'الإشعار غير موجود');
|
|
60
|
+
await this.db('notifications')
|
|
61
|
+
.where({ id, user_id: userId })
|
|
62
|
+
.whereNull('read_at')
|
|
63
|
+
.update({ read_at: this.db.fn.now() });
|
|
64
|
+
}
|
|
65
|
+
/** Marks the notification read and returns where it points (null without a target). */
|
|
66
|
+
async open(userId, id) {
|
|
67
|
+
const row = await this.db('notifications').where({ id, user_id: userId }).first();
|
|
68
|
+
if (!row)
|
|
69
|
+
throw new AdulaError(404, 'E_NOTIFICATION_NOT_FOUND', 'الإشعار غير موجود');
|
|
70
|
+
if (!row.read_at)
|
|
71
|
+
await this.db('notifications')
|
|
72
|
+
.where({ id, user_id: userId })
|
|
73
|
+
.whereNull('read_at')
|
|
74
|
+
.update({ read_at: this.db.fn.now() });
|
|
75
|
+
return this.target(row)?.href ?? null;
|
|
76
|
+
}
|
|
77
|
+
async markAllRead(userId) {
|
|
78
|
+
return this.db('notifications')
|
|
79
|
+
.where('user_id', userId)
|
|
80
|
+
.whereNull('read_at')
|
|
81
|
+
.update({ read_at: this.db.fn.now() });
|
|
82
|
+
}
|
|
83
|
+
async unreadCount(userId) {
|
|
84
|
+
const row = await this.db('notifications')
|
|
85
|
+
.where('user_id', userId)
|
|
86
|
+
.whereNull('read_at')
|
|
87
|
+
.count('id as count')
|
|
88
|
+
.first();
|
|
89
|
+
return Number(row?.count ?? 0);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
import type { ResourceRegistry } from '../resource/registry.js';
|
|
3
|
+
export type OrgUnitNode = {
|
|
4
|
+
id: number;
|
|
5
|
+
parentId: number | null;
|
|
6
|
+
name: string;
|
|
7
|
+
type: string;
|
|
8
|
+
path: string;
|
|
9
|
+
depth: number;
|
|
10
|
+
members: number;
|
|
11
|
+
};
|
|
12
|
+
export declare class OrgUnitsAdmin {
|
|
13
|
+
private db;
|
|
14
|
+
private registry;
|
|
15
|
+
constructor(db: Knex, registry: ResourceRegistry);
|
|
16
|
+
tree(): Promise<OrgUnitNode[]>;
|
|
17
|
+
create(actorId: number, input: {
|
|
18
|
+
parentId: number | null;
|
|
19
|
+
name: string;
|
|
20
|
+
type: string;
|
|
21
|
+
}): Promise<{
|
|
22
|
+
id: number;
|
|
23
|
+
path: string;
|
|
24
|
+
}>;
|
|
25
|
+
rename(actorId: number, id: number, value: string): Promise<void>;
|
|
26
|
+
move(actorId: number, id: number, parentId: number | null): Promise<void>;
|
|
27
|
+
/** A unit leaves only when nothing points at it: children, memberships or scoped records. */
|
|
28
|
+
delete(actorId: number, id: number): Promise<void>;
|
|
29
|
+
private find;
|
|
30
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { identifier } from '../resource/define_resource.js';
|
|
3
|
+
import { AdulaError } from '../admin/errors.js';
|
|
4
|
+
import { moveOrgUnit } from '../org/org_service.js';
|
|
5
|
+
import { logActivity } from './activity.js';
|
|
6
|
+
const RESOURCE = 'core.org_units';
|
|
7
|
+
// Shared with moveOrgUnit so every tree edit serializes on the same lock.
|
|
8
|
+
const TREE_LOCK = 717010;
|
|
9
|
+
function text(value, field) {
|
|
10
|
+
const trimmed = typeof value === 'string' ? value.trim() : '';
|
|
11
|
+
if (!trimmed || trimmed.length > 100)
|
|
12
|
+
throw new AdulaError(422, 'E_ORG_INPUT', `${field} مطلوب (حتى 100 حرف)`);
|
|
13
|
+
return trimmed;
|
|
14
|
+
}
|
|
15
|
+
export class OrgUnitsAdmin {
|
|
16
|
+
db;
|
|
17
|
+
registry;
|
|
18
|
+
constructor(db, registry) {
|
|
19
|
+
this.db = db;
|
|
20
|
+
this.registry = registry;
|
|
21
|
+
}
|
|
22
|
+
async tree() {
|
|
23
|
+
const rows = await this.db('org_units as o')
|
|
24
|
+
.select('o.id', 'o.parent_id', 'o.name', 'o.type', this.db.raw('o.path::text AS path'), this.db.raw('nlevel(o.path) AS depth'), this.db.raw('(SELECT count(*) FROM user_org_units m WHERE m.org_unit_id = o.id) AS members'))
|
|
25
|
+
.orderBy('o.path');
|
|
26
|
+
return rows.map((row) => ({
|
|
27
|
+
id: row.id,
|
|
28
|
+
parentId: row.parent_id ?? null,
|
|
29
|
+
name: row.name,
|
|
30
|
+
type: row.type,
|
|
31
|
+
path: row.path,
|
|
32
|
+
depth: Number(row.depth),
|
|
33
|
+
members: Number(row.members),
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
async create(actorId, input) {
|
|
37
|
+
const name = text(input.name, 'الاسم');
|
|
38
|
+
const type = text(input.type, 'النوع');
|
|
39
|
+
return this.db.transaction(async (trx) => {
|
|
40
|
+
await trx.raw('SELECT pg_advisory_xact_lock(?)', [TREE_LOCK]);
|
|
41
|
+
const parent = input.parentId === null ? null : await trx('org_units').where('id', input.parentId).first();
|
|
42
|
+
if (input.parentId !== null && !parent)
|
|
43
|
+
throw new AdulaError(404, 'E_ORG_NOT_FOUND', 'الوحدة الأم غير موجودة');
|
|
44
|
+
const [unit] = await trx('org_units')
|
|
45
|
+
.insert({
|
|
46
|
+
parent_id: input.parentId,
|
|
47
|
+
name,
|
|
48
|
+
type,
|
|
49
|
+
path: `tmp_${randomBytes(8).toString('hex')}`,
|
|
50
|
+
})
|
|
51
|
+
.returning('id');
|
|
52
|
+
const path = parent ? `${parent.path}.${unit.id}` : `${unit.id}`;
|
|
53
|
+
await trx('org_units').where('id', unit.id).update({ path });
|
|
54
|
+
await logActivity(trx, {
|
|
55
|
+
resource: RESOURCE,
|
|
56
|
+
recordId: unit.id,
|
|
57
|
+
actorId,
|
|
58
|
+
action: 'create',
|
|
59
|
+
changes: { name, type, parentId: input.parentId, path },
|
|
60
|
+
});
|
|
61
|
+
return { id: unit.id, path };
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
async rename(actorId, id, value) {
|
|
65
|
+
const name = text(value, 'الاسم');
|
|
66
|
+
return this.db.transaction(async (trx) => {
|
|
67
|
+
const unit = await this.find(trx, id);
|
|
68
|
+
await trx('org_units').where('id', id).update({ name });
|
|
69
|
+
await logActivity(trx, {
|
|
70
|
+
resource: RESOURCE,
|
|
71
|
+
recordId: id,
|
|
72
|
+
actorId,
|
|
73
|
+
action: 'rename',
|
|
74
|
+
changes: { from: unit.name, to: name },
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async move(actorId, id, parentId) {
|
|
79
|
+
return this.db.transaction(async (trx) => {
|
|
80
|
+
const unit = await this.find(trx, id);
|
|
81
|
+
await moveOrgUnit(trx, id, parentId);
|
|
82
|
+
const moved = await trx('org_units').where('id', id).first();
|
|
83
|
+
await logActivity(trx, {
|
|
84
|
+
resource: RESOURCE,
|
|
85
|
+
recordId: id,
|
|
86
|
+
actorId,
|
|
87
|
+
action: 'move',
|
|
88
|
+
changes: { from: unit.parent_id ?? null, to: parentId, path: String(moved.path) },
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/** A unit leaves only when nothing points at it: children, memberships or scoped records. */
|
|
93
|
+
async delete(actorId, id) {
|
|
94
|
+
return this.db.transaction(async (trx) => {
|
|
95
|
+
await trx.raw('SELECT pg_advisory_xact_lock(?)', [TREE_LOCK]);
|
|
96
|
+
const unit = await this.find(trx, id);
|
|
97
|
+
if (await trx('org_units').where('parent_id', id).first())
|
|
98
|
+
throw new AdulaError(409, 'E_ORG_HAS_CHILDREN', 'انقل الوحدات الفرعية أولاً');
|
|
99
|
+
if ((await trx('user_org_units').where('org_unit_id', id).first()) ||
|
|
100
|
+
(await trx('user_roles').where('org_unit_id', id).first()))
|
|
101
|
+
throw new AdulaError(409, 'E_ORG_HAS_MEMBERS', 'أزل أعضاء الوحدة وأدوارها المقيدة أولاً');
|
|
102
|
+
for (const resource of this.registry.all().filter((r) => r.scoped)) {
|
|
103
|
+
const record = await trx(identifier(resource.name)).where('org_unit_id', id).first('id');
|
|
104
|
+
if (record)
|
|
105
|
+
throw new AdulaError(409, 'E_ORG_HAS_RECORDS', `الوحدة تحتوي سجلات في ${resource.label.ar}؛ انقلها أولاً`);
|
|
106
|
+
}
|
|
107
|
+
await trx('org_units').where('id', id).delete();
|
|
108
|
+
await logActivity(trx, {
|
|
109
|
+
resource: RESOURCE,
|
|
110
|
+
recordId: id,
|
|
111
|
+
actorId,
|
|
112
|
+
action: 'delete',
|
|
113
|
+
changes: { name: unit.name, path: String(unit.path) },
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
async find(db, id) {
|
|
118
|
+
const unit = await db('org_units').where('id', id).first();
|
|
119
|
+
if (!unit)
|
|
120
|
+
throw new AdulaError(404, 'E_ORG_NOT_FOUND', 'الوحدة التنظيمية غير موجودة');
|
|
121
|
+
return unit;
|
|
122
|
+
}
|
|
123
|
+
}
|