@memberjunction/core-entities 6.2.2 → 6.3.0-edge.1

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 (188) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/AnchoredConversationSecurity.d.ts +10 -1
  3. package/dist/custom/AnchoredConversationSecurity.d.ts.map +1 -1
  4. package/dist/custom/AnchoredConversationSecurity.js +15 -0
  5. package/dist/custom/AnchoredConversationSecurity.js.map +1 -1
  6. package/dist/custom/ArtifactLockValidation.d.ts +28 -0
  7. package/dist/custom/ArtifactLockValidation.d.ts.map +1 -0
  8. package/dist/custom/ArtifactLockValidation.js +867 -0
  9. package/dist/custom/ArtifactLockValidation.js.map +1 -0
  10. package/dist/custom/ArtifactPermissionDelegate.d.ts +267 -0
  11. package/dist/custom/ArtifactPermissionDelegate.d.ts.map +1 -0
  12. package/dist/custom/ArtifactPermissionDelegate.js +1232 -0
  13. package/dist/custom/ArtifactPermissionDelegate.js.map +1 -0
  14. package/dist/custom/ArtifactPreviewSnapshot.d.ts +199 -0
  15. package/dist/custom/ArtifactPreviewSnapshot.d.ts.map +1 -0
  16. package/dist/custom/ArtifactPreviewSnapshot.js +772 -0
  17. package/dist/custom/ArtifactPreviewSnapshot.js.map +1 -0
  18. package/dist/custom/ArtifactSynthesisEngine.d.ts +151 -0
  19. package/dist/custom/ArtifactSynthesisEngine.d.ts.map +1 -0
  20. package/dist/custom/ArtifactSynthesisEngine.js +1124 -0
  21. package/dist/custom/ArtifactSynthesisEngine.js.map +1 -0
  22. package/dist/custom/ConversationWriteAccess.d.ts +27 -0
  23. package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
  24. package/dist/custom/ConversationWriteAccess.js +53 -0
  25. package/dist/custom/ConversationWriteAccess.js.map +1 -1
  26. package/dist/custom/DocumentLiveBlockEngine.d.ts +612 -0
  27. package/dist/custom/DocumentLiveBlockEngine.d.ts.map +1 -0
  28. package/dist/custom/DocumentLiveBlockEngine.js +2352 -0
  29. package/dist/custom/DocumentLiveBlockEngine.js.map +1 -0
  30. package/dist/custom/MJQueryEntityExtended.d.ts.map +1 -1
  31. package/dist/custom/MJQueryEntityExtended.js +27 -11
  32. package/dist/custom/MJQueryEntityExtended.js.map +1 -1
  33. package/dist/custom/MJUserViewEntityExtended.d.ts +4 -7
  34. package/dist/custom/MJUserViewEntityExtended.d.ts.map +1 -1
  35. package/dist/custom/MJUserViewEntityExtended.js +15 -97
  36. package/dist/custom/MJUserViewEntityExtended.js.map +1 -1
  37. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.d.ts.map +1 -1
  38. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js +31 -7
  39. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js.map +1 -1
  40. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts +3 -4
  41. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts.map +1 -1
  42. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js +334 -47
  43. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js.map +1 -1
  44. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts +19 -3
  45. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts.map +1 -1
  46. package/dist/custom/Permissions/BaseShareEntityExtended.js +139 -13
  47. package/dist/custom/Permissions/BaseShareEntityExtended.js.map +1 -1
  48. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts +8 -6
  49. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
  50. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +93 -41
  51. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
  52. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts +12 -5
  53. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
  54. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +240 -37
  55. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
  56. package/dist/custom/SlideDeckEngine.d.ts +427 -0
  57. package/dist/custom/SlideDeckEngine.d.ts.map +1 -0
  58. package/dist/custom/SlideDeckEngine.js +1669 -0
  59. package/dist/custom/SlideDeckEngine.js.map +1 -0
  60. package/dist/custom/SlideDeckPptxEngine.d.ts +25 -0
  61. package/dist/custom/SlideDeckPptxEngine.d.ts.map +1 -0
  62. package/dist/custom/SlideDeckPptxEngine.js +1237 -0
  63. package/dist/custom/SlideDeckPptxEngine.js.map +1 -0
  64. package/dist/custom/SpreadsheetEngine.d.ts +1370 -0
  65. package/dist/custom/SpreadsheetEngine.d.ts.map +1 -0
  66. package/dist/custom/SpreadsheetEngine.js +17580 -0
  67. package/dist/custom/SpreadsheetEngine.js.map +1 -0
  68. package/dist/custom/approvals.d.ts +7 -1
  69. package/dist/custom/approvals.d.ts.map +1 -1
  70. package/dist/custom/approvals.js +8 -1
  71. package/dist/custom/approvals.js.map +1 -1
  72. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts +7 -0
  73. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts.map +1 -0
  74. package/dist/custom/operations/ArtifactComplianceAuditOperation.js +7 -0
  75. package/dist/custom/operations/ArtifactComplianceAuditOperation.js.map +1 -0
  76. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts +7 -0
  77. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts.map +1 -0
  78. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js +7 -0
  79. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js.map +1 -0
  80. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts +60 -0
  81. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts.map +1 -0
  82. package/dist/custom/operations/ArtifactGuestShareOperations.js +6 -0
  83. package/dist/custom/operations/ArtifactGuestShareOperations.js.map +1 -0
  84. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts +7 -0
  85. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts.map +1 -0
  86. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js +7 -0
  87. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js.map +1 -0
  88. package/dist/custom/typedQuery.d.ts +162 -0
  89. package/dist/custom/typedQuery.d.ts.map +1 -0
  90. package/dist/custom/typedQuery.js +296 -0
  91. package/dist/custom/typedQuery.js.map +1 -0
  92. package/dist/engines/CanonGraphEngine.d.ts +122 -0
  93. package/dist/engines/CanonGraphEngine.d.ts.map +1 -0
  94. package/dist/engines/CanonGraphEngine.js +500 -0
  95. package/dist/engines/CanonGraphEngine.js.map +1 -0
  96. package/dist/engines/EncryptionEngineBase.js +2 -2
  97. package/dist/engines/EncryptionEngineBase.js.map +1 -1
  98. package/dist/engines/QueryEngine.js +2 -2
  99. package/dist/engines/QueryEngine.js.map +1 -1
  100. package/dist/engines/SearchEngineBase.d.ts +17 -3
  101. package/dist/engines/SearchEngineBase.d.ts.map +1 -1
  102. package/dist/engines/SearchEngineBase.js +100 -28
  103. package/dist/engines/SearchEngineBase.js.map +1 -1
  104. package/dist/engines/UserInfoEngine.d.ts +8 -0
  105. package/dist/engines/UserInfoEngine.d.ts.map +1 -1
  106. package/dist/engines/UserInfoEngine.js +62 -10
  107. package/dist/engines/UserInfoEngine.js.map +1 -1
  108. package/dist/engines/conversations.d.ts +213 -12
  109. package/dist/engines/conversations.d.ts.map +1 -1
  110. package/dist/engines/conversations.js +578 -30
  111. package/dist/engines/conversations.js.map +1 -1
  112. package/dist/generated/entities/__mj.d.ts +4265 -25257
  113. package/dist/generated/entities/__mj.d.ts.map +1 -1
  114. package/dist/generated/entities/__mj.js +3793 -40542
  115. package/dist/generated/entities/__mj.js.map +1 -1
  116. package/dist/generated/queries/__mj.d.ts +269 -0
  117. package/dist/generated/queries/__mj.d.ts.map +1 -0
  118. package/dist/generated/queries/__mj.js +100 -0
  119. package/dist/generated/queries/__mj.js.map +1 -0
  120. package/dist/generated/queries/index.d.ts +2 -0
  121. package/dist/generated/queries/index.d.ts.map +1 -0
  122. package/dist/generated/queries/index.js +4 -0
  123. package/dist/generated/queries/index.js.map +1 -0
  124. package/dist/generated/remote_operations.d.ts +275 -22
  125. package/dist/generated/remote_operations.d.ts.map +1 -1
  126. package/dist/generated/remote_operations.js +98 -3
  127. package/dist/generated/remote_operations.js.map +1 -1
  128. package/dist/generated/schemas/__mj.d.ts +25489 -0
  129. package/dist/generated/schemas/__mj.d.ts.map +1 -0
  130. package/dist/generated/schemas/__mj.js +41768 -0
  131. package/dist/generated/schemas/__mj.js.map +1 -0
  132. package/dist/generated/schemas.d.ts +2 -0
  133. package/dist/generated/schemas.d.ts.map +1 -0
  134. package/dist/generated/schemas.js +2 -0
  135. package/dist/generated/schemas.js.map +1 -0
  136. package/dist/graph/BaseGraphEdgeProvider.d.ts +158 -0
  137. package/dist/graph/BaseGraphEdgeProvider.d.ts.map +1 -0
  138. package/dist/graph/BaseGraphEdgeProvider.js +70 -0
  139. package/dist/graph/BaseGraphEdgeProvider.js.map +1 -0
  140. package/dist/graph/GraphEngine.d.ts +274 -0
  141. package/dist/graph/GraphEngine.d.ts.map +1 -0
  142. package/dist/graph/GraphEngine.js +1156 -0
  143. package/dist/graph/GraphEngine.js.map +1 -0
  144. package/dist/graph/GraphExpansion.d.ts +142 -0
  145. package/dist/graph/GraphExpansion.d.ts.map +1 -0
  146. package/dist/graph/GraphExpansion.js +87 -0
  147. package/dist/graph/GraphExpansion.js.map +1 -0
  148. package/dist/graph/index.d.ts +15 -0
  149. package/dist/graph/index.d.ts.map +1 -0
  150. package/dist/graph/index.js +30 -0
  151. package/dist/graph/index.js.map +1 -0
  152. package/dist/graph/providers/AlternateBaseViewEdgeProvider.d.ts +16 -0
  153. package/dist/graph/providers/AlternateBaseViewEdgeProvider.d.ts.map +1 -0
  154. package/dist/graph/providers/AlternateBaseViewEdgeProvider.js +115 -0
  155. package/dist/graph/providers/AlternateBaseViewEdgeProvider.js.map +1 -0
  156. package/dist/graph/providers/EntityMetadataEdgeProvider.d.ts +17 -0
  157. package/dist/graph/providers/EntityMetadataEdgeProvider.d.ts.map +1 -0
  158. package/dist/graph/providers/EntityMetadataEdgeProvider.js +145 -0
  159. package/dist/graph/providers/EntityMetadataEdgeProvider.js.map +1 -0
  160. package/dist/graph/providers/ForeignKeyEdgeProvider.d.ts +25 -0
  161. package/dist/graph/providers/ForeignKeyEdgeProvider.d.ts.map +1 -0
  162. package/dist/graph/providers/ForeignKeyEdgeProvider.js +131 -0
  163. package/dist/graph/providers/ForeignKeyEdgeProvider.js.map +1 -0
  164. package/dist/graph/providers/JoinEntityEdgeProvider.d.ts +37 -0
  165. package/dist/graph/providers/JoinEntityEdgeProvider.d.ts.map +1 -0
  166. package/dist/graph/providers/JoinEntityEdgeProvider.js +170 -0
  167. package/dist/graph/providers/JoinEntityEdgeProvider.js.map +1 -0
  168. package/dist/graph/providers/QueryEdgeProvider.d.ts +33 -0
  169. package/dist/graph/providers/QueryEdgeProvider.d.ts.map +1 -0
  170. package/dist/graph/providers/QueryEdgeProvider.js +120 -0
  171. package/dist/graph/providers/QueryEdgeProvider.js.map +1 -0
  172. package/dist/graph/providers/QueryMetadataEdgeProvider.d.ts +18 -0
  173. package/dist/graph/providers/QueryMetadataEdgeProvider.d.ts.map +1 -0
  174. package/dist/graph/providers/QueryMetadataEdgeProvider.js +163 -0
  175. package/dist/graph/providers/QueryMetadataEdgeProvider.js.map +1 -0
  176. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts +20 -0
  177. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts.map +1 -0
  178. package/dist/graph/providers/RecordLinkEdgeProvider.js +172 -0
  179. package/dist/graph/providers/RecordLinkEdgeProvider.js.map +1 -0
  180. package/dist/index.d.ts +15 -0
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +23 -0
  183. package/dist/index.js.map +1 -1
  184. package/dist/schemas.d.ts +6 -0
  185. package/dist/schemas.d.ts.map +1 -0
  186. package/dist/schemas.js +6 -0
  187. package/dist/schemas.js.map +1 -0
  188. package/package.json +17 -6
