using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using AyaNova.Models; using AyaNova.Api.ControllerHelpers; using AyaNova.Biz; namespace AyaNova.Api.Controllers { //DOCUMENTATING THE API //https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/recommended-tags-for-documentation-comments //https://github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments /// /// Translation controller /// [ApiController] [ApiVersion("8.0")] [Route("api/v{version:apiVersion}/translation")] [Produces("application/json")] [Authorize] public class TranslationController : ControllerBase { private readonly AyContext ct; private readonly ILogger log; private readonly ApiServerState serverState; /// /// ctor /// /// /// /// public TranslationController(AyContext dbcontext, ILogger logger, ApiServerState apiServerState) { ct = dbcontext; log = logger; serverState = apiServerState; } /// /// Get Translation all values /// /// /// A single Translation and it's values [HttpGet("{id}")] public async Task GetTranslation([FromRoute] long id) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); if (!ModelState.IsValid) { return BadRequest(new ApiErrorResponse(ModelState)); } //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); var o = await biz.GetAsync(id); if (o == null) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } return Ok(ApiOkResponse.Response(o)); } /// /// Get Translations list /// /// List in alphabetical order of all Translations [HttpGet("list")] public async Task TranslationList() { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); var l = await biz.GetTranslationListAsync(); return Ok(ApiOkResponse.Response(l)); } #if (DEBUG) /// /// Get a coverage report of translation keys used versus unused /// /// Report of all unique translation keys requested since last server reboot [HttpGet("translationkeycoverage")] public async Task TranslationKeyCoverage() { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); var l = await biz.TranslationKeyCoverageAsync(); return Ok(ApiOkResponse.Response(l)); } #endif /// /// Get subset of translation values /// /// List of translation key strings /// A key value array of translation text values [HttpPost("subset")] public async Task SubSet([FromBody] List inObj) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); //Instantiate the business object handler //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); var l = await biz.GetSubsetAsync(inObj); return Ok(ApiOkResponse.Response(l)); } /// /// Duplicates an existing translation with a new name /// /// NameIdItem object containing source translation Id and new name /// From route path /// Error response or newly created translation [HttpPost("duplicate")] public async Task Duplicate([FromBody] NameIdItem inObj, ApiVersion apiVersion) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); var o = await biz.DuplicateAsync(inObj); if (o == null) { //error return return BadRequest(new ApiErrorResponse(biz.Errors)); } else { return CreatedAtAction(nameof(TranslationController.GetTranslation), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o)); } } /// /// Put (UpdateTranslationItemDisplayText) /// Update a single key with new display text /// /// NewText/Id/Concurrency token object. NewText is new display text, Id is TranslationItem Id, concurrency token is required /// [HttpPut("updatetranslationitemdisplaytext")] public async Task PutTranslationItemDisplayText([FromBody] NewTextIdConcurrencyTokenItem inObj) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); if (!ModelState.IsValid) { return BadRequest(new ApiErrorResponse(ModelState)); } var oFromDb = await ct.TranslationItem.SingleOrDefaultAsync(z => z.Id == inObj.Id); if (oFromDb == null) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } //Now fetch translation for rights and to ensure not stock var oDbParent = await ct.Translation.SingleOrDefaultAsync(z => z.Id == oFromDb.TranslationId); if (oDbParent == null) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } if (!Authorized.HasModifyRole(HttpContext.Items, AyaType.Translation)) { return StatusCode(403, new ApiNotAuthorizedResponse()); } //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); try { if (!await biz.PutTranslationItemDisplayTextAsync(oFromDb, inObj, oDbParent)) { return BadRequest(new ApiErrorResponse(biz.Errors)); } } catch (DbUpdateConcurrencyException) { if (!await biz.TranslationItemExistsAsync(inObj.Id)) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } else { //exists but was changed by another user //I considered returning new and old record, but where would it end? //Better to let the client decide what to do than to send extra data that is not required return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT)); } } return Ok(ApiOkResponse.Response(new { Concurrency = oFromDb.Concurrency })); } /// /// Put (UpdateTranslationItemDisplayText) /// Update a list of items with new display text /// /// Array of NewText/Id/Concurrency token objects. NewText is new display text, Id is TranslationItem Id, concurrency token is required /// [HttpPut("updatetranslationitemsdisplaytext")] public async Task PutTranslationItemsDisplayText([FromBody] List inObj) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); if (!ModelState.IsValid) { return BadRequest(new ApiErrorResponse(ModelState)); } var oFromDb = await ct.TranslationItem.AsNoTracking().SingleOrDefaultAsync(z => z.Id == inObj[0].Id); if (oFromDb == null) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } //Now fetch translation for rights and to ensure not stock var oDbParent = await ct.Translation.SingleOrDefaultAsync(z => z.Id == oFromDb.TranslationId); if (oDbParent == null) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } if (!Authorized.HasModifyRole(HttpContext.Items, AyaType.Translation)) { return StatusCode(403, new ApiNotAuthorizedResponse()); } //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); try { if (!await biz.PutTranslationItemsDisplayTextAsync(inObj, oDbParent)) { return BadRequest(new ApiErrorResponse(biz.Errors)); } } catch (DbUpdateConcurrencyException) { //exists but was changed by another user //I considered returning new and old record, but where would it end? //Better to let the client decide what to do than to send extra data that is not required return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT)); } return NoContent(); } /// /// Put (UpdateTranslationName) /// Update a translation to change the name (non-stock Translations only) /// /// NewText/Id/Concurrency token object. NewText is new translation name, Id is Translation Id, concurrency token is required /// [HttpPut("updatetranslationname")] public async Task PutTranslationName([FromBody] NewTextIdConcurrencyTokenItem inObj) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); if (!ModelState.IsValid) { return BadRequest(new ApiErrorResponse(ModelState)); } var oFromDb = await ct.Translation.SingleOrDefaultAsync(z => z.Id == inObj.Id); if (oFromDb == null) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } if (!Authorized.HasModifyRole(HttpContext.Items, AyaType.Translation)) { return StatusCode(403, new ApiNotAuthorizedResponse()); } //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); try { if (!await biz.PutTranslationNameAsync(oFromDb, inObj)) { return BadRequest(new ApiErrorResponse(biz.Errors)); } } catch (DbUpdateConcurrencyException) { if (!await biz.TranslationExistsAsync(inObj.Id)) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } else { //exists but was changed by another user //I considered returning new and old record, but where would it end? //Better to let the client decide what to do than to send extra data that is not required return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT)); } } return Ok(ApiOkResponse.Response(new { Concurrency = oFromDb.Concurrency })); } /// /// Delete Translation /// /// /// Ok [HttpDelete("{id}")] public async Task DeleteTranslation([FromRoute] long id) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); if (!ModelState.IsValid) { return BadRequest(new ApiErrorResponse(ModelState)); } //Fetch translation and it's children //(fetch here so can return proper REST responses on failing basic validity) var dbObj = await ct.Translation.Include(z => z.TranslationItems).SingleOrDefaultAsync(z => z.Id == id); if (dbObj == null) { return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); } if (!Authorized.HasDeleteRole(HttpContext.Items, AyaType.Translation)) { return StatusCode(403, new ApiNotAuthorizedResponse()); } //Instantiate the business object handler TranslationBiz biz = TranslationBiz.GetBiz(ct, HttpContext); if (!await biz.DeleteAsync(dbObj)) { return BadRequest(new ApiErrorResponse(biz.Errors)); } return NoContent(); } #if (DEBUG) public class TranslationCoverageInfo { public List RequestedKeys { get; set; } public int RequestedKeyCount { get; set; } public List NotRequestedKeys { get; set; } public int NotRequestedKeyCount { get; set; } public TranslationCoverageInfo() { RequestedKeys = new List(); NotRequestedKeys = new List(); } } #endif } }