codeapp-js 0.2.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/AI/codeapp.agent.md +105 -0
  2. package/AI/skills/connections/SKILL.md +47 -0
  3. package/AI/skills/dataverse/SKILL.md +99 -0
  4. package/AI/skills/environment-variables/SKILL.md +89 -0
  5. package/AI/skills/frontend-design/SKILL.md +34 -0
  6. package/AI/skills/jira/SKILL.md +81 -0
  7. package/AI/skills/office365-groups/SKILL.md +61 -0
  8. package/AI/skills/office365-outlook/SKILL.md +52 -0
  9. package/AI/skills/office365-users/SKILL.md +78 -0
  10. package/AI/skills/sharepoint/SKILL.md +77 -0
  11. package/AI/skills/sql/SKILL.md +85 -0
  12. package/AI/skills/start/SKILL.md +46 -0
  13. package/AI/skills/teams/SKILL.md +55 -0
  14. package/codeApp/.power/schemas/appschemas/dataSourcesInfo.ts +6275 -0
  15. package/codeApp/.power/schemas/jira/jira.Schema.json +6903 -0
  16. package/codeApp/.power/schemas/keyvault/keyvault.Schema.json +1600 -0
  17. package/{examples/combined demo/.power/schemas/office365groups/office365groups.Schema.json → codeApp/.power/schemas/office365groups/office365groups.Schema.json} +2203 -2203
  18. package/codeApp/.power/schemas/teams/teams.Schema.json +11112 -0
  19. package/codeApp/dist/codeapp.js +103 -1043
  20. package/codeApp/dist/connectors/azureKeyvault.js +459 -0
  21. package/codeApp/dist/connectors/jira.js +1247 -0
  22. package/codeApp/dist/connectors/office365groups.js +642 -0
  23. package/codeApp/dist/connectors/office365users.js +513 -0
  24. package/codeApp/dist/connectors/outlook.js +1393 -0
  25. package/{examples/kanban/dist → codeApp/dist/connectors}/sharepoint.js +466 -339
  26. package/codeApp/dist/connectors/sql.js +149 -0
  27. package/codeApp/dist/connectors/teams.js +280 -0
  28. package/codeApp/dist/index.js +1 -1
  29. package/codeApp/dist/power-apps-data.js +725 -176
  30. package/codeApp/src/generated/index.ts +12 -0
  31. package/codeApp/src/generated/models/AzureKeyVaultModel.ts +107 -0
  32. package/codeApp/src/generated/models/JiraModel.ts +501 -0
  33. package/codeApp/src/generated/services/AzureKeyVaultService.ts +257 -0
  34. package/codeApp/src/generated/services/JiraService.ts +1124 -0
  35. package/examples/{kanban → apps/kanban}/dist/dataverse.js +94 -94
  36. package/examples/{kanban → apps/kanban}/dist/index.css +605 -605
  37. package/examples/{kanban → apps/kanban}/dist/index.html +21 -21
  38. package/examples/{kanban → apps/kanban}/dist/index.js +860 -860
  39. package/examples/{kanban → apps/kanban}/dist/office365groups.js +97 -97
  40. package/examples/apps/kanban/dist/office365users.js +451 -0
  41. package/examples/{kanban → apps/kanban}/dist/outlook.js +162 -162
  42. package/examples/{planning Poker/dist/power-apps-data.js → apps/kanban/dist/power-apps-data.js} +2953 -2953
  43. package/{dev files/sharepoint.js → examples/apps/kanban/dist/sharepoint.js} +195 -99
  44. package/examples/{kanban → apps/kanban}/power.config.json +35 -35
  45. package/examples/{planning Poker → apps/planning Poker}/additional files/customizations (tables).xml +6428 -6428
  46. package/examples/{planning Poker → apps/planning Poker}/additional files/dataverse-tables.json +165 -165
  47. package/examples/{planning Poker → apps/planning Poker}/additional files/readme.md +122 -122
  48. package/examples/{planning Poker → apps/planning Poker}/dist/dataverse.js +78 -78
  49. package/examples/{planning Poker → apps/planning Poker}/dist/index.html +198 -198
  50. package/examples/{planning Poker → apps/planning Poker}/dist/index.js +954 -954
  51. package/examples/{kanban/dist/power-apps-data.js → apps/planning Poker/dist/power-apps-data.js } +2953 -2953
  52. package/examples/{planning Poker → apps/planning Poker}/dist/styles.css +815 -815
  53. package/examples/{planning Poker → apps/planning Poker}/power.config.json +50 -50
  54. package/examples/{solution explorer → apps/solution explorer}/dist/codeapp.js +1098 -1098
  55. package/examples/{solution explorer → apps/solution explorer}/dist/index.html +80 -80
  56. package/examples/{solution explorer → apps/solution explorer}/dist/index.js +735 -735
  57. package/examples/{solution explorer → apps/solution explorer}/dist/styles.css +571 -571
  58. package/examples/{solution explorer → apps/solution explorer}/power.config.json +150 -150
  59. package/examples/{todo → apps/todo}/dist/dataverse.js +64 -64
  60. package/examples/{todo → apps/todo}/dist/index.html +75 -75
  61. package/examples/{todo → apps/todo}/dist/index.js +8 -8
  62. package/examples/{todo → apps/todo}/dist/power-apps-data.js +2953 -2953
  63. package/examples/{todo → apps/todo}/dist/renderer.js +375 -375
  64. package/examples/{todo → apps/todo}/dist/styles.css +691 -691
  65. package/examples/{todo → apps/todo}/power.config.json +34 -34
  66. package/examples/combined demo/.power/schemas/appschemas/dataSourcesInfo.ts +6275 -7830
  67. package/examples/combined demo/.power/schemas/jira/jira.Schema.json +6903 -0
  68. package/examples/combined demo/.power/schemas/keyvault/keyvault.Schema.json +1600 -0
  69. package/examples/combined demo/.power/schemas/teams/teams.Schema.json +11112 -0
  70. package/examples/combined demo/dist/codeapp.js +394 -1098
  71. package/examples/combined demo/dist/index.html +29 -511
  72. package/examples/combined demo/dist/index.js +490 -470
  73. package/examples/combined demo/dist/office365users.js +513 -0
  74. package/examples/combined demo/dist/outlook.js +1393 -0
  75. package/examples/combined demo/dist/power-apps-data.js +3079 -3006
  76. package/examples/combined demo/dist/styles.css +483 -0
  77. package/examples/combined demo/power.config.json +33 -42
  78. package/examples/combined demo/src/generated/index.ts +12 -14
  79. package/examples/combined demo/src/generated/models/AzureKeyVaultModel.ts +107 -0
  80. package/examples/combined demo/src/generated/models/JiraModel.ts +501 -0
  81. package/examples/combined demo/src/generated/services/AzureKeyVaultService.ts +257 -0
  82. package/examples/combined demo/src/generated/services/JiraService.ts +1124 -0
  83. package/examples/dataverse Demo/dist/codeapp.js +394 -1085
  84. package/examples/{outlook Demo2/OutlookDemo_1_0_0_1.zip → dataverse Demo/dist/icon-512.png} +0 -0
  85. package/examples/dataverse Demo/dist/index.html +146 -54
  86. package/examples/dataverse Demo/dist/index.js +693 -83
  87. package/examples/dataverse Demo/dist/power-apps-data.js +3079 -2911
  88. package/examples/dataverse Demo/dist/styles.css +528 -0
  89. package/examples/dataverse Demo/power.config.json +41 -35
  90. package/examples/dataverse Demo/readme.md +79 -79
  91. package/examples/groups Demo/dist/codeapp.js +394 -1085
  92. package/examples/groups Demo/dist/icon-512.png +0 -0
  93. package/examples/groups Demo/dist/index.html +21 -25
  94. package/examples/groups Demo/dist/index.js +304 -113
  95. package/examples/groups Demo/dist/office365groups.js +642 -0
  96. package/examples/groups Demo/dist/power-apps-data.js +3079 -2911
  97. package/examples/groups Demo/dist/styles.css +509 -0
  98. package/examples/groups Demo/power.config.json +25 -25
  99. package/examples/myProfile/dist/codeapp.js +398 -0
  100. package/examples/myProfile/dist/index.html +21 -184
  101. package/examples/myProfile/dist/index.js +324 -141
  102. package/examples/myProfile/dist/office365users.js +517 -169
  103. package/examples/myProfile/dist/power-apps-data.js +3080 -2953
  104. package/examples/myProfile/dist/styles.css +458 -0
  105. package/examples/myProfile/power.config.json +24 -23
  106. package/examples/outlook Demo/dist/codeapp.js +394 -1085
  107. package/examples/outlook Demo/dist/index.html +150 -35
  108. package/examples/outlook Demo/dist/index.js +516 -170
  109. package/examples/outlook Demo/dist/outlook.js +1393 -121
  110. package/examples/outlook Demo/dist/power-apps-data.js +3079 -2911
  111. package/examples/outlook Demo/dist/styles.css +408 -84
  112. package/examples/outlook Demo/power.config.json +24 -23
  113. package/examples/outlook Demo/readme.md +92 -82
  114. package/examples/sharePoint Demo/dist/codeapp.js +394 -1085
  115. package/examples/sharePoint Demo/dist/icon-512.png +0 -0
  116. package/examples/sharePoint Demo/dist/index.html +22 -255
  117. package/examples/sharePoint Demo/dist/index.js +899 -262
  118. package/examples/sharePoint Demo/dist/power-apps-data.js +3079 -2911
  119. package/examples/sharePoint Demo/dist/sharepoint.js +466 -0
  120. package/examples/sharePoint Demo/dist/styles.css +587 -0
  121. package/examples/sharePoint Demo/power.config.json +23 -22
  122. package/package.json +1 -1
  123. package/readme.md +479 -61
  124. package/.github/instructions/wyattdave.instructions.md +0 -39
  125. package/.vscode/settings.json +0 -6
  126. package/dev files/dataverse.js +0 -105
  127. package/dev files/office365groups.js +0 -65
  128. package/dev files/office365users.js +0 -169
  129. package/dev files/outlook.js +0 -330
  130. package/examples/combined demo/.power/schemas/office365/office365.Schema.json +0 -21098
  131. package/examples/combined demo/.power/schemas/office365users/office365users.Schema.json +0 -2094
  132. package/examples/kanban/agent/decision-log.md +0 -9
  133. package/examples/kanban/agent/mockup-01-editorial-glass.html +0 -159
  134. package/examples/kanban/agent/mockup-02-dark-rail.html +0 -147
  135. package/examples/kanban/agent/mockup-03-paper-grid.html +0 -114
  136. package/examples/kanban/agent/mockup-04-neon-minimal.html +0 -141
  137. package/examples/kanban/agent/mockup-05-mono-architect.html +0 -119
  138. package/examples/kanban/dist/environmentVar.js +0 -55
  139. package/examples/kanban/dist/office365users.js +0 -169
  140. package/examples/kanban/src/generated/index.ts +0 -14
  141. package/examples/outlook Demo2/agent/decision-log.md +0 -7
  142. package/examples/outlook Demo2/dist/codeapp.js +0 -1334
  143. package/examples/outlook Demo2/dist/index.html +0 -98
  144. package/examples/outlook Demo2/dist/index.js +0 -346
  145. package/examples/outlook Demo2/dist/styles.css +0 -639
  146. package/examples/outlook Demo2/power.config.json +0 -23
  147. package/examples/planning Poker/.vscode/settings.json +0 -5
  148. package/examples/sharePoint Demo/agent/decision-log.md +0 -17
  149. package/examples/solution explorer/agent/decision-log.md +0 -27
  150. package/examples/solution explorer/agent/mockup-01-swiss-grid.html +0 -452
  151. package/examples/solution explorer/agent/mockup-02-dark-glass.html +0 -496
  152. package/examples/solution explorer/agent/mockup-03-paper-console.html +0 -510
  153. package/examples/solution explorer/agent/mockup-04-neon-noir.html +0 -546
  154. package/examples/solution explorer/agent/mockup-05-zen-garden.html +0 -534
  155. package/examples/solution explorer/dist/power-apps-data.js +0 -3007
  156. package/scripts/build-power-sdk.mjs +0 -69
  157. /package/{examples/kanban → codeApp}/src/generated/models/Office365GroupsModel.ts +0 -0
  158. /package/{examples/kanban → codeApp}/src/generated/models/Office365OutlookModel.ts +0 -0
  159. /package/{examples/kanban → codeApp}/src/generated/models/Office365UsersModel.ts +0 -0
  160. /package/{examples/kanban → codeApp}/src/generated/services/Office365GroupsService.ts +0 -0
  161. /package/{examples/kanban → codeApp}/src/generated/services/Office365OutlookService.ts +0 -0
  162. /package/{examples/kanban → codeApp}/src/generated/services/Office365UsersService.ts +0 -0
  163. /package/{dev files → examples/apps/kanban/dist}/environmentVar.js +0 -0
  164. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/index.ts +0 -0
  165. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/models/Office365GroupsModel.ts +0 -0
  166. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/models/Office365OutlookModel.ts +0 -0
  167. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/models/Office365UsersModel.ts +0 -0
  168. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/services/Office365GroupsService.ts +0 -0
  169. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/services/Office365OutlookService.ts +0 -0
  170. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/services/Office365UsersService.ts +0 -0
  171. /package/examples/{planning Poker → apps/planning Poker}/additional files/AgilePoker_1_0_0_1.zip +0 -0
  172. /package/examples/{planning Poker → apps/planning Poker}/additional files/PokerTables_1_0_0_1.zip +0 -0
  173. /package/examples/{outlook Demo2 → apps/solution explorer}/dist/icon-512.png +0 -0
  174. /package/examples/{outlook Demo2 → apps/solution explorer}/dist/power-apps-data.js +0 -0
  175. /package/examples/{todo → apps/todo}/dist/icon192.png +0 -0
  176. /package/examples/{solution explorer → combined demo}/dist/icon-512.png +0 -0