@@ -1,8 +1,9 @@
1
- import { BaseEngine, EntityEventRowIsFree, ResolveEntityEventKey, ResolveEntityEventRow, RunQuery, RunView, TransformSimpleObjectToEntityObject } from "@memberjunction/core";
1
+ import { BaseEngine, EntityEventRowIsFree, EntityPermissionType, ResolveEntityEventKey, ResolveEntityEventRow, RunQuery, RunView, TransformSimpleObjectToEntityObject } from "@memberjunction/core";
2
2
  import { EscapeSQLString, IndexByUUID, NormalizeUUID, ToEpochMs, UUIDMap, UUIDSet, UUIDsEqual } from "@memberjunction/global";
3
3
  import { BehaviorSubject } from "rxjs";
4
4
  import { ArtifactMetadataEngine } from "./artifacts.js";
5
5
  import { ResourcePermissionEngine } from "../custom/ResourcePermissions/ResourcePermissionEngine.js";
6
+ import { CONVERSATION_DELETE_REFUSED_REASON, ConversationDeleteAllowed } from "../custom/ConversationWriteAccess.js";
6
7
  import { FilterAnchoredConversationsForUser, IsConversationHiddenByFieldSecurity, ParseConversationAnchorMetadata } from "../custom/AnchoredConversationSecurity.js";
7
8
  /**
8
9
  * `MJ: Resource Types.ID` for Conversations. Conversations that the current
@@ -16,6 +17,56 @@ const CONVERSATIONS_RESOURCE_TYPE_ID = '81D4BC3D-9FEB-EF11-B01A-286B35C04427';
16
17
  * folder inherit access to conversations inside it.
17
18
  */
18
19
  export const PROJECTS_RESOURCE_TYPE_ID = '88D0DF27-AF8F-43AC-9EC4-2AC314F49355';
