diff --git a/Marco.Pms.Services/Controllers/OrganizationController.cs b/Marco.Pms.Services/Controllers/OrganizationController.cs index 5b00634..697e06d 100644 --- a/Marco.Pms.Services/Controllers/OrganizationController.cs +++ b/Marco.Pms.Services/Controllers/OrganizationController.cs @@ -722,31 +722,31 @@ namespace Marco.Pms.Services.Controllers return NotFound(ApiResponse.ErrorResponse("Organization not found", "Organization not found in database", 404)); } - if (organizationTenantMapping == null) - { - // Create new tenant-organization mapping if none exists - var newMapping = new TenantOrgMapping - { - OrganizationId = organization.Id, - SPRID = organization.SPRID, - AssignedDate = DateTime.UtcNow, - IsActive = true, - AssignedById = loggedInEmployee.Id, - TenantId = tenantId - }; - _context.TenantOrgMappings.Add(newMapping); - await _context.SaveChangesAsync(); - await transaction.CommitAsync(); - - _logger.LogInfo("Assigned organization {OrganizationId} to tenant {TenantId} successfully.", organizationId, tenantId); - } - else + if (organizationTenantMapping != null) { _logger.LogInfo("Organization {OrganizationId} is already assigned to tenant {TenantId}. No action taken.", organizationId, tenantId); // Commit transaction anyway to complete scope cleanly (optional) - await transaction.CommitAsync(); + await transaction.RollbackAsync(); + return StatusCode(409, ApiResponse.ErrorResponse("Organization is already assigned to tenant", "Organization is already assigned to tenant", 409)); } + // Create new tenant-organization mapping if none exists + var newMapping = new TenantOrgMapping + { + OrganizationId = organization.Id, + SPRID = organization.SPRID, + AssignedDate = DateTime.UtcNow, + IsActive = true, + AssignedById = loggedInEmployee.Id, + TenantId = tenantId + }; + _context.TenantOrgMappings.Add(newMapping); + await _context.SaveChangesAsync(); + await transaction.CommitAsync(); + + _logger.LogInfo("Assigned organization {OrganizationId} to tenant {TenantId} successfully.", organizationId, tenantId); + + // Prepare response view model var response = _mapper.Map(organization);