manager-service/ManagerService/Controllers/SectionMenuController.cs
2025-05-23 15:32:30 +02:00

283 lines
11 KiB
C#

using ManagerService.Data;
using ManagerService.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NSwag.Annotations;
namespace ManagerService.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[ApiController, Route("api/[controller]")]
[OpenApiTag("Section menu", Description = "Section menu management")]
public class SectionMenuController : ControllerBase
{
private readonly MyInfoMateDbContext _myInfoMateDbContext;
private readonly ILogger<SectionController> _logger;
private readonly IConfiguration _configuration;
IHexIdGeneratorService idService = new HexIdGeneratorService();
public SectionMenuController(IConfiguration configuration, ILogger<SectionController> logger, MyInfoMateDbContext myInfoMateDbContext)
{
_logger = logger;
_configuration = configuration;
_myInfoMateDbContext = myInfoMateDbContext;
}
/// <summary>
/// Create a new section
/// </summary>
/// <param name="newSection">New section info</param>
/*[ProducesResponseType(typeof(SectionDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost()]
public ObjectResult Create([FromBody] SectionDTO newSection)
{
try
{
if (newSection == null)
throw new ArgumentNullException("Section param is null");
if (newSection.configurationId == null)
throw new ArgumentNullException("Configuration param is null");
var configuration = _myInfoMateDbContext.Configurations.FirstOrDefault(c => c.Id == newSection.configurationId);
if (configuration == null)
throw new KeyNotFoundException("Configuration does not exist");
// Todo add some verification ?
Section section = new Section();
// Preparation
List<string> languages = _configuration.GetSection("SupportedLanguages").Get<List<string>>();
switch (newSection.type)
{
case SectionType.Map:
section = new SectionMap
{
MapMapType = MapTypeApp.hybrid,
MapTypeMapbox = MapTypeMapBox.standard,
MapMapProvider = MapProvider.Google,
MapZoom = 18,
MapPoints = new List<GeoPoint>(),
MapCategories = new List<Categorie>()
};
break;
case SectionType.Slider:
section = new SectionSlider
{
SliderContents = new List<Content>()
};
break;
case SectionType.Video:
section = new SectionVideo
{
VideoSource = "",
};
break;
case SectionType.Web:
section = new SectionWeb
{
WebSource = "",
};
break;
case SectionType.Menu:
section = new SectionMenu
{
MenuSections = new List<Section>(),
};
break;
case SectionType.Quiz:
section = new SectionQuiz
{
QuizQuestions = new List<QuizQuestion>(),
// TODO levels ?
};
break;
case SectionType.Article:
section = new SectionArticle
{
ArticleContents = new List<Content>(),
ArticleContent = LanguageInit.Init("Content", languages),
ArticleAudioIds = LanguageInit.Init("Audio", languages, true)
};
break;
case SectionType.PDF:
section = new SectionPdf
{
PDFOrderedTranslationAndResources = []
};
break;
case SectionType.Puzzle:
section = new SectionPuzzle
{
PuzzleMessageDebut = [],
PuzzleMessageFin = []
};
break;
case SectionType.Agenda:
section = new SectionAgenda
{
AgendaResourceIds = new List<Translation>()
};
break;
case SectionType.Weather:
section = new SectionWeather();
break;
}
section.InstanceId = newSection.instanceId;
section.Label = newSection.label;
section.ImageId = newSection.imageId;
section.ImageSource = newSection.imageSource;
section.ConfigurationId = newSection.configurationId;
section.DateCreation = DateTime.Now.ToUniversalTime();
section.IsSubSection = newSection.isSubSection;
section.ParentId = newSection.parentId;
section.Type = newSection.type;
section.Order = _myInfoMateDbContext.Sections.Count(s => s.ConfigurationId == newSection.configurationId && !s.IsSubSection) + 1;
section.IsBeacon = newSection.isBeacon;
section.BeaconId = newSection.beaconId;
section.Latitude = newSection.latitude;
section.Longitude = newSection.longitude;
section.MeterZoneGPS = newSection.meterZoneGPS;
section.Title = LanguageInit.Init("Title", languages);
section.Description = LanguageInit.Init("Description", languages);
section.Id = idService.GenerateHexId();
//_sectionService.Create(section);
_myInfoMateDbContext.Add(section);
_myInfoMateDbContext.SaveChanges();
return new OkObjectResult(section.ToDTO());
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (InvalidOperationException ex)
{
return new ConflictObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}*/
/// <summary>
/// Update sections order
/// </summary>
/// <param name="updatedSectionsOrder">New sections order</param>
/*[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut("order")]
public ObjectResult UpdateOrder([FromBody] List<SectionDTO> updatedSectionsOrder)
{
// TODO REWRITE LOGIC..
try
{
if (updatedSectionsOrder == null)
throw new ArgumentNullException("Sections param is null");
foreach (var section in updatedSectionsOrder)
{
var sectionDB = _myInfoMateDbContext.Sections.FirstOrDefault(s => s.Id == section.id);
if (sectionDB == null)
throw new KeyNotFoundException($"Section {section.label} with id {section.id} does not exist");
}
foreach (var updatedSection in updatedSectionsOrder)
{
var section = _myInfoMateDbContext.Sections.FirstOrDefault(s => s.Id == updatedSection.id);
//OldSection section = _sectionService.GetById(updatedSection.id);
section.Order = updatedSection.order.GetValueOrDefault();
_myInfoMateDbContext.SaveChanges();
//_sectionService.Update(section.Id, section);
}
if (updatedSectionsOrder.Count > 0) {
MqttClientService.PublishMessage($"config/{updatedSectionsOrder[0].configurationId}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
}
return new ObjectResult("Sections order has been successfully modified") { StatusCode = 200 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}*/
/// <summary>
/// Delete a section
/// </summary>
/// <param name="id">Id of section to delete</param>
/*[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpDelete("{id}")]
public ObjectResult Delete(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Section param is null");
var section = _myInfoMateDbContext.Sections.FirstOrDefault(s => s.Id == id);
if (section == null)
throw new KeyNotFoundException("Section does not exist");
_myInfoMateDbContext.Remove(section);
//_sectionService.Remove(id);
// update order from rest // TODO TEST
List<Section> sections = _myInfoMateDbContext.Sections.Where(s => s.ConfigurationId == section.ConfigurationId && !s.IsSubSection).ToList();
int i = 1;
foreach (var sectionDb in sections.OrderBy(s => s.Order))
{
sectionDb.Order = i;
i++;
}
_myInfoMateDbContext.SaveChanges();
return new ObjectResult("The section has been deleted") { StatusCode = 202 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}*/
}
}