20
+ /**
21
+ * Canonical built-in `MJ: Conversation Types.Code` constants.
22
+ * Custom Open Apps may seed additional `ConversationType` rows and look them up via
23
+ * {@link ConversationEngine.TypeByCode} or {@link ConversationEngine.ResolveConversationTypeID}.
24
+ */
25
+ export const CONVERSATION_TYPE_CODES = {
26
+ CHAT: 'CHAT',
27
+ SKIP: 'SKIP',
28
+ ROUTINE: 'ROUTINE',
29
+ MEETING_ROOM: 'MEETING_ROOM',
30
+ COMMENT: 'COMMENT',
31
+ };
32
+ /**
33
+ * Seeded primary-key UUIDs for built-in `MJ: Conversation Types` rows, used as deterministic
34
+ * fallbacks when {@link ConversationEngine.Config} has not yet run (for example in unit tests).
35
+ */
36
+ export const BUILT_IN_CONVERSATION_TYPE_IDS = {
37
+ CHAT: '7F81FF57-C5A8-464D-B3B4-35A4FCF10717',
38
+ SKIP: 'FDAE66B9-CF87-48EA-8A12-8E521740A66A',
39
+ ROUTINE: '18D12ABA-BE8C-4087-B440-835B6D077DD7',
40
+ MEETING_ROOM: '2E9EF85D-D18A-4B8E-B6AB-F65C7F91A926',
41
+ COMMENT: '17E6A105-AE51-43A2-9D56-290BC8D1D6BB',
42
+ };
43
+ const BUILT_IN_CONVERSATION_TYPE_NAMES = {
44
+ chat: 'CHAT',
45
+ skip: 'SKIP',
46
+ routine: 'ROUTINE',
47
+ 'meeting room': 'MEETING_ROOM',
48
+ meeting_room: 'MEETING_ROOM',
49
+ comment: 'COMMENT',
50
+ };
51
+ /**
52
+ * Canonical built-in `MJ: Comment Types.Code` constants.
53
+ */
54
+ export const COMMENT_TYPE_CODES = {
55
+ COMMENT: 'COMMENT',
56
+ FIELD_SUGGESTION: 'FIELD_SUGGESTION',
57
+ };
58
+ /**
59
+ * Seeded primary-key UUIDs for built-in `MJ: Comment Types` rows.
60
+ */
61
+ export const BUILT_IN_COMMENT_TYPE_IDS = {
62
+ COMMENT: '4B3A3797-EFA5-419F-80FF-F9515E5F4AA8',
63
+ FIELD_SUGGESTION: '8918DBA5-EDDD-4AF4-A518-FEB387ED02F9',
64
+ };
65
+ const BUILT_IN_COMMENT_TYPE_NAMES = {
66
+ comment: 'COMMENT',
67
+ 'field suggestion': 'FIELD_SUGGESTION',
68
+ field_suggestion: 'FIELD_SUGGESTION',
69
+ };
19
70
  /**
20
71
  * The spellings of `"inheritFolderAccess": true` the SQL filter recognises: the compact one every MJ writer
21
72
  * produces (`JSON.stringify` and the server's save, which rewrites `AdditionalData` compactly) and the
@@ -137,14 +188,18 @@ export function ComparePermissionLevels(a, b) {
137
188
  * fields, sections, groups, and contributions, while enforcing FLS visibility when
138
189
  * `entityInfo` and `currentUser` are provided.
139
190
  */