@@ -1,860 +1,860 @@
1
-
2
- import { registerTable, listItems, createItem, updateItem, deleteItem } from './dataverse.js';
3
-
4
- const sBoardPrefix = 'worktracker|';
5
- const sCacheKey = 'workTrackerTasksCache';
6
-
7
- const aColumns = [
8
- { id: 'backlog', title: 'Backlog', color: '#7c8aa5' },
9
- { id: 'ready', title: 'Ready', color: '#395cff' },
10
- { id: 'inprogress', title: 'In Progress', color: '#f59e0b' },
11
- { id: 'complete', title: 'Complete', color: '#13b981' },
12
- { id: 'rejected', title: 'Rejected', color: '#ef476f' }
13
- ];
14
-
15
- const aSeedTasks = [
16
- {
17
- id: createId(),
18
- title: 'Prepare monthly planning summary',
19
- description: 'Pull together the current priorities, risks, and proposed actions for the next review.',
20
- status: 'backlog',
21
- priority: 'High',
22
- owner: 'You',
23
- dueDate: '2026-03-18',
24
- estimate: '3h',
25
- progress: 10,
26
- tags: ['Planning', 'Reporting']
27
- },
28
- {
29
- id: createId(),
30
- title: 'Review ready-for-build requests',
31
- description: 'Check scope, confirm acceptance criteria, and mark the next best work items for execution.',
32
- status: 'ready',
33
- priority: 'Medium',
34
- owner: 'You',
35
- dueDate: '2026-03-16',
36
- estimate: '2h',
37
- progress: 35,
38
- tags: ['Triage']
39
- },
40
- {
41
- id: createId(),
42
- title: 'Build stakeholder update deck',
43
- description: 'Turn the latest work highlights into a concise narrative for the weekly stakeholder sync.',
44
- status: 'inprogress',
45
- priority: 'High',
46
- owner: 'You',
47
- dueDate: '2026-03-15',
48
- estimate: '5h',
49
- progress: 68,
50
- tags: ['Comms', 'Weekly']
51
- },
52
- {
53
- id: createId(),
54
- title: 'Close completed support actions',
55
- description: 'Archive the delivered improvements and note what changed for future reference.',
56
- status: 'complete',
57
- priority: 'Low',
58
- owner: 'You',
59
- dueDate: '2026-03-12',
60
- estimate: '1h',
61
- progress: 100,
62
- tags: ['Ops']
63
- },
64
- {
65
- id: createId(),
66
- title: 'Drop duplicate reporting request',
67
- description: 'The request overlaps with an existing dashboard and no longer adds useful value.',
68
- status: 'rejected',
69
- priority: 'Low',
70
- owner: 'You',
71
- dueDate: '2026-03-11',
72
- estimate: '30m',
73
- progress: 0,
74
- tags: ['Archive']
75
- }
76
- ];
77
-
78
- const oState = {
79
- tasks: [],
80
- search: '',
81
- statusFilter: 'all',
82
- draggedTaskId: '',
83
- editingTaskId: '',
84
- syncMessage: 'Connecting to Dataverse task table...'
85
- };
86
-
87
- const iInitialConnectionRetries = 4;
88
- const iInitialConnectionRetryDelayMs = 500;
89
-
90
- function createId() {
91
- return 'task-' + Math.random().toString(36).slice(2, 10);
92
- }
93
-
94
- function getSeedTasks() {
95
- return aSeedTasks.map((oTask) => ({
96
- ...oTask,
97
- id: createId(),
98
- tags: Array.isArray(oTask.tags) ? [...oTask.tags] : []
99
- }));
100
- }
101
-
102
- function loadCachedTasks() {
103
- const sSaved = localStorage.getItem(sCacheKey);
104
- if (!sSaved) {
105
- return [];
106
- }
107
-
108
- try {
109
- const aParsed = JSON.parse(sSaved);
110
- return Array.isArray(aParsed) ? aParsed : [];
111
- } catch (oError) {
112
- console.error('Failed to read cached tasks:', oError);
113
- return [];
114
- }
115
- }
116
-
117
- function saveCachedTasks() {
118
- localStorage.setItem(sCacheKey, JSON.stringify(oState.tasks));
119
- }
120
-
121
- function isValidStatus(sStatus) {
122
- return aColumns.some((oColumn) => oColumn.id === sStatus);
123
- }
124
-
125
- function clampProgress(iValue) {
126
- return Math.max(0, Math.min(100, Number(iValue) || 0));
127
- }
128
-
129
- function mapPriorityToCode(sPriority) {
130
- if (sPriority === 'High') {
131
- return 2;
132
- }
133
- if (sPriority === 'Low') {
134
- return 0;
135
- }
136
- return 1;
137
- }
138
-
139
- function mapPriorityFromCode(iCode) {
140
- if (Number(iCode) === 2) {
141
- return 'High';
142
- }
143
- if (Number(iCode) === 0) {
144
- return 'Low';
145
- }
146
- return 'Medium';
147
- }
148
-
149
- function normalizeDate(sDateValue) {
150
- if (!sDateValue) {
151
- return '';
152
- }
153
- return String(sDateValue).slice(0, 10);
154
- }
155
-
156
- function toDataverseDateValue(sDateValue) {
157
- if (!sDateValue) {
158
- return null;
159
- }
160
- return sDateValue + 'T12:00:00Z';
161
- }
162
-
163
- function parseBoardMeta(sCategory) {
164
- if (!sCategory || !String(sCategory).startsWith(sBoardPrefix)) {
165
- return null;
166
- }
167
-
168
- try {
169
- return JSON.parse(String(sCategory).slice(sBoardPrefix.length));
170
- } catch (oError) {
171
- console.error('Failed to parse board metadata:', oError);
172
- return null;
173
- }
174
- }
175
-
176
- function buildBoardMetaString(oTask) {
177
- const oMeta = {
178
- status: isValidStatus(oTask.status) ? oTask.status : 'backlog',
179
- owner: String(oTask.owner || 'You').slice(0, 80),
180
- estimate: String(oTask.estimate || '').slice(0, 30),
181
- tags: Array.isArray(oTask.tags) ? oTask.tags.slice(0, 8).map((sTag) => String(sTag).slice(0, 24)) : []
182
- };
183
-
184
- let sValue = sBoardPrefix + JSON.stringify(oMeta);
185
-
186
- while (sValue.length > 240 && oMeta.tags.length > 0) {
187
- oMeta.tags.pop();
188
- sValue = sBoardPrefix + JSON.stringify(oMeta);
189
- }
190
-
191
- return sValue.slice(0, 240);
192
- }
193
-
194
- function mapDataverseTaskToBoardTask(oRecord) {
195
- const oMeta = parseBoardMeta(oRecord.category) || {};
196
- const sTaskId = oRecord.activityid || oRecord.taskid || createId();
197
-
198
- return {
199
- id: sTaskId,
200
- title: oRecord.subject || 'Untitled task',
201
- description: oRecord.description || '',
202
- status: isValidStatus(oMeta.status) ? oMeta.status : 'backlog',
203
- priority: mapPriorityFromCode(oRecord.prioritycode),
204
- owner: oMeta.owner || 'You',
205
- dueDate: normalizeDate(oRecord.scheduledend),
206
- estimate: oMeta.estimate || '',
207
- progress: clampProgress(oRecord.percentcomplete),
208
- tags: Array.isArray(oMeta.tags) ? oMeta.tags : []
209
- };
210
- }
211
-
212
- function buildDataverseTaskPayload(oTaskInput) {
213
- const oPayload = {
214
- subject: oTaskInput.title,
215
- description: oTaskInput.description,
216
- prioritycode: mapPriorityToCode(oTaskInput.priority),
217
- percentcomplete: clampProgress(oTaskInput.progress),
218
- category: buildBoardMetaString(oTaskInput)
219
- };
220
-
221
- if (oTaskInput.dueDate) {
222
- oPayload.scheduledend = toDataverseDateValue(oTaskInput.dueDate);
223
- } else {
224
- oPayload.scheduledend = null;
225
- }
226
-
227
- return oPayload;
228
- }
229
-
230
- async function loadDataverseTasks() {
231
- const oResult = await listItems('tasks', 'activityid', {
232
- filter: "startswith(category, '" + sBoardPrefix + "')",
233
- select: ['activityid', 'subject', 'description', 'prioritycode', 'scheduledend', 'percentcomplete', 'category', 'modifiedon'],
234
- orderBy: ['modifiedon desc'],
235
- top: 200
236
- });
237
-
238
- return (oResult.entities || []).map((oRecord) => mapDataverseTaskToBoardTask(oRecord));
239
- }
240
-
241
- async function refreshBoardFromDataverse(sMessage) {
242
- const aTasks = await loadDataverseTasks();
243
- oState.tasks = aTasks;
244
- oState.syncMessage = sMessage || 'Synced with Dataverse task table.';
245
- saveCachedTasks();
246
- }
247
-
248
- async function createBoardTask(oTaskInput) {
249
- await createItem('tasks', 'activityid', buildDataverseTaskPayload(oTaskInput));
250
- }
251
-
252
- async function updateBoardTask(sTaskId, oTaskInput) {
253
- await updateItem('tasks', 'activityid', sTaskId, buildDataverseTaskPayload(oTaskInput));
254
- }
255
-
256
- async function deleteBoardTask(sTaskId) {
257
- await deleteItem('tasks', 'activityid', sTaskId);
258
- }
259
-
260
- function getFilteredTasks() {
261
- return oState.tasks.filter((oTask) => {
262
- const bSearchMatch = !oState.search || [oTask.title, oTask.description, oTask.owner, ...(oTask.tags || [])]
263
- .join(' ')
264
- .toLowerCase()
265
- .includes(oState.search.toLowerCase());
266
-
267
- const bStatusMatch = oState.statusFilter === 'all' || oTask.status === oState.statusFilter;
268
- return bSearchMatch && bStatusMatch;
269
- });
270
- }
271
-
272
- function getTasksByColumn(sColumnId) {
273
- return getFilteredTasks().filter((oTask) => oTask.status === sColumnId);
274
- }
275
-
276
- function countOpenTasks() {
277
- return oState.tasks.filter((oTask) => oTask.status !== 'complete' && oTask.status !== 'rejected').length;
278
- }
279
-
280
- function countInProgressTasks() {
281
- return oState.tasks.filter((oTask) => oTask.status === 'inprogress').length;
282
- }
283
-
284
- function countCompletedTasks() {
285
- return oState.tasks.filter((oTask) => oTask.status === 'complete').length;
286
- }
287
-
288
- function getFocusScore() {
289
- const iTotal = oState.tasks.length || 1;
290
- const iDoneWeight = countCompletedTasks() * 100;
291
- const iActiveWeight = countInProgressTasks() * 60;
292
- const iReadyWeight = oState.tasks.filter((oTask) => oTask.status === 'ready').length * 30;
293
- return Math.min(100, Math.round((iDoneWeight + iActiveWeight + iReadyWeight) / iTotal));
294
- }
295
-
296
- function getPriorityBadgeClass(sPriority) {
297
- if (sPriority === 'High') {
298
- return 'badge badgePriorityHigh';
299
- }
300
- if (sPriority === 'Medium') {
301
- return 'badge badgePriorityMedium';
302
- }
303
- return 'badge badgePriorityLow';
304
- }
305
-
306
- function escapeHtml(sValue) {
307
- return String(sValue)
308
- .replace(new RegExp('&', 'g'), '&')
309
- .replace(new RegExp('<', 'g'), '&lt;')
310
- .replace(new RegExp('>', 'g'), '&gt;')
311
- .replace(new RegExp('\"', 'g'), '&quot;')
312
- .replace(new RegExp("'", 'g'), '&#39;');
313
- }
314
-
315
- function delay(iMilliseconds) {
316
- return new Promise((resolve) => {
317
- window.setTimeout(resolve, iMilliseconds);
318
- });
319
- }
320
-
321
- function waitForHostLoad() {
322
- if (document.readyState === 'complete') {
323
- return Promise.resolve();
324
- }
325
-
326
- return new Promise((resolve) => {
327
- window.addEventListener('load', resolve, { once: true });
328
- });
329
- }
330
-
331
- function isHostStartupError(oError) {
332
- const sMessage = String(oError && oError.message ? oError.message : oError || '').toLowerCase();
333
- return sMessage.includes('metadata')
334
- || sMessage.includes('runtime')
335
- || sMessage.includes('connection')
336
- || sMessage.includes('initial')
337
- || sMessage.includes('token')
338
- || sMessage.includes('postmessage');
339
- }
340
-
341
- function getConnectionErrorMessage(oError) {
342
- const sMessage = String(oError && oError.message ? oError.message : oError || 'Unknown Dataverse error');
343
-
344
- if (isHostStartupError(oError)) {
345
- return 'Dataverse connection is only available after the Power Apps Code App host finishes initializing: ' + sMessage;
346
- }
347
-
348
- return 'Dataverse load failed: ' + sMessage;
349
- }
350
-
351
- async function connectToDataverseOnStartup() {
352
- let oLastError = null;
353
-
354
- for (let iAttempt = 0; iAttempt < iInitialConnectionRetries; iAttempt += 1) {
355
- try {
356
- await refreshBoardFromDataverse('Connected to Dataverse task table.');
357
- if (oState.tasks.length === 0) {
358
- oState.syncMessage = 'No board tasks found in Dataverse yet.';
359
- }
360
- return;
361
- } catch (oError) {
362
- oLastError = oError;
363
-
364
- if (!isHostStartupError(oError) || iAttempt === iInitialConnectionRetries - 1) {
365
- break;
366
- }
367
-
368
- oState.syncMessage = 'Waiting for Power Apps Code App host to initialize Dataverse connection...';
369
- renderApp();
370
- await delay(iInitialConnectionRetryDelayMs * (iAttempt + 1));
371
- }
372
- }
373
-
374
- throw oLastError;
375
- }
376
-
377
- function renderCard(oTask) {
378
- const sTags = (oTask.tags || []).join(', ') || 'None';
379
- const iProgress = clampProgress(oTask.progress);
380
-
381
- return `
382
- <article class="card" draggable="true" data-task-id="${escapeHtml(oTask.id)}">
383
- <div class="cardHeader">
384
- <h3 class="cardTitle">${escapeHtml(oTask.title)}</h3>
385
- <span class="${getPriorityBadgeClass(oTask.priority)}">${escapeHtml(oTask.priority)}</span>
386
- </div>
387
- <p class="cardDescription">${escapeHtml(oTask.description)}</p>
388
- <div class="progressBar">
389
- <div class="progressValue" style="width: ${iProgress}%"></div>
390
- </div>
391
- <div class="cardMetaGrid">
392
- <div class="metaItem">
393
- <span class="metaLabel">Owner</span>
394
- <span class="metaValue">${escapeHtml(oTask.owner)}</span>
395
- </div>
396
- <div class="metaItem">
397
- <span class="metaLabel">Due</span>
398
- <span class="metaValue">${escapeHtml(oTask.dueDate || 'Not set')}</span>
399
- </div>
400
- <div class="metaItem">
401
- <span class="metaLabel">Estimate</span>
402
- <span class="metaValue">${escapeHtml(oTask.estimate || 'Not set')}</span>
403
- </div>
404
- <div class="metaItem">
405
- <span class="metaLabel">Tags</span>
406
- <span class="metaValue">${escapeHtml(sTags)}</span>
407
- </div>
408
- </div>
409
- <div class="cardFooter">
410
- <span>${escapeHtml(String(iProgress))}% complete</span>
411
- <button class="ghostButton" type="button" data-edit-task-id="${escapeHtml(oTask.id)}">Edit</button>
412
- </div>
413
- </article>
414
- `;
415
- }
416
-
417
- function renderColumn(oColumn) {
418
- const aTasks = getTasksByColumn(oColumn.id);
419
- const sCards = aTasks.length
420
- ? aTasks.map((oTask) => renderCard(oTask)).join('')
421
- : '<div class="emptyState">Drop work here or add a new task.</div>';
422
-
423
- return `
424
- <section class="column" aria-label="${escapeHtml(oColumn.title)}">
425
- <div class="columnHeader">
426
- <div class="columnTitleWrap">
427
- <span class="columnDot" style="background:${escapeHtml(oColumn.color)}"></span>
428
- <h2 class="columnTitle">${escapeHtml(oColumn.title)}</h2>
429
- </div>
430
- <span class="columnCount">${aTasks.length}</span>
431
- </div>
432
- <div class="columnBody" data-column-id="${escapeHtml(oColumn.id)}">
433
- ${sCards}
434
- </div>
435
- </section>
436
- `;
437
- }
438
-
439
- function renderApp() {
440
- const eApp = document.getElementById('app');
441
- if (!eApp) {
442
- return;
443
- }
444
-
445
- eApp.innerHTML = `
446
- <div class="shell">
447
- <section class="hero">
448
- <div>
449
- <h1 class="heroTitle">Track work on a clean paper-grid board.</h1>
450
- <p class="heroCopy">A quiet editorial kanban for backlog, ready, in progress, complete, and rejected work. Drag cards between columns, keep the important details visible, and save the board into Dataverse task records.</p>
451
- </div>
452
- <div class="heroMeta">
453
- <div class="metricCard">
454
- <span class="metricLabel">Open tasks</span>
455
- <strong class="metricValue">${countOpenTasks()}</strong>
456
- </div>
457
- <div class="metricCard">
458
- <span class="metricLabel">In progress</span>
459
- <strong class="metricValue">${countInProgressTasks()}</strong>
460
- </div>
461
- <div class="metricCard">
462
- <span class="metricLabel">Completed</span>
463
- <strong class="metricValue">${countCompletedTasks()}</strong>
464
- </div>
465
- <div class="metricCard">
466
- <span class="metricLabel">Focus score</span>
467
- <strong class="metricValue">${getFocusScore()}%</strong>
468
- </div>
469
- </div>
470
- </section>
471
-
472
- <section class="toolbar">
473
- <div class="toolbarGroup">
474
- <input id="searchInput" class="toolbarInput" type="search" placeholder="Search title, description, owner, or tags" value="${escapeHtml(oState.search)}">
475
- <select id="statusFilter" class="toolbarSelect" aria-label="Filter tasks by status">
476
- <option value="all"${oState.statusFilter === 'all' ? ' selected' : ''}>All statuses</option>
477
- ${aColumns.map((oColumn) => `<option value="${escapeHtml(oColumn.id)}"${oState.statusFilter === oColumn.id ? ' selected' : ''}>${escapeHtml(oColumn.title)}</option>`).join('')}
478
- </select>
479
- </div>
480
- <div class="toolbarGroup">
481
- <span class="statusText">${escapeHtml(oState.syncMessage)}</span>
482
- <button id="addTaskButton" class="primaryButton" type="button">Add task</button>
483
- <button id="resetBoardButton" class="secondaryButton" type="button">Load sample board</button>
484
- </div>
485
- </section>
486
-
487
- <section class="boardWrap">
488
- <div class="board">
489
- ${aColumns.map((oColumn) => renderColumn(oColumn)).join('')}
490
- </div>
491
- </section>
492
- </div>
493
-
494
- <div id="taskDialogBackdrop" class="dialogBackdrop" aria-hidden="true">
495
- <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="taskDialogTitle">
496
- <div class="dialogHeader">
497
- <h2 id="taskDialogTitle" class="dialogTitle">Task details</h2>
498
- </div>
499
- <form id="taskForm">
500
- <div class="dialogBody">
501
- <div class="formGrid">
502
- <div class="field fieldWide">
503
- <label for="taskTitle">Title</label>
504
- <input id="taskTitle" class="toolbarInput" name="taskTitle" type="text" maxlength="120" required>
505
- </div>
506
- <div class="field fieldWide">
507
- <label for="taskDescription">Description</label>
508
- <textarea id="taskDescription" class="toolbarTextarea" name="taskDescription" rows="4" maxlength="400"></textarea>
509
- </div>
510
- <div class="field">
511
- <label for="taskOwner">Owner</label>
512
- <input id="taskOwner" class="toolbarInput" name="taskOwner" type="text" maxlength="80" placeholder="You">
513
- </div>
514
- <div class="field">
515
- <label for="taskPriority">Priority</label>
516
- <select id="taskPriority" class="toolbarSelect" name="taskPriority">
517
- <option>High</option>
518
- <option>Medium</option>
519
- <option>Low</option>
520
- </select>
521
- </div>
522
- <div class="field">
523
- <label for="taskDueDate">Due date</label>
524
- <input id="taskDueDate" class="toolbarInput" name="taskDueDate" type="date">
525
- </div>
526
- <div class="field">
527
- <label for="taskEstimate">Estimate</label>
528
- <input id="taskEstimate" class="toolbarInput" name="taskEstimate" type="text" maxlength="30" placeholder="2h">
529
- </div>
530
- <div class="field">
531
- <label for="taskStatus">Status</label>
532
- <select id="taskStatus" class="toolbarSelect" name="taskStatus">
533
- ${aColumns.map((oColumn) => `<option value="${escapeHtml(oColumn.id)}">${escapeHtml(oColumn.title)}</option>`).join('')}
534
- </select>
535
- </div>
536
- <div class="field">
537
- <label for="taskProgress">Progress</label>
538
- <input id="taskProgress" class="toolbarInput" name="taskProgress" type="number" min="0" max="100" value="0">
539
- </div>
540
- <div class="field fieldWide">
541
- <label for="taskTags">Tags</label>
542
- <input id="taskTags" class="toolbarInput" name="taskTags" type="text" maxlength="120" placeholder="Planning, Reporting">
543
- <span class="helperText">Separate tags with commas.</span>
544
- </div>
545
- </div>
546
- </div>
547
- <div class="dialogFooter">
548
- <div class="toolbarGroup">
549
- <button id="deleteTaskButton" class="ghostButton hidden" type="button">Delete</button>
550
- <span class="statusText">Board status, owner, estimate, and tags are stored in task category metadata.</span>
551
- </div>
552
- <div class="toolbarGroup">
553
- <button id="cancelTaskButton" class="secondaryButton" type="button">Cancel</button>
554
- <button class="primaryButton" type="submit">Save task</button>
555
- </div>
556
- </div>
557
- </form>
558
- </div>
559
- </div>
560
- `;
561
-
562
- bindAppEvents();
563
- }
564
-
565
- function bindAppEvents() {
566
- const eSearchInput = document.getElementById('searchInput');
567
- const eStatusFilter = document.getElementById('statusFilter');
568
- const eAddTaskButton = document.getElementById('addTaskButton');
569
- const eResetBoardButton = document.getElementById('resetBoardButton');
570
- const eBackdrop = document.getElementById('taskDialogBackdrop');
571
- const eTaskForm = document.getElementById('taskForm');
572
- const eCancelTaskButton = document.getElementById('cancelTaskButton');
573
- const eDeleteTaskButton = document.getElementById('deleteTaskButton');
574
-
575
- if (eSearchInput) {
576
- eSearchInput.addEventListener('input', (oEvent) => {
577
- oState.search = oEvent.target.value;
578
- renderApp();
579
- });
580
- }
581
-
582
- if (eStatusFilter) {
583
- eStatusFilter.addEventListener('change', (oEvent) => {
584
- oState.statusFilter = oEvent.target.value;
585
- renderApp();
586
- });
587
- }
588
-
589
- if (eAddTaskButton) {
590
- eAddTaskButton.addEventListener('click', () => openTaskDialog(''));
591
- }
592
-
593
- if (eResetBoardButton) {
594
- eResetBoardButton.addEventListener('click', async () => {
595
- try {
596
- oState.syncMessage = 'Loading sample board into Dataverse...';
597
- renderApp();
598
-
599
- const aExistingTasks = [...oState.tasks];
600
- await Promise.all(aExistingTasks.map((oTask) => deleteBoardTask(oTask.id)));
601
- await Promise.all(getSeedTasks().map((oTask) => createBoardTask(oTask)));
602
- await refreshBoardFromDataverse('Sample board loaded into Dataverse task table.');
603
- } catch (oError) {
604
- oState.syncMessage = 'Sample load failed: ' + (oError.message || oError);
605
- }
606
-
607
- renderApp();
608
- });
609
- }
610
-
611
- if (eCancelTaskButton) {
612
- eCancelTaskButton.addEventListener('click', closeTaskDialog);
613
- }
614
-
615
- if (eBackdrop) {
616
- eBackdrop.addEventListener('click', (oEvent) => {
617
- if (oEvent.target === eBackdrop) {
618
- closeTaskDialog();
619
- }
620
- });
621
- }
622
-
623
- if (eTaskForm) {
624
- eTaskForm.addEventListener('submit', async (oEvent) => {
625
- await handleTaskSubmit(oEvent);
626
- });
627
- }
628
-
629
- if (eDeleteTaskButton) {
630
- eDeleteTaskButton.addEventListener('click', async () => {
631
- await handleTaskDelete();
632
- });
633
- }
634
-
635
- document.querySelectorAll('[data-edit-task-id]').forEach((eButton) => {
636
- eButton.addEventListener('click', () => {
637
- openTaskDialog(eButton.getAttribute('data-edit-task-id') || '');
638
- });
639
- });
640
-
641
- document.querySelectorAll('.card').forEach((eCard) => {
642
- eCard.addEventListener('dragstart', handleDragStart);
643
- eCard.addEventListener('dragend', handleDragEnd);
644
- });
645
-
646
- document.querySelectorAll('.columnBody').forEach((eColumnBody) => {
647
- eColumnBody.addEventListener('dragover', handleDragOver);
648
- eColumnBody.addEventListener('dragleave', handleDragLeave);
649
- eColumnBody.addEventListener('drop', async (oEvent) => {
650
- await handleDrop(oEvent);
651
- });
652
- });
653
- }
654
-
655
- function openTaskDialog(sTaskId) {
656
- oState.editingTaskId = sTaskId;
657
- const eBackdrop = document.getElementById('taskDialogBackdrop');
658
- const eDeleteTaskButton = document.getElementById('deleteTaskButton');
659
- const oTask = oState.tasks.find((oItem) => oItem.id === sTaskId);
660
-
661
- const eTitle = document.getElementById('taskTitle');
662
- const eDescription = document.getElementById('taskDescription');
663
- const eOwner = document.getElementById('taskOwner');
664
- const ePriority = document.getElementById('taskPriority');
665
- const eDueDate = document.getElementById('taskDueDate');
666
- const eEstimate = document.getElementById('taskEstimate');
667
- const eStatus = document.getElementById('taskStatus');
668
- const eProgress = document.getElementById('taskProgress');
669
- const eTags = document.getElementById('taskTags');
670
-
671
- if (!eBackdrop || !eTitle || !eDescription || !eOwner || !ePriority || !eDueDate || !eEstimate || !eStatus || !eProgress || !eTags) {
672
- return;
673
- }
674
-
675
- eTitle.value = oTask ? oTask.title : '';
676
- eDescription.value = oTask ? oTask.description : '';
677
- eOwner.value = oTask ? oTask.owner : 'You';
678
- ePriority.value = oTask ? oTask.priority : 'Medium';
679
- eDueDate.value = oTask ? oTask.dueDate : '';
680
- eEstimate.value = oTask ? oTask.estimate : '';
681
- eStatus.value = oTask ? oTask.status : 'backlog';
682
- eProgress.value = oTask ? String(oTask.progress) : '0';
683
- eTags.value = oTask ? (oTask.tags || []).join(', ') : '';
684
-
685
- if (eDeleteTaskButton) {
686
- eDeleteTaskButton.classList.toggle('hidden', !oTask);
687
- }
688
-
689
- eBackdrop.classList.add('open');
690
- eBackdrop.setAttribute('aria-hidden', 'false');
691
- eTitle.focus();
692
- }
693
-
694
- function closeTaskDialog() {
695
- const eBackdrop = document.getElementById('taskDialogBackdrop');
696
- if (!eBackdrop) {
697
- return;
698
- }
699
-
700
- oState.editingTaskId = '';
701
- eBackdrop.classList.remove('open');
702
- eBackdrop.setAttribute('aria-hidden', 'true');
703
- }
704
-
705
- async function handleTaskSubmit(oEvent) {
706
- oEvent.preventDefault();
707
-
708
- const eForm = oEvent.target;
709
- const oFormData = new FormData(eForm);
710
- const aTags = String(oFormData.get('taskTags') || '')
711
- .split(',')
712
- .map((sTag) => sTag.trim())
713
- .filter(Boolean);
714
-
715
- const oTaskInput = {
716
- title: String(oFormData.get('taskTitle') || '').trim(),
717
- description: String(oFormData.get('taskDescription') || '').trim(),
718
- owner: String(oFormData.get('taskOwner') || '').trim() || 'You',
719
- priority: String(oFormData.get('taskPriority') || 'Medium'),
720
- dueDate: String(oFormData.get('taskDueDate') || ''),
721
- estimate: String(oFormData.get('taskEstimate') || '').trim(),
722
- status: String(oFormData.get('taskStatus') || 'backlog'),
723
- progress: clampProgress(oFormData.get('taskProgress')),
724
- tags: aTags
725
- };
726
-
727
- if (!oTaskInput.title) {
728
- return;
729
- }
730
-
731
- try {
732
- oState.syncMessage = oState.editingTaskId ? 'Updating Dataverse task...' : 'Creating Dataverse task...';
733
- renderApp();
734
-
735
- if (oState.editingTaskId) {
736
- await updateBoardTask(oState.editingTaskId, oTaskInput);
737
- await refreshBoardFromDataverse('Task updated in Dataverse.');
738
- } else {
739
- await createBoardTask(oTaskInput);
740
- await refreshBoardFromDataverse('Task created in Dataverse.');
741
- }
742
-
743
- closeTaskDialog();
744
- } catch (oError) {
745
- oState.syncMessage = 'Save failed: ' + (oError.message || oError);
746
- }
747
-
748
- renderApp();
749
- }
750
-
751
- async function handleTaskDelete() {
752
- if (!oState.editingTaskId) {
753
- return;
754
- }
755
-
756
- try {
757
- oState.syncMessage = 'Deleting Dataverse task...';
758
- renderApp();
759
- await deleteBoardTask(oState.editingTaskId);
760
- await refreshBoardFromDataverse('Task deleted from Dataverse.');
761
- closeTaskDialog();
762
- } catch (oError) {
763
- oState.syncMessage = 'Delete failed: ' + (oError.message || oError);
764
- }
765
-
766
- renderApp();
767
- }
768
-
769
- function handleDragStart(oEvent) {
770
- const eCard = oEvent.currentTarget;
771
- const sTaskId = eCard.getAttribute('data-task-id') || '';
772
- oState.draggedTaskId = sTaskId;
773
- eCard.classList.add('dragging');
774
-
775
- if (oEvent.dataTransfer) {
776
- oEvent.dataTransfer.effectAllowed = 'move';
777
- oEvent.dataTransfer.setData('text/plain', sTaskId);
778
- }
779
- }
780
-
781
- function handleDragEnd(oEvent) {
782
- oEvent.currentTarget.classList.remove('dragging');
783
- document.querySelectorAll('.columnBody').forEach((eColumn) => eColumn.classList.remove('dragOver'));
784
- oState.draggedTaskId = '';
785
- }
786
-
787
- function handleDragOver(oEvent) {
788
- oEvent.preventDefault();
789
- oEvent.currentTarget.classList.add('dragOver');
790
- }
791
-
792
- function handleDragLeave(oEvent) {
793
- oEvent.currentTarget.classList.remove('dragOver');
794
- }
795
-
796
- async function handleDrop(oEvent) {
797
- oEvent.preventDefault();
798
- const eColumnBody = oEvent.currentTarget;
799
- const sColumnId = eColumnBody.getAttribute('data-column-id') || '';
800
- const sTaskId = oState.draggedTaskId || (oEvent.dataTransfer ? oEvent.dataTransfer.getData('text/plain') : '');
801
-
802
- eColumnBody.classList.remove('dragOver');
803
-
804
- if (!sColumnId || !sTaskId) {
805
- return;
806
- }
807
-
808
- const oTask = oState.tasks.find((oItem) => oItem.id === sTaskId);
809
- if (!oTask) {
810
- return;
811
- }
812
-
813
- try {
814
- const iProgress = sColumnId === 'complete' ? 100 : sColumnId === 'rejected' ? 0 : oTask.progress;
815
- oState.syncMessage = 'Moving Dataverse task...';
816
- renderApp();
817
-
818
- await updateBoardTask(sTaskId, {
819
- ...oTask,
820
- status: sColumnId,
821
- progress: iProgress
822
- });
823
-
824
- await refreshBoardFromDataverse('Task moved in Dataverse.');
825
- } catch (oError) {
826
- oState.syncMessage = 'Move failed: ' + (oError.message || oError);
827
- }
828
-
829
- renderApp();
830
- }
831
-
832
- async function boot() {
833
- await waitForHostLoad();
834
-
835
- registerTable('tasks', 'activityid');
836
-
837
- oState.tasks = loadCachedTasks();
838
- if (oState.tasks.length > 0) {
839
- oState.syncMessage = 'Loading fresh data from Dataverse...';
840
- } else {
841
- oState.syncMessage = 'Connecting to Dataverse task table...';
842
- }
843
-
844
- renderApp();
845
-
846
- try {
847
- await connectToDataverseOnStartup();
848
- } catch (oError) {
849
- if (oState.tasks.length > 0) {
850
- oState.syncMessage = 'Dataverse unavailable. Showing cached board: ' + getConnectionErrorMessage(oError);
851
- } else {
852
- oState.tasks = [];
853
- oState.syncMessage = getConnectionErrorMessage(oError);
854
- }
855
- }
856
-
857
- renderApp();
858
- }
859
-
860
- boot();
1
+
2
+ import { registerTable, listItems, createItem, updateItem, deleteItem } from './dataverse.js';
3
+
4
+ const sBoardPrefix = 'worktracker|';
5
+ const sCacheKey = 'workTrackerTasksCache';
6
+
7
+ const aColumns = [
8
+ { id: 'backlog', title: 'Backlog', color: '#7c8aa5' },
9
+ { id: 'ready', title: 'Ready', color: '#395cff' },
10
+ { id: 'inprogress', title: 'In Progress', color: '#f59e0b' },
11
+ { id: 'complete', title: 'Complete', color: '#13b981' },
12
+ { id: 'rejected', title: 'Rejected', color: '#ef476f' }
13
+ ];
14
+
15
+ const aSeedTasks = [
16
+ {
17
+ id: createId(),
18
+ title: 'Prepare monthly planning summary',
19
+ description: 'Pull together the current priorities, risks, and proposed actions for the next review.',
20
+ status: 'backlog',
21
+ priority: 'High',
22
+ owner: 'You',
23
+ dueDate: '2026-03-18',
24
+ estimate: '3h',
25
+ progress: 10,
26
+ tags: ['Planning', 'Reporting']
27
+ },
28
+ {
29
+ id: createId(),
30
+ title: 'Review ready-for-build requests',
31
+ description: 'Check scope, confirm acceptance criteria, and mark the next best work items for execution.',
32
+ status: 'ready',
33
+ priority: 'Medium',
34
+ owner: 'You',
35
+ dueDate: '2026-03-16',
36
+ estimate: '2h',
37
+ progress: 35,
38
+ tags: ['Triage']
39
+ },
40
+ {
41
+ id: createId(),
42
+ title: 'Build stakeholder update deck',
43
+ description: 'Turn the latest work highlights into a concise narrative for the weekly stakeholder sync.',
44
+ status: 'inprogress',
45
+ priority: 'High',
46
+ owner: 'You',
47
+ dueDate: '2026-03-15',
48
+ estimate: '5h',
49
+ progress: 68,
50
+ tags: ['Comms', 'Weekly']
51
+ },
52
+ {
53
+ id: createId(),
54
+ title: 'Close completed support actions',
55
+ description: 'Archive the delivered improvements and note what changed for future reference.',
56
+ status: 'complete',
57
+ priority: 'Low',
58
+ owner: 'You',
59
+ dueDate: '2026-03-12',
60
+ estimate: '1h',
61
+ progress: 100,
62
+ tags: ['Ops']
63
+ },
64
+ {
65
+ id: createId(),
66
+ title: 'Drop duplicate reporting request',
67
+ description: 'The request overlaps with an existing dashboard and no longer adds useful value.',
68
+ status: 'rejected',
69
+ priority: 'Low',
70
+ owner: 'You',
71
+ dueDate: '2026-03-11',
72
+ estimate: '30m',
73
+ progress: 0,
74
+ tags: ['Archive']
75
+ }
76
+ ];
77
+
78
+ const oState = {
79
+ tasks: [],
80
+ search: '',
81
+ statusFilter: 'all',
82
+ draggedTaskId: '',
83
+ editingTaskId: '',
84
+ syncMessage: 'Connecting to Dataverse task table...'
85
+ };
86
+
87
+ const iInitialConnectionRetries = 4;
88
+ const iInitialConnectionRetryDelayMs = 500;
89
+
90
+ function createId() {
91
+ return 'task-' + Math.random().toString(36).slice(2, 10);
92
+ }
93
+
94
+ function getSeedTasks() {
95
+ return aSeedTasks.map((oTask) => ({
96
+ ...oTask,
97
+ id: createId(),
98
+ tags: Array.isArray(oTask.tags) ? [...oTask.tags] : []
99
+ }));
100
+ }
101
+
102
+ function loadCachedTasks() {
103
+ const sSaved = localStorage.getItem(sCacheKey);
104
+ if (!sSaved) {
105
+ return [];
106
+ }
107
+
108
+ try {
109
+ const aParsed = JSON.parse(sSaved);
110
+ return Array.isArray(aParsed) ? aParsed : [];
111
+ } catch (oError) {
112
+ console.error('Failed to read cached tasks:', oError);
113
+ return [];
114
+ }
115
+ }
116
+
117
+ function saveCachedTasks() {
118
+ localStorage.setItem(sCacheKey, JSON.stringify(oState.tasks));
119
+ }
120
+
121
+ function isValidStatus(sStatus) {
122
+ return aColumns.some((oColumn) => oColumn.id === sStatus);
123
+ }
124
+
125
+ function clampProgress(iValue) {
126
+ return Math.max(0, Math.min(100, Number(iValue) || 0));
127
+ }
128
+
129
+ function mapPriorityToCode(sPriority) {
130
+ if (sPriority === 'High') {
131
+ return 2;
132
+ }
133
+ if (sPriority === 'Low') {
134
+ return 0;
135
+ }
136
+ return 1;
137
+ }
138
+
139
+ function mapPriorityFromCode(iCode) {
140
+ if (Number(iCode) === 2) {
141
+ return 'High';
142
+ }
143
+ if (Number(iCode) === 0) {
144
+ return 'Low';
145
+ }
146
+ return 'Medium';
147
+ }
148
+
149
+ function normalizeDate(sDateValue) {
150
+ if (!sDateValue) {
151
+ return '';
152
+ }
153
+ return String(sDateValue).slice(0, 10);
154
+ }
155
+
156
+ function toDataverseDateValue(sDateValue) {
157
+ if (!sDateValue) {
158
+ return null;
159
+ }
160
+ return sDateValue + 'T12:00:00Z';
161
+ }
162
+
163
+ function parseBoardMeta(sCategory) {
164
+ if (!sCategory || !String(sCategory).startsWith(sBoardPrefix)) {
165
+ return null;
166
+ }
167
+
168
+ try {
169
+ return JSON.parse(String(sCategory).slice(sBoardPrefix.length));
170
+ } catch (oError) {
171
+ console.error('Failed to parse board metadata:', oError);
172
+ return null;
173
+ }
174
+ }
175
+
176
+ function buildBoardMetaString(oTask) {
177
+ const oMeta = {
178
+ status: isValidStatus(oTask.status) ? oTask.status : 'backlog',
179
+ owner: String(oTask.owner || 'You').slice(0, 80),
180
+ estimate: String(oTask.estimate || '').slice(0, 30),
181
+ tags: Array.isArray(oTask.tags) ? oTask.tags.slice(0, 8).map((sTag) => String(sTag).slice(0, 24)) : []
182
+ };
183
+
184
+ let sValue = sBoardPrefix + JSON.stringify(oMeta);
185
+
186
+ while (sValue.length > 240 && oMeta.tags.length > 0) {
187
+ oMeta.tags.pop();
188
+ sValue = sBoardPrefix + JSON.stringify(oMeta);
189
+ }
190
+
191
+ return sValue.slice(0, 240);
192
+ }
193
+
194
+ function mapDataverseTaskToBoardTask(oRecord) {
195
+ const oMeta = parseBoardMeta(oRecord.category) || {};
196
+ const sTaskId = oRecord.activityid || oRecord.taskid || createId();
197
+
198
+ return {
199
+ id: sTaskId,
200
+ title: oRecord.subject || 'Untitled task',
201
+ description: oRecord.description || '',
202
+ status: isValidStatus(oMeta.status) ? oMeta.status : 'backlog',
203
+ priority: mapPriorityFromCode(oRecord.prioritycode),
204
+ owner: oMeta.owner || 'You',
205
+ dueDate: normalizeDate(oRecord.scheduledend),
206
+ estimate: oMeta.estimate || '',
207
+ progress: clampProgress(oRecord.percentcomplete),
208
+ tags: Array.isArray(oMeta.tags) ? oMeta.tags : []
209
+ };
210
+ }
211
+
212
+ function buildDataverseTaskPayload(oTaskInput) {
213
+ const oPayload = {
214
+ subject: oTaskInput.title,
215
+ description: oTaskInput.description,
216
+ prioritycode: mapPriorityToCode(oTaskInput.priority),
217
+ percentcomplete: clampProgress(oTaskInput.progress),
218
+ category: buildBoardMetaString(oTaskInput)
219
+ };
220
+
221
+ if (oTaskInput.dueDate) {
222
+ oPayload.scheduledend = toDataverseDateValue(oTaskInput.dueDate);
223
+ } else {
224
+ oPayload.scheduledend = null;
225
+ }
226
+
227
+ return oPayload;
228
+ }
229
+
230
+ async function loadDataverseTasks() {
231
+ const oResult = await listItems('tasks', 'activityid', {
232
+ filter: "startswith(category, '" + sBoardPrefix + "')",
233
+ select: ['activityid', 'subject', 'description', 'prioritycode', 'scheduledend', 'percentcomplete', 'category', 'modifiedon'],
234
+ orderBy: ['modifiedon desc'],
235
+ top: 200
236
+ });
237
+
238
+ return (oResult.entities || []).map((oRecord) => mapDataverseTaskToBoardTask(oRecord));
239
+ }
240
+
241
+ async function refreshBoardFromDataverse(sMessage) {
242
+ const aTasks = await loadDataverseTasks();
243
+ oState.tasks = aTasks;
244
+ oState.syncMessage = sMessage || 'Synced with Dataverse task table.';
245
+ saveCachedTasks();
246
+ }
247
+
248
+ async function createBoardTask(oTaskInput) {
249
+ await createItem('tasks', 'activityid', buildDataverseTaskPayload(oTaskInput));
250
+ }
251
+
252
+ async function updateBoardTask(sTaskId, oTaskInput) {
253
+ await updateItem('tasks', 'activityid', sTaskId, buildDataverseTaskPayload(oTaskInput));
254
+ }
255
+
256
+ async function deleteBoardTask(sTaskId) {
257
+ await deleteItem('tasks', 'activityid', sTaskId);
258
+ }
259
+
260
+ function getFilteredTasks() {
261
+ return oState.tasks.filter((oTask) => {
262
+ const bSearchMatch = !oState.search || [oTask.title, oTask.description, oTask.owner, ...(oTask.tags || [])]
263
+ .join(' ')
264
+ .toLowerCase()
265
+ .includes(oState.search.toLowerCase());
266
+
267
+ const bStatusMatch = oState.statusFilter === 'all' || oTask.status === oState.statusFilter;
268
+ return bSearchMatch && bStatusMatch;
269
+ });
270
+ }
271
+
272
+ function getTasksByColumn(sColumnId) {
273
+ return getFilteredTasks().filter((oTask) => oTask.status === sColumnId);
274
+ }
275
+
276
+ function countOpenTasks() {
277
+ return oState.tasks.filter((oTask) => oTask.status !== 'complete' && oTask.status !== 'rejected').length;
278
+ }
279
+
280
+ function countInProgressTasks() {
281
+ return oState.tasks.filter((oTask) => oTask.status === 'inprogress').length;
282
+ }
283
+
284
+ function countCompletedTasks() {
285
+ return oState.tasks.filter((oTask) => oTask.status === 'complete').length;
286
+ }
287
+
288
+ function getFocusScore() {
289
+ const iTotal = oState.tasks.length || 1;
290
+ const iDoneWeight = countCompletedTasks() * 100;
291
+ const iActiveWeight = countInProgressTasks() * 60;
292
+ const iReadyWeight = oState.tasks.filter((oTask) => oTask.status === 'ready').length * 30;
293
+ return Math.min(100, Math.round((iDoneWeight + iActiveWeight + iReadyWeight) / iTotal));
294
+ }
295
+
296
+ function getPriorityBadgeClass(sPriority) {
297
+ if (sPriority === 'High') {
298
+ return 'badge badgePriorityHigh';
299
+ }
300
+ if (sPriority === 'Medium') {
301
+ return 'badge badgePriorityMedium';
302
+ }
303
+ return 'badge badgePriorityLow';
304
+ }
305
+
306
+ function escapeHtml(sValue) {
307
+ return String(sValue)
308
+ .replace(new RegExp('&', 'g'), '&amp;')
309
+ .replace(new RegExp('<', 'g'), '&lt;')
310
+ .replace(new RegExp('>', 'g'), '&gt;')
311
+ .replace(new RegExp('\"', 'g'), '&quot;')
312
+ .replace(new RegExp("'", 'g'), '&#39;');
313
+ }
314
+
315
+ function delay(iMilliseconds) {
316
+ return new Promise((resolve) => {
317
+ window.setTimeout(resolve, iMilliseconds);
318
+ });
319
+ }
320
+
321
+ function waitForHostLoad() {
322
+ if (document.readyState === 'complete') {
323
+ return Promise.resolve();
324
+ }
325
+
326
+ return new Promise((resolve) => {
327
+ window.addEventListener('load', resolve, { once: true });
328
+ });
329
+ }
330
+
331
+ function isHostStartupError(oError) {
332
+ const sMessage = String(oError && oError.message ? oError.message : oError || '').toLowerCase();
333
+ return sMessage.includes('metadata')
334
+ || sMessage.includes('runtime')
335
+ || sMessage.includes('connection')
336
+ || sMessage.includes('initial')
337
+ || sMessage.includes('token')
338
+ || sMessage.includes('postmessage');
339
+ }
340
+
341
+ function getConnectionErrorMessage(oError) {
342
+ const sMessage = String(oError && oError.message ? oError.message : oError || 'Unknown Dataverse error');
343
+
344
+ if (isHostStartupError(oError)) {
345
+ return 'Dataverse connection is only available after the Power Apps Code App host finishes initializing: ' + sMessage;
346
+ }
347
+
348
+ return 'Dataverse load failed: ' + sMessage;
349
+ }
350
+
351
+ async function connectToDataverseOnStartup() {
352
+ let oLastError = null;
353
+
354
+ for (let iAttempt = 0; iAttempt < iInitialConnectionRetries; iAttempt += 1) {
355
+ try {
356
+ await refreshBoardFromDataverse('Connected to Dataverse task table.');
357
+ if (oState.tasks.length === 0) {
358
+ oState.syncMessage = 'No board tasks found in Dataverse yet.';
359
+ }
360
+ return;
361
+ } catch (oError) {
362
+ oLastError = oError;
363
+
364
+ if (!isHostStartupError(oError) || iAttempt === iInitialConnectionRetries - 1) {
365
+ break;
366
+ }
367
+
368
+ oState.syncMessage = 'Waiting for Power Apps Code App host to initialize Dataverse connection...';
369
+ renderApp();
370
+ await delay(iInitialConnectionRetryDelayMs * (iAttempt + 1));
371
+ }
372
+ }
373
+
374
+ throw oLastError;
375
+ }
376
+
377
+ function renderCard(oTask) {
378
+ const sTags = (oTask.tags || []).join(', ') || 'None';
379
+ const iProgress = clampProgress(oTask.progress);
380
+
381
+ return `
382
+ <article class="card" draggable="true" data-task-id="${escapeHtml(oTask.id)}">
383
+ <div class="cardHeader">
384
+ <h3 class="cardTitle">${escapeHtml(oTask.title)}</h3>
385
+ <span class="${getPriorityBadgeClass(oTask.priority)}">${escapeHtml(oTask.priority)}</span>
386
+ </div>
387
+ <p class="cardDescription">${escapeHtml(oTask.description)}</p>
388
+ <div class="progressBar">
389
+ <div class="progressValue" style="width: ${iProgress}%"></div>
390
+ </div>
391
+ <div class="cardMetaGrid">
392
+ <div class="metaItem">
393
+ <span class="metaLabel">Owner</span>
394
+ <span class="metaValue">${escapeHtml(oTask.owner)}</span>
395
+ </div>
396
+ <div class="metaItem">
397
+ <span class="metaLabel">Due</span>
398
+ <span class="metaValue">${escapeHtml(oTask.dueDate || 'Not set')}</span>
399
+ </div>
400
+ <div class="metaItem">
401
+ <span class="metaLabel">Estimate</span>
402
+ <span class="metaValue">${escapeHtml(oTask.estimate || 'Not set')}</span>
403
+ </div>
404
+ <div class="metaItem">
405
+ <span class="metaLabel">Tags</span>
406
+ <span class="metaValue">${escapeHtml(sTags)}</span>
407
+ </div>
408
+ </div>
409
+ <div class="cardFooter">
410
+ <span>${escapeHtml(String(iProgress))}% complete</span>
411
+ <button class="ghostButton" type="button" data-edit-task-id="${escapeHtml(oTask.id)}">Edit</button>
412
+ </div>
413
+ </article>
414
+ `;
415
+ }
416
+
417
+ function renderColumn(oColumn) {
418
+ const aTasks = getTasksByColumn(oColumn.id);
419
+ const sCards = aTasks.length
420
+ ? aTasks.map((oTask) => renderCard(oTask)).join('')
421
+ : '<div class="emptyState">Drop work here or add a new task.</div>';
422
+
423
+ return `
424
+ <section class="column" aria-label="${escapeHtml(oColumn.title)}">
425
+ <div class="columnHeader">
426
+ <div class="columnTitleWrap">
427
+ <span class="columnDot" style="background:${escapeHtml(oColumn.color)}"></span>
428
+ <h2 class="columnTitle">${escapeHtml(oColumn.title)}</h2>
429
+ </div>
430
+ <span class="columnCount">${aTasks.length}</span>
431
+ </div>
432
+ <div class="columnBody" data-column-id="${escapeHtml(oColumn.id)}">
433
+ ${sCards}
434
+ </div>
435
+ </section>
436
+ `;
437
+ }
438
+
439
+ function renderApp() {
440
+ const eApp = document.getElementById('app');
441
+ if (!eApp) {
442
+ return;
443
+ }
444
+
445
+ eApp.innerHTML = `
446
+ <div class="shell">
447
+ <section class="hero">
448
+ <div>
449
+ <h1 class="heroTitle">Track work on a clean paper-grid board.</h1>
450
+ <p class="heroCopy">A quiet editorial kanban for backlog, ready, in progress, complete, and rejected work. Drag cards between columns, keep the important details visible, and save the board into Dataverse task records.</p>
451
+ </div>
452
+ <div class="heroMeta">
453
+ <div class="metricCard">
454
+ <span class="metricLabel">Open tasks</span>
455
+ <strong class="metricValue">${countOpenTasks()}</strong>
456
+ </div>
457
+ <div class="metricCard">
458
+ <span class="metricLabel">In progress</span>
459
+ <strong class="metricValue">${countInProgressTasks()}</strong>
460
+ </div>
461
+ <div class="metricCard">
462
+ <span class="metricLabel">Completed</span>
463
+ <strong class="metricValue">${countCompletedTasks()}</strong>
464
+ </div>
465
+ <div class="metricCard">
466
+ <span class="metricLabel">Focus score</span>
467
+ <strong class="metricValue">${getFocusScore()}%</strong>
468
+ </div>
469
+ </div>
470
+ </section>
471
+
472
+ <section class="toolbar">
473
+ <div class="toolbarGroup">
474
+ <input id="searchInput" class="toolbarInput" type="search" placeholder="Search title, description, owner, or tags" value="${escapeHtml(oState.search)}">
475
+ <select id="statusFilter" class="toolbarSelect" aria-label="Filter tasks by status">
476
+ <option value="all"${oState.statusFilter === 'all' ? ' selected' : ''}>All statuses</option>
477
+ ${aColumns.map((oColumn) => `<option value="${escapeHtml(oColumn.id)}"${oState.statusFilter === oColumn.id ? ' selected' : ''}>${escapeHtml(oColumn.title)}</option>`).join('')}
478
+ </select>
479
+ </div>
480
+ <div class="toolbarGroup">
481
+ <span class="statusText">${escapeHtml(oState.syncMessage)}</span>
482
+ <button id="addTaskButton" class="primaryButton" type="button">Add task</button>
483
+ <button id="resetBoardButton" class="secondaryButton" type="button">Load sample board</button>
484
+ </div>
485
+ </section>
486
+
487
+ <section class="boardWrap">
488
+ <div class="board">
489
+ ${aColumns.map((oColumn) => renderColumn(oColumn)).join('')}
490
+ </div>
491
+ </section>
492
+ </div>
493
+
494
+ <div id="taskDialogBackdrop" class="dialogBackdrop" aria-hidden="true">
495
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="taskDialogTitle">
496
+ <div class="dialogHeader">
497
+ <h2 id="taskDialogTitle" class="dialogTitle">Task details</h2>
498
+ </div>
499
+ <form id="taskForm">
500
+ <div class="dialogBody">
501
+ <div class="formGrid">
502
+ <div class="field fieldWide">
503
+ <label for="taskTitle">Title</label>
504
+ <input id="taskTitle" class="toolbarInput" name="taskTitle" type="text" maxlength="120" required>
505
+ </div>
506
+ <div class="field fieldWide">
507
+ <label for="taskDescription">Description</label>
508
+ <textarea id="taskDescription" class="toolbarTextarea" name="taskDescription" rows="4" maxlength="400"></textarea>
509
+ </div>
510
+ <div class="field">
511
+ <label for="taskOwner">Owner</label>
512
+ <input id="taskOwner" class="toolbarInput" name="taskOwner" type="text" maxlength="80" placeholder="You">
513
+ </div>
514
+ <div class="field">
515
+ <label for="taskPriority">Priority</label>
516
+ <select id="taskPriority" class="toolbarSelect" name="taskPriority">
517
+ <option>High</option>
518
+ <option>Medium</option>
519
+ <option>Low</option>
520
+ </select>
521
+ </div>
522
+ <div class="field">
523
+ <label for="taskDueDate">Due date</label>
524
+ <input id="taskDueDate" class="toolbarInput" name="taskDueDate" type="date">
525
+ </div>
526
+ <div class="field">
527
+ <label for="taskEstimate">Estimate</label>
528
+ <input id="taskEstimate" class="toolbarInput" name="taskEstimate" type="text" maxlength="30" placeholder="2h">
529
+ </div>
530
+ <div class="field">
531
+ <label for="taskStatus">Status</label>
532
+ <select id="taskStatus" class="toolbarSelect" name="taskStatus">
533
+ ${aColumns.map((oColumn) => `<option value="${escapeHtml(oColumn.id)}">${escapeHtml(oColumn.title)}</option>`).join('')}
534
+ </select>
535
+ </div>
536
+ <div class="field">
537
+ <label for="taskProgress">Progress</label>
538
+ <input id="taskProgress" class="toolbarInput" name="taskProgress" type="number" min="0" max="100" value="0">
539
+ </div>
540
+ <div class="field fieldWide">
541
+ <label for="taskTags">Tags</label>
542
+ <input id="taskTags" class="toolbarInput" name="taskTags" type="text" maxlength="120" placeholder="Planning, Reporting">
543
+ <span class="helperText">Separate tags with commas.</span>
544
+ </div>
545
+ </div>
546
+ </div>
547
+ <div class="dialogFooter">
548
+ <div class="toolbarGroup">
549
+ <button id="deleteTaskButton" class="ghostButton hidden" type="button">Delete</button>
550
+ <span class="statusText">Board status, owner, estimate, and tags are stored in task category metadata.</span>
551
+ </div>
552
+ <div class="toolbarGroup">
553
+ <button id="cancelTaskButton" class="secondaryButton" type="button">Cancel</button>
554
+ <button class="primaryButton" type="submit">Save task</button>
555
+ </div>
556
+ </div>
557
+ </form>
558
+ </div>
559
+ </div>
560
+ `;
561
+
562
+ bindAppEvents();
563
+ }
564
+
565
+ function bindAppEvents() {
566
+ const eSearchInput = document.getElementById('searchInput');
567
+ const eStatusFilter = document.getElementById('statusFilter');
568
+ const eAddTaskButton = document.getElementById('addTaskButton');
569
+ const eResetBoardButton = document.getElementById('resetBoardButton');
570
+ const eBackdrop = document.getElementById('taskDialogBackdrop');
571
+ const eTaskForm = document.getElementById('taskForm');
572
+ const eCancelTaskButton = document.getElementById('cancelTaskButton');
573
+ const eDeleteTaskButton = document.getElementById('deleteTaskButton');
574
+
575
+ if (eSearchInput) {
576
+ eSearchInput.addEventListener('input', (oEvent) => {
577
+ oState.search = oEvent.target.value;
578
+ renderApp();
579
+ });
580
+ }
581
+
582
+ if (eStatusFilter) {
583
+ eStatusFilter.addEventListener('change', (oEvent) => {
584
+ oState.statusFilter = oEvent.target.value;
585
+ renderApp();
586
+ });
587
+ }
588
+
589
+ if (eAddTaskButton) {
590
+ eAddTaskButton.addEventListener('click', () => openTaskDialog(''));
591
+ }
592
+
593
+ if (eResetBoardButton) {
594
+ eResetBoardButton.addEventListener('click', async () => {
595
+ try {
596
+ oState.syncMessage = 'Loading sample board into Dataverse...';
597
+ renderApp();
598
+
599
+ const aExistingTasks = [...oState.tasks];
600
+ await Promise.all(aExistingTasks.map((oTask) => deleteBoardTask(oTask.id)));
601
+ await Promise.all(getSeedTasks().map((oTask) => createBoardTask(oTask)));
602
+ await refreshBoardFromDataverse('Sample board loaded into Dataverse task table.');
603
+ } catch (oError) {
604
+ oState.syncMessage = 'Sample load failed: ' + (oError.message || oError);
605
+ }
606
+
607
+ renderApp();
608
+ });
609
+ }
610
+
611
+ if (eCancelTaskButton) {
612
+ eCancelTaskButton.addEventListener('click', closeTaskDialog);
613
+ }
614
+
615
+ if (eBackdrop) {
616
+ eBackdrop.addEventListener('click', (oEvent) => {
617
+ if (oEvent.target === eBackdrop) {
618
+ closeTaskDialog();
619
+ }
620
+ });
621
+ }
622
+
623
+ if (eTaskForm) {
624
+ eTaskForm.addEventListener('submit', async (oEvent) => {
625
+ await handleTaskSubmit(oEvent);
626
+ });
627
+ }
628
+
629
+ if (eDeleteTaskButton) {
630
+ eDeleteTaskButton.addEventListener('click', async () => {
631
+ await handleTaskDelete();
632
+ });
633
+ }
634
+
635
+ document.querySelectorAll('[data-edit-task-id]').forEach((eButton) => {
636
+ eButton.addEventListener('click', () => {
637
+ openTaskDialog(eButton.getAttribute('data-edit-task-id') || '');
638
+ });
639
+ });
640
+
641
+ document.querySelectorAll('.card').forEach((eCard) => {
642
+ eCard.addEventListener('dragstart', handleDragStart);
643
+ eCard.addEventListener('dragend', handleDragEnd);
644
+ });
645
+
646
+ document.querySelectorAll('.columnBody').forEach((eColumnBody) => {
647
+ eColumnBody.addEventListener('dragover', handleDragOver);
648
+ eColumnBody.addEventListener('dragleave', handleDragLeave);
649
+ eColumnBody.addEventListener('drop', async (oEvent) => {
650
+ await handleDrop(oEvent);
651
+ });
652
+ });
653
+ }
654
+
655
+ function openTaskDialog(sTaskId) {
656
+ oState.editingTaskId = sTaskId;
657
+ const eBackdrop = document.getElementById('taskDialogBackdrop');
658
+ const eDeleteTaskButton = document.getElementById('deleteTaskButton');
659
+ const oTask = oState.tasks.find((oItem) => oItem.id === sTaskId);
660
+
661
+ const eTitle = document.getElementById('taskTitle');
662
+ const eDescription = document.getElementById('taskDescription');
663
+ const eOwner = document.getElementById('taskOwner');
664
+ const ePriority = document.getElementById('taskPriority');
665
+ const eDueDate = document.getElementById('taskDueDate');
666
+ const eEstimate = document.getElementById('taskEstimate');
667
+ const eStatus = document.getElementById('taskStatus');
668
+ const eProgress = document.getElementById('taskProgress');
669
+ const eTags = document.getElementById('taskTags');
670
+
671
+ if (!eBackdrop || !eTitle || !eDescription || !eOwner || !ePriority || !eDueDate || !eEstimate || !eStatus || !eProgress || !eTags) {
672
+ return;
673
+ }
674
+
675
+ eTitle.value = oTask ? oTask.title : '';
676
+ eDescription.value = oTask ? oTask.description : '';
677
+ eOwner.value = oTask ? oTask.owner : 'You';
678
+ ePriority.value = oTask ? oTask.priority : 'Medium';
679
+ eDueDate.value = oTask ? oTask.dueDate : '';
680
+ eEstimate.value = oTask ? oTask.estimate : '';
681
+ eStatus.value = oTask ? oTask.status : 'backlog';
682
+ eProgress.value = oTask ? String(oTask.progress) : '0';
683
+ eTags.value = oTask ? (oTask.tags || []).join(', ') : '';
684
+
685
+ if (eDeleteTaskButton) {
686
+ eDeleteTaskButton.classList.toggle('hidden', !oTask);
687
+ }
688
+
689
+ eBackdrop.classList.add('open');
690
+ eBackdrop.setAttribute('aria-hidden', 'false');
691
+ eTitle.focus();
692
+ }
693
+
694
+ function closeTaskDialog() {
695
+ const eBackdrop = document.getElementById('taskDialogBackdrop');
696
+ if (!eBackdrop) {
697
+ return;
698
+ }
699
+
700
+ oState.editingTaskId = '';
701
+ eBackdrop.classList.remove('open');
702
+ eBackdrop.setAttribute('aria-hidden', 'true');
703
+ }
704
+
705
+ async function handleTaskSubmit(oEvent) {
706
+ oEvent.preventDefault();
707
+
708
+ const eForm = oEvent.target;
709
+ const oFormData = new FormData(eForm);
710
+ const aTags = String(oFormData.get('taskTags') || '')
711
+ .split(',')
712
+ .map((sTag) => sTag.trim())
713
+ .filter(Boolean);
714
+
715
+ const oTaskInput = {
716
+ title: String(oFormData.get('taskTitle') || '').trim(),
717
+ description: String(oFormData.get('taskDescription') || '').trim(),
718
+ owner: String(oFormData.get('taskOwner') || '').trim() || 'You',
719
+ priority: String(oFormData.get('taskPriority') || 'Medium'),
720
+ dueDate: String(oFormData.get('taskDueDate') || ''),
721
+ estimate: String(oFormData.get('taskEstimate') || '').trim(),
722
+ status: String(oFormData.get('taskStatus') || 'backlog'),
723
+ progress: clampProgress(oFormData.get('taskProgress')),
724
+ tags: aTags
725
+ };
726
+
727
+ if (!oTaskInput.title) {
728
+ return;
729
+ }
730
+
731
+ try {
732
+ oState.syncMessage = oState.editingTaskId ? 'Updating Dataverse task...' : 'Creating Dataverse task...';
733
+ renderApp();
734
+
735
+ if (oState.editingTaskId) {
736
+ await updateBoardTask(oState.editingTaskId, oTaskInput);
737
+ await refreshBoardFromDataverse('Task updated in Dataverse.');
738
+ } else {
739
+ await createBoardTask(oTaskInput);
740
+ await refreshBoardFromDataverse('Task created in Dataverse.');
741
+ }
742
+
743
+ closeTaskDialog();
744
+ } catch (oError) {
745
+ oState.syncMessage = 'Save failed: ' + (oError.message || oError);
746
+ }
747
+
748
+ renderApp();
749
+ }
750
+
751
+ async function handleTaskDelete() {
752
+ if (!oState.editingTaskId) {
753
+ return;
754
+ }
755
+
756
+ try {
757
+ oState.syncMessage = 'Deleting Dataverse task...';
758
+ renderApp();
759
+ await deleteBoardTask(oState.editingTaskId);
760
+ await refreshBoardFromDataverse('Task deleted from Dataverse.');
761
+ closeTaskDialog();
762
+ } catch (oError) {
763
+ oState.syncMessage = 'Delete failed: ' + (oError.message || oError);
764
+ }
765
+
766
+ renderApp();
767
+ }
768
+
769
+ function handleDragStart(oEvent) {
770
+ const eCard = oEvent.currentTarget;
771
+ const sTaskId = eCard.getAttribute('data-task-id') || '';
772
+ oState.draggedTaskId = sTaskId;
773
+ eCard.classList.add('dragging');
774
+
775
+ if (oEvent.dataTransfer) {
776
+ oEvent.dataTransfer.effectAllowed = 'move';
777
+ oEvent.dataTransfer.setData('text/plain', sTaskId);
778
+ }
779
+ }
780
+
781
+ function handleDragEnd(oEvent) {
782
+ oEvent.currentTarget.classList.remove('dragging');
783
+ document.querySelectorAll('.columnBody').forEach((eColumn) => eColumn.classList.remove('dragOver'));
784
+ oState.draggedTaskId = '';
785
+ }
786
+
787
+ function handleDragOver(oEvent) {
788
+ oEvent.preventDefault();
789
+ oEvent.currentTarget.classList.add('dragOver');
790
+ }
791
+
792
+ function handleDragLeave(oEvent) {
793
+ oEvent.currentTarget.classList.remove('dragOver');
794
+ }
795
+
796
+ async function handleDrop(oEvent) {
797
+ oEvent.preventDefault();
798
+ const eColumnBody = oEvent.currentTarget;
799
+ const sColumnId = eColumnBody.getAttribute('data-column-id') || '';
800
+ const sTaskId = oState.draggedTaskId || (oEvent.dataTransfer ? oEvent.dataTransfer.getData('text/plain') : '');
801
+
802
+ eColumnBody.classList.remove('dragOver');
803
+
804
+ if (!sColumnId || !sTaskId) {
805
+ return;
806
+ }
807
+
808
+ const oTask = oState.tasks.find((oItem) => oItem.id === sTaskId);
809
+ if (!oTask) {
810
+ return;
811
+ }
812
+
813
+ try {
814
+ const iProgress = sColumnId === 'complete' ? 100 : sColumnId === 'rejected' ? 0 : oTask.progress;
815
+ oState.syncMessage = 'Moving Dataverse task...';
816
+ renderApp();
817
+
818
+ await updateBoardTask(sTaskId, {
819
+ ...oTask,
820
+ status: sColumnId,
821
+ progress: iProgress
822
+ });
823
+
824
+ await refreshBoardFromDataverse('Task moved in Dataverse.');
825
+ } catch (oError) {
826
+ oState.syncMessage = 'Move failed: ' + (oError.message || oError);
827
+ }
828
+
829
+ renderApp();
830
+ }
831
+
832
+ async function boot() {
833
+ await waitForHostLoad();
834
+
835
+ registerTable('tasks', 'activityid');
836
+
837
+ oState.tasks = loadCachedTasks();
838
+ if (oState.tasks.length > 0) {
839
+ oState.syncMessage = 'Loading fresh data from Dataverse...';
840
+ } else {
841
+ oState.syncMessage = 'Connecting to Dataverse task table...';
842
+ }
843
+
844
+ renderApp();
845
+
846
+ try {
847
+ await connectToDataverseOnStartup();
848
+ } catch (oError) {
849
+ if (oState.tasks.length > 0) {
850
+ oState.syncMessage = 'Dataverse unavailable. Showing cached board: ' + getConnectionErrorMessage(oError);
851
+ } else {
852
+ oState.tasks = [];
853
+ oState.syncMessage = getConnectionErrorMessage(oError);
854
+ }
855
+ }
856
+
857
+ renderApp();
858
+ }
859
+
860
+ boot();