adula 2.0.0 → 2.2.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.
Files changed (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +5 -3
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -0,0 +1,1015 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ import { logActivity } from '../core/activity.js';
4
+ import { sanitizePrintHtml } from '../core/html_sanitizer.js';
5
+ import { parseTemplate, templateError, walkTemplate, } from '../core/template_language.js';
6
+ import { uiPreferences, } from '../core/ui_preferences.js';
7
+ import { escapeHtml, printLogoHtml, relationTitle, renderPrintHtml, } from './print.js';
8
+ /** The implicit template of every resource: the generic layout of renderPrintHtml. */
9
+ export const DEFAULT_PRINT_TEMPLATE = 'default';
10
+ export const PRINT_PAPERS = ['A4', 'A5', 'Letter'];
11
+ export const PRINT_ORIENTATIONS = ['portrait', 'landscape'];
12
+ /** Helpers a template may call; nothing else is callable. */
13
+ export const PRINT_HELPERS = ['date', 'money', 'number', 'digits', 'label', 'total'];
14
+ /** Document values addressable by bare name. */
15
+ export const PRINT_VALUES = [
16
+ 'id',
17
+ 'resource',
18
+ 'template',
19
+ 'company',
20
+ 'status',
21
+ 'printedBy',
22
+ 'printedAt',
23
+ 'rowNumber',
24
+ 'logo',
25
+ ];
26
+ const KEY = /^[a-z][a-z0-9_]{0,63}$/;
27
+ const LABEL_LIMIT = 200;
28
+ const TEXT_LIMIT = 500;
29
+ const NUMERIC = ['money', 'integer', 'decimal', 'percent'];
30
+ const DATES = ['date', 'datetime'];
31
+ const lineLimit = () => new AdulaError(422, 'E_PRINT_LINE_LIMIT', 'عدد البنود يتجاوز حد الطباعة (1000 بند)');
32
+ const duplicateKey = () => new AdulaError(409, 'E_PRINT_TEMPLATE_EXISTS', 'يوجد قالب طباعة بهذا المفتاح لهذا الكيان');
33
+ const staleVersion = () => new AdulaError(409, 'E_PRINT_TEMPLATE_CONFLICT', 'عدّل مسؤول آخر هذا القالب بعد أن فتحته. أعد فتحه وطبّق تعديلك مجدداً.');
34
+ const notFound = () => new AdulaError(404, 'E_PRINT_TEMPLATE_NOT_FOUND', 'قالب الطباعة غير موجود');
35
+ const labelOf = (label) => label.ar;
36
+ // ---------------------------------------------------------------------------------------
37
+ // Definition-time checks of code templates (defineResource and ResourceRegistry.register)
38
+ // ---------------------------------------------------------------------------------------
39
+ function definitionSchema(resource) {
40
+ const fields = {};
41
+ const groups = {};
42
+ for (const [key, field] of Object.entries(resource.fields))
43
+ if (field.type === 'hasMany')
44
+ groups[key] = {};
45
+ else
46
+ fields[key] = field;
47
+ return { fields, groups };
48
+ }
49
+ /** Checks the printTemplates of one resource definition; called by defineResource. */
50
+ export function assertPrintTemplates(resource) {
51
+ const templates = resource.printTemplates;
52
+ if (templates === undefined)
53
+ return;
54
+ if (!Array.isArray(templates))
55
+ throw new Error(`${resource.name}: printTemplates must be a list`);
56
+ const keys = new Set();
57
+ const schema = definitionSchema(resource);
58
+ for (const template of templates) {
59
+ const context = `${resource.name}: print template ${String(template?.key)}`;
60
+ if (typeof template?.key !== 'string' || !KEY.test(template.key))
61
+ throw new Error(`${context}: key must match ${KEY.source}`);
62
+ if (template.key === DEFAULT_PRINT_TEMPLATE)
63
+ throw new Error(`${context}: «default» is the generic layout`);
64
+ if (keys.has(template.key))
65
+ throw new Error(`${context}: duplicate key`);
66
+ keys.add(template.key);
67
+ if (!template.label || typeof template.label.ar !== 'string' || !template.label.ar.trim())
68
+ throw new Error(`${context}: label needs Arabic text`);
69
+ if (template.paper !== undefined && !PRINT_PAPERS.includes(template.paper))
70
+ throw new Error(`${context}: paper must be A4, A5 or Letter`);
71
+ if (template.orientation !== undefined && !PRINT_ORIENTATIONS.includes(template.orientation))
72
+ throw new Error(`${context}: orientation must be portrait or landscape`);
73
+ for (const text of [template.header, template.footer])
74
+ if (text !== undefined) {
75
+ if (typeof text !== 'string' || text.length > TEXT_LIMIT)
76
+ throw new Error(`${context}: header and footer are strings of ${TEXT_LIMIT} characters at most`);
77
+ try {
78
+ checkTemplate(parseTemplate(text), schema, 'text');
79
+ }
80
+ catch (error) {
81
+ throw new Error(`${context}: ${error.message}`);
82
+ }
83
+ }
84
+ if (!Array.isArray(template.fields))
85
+ throw new Error(`${context}: fields must be a list`);
86
+ for (const key of template.fields)
87
+ if (!(key in schema.fields))
88
+ throw new Error(`${context}: unknown or line field ${String(key)}`);
89
+ for (const [group, columns] of Object.entries(template.lines ?? {})) {
90
+ if (!(group in schema.groups))
91
+ throw new Error(`${context}: ${group} is not a hasMany field`);
92
+ if (!Array.isArray(columns) || !columns.length || columns.some((c) => typeof c !== 'string'))
93
+ throw new Error(`${context}: lines.${group} must list child columns`);
94
+ }
95
+ for (const total of template.totals ?? []) {
96
+ if (!total?.label?.ar?.trim())
97
+ throw new Error(`${context}: every total needs an Arabic label`);
98
+ if ('field' in total) {
99
+ const field = schema.fields[total.field];
100
+ if (!field || !NUMERIC.includes(field.type))
101
+ throw new Error(`${context}: total field ${total.field} must be a money or number field`);
102
+ }
103
+ else if (!template.lines?.[total.lines]?.includes(total.column))
104
+ throw new Error(`${context}: total ${total.lines}.${total.column} must sum a printed line column`);
105
+ }
106
+ }
107
+ }
108
+ /** Checks line columns of code templates against the child resources; called on register. */
109
+ export function assertPrintTemplateColumns(resource, registry) {
110
+ for (const template of resource.printTemplates ?? [])
111
+ for (const [group, columns] of Object.entries(template.lines ?? {})) {
112
+ const field = resource.fields[group];
113
+ if (field.type !== 'hasMany')
114
+ continue;
115
+ const child = registry.get(field.resource);
116
+ for (const column of columns) {
117
+ const definition = child.fields[column];
118
+ if (!definition || definition.type === 'hasMany')
119
+ throw new Error(`${resource.name}: print template ${template.key}: unknown column ${group}.${column}`);
120
+ }
121
+ for (const total of template.totals ?? [])
122
+ if ('lines' in total && total.lines === group) {
123
+ const type = child.fields[total.column].type;
124
+ if (!NUMERIC.includes(type))
125
+ throw new Error(`${resource.name}: print template ${template.key}: total ${group}.${total.column} must be a money or number column`);
126
+ }
127
+ }
128
+ }
129
+ // ---------------------------------------------------------------------------------------
130
+ // Template language: checking names against a schema
131
+ // ---------------------------------------------------------------------------------------
132
+ /** Most lines one printed group holds; a longer document is refused, never truncated. */
133
+ export const PRINT_LINE_LIMIT = 1000;
134
+ /**
135
+ * The hasMany fields a print may read: those the record exposes (`serialize`, or `list`
136
+ * and `show`) and those the resource's own code print templates declare. The resource
137
+ * author decides both; an administrator template cannot reach any other line group.
138
+ */
139
+ export function printableGroups(resource) {
140
+ const exposed = new Set([
141
+ ...(resource.serialize ?? [...resource.list, ...resource.show]),
142
+ ...(resource.printTemplates ?? []).flatMap((template) => Object.keys(template.lines ?? {})),
143
+ ]);
144
+ return Object.keys(resource.fields).filter((key) => resource.fields[key].type === 'hasMany' && exposed.has(key));
145
+ }
146
+ /** The names a template of this registered resource may use. */
147
+ export function printSchema(registry, name) {
148
+ const resource = registry.get(name);
149
+ const schema = definitionSchema(resource);
150
+ const printable = new Set(printableGroups(resource));
151
+ for (const key of Object.keys(schema.groups)) {
152
+ const field = resource.fields[key];
153
+ if (field.type !== 'hasMany' || !printable.has(key)) {
154
+ delete schema.groups[key];
155
+ continue;
156
+ }
157
+ schema.groups[key] = Object.fromEntries(Object.entries(registry.get(field.resource).fields).filter(([, f]) => f.type !== 'hasMany'));
158
+ }
159
+ return schema;
160
+ }
161
+ function unknownName(name) {
162
+ return templateError(`اسم غير معروف في القالب: ${name}`);
163
+ }
164
+ function refField(ref, schema, group) {
165
+ switch (ref.kind) {
166
+ case 'field':
167
+ return schema.fields[ref.key] ?? unknownName(`field.${ref.key}`);
168
+ case 'row':
169
+ if (!group)
170
+ return templateError(`row.${ref.key} يُستخدم داخل {{#each}} فقط`);
171
+ return schema.groups[group]?.[ref.key] ?? unknownName(`row.${ref.key}`);
172
+ case 'meta':
173
+ if (!PRINT_VALUES.includes(ref.key))
174
+ unknownName(ref.key);
175
+ return null;
176
+ case 'lines':
177
+ if (!(ref.key in schema.groups))
178
+ unknownName(`lines.${ref.key}`);
179
+ if (ref.column !== undefined && !(ref.column in schema.groups[ref.key]))
180
+ unknownName(`lines.${ref.key}.${ref.column}`);
181
+ return ref.column === undefined ? null : schema.groups[ref.key][ref.column];
182
+ case 'string':
183
+ return null;
184
+ }
185
+ }
186
+ /**
187
+ * Refuses unknown names and helpers and misplaced values with a 422 E_PRINT_TEMPLATE.
188
+ * `text` mode (header and footer) allows only document values and record fields.
189
+ */
190
+ export function checkTemplate(nodes, schema, mode = 'html') {
191
+ walkTemplate(nodes, (node, group) => {
192
+ if (mode === 'text' && node.type !== 'output')
193
+ templateError('الترويسة والتذييل نص فقط: لا تُستخدم فيهما {{#if}} أو {{#each}}');
194
+ if (node.type === 'each') {
195
+ if (!(node.group in schema.groups))
196
+ unknownName(`lines.${node.group}`);
197
+ return;
198
+ }
199
+ if (node.type === 'if') {
200
+ if (node.test.kind === 'string' || (node.test.kind === 'lines' && node.test.column))
201
+ templateError(`شرط غير مسموح في القالب: {{${node.source}}}`);
202
+ refField(node.test, schema, group);
203
+ return;
204
+ }
205
+ const { helper, arg } = node;
206
+ if (mode === 'text' && (arg.kind === 'row' || arg.kind === 'lines' || helper === 'total'))
207
+ templateError('الترويسة والتذييل نص فقط: لا تُستخدم فيهما البنود');
208
+ if (helper === null) {
209
+ if (arg.kind === 'string' || arg.kind === 'lines')
210
+ templateError(`قيمة غير مسموحة في القالب: {{${node.source}}}`);
211
+ if (mode === 'text' && arg.kind === 'meta' && arg.key === 'logo')
212
+ templateError('الشعار {{logo}} يُستخدم في متن القالب فقط');
213
+ refField(arg, schema, group);
214
+ return;
215
+ }
216
+ if (!PRINT_HELPERS.includes(helper))
217
+ templateError(`دالة غير مسموحة في القالب: ${helper}`);
218
+ if (helper === 'label') {
219
+ if (arg.kind !== 'string')
220
+ templateError('label يقبل اسم حقل بين علامتي تنصيص مثل label "total"');
221
+ const [key, column] = arg.value.split('.');
222
+ if (column === undefined
223
+ ? !(key in schema.fields) && !(key in schema.groups)
224
+ : !schema.groups[key]?.[column])
225
+ unknownName(arg.value);
226
+ return;
227
+ }
228
+ if (helper === 'total') {
229
+ if (arg.kind !== 'lines' || !arg.column)
230
+ templateError('total يقبل عمود بنود مثل total lines.items.quantity');
231
+ const field = refField(arg, schema, group);
232
+ if (!field || !NUMERIC.includes(field.type))
233
+ templateError(`total يجمع عمودًا ماليًا أو رقميًا فقط: ${node.source}`);
234
+ return;
235
+ }
236
+ if (arg.kind === 'string' || arg.kind === 'lines')
237
+ templateError(`قيمة غير مسموحة في القالب: {{${node.source}}}`);
238
+ const field = refField(arg, schema, group);
239
+ if (helper === 'digits')
240
+ return;
241
+ if (arg.kind === 'meta' && !(helper === 'date' && arg.key === 'printedAt'))
242
+ templateError(`${helper} يقبل حقلًا من السجل أو البنود: {{${node.source}}}`);
243
+ if (helper === 'date' && field && !DATES.includes(field.type))
244
+ templateError(`date يقبل حقل تاريخ فقط: {{${node.source}}}`);
245
+ if (helper === 'money' && field?.type !== 'money')
246
+ templateError(`money يقبل حقلًا ماليًا فقط: {{${node.source}}}`);
247
+ if (helper === 'number' && (!field || !NUMERIC.includes(field.type)))
248
+ templateError(`number يقبل حقلًا رقميًا فقط: {{${node.source}}}`);
249
+ });
250
+ }
251
+ // ---------------------------------------------------------------------------------------
252
+ // Formatting
253
+ // ---------------------------------------------------------------------------------------
254
+ const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩';
255
+ function withDigits(text, digits) {
256
+ return digits === 'arab' ? text.replace(/[0-9]/g, (d) => ARABIC_DIGITS[Number(d)]) : text;
257
+ }
258
+ /** Groups an integer or decimal string; Arabic-Indic digits use ٬ and ٫ separators. */
259
+ function groupNumber(value, digits) {
260
+ const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(value);
261
+ if (!match)
262
+ return withDigits(value, digits);
263
+ const [group, point] = digits === 'arab' ? ['٬', '٫'] : [',', '.'];
264
+ const whole = match[2].replace(/\B(?=(\d{3})+(?!\d))/g, group);
265
+ return withDigits(`${match[1]}${whole}${match[3] === undefined ? '' : point + match[3]}`, digits);
266
+ }
267
+ function formatMoney(value, digits) {
268
+ // Same presentation as the UI: grouped major units and two minor digits.
269
+ if (!/^-?\d+$/.test(String(value)))
270
+ return withDigits(String(value), digits);
271
+ const minor = BigInt(String(value));
272
+ const abs = minor < 0n ? -minor : minor;
273
+ return groupNumber(`${minor < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`, digits);
274
+ }
275
+ function formatDate(value, type, format) {
276
+ const raw = String(value);
277
+ const date = new Date(type === 'date' && /^\d{4}-\d{2}-\d{2}$/.test(raw) ? `${raw}T00:00:00Z` : raw);
278
+ if (Number.isNaN(date.getTime()))
279
+ return withDigits(raw, format.digits);
280
+ const options = {
281
+ // A date has no time of day; a date-time is shown in the application time zone.
282
+ timeZone: type === 'date' ? 'UTC' : format.timeZone,
283
+ year: 'numeric',
284
+ month: '2-digit',
285
+ day: '2-digit',
286
+ ...(type === 'date' ? {} : { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }),
287
+ };
288
+ const one = (calendar) => new Intl.DateTimeFormat(`ar-u-ca-${calendar}-nu-${format.digits}`, options).format(date);
289
+ return format.calendar === 'both'
290
+ ? `${one('gregory')} · ${one('islamic-umalqura')}`
291
+ : one(format.calendar);
292
+ }
293
+ function formatNumber(field, value, format) {
294
+ if (field.type === 'money')
295
+ return formatMoney(value, format.digits);
296
+ const text = groupNumber(String(value), format.digits);
297
+ return field.type === 'percent' ? `${text}%` : text;
298
+ }
299
+ /** The display text of one readable value ('' when there is none). */
300
+ function display(field, value, labels, key, format) {
301
+ if (value === null || value === undefined || value === '')
302
+ return '';
303
+ switch (field.type) {
304
+ case 'boolean':
305
+ return value ? 'نعم' : 'لا';
306
+ case 'money':
307
+ case 'integer':
308
+ case 'decimal':
309
+ case 'percent':
310
+ return formatNumber(field, value, format);
311
+ case 'date':
312
+ case 'datetime':
313
+ return formatDate(value, field.type, format);
314
+ case 'lookup':
315
+ return labels.lookups[key]?.find((option) => option.value === value)?.label ?? String(value);
316
+ case 'enum':
317
+ return field.options.find((option) => option.value === value)?.label.ar ?? String(value);
318
+ case 'multiSelect':
319
+ return (Array.isArray(value) ? value : [value])
320
+ .map((item) => field.options.find((option) => option.value === item)?.label.ar ?? String(item))
321
+ .join('، ');
322
+ case 'user':
323
+ case 'belongsTo':
324
+ return relationTitle(labels.related[key], value);
325
+ case 'manyToMany':
326
+ return (Array.isArray(value) ? value : [])
327
+ .map((id) => relationTitle(labels.related[key], id))
328
+ .join('، ');
329
+ case 'attachment':
330
+ return typeof value === 'object' && !Array.isArray(value) && value.name
331
+ ? String(value.name)
332
+ : 'مرفق';
333
+ case 'json':
334
+ return JSON.stringify(value);
335
+ default:
336
+ return String(value);
337
+ }
338
+ }
339
+ /** Fixed-point value of a decimal string with `scale` fractional digits, or null. */
340
+ function scaled(value, scale) {
341
+ const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(String(value));
342
+ if (!match)
343
+ return null;
344
+ const fraction = (match[3] ?? '').padEnd(scale, '0').slice(0, scale);
345
+ const amount = BigInt(match[2] + fraction);
346
+ return match[1] ? -amount : amount;
347
+ }
348
+ function sum(field, rows, key) {
349
+ const scale = field.type === 'decimal' || field.type === 'percent' ? (field.scale ?? 2) : 0;
350
+ let total = 0n;
351
+ for (const row of rows) {
352
+ const value = row[key];
353
+ if (value === null || value === undefined || value === '')
354
+ continue;
355
+ const amount = scaled(value, scale);
356
+ if (amount !== null)
357
+ total += amount;
358
+ }
359
+ if (field.type === 'money' || scale === 0)
360
+ return total.toString();
361
+ const negative = total < 0n;
362
+ const digits = (negative ? -total : total).toString().padStart(scale + 1, '0');
363
+ return `${negative ? '-' : ''}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;
364
+ }
365
+ function lookup(ref, data, scope) {
366
+ // Only fields in the reader's description are printable, whatever the record holds.
367
+ if (ref.kind === 'field') {
368
+ const field = data.fields.get(ref.key);
369
+ return field && ref.key in data.record
370
+ ? { field, value: data.record[ref.key], key: ref.key, labels: data }
371
+ : null;
372
+ }
373
+ if (ref.kind === 'row' && scope.group && scope.row) {
374
+ const group = data.groups[scope.group];
375
+ const field = group?.fields.get(ref.key);
376
+ // Relations and lookups of a line come from the line resource, not the record.
377
+ return field && ref.key in scope.row
378
+ ? { field, value: scope.row[ref.key], key: ref.key, labels: group }
379
+ : null;
380
+ }
381
+ return null;
382
+ }
383
+ /** Document values; id, rowNumber and the print time follow the digits preference. */
384
+ function metaValue(key, data, scope, format) {
385
+ if (key === 'rowNumber')
386
+ return scope.row ? withDigits(String(scope.index + 1), format.digits) : '';
387
+ if (key === 'id')
388
+ return withDigits(data.values.id, format.digits);
389
+ if (key === 'printedAt')
390
+ return formatDate(data.values.printedIso, 'datetime', format);
391
+ return data.values[key] ?? '';
392
+ }
393
+ function truthy(ref, data, scope, format) {
394
+ if (ref.kind === 'lines')
395
+ return Boolean(data.groups[ref.key]?.rows.length);
396
+ if (ref.kind === 'meta')
397
+ return metaValue(ref.key, data, scope, format) !== '';
398
+ const found = lookup(ref, data, scope);
399
+ if (!found)
400
+ return false;
401
+ const value = found.value;
402
+ return !(value === null ||
403
+ value === undefined ||
404
+ value === '' ||
405
+ value === false ||
406
+ (Array.isArray(value) && !value.length));
407
+ }
408
+ function output(node, data, scope, format) {
409
+ const { helper, arg } = node;
410
+ if (helper === 'label') {
411
+ if (arg.kind !== 'string')
412
+ return '';
413
+ const [key, column] = arg.value.split('.');
414
+ if (column !== undefined) {
415
+ const field = data.groups[key]?.fields.get(column);
416
+ return field ? escapeHtml(labelOf(field.label)) : '';
417
+ }
418
+ const field = data.fields.get(key);
419
+ if (field)
420
+ return escapeHtml(labelOf(field.label));
421
+ return data.groups[key] ? escapeHtml(labelOf(data.groups[key].label)) : '';
422
+ }
423
+ if (helper === 'total') {
424
+ if (arg.kind !== 'lines' || !arg.column)
425
+ return '';
426
+ const group = data.groups[arg.key];
427
+ const field = group?.fields.get(arg.column);
428
+ return field ? escapeHtml(formatNumber(field, sum(field, group.rows, arg.column), format)) : '';
429
+ }
430
+ if (arg.kind === 'meta') {
431
+ if (arg.key === 'logo')
432
+ return helper === null ? data.logo : '';
433
+ const value = metaValue(arg.key, data, scope, format);
434
+ return escapeHtml(helper === 'digits' ? withDigits(value, format.digits) : value);
435
+ }
436
+ const found = lookup(arg, data, scope);
437
+ if (!found || found.value === null || found.value === undefined || found.value === '')
438
+ return '';
439
+ const { field, value, key, labels } = found;
440
+ switch (helper) {
441
+ case 'date':
442
+ return escapeHtml(DATES.includes(field.type) ? formatDate(value, field.type, format) : '');
443
+ case 'money':
444
+ return escapeHtml(field.type === 'money' ? formatMoney(value, format.digits) : '');
445
+ case 'number':
446
+ return escapeHtml(NUMERIC.includes(field.type) ? formatNumber(field, value, format) : '');
447
+ case 'digits':
448
+ return escapeHtml(withDigits(display(field, value, labels, key, format), format.digits));
449
+ default:
450
+ return escapeHtml(display(field, value, labels, key, format));
451
+ }
452
+ }
453
+ function render(nodes, data, format, plain, scope) {
454
+ let html = '';
455
+ for (const node of nodes) {
456
+ switch (node.type) {
457
+ case 'text':
458
+ html += plain ? escapeHtml(node.value) : node.value;
459
+ break;
460
+ case 'output':
461
+ html += output(node, data, scope, format);
462
+ break;
463
+ case 'if':
464
+ html += render(truthy(node.test, data, scope, format) ? node.then : node.else, data, format, plain, scope);
465
+ break;
466
+ case 'each': {
467
+ const group = data.groups[node.group];
468
+ if (!group)
469
+ break;
470
+ group.rows.forEach((row, index) => {
471
+ html += render(node.body, data, format, plain, { group: node.group, row, index });
472
+ });
473
+ break;
474
+ }
475
+ }
476
+ }
477
+ return html;
478
+ }
479
+ const PAGE_SIZES = { A4: 'A4', A5: 'A5', Letter: 'letter' };
480
+ const SCREEN_WIDTH = {
481
+ A4: { portrait: '210mm', landscape: '297mm' },
482
+ A5: { portrait: '148mm', landscape: '210mm' },
483
+ Letter: { portrait: '216mm', landscape: '279mm' },
484
+ };
485
+ function page(input, printed) {
486
+ return `<!doctype html>
487
+ <html lang="ar" dir="rtl">
488
+ <head>
489
+ <meta charset="utf-8">
490
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:">
491
+ <title>${escapeHtml(input.title)}</title>
492
+ <style>
493
+ @page { size: ${PAGE_SIZES[input.paper]} ${input.orientation}; margin: 16mm 14mm; }
494
+ * { box-sizing: border-box; }
495
+ body { font-family: "Noto Sans Arabic", "Segoe UI", Tahoma, sans-serif; color: #1c1917; font-size: 11pt; margin: 0; }
496
+ header.doc { display: flex; align-items: center; justify-content: space-between; border-bottom: 2px solid #1c1917; padding-bottom: 6mm; margin-bottom: 6mm; }
497
+ h1 { font-size: 17pt; margin: 0; } h2 { font-size: 12.5pt; margin: 7mm 0 3mm; } h3, h4 { margin: 4mm 0 2mm; }
498
+ p { margin: 1.5mm 0; }
499
+ .logo { max-height: 18mm; max-width: 50mm; }
500
+ table { width: 100%; border-collapse: collapse; }
501
+ th, td { text-align: start; padding: 2mm 3mm; border-bottom: 1px solid #e7e5e4; vertical-align: top; }
502
+ .fields th { width: 35%; color: #57534e; font-weight: 600; }
503
+ .lines thead th { background: #f5f5f4; font-size: 9.5pt; }
504
+ .totals { width: 55%; margin-inline-start: auto; margin-top: 4mm; }
505
+ .totals th { color: #57534e; } .totals td { font-weight: 700; }
506
+ .num, .totals td { font-variant-numeric: tabular-nums; }
507
+ .muted { color: #57534e; } .small { font-size: 9pt; } .center { text-align: center; } .end { text-align: end; }
508
+ .running-header { color: #57534e; font-size: 9.5pt; margin-bottom: 4mm; }
509
+ .running-footer { margin-top: 8mm; color: #57534e; font-size: 9.5pt; }
510
+ footer.printed { margin-top: 8mm; color: #78716c; font-size: 8.5pt; }
511
+ @media screen { body { max-width: ${SCREEN_WIDTH[input.paper][input.orientation]}; margin: 10mm auto; padding: 0 10mm; } }
512
+ </style>
513
+ </head>
514
+ <body>
515
+ ${input.header ? `<div class="running-header">${input.header}</div>\n` : ''}${input.body}
516
+ ${input.footer ? `<div class="running-footer">${input.footer}</div>\n` : ''}<footer class="printed">${printed}</footer>
517
+ </body>
518
+ </html>`;
519
+ }
520
+ const STATUS = ['مسودة', 'معتمد', 'ملغي'];
521
+ /** Escapes static text placed in generated template markup (braces included). */
522
+ const literal = (text) => escapeHtml(text).replaceAll('{', '&#123;').replaceAll('}', '&#125;');
523
+ /**
524
+ * The markup of a code template, limited to what this reader may read: fields and
525
+ * columns the reader cannot read are left out rather than printed empty.
526
+ */
527
+ function codeTemplateSource(template, data) {
528
+ const fields = template.fields.filter((key) => data.fields.has(key));
529
+ const rows = fields
530
+ .map((key) => `<tr><th>{{label "${key}"}}</th><td>{{field.${key}}}</td></tr>`)
531
+ .join('');
532
+ const groups = Object.entries(template.lines ?? {})
533
+ .filter(([group]) => data.groups[group])
534
+ .map(([group, columns]) => {
535
+ const visible = columns.filter((column) => data.groups[group].fields.has(column));
536
+ const numeric = (column) => NUMERIC.includes(data.groups[group].fields.get(column).type) ? ' class="num"' : '';
537
+ return `<section><h2>{{label "${group}"}}</h2><table class="lines"><thead><tr><th>#</th>${visible
538
+ .map((column) => `<th>{{label "${group}.${column}"}}</th>`)
539
+ .join('')}</tr></thead><tbody>{{#each lines.${group}}}<tr><td>{{rowNumber}}</td>${visible
540
+ .map((column) => `<td${numeric(column)}>{{row.${column}}}</td>`)
541
+ .join('')}</tr>{{/each}}</tbody></table></section>`;
542
+ })
543
+ .join('');
544
+ const totals = (template.totals ?? [])
545
+ .filter((total) => 'field' in total
546
+ ? data.fields.has(total.field)
547
+ : Boolean(data.groups[total.lines]?.fields.has(total.column)))
548
+ .map((total) => `<tr><th>${literal(labelOf(total.label))}</th><td>${'field' in total
549
+ ? `{{field.${total.field}}}`
550
+ : `{{total lines.${total.lines}.${total.column}}}`}</td></tr>`)
551
+ .join('');
552
+ return `<header class="doc"><div><h1>${literal(labelOf(template.label))}</h1><p>{{company}}</p><p class="muted">{{resource}} #{{id}}{{#if status}} · {{status}}{{/if}}</p></div><div>{{logo}}</div></header>${rows ? `<table class="fields"><tbody>${rows}</tbody></table>` : ''}${groups}${totals ? `<table class="totals"><tbody>${totals}</tbody></table>` : ''}`;
553
+ }
554
+ /** A version label of a code template: a hash of its declaration, so a change is visible. */
555
+ export function codeTemplateVersion(template) {
556
+ return `code:${createHash('sha256').update(JSON.stringify(template)).digest('hex').slice(0, 12)}`;
557
+ }
558
+ function draftOf(input) {
559
+ const string = (value) => (typeof value === 'string' ? value.trim() : '');
560
+ const label = string(input.label);
561
+ if (!label || label.length > LABEL_LIMIT)
562
+ throw new AdulaError(422, 'E_PRINT_TEMPLATE_LABEL', 'اسم القالب مطلوب ولا يتجاوز 200 حرف');
563
+ const body = string(input.body);
564
+ if (!body)
565
+ throw new AdulaError(422, 'E_PRINT_TEMPLATE_BODY', 'متن القالب مطلوب');
566
+ const paper = (input.paper ?? 'A4');
567
+ const orientation = (input.orientation ?? 'portrait');
568
+ if (!PRINT_PAPERS.includes(paper) || !PRINT_ORIENTATIONS.includes(orientation))
569
+ throw new AdulaError(422, 'E_PRINT_TEMPLATE_PAPER', 'اختر مقاس ورق واتجاهًا صالحين');
570
+ const header = string(input.header);
571
+ const footer = string(input.footer);
572
+ if (header.length > TEXT_LIMIT || footer.length > TEXT_LIMIT)
573
+ throw new AdulaError(422, 'E_PRINT_TEMPLATE_TEXT', 'الترويسة والتذييل لا يتجاوز كل منهما 500 حرف');
574
+ return { label, body, paper, orientation, header, footer };
575
+ }
576
+ /**
577
+ * Renders a print template for one reader (ADR 048). A value prints only when its field
578
+ * is in the reader's description (`source.resource.fields`, `lines[*].fields`), even if
579
+ * the record object holds more; the markup is sanitized again and every value escaped.
580
+ */
581
+ export function renderTemplateDocument(source, layout, options) {
582
+ const format = {
583
+ calendar: options.calendar ?? 'gregory',
584
+ digits: options.digits ?? 'latn',
585
+ timeZone: options.timeZone ?? 'UTC',
586
+ };
587
+ const readable = (fields) => new Map(fields.filter((f) => f.type !== 'hasMany').map((f) => [f.key, f]));
588
+ const printedAt = options.printedAt ?? new Date();
589
+ const data = {
590
+ resource: source.resource,
591
+ record: source.record,
592
+ fields: readable(source.resource.fields),
593
+ related: source.related ?? {},
594
+ lookups: source.lookups ?? {},
595
+ groups: Object.fromEntries(Object.entries(source.lines ?? {}).map(([key, group]) => [
596
+ key,
597
+ {
598
+ label: group.label,
599
+ fields: readable(group.fields),
600
+ rows: group.rows,
601
+ related: group.related ?? {},
602
+ lookups: group.lookups ?? {},
603
+ },
604
+ ])),
605
+ logo: printLogoHtml(options.identity),
606
+ values: {
607
+ id: String(source.record.id),
608
+ resource: source.resource.label,
609
+ template: layout.title,
610
+ company: options.identity.name,
611
+ status: source.resource.submittable && typeof source.record.docStatus === 'number'
612
+ ? (STATUS[source.record.docStatus] ?? '')
613
+ : '',
614
+ printedBy: options.printedBy,
615
+ printedIso: printedAt.toISOString(),
616
+ },
617
+ };
618
+ const scope = { group: null, row: null, index: 0 };
619
+ const markup = 'code' in layout ? codeTemplateSource(layout.code, data) : layout.body;
620
+ // Sanitized again at render (defense in depth), then rendered with escaped values.
621
+ const body = render(parseTemplate(sanitizePrintHtml(markup)), data, format, false, scope);
622
+ const text = (value) => render(parseTemplate(value), data, format, true, scope);
623
+ return page({
624
+ title: `${layout.title} — ${data.resource.label} #${withDigits(data.values.id, format.digits)}`,
625
+ paper: layout.paper,
626
+ orientation: layout.orientation,
627
+ header: text(layout.header ?? ''),
628
+ footer: text(layout.footer ?? ''),
629
+ body,
630
+ }, `طُبع بواسطة ${escapeHtml(options.printedBy)} في ${escapeHtml(`${formatDate(data.values.printedIso, 'datetime', format)} (${format.timeZone})`)}`);
631
+ }
632
+ /**
633
+ * Print templates (ADR 048): code templates declared on resources, administrator
634
+ * templates stored with immutable versions in print_templates / print_template_versions,
635
+ * and the generic layout as the implicit `default`. Every print reads the record through
636
+ * ResourceService as the actor, so the printed values are those the record page shows.
637
+ */
638
+ export class PrintTemplates {
639
+ db;
640
+ registry;
641
+ constructor(db, registry) {
642
+ this.db = db;
643
+ this.registry = registry;
644
+ }
645
+ resource(name) {
646
+ try {
647
+ return this.registry.get(name);
648
+ }
649
+ catch {
650
+ throw new AdulaError(404, 'E_NOT_FOUND', 'الكيان غير موجود');
651
+ }
652
+ }
653
+ /** Every template of every registered resource, for the administration screen. */
654
+ async list() {
655
+ const rows = await this.db('print_templates as t')
656
+ .join('print_template_versions as v', (join) => join.on('v.template_id', 't.id').andOn('v.version', 't.current_version'))
657
+ .select('t.*', 'v.paper', 'v.orientation')
658
+ .orderBy(['t.resource', 't.key']);
659
+ const custom = new Map();
660
+ for (const row of rows)
661
+ custom.set(row.resource, [...(custom.get(row.resource) ?? []), row]);
662
+ return this.registry.all().flatMap((resource) => [
663
+ ...(resource.printTemplates ?? []).map((template) => ({
664
+ resource: resource.name,
665
+ resourceLabel: resource.label.ar,
666
+ key: template.key,
667
+ label: template.label.ar,
668
+ source: 'code',
669
+ version: codeTemplateVersion(template),
670
+ active: true,
671
+ paper: template.paper ?? 'A4',
672
+ orientation: template.orientation ?? 'portrait',
673
+ updatedAt: null,
674
+ })),
675
+ ...(custom.get(resource.name) ?? []).map((row) => this.summary(resource, row)),
676
+ ]);
677
+ }
678
+ summary(resource, row) {
679
+ return {
680
+ resource: resource.name,
681
+ resourceLabel: resource.label.ar,
682
+ key: String(row.key),
683
+ label: String(row.label),
684
+ source: 'custom',
685
+ version: String(row.current_version),
686
+ active: Boolean(row.active),
687
+ paper: row.paper,
688
+ orientation: row.orientation,
689
+ updatedAt: new Date(row.updated_at).toISOString(),
690
+ };
691
+ }
692
+ /** One administrator template with the content of its current version. */
693
+ async get(name, key) {
694
+ const resource = this.resource(name);
695
+ const row = await this.db('print_templates as t')
696
+ .join('print_template_versions as v', (join) => join.on('v.template_id', 't.id').andOn('v.version', 't.current_version'))
697
+ .where({ 't.resource': name, 't.key': key })
698
+ .select('t.*', 'v.body', 'v.paper', 'v.orientation', 'v.header', 'v.footer')
699
+ .first();
700
+ if (!row)
701
+ throw notFound();
702
+ return {
703
+ ...this.summary(resource, row),
704
+ body: String(row.body),
705
+ header: String(row.header ?? ''),
706
+ footer: String(row.footer ?? ''),
707
+ };
708
+ }
709
+ /** The version history of an administrator template, newest first. */
710
+ async versions(name, key) {
711
+ this.resource(name);
712
+ const template = await this.db('print_templates').where({ resource: name, key }).first();
713
+ if (!template)
714
+ throw notFound();
715
+ // Core deployments may keep users without a full_name column.
716
+ const named = await this.db.schema.hasColumn('users', 'full_name');
717
+ const rows = await this.db('print_template_versions as v')
718
+ .leftJoin('users as u', 'u.id', 'v.created_by')
719
+ .where('v.template_id', template.id)
720
+ .orderBy('v.version', 'desc')
721
+ .select('v.*', 'u.email as creator_email', ...(named ? ['u.full_name as creator_name'] : []));
722
+ return rows.map((row) => ({
723
+ version: Number(row.version),
724
+ label: String(row.label),
725
+ body: String(row.body),
726
+ paper: row.paper,
727
+ orientation: row.orientation,
728
+ header: String(row.header ?? ''),
729
+ footer: String(row.footer ?? ''),
730
+ createdBy: row.creator_name ?? row.creator_email ?? null,
731
+ createdAt: new Date(row.created_at).toISOString(),
732
+ }));
733
+ }
734
+ /**
735
+ * Checks and sanitizes a draft: the markup goes through sanitizePrintHtml, then every
736
+ * name and helper is checked against the resource. Returns the stored form.
737
+ */
738
+ validate(name, input) {
739
+ this.resource(name);
740
+ const draft = draftOf(input);
741
+ const schema = printSchema(this.registry, name);
742
+ const body = sanitizePrintHtml(draft.body);
743
+ if (!body.trim())
744
+ throw new AdulaError(422, 'E_PRINT_TEMPLATE_BODY', 'لم يبقَ من متن القالب شيء بعد إزالة الوسوم غير المسموحة');
745
+ checkTemplate(parseTemplate(body), schema, 'html');
746
+ checkTemplate(parseTemplate(draft.header), schema, 'text');
747
+ checkTemplate(parseTemplate(draft.footer), schema, 'text');
748
+ return { ...draft, body };
749
+ }
750
+ /** Creates an administrator template at version 1; 409 when the key already exists. */
751
+ async create(name, input, actorId) {
752
+ return this.save(name, input, actorId, 'create');
753
+ }
754
+ /**
755
+ * Saves a new version of an existing administrator template (404 when there is none).
756
+ * `active` keeps its stored value when the input leaves it out. `expectedVersion` must
757
+ * equal the current version, so a concurrent edit is refused (409) rather than lost.
758
+ */
759
+ async update(name, key, input, actorId) {
760
+ return this.save(name, { ...input, key }, actorId, 'update');
761
+ }
762
+ /** Versions are never changed; the template row points to the current one. */
763
+ async save(name, input, actorId, mode) {
764
+ const resource = this.resource(name);
765
+ const key = typeof input.key === 'string' ? input.key.trim() : '';
766
+ if (mode === 'create') {
767
+ if (!KEY.test(key))
768
+ throw new AdulaError(422, 'E_PRINT_TEMPLATE_KEY', 'مفتاح القالب حروف إنجليزية صغيرة وأرقام وشرطة سفلية، ويبدأ بحرف');
769
+ if (key === DEFAULT_PRINT_TEMPLATE || resource.printTemplates?.some((t) => t.key === key))
770
+ throw new AdulaError(422, 'E_PRINT_TEMPLATE_KEY_TAKEN', 'هذا المفتاح مستخدم لقالب معرّف في النظام');
771
+ }
772
+ const draft = this.validate(name, input);
773
+ return this.db.transaction(async (trx) => {
774
+ let template = await trx('print_templates').where({ resource: name, key }).forUpdate().first();
775
+ if (mode === 'update') {
776
+ if (!template)
777
+ throw notFound();
778
+ const expected = input.expectedVersion;
779
+ if ((typeof expected !== 'number' && typeof expected !== 'string') ||
780
+ !/^\d+$/.test(String(expected)) ||
781
+ Number(expected) !== Number(template.current_version))
782
+ throw staleVersion();
783
+ }
784
+ if (mode === 'create') {
785
+ if (template)
786
+ throw duplicateKey();
787
+ [template] = await trx('print_templates')
788
+ .insert({
789
+ resource: name,
790
+ key,
791
+ label: draft.label,
792
+ current_version: 0,
793
+ active: input.active === undefined ? true : input.active === true,
794
+ created_by: actorId,
795
+ updated_by: actorId,
796
+ })
797
+ .onConflict(['resource', 'key'])
798
+ .ignore()
799
+ .returning('*');
800
+ // A concurrent create of the same key won the insert.
801
+ if (!template)
802
+ throw duplicateKey();
803
+ }
804
+ const version = Number(template.current_version) + 1;
805
+ await trx('print_template_versions').insert({
806
+ template_id: template.id,
807
+ version,
808
+ label: draft.label,
809
+ body: draft.body,
810
+ paper: draft.paper,
811
+ orientation: draft.orientation,
812
+ header: draft.header,
813
+ footer: draft.footer,
814
+ created_by: actorId,
815
+ });
816
+ await trx('print_templates')
817
+ .where('id', template.id)
818
+ .update({
819
+ label: draft.label,
820
+ current_version: version,
821
+ active: input.active === undefined ? Boolean(template.active) : input.active === true,
822
+ updated_by: actorId,
823
+ updated_at: trx.fn.now(),
824
+ });
825
+ return { resource: name, key, version };
826
+ });
827
+ }
828
+ /** Templates the actor may print a record of this resource with (403 without view). */
829
+ async available(resources, name, actor) {
830
+ const resource = this.resource(name);
831
+ resources.describe(name, actor);
832
+ const custom = await this.db('print_templates')
833
+ .where({ resource: name, active: true })
834
+ .orderBy('label')
835
+ .select('key', 'label');
836
+ return [
837
+ {
838
+ key: DEFAULT_PRINT_TEMPLATE,
839
+ label: { ar: 'الطباعة العامة', en: 'Standard print' },
840
+ source: 'generic',
841
+ },
842
+ ...(resource.printTemplates ?? []).map((template) => ({
843
+ key: template.key,
844
+ label: template.label,
845
+ source: 'code',
846
+ })),
847
+ ...custom.map((row) => ({
848
+ key: String(row.key),
849
+ label: { ar: String(row.label) },
850
+ source: 'custom',
851
+ })),
852
+ ];
853
+ }
854
+ /** The record as the actor may read it, with its lines and display maps. */
855
+ /** The record, its lines and display maps as the actor may read them. */
856
+ async source(resources, name, id, actor) {
857
+ const shown = await resources.show(name, id, actor);
858
+ const resource = resources.describe(name, actor);
859
+ // Only the line groups a template may name (printableGroups) are read; documentLines
860
+ // applies the hasMany field's rules and level, the child's view permission and each
861
+ // line's scope, like the record page.
862
+ const definition = this.resource(name);
863
+ const lines = await resources.documentLines(name, id, actor, {
864
+ fields: printableGroups(definition),
865
+ limit: PRINT_LINE_LIMIT,
866
+ });
867
+ const groups = {};
868
+ for (const [key, group] of Object.entries(lines)) {
869
+ const field = definition.fields[key];
870
+ if (field?.type !== 'hasMany')
871
+ continue;
872
+ // Never print a truncated table or total.
873
+ if (group.hasMore)
874
+ throw lineLimit();
875
+ groups[key] = {
876
+ label: field.label,
877
+ fields: resources.describe(field.resource, actor).fields,
878
+ rows: group.rows,
879
+ related: group.related ?? {},
880
+ lookups: await resources.lookups(field.resource, actor),
881
+ };
882
+ }
883
+ return {
884
+ resource,
885
+ record: shown.data,
886
+ related: (shown.related ?? {}),
887
+ lookups: await resources.lookups(name, actor),
888
+ lines: groups,
889
+ };
890
+ }
891
+ async formatting(options) {
892
+ const stored = options.calendar && options.digits ? null : await uiPreferences(this.db);
893
+ return {
894
+ ...options,
895
+ calendar: options.calendar ?? stored?.calendar ?? 'gregory',
896
+ digits: options.digits ?? stored?.digits ?? 'latn',
897
+ };
898
+ }
899
+ /**
900
+ * Renders one record with a template (`default` for the generic layout). Call
901
+ * recordPrinted once the document was delivered (after a PDF conversion succeeded).
902
+ */
903
+ async print(resources, name, id, actor, options) {
904
+ const resource = this.resource(name);
905
+ const key = options.template || DEFAULT_PRINT_TEMPLATE;
906
+ let html;
907
+ let template;
908
+ if (key === DEFAULT_PRINT_TEMPLATE) {
909
+ const shown = await resources.show(name, id, actor);
910
+ const description = resources.describe(name, actor);
911
+ // The generic layout prints the line groups of the detail view, complete.
912
+ const childData = await resources.documentLines(name, id, actor, {
913
+ fields: resource.show.filter((entry) => resource.fields[entry]?.type === 'hasMany'),
914
+ limit: PRINT_LINE_LIMIT,
915
+ });
916
+ if (Object.values(childData).some((group) => group.hasMore))
917
+ throw lineLimit();
918
+ const children = {};
919
+ for (const [childKey, group] of Object.entries(childData)) {
920
+ const field = description.fields.find((entry) => entry.key === childKey);
921
+ if (!field || field.type !== 'hasMany')
922
+ continue;
923
+ const child = resources.describe(field.resource, actor);
924
+ children[childKey] = {
925
+ rows: group.rows,
926
+ fields: child.fields.filter((entry) => child.list.includes(entry.key)),
927
+ };
928
+ }
929
+ html = renderPrintHtml({
930
+ identity: options.identity,
931
+ resource: description,
932
+ record: shown.data,
933
+ related: shown.related,
934
+ lookups: await resources.lookups(name, actor),
935
+ children,
936
+ printedBy: options.printedBy,
937
+ printedAt: options.printedAt,
938
+ });
939
+ template = { key, version: 'generic', source: 'generic' };
940
+ }
941
+ else {
942
+ const code = resource.printTemplates?.find((entry) => entry.key === key);
943
+ const stored = code
944
+ ? null
945
+ : await this.db('print_templates as t')
946
+ .join('print_template_versions as v', (join) => join.on('v.template_id', 't.id').andOn('v.version', 't.current_version'))
947
+ .where({ 't.resource': name, 't.key': key, 't.active': true })
948
+ .select('v.*')
949
+ .first();
950
+ if (!code && !stored) {
951
+ // Authorize the record first so an unknown template never reveals a hidden record.
952
+ await resources.show(name, id, actor);
953
+ throw notFound();
954
+ }
955
+ const title = code ? code.label.ar : String(stored.label);
956
+ html = renderTemplateDocument(await this.source(resources, name, id, actor), code
957
+ ? {
958
+ title,
959
+ code,
960
+ paper: code.paper ?? 'A4',
961
+ orientation: code.orientation ?? 'portrait',
962
+ header: code.header ?? '',
963
+ footer: code.footer ?? '',
964
+ }
965
+ : {
966
+ title,
967
+ body: String(stored.body),
968
+ paper: stored.paper,
969
+ orientation: stored.orientation,
970
+ header: String(stored.header ?? ''),
971
+ footer: String(stored.footer ?? ''),
972
+ }, await this.formatting(options));
973
+ template = code
974
+ ? { key, version: codeTemplateVersion(code), source: 'code' }
975
+ : { key, version: String(stored.version), source: 'custom' };
976
+ }
977
+ return { html, template };
978
+ }
979
+ /**
980
+ * Records a `printed` activity on the record with the template key, version and format.
981
+ * Call it after the document was produced (HTML rendered, or PDF converted).
982
+ */
983
+ async recordPrinted(name, id, actor, template, format) {
984
+ await logActivity(this.db, {
985
+ resource: name,
986
+ recordId: id,
987
+ actorId: actor.id,
988
+ impersonatorId: actor.impersonatorId,
989
+ action: 'printed',
990
+ changes: { template: template.key, version: template.version, format },
991
+ });
992
+ }
993
+ /**
994
+ * Renders an unsaved draft against a record the actor may read: `recordId`, or the
995
+ * newest record of the actor's list. Nothing is stored or audited.
996
+ */
997
+ async preview(resources, name, input, actor, options) {
998
+ const draft = this.validate(name, input);
999
+ let id = options.recordId ?? null;
1000
+ if (id === null) {
1001
+ const listed = await resources.list(name, actor, {
1002
+ limit: 1,
1003
+ estimate: false,
1004
+ sort: 'id',
1005
+ direction: 'desc',
1006
+ });
1007
+ const first = listed.data[0];
1008
+ if (!first)
1009
+ throw new AdulaError(404, 'E_PRINT_PREVIEW_EMPTY', 'لا يوجد سجل متاح لك لمعاينة القالب');
1010
+ id = Number(first.id);
1011
+ }
1012
+ const html = renderTemplateDocument(await this.source(resources, name, id, actor), { ...draft, title: draft.label }, await this.formatting(options));
1013
+ return { html, recordId: id };
1014
+ }
1015
+ }