140
- export function ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo) {
191
+ export function ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo, commentTypeCodeByConversationId) {
141
192
  let totalOpenCount = 0;
142
193
  let totalResolvedCount = 0;
143
194
  let recordLevelOpenCount = 0;
195
+ let openNoteCount = 0;
196
+ let openSuggestionCount = 0;
144
197
  const byField = new Map();
145
198
  const bySection = new Map();
146
199
  const byGroup = new Map();
147
200
  const byContribution = new Map();
201
+ const byFieldSuggestions = new Map();
202
+ const byFieldByType = new Map();
148
203
  for (const conv of conversations) {
149
204
  if (!conv.AnchorType) {
150
205
  continue;
@@ -159,6 +214,18 @@ export function ComputeAnchoredCommentCounts(conversations, currentUser, entityI
159
214
  continue;
160
215
  }
161
216
  totalOpenCount++;
217
+ const normId = conv.ID ? NormalizeUUID(conv.ID) : '';
218
+ const rawTypeCode = normId && commentTypeCodeByConversationId
219
+ ? commentTypeCodeByConversationId.get(normId)
220
+ : undefined;
221
+ const typeCode = (rawTypeCode?.trim().toUpperCase()) || COMMENT_TYPE_CODES.COMMENT;
222
+ const isSuggestion = typeCode === COMMENT_TYPE_CODES.FIELD_SUGGESTION;
223
+ if (isSuggestion) {
224
+ openSuggestionCount++;
225
+ }
226
+ else {
227
+ openNoteCount++;
228
+ }
162
229
  const meta = ParseConversationAnchorMetadata(conv.AnchorMetadataObject ?? conv.AnchorMetadata);
163
230
  const rawKey = conv.AnchorKey?.trim() ?? '';
164
231
  if (conv.AnchorType === 'Record') {
@@ -168,6 +235,15 @@ export function ComputeAnchoredCommentCounts(conversations, currentUser, entityI
168
235
  const fieldKey = (rawKey || meta?.fieldName?.trim() || '').toLowerCase();
169
236
  if (fieldKey) {
170
237
  byField.set(fieldKey, (byField.get(fieldKey) ?? 0) + 1);
238
+ if (isSuggestion) {
239
+ byFieldSuggestions.set(fieldKey, (byFieldSuggestions.get(fieldKey) ?? 0) + 1);
240
+ }
241
+ let typeMap = byFieldByType.get(fieldKey);
242
+ if (!typeMap) {
243
+ typeMap = new Map();
244
+ byFieldByType.set(fieldKey, typeMap);
245
+ }
246
+ typeMap.set(typeCode, (typeMap.get(typeCode) ?? 0) + 1);
171
247
  }
172
248
  }
173
249
  else if (conv.AnchorType === 'Section') {
@@ -208,7 +284,11 @@ export function ComputeAnchoredCommentCounts(conversations, currentUser, entityI
208
284
  ByField: byField,
209
285
  BySection: bySection,
210
286
  ByGroup: byGroup,
211
- ByContribution: byContribution
287
+ ByContribution: byContribution,
288
+ OpenNoteCount: openNoteCount,
289
+ OpenSuggestionCount: openSuggestionCount,
290
+ ByFieldSuggestions: byFieldSuggestions,
291
+ ByFieldByType: byFieldByType,
212
292
  };
213
293
  }
214
294
  /**
@@ -601,6 +681,8 @@ export class ConversationEngine extends BaseEngine {
601
681
  * which would cause redundant cache updates or infinite loops.
602
682
  */
603
683
  this._selfMutating = false;
684
+ this._conversationTypes = [];
685
+ this._commentTypes = [];
604
686
  }
605
687
  /**
606
688
  * Returns the global instance of the class. This is a singleton class, so there is only
@@ -656,6 +738,15 @@ export class ConversationEngine extends BaseEngine {
656
738
  }
657
739
  return this.GetSharedByInfo(conversation.ID)?.Level === 'Owner';
658
740
  }
741
+ /**
742
+ * True when the user may delete the conversation for everyone: they own it, hold an
743
+ * Owner-level grant on it, or are in the Developer or Integration role. An Edit grant
744
+ * is not enough. Mirrors the server's delete gate in `MJConversationEntityServer`, so
745
+ * the UI never offers a delete the server would refuse.
746
+ */
747
+ CanDeleteConversation(conversation, user) {
748
+ return ConversationDeleteAllowed(conversation.UserID, user, this.GetSharedByInfo(conversation.ID)?.Level ?? null);
749
+ }
659
750
  /**
660
751
  * True when the user may move the conversation to another folder or change whether it inherits its
661
752
  * folder's access: only its owner. Both decide who else sees it, so an Edit or Owner grant is not
@@ -676,26 +767,134 @@ export class ConversationEngine extends BaseEngine {
676
767
  return level === 'Edit' || level === 'Owner';
677
768
  }
678
769
  // ========================================================================
770
+ // CONVERSATION & COMMENT TYPE LOOKUPS
771
+ // ========================================================================
772
+ /** Cached `MJ: Conversation Types` rows loaded during {@link Config}. */
773
+ get ConversationTypes() {
774
+ return this._conversationTypes;
775
+ }
776
+ /** Cached `MJ: Comment Types` rows loaded during {@link Config}. */
777
+ get CommentTypes() {
778
+ return this._commentTypes;
779
+ }
780
+ /** Looks up a cached `MJ: Conversation Types` row by its case-insensitive `Code`. */
781
+ TypeByCode(code) {
782
+ const normalized = code?.trim().toUpperCase();
783
+ if (!normalized) {
784
+ return undefined;
785
+ }
786
+ return this._conversationTypes.find((t) => t.Code?.trim().toUpperCase() === normalized);
787
+ }
788
+ /** Looks up a cached `MJ: Conversation Types` row by its case-insensitive `Name`. */
789
+ TypeByName(name) {
790
+ const normalized = name?.trim().toLowerCase();
791
+ if (!normalized) {
792
+ return undefined;
793
+ }
794
+ return this._conversationTypes.find((t) => t.Name?.trim().toLowerCase() === normalized);
795
+ }
796
+ /** Looks up a cached `MJ: Conversation Types` row by `ID`. */
797
+ TypeByID(id) {
798
+ if (!id) {
799
+ return undefined;
800
+ }
801
+ return this._conversationTypes.find((t) => UUIDsEqual(t.ID, id));
802
+ }
803
+ /**
804
+ * Resolves a `ConversationType.ID` by `Code` or `Name`, consulting cached `ConversationTypes`
805
+ * first and falling back to built-in seeded UUIDs when {@link Config} has not yet populated cache.
806
+ */
807
+ ResolveConversationTypeID(codeOrName) {
808
+ const trimmed = codeOrName?.trim();
809
+ if (!trimmed) {
810
+ return null;
811
+ }
812
+ const fromCache = this.TypeByCode(trimmed) ?? this.TypeByName(trimmed);
813
+ if (fromCache?.ID) {
814
+ return fromCache.ID;
815
+ }
816
+ const upper = trimmed.toUpperCase();
817
+ if (upper in BUILT_IN_CONVERSATION_TYPE_IDS) {
818
+ return BUILT_IN_CONVERSATION_TYPE_IDS[upper];
819
+ }
820
+ const mappedCode = BUILT_IN_CONVERSATION_TYPE_NAMES[trimmed.toLowerCase()];
821
+ return mappedCode ? BUILT_IN_CONVERSATION_TYPE_IDS[mappedCode] : null;
822
+ }
823
+ /** Looks up a cached `MJ: Comment Types` row by its case-insensitive `Code`. */
824
+ CommentTypeByCode(code) {
825
+ const normalized = code?.trim().toUpperCase();
826
+ if (!normalized) {
827
+ return undefined;
828
+ }
829
+ return this._commentTypes.find((t) => t.Code?.trim().toUpperCase() === normalized);
830
+ }
831
+ /** Looks up a cached `MJ: Comment Types` row by its case-insensitive `Name`. */
832
+ CommentTypeByName(name) {
833
+ const normalized = name?.trim().toLowerCase();
834
+ if (!normalized) {
835
+ return undefined;
836
+ }
837
+ return this._commentTypes.find((t) => t.Name?.trim().toLowerCase() === normalized);
838
+ }
839
+ /** Looks up a cached `MJ: Comment Types` row by `ID`. */
840
+ CommentTypeByID(id) {
841
+ if (!id) {
842
+ return undefined;
843
+ }
844
+ return this._commentTypes.find((t) => UUIDsEqual(t.ID, id));
845
+ }
846
+ /**
847
+ * Resolves a `CommentType.ID` by `Code` or `Name`, consulting cached `CommentTypes`
848
+ * first and falling back to built-in seeded UUIDs when {@link Config} has not yet populated cache.
849
+ */
850
+ ResolveCommentTypeID(codeOrName) {
851
+ const trimmed = codeOrName?.trim();
852
+ if (!trimmed) {
853
+ return null;
854
+ }
855
+ const fromCache = this.CommentTypeByCode(trimmed) ?? this.CommentTypeByName(trimmed);
856
+ if (fromCache?.ID) {
857
+ return fromCache.ID;
858
+ }
859
+ const upper = trimmed.toUpperCase();
860
+ if (upper in BUILT_IN_COMMENT_TYPE_IDS) {
861
+ return BUILT_IN_COMMENT_TYPE_IDS[upper];
862
+ }
863
+ const mappedCode = BUILT_IN_COMMENT_TYPE_NAMES[trimmed.toLowerCase()];
864
+ return mappedCode ? BUILT_IN_COMMENT_TYPE_IDS[mappedCode] : null;
865
+ }
866
+ // ========================================================================
679
867
  // ENGINE CONFIG (BaseEngine pattern)
680
868
  // ========================================================================
681
869
  /**
682
- * Configures the engine. Unlike other engines that bulk-load entity tables via BaseEngine.Load(),
683
- * ConversationEngine manages its own caching because conversations are user-scoped and filtered
684
- * by environment, which doesn't fit the standard "load all rows" pattern.
685
- *
686
- * Call this once at startup to initialize the engine. Conversation data is loaded
687
- * separately via LoadConversations().
870
+ * Configures the engine, bulk-loading small lookup tables (`MJ: Conversation Types`
871
+ * and `MJ: Comment Types`) while keeping user-scoped conversation data lazy via
872
+ * {@link LoadConversations}.
688
873
  */
689
874
  async Config(forceRefresh, contextUser, provider) {
690
- // Ensure ArtifactMetadataEngine is loaded — conversation details reference artifacts
691
- // and we need artifact types available before processing. Passing false means
692
- // this is a no-op if it's already loaded.
693
875
  await ArtifactMetadataEngine.Instance.Config(forceRefresh, contextUser, provider);
694
- // We don't use BaseEngine.Load() because conversations are user-scoped.
695
- // Mark the engine as "configured" so consumers can check .Loaded.
696
- // We call Load with an empty config array just to set the Loaded flag and wire up
697
- // the BaseEngine infrastructure (entity event listeners, etc.)
698
- const configs = [];
876
+ const activeProvider = provider ?? this.ProviderToUse;
877
+ const entities = activeProvider?.Entities;
878
+ const hasTypeEntities = !Array.isArray(entities) ||
879
+ entities.length === 0 ||
880
+ (entities.some((e) => e.Name === 'MJ: Conversation Types') &&
881
+ entities.some((e) => e.Name === 'MJ: Comment Types'));
882
+ const configs = hasTypeEntities
883
+ ? [
884
+ {
885
+ Type: 'entity',
886
+ EntityName: 'MJ: Conversation Types',
887
+ PropertyName: '_conversationTypes',
888
+ CacheLocal: true,
889
+ },
890
+ {
891
+ Type: 'entity',
892
+ EntityName: 'MJ: Comment Types',
893
+ PropertyName: '_commentTypes',
894
+ CacheLocal: true,
895
+ },
896
+ ]
897
+ : [];
699
898
  await this.Load(configs, provider, forceRefresh, contextUser);
700
899
  }
701
900
  // ========================================================================
@@ -914,6 +1113,34 @@ export class ConversationEngine extends BaseEngine {
914
1113
  }
915
1114
  return [...byProjectId.values()];
916
1115
  }
1116
+ /**
1117
+ * True when one of the user's roles grants this kind of write on folders (`MJ: Projects`) with no row-level
1118
+ * filter. A user whose folder writes are all filtered (the UI role: own folders only) writes only folders they
1119
+ * own: they cannot make a folder Public (no owner) or rename, move or delete a Public folder or someone else's.
1120
+ * Answers false when the folder entity's metadata is not loaded.
1121
+ *
1122
+ * @param provider the metadata provider the caller works against; defaults to the engine's.
1123
+ */
1124
+ CanWriteAnyProject(user, type, provider) {
1125
+ if (!user) {
1126
+ return false;
1127
+ }
1128
+ const entity = (provider ?? this.ProviderToUse)?.EntityByName('MJ: Projects');
1129
+ return !!entity && entity.UserExemptFromRowLevelSecurity(user, type);
1130
+ }
1131
+ /**
1132
+ * True when the user may rename or delete this folder from the sidebar: they own it, or their folder writes
1133
+ * are not row-filtered (see {@link CanWriteAnyProject}).
1134
+ */
1135
+ CanManageProject(project, user, provider) {
1136
+ if (!project || !user) {
1137
+ return false;
1138
+ }
1139
+ if (project.OwnerUserID && UUIDsEqual(project.OwnerUserID, user.ID)) {
1140
+ return true;
1141
+ }
1142
+ return this.CanWriteAnyProject(user, EntityPermissionType.Update, provider);
1143
+ }
917
1144
  /**
918
1145
  * Returns the three-tier visibility mode (`'Private' | 'Shared' | 'Public'`) for a folder:
919
1146
  * - `'Public'`: `OwnerUserID == null` (environment-wide)
@@ -1246,6 +1473,8 @@ export class ConversationEngine extends BaseEngine {
1246
1473
  * 2. Reparents direct child folders to this folder's parent (one level up).
1247
1474
  * 3. Deletes the now-unreferenced folder.
1248
1475
  * Conversations and subfolders are preserved — only the folder itself is removed.
1476
+ * Steps 1 and 2 cover the rows the caller can change; the server's folder delete
1477
+ * (`MJProjectEntityServer.Delete`) moves the rest in the delete's transaction.
1249
1478
  *
1250
1479
  * Note: this does NOT reassign Tasks that reference the project; if a Task still
1251
1480
  * references it, the final delete will fail and this throws with the DB message.
@@ -1269,9 +1498,10 @@ export class ConversationEngine extends BaseEngine {
1269
1498
  }
1270
1499
  const newParentId = project.ParentID ?? null;
1271
1500
  // 1. Unassign conversations directly in this folder that the caller can edit.
1272
- // View-only conversations owned by other users in a shared folder cannot be edited
1273
- // by this caller; if any still exist in the DB, the delete below will surface
1274
- // FK_Conversation_Project via ExplainProjectDeleteFailure.
1501
+ // Conversations owned by other users in a shared folder cannot be edited by this
1502
+ // caller; the server's folder delete takes them out of the folder in the delete's
1503
+ // transaction (on a server without that, the delete below surfaces
1504
+ // FK_Conversation_Project via ExplainProjectDeleteFailure).
1275
1505
  const directConversations = this._conversations$.value.filter(c => c.ProjectID && UUIDsEqual(c.ProjectID, id));
1276
1506
  for (const conv of directConversations) {
1277
1507
  if (!contextUser?.ID || !conv.UserID || this.CanEditConversation(conv, contextUser.ID)) {
@@ -1288,21 +1518,27 @@ export class ConversationEngine extends BaseEngine {
1288
1518
  // RESTRICT foreign key with no ON DELETE clause, so the delete below would then fail
1289
1519
  // with a raw constraint message, about a row the user is not allowed to know exists.
1290
1520
  //
1291
- // The read carries NO ownership clause, deliberately. Deleting a folder needs
1292
- // CanDelete on the entity, which the UI role does not hold; the roles that do also
1293
- // hold unfiltered read, which makes them exempt from the row-level filter — so this
1294
- // read returns the complete child set for every principal that can actually reach
1295
- // here. Should a deployment grant delete to a filtered role anyway, the server still
1296
- // narrows the read, and step 3's guard turns the resulting FK failure into something
1297
- // legible rather than "Failed to save project".
1521
+ // The read carries no ownership clause; the server narrows it to what the caller
1522
+ // may read. A subfolder another user owns may refuse the move (only its owner moves
1523
+ // it, and a row-filtered caller writes only their own folders): that one is left in
1524
+ // place, and the server's folder delete moves it, as the system user and in the
1525
+ // delete's transaction, once the caller's Delete permission and row filter pass. On a
1526
+ // server without that, the delete below fails on the foreign key and step 3's guard
1527
+ // explains it.
1298
1528
  const childFolders = await this.readChildFolders(id, contextUser);
1299
1529
  if (childFolders.length > 0) {
1300
1530
  this._selfMutating = true;
1301
1531
  try {
1302
1532
  for (const child of childFolders) {
1533
+ const previousParentId = child.ParentID;
1303
1534
  child.ParentID = newParentId;
1304
1535
  const saved = await child.Save();
1305
1536
  if (!saved) {
1537
+ const ownedByOther = !!child.OwnerUserID && !!contextUser?.ID && !UUIDsEqual(child.OwnerUserID, contextUser.ID);
1538
+ if (ownedByOther) {
1539
+ child.ParentID = previousParentId; // left for the server's folder delete
1540
+ continue;
1541
+ }
1306
1542
  throw new Error(child.LatestResult?.CompleteMessage || 'Failed to reparent subfolder');
1307
1543
  }
1308
1544
  }
@@ -1390,6 +1626,11 @@ export class ConversationEngine extends BaseEngine {
1390
1626
  conversation.Name = name;
1391
1627
  conversation.EnvironmentID = environmentId;
1392
1628
  conversation.UserID = contextUser.ID;
1629
+ const resolvedTypeId = options?.typeId ??
1630
+ this.ResolveConversationTypeID(options?.typeCode ??
1631
+ (options?.anchorType ? CONVERSATION_TYPE_CODES.COMMENT : CONVERSATION_TYPE_CODES.CHAT)) ??
1632
+ BUILT_IN_CONVERSATION_TYPE_IDS.CHAT;
1633
+ conversation.TypeID = resolvedTypeId;
1393
1634
  if (description)
1394
1635
  conversation.Description = description;
1395
1636
  if (projectId)
@@ -1593,6 +1834,9 @@ export class ConversationEngine extends BaseEngine {
1593
1834
  conversation.EnvironmentID = this._lastEnvironmentId;
1594
1835
  }
1595
1836
  conversation.UserID = contextUser.ID;
1837
+ conversation.TypeID =
1838
+ this.ResolveConversationTypeID(CONVERSATION_TYPE_CODES.COMMENT) ??
1839
+ BUILT_IN_CONVERSATION_TYPE_IDS.COMMENT;
1596
1840
  conversation.ApplicationScope = 'Global';
1597
1841
  conversation.LinkedEntityID = params.linkedEntityId;
1598
1842
  conversation.LinkedRecordID = params.linkedRecordId;
@@ -1602,12 +1846,40 @@ export class ConversationEngine extends BaseEngine {
1602
1846
  if (params.defaultAgentId !== undefined) {
1603
1847
  conversation.DefaultAgentID = params.defaultAgentId;
1604
1848
  }
1849
+ const requestedCommentTypeId = params.commentTypeId ??
1850
+ (params.commentTypeCode ? this.ResolveCommentTypeID(params.commentTypeCode) : null);
1605
1851
  this._selfMutating = true;
1606
1852
  try {
1607
1853
  const saved = await conversation.Save();
1608
1854
  if (!saved) {
1609
1855
  throw new Error(conversation.LatestResult?.CompleteMessage || conversation.LatestResult?.Message || 'Failed to create anchored conversation');
1610
1856
  }
1857
+ if (requestedCommentTypeId &&
1858
+ !UUIDsEqual(requestedCommentTypeId, BUILT_IN_COMMENT_TYPE_IDS.COMMENT)) {
1859
+ const isaComment = conversation.ISAChild;
1860
+ if (isaComment) {
1861
+ isaComment.CommentTypeID = requestedCommentTypeId;
1862
+ const commentSaved = await isaComment.Save();
1863
+ if (!commentSaved) {
1864
+ throw new Error(isaComment.LatestResult?.CompleteMessage ||
1865
+ isaComment.LatestResult?.Message ||
1866
+ 'Failed to update comment type on anchored conversation');
1867
+ }
1868
+ }
1869
+ else {
1870
+ const commentObj = await md.GetEntityObject('MJ: Comments', contextUser);
1871
+ const loadedComment = await commentObj.Load(conversation.ID);
1872
+ if (loadedComment) {
1873
+ commentObj.CommentTypeID = requestedCommentTypeId;
1874
+ const commentSaved = await commentObj.Save();
1875
+ if (!commentSaved) {
1876
+ throw new Error(commentObj.LatestResult?.CompleteMessage ||
1877
+ commentObj.LatestResult?.Message ||
1878
+ 'Failed to update comment type on anchored conversation');
1879
+ }
1880
+ }
1881
+ }
1882
+ }
1611
1883
  }
1612
1884
  finally {
1613
1885
  this._selfMutating = false;
@@ -1654,12 +1926,203 @@ export class ConversationEngine extends BaseEngine {
1654
1926
  }
1655
1927
  return conversation;
1656
1928
  }
1929
+ /**
1930
+ * Batch-loads `MJ: Comments` and `MJ: Field Suggestions` for the specified anchored
1931
+ * `conversationIds` in a single batched `RunViews` round trip, avoiding N+1 queries
1932
+ * when rendering forms with multiple comments and field suggestions.
1933
+ */
1934
+ async LoadAnchoredCommentsAndSuggestions(conversationIds, contextUser, provider, bypassCache = false) {
1935
+ const commentsByConversationId = new Map();
1936
+ const suggestionsByConversationId = new Map();
1937
+ const commentTypeCodeByConversationId = new Map();
1938
+ const cleanIds = conversationIds.map((id) => id?.trim()).filter((id) => !!id);
1939
+ if (cleanIds.length === 0) {
1940
+ return {
1941
+ CommentsByConversationId: commentsByConversationId,
1942
+ SuggestionsByConversationId: suggestionsByConversationId,
1943
+ CommentTypeCodeByConversationId: commentTypeCodeByConversationId,
1944
+ };
1945
+ }
1946
+ const md = provider ?? this.ProviderToUse;
1947
+ const entities = md?.Entities;
1948
+ const hasCommentEntities = !Array.isArray(entities) ||
1949
+ entities.length === 0 ||
1950
+ (entities.some((e) => e.Name === 'MJ: Comments') &&
1951
+ entities.some((e) => e.Name === 'MJ: Field Suggestions'));
1952
+ if (!hasCommentEntities) {
1953
+ return {
1954
+ CommentsByConversationId: commentsByConversationId,
1955
+ SuggestionsByConversationId: suggestionsByConversationId,
1956
+ CommentTypeCodeByConversationId: commentTypeCodeByConversationId,
1957
+ };
1958
+ }
1959
+ const rv = RunView.FromMetadataProvider(md);
1960
+ const inList = cleanIds.map((id) => `'${EscapeSQLString(id)}'`).join(',');
1961
+ const [commentsResult, suggestionsResult] = await rv.RunViews([
1962
+ {
1963
+ EntityName: 'MJ: Comments',
1964
+ ExtraFilter: `ID IN (${inList})`,
1965
+ ResultType: 'entity_object',
1966
+ BypassCache: bypassCache,
1967
+ },
1968
+ {
1969
+ EntityName: 'MJ: Field Suggestions',
1970
+ ExtraFilter: `ID IN (${inList})`,
1971
+ ResultType: 'entity_object',
1972
+ BypassCache: bypassCache,
1973
+ },
1974
+ ], contextUser);
1975
+ if (commentsResult && !commentsResult.Success) {
1976
+ throw new Error(commentsResult.ErrorMessage || 'Failed to load anchored MJ: Comments records');
1977
+ }
1978
+ if (suggestionsResult && !suggestionsResult.Success) {
1979
+ throw new Error(suggestionsResult.ErrorMessage || 'Failed to load anchored MJ: Field Suggestions records');
1980
+ }
1981
+ if (commentsResult?.Success && Array.isArray(commentsResult.Results)) {
1982
+ for (const rawComment of commentsResult.Results) {
1983
+ const normId = NormalizeUUID(rawComment.ID);
1984
+ commentsByConversationId.set(normId, rawComment);
1985
+ const ct = this.CommentTypeByID(rawComment.CommentTypeID);
1986
+ if (ct?.Code) {
1987
+ commentTypeCodeByConversationId.set(normId, ct.Code.trim().toUpperCase());
1988
+ }
1989
+ else if (UUIDsEqual(rawComment.CommentTypeID, BUILT_IN_COMMENT_TYPE_IDS.FIELD_SUGGESTION)) {
1990
+ commentTypeCodeByConversationId.set(normId, COMMENT_TYPE_CODES.FIELD_SUGGESTION);
1991
+ }
1992
+ else {
1993
+ commentTypeCodeByConversationId.set(normId, COMMENT_TYPE_CODES.COMMENT);
1994
+ }
1995
+ }
1996
+ }
1997
+ if (suggestionsResult?.Success && Array.isArray(suggestionsResult.Results)) {
1998
+ for (const rawSuggestion of suggestionsResult.Results) {
1999
+ const normId = NormalizeUUID(rawSuggestion.ID);
2000
+ suggestionsByConversationId.set(normId, rawSuggestion);
2001
+ commentTypeCodeByConversationId.set(normId, COMMENT_TYPE_CODES.FIELD_SUGGESTION);
2002
+ }
2003
+ }
2004
+ return {
2005
+ CommentsByConversationId: commentsByConversationId,
2006
+ SuggestionsByConversationId: suggestionsByConversationId,
2007
+ CommentTypeCodeByConversationId: commentTypeCodeByConversationId,
2008
+ };
2009
+ }
2010
+ /**
2011
+ * Creates a new `MJ: Field Suggestions` comment thread (saving `Conversation`, `Comment`,
2012
+ * and `FieldSuggestion` in a single IS-A chain transaction) and optionally posts the opening
2013
+ * rationale message into `MJ: Conversation Details`.
2014
+ */
2015
+ async CreateFieldSuggestion(params, contextUser) {
2016
+ const md = params.provider ?? this.ProviderToUse;
2017
+ const suggestion = await md.GetEntityObject('MJ: Field Suggestions', contextUser);
2018
+ suggestion.NewRecord();
2019
+ const cleanFieldName = params.fieldName.trim();
2020
+ const fallbackTitle = `${params.anchorMetadata?.anchorDisplayName || cleanFieldName} Suggestion`;
2021
+ suggestion.Name = (params.name?.trim() || fallbackTitle).slice(0, 255);
2022
+ if (params.environmentId) {
2023
+ suggestion.EnvironmentID = params.environmentId;
2024
+ }
2025
+ else if (this._lastEnvironmentId) {
2026
+ suggestion.EnvironmentID = this._lastEnvironmentId;
2027
+ }
2028
+ suggestion.UserID = contextUser.ID;
2029
+ suggestion.TypeID =
2030
+ this.ResolveConversationTypeID(CONVERSATION_TYPE_CODES.COMMENT) ??
2031
+ BUILT_IN_CONVERSATION_TYPE_IDS.COMMENT;
2032
+ suggestion.CommentTypeID =
2033
+ this.ResolveCommentTypeID(COMMENT_TYPE_CODES.FIELD_SUGGESTION) ??
2034
+ BUILT_IN_COMMENT_TYPE_IDS.FIELD_SUGGESTION;
2035
+ suggestion.ApplicationScope = 'Global';
2036
+ suggestion.LinkedEntityID = params.linkedEntityId;
2037
+ suggestion.LinkedRecordID = params.linkedRecordId;
2038
+ suggestion.AnchorType = 'Field';
2039
+ suggestion.AnchorKey = cleanFieldName;
2040
+ suggestion.AnchorMetadata = JSON.stringify({
2041
+ ...(params.anchorMetadata ?? {}),
2042
+ fieldName: cleanFieldName,
2043
+ });
2044
+ suggestion.SuggestedValue = params.suggestedValue;
2045
+ suggestion.Source = params.source ?? 'Agent';
2046
+ suggestion.Confidence = params.confidence ?? null;
2047
+ suggestion.AIPromptRunID = params.aiPromptRunId ?? null;
2048
+ suggestion.Outcome = null;
2049
+ this._selfMutating = true;
2050
+ try {
2051
+ const saved = await suggestion.Save();
2052
+ if (!saved) {
2053
+ throw new Error(suggestion.LatestResult?.CompleteMessage ||
2054
+ suggestion.LatestResult?.Message ||
2055
+ 'Failed to create field suggestion');
2056
+ }
2057
+ }
2058
+ finally {
2059
+ this._selfMutating = false;
2060
+ }
2061
+ let initialDetail = null;
2062
+ const messageText = params.initialMessage?.trim();
2063
+ if (messageText) {
2064
+ initialDetail = await md.GetEntityObject('MJ: Conversation Details', contextUser);
2065
+ initialDetail.NewRecord();
2066
+ initialDetail.ConversationID = suggestion.ID;
2067
+ initialDetail.UserID = contextUser.ID;
2068
+ initialDetail.Role = 'User';
2069
+ initialDetail.Message = messageText;
2070
+ const detailSaved = await initialDetail.Save();
2071
+ if (!detailSaved) {
2072
+ throw new Error(initialDetail.LatestResult?.CompleteMessage ||
2073
+ initialDetail.LatestResult?.Message ||
2074
+ 'Failed to save initial field suggestion message');
2075
+ }
2076
+ }
2077
+ return { Suggestion: suggestion, InitialDetail: initialDetail };
2078
+ }
2079
+ /**
2080
+ * Accepts a pending `MJ: Field Suggestions` row as `contextUser`. Server-side
2081
+ * `FieldSuggestionCommentDriver.OnAccept` writes `SuggestedValue` onto the target record
2082
+ * through a normal `Save()` as `contextUser` (enforcing RLS, FLS, and `Update` permission,
2083
+ * and recording `Record Changes`), then stamps `Outcome = 'Accepted'`, `IsResolved = true`,
2084
+ * `ResolvedByUserID`, and `ResolvedAt`.
2085
+ */
2086
+ async AcceptFieldSuggestion(suggestionId, contextUser, provider) {
2087
+ return this.transitionFieldSuggestionOutcome(suggestionId, 'Accepted', contextUser, provider);
2088
+ }
2089
+ /**
2090
+ * Rejects a pending `MJ: Field Suggestions` row as `contextUser`. Server-side
2091
+ * `FieldSuggestionCommentDriver.OnReject` verifies `contextUser` holds update rights on the
2092
+ * target record and field, then stamps `Outcome = 'Rejected'`, `IsResolved = true`,
2093
+ * `ResolvedByUserID`, and `ResolvedAt`.
2094
+ */
2095
+ async RejectFieldSuggestion(suggestionId, contextUser, provider) {
2096
+ return this.transitionFieldSuggestionOutcome(suggestionId, 'Rejected', contextUser, provider);
2097
+ }
2098
+ async transitionFieldSuggestionOutcome(suggestionId, outcome, contextUser, provider) {
2099
+ const md = provider ?? this.ProviderToUse;
2100
+ const suggestion = await md.GetEntityObject('MJ: Field Suggestions', contextUser);
2101
+ const loaded = await suggestion.Load(suggestionId);
2102
+ if (!loaded) {
2103
+ throw new Error(`Field suggestion ${suggestionId} not found`);
2104
+ }
2105
+ suggestion.Outcome = outcome;
2106
+ this._selfMutating = true;
2107
+ try {
2108
+ const saved = await suggestion.Save();
2109
+ if (!saved) {
2110
+ throw new Error(suggestion.LatestResult?.CompleteMessage ||
2111
+ suggestion.LatestResult?.Message ||
2112
+ `Failed to mark field suggestion as ${outcome}`);
2113
+ }
2114
+ }
2115
+ finally {
2116
+ this._selfMutating = false;
2117
+ }
2118
+ return suggestion;
2119
+ }
1657
2120
  /**
1658
2121
  * Computes open and resolved anchored comment counts across fields, sections, groups,
1659
2122
  * and contributions for a record, respecting FLS for `currentUser`.
1660
2123
  */
1661
- ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo) {
1662
- return ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo);
2124
+ ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo, commentTypeCodeByConversationId) {
2125
+ return ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo, commentTypeCodeByConversationId);
1663
2126
  }
