-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_with_custom_fields_ontask.js
More file actions
1374 lines (1164 loc) · 46.8 KB
/
server_with_custom_fields_ontask.js
File metadata and controls
1374 lines (1164 loc) · 46.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import cors from 'cors';
import { config } from 'dotenv';
config();
const app = express();
const PORT = 3001;
app.use(cors({
origin: ['http://localhost:3000', 'http://localhost:3001'],
credentials: true
}));
app.use(express.json());
// In-memory storage for enhanced features (in production, use a real database)
let themes = [
{ id: 1, name: 'Default', primary: '#3182ce', secondary: '#48bb78', background: '#f8f9fa' },
{ id: 2, name: 'Dark Mode', primary: '#4299e1', secondary: '#68d391', background: '#1a202c' },
{ id: 3, name: 'Ocean', primary: '#0077be', secondary: '#00a693', background: '#e6f7ff' },
{ id: 4, name: 'Sunset', primary: '#ed8936', secondary: '#f56565', background: '#fffaf0' },
{ id: 5, name: 'Forest', primary: '#38a169', secondary: '#68d391', background: '#f0fff4' }
];
let notifications = [];
let aiInsights = [];
let activityLogs = [];
const makeAsanaRequest = async (endpoint, method = 'GET', data = null) => {
const { default: fetch } = await import('node-fetch');
console.log(`🔗 ${method} ${endpoint}`);
if (data) console.log('📤 Data:', JSON.stringify(data, null, 2));
const options = {
method,
headers: {
'Authorization': `Bearer ${process.env.VITE_ASANA_TOKEN}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
if (data && method !== 'GET') {
options.body = JSON.stringify({ data });
}
const response = await fetch(`https://app.asana.com/api/1.0${endpoint}`, options);
const result = await response.json();
console.log(`📥 Response Status: ${response.status}`);
if (!response.ok) {
console.error('❌ Asana API Error:', result);
throw new Error(`Asana API Error: ${response.status} - ${result.errors?.[0]?.message || 'Unknown error'}`);
}
return result;
};
// Utility function to add activity log
const addActivityLog = (action, entityType, entityName, userId = 'current_user') => {
const log = {
id: Date.now(),
action,
entityType,
entityName,
userId,
timestamp: new Date().toISOString(),
details: `${action} ${entityType}: ${entityName}`
};
activityLogs.unshift(log);
// Keep only last 100 logs
if (activityLogs.length > 100) {
activityLogs = activityLogs.slice(0, 100);
}
};
// Utility function to create custom fields if they don't exist
const ensureCustomFieldsExist = async (projectId) => {
try {
console.log('🔍 Checking custom fields for project:', projectId);
// First, try to get workspace and then fetch custom fields from workspace
const projectData = await makeAsanaRequest(`/projects/${projectId}?opt_fields=workspace`);
const workspaceId = projectData.data.workspace?.gid;
if (!workspaceId) {
console.error('❌ Could not determine workspace for project');
return [];
}
console.log('📋 Project workspace:', workspaceId);
// Get ALL workspace custom fields first
const workspaceFields = await makeAsanaRequest(`/workspaces/${workspaceId}/custom_fields?opt_fields=name,gid,enum_options.name,enum_options.gid,enum_options.color`);
const allWorkspaceFields = workspaceFields.data || [];
console.log('📋 All workspace custom fields:', allWorkspaceFields.map(f => `${f.name} (${f.gid})`));
// Find the Priority and Progress fields
const priorityField = allWorkspaceFields.find(field => field.name === "Priority");
const progressField = allWorkspaceFields.find(field => field.name === "Task Progress");
const fieldsToCreate = [];
const existingFields = [];
// Handle Priority field
if (!priorityField) {
console.log('🔴 Priority field not found in workspace, will create it');
fieldsToCreate.push({
name: "Priority",
description: "Task priority level - automatically created by Enhanced Asana Dashboard",
type: "enum",
workspace: workspaceId,
enum_options: [
{ name: "High", color: "red", enabled: true },
{ name: "Medium", color: "orange", enabled: true },
{ name: "Low", color: "yellow-orange", enabled: true },
{ name: "None", color: "none", enabled: true }
]
});
} else {
console.log('✅ Priority field exists in workspace:', priorityField.gid);
existingFields.push(priorityField);
}
// Handle Progress field
if (!progressField) {
console.log('🟡 Task Progress field not found in workspace, will create it');
fieldsToCreate.push({
name: "Task Progress",
description: "Task progress status - automatically created by Enhanced Asana Dashboard",
type: "enum",
workspace: workspaceId,
enum_options: [
{ name: "Not Started", color: "blue", enabled: true },
{ name: "In Progress", color: "cool-gray", enabled: true },
{ name: "Waiting", color: "yellow", enabled: true },
{ name: "Deferred", color: "orange", enabled: true },
{ name: "Done", color: "blue-green", enabled: true }
]
});
} else {
console.log('✅ Task Progress field exists in workspace:', progressField.gid);
existingFields.push(progressField);
}
// Add existing fields to project (ignore "already exists" errors)
for (const field of existingFields) {
try {
console.log(`📌 Ensuring custom field is in project: ${field.name} (${field.gid})`);
await makeAsanaRequest(`/projects/${projectId}/addCustomFieldSetting`, 'POST', {
custom_field: field.gid,
is_important: true
});
console.log(`✅ Added custom field to project: ${field.name}`);
} catch (addError) {
// This is expected if the field already exists - that's OK!
if (addError.message.includes('Custom field already exists')) {
console.log(`✅ Custom field ${field.name} already in project - perfect!`);
} else {
console.error(`❌ Failed to add custom field ${field.name} to project:`, addError.message);
}
}
}
// Create missing fields
const createdFields = [];
for (const fieldData of fieldsToCreate) {
try {
console.log(`🚀 Creating custom field: ${fieldData.name} in workspace: ${workspaceId}`);
// Create the custom field
const newField = await makeAsanaRequest('/custom_fields', 'POST', fieldData);
console.log(`✅ Created custom field: ${newField.data.name} (${newField.data.gid})`);
// Add the field to the project
await makeAsanaRequest(`/projects/${projectId}/addCustomFieldSetting`, 'POST', {
custom_field: newField.data.gid,
is_important: true
});
console.log(`📌 Added new custom field to project: ${fieldData.name}`);
createdFields.push(newField.data);
existingFields.push(newField.data);
// Add to activity log
addActivityLog('Created', 'Custom Field', fieldData.name);
} catch (fieldError) {
console.error(`❌ Failed to create custom field ${fieldData.name}:`, fieldError.message);
// Continue with other fields even if one fails
}
}
// Return the fields we know exist (from workspace + any we created)
const finalFields = [
...existingFields,
...createdFields
];
console.log('📋 Final available custom fields:', finalFields.map(f => `${f.name} (${f.gid}) with ${f.enum_options?.length || 0} options`));
return finalFields;
} catch (error) {
console.error('❌ Error ensuring custom fields exist:', error.message);
// Don't throw error, just return empty array so the task creation can continue
return [];
}
};
// Utility function to get or create custom field mapping
const getCustomFieldMapping = async (projectId, customFieldsData) => {
try {
// Ensure custom fields exist first
const projectFields = await ensureCustomFieldsExist(projectId);
console.log('📋 Available project fields for mapping:');
projectFields.forEach(field => {
console.log(` - ${field.name} (${field.gid})`);
if (field.enum_options) {
field.enum_options.forEach(option => {
console.log(` * ${option.name} (${option.gid})`);
});
}
});
const customFieldsToUpdate = {};
// Handle Priority
if (customFieldsData.priority !== undefined) {
const priorityField = projectFields.find(field => field.name === "Priority");
if (priorityField && priorityField.enum_options) {
let enumOptionGid = null;
if (customFieldsData.priority && customFieldsData.priority !== 'None') {
const enumOption = priorityField.enum_options.find(option =>
option.name.toLowerCase() === customFieldsData.priority.toLowerCase()
);
enumOptionGid = enumOption?.gid || null;
console.log(`🎯 Mapping priority "${customFieldsData.priority}" to GID: ${enumOptionGid}`);
if (!enumOptionGid) {
console.warn(`⚠️ Could not find enum option for priority: ${customFieldsData.priority}`);
console.log('Available priority options:', priorityField.enum_options.map(opt => opt.name));
}
} else {
console.log('🎯 Setting priority to None (null)');
}
customFieldsToUpdate[priorityField.gid] = enumOptionGid;
} else {
console.warn('⚠️ Priority field not found in project fields or missing enum options');
}
}
// Handle Progress
if (customFieldsData.progress !== undefined) {
const progressField = projectFields.find(field => field.name === "Task Progress");
if (progressField && progressField.enum_options) {
let enumOptionGid = null;
if (customFieldsData.progress) {
const enumOption = progressField.enum_options.find(option =>
option.name === customFieldsData.progress
);
enumOptionGid = enumOption?.gid || null;
console.log(`🚀 Mapping progress "${customFieldsData.progress}" to GID: ${enumOptionGid}`);
if (!enumOptionGid) {
console.warn(`⚠️ Could not find enum option for progress: ${customFieldsData.progress}`);
console.log('Available progress options:', progressField.enum_options.map(opt => opt.name));
}
} else {
console.log('🚀 Setting progress to null');
}
customFieldsToUpdate[progressField.gid] = enumOptionGid;
} else {
console.warn('⚠️ Task Progress field not found in project fields or missing enum options');
}
}
console.log('📤 Final custom field mapping:', customFieldsToUpdate);
return customFieldsToUpdate;
} catch (error) {
console.error('❌ Error getting custom field mapping:', error.message);
return {};
}
};
// ========== USER & WORKSPACE ENDPOINTS ==========
app.get('/api/users/me', async (req, res) => {
try {
const data = await makeAsanaRequest('/users/me');
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/workspaces', async (req, res) => {
try {
const data = await makeAsanaRequest('/workspaces');
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/workspaces/:workspaceId/users', async (req, res) => {
try {
const { workspaceId } = req.params;
const data = await makeAsanaRequest(`/workspaces/${workspaceId}/users?opt_fields=name,email,photo`);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ========== ENHANCED PROJECT ENDPOINTS ==========
// Get projects with enhanced fields
app.get('/api/projects', async (req, res) => {
try {
const { workspace, opt_fields } = req.query;
let endpoint = `/projects?workspace=${workspace}`;
if (opt_fields) {
endpoint += `&opt_fields=${opt_fields}`;
} else {
endpoint += `&opt_fields=name,color,created_at,modified_at,owner.name,archived,notes,public,team.name,members.name,current_status.text,followers.name,custom_fields`;
}
console.log('📁 Getting projects with endpoint:', endpoint);
const data = await makeAsanaRequest(endpoint);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get project details with members and status
app.get('/api/projects/:projectId', async (req, res) => {
try {
const { projectId } = req.params;
const endpoint = `/projects/${projectId}?opt_fields=name,notes,color,created_at,modified_at,owner,team,members.name,current_status,followers,archived,public,custom_fields`;
const data = await makeAsanaRequest(endpoint);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Create project
app.post('/api/projects', async (req, res) => {
try {
console.log('🎯 CREATE PROJECT REQUEST RECEIVED');
console.log('📥 Full request body:', JSON.stringify(req.body, null, 2));
const { name, notes, color, workspace, public: isPublic, archived, team } = req.body;
if (!name) {
console.log('❌ Missing project name');
return res.status(400).json({ error: 'Project name is required' });
}
if (!workspace) {
console.log('❌ Missing workspace');
return res.status(400).json({ error: 'Workspace is required' });
}
const projectData = {
name: name.trim(),
workspace: workspace
};
if (notes && notes.trim()) projectData.notes = notes.trim();
if (color) projectData.color = color;
if (isPublic !== undefined) projectData.public = isPublic;
if (archived !== undefined) projectData.archived = archived;
if (team) projectData.team = team;
console.log('📤 Sending to Asana:', JSON.stringify(projectData, null, 2));
const data = await makeAsanaRequest('/projects', 'POST', projectData);
addActivityLog('Created', 'Project', name);
console.log('✅ SUCCESS! Project created');
res.json(data);
} catch (error) {
console.error('❌ CREATE PROJECT ERROR:', error.message);
res.status(500).json({ error: error.message });
}
});
// Update project
app.put('/api/projects/:projectId', async (req, res) => {
try {
const { projectId } = req.params;
const { name, notes, color, public: isPublic, archived } = req.body;
const updateData = {};
if (name !== undefined) updateData.name = name;
if (notes !== undefined) updateData.notes = notes;
if (color !== undefined) updateData.color = color;
if (isPublic !== undefined) updateData.public = isPublic;
if (archived !== undefined) updateData.archived = archived;
const data = await makeAsanaRequest(`/projects/${projectId}`, 'PUT', updateData);
addActivityLog('Updated', 'Project', name || 'Unknown');
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Delete project
app.delete('/api/projects/:projectId', async (req, res) => {
try {
const { projectId } = req.params;
const data = await makeAsanaRequest(`/projects/${projectId}`, 'DELETE');
addActivityLog('Deleted', 'Project', projectId);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Add members to project
app.post('/api/projects/:projectId/members', async (req, res) => {
try {
const { projectId } = req.params;
const { members } = req.body;
const data = await makeAsanaRequest(`/projects/${projectId}/addMembers`, 'POST', { members });
addActivityLog('Added members to', 'Project', projectId);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Remove members from project
app.delete('/api/projects/:projectId/members', async (req, res) => {
try {
const { projectId } = req.params;
const { members } = req.body;
const data = await makeAsanaRequest(`/projects/${projectId}/removeMembers`, 'POST', { members });
addActivityLog('Removed members from', 'Project', projectId);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ========== ENHANCED TASK ENDPOINTS ==========
// Get tasks with enhanced fields
app.get('/api/tasks', async (req, res) => {
try {
const { project, assignee, workspace, opt_fields } = req.query;
let endpoint = '/tasks?';
if (project) endpoint += `project=${project}&`;
if (assignee) endpoint += `assignee=${assignee}&`;
if (workspace) endpoint += `workspace=${workspace}&`;
if (opt_fields) {
endpoint += `opt_fields=${opt_fields}`;
} else {
endpoint += `opt_fields=name,completed,assignee.name,due_on,due_at,created_at,modified_at,notes,custom_fields,tags.name,projects.name,followers.name,num_subtasks,parent.name`;
}
console.log('📋 Getting tasks with endpoint:', endpoint);
const data = await makeAsanaRequest(endpoint);
// 🐛 DEBUG: Show what Asana actually returns
if (data.data && data.data.length > 0) {
console.log('📥 FIRST TASK FROM ASANA:', JSON.stringify(data.data[0], null, 2));
// Check for priority in custom fields
const firstTask = data.data[0];
if (firstTask.custom_fields) {
const priorityField = firstTask.custom_fields.find(field => field.name === "Priority");
console.log('📥 PRIORITY FIELD:', priorityField);
console.log('📥 PRIORITY VALUE:', priorityField?.enum_value?.name);
}
console.log('📥 ALL TASK KEYS:', Object.keys(data.data[0]));
}
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get task details
app.get('/api/tasks/:taskId', async (req, res) => {
try {
const { taskId } = req.params;
const endpoint = `/tasks/${taskId}?opt_fields=name,notes,completed,assignee,due_on,due_at,created_at,modified_at,custom_fields,tags,projects,followers,parent,subtasks,dependencies,dependents`;
const data = await makeAsanaRequest(endpoint);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Create task with custom fields support
app.post('/api/tasks', async (req, res) => {
try {
const { name, notes, due_on, assignee, projects, priority, parent, custom_fields } = req.body;
console.log('📥 Full CREATE request body:', JSON.stringify(req.body, null, 2));
if (!name) {
return res.status(400).json({ error: 'Task name is required' });
}
if (!projects) {
return res.status(400).json({ error: 'Projects array is required' });
}
const taskData = {
name: name.trim(),
projects: Array.isArray(projects) ? projects : [projects]
};
if (notes && notes.trim()) taskData.notes = notes.trim();
if (due_on && due_on.trim()) taskData.due_on = due_on.trim();
if (assignee && assignee.trim()) taskData.assignee = assignee.trim();
if (parent) taskData.parent = parent;
// Handle legacy priority
if (priority && !custom_fields?.priority) {
taskData.priority = priority;
}
console.log('📤 Creating task with data:', JSON.stringify(taskData, null, 2));
// First create the task
const data = await makeAsanaRequest('/tasks', 'POST', taskData);
const newTaskId = data.data.gid;
console.log('✅ Task created with ID:', newTaskId);
// If we have custom fields, set them after creation
if (custom_fields && newTaskId) {
console.log('📋 Setting custom fields on new task...');
try {
const projectId = Array.isArray(projects) ? projects[0] : projects;
// Use the new utility function that creates fields if they don't exist
const customFieldsToUpdate = await getCustomFieldMapping(projectId, custom_fields);
// Update the task with custom fields if we have any
if (Object.keys(customFieldsToUpdate).length > 0) {
console.log('📤 Updating new task custom fields:', customFieldsToUpdate);
await makeAsanaRequest(`/tasks/${newTaskId}`, 'PUT', { custom_fields: customFieldsToUpdate });
console.log('✅ Custom fields set successfully!');
} else {
console.warn('⚠️ No custom fields to update - mapping returned empty object');
}
} catch (customFieldError) {
console.error('⚠️ Custom field update failed:', customFieldError.message);
// Don't fail the whole request, just log the error
}
}
addActivityLog('Created', 'Task', name);
res.json(data);
} catch (error) {
console.error('❌ Task creation error:', error.message);
res.status(500).json({ error: error.message });
}
});
// Update task with custom fields support
app.put('/api/tasks/:taskId', async (req, res) => {
try {
const { taskId } = req.params;
const { name, notes, due_on, completed, assignee, priority, custom_fields } = req.body;
console.log('📥 Full UPDATE request body:', JSON.stringify(req.body, null, 2));
const updateData = {};
if (name !== undefined) updateData.name = name;
if (notes !== undefined) updateData.notes = notes;
if (completed !== undefined) updateData.completed = completed;
if (assignee !== undefined) updateData.assignee = assignee || null;
if (due_on !== undefined) {
updateData.due_on = due_on && due_on.trim() ? due_on.trim() : null;
}
// Handle custom fields for priority and progress
if (custom_fields) {
console.log('📋 Processing custom fields:', custom_fields);
try {
// First, get the task to find which project it belongs to
const currentTask = await makeAsanaRequest(`/tasks/${taskId}?opt_fields=projects`);
const projectId = currentTask.data.projects?.[0]?.gid;
if (projectId) {
console.log('🏗️ Found task project:', projectId);
// Use the new utility function that creates fields if they don't exist
const customFieldsToUpdate = await getCustomFieldMapping(projectId, custom_fields);
// Add custom fields to update data if we have any
if (Object.keys(customFieldsToUpdate).length > 0) {
updateData.custom_fields = customFieldsToUpdate;
console.log('📤 Final custom fields to send:', customFieldsToUpdate);
} else {
console.warn('⚠️ No custom fields to update - mapping returned empty object');
}
} else {
console.log('⚠️ Could not find project for task, skipping custom fields');
}
} catch (customFieldError) {
console.error('⚠️ Custom field processing failed:', customFieldError.message);
// Continue without custom fields
}
}
// Handle legacy priority field (fallback)
if (priority !== undefined && !custom_fields?.priority) {
updateData.priority = priority;
}
console.log('📤 Final update data to Asana:', JSON.stringify(updateData, null, 2));
const data = await makeAsanaRequest(`/tasks/${taskId}`, 'PUT', updateData);
addActivityLog('Updated', 'Task', name || 'Unknown');
res.json(data);
} catch (error) {
console.error('❌ Task update error:', error.message);
res.status(500).json({ error: error.message });
}
});
// Add endpoint to manually create custom fields for a project
app.post('/api/projects/:projectId/custom-fields/ensure', async (req, res) => {
try {
const { projectId } = req.params;
console.log('🔧 Manual custom field creation requested for project:', projectId);
const createdFields = await ensureCustomFieldsExist(projectId);
res.json({
data: {
message: 'Custom fields ensured successfully',
fields: createdFields,
count: createdFields.length
}
});
} catch (error) {
console.error('❌ Manual custom field creation error:', error.message);
res.status(500).json({ error: error.message });
}
});
// Add endpoint to get custom fields for a project
app.get('/api/projects/:projectId/custom-fields', async (req, res) => {
try {
const { projectId } = req.params;
const projectData = await makeAsanaRequest(`/projects/${projectId}?opt_fields=custom_fields`);
const customFields = projectData.data.custom_fields || [];
const priorityField = customFields.find(f => f.name === "Priority");
const progressField = customFields.find(f => f.name === "Task Progress");
res.json({
data: {
all_fields: customFields,
priority_field: priorityField || null,
progress_field: progressField || null,
has_priority: !!priorityField,
has_progress: !!progressField
}
});
} catch (error) {
console.error('❌ Get custom fields error:', error.message);
res.status(500).json({ error: error.message });
}
});
// Delete task
app.delete('/api/tasks/:taskId', async (req, res) => {
try {
const { taskId } = req.params;
const data = await makeAsanaRequest(`/tasks/${taskId}`, 'DELETE');
addActivityLog('Deleted', 'Task', taskId);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get subtasks
app.get('/api/tasks/:taskId/subtasks', async (req, res) => {
try {
const { taskId } = req.params;
const data = await makeAsanaRequest(`/tasks/${taskId}/subtasks?opt_fields=name,completed,assignee.name,due_on`);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ========== TEAM ENDPOINTS ==========
app.get('/api/teams', async (req, res) => {
try {
const { workspace } = req.query;
const data = await makeAsanaRequest(`/teams?workspace=${workspace}&opt_fields=name,description`);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/teams/:teamId/members', async (req, res) => {
try {
const { teamId } = req.params;
const data = await makeAsanaRequest(`/teams/${teamId}/users?opt_fields=name,email,photo`);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ========== TAG ENDPOINTS ==========
app.get('/api/tags', async (req, res) => {
try {
const { workspace } = req.query;
const data = await makeAsanaRequest(`/tags?workspace=${workspace}&opt_fields=name,color,notes`);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/tags', async (req, res) => {
try {
const { name, color, workspace } = req.body;
const tagData = { name, workspace };
if (color) tagData.color = color;
const data = await makeAsanaRequest('/tags', 'POST', tagData);
addActivityLog('Created', 'Tag', name);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ========== CUSTOM STATUS ENDPOINTS ==========
app.get('/api/projects/:projectId/status', async (req, res) => {
try {
const { projectId } = req.params;
const data = await makeAsanaRequest(`/projects/${projectId}/project_statuses`);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/projects/:projectId/status', async (req, res) => {
try {
const { projectId } = req.params;
const { text, color } = req.body;
const statusData = { text, color: color || 'green' };
const data = await makeAsanaRequest(`/projects/${projectId}/project_statuses`, 'POST', statusData);
addActivityLog('Updated status for', 'Project', projectId);
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ========== THEME ENDPOINTS ==========
app.get('/api/themes', (req, res) => {
res.json({ data: themes });
});
app.post('/api/themes', (req, res) => {
const { name, primary, secondary, background } = req.body;
const newTheme = {
id: themes.length + 1,
name,
primary,
secondary,
background
};
themes.push(newTheme);
res.json({ data: newTheme });
});
app.put('/api/themes/:themeId', (req, res) => {
const { themeId } = req.params;
const themeIndex = themes.findIndex(t => t.id === parseInt(themeId));
if (themeIndex === -1) {
return res.status(404).json({ error: 'Theme not found' });
}
themes[themeIndex] = { ...themes[themeIndex], ...req.body };
res.json({ data: themes[themeIndex] });
});
app.delete('/api/themes/:themeId', (req, res) => {
const { themeId } = req.params;
const themeIndex = themes.findIndex(t => t.id === parseInt(themeId));
if (themeIndex === -1) {
return res.status(404).json({ error: 'Theme not found' });
}
themes.splice(themeIndex, 1);
res.json({ data: { success: true } });
});
// ========== NOTIFICATION ENDPOINTS ==========
app.get('/api/notifications', (req, res) => {
res.json({ data: notifications });
});
app.post('/api/notifications', (req, res) => {
const { title, message, type = 'info', userId } = req.body;
const notification = {
id: Date.now(),
title,
message,
type,
userId,
read: false,
createdAt: new Date().toISOString()
};
notifications.unshift(notification);
res.json({ data: notification });
});
app.put('/api/notifications/:notificationId/read', (req, res) => {
const { notificationId } = req.params;
const notification = notifications.find(n => n.id === parseInt(notificationId));
if (!notification) {
return res.status(404).json({ error: 'Notification not found' });
}
notification.read = true;
res.json({ data: notification });
});
app.delete('/api/notifications/:notificationId', (req, res) => {
const { notificationId } = req.params;
const index = notifications.findIndex(n => n.id === parseInt(notificationId));
if (index === -1) {
return res.status(404).json({ error: 'Notification not found' });
}
notifications.splice(index, 1);
res.json({ data: { success: true } });
});
// ========== AI INSIGHTS & ANALYTICS ENDPOINTS ==========
app.get('/api/ai/insights', async (req, res) => {
try {
const { workspace } = req.query;
if (!workspace) {
return res.status(400).json({ error: 'Workspace ID is required' });
}
// Fetch real data from Asana - Get projects first, then tasks from each project
const [projectsData, usersData] = await Promise.all([
makeAsanaRequest(`/projects?workspace=${workspace}&opt_fields=name,completed,due_on,created_at,modified_at,owner.name`),
makeAsanaRequest(`/workspaces/${workspace}/users?opt_fields=name,email`)
]);
const projects = projectsData.data || [];
const users = usersData.data || [];
// Get tasks from all projects (limited to first 10 projects to avoid API limits)
let allTasks = [];
const projectsToProcess = projects.slice(0, 10); // Limit to prevent too many API calls
for (const project of projectsToProcess) {
try {
const tasksData = await makeAsanaRequest(`/tasks?project=${project.gid}&opt_fields=name,completed,due_on,assignee.name,created_at,priority,projects.name&limit=50`);
if (tasksData.data) {
allTasks = allTasks.concat(tasksData.data);
}
} catch (error) {
console.log(`⚠️ Skipping project ${project.name} - ${error.message}`);
continue;
}
}
console.log(`📊 Analyzing ${allTasks.length} tasks from ${projectsToProcess.length} projects`);
// Generate real AI insights
const insights = [];
const now = new Date();
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const threeDaysFromNow = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);
// 1. Task Completion Analysis
const completedTasks = allTasks.filter(task => task.completed);
const totalTasks = allTasks.length;
const completionRate = totalTasks > 0 ? (completedTasks.length / totalTasks) * 100 : 0;
if (totalTasks === 0) {
insights.push({
id: 1,
type: 'info',
title: 'No Tasks Found',
description: `No tasks found in your workspace. Start by creating some tasks in your projects to get AI insights.`,
priority: 'low',
category: 'setup'
});
} else if (completionRate > 80) {
insights.push({
id: 1,
type: 'productivity',
title: 'Excellent Task Completion Rate',
description: `Your team has an outstanding ${completionRate.toFixed(1)}% task completion rate across ${totalTasks} tasks. Keep up the great work!`,
priority: 'high',
category: 'performance'
});
} else if (completionRate < 50) {
insights.push({
id: 1,
type: 'productivity',
title: 'Low Task Completion Rate',
description: `Only ${completionRate.toFixed(1)}% of tasks are completed (${completedTasks.length}/${totalTasks}). Consider reviewing task priorities and workload distribution.`,
priority: 'high',
category: 'performance'
});
} else {
insights.push({
id: 1,
type: 'productivity',
title: 'Good Task Progress',
description: `Your team has a ${completionRate.toFixed(1)}% task completion rate across ${totalTasks} tasks. There's room for improvement!`,
priority: 'medium',
category: 'performance'
});
}
// 2. Overdue Tasks Analysis
const overdueTasks = allTasks.filter(task =>
!task.completed && task.due_on && new Date(task.due_on) < now
);
if (overdueTasks.length > 0) {
insights.push({
id: 2,
type: 'deadline',
title: 'Overdue Tasks Alert',
description: `You have ${overdueTasks.length} overdue task${overdueTasks.length > 1 ? 's' : ''} that need immediate attention. Review and prioritize these items.`,
priority: 'high',
category: 'deadlines'
});
}
// 3. Upcoming Deadlines
const upcomingTasks = allTasks.filter(task =>
!task.completed && task.due_on &&
new Date(task.due_on) >= now && new Date(task.due_on) <= threeDaysFromNow
);
if (upcomingTasks.length > 0) {
insights.push({
id: 3,
type: 'deadline',
title: 'Upcoming Deadlines',
description: `${upcomingTasks.length} task${upcomingTasks.length > 1 ? 's are' : ' is'} due within the next 3 days. Plan your priorities accordingly.`,
priority: 'medium',
category: 'deadlines'
});
}
// 4. Workload Distribution Analysis