From e0aa975f63d7da31e3e03ddffb4d5403792f8805 Mon Sep 17 00:00:00 2001 From: danjov Date: Wed, 10 Jan 2024 11:39:27 +0100 Subject: [PATCH 1/4] Add Edit functionality for stratigraphies in .NET API --- src/api/Controllers/StratigraphyController.cs | 48 +++++++++ .../Controllers/StratigraphyControllerTest.cs | 97 ++++++++++++++++--- 2 files changed, 133 insertions(+), 12 deletions(-) diff --git a/src/api/Controllers/StratigraphyController.cs b/src/api/Controllers/StratigraphyController.cs index dd0ef70a4..3a715513b 100644 --- a/src/api/Controllers/StratigraphyController.cs +++ b/src/api/Controllers/StratigraphyController.cs @@ -246,4 +246,52 @@ public async Task> AddBedrockLayerAsync([Required] int id) return Ok(bedrockLayer.Id); } + + /// + [Authorize(Policy = PolicyNames.Viewer)] + public override async Task> EditAsync(Stratigraphy entity) + { + try + { + // Check if associated borehole is locked + var userName = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value; + if (await boreholeLockService.IsBoreholeLockedAsync(entity.BoreholeId, userName).ConfigureAwait(false)) + { + return Problem("The borehole is locked by another user."); + } + } + catch (UnauthorizedAccessException) + { + return Unauthorized("You are not authorized to add a bedrock layer to this stratigraphy."); + } + catch (Exception ex) + { + var message = "An error ocurred while adding a bedrock layer to the stratigraphy."; + Logger.LogError(ex, message); + return Problem(message); + } + + var editResult = await base.EditAsync(entity).ConfigureAwait(false); + if (editResult.Result is not OkObjectResult) return editResult; + + // If the stratigraphy to edit is the primary stratigraphy, + // then reset any other primary stratigraphies of the borehole. + if (entity.IsPrimary.GetValueOrDefault()) + { + var otherPrimaryStratigraphies = await Context.Stratigraphies + .Where(s => s.BoreholeId == entity.BoreholeId && s.IsPrimary == true && s.Id != entity.Id) + .ToListAsync() + .ConfigureAwait(false); + + foreach (var stratigraphy in otherPrimaryStratigraphies) + { + stratigraphy.IsPrimary = false; + Context.Update(stratigraphy); + } + + await Context.UpdateChangeInformationAndSaveChangesAsync(HttpContext).ConfigureAwait(false); + } + + return editResult; + } } diff --git a/tests/Controllers/StratigraphyControllerTest.cs b/tests/Controllers/StratigraphyControllerTest.cs index 531782f4c..e7131b813 100644 --- a/tests/Controllers/StratigraphyControllerTest.cs +++ b/tests/Controllers/StratigraphyControllerTest.cs @@ -300,12 +300,7 @@ public async Task CreateWithUserNotSet() [TestMethod] public async Task CreateForLockedBorehole() { - var boreholeLockServiceMock = new Mock(MockBehavior.Strict); - boreholeLockServiceMock - .Setup(x => x.IsBoreholeLockedAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(true); - - controller = new StratigraphyController(context, new Mock>().Object, boreholeLockServiceMock.Object) { ControllerContext = GetControllerContextAdmin() }; + SetupControllerWithAlwaysLockedBorehole(); var createResult = await controller.CreateAsync(new()); ActionResultAssert.IsInternalServerError(createResult.Result); @@ -365,18 +360,86 @@ public async Task AddBedrockLayerForBoreholeWithoutTopBedrockValue() [TestMethod] public async Task AddBedrockLayerForLockedBorehole() { - var boreholeLockServiceMock = new Mock(MockBehavior.Strict); - boreholeLockServiceMock - .Setup(x => x.IsBoreholeLockedAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(true); - - controller = new StratigraphyController(context, new Mock>().Object, boreholeLockServiceMock.Object) { ControllerContext = GetControllerContextAdmin() }; + SetupControllerWithAlwaysLockedBorehole(); var existingStratigraphy = await context.Stratigraphies.FirstAsync(); var addBedrockResult = await controller.AddBedrockLayerAsync(existingStratigraphy.Id); ActionResultAssert.IsInternalServerError(addBedrockResult.Result, "locked"); } + [TestMethod] + public async Task Edit() + { + var borehole = await context.Boreholes.OrderBy(x => x.CreatedById).LastAsync(); + var stratigraphyToEdit = await context.Stratigraphies.FirstAsync(); + stratigraphyToEdit.BoreholeId = borehole.Id; + stratigraphyToEdit.KindId = StratigraphyController.StratigraphyKindId; + stratigraphyToEdit.IsPrimary = false; + stratigraphyToEdit.Date = new DateTime(1999, 9, 9).ToUniversalTime(); + stratigraphyToEdit.Name = "ERRONEOUS"; + stratigraphyToEdit.Notes = "REDPOINT"; + + var editResult = await controller.EditAsync(stratigraphyToEdit); + var editedStratigraphy = ActionResultAssert.IsOkObjectResult(editResult.Result); + Assert.AreEqual(borehole.Id, editedStratigraphy.BoreholeId); + Assert.AreEqual(StratigraphyController.StratigraphyKindId, editedStratigraphy.KindId); + Assert.AreEqual(false, editedStratigraphy.IsPrimary); + Assert.AreEqual(new DateTime(1999, 9, 9).ToUniversalTime(), editedStratigraphy.Date); + Assert.AreEqual("ERRONEOUS", editedStratigraphy.Name); + Assert.AreEqual("REDPOINT", editedStratigraphy.Notes); + } + + [TestMethod] + public async Task EditSetMainStratigraphy() + { + // Precondition: Create two stratigraphies for the same borehole, + // one of which is the main stratigraphy. + var boreholeWithoutStratigraphy = await context + .Boreholes + .Include(b => b.Stratigraphies) + .FirstAsync(b => !b.Stratigraphies.Any()); + + var firstStratigraphy = new Stratigraphy + { + IsPrimary = true, + KindId = StratigraphyController.StratigraphyKindId, + BoreholeId = boreholeWithoutStratigraphy.Id, + Name = "FALLOUT-VII", + }; + + var secondStratigraphy = new Stratigraphy + { + IsPrimary = false, + KindId = StratigraphyController.StratigraphyKindId, + BoreholeId = boreholeWithoutStratigraphy.Id, + Name = "KARMACANDID", + }; + + firstStratigraphy = ActionResultAssert.IsOkObjectResult((await controller.CreateAsync(firstStratigraphy)).Result); + secondStratigraphy = ActionResultAssert.IsOkObjectResult((await controller.CreateAsync(secondStratigraphy)).Result); + + // Setting the second stratigraphy as the main stratigraphy + // should set the first stratigraphy as non-main. + secondStratigraphy.IsPrimary = true; + secondStratigraphy = ActionResultAssert.IsOkObjectResult((await controller.EditAsync(secondStratigraphy)).Result); + Assert.AreEqual(true, secondStratigraphy.IsPrimary); + Assert.AreEqual("KARMACANDID", secondStratigraphy.Name); + + firstStratigraphy = GetStratigraphy(firstStratigraphy.Id); + Assert.AreEqual(false, firstStratigraphy.IsPrimary); + Assert.AreEqual("FALLOUT-VII", firstStratigraphy.Name); + } + + [TestMethod] + public async Task EditForLockedBorehole() + { + SetupControllerWithAlwaysLockedBorehole(); + + var existingStratigraphy = await context.Stratigraphies.FirstAsync(); + var editResult = await controller.EditAsync(existingStratigraphy); + ActionResultAssert.IsInternalServerError(editResult.Result, "locked"); + } + private void AssertStratigraphy(Stratigraphy actual, int expectedBoreholeId, string exptectedName, string expectedNotes) { Assert.AreEqual(StratigraphyController.StratigraphyKindId, actual.KindId); @@ -384,4 +447,14 @@ private void AssertStratigraphy(Stratigraphy actual, int expectedBoreholeId, str Assert.AreEqual(exptectedName, actual.Name); Assert.AreEqual(expectedNotes, actual.Notes); } + + private void SetupControllerWithAlwaysLockedBorehole() + { + var boreholeLockServiceMock = new Mock(MockBehavior.Strict); + boreholeLockServiceMock + .Setup(x => x.IsBoreholeLockedAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + + controller = new StratigraphyController(context, new Mock>().Object, boreholeLockServiceMock.Object) { ControllerContext = GetControllerContextAdmin() }; + } } From 9acb872f53e018e145362bf2f65ae2e6bc3f588f Mon Sep 17 00:00:00 2001 From: danjov Date: Wed, 10 Jan 2024 11:39:27 +0100 Subject: [PATCH 2/4] Simplify reading username out of current HttpContext --- src/api/BoreholeFileUploadService.cs | 7 +++---- src/api/Controllers/BoreholeController.cs | 3 +-- src/api/Controllers/StratigraphyController.cs | 9 ++++----- src/api/Controllers/UploadController.cs | 3 +-- src/api/Controllers/UserController.cs | 4 +--- src/api/HttpContextExtensions.cs | 17 +++++++++++++++++ 6 files changed, 27 insertions(+), 16 deletions(-) create mode 100644 src/api/HttpContextExtensions.cs diff --git a/src/api/BoreholeFileUploadService.cs b/src/api/BoreholeFileUploadService.cs index 9d3f11742..a3fb7490d 100644 --- a/src/api/BoreholeFileUploadService.cs +++ b/src/api/BoreholeFileUploadService.cs @@ -2,7 +2,6 @@ using Amazon.S3.Model; using BDMS.Models; using Microsoft.EntityFrameworkCore; -using System.Security.Claims; using System.Security.Cryptography; namespace BDMS; @@ -52,7 +51,7 @@ public async Task UploadFileAndLinkToBorehole(IFormFile file, int boreholeId) using var transaction = context.Database.CurrentTransaction == null ? await context.Database.BeginTransactionAsync().ConfigureAwait(false) : null; try { - var userName = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value; + var userName = httpContextAccessor.HttpContext?.GetUserName(); var user = await context.Users .AsNoTracking() @@ -70,7 +69,7 @@ public async Task UploadFileAndLinkToBorehole(IFormFile file, int boreholeId) var bdmsFile = new Models.File { Name = file.FileName, NameUuid = fileNameGuid, Hash = base64Hash, Type = file.ContentType }; await context.Files.AddAsync(bdmsFile).ConfigureAwait(false); - await context.UpdateChangeInformationAndSaveChangesAsync(httpContextAccessor.HttpContext).ConfigureAwait(false); + await context.UpdateChangeInformationAndSaveChangesAsync(httpContextAccessor.HttpContext!).ConfigureAwait(false); fileId = bdmsFile.Id; @@ -85,7 +84,7 @@ public async Task UploadFileAndLinkToBorehole(IFormFile file, int boreholeId) var boreholeFile = new BoreholeFile { FileId = (int)fileId, BoreholeId = boreholeId, UserId = user.Id, Attached = DateTime.UtcNow }; await context.BoreholeFiles.AddAsync(boreholeFile).ConfigureAwait(false); - await context.UpdateChangeInformationAndSaveChangesAsync(httpContextAccessor.HttpContext).ConfigureAwait(false); + await context.UpdateChangeInformationAndSaveChangesAsync(httpContextAccessor.HttpContext!).ConfigureAwait(false); if (transaction != null) await transaction.CommitAsync().ConfigureAwait(false); } diff --git a/src/api/Controllers/BoreholeController.cs b/src/api/Controllers/BoreholeController.cs index a5ab82ba0..8a4c2111e 100644 --- a/src/api/Controllers/BoreholeController.cs +++ b/src/api/Controllers/BoreholeController.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; -using System.Security.Claims; namespace BDMS.Controllers; @@ -36,7 +35,7 @@ public async Task> CopyAsync([Required] int id, [Required] int var user = await context.Users .Include(u => u.WorkgroupRoles) .AsNoTracking() - .SingleOrDefaultAsync(u => u.Name == HttpContext.User.FindFirst(ClaimTypes.Name).Value) + .SingleOrDefaultAsync(u => u.Name == HttpContext.GetUserName()) .ConfigureAwait(false); if (user == null || !user.WorkgroupRoles.Any(w => w.WorkgroupId == workgroupId && w.Role == Role.Editor)) diff --git a/src/api/Controllers/StratigraphyController.cs b/src/api/Controllers/StratigraphyController.cs index 3a715513b..8a6830fc6 100644 --- a/src/api/Controllers/StratigraphyController.cs +++ b/src/api/Controllers/StratigraphyController.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; -using System.Security.Claims; namespace BDMS.Controllers; @@ -59,7 +58,7 @@ public async Task> CopyAsync([Required] int id) var user = await Context.Users .Include(u => u.WorkgroupRoles) .AsNoTracking() - .SingleOrDefaultAsync(u => u.Name == HttpContext.User.FindFirst(ClaimTypes.Name).Value) + .SingleOrDefaultAsync(u => u.Name == HttpContext.GetUserName()) .ConfigureAwait(false); if (user == null || !user.WorkgroupRoles.Any(w => w.Role == Role.Editor)) @@ -161,7 +160,7 @@ public override async Task> CreateAsync(Stratigraphy try { // Check if associated borehole is locked - var userName = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value; + var userName = HttpContext.GetUserName(); if (await boreholeLockService.IsBoreholeLockedAsync(entity.BoreholeId, userName).ConfigureAwait(false)) { return Problem("The borehole is locked by another user."); @@ -207,7 +206,7 @@ public async Task> AddBedrockLayerAsync([Required] int id) try { // Check if associated borehole is locked - var userName = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value; + var userName = HttpContext.GetUserName(); if (await boreholeLockService.IsBoreholeLockedAsync(stratigraphy.BoreholeId, userName).ConfigureAwait(false)) { return Problem("The borehole is locked by another user."); @@ -254,7 +253,7 @@ public override async Task> EditAsync(Stratigraphy en try { // Check if associated borehole is locked - var userName = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value; + var userName = HttpContext.GetUserName(); if (await boreholeLockService.IsBoreholeLockedAsync(entity.BoreholeId, userName).ConfigureAwait(false)) { return Problem("The borehole is locked by another user."); diff --git a/src/api/Controllers/UploadController.cs b/src/api/Controllers/UploadController.cs index bec81ad4a..31e8a2c13 100644 --- a/src/api/Controllers/UploadController.cs +++ b/src/api/Controllers/UploadController.cs @@ -8,7 +8,6 @@ using Microsoft.EntityFrameworkCore; using System.Globalization; using System.Net; -using System.Security.Claims; namespace BDMS.Controllers; @@ -93,7 +92,7 @@ public async Task> UploadFileAsync(int workgroupId, IFormFile return ValidationProblem(statusCode: (int)HttpStatusCode.BadRequest); } - var userName = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value; + var userName = HttpContext.GetUserName(); var user = await context.Users .AsNoTracking() diff --git a/src/api/Controllers/UserController.cs b/src/api/Controllers/UserController.cs index c4fa20c0d..926b5c023 100644 --- a/src/api/Controllers/UserController.cs +++ b/src/api/Controllers/UserController.cs @@ -3,8 +3,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using Swashbuckle.AspNetCore.Annotations; -using System.Security.Claims; namespace BDMS.Controllers; @@ -29,7 +27,7 @@ public UserController(BdmsContext context) [HttpGet("self")] [Authorize(Policy = PolicyNames.Viewer)] public async Task> GetUserInformationAsync() => - await context.Users.SingleOrDefaultAsync(u => u.Name == HttpContext.User.FindFirst(ClaimTypes.Name).Value).ConfigureAwait(false); + await context.Users.SingleOrDefaultAsync(u => u.Name == HttpContext.GetUserName()).ConfigureAwait(false); /// /// Gets the user list. diff --git a/src/api/HttpContextExtensions.cs b/src/api/HttpContextExtensions.cs new file mode 100644 index 000000000..c584b19cf --- /dev/null +++ b/src/api/HttpContextExtensions.cs @@ -0,0 +1,17 @@ +using System.Security.Claims; + +namespace BDMS; + +/// +/// Provides extension methods for the . +/// +internal static class HttpContextExtensions +{ + /// + /// Gets the name of the user from the . + /// + /// The current . + /// The username or null, if the username cannot be read. + internal static string GetUserName(this HttpContext httpContext) + => httpContext.User.FindFirst(ClaimTypes.Name).Value; +} From dc3bfdc4bdfe95ba24f0b42208e79d102fd457ac Mon Sep 17 00:00:00 2001 From: danjov Date: Wed, 10 Jan 2024 11:39:27 +0100 Subject: [PATCH 3/4] Add GetById functionality for stratigraphies in .NET API --- src/api/Controllers/StratigraphyController.cs | 30 +++++++++++++++---- .../Controllers/StratigraphyControllerTest.cs | 18 +++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/api/Controllers/StratigraphyController.cs b/src/api/Controllers/StratigraphyController.cs index 8a6830fc6..c97f72c50 100644 --- a/src/api/Controllers/StratigraphyController.cs +++ b/src/api/Controllers/StratigraphyController.cs @@ -21,6 +21,26 @@ public StratigraphyController(BdmsContext context, ILogger logger, this.boreholeLockService = boreholeLockService; } + /// + /// Asynchronously gets the with the specified . + /// + /// The id of the to get. + [HttpGet("{id}")] + [Authorize(Policy = PolicyNames.Viewer)] + public async Task> GetByIdAsync([Required] int id) + { + var stratigraphy = await Context.Stratigraphies + .SingleOrDefaultAsync(x => x.Id == id) + .ConfigureAwait(false); + + if (stratigraphy == null) + { + return NotFound(); + } + + return Ok(stratigraphy); + } + /// /// Asynchronously gets the s, optionally filtered by and . /// @@ -261,11 +281,11 @@ public override async Task> EditAsync(Stratigraphy en } catch (UnauthorizedAccessException) { - return Unauthorized("You are not authorized to add a bedrock layer to this stratigraphy."); + return Unauthorized("You are not authorized to edit to this stratigraphy."); } catch (Exception ex) { - var message = "An error ocurred while adding a bedrock layer to the stratigraphy."; + var message = "An error ocurred while editing the stratigraphy."; Logger.LogError(ex, message); return Problem(message); } @@ -282,10 +302,10 @@ public override async Task> EditAsync(Stratigraphy en .ToListAsync() .ConfigureAwait(false); - foreach (var stratigraphy in otherPrimaryStratigraphies) + foreach (var other in otherPrimaryStratigraphies) { - stratigraphy.IsPrimary = false; - Context.Update(stratigraphy); + other.IsPrimary = false; + Context.Update(other); } await Context.UpdateChangeInformationAndSaveChangesAsync(HttpContext).ConfigureAwait(false); diff --git a/tests/Controllers/StratigraphyControllerTest.cs b/tests/Controllers/StratigraphyControllerTest.cs index e7131b813..caa70bdf0 100644 --- a/tests/Controllers/StratigraphyControllerTest.cs +++ b/tests/Controllers/StratigraphyControllerTest.cs @@ -79,6 +79,24 @@ public async Task GetCasingsByBoreholeId() Assert.AreEqual(stratigraphy.UpdatedById, 2); } + [TestMethod] + public async Task GetById() + { + var stratigraphyResult = await controller.GetByIdAsync(StratigraphyId); + + var stratigraphy = ActionResultAssert.IsOkObjectResult(stratigraphyResult.Result); + Assert.AreEqual(stratigraphy.BoreholeId, 1008078); + Assert.AreEqual(stratigraphy.Name, "Earnest Little"); + Assert.AreEqual(stratigraphy.Notes, "My co-worker Tyron has one of these. He says it looks stout."); + } + + [TestMethod] + public async Task GetByUnknownId() + { + var stratigraphyResult = await controller.GetByIdAsync(int.MinValue); + ActionResultAssert.IsNotFound(stratigraphyResult.Result); + } + [TestMethod] public async Task Copy() { From 0827e2fbd593bcc607de63e410b80cb1fc5900d1 Mon Sep 17 00:00:00 2001 From: danjov Date: Wed, 10 Jan 2024 11:39:27 +0100 Subject: [PATCH 4/4] Use .NET API for editing stratigraphies --- CHANGELOG.md | 1 + src/api-legacy/__init__.py | 1 - src/api-legacy/main.py | 3 - src/api-legacy/v1/borehole/profile/patch.py | 190 ------------------ .../v1/borehole/profile/producer.py | 49 ----- src/client/src/api-lib/index.js | 8 +- src/client/src/api/fetchApiV2.js | 12 ++ .../components/profileInfo/api/index.js | 33 +-- 8 files changed, 33 insertions(+), 264 deletions(-) delete mode 100644 src/api-legacy/v1/borehole/profile/patch.py delete mode 100644 src/api-legacy/v1/borehole/profile/producer.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d42511274..01587947a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Changed - Updated layer management to use the .NET API. +- Update stratigraphy management to use the .NET API. ## v2.0.506 - 2023-12-21 diff --git a/src/api-legacy/__init__.py b/src/api-legacy/__init__.py index 3d93452f4..a9bacb176 100644 --- a/src/api-legacy/__init__.py +++ b/src/api-legacy/__init__.py @@ -36,7 +36,6 @@ # Profiles's ACTION Handlers from bms.v1.borehole.profile.viewer import ProfileViewerHandler -from bms.v1.borehole.profile.producer import ProfileProducerHandler # Profiles layers's ACTION Handlers from bms.v1.borehole.profile.layer.viewer import ProfileLayerViewerHandler diff --git a/src/api-legacy/main.py b/src/api-legacy/main.py index d09f6db87..ac4c024dc 100644 --- a/src/api-legacy/main.py +++ b/src/api-legacy/main.py @@ -146,7 +146,6 @@ async def close(application): # Profile handlers ProfileViewerHandler, - ProfileProducerHandler, # Layer handlers ProfileLayerViewerHandler, @@ -221,11 +220,9 @@ async def close(application): # Profile handlers (r'/api/v1/borehole/profile', ProfileViewerHandler), - (r'/api/v1/borehole/profile/edit', ProfileProducerHandler), # Profile Layer handlers (r'/api/v1/borehole/profile/layer', ProfileLayerViewerHandler), - (r'/api/v1/borehole/profile/layer/edit', ProfileProducerHandler), # Other handlers (r'/api/v1/borehole/codes', CodeListHandler), diff --git a/src/api-legacy/v1/borehole/profile/patch.py b/src/api-legacy/v1/borehole/profile/patch.py deleted file mode 100644 index 7849a53e0..000000000 --- a/src/api-legacy/v1/borehole/profile/patch.py +++ /dev/null @@ -1,190 +0,0 @@ -# -*- coding: utf-8 -*- -from bms.v1.action import Action -from bms.v1.exceptions import ( - PatchAttributeException -) -import traceback - - -class PatchProfile(Action): - - async def execute(self, id, field, value, user_id): - try: - # Updating character varing, boolean fields - if field in [ - 'date', 'date_spud', 'date_fin', 'date_abd' - ]: - - column = None - - if field == 'date': - column = 'date_sty' - - elif field == 'date_abd': - column = 'casng_date_abd_sty' - - if value == '': - value = None - - await self.conn.execute(""" - UPDATE bdms.stratigraphy - SET - %s = to_date($1, 'YYYY-MM-DD'), - update_sty = now(), - updater_sty = $2 - WHERE id_sty = $3 - """ % column, value, user_id, id) - - elif field in ['primary']: - # Boolean values - - column = None - - if field == 'primary': - column = 'primary_sty' - - if value not in [True, False]: - raise Exception( - f"Value of field {field} is not a boolean" - ) - - if value: - # Reset all others stratigraphy to false - - id_bho = await self.conn.fetchval(""" - SELECT - id_bho_fk - FROM - bdms.stratigraphy - WHERE - id_sty = $1 - """, id) - - await self.conn.execute(""" - UPDATE bdms.stratigraphy - SET - %s = FALSE, - update_sty = now(), - updater_sty = $1 - WHERE id_bho_fk = $2 - """ % column, user_id, id_bho) - - await self.conn.execute(""" - UPDATE bdms.stratigraphy - SET - %s = $1, - update_sty = now(), - updater_sty = $2 - WHERE id_sty = $3 - """ % column, value, user_id, id) - - elif field in [ - 'name', 'fill_name', 'notes' - ]: - # Text values - - column = None - - if field in ['name', 'fill_name']: - column = 'name_sty' - - elif field == 'notes': - column = 'notes_sty' - - await self.conn.execute(""" - UPDATE bdms.stratigraphy - SET - %s = $1, - update_sty = now(), - updater_sty = $2 - WHERE id_sty = $3 - """ % column, value, user_id, id) - - elif field in [ - 'kind' - ]: - - column = None - schema = field - - if field == 'kind': - column = 'kind_id_cli' - schema = 'layer_kind' - - # Check if domain is extracted from the correct schema - if value is not None and schema != (await self.conn.fetchval(""" - SELECT - schema_cli - FROM - bdms.codelist - WHERE - id_cli = $1 - """, value)): - raise Exception( - "Attribute id %s not part of schema %s" % - ( - value, schema - ) - ) - - await self.conn.execute(""" - UPDATE bdms.stratigraphy - SET - %s = $1, - update_sty = now(), - updater_sty = $2 - WHERE id_sty = $3 - """ % column, value, user_id, id) - - elif field in [ - 'fill_casing' - ]: - column = None - schema = field - - if field == 'fill_casing': - column = 'fill_casng_id_sty_fk' - - if value is not None and value != 0: - # Check that the casing and the filling borehole is the same - fill_borehole_id = await self.conn.fetchval(""" - SELECT - id_bho_fk - FROM - bdms.stratigraphy - WHERE - id_sty = $1 - """, id) - - casng_borehole_id = await self.conn.fetchval(""" - SELECT - id_bho_fk - FROM - bdms.stratigraphy - WHERE - id_sty = $1 - """, value) - - if casng_borehole_id != fill_borehole_id: - raise Exception( - "Casing and filling borehole must be the same" - ) - - await self.conn.execute(""" - UPDATE bdms.stratigraphy - SET - %s = $1 - WHERE id_sty = $2 - """ % column, value, id) - - else: - raise PatchAttributeException(field) - - return None - - except PatchAttributeException as bmsx: - raise bmsx - - except Exception: - print(traceback.print_exc()) - raise Exception("Error while updating stratigraphy") diff --git a/src/api-legacy/v1/borehole/profile/producer.py b/src/api-legacy/v1/borehole/profile/producer.py deleted file mode 100644 index 603b337e9..000000000 --- a/src/api-legacy/v1/borehole/profile/producer.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -from bms.v1.borehole.profile.patch import PatchProfile -from bms.v1.handlers import Producer - - -class ProfileProducerHandler(Producer): - async def execute(self, request): - action = request.pop('action', None) - - if action in [ - 'PATCH' - ]: - - async with self.pool.acquire() as conn: - - exe = None - - id_bho = None - - if action in [ - 'PATCH', - ]: - # Get Borehole id - id_bho = await conn.fetchval(""" - SELECT - id_bho_fk - FROM - bdms.stratigraphy - WHERE - id_sty = $1; - """, request['id']) - - # Lock check - await self.check_lock( - id_bho, self.user, conn - ) - - if action == 'PATCH': - exe = PatchProfile(conn) - request['user_id'] = self.user['id'] - - request.pop('lang', None) - - if exe is not None: - return ( - await exe.execute(**request) - ) - - raise Exception("Action '%s' unknown" % action) diff --git a/src/client/src/api-lib/index.js b/src/client/src/api-lib/index.js index b9f6c9319..d9eb68183 100644 --- a/src/client/src/api-lib/index.js +++ b/src/client/src/api-lib/index.js @@ -83,12 +83,7 @@ import { getLayers, } from "./actions/stratigraphy"; -import { - getProfile, - getProfiles, - getProfileLayers, - patchProfile, -} from "./actions/profile"; +import { getProfile, getProfiles, getProfileLayers } from "./actions/profile"; import { loadDomains, patchCodeConfig } from "./actions/domains"; @@ -167,7 +162,6 @@ export { getProfile, getProfiles, getProfileLayers, - patchProfile, loadDomains, patchCodeConfig, getWms, diff --git a/src/client/src/api/fetchApiV2.js b/src/client/src/api/fetchApiV2.js index 5f7db8956..06ac647b5 100644 --- a/src/client/src/api/fetchApiV2.js +++ b/src/client/src/api/fetchApiV2.js @@ -171,6 +171,10 @@ export const deleteFaciesDescription = async id => { export const fetchUsers = async () => await fetchApiV2("user", "GET"); // stratigraphy +export const fetchStratigraphy = async id => { + return await fetchApiV2(`stratigraphy/${id}`, "GET"); +}; + export const copyStratigraphy = async id => { return await fetchApiV2(`stratigraphy/copy?id=${id}`, "POST"); }; @@ -190,6 +194,14 @@ export const addBedrock = async id => { return await fetchApiV2(`stratigraphy/addbedrock?id=${id}`, "POST"); }; +export const updateStratigraphy = async stratigraphy => { + // remove derived objects + delete stratigraphy.createdBy; + delete stratigraphy.updatedBy; + + return await fetchApiV2("stratigraphy", "PUT", stratigraphy); +}; + // Enable using react-query outputs across the application. // eslint-disable-next-line react-hooks/rules-of-hooks diff --git a/src/client/src/commons/form/profile/components/profileInfo/api/index.js b/src/client/src/commons/form/profile/components/profileInfo/api/index.js index ec5a34bae..99148d1cc 100644 --- a/src/client/src/commons/form/profile/components/profileInfo/api/index.js +++ b/src/client/src/commons/form/profile/components/profileInfo/api/index.js @@ -1,4 +1,8 @@ -import { getProfile, patchProfile } from "../../../../../../api-lib/index"; +import { getProfile } from "../../../../../../api-lib/index"; +import { + fetchStratigraphy, + updateStratigraphy, +} from "../../../../../../api/fetchApiV2"; let data = []; export const getData = async id => { @@ -17,19 +21,20 @@ export const getData = async id => { return data; }; -let isSendProfile = false; export const sendProfile = async (id, attribute, value) => { - await patchProfile(id, attribute, value) - .then(response => { - if (response.data.success) { - isSendProfile = true; - } else { - alert(response.data.message); - } - }) - .catch(function (error) { - console.error(error); - }); + let success = false; + await fetchStratigraphy(id).then(async stratigraphy => { + if (stratigraphy) { + stratigraphy[attribute] = value; + await updateStratigraphy(stratigraphy).then(response => { + if (response) { + success = true; + } + }); + } else { + alert("Failed to get stratigraphy data for update."); + } + }); - return isSendProfile; + return success; };