-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1785 lines (1506 loc) Β· 65 KB
/
server.js
File metadata and controls
1785 lines (1506 loc) Β· 65 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);
}
};
// Enhanced function to ensure custom fields exist and are added to project
const ensureProjectCustomFields = async (projectId, workspaceId) => {
try {
console.log('π§ Setting up custom fields for new project:', projectId);
// 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('π Available workspace custom fields:', allWorkspaceFields.map(f => `${f.name} (${f.gid})`));
// Find existing 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);
}
// Create missing fields first
const createdFields = [];
for (const fieldData of fieldsToCreate) {
try {
console.log(`π Creating custom field: ${fieldData.name} in workspace: ${workspaceId}`);
const newField = await makeAsanaRequest('/custom_fields', 'POST', fieldData);
console.log(`β
Created custom field: ${newField.data.name} (${newField.data.gid})`);
createdFields.push(newField.data);
addActivityLog('Created', 'Custom Field', fieldData.name);
} catch (fieldError) {
console.error(`β Failed to create custom field ${fieldData.name}:`, fieldError.message);
}
}
// Combine existing and newly created fields
const allProjectFields = [...existingFields, ...createdFields];
// Add all custom fields to the project
for (const field of allProjectFields) {
try {
console.log(`π Adding custom field to 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) {
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);
}
}
}
console.log('π― Project custom fields setup complete!');
return allProjectFields;
} catch (error) {
console.error('β Error setting up project custom fields:', error.message);
return [];
}
};
// Enhanced utility function to get custom field mapping for tasks
const getCustomFieldMapping = async (projectId, customFieldsData) => {
try {
console.log('π Getting custom field mapping for project:', projectId);
console.log('π Custom fields data received:', customFieldsData);
// First, get the project to find its workspace
const projectInfo = await makeAsanaRequest(`/projects/${projectId}?opt_fields=workspace`);
const workspaceId = projectInfo.data.workspace?.gid;
if (!workspaceId) {
console.error('β Could not get workspace ID for project');
return {};
}
console.log('π’ Project workspace ID:', workspaceId);
// Get ALL workspace custom fields with full details
const workspaceFieldsResponse = await makeAsanaRequest(`/workspaces/${workspaceId}/custom_fields?opt_fields=name,gid,enum_options.name,enum_options.gid,enum_options.color,enum_options.enabled`);
const allWorkspaceFields = workspaceFieldsResponse.data || [];
console.log('π Found', allWorkspaceFields.length, 'workspace custom fields');
// Get project custom field settings to see which fields are attached
const projectFieldsResponse = await makeAsanaRequest(`/projects/${projectId}/custom_field_settings?opt_fields=custom_field.name,custom_field.gid,is_important`);
const projectFieldSettings = projectFieldsResponse.data || [];
console.log('π Found', projectFieldSettings.length, 'custom field settings for project');
// Build a map of custom fields that are attached to this project
const projectCustomFields = [];
for (const setting of projectFieldSettings) {
const fieldGid = setting.custom_field?.gid;
if (fieldGid) {
// Find the full field details from workspace fields
const fullField = allWorkspaceFields.find(wf => wf.gid === fieldGid);
if (fullField) {
projectCustomFields.push(fullField);
console.log(`β
Project has custom field: ${fullField.name} (${fullField.gid})`);
if (fullField.enum_options) {
fullField.enum_options.forEach(option => {
console.log(` - Option: ${option.name} (${option.gid}) [${option.color}]`);
});
}
}
}
}
if (projectCustomFields.length === 0) {
console.log('β οΈ No custom fields are attached to this project');
return {};
}
const customFieldsToUpdate = {};
// Handle Priority
if (customFieldsData.priority !== undefined) {
console.log(`π― Processing priority: "${customFieldsData.priority}"`);
const priorityField = projectCustomFields.find(field => field.name === "Priority");
if (priorityField) {
console.log(`β
Found Priority field: ${priorityField.gid}`);
console.log(`π Priority field enum options:`, priorityField.enum_options);
if (priorityField.enum_options && priorityField.enum_options.length > 0) {
let enumOptionGid = null;
if (customFieldsData.priority && customFieldsData.priority !== 'None') {
const enumOption = priorityField.enum_options.find(option =>
option.name.toLowerCase() === customFieldsData.priority.toLowerCase()
);
if (enumOption) {
enumOptionGid = enumOption.gid;
console.log(`π― β
Mapping priority "${customFieldsData.priority}" to GID: ${enumOptionGid}`);
} else {
console.log(`β Could not find enum option for priority: "${customFieldsData.priority}"`);
console.log('Available options:', priorityField.enum_options.map(opt => `"${opt.name}"`));
}
} else {
console.log('π― Setting priority to None (null)');
}
customFieldsToUpdate[priorityField.gid] = enumOptionGid;
} else {
console.log('β Priority field has no enum options');
}
} else {
console.log('β Priority field not found in project custom fields');
console.log('Available fields:', projectCustomFields.map(f => f.name));
}
}
// Handle Progress
if (customFieldsData.progress !== undefined) {
console.log(`π Processing progress: "${customFieldsData.progress}"`);
const progressField = projectCustomFields.find(field => field.name === "Task Progress");
if (progressField) {
console.log(`β
Found Task Progress field: ${progressField.gid}`);
console.log(`π Progress field enum options:`, progressField.enum_options);
if (progressField.enum_options && progressField.enum_options.length > 0) {
let enumOptionGid = null;
if (customFieldsData.progress) {
const enumOption = progressField.enum_options.find(option =>
option.name === customFieldsData.progress
);
if (enumOption) {
enumOptionGid = enumOption.gid;
console.log(`π β
Mapping progress "${customFieldsData.progress}" to GID: ${enumOptionGid}`);
} else {
console.log(`β Could not find enum option for progress: "${customFieldsData.progress}"`);
console.log('Available options:', progressField.enum_options.map(opt => `"${opt.name}"`));
}
} else {
console.log('π Setting progress to null');
}
customFieldsToUpdate[progressField.gid] = enumOptionGid;
} else {
console.log('β Task Progress field has no enum options');
}
} else {
console.log('β Task Progress field not found in project custom fields');
console.log('Available fields:', projectCustomFields.map(f => f.name));
}
}
console.log('π€ Final custom field mapping:', customFieldsToUpdate);
if (Object.keys(customFieldsToUpdate).length === 0) {
console.log('β οΈ No custom fields will be updated - check that:');
console.log(' 1. Custom fields exist in the project');
console.log(' 2. Field names match exactly ("Priority" and "Task Progress")');
console.log(' 3. Enum option names match exactly');
}
return customFieldsToUpdate;
} catch (error) {
console.error('β Error getting custom field mapping:', error.message);
console.error('β Full error stack:', error.stack);
return {};
}
};
// Add this middleware and protective functions to your main server.js
// Place this BEFORE your existing endpoints
// =============================================================================
// LOCAL ID PROTECTION MIDDLEWARE - Add this to your main server.js
// =============================================================================
// Middleware to block local IDs from reaching Asana API
const protectFromLocalIds = (req, res, next) => {
// Check all possible ID parameters
const ids = [
req.params.taskId,
req.params.projectId,
req.params.id,
req.body?.assignee,
req.body?.parent,
req.body?.projects && Array.isArray(req.body.projects) ? req.body.projects : []
].flat().filter(Boolean);
// Check for any local IDs
const hasLocalId = ids.some(id => typeof id === 'string' && id.startsWith('local_'));
if (hasLocalId) {
const localId = ids.find(id => typeof id === 'string' && id.startsWith('local_'));
console.log(`β οΈ BLOCKED: Attempt to send local ID ${localId} to Asana API`);
return res.status(400).json({
error: 'Local ID not allowed',
message: `Local ID ${localId} cannot be sent to Asana. Please use a real Asana GID.`,
local_id: localId,
help: 'Local IDs must be converted to real Asana GIDs before API calls'
});
}
next();
};
// Apply protection to all Asana API endpoints
app.use('/api/tasks/:taskId', protectFromLocalIds);
app.use('/api/projects/:projectId', protectFromLocalIds);
// =============================================================================
// PROTECTED PROJECT CREATION - Replace your existing POST /api/projects
// =============================================================================
// Replace your existing app.post('/api/projects', ...) with this protected version
app.post('/api/projects', protectFromLocalIds, 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' });
}
// Additional check for workspace being a local ID
if (typeof workspace === 'string' && workspace.startsWith('local_')) {
console.log(`β BLOCKED: Workspace cannot be a local ID: ${workspace}`);
return res.status(400).json({
error: 'Invalid workspace ID',
message: `Workspace ID ${workspace} appears to be a local ID. Please use a real Asana workspace GID.`
});
}
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));
// Create the project first
const data = await makeAsanaRequest('/projects', 'POST', projectData);
const newProjectId = data.data.gid;
console.log('β
Project created with ID:', newProjectId);
// Set up custom fields for the new project
try {
console.log('π§ Setting up custom fields for new project...');
await ensureProjectCustomFields(newProjectId, workspace);
console.log('β
Custom fields setup completed for project');
} catch (customFieldError) {
console.error('β οΈ Custom field setup failed, but project was created:', customFieldError.message);
// Don't fail the whole request, project was created successfully
}
addActivityLog('Created', 'Project', name);
console.log('β
SUCCESS! Project created with custom fields ready');
res.json(data);
} catch (error) {
console.error('β CREATE PROJECT ERROR:', error.message);
res.status(500).json({ error: error.message });
}
});
// =============================================================================
// PROTECTED TASK CREATION - Replace your existing POST /api/tasks
// =============================================================================
// Replace your existing app.post('/api/tasks', ...) with this protected version
app.post('/api/tasks', protectFromLocalIds, async (req, res) => {
try {
const { name, notes, due_on, assignee, projects, priority, parent, custom_fields } = req.body;
console.log('π₯ Full CREATE TASK 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' });
}
// Check for local IDs in projects array
const projectsArray = Array.isArray(projects) ? projects : [projects];
const hasLocalProject = projectsArray.some(id => typeof id === 'string' && id.startsWith('local_'));
if (hasLocalProject) {
const localProject = projectsArray.find(id => typeof id === 'string' && id.startsWith('local_'));
console.log(`β BLOCKED: Cannot create task in local project: ${localProject}`);
return res.status(400).json({
error: 'Local project ID not allowed',
message: `Cannot create task in local project ${localProject}. Please use a real Asana project GID.`,
local_project_id: localProject
});
}
// Check assignee for local ID
if (assignee && typeof assignee === 'string' && assignee.startsWith('local_')) {
console.log(`β BLOCKED: Cannot assign to local user: ${assignee}`);
return res.status(400).json({
error: 'Local assignee ID not allowed',
message: `Cannot assign task to local user ${assignee}. Please use a real Asana user GID.`,
local_assignee_id: assignee
});
}
const taskData = {
name: name.trim(),
projects: projectsArray
};
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;
console.log('π€ Creating task with data:', JSON.stringify(taskData, null, 2));
// Create the task first
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...');
console.log('π Custom fields to process:', custom_fields);
try {
const projectId = projectsArray[0];
console.log('ποΈ Using project ID:', projectId);
const customFieldsToUpdate = await getCustomFieldMapping(projectId, custom_fields);
if (Object.keys(customFieldsToUpdate).length > 0) {
console.log('π€ Updating new task custom fields:', customFieldsToUpdate);
// Make the update request to set custom fields
const updateResponse = 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 });
}
});
// =============================================================================
// PROTECTED TASK UPDATE - Replace your existing PUT /api/tasks/:taskId
// =============================================================================
// Replace your existing app.put('/api/tasks/:taskId', ...) with this protected version
app.put('/api/tasks/:taskId', protectFromLocalIds, async (req, res) => {
try {
const { taskId } = req.params;
const { name, notes, due_on, completed, assignee, custom_fields } = req.body;
console.log('π₯ Full UPDATE TASK request body:', JSON.stringify(req.body, null, 2));
// Additional protection - double check taskId
if (taskId.startsWith('local_')) {
console.log(`β BLOCKED: Cannot update local task ID: ${taskId}`);
return res.status(400).json({
error: 'Local task ID not allowed',
message: `Cannot update local task ${taskId}. Please use a real Asana task GID.`,
local_task_id: taskId
});
}
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
if (custom_fields) {
console.log('π Processing custom fields:', custom_fields);
try {
const currentTask = await makeAsanaRequest(`/tasks/${taskId}?opt_fields=projects`);
const projectId = currentTask.data.projects?.[0]?.gid;
if (projectId) {
const customFieldsToUpdate = await getCustomFieldMapping(projectId, custom_fields);
if (Object.keys(customFieldsToUpdate).length > 0) {
updateData.custom_fields = customFieldsToUpdate;
}
}
} catch (customFieldError) {
console.error('β οΈ Custom field processing failed:', customFieldError.message);
}
}
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 SYNC ENDPOINT FOR LOCAL SERVER COMMUNICATION
// =============================================================================
// Add this endpoint to handle sync requests from your local server
app.post('/api/sync/from-local', async (req, res) => {
try {
const { operation_type, resource_type, resource_id, payload } = req.body;
console.log(`π Sync request from local server: ${operation_type} ${resource_type} ${resource_id}`);
// CRITICAL: Block any local IDs from being processed
if (resource_id.startsWith('local_')) {
console.log(`β οΈ BLOCKED: Sync request with local ID ${resource_id} - rejecting`);
return res.status(400).json({
error: 'Local ID sync not allowed',
message: `Cannot sync local ID ${resource_id} to Asana. Local IDs must be converted first.`,
operation_type,
resource_type,
resource_id
});
}
// Process the sync request safely
let result;
switch (operation_type) {
case 'CREATE':
if (resource_type === 'project') {
result = await makeAsanaRequest('/projects', 'POST', payload);
} else if (resource_type === 'task') {
result = await makeAsanaRequest('/tasks', 'POST', payload);
}
break;
case 'UPDATE':
if (resource_type === 'project') {
result = await makeAsanaRequest(`/projects/${resource_id}`, 'PUT', payload);
} else if (resource_type === 'task') {
result = await makeAsanaRequest(`/tasks/${resource_id}`, 'PUT', payload);
}
break;
case 'DELETE':
if (resource_type === 'project') {
result = await makeAsanaRequest(`/projects/${resource_id}`, 'DELETE');
} else if (resource_type === 'task') {
result = await makeAsanaRequest(`/tasks/${resource_id}`, 'DELETE');
}
break;
default:
throw new Error(`Unknown operation type: ${operation_type}`);
}
console.log(`β
Sync completed: ${operation_type} ${resource_type} ${resource_id}`);
res.json({ success: true, result });
} catch (error) {
console.error('β Sync from local failed:', error.message);
res.status(500).json({
error: 'Sync failed',
message: error.message,
operation: req.body.operation_type,
resource: req.body.resource_id
});
}
});
// ========== 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 with automatic custom field setup
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));
// Create the project first
const data = await makeAsanaRequest('/projects', 'POST', projectData);
const newProjectId = data.data.gid;
console.log('β
Project created with ID:', newProjectId);
// Set up custom fields for the new project
try {
console.log('π§ Setting up custom fields for new project...');
await ensureProjectCustomFields(newProjectId, workspace);
console.log('β
Custom fields setup completed for project');
} catch (customFieldError) {
console.error('β οΈ Custom field setup failed, but project was created:', customFieldError.message);
// Don't fail the whole request, project was created successfully
}
addActivityLog('Created', 'Project', name);
console.log('β
SUCCESS! Project created with custom fields ready');
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);
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 (enhanced)
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 TASK 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;
console.log('π€ Creating task with data:', JSON.stringify(taskData, null, 2));
// Create the task first
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...');
console.log('π Custom fields to process:', custom_fields);
try {
const projectId = Array.isArray(projects) ? projects[0] : projects;
console.log('ποΈ Using project ID:', projectId);
const customFieldsToUpdate = await getCustomFieldMapping(projectId, custom_fields);
if (Object.keys(customFieldsToUpdate).length > 0) {
console.log('π€ Updating new task custom fields:', customFieldsToUpdate);
// Make the update request to set custom fields
const updateResponse = await makeAsanaRequest(`/tasks/${newTaskId}`, 'PUT', {
custom_fields: customFieldsToUpdate
});
console.log('β
Custom fields set successfully!');
console.log('π₯ Update response status:', updateResponse ? 'Success' : 'Failed');
} else {
console.warn('β οΈ No custom fields to update - mapping returned empty object');
console.log('π This might mean:');
console.log(' - Custom fields don\'t exist in the project yet');
console.log(' - There was an issue with field mapping');
console.log(' - The field names don\'t match exactly');
}
} catch (customFieldError) {
console.error('β Custom field update failed:', customFieldError.message);
console.error('β Full error:', customFieldError);
// Don't fail the whole request, just log the error
}
} else {
if (!custom_fields) {
console.log('βΉοΈ No custom fields provided in request');
}
if (!newTaskId) {
console.log('β No task ID available for custom field update');
}
}
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 (simplified)
app.put('/api/tasks/:taskId', async (req, res) => {
try {
const { taskId } = req.params;
const { name, notes, due_on, completed, assignee, custom_fields } = req.body;
console.log('π₯ Full UPDATE TASK 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
if (custom_fields) {
console.log('π Processing custom fields:', custom_fields);
try {
const currentTask = await makeAsanaRequest(`/tasks/${taskId}?opt_fields=projects`);
const projectId = currentTask.data.projects?.[0]?.gid;
if (projectId) {
const customFieldsToUpdate = await getCustomFieldMapping(projectId, custom_fields);
if (Object.keys(customFieldsToUpdate).length > 0) {
updateData.custom_fields = customFieldsToUpdate;
}
}