@@ -406,6 +406,55 @@ public async Task<IActionResult> AddComment(string id, [FromBody] CommentDto com
406406 }
407407 }
408408
409+ // PATCH /api/tasks/{id}/category - Update only the category of a task
410+ [ HttpPatch ( "{id}/category" ) ]
411+ public async Task < IActionResult > PatchCategory ( string id , [ FromBody ] PatchCategoryDto dto )
412+ {
413+ if ( ! ObjectId . TryParse ( id , out _ ) )
414+ return BadRequest ( new { message = "Invalid ID format." } ) ;
415+
416+ if ( dto == null || string . IsNullOrWhiteSpace ( dto . CategoryId ) )
417+ return BadRequest ( new { message = "CategoryId is required." } ) ;
418+
419+ try
420+ {
421+ // Fetch existing task to get projectId for validation
422+ var existingTask = await _tasksCollection . Find ( t => t . Id == id ) . FirstOrDefaultAsync ( ) ;
423+ if ( existingTask == null )
424+ return NotFound ( new { message = "Task not found." } ) ;
425+
426+ // Validate that categoryId exists and belongs to the task's project
427+ var db = _mongoDbService . GetDatabase ( ) ;
428+ var categoriesCollection = db . GetCollection < FlowModels . Category > ( "categories" ) ;
429+ var category = await categoriesCollection . Find ( c => c . Id == dto . CategoryId ) . FirstOrDefaultAsync ( ) ;
430+
431+ if ( category == null )
432+ return BadRequest ( new { message = "CategoryId does not exist." } ) ;
433+
434+ if ( category . ProjectId != existingTask . ProjectId )
435+ return BadRequest ( new { message = "CategoryId does not belong to the task's project." } ) ;
436+
437+ // Update both CategoryId and Category name
438+ var update = Builders < TaskModel > . Update
439+ . Set ( t => t . CategoryId , dto . CategoryId )
440+ . Set ( t => t . Category , category . CategoryName ) ;
441+
442+ var result = await _tasksCollection . UpdateOneAsync (
443+ Builders < TaskModel > . Filter . Eq ( "_id" , ObjectId . Parse ( id ) ) ,
444+ update
445+ ) ;
446+
447+ if ( result . MatchedCount == 0 )
448+ return NotFound ( new { message = "Task not found." } ) ;
449+
450+ return Ok ( new { message = "Task category updated." , categoryId = dto . CategoryId , categoryName = category . CategoryName } ) ;
451+ }
452+ catch ( Exception ex )
453+ {
454+ return StatusCode ( 500 , new { message = "Failed to update task category." , detail = ex . Message } ) ;
455+ }
456+ }
457+
409458 // DELETE /api/tasks/{id} - Delete a task
410459 [ HttpDelete ( "{id}" ) ]
411460 public async Task < IActionResult > Delete ( string id )
@@ -466,5 +515,11 @@ public class UpdateTaskDto
466515 public string ? StartDate { get ; set ; }
467516 public string ? EndDate { get ; set ; }
468517 }
518+
519+ // DTO for patching only the category
520+ public class PatchCategoryDto
521+ {
522+ public string ? CategoryId { get ; set ; }
523+ }
469524 }
470525}
0 commit comments