1664
2127
  /**
1665
2128
  * Folds a conversation that was created OUTSIDE this engine (e.g. server-side by a
@@ -1710,7 +2173,7 @@ export class ConversationEngine extends BaseEngine {
1710
2173
  * @param id - The conversation ID to delete
1711
2174
  * @param contextUser - The current user context
1712
2175
  * @returns true if successful
1713
- * @throws Error if conversation not found or delete fails
2176
+ * @throws Error if conversation not found, the user may not delete it ({@link CanDeleteConversation}), or delete fails
1714
2177
  */
1715
2178
  async DeleteConversation(id, contextUser) {
1716
2179
  // Try to use the cached entity object first to avoid a DB round-trip
@@ -1724,6 +2187,10 @@ export class ConversationEngine extends BaseEngine {
1724
2187
  throw new Error('Conversation not found');
1725
2188
  }
1726
2189
  }
2190
+ // Refuse before the optimistic removal below, so a refused conversation never leaves the list.
2191
+ if (!this.CanDeleteConversation(conversation, contextUser)) {
2192
+ throw new Error(CONVERSATION_DELETE_REFUSED_REASON);
2193
+ }
1727
2194
  // Remove from the list and cache BEFORE calling Delete(), because
1728
2195
  // BaseEntity.Delete() calls NewRecord() which wipes the entity's fields.
1729
2196
  // Since the cached entity is the same object reference in the list,
@@ -1846,6 +2313,8 @@ export class ConversationEngine extends BaseEngine {
1846
2313
  }
1847
2314
  /**
1848
2315
  * Deletes multiple conversations in a batch operation with per-item error tracking.
2316
+ * Conversations the user may not delete ({@link CanDeleteConversation}) are reported
2317
+ * as failed, by name, without a delete.
1849
2318
  *
1850
2319
  * @param ids - Array of conversation IDs to delete
1851
2320
  * @param contextUser - The current user context
@@ -1894,6 +2363,10 @@ export class ConversationEngine extends BaseEngine {
1894
2363
  try {
1895
2364
  for (const entity of entitiesToDelete) {
1896
2365
  const name = entity.Name || 'Unknown';
2366
+ if (!this.CanDeleteConversation(entity, contextUser)) {
2367
+ failed.push({ ID: entity.ID, Name: name, Error: CONVERSATION_DELETE_REFUSED_REASON });
2368
+ continue;
2369
+ }
1897
2370
  try {
1898
2371
  // Use DeleteConversation which handles Load + Delete properly
1899
2372
  // and removes from list/cache on success
@@ -2930,10 +3403,85 @@ export class ConversationEngine extends BaseEngine {
2930
3403
  static FilterToScope(scope, rows) {
2931
3404
  return ConversationEngine.FilterRowsToBranchPath(rows, scope.BranchID, scope.Branches);
2932
3405
  }
3406
+ /**
3407
+ * Client-safe query descriptor loading `MJ: Conversation Details.ID` values visible in `scope`,
3408
+ * optionally narrowed to `candidateDetailIds`. Runs directly against `MJ: Conversation Details`
3409
+ * so server `PostRunView` security hooks apply and `ClientClauseScreen` never rejects a base-view subquery.
3410
+ */
3411
+ static BuildScopedDetailIdsQuery(scope, candidateDetailIds) {
3412
+ let filter = ConversationEngine.ScopeFilter(scope);
3413
+ if (candidateDetailIds && candidateDetailIds.length > 0) {
3414
+ const uniqueEscaped = [...new Set(candidateDetailIds.map((id) => id.trim()).filter(Boolean))]
3415
+ .map((id) => `'${EscapeSQLString(id)}'`);
3416
+ if (uniqueEscaped.length > 0) {
3417
+ filter = `(${filter}) AND [ID] IN (${uniqueEscaped.join(',')})`;
3418
+ }
3419
+ }
3420
+ return {
3421
+ EntityName: 'MJ: Conversation Details',
3422
+ ExtraFilter: filter,
3423
+ Fields: ['ID'],
3424
+ ResultType: 'simple',
3425
+ IgnoreMaxRows: true
3426
+ };
3427
+ }
3428
+ /**
3429
+ * Loads lowercased `MJ: Conversation Details.ID` values visible in `scope` via `RunView`, returning
3430
+ * `null` if the read fails so callers can fail closed. Avoids emitting `[__mj].[vwConversationDetails]`
3431
+ * subqueries from GraphQL client filters.
3432
+ */
3433
+ static async LoadScopedDetailIds(scope, provider, contextUser, candidateDetailIds) {
3434
+ if (candidateDetailIds) {
3435
+ const unique = candidateDetailIds.map((id) => id.trim()).filter(Boolean);
3436
+ if (unique.length === 0) {
3437
+ return new Set();
3438
+ }
3439
+ }
3440
+ const rv = RunView.FromMetadataProvider(provider);
3441
+ const res = await rv.RunView(ConversationEngine.BuildScopedDetailIdsQuery(scope, candidateDetailIds), contextUser);
3442
+ if (!res?.Success || !Array.isArray(res.Results)) {
3443
+ return null;
3444
+ }
3445
+ const ids = new Set();
3446
+ for (const row of res.Results) {
3447
+ const id = typeof row.ID === 'string' ? row.ID.trim().toLowerCase() : '';
3448
+ if (id) {
3449
+ ids.add(id);
3450
+ }
3451
+ }
3452
+ return ids;
3453
+ }
3454
+ /**
3455
+ * Filters artifact versions to those visible in `scope` (`{@link ArtifactVersionScopeFilter}` semantics):
3456
+ * keeps versions linked in any direction to a detail in `scopedDetailIds`, plus versions that have
3457
+ * no `MJ: Conversation Detail Artifacts` link at all.
3458
+ */
3459
+ static FilterArtifactVersionsByScope(versions, links, scopedDetailIds) {
3460
+ const allLinkedVersionIds = new Set();
3461
+ const scopedLinkedVersionIds = new Set();
3462
+ for (const link of links) {
3463
+ const versionId = typeof link.ArtifactVersionID === 'string' ? link.ArtifactVersionID.trim().toLowerCase() : '';
3464
+ if (!versionId)
3465
+ continue;
3466
+ allLinkedVersionIds.add(versionId);
3467
+ const detailId = typeof link.ConversationDetailID === 'string' ? link.ConversationDetailID.trim().toLowerCase() : '';
3468
+ if (detailId && scopedDetailIds.has(detailId)) {
3469
+ scopedLinkedVersionIds.add(versionId);
3470
+ }
3471
+ }
3472
+ return versions.filter((v) => {
3473
+ const id = typeof v.ID === 'string' ? v.ID.trim().toLowerCase() : '';
3474
+ return id ? (!allLinkedVersionIds.has(id) || scopedLinkedVersionIds.has(id)) : false;
3475
+ });
3476
+ }
2933
3477
  /**
2934
3478
  * Filter over MJ: Artifact Versions for the versions of one artifact visible in scope: versions
2935
3479
  * linked (in any direction) from a message on the path, and versions with no conversation link
2936
3480
  * at all.
3481
+ *
3482
+ * Note: server/internal callers only — GraphQL clients must use {@link BuildScopedDetailIdsQuery} +
3483
+ * {@link FilterArtifactVersionsByScope} because `ClientClauseScreen` blocks `[__mj].[vwConversationDetails]`
3484
+ * subqueries in client-supplied `ExtraFilter`s.
2937
3485
  */
2938
3486
  static ArtifactVersionScopeFilter(scope, artifactId) {
2939
3487
  const path = ConversationEngine.ScopeFilter(scope);