public void TestCustomBatchPropValues() { // Prerequisite entities Plastic pp = PlasticsRepository.CreatePlastic("PP", "Polypropylene"); Material mat = MaterialsRepository.CreateMaterial("mat", "manu", "manu-id", pp); StorageSite site = LocationsRepository.CreateStorageSite("test_site"); StorageArea area = LocationsRepository.CreateStorageArea(site, "test_area"); StorageLocation loc = new StorageLocation() { StorageSiteId = site.Id, StorageAreaId = area.Id, StorageSiteName = site.Name, StorageAreaName = area.Name }; CustomBatchProp prop1 = PropRepository.CreateCustomBatchProp("prop-1"); CustomBatchProp prop2 = PropRepository.CreateCustomBatchProp("prop-2"); // Create batch with custom prop values MaterialBatch batch = Repository.CreateMaterialBatch(mat, DateTime.Today.AddDays(17), loc, 42, 42, new Dictionary <Guid, string>() { { prop1.Id, "Ak Bars" }, { prop2.Id, "Aloha" } }, false); Assert.Equal(2, batch.CustomProps.Count); // Test updating batch.CustomProps[prop1.Id] = "UPDATE TEST"; Repository.UpdateMaterialBatch(batch); batch = Repository.GetMaterialBatch(batch.Id); Assert.Equal(2, batch.CustomProps.Count); Assert.Single(batch.CustomProps.Where(p => p.Value == "UPDATE TEST")); }
/// <summary> /// Gets all available storage site. /// </summary> /// <returns> /// Returns all storage sites. /// </returns> public IEnumerable <StorageSite> GetAllStorageSites() { Dictionary <Guid, StorageSite> siteMap = new Dictionary <Guid, StorageSite>(); string sql = "SELECT * FROM storage_sites s LEFT JOIN storage_areas a ON a.site_id = s.id"; IEnumerable <StorageSite> sites = null; using (IDbConnection connection = GetNewConnection()) { sites = connection.Query <StorageSite, StorageArea, StorageSite>(sql, (site, area) => { StorageSite storageSite = null; if (!siteMap.TryGetValue(site.Id, out storageSite)) { storageSite = site; siteMap.Add(storageSite.Id, storageSite); } if (area != null) { storageSite.Areas.Add(area); } return(storageSite); }, splitOn: "id"); } return(sites.Distinct()); }
/// <summary> /// Searches storage sites using a partial name. /// </summary> /// <param name="partialName">String to search for in site names.</param> /// <returns> /// Returns filtered storage sites. /// </returns> public IEnumerable <StorageSite> SearchStorageSitesByName(string partialName) { string name = $"%{partialName}%"; Dictionary <Guid, StorageSite> siteMap = new Dictionary <Guid, StorageSite>(); string sql = "SELECT * FROM storage_sites s LEFT JOIN storage_areas a ON a.site_id = s.id WHERE s.name ILIKE @Name"; IEnumerable <StorageSite> sites = null; using (IDbConnection connection = GetNewConnection()) { sites = connection.Query <StorageSite, StorageArea, StorageSite>(sql, (site, area) => { StorageSite storageSite = null; if (!siteMap.TryGetValue(site.Id, out storageSite)) { storageSite = site; siteMap.Add(storageSite.Id, storageSite); } if (area != null) { storageSite.Areas.Add(area); } return(storageSite); }, param: new { name }, splitOn: "id"); } return(sites.Distinct()); }
/// <summary> /// Updates an existing storage site. This does not update associated storage areas. /// </summary> /// <param name="storageSite">Storage site to update.</param> /// <returns> /// Returns the updated storage site. /// </returns> public StorageSite UpdateStorageSite(StorageSite storageSite) { using (IDbConnection connection = GetNewConnection()) { connection.Execute("UPDATE storage_sites SET name=@Name WHERE id=@Id", new { storageSite.Id, storageSite.Name }); } return(storageSite); }
public StorageArea CreateStorageArea(StorageSite storageSite, string areaName) { StorageArea area = new StorageArea(areaName); storageSite.Areas.Add(area); StorageAreas.Add(area.Id, area); StorageSites[storageSite.Id] = storageSite; return(area); }
public IActionResult CreateStorageSite([FromBody] StorageSiteCreationRequest storageSiteCreationRequest) { if (storageSiteCreationRequest == null || string.IsNullOrWhiteSpace(storageSiteCreationRequest.Name)) { return(HandleBadRequest("A valid storage site name has to be supplied.")); } StorageSite site = LocationsService.CreateStorageSite(storageSiteCreationRequest.Name); return(Created(GetNewResourceUri(site.Id), site)); }
public StorageSite CreateStorageSite(string name) { StorageSite site = new StorageSite() { Id = Guid.NewGuid(), Name = name, Areas = new List <StorageArea>() }; StorageSites.Add(site.Id, site); return(site); }
/// <summary> /// Creates a new storage site. /// </summary> /// <param name="name">Name of the new storage site.</param> /// <returns> /// Returns the newly created storage site. /// </returns> public StorageSite CreateStorageSite(string name) { Guid id = Guid.NewGuid(); StorageSite site = null; using (IDbConnection connection = GetNewConnection()) { connection.Execute("INSERT INTO storage_sites (id, name) VALUES (@Id, @Name)", new { id, name }); site = connection.QuerySingleOrDefault <StorageSite>("SELECT * FROM storage_sites WHERE id=@Id", new { id }); } return(site); }
/// <summary> /// Gets the latest value for a specific storage site and environmental factor. /// </summary> /// <param name="site">The storage site to get the latest value for.</param> /// <param name="factor">The factor to get the latest value for.</param> /// <returns> /// Returns the latest value, or null. /// </returns> public DataPoint GetLatestValue(StorageSite site, EnvironmentalFactor factor) { string column = GetColumnName(factor); DataPoint value = null; using (IDbConnection connection = GetNewConnection()) { value = connection.QuerySingleOrDefault <DataPoint>($"SELECT timestamp,{column} AS value FROM environment WHERE site=@Id AND timestamp>now()-interval '1day' ORDER BY timestamp DESC LIMIT 1", new { site.Id }); } return(value); }
private void GenerateLocation(string guid, string name, string[] areas) { Guid id = new Guid(guid); StorageSite site = new StorageSite() { Id = id, Name = name, Areas = new List <StorageArea>() }; foreach (string area in areas) { site.Areas.Add(new StorageArea(area)); } StorageSites.Add(id, site); }
/// <summary> /// Gets the min and max values for a specific storage site and environmental factor. /// </summary> /// <param name="site">The storage site to get the history for.</param> /// <param name="factor">The factor to get the history for.</param> /// <param name="startTime">Start time of the period to get value for.</param> /// <param name="endTime">End time of the period to get value for.</param> /// <returns> /// Returns the extrema. /// </returns> public Extrema GetExtrema(StorageSite site, EnvironmentalFactor factor, DateTime startTime, DateTime endTime) { string column = GetColumnName(factor); Extrema extrema = null; using (IDbConnection connection = GetNewConnection()) { extrema = connection.QuerySingleOrDefault <Extrema>($"SELECT min({column}) AS min_value, max({column}) AS max_value FROM environment WHERE site=@Id AND timestamp>@StartTime AND timestamp<@EndTime", new { site.Id, startTime, endTime }); } return(extrema); }
/// <summary> /// Gets the history of a specific storage site and environmental factor. /// </summary> /// <param name="site">The storage site to get the history for.</param> /// <param name="factor">The factor to get the history for.</param> /// <param name="startTime">Start time of the period to get value for.</param> /// <param name="endTime">End time of the period to get value for.</param> /// <returns> /// Returns the matching values. /// </returns> public IEnumerable <DataPoint> GetHistory(StorageSite site, EnvironmentalFactor factor, DateTime startTime, DateTime endTime) { string column = GetColumnName(factor); IEnumerable <DataPoint> history = null; using (IDbConnection connection = GetNewConnection()) { history = connection.Query <DataPoint>($"SELECT timestamp,{column} AS value FROM environment WHERE site=@Id AND timestamp>@StartTime AND timestamp<@EndTime ORDER BY timestamp ASC", new { site.Id, startTime, endTime }); } return(history); }
private void GenerateBatches() { StorageSite pontStrKeller = StorageSites[new Guid("2f02b4f2-fc8c-455f-b05f-869d6ab9408c")]; StorageSite melatenRaum07 = StorageSites[new Guid("825ff2e8-a057-4434-8279-60a9f4ddbbdf")]; StorageLocation loc1 = new StorageLocation(pontStrKeller, pontStrKeller.Areas.First()); StorageLocation loc2 = new StorageLocation(melatenRaum07, melatenRaum07.Areas.First()); string pat = "Patrick Sapel"; string ann = "Anna A. Annamann"; GenerateBatch(1, loc1, 34, pat); GenerateBatch(1, loc1, 35, pat); GenerateBatch(1, loc2, 36, ann); GenerateBatch(2, loc1, 42, pat); GenerateBatch(3, loc2, 1, "Obelix"); GenerateBatch(4, loc2, 203, "Obelix"); GenerateBatch(5, loc1, 22, pat); GenerateBatch(5, loc2, 9000, pat); }
/// <summary> /// Creates a new area for an existing storage site. /// </summary> /// <param name="storageSite">Site to add an area to.</param> /// <param name="areaName">Name of the area to create.</param> /// <returns> /// Returns the newly created area. /// </returns> public StorageArea CreateStorageArea(StorageSite storageSite, string areaName) { Guid id = Guid.NewGuid(); StorageArea area = null; using (IDbConnection connection = GetNewConnection()) { connection.Execute("INSERT INTO storage_areas (id, name, site_id) VALUES (@Id, @Name, @SiteId)", new { Id = id, Name = areaName, SiteId = storageSite.Id }); area = connection.QuerySingleOrDefault <StorageArea>("SELECT * FROM storage_areas WHERE id=@Id", new { id }); } return(area); }
/// <summary> /// Initializes a new instance of the <see cref="EnvironmentalDataReader"/> class. /// </summary> /// <param name="logger">Used to log information.</param> /// <param name="snapshotQueue">Thread-safe queue to write data to.</param> /// <param name="kafkaEndpoint">The Kafka endpoint to read data from.</param> /// <param name="site">The storage site for which to read data.</param> public EnvironmentalDataReader(ILogger <EnvironmentalDataReader> logger, ConcurrentQueue <EnvironmentSnapshot> snapshotQueue, string kafkaEndpoint, StorageSite site) { StorageSiteId = site.Id; SnapshotQueue = snapshotQueue; ConsumerConfig = new ConsumerConfig { GroupId = "openmts-environment-consumers", BootstrapServers = kafkaEndpoint, AutoOffsetReset = AutoOffsetReset.Earliest }; Topic = $"openmts-environment-{StorageSiteId}"; Logger = logger; // Start consuming Worker = StartConsuming(); }
public IActionResult UpdateStorageSiteMasterData(Guid id, [FromBody] StorageSiteMasterDataUpdateRequest storageSiteMasterDataUpdateRequest) { if (id == null || storageSiteMasterDataUpdateRequest == null || string.IsNullOrWhiteSpace(storageSiteMasterDataUpdateRequest.Name)) { return(HandleBadRequest("A valid storage site ID and name have to be supplied.")); } try { StorageSite site = LocationsService.UpdateStorageSiteMasterData(id, storageSiteMasterDataUpdateRequest.Name); return(Ok(site)); } catch (StorageSiteNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (Exception exception) { return(HandleUnexpectedException(exception)); } }
public Extrema GetExtrema(StorageSite site, EnvironmentalFactor factor, DateTime startTime, DateTime endTime) { Extrema extrema = null; switch (factor) { case EnvironmentalFactor.Temperature: if (Temperature.TryGetValue(site.Id, out List <DataPoint> temperatures)) { if (temperatures.Count > 0) { extrema = new Extrema() { MaxValue = temperatures.Where(t => t.Timestamp >= startTime && t.Timestamp <= endTime).Max(t => t.Value), MinValue = temperatures.Where(t => t.Timestamp >= startTime && t.Timestamp <= endTime).Min(t => t.Value) }; } } break; case EnvironmentalFactor.Humidity: if (Humidity.TryGetValue(site.Id, out List <DataPoint> humidities)) { if (humidities.Count > 0) { extrema = new Extrema() { MaxValue = humidities.Where(t => t.Timestamp >= startTime && t.Timestamp <= endTime).Max(t => t.Value), MinValue = humidities.Where(t => t.Timestamp >= startTime && t.Timestamp <= endTime).Min(t => t.Value) }; } } break; default: throw new NotImplementedException(); } return(extrema); }
public DataPoint GetLatestValue(StorageSite site, EnvironmentalFactor factor) { DataPoint dataPoint = null; switch (factor) { case EnvironmentalFactor.Temperature: if (Temperature.TryGetValue(site.Id, out List <DataPoint> temperatures)) { dataPoint = temperatures.LastOrDefault(); } break; case EnvironmentalFactor.Humidity: if (Humidity.TryGetValue(site.Id, out List <DataPoint> humidities)) { dataPoint = humidities.LastOrDefault(); } break; default: throw new NotImplementedException(); } return(dataPoint); }
public IEnumerable <DataPoint> GetHistory(StorageSite site, EnvironmentalFactor factor, DateTime startTime, DateTime endTime) { IEnumerable <DataPoint> history = new List <DataPoint>(); switch (factor) { case EnvironmentalFactor.Temperature: if (Temperature.TryGetValue(site.Id, out List <DataPoint> temperatures)) { history = temperatures.Where(t => t.Timestamp >= startTime && t.Timestamp <= endTime); } break; case EnvironmentalFactor.Humidity: if (Humidity.TryGetValue(site.Id, out List <DataPoint> humidities)) { history = humidities.Where(t => t.Timestamp >= startTime && t.Timestamp <= endTime); } break; default: throw new NotImplementedException(); } return(history); }
public IActionResult UpdateMaterialBatch(Guid batchId, [FromBody] BatchUpdateRequest batchUpdateRequest) { if (batchUpdateRequest == null || batchUpdateRequest.ExpirationDate == null || batchUpdateRequest.StorageSiteId == null || batchUpdateRequest.StorageAreaId == null || batchUpdateRequest.CustomProps == null) { return(HandleBadRequest("Batch data missing for batch update.")); } // Validate batch number if (batchUpdateRequest.BatchNumber <= 0) { return(HandleBadRequest("The batch number must be greater than 0!")); } try { // Get material Material material = MaterialsService.GetMaterial(batchUpdateRequest.MaterialId); // Get storage location StorageSite site = LocationsService.GetStorageSite(batchUpdateRequest.StorageSiteId); StorageArea area = site.Areas.FirstOrDefault(a => a.Id == batchUpdateRequest.StorageAreaId); if (area == null) { throw new StorageAreaNotFoundException(site.Id, batchUpdateRequest.StorageAreaId); } StorageLocation storageLocation = new StorageLocation(site, area); // Proceed with creation and return new batch! MaterialBatch batch = InventoryService.UpdateMaterialBatch(batchId, material, batchUpdateRequest.ExpirationDate, storageLocation, batchUpdateRequest.BatchNumber, batchUpdateRequest.CustomProps); return(Ok(batch)); } catch (MaterialNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (StorageSiteNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (StorageAreaNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (ArgumentException exception) { return(HandleBadRequest(exception.Message)); } catch (Exception exception) { return(HandleUnexpectedException(exception)); } }
public StorageSite UpdateStorageSite(StorageSite storageSite) { StorageSites[storageSite.Id] = storageSite; return(storageSite); }
public void TestTransactionRepository() { // Create prerequisite entities Plastic plastic = PlasticsRepository.CreatePlastic("PP", "Polypropylene"); Material material = MaterialsRepository.CreateMaterial("m", "m", "m", plastic); StorageSite site = LocationsRepository.CreateStorageSite("site"); StorageArea area = LocationsRepository.CreateStorageArea(site, "area"); StorageLocation location = new StorageLocation() { StorageSiteId = site.Id, StorageAreaId = area.Id, StorageSiteName = site.Name, StorageAreaName = area.Name }; MaterialBatch batch = BatchRepository.CreateMaterialBatch(material, DateTime.Today.AddDays(3), location, 42, 42, new Dictionary <Guid, string>(), false); (string password, byte[] salt) = new PasswordHashingService(new LoggerFactory()).HashAndSaltPassword("test"); User user = UserRepository.CreateUser("alex", "Alex", password, salt, Role.Administrator); // Create transactions Repository.LogTransaction(new Transaction() { Id = Guid.NewGuid(), MaterialBatchId = batch.Id, Quantity = -3, Timestamp = DateTime.Today.AddDays(-3), UserId = user.Id }); Repository.LogTransaction(new Transaction() { Id = Guid.NewGuid(), MaterialBatchId = batch.Id, Quantity = -2, Timestamp = DateTime.Today.AddDays(-2), UserId = user.Id }); Guid lastId = Guid.NewGuid(); Repository.LogTransaction(new Transaction() { Id = lastId, MaterialBatchId = batch.Id, Quantity = -1, Timestamp = DateTime.Today.AddDays(-1), UserId = user.Id }); // Check with getAll IEnumerable <Transaction> transactions = Repository.GetTransactionsForBatch(batch.Id); Assert.Equal(3, transactions.Count()); Assert.Single(transactions, t => t.Quantity == -3); Assert.Single(transactions, t => t.Quantity == -2); Assert.Single(transactions, t => t.Quantity == -1); // Check get last Transaction transaction = Repository.GetLastTransactionForBatch(batch.Id); Assert.Equal(batch.Id, transaction.MaterialBatchId); Assert.Equal(lastId, transaction.Id); Assert.Equal(-1, transaction.Quantity); // Test transaction update transaction.Quantity = 200; Repository.UpdateTransaction(transaction); transaction = Repository.GetLastTransactionForBatch(batch.Id); Assert.Equal(lastId, transaction.Id); Assert.Equal(200, transaction.Quantity); }
public void TestMaterialBatchRepository() { Assert.Empty(Repository.GetAllMaterialBatches()); // Create prerequisite entities Plastic pp = PlasticsRepository.CreatePlastic("PP", "Polypropylene"); Plastic ep = PlasticsRepository.CreatePlastic("EP", "Epoxy"); Material pp1 = MaterialsRepository.CreateMaterial("pp-1", "Umbrella Corp.", "pp-1", pp); Material ep1 = MaterialsRepository.CreateMaterial("ep-1", "Umbrella Corp.", "ep-1", ep); StorageSite site = LocationsRepository.CreateStorageSite("Test Site"); StorageArea area = LocationsRepository.CreateStorageArea(site, "Test Area"); StorageLocation loc = new StorageLocation() { StorageSiteId = site.Id, StorageAreaId = area.Id, StorageSiteName = site.Name, StorageAreaName = area.Name }; // Create batch and check return DateTime expDate = DateTime.Today.AddDays(5); MaterialBatch batch = Repository.CreateMaterialBatch(pp1, expDate, loc, 1, 125.0, new Dictionary <Guid, string>(), false); Assert.Equal(pp1.Id, batch.Material.Id); Assert.Equal(expDate, batch.ExpirationDate); Assert.Equal(area.Id, batch.StorageLocation.StorageAreaId); Assert.Equal(site.Id, batch.StorageLocation.StorageSiteId); Assert.Equal(1, batch.BatchNumber); Assert.Equal(125.0, batch.Quantity); Assert.Empty(batch.CustomProps); Assert.False(batch.IsLocked); Assert.False(batch.IsArchived); // Check get all batches IEnumerable <MaterialBatch> batches = Repository.GetAllMaterialBatches(); Assert.Single(batches); batch = batches.Single(); Assert.Equal(pp1.Id, batch.Material.Id); Assert.Equal(expDate, batch.ExpirationDate); Assert.Equal(area.Id, batch.StorageLocation.StorageAreaId); Assert.Equal(site.Id, batch.StorageLocation.StorageSiteId); Assert.Equal(1, batch.BatchNumber); Assert.Equal(125.0, batch.Quantity); Assert.Empty(batch.CustomProps); Assert.False(batch.IsLocked); Assert.False(batch.IsArchived); // Check get single batch batch = Repository.GetMaterialBatch(batch.Id); Assert.Equal(pp1.Id, batch.Material.Id); Assert.Equal(expDate, batch.ExpirationDate); Assert.Equal(area.Id, batch.StorageLocation.StorageAreaId); Assert.Equal(site.Id, batch.StorageLocation.StorageSiteId); Assert.Equal(1, batch.BatchNumber); Assert.Equal(125.0, batch.Quantity); Assert.Empty(batch.CustomProps); Assert.False(batch.IsLocked); Assert.False(batch.IsArchived); // Check filters batches = Repository.GetMaterialBatches(pp1.Id); Assert.Single(batches); batch = batches.Single(); Assert.Equal(pp1.Id, batch.Material.Id); batches = Repository.GetMaterialBatches(siteId: site.Id); Assert.Single(batches); batch = batches.Single(); Assert.Equal(pp1.Id, batch.Material.Id); batches = Repository.GetMaterialBatches(pp1.Id, site.Id); Assert.Single(batches); batch = batches.Single(); Assert.Equal(pp1.Id, batch.Material.Id); batches = Repository.GetMaterialBatches(99999, site.Id); Assert.Empty(batches); batches = Repository.GetMaterialBatches(pp1.Id, area.Id); Assert.Empty(batches); // Create another batch and test filters again Repository.CreateMaterialBatch(ep1, expDate, loc, 33, 25.5, new Dictionary <Guid, string>(), false); batches = Repository.GetMaterialBatches(ep1.Id, site.Id); Assert.Single(batches); batch = batches.Single(); Assert.Equal(ep1.Id, batch.Material.Id); batches = Repository.GetMaterialBatches(siteId: site.Id); Assert.Equal(2, batches.Count()); Assert.Single(batches, b => b.Material.Id == pp1.Id); Assert.Single(batches, b => b.Material.Id == ep1.Id); // Test updating a batch batch = batches.Single(b => b.Material.Id == ep1.Id); Assert.Equal(33, batch.BatchNumber); Assert.Equal(25.5, batch.Quantity); Assert.False(batch.IsLocked); batch.BatchNumber = 333; batch.Quantity = 203.1; batch.IsLocked = true; Repository.UpdateMaterialBatch(batch); batch = Repository.GetMaterialBatch(batch.Id); Assert.Equal(333, batch.BatchNumber); Assert.Equal(203.1, batch.Quantity); Assert.True(batch.IsLocked); // Test archiving Guid archivedId = batch.Id; batch.IsArchived = true; Repository.UpdateMaterialBatch(batch); batches = Repository.GetAllMaterialBatches(); Assert.Single(batches); batch = batches.Single(); Assert.Equal(pp1.Id, batch.Material.Id); // Still directly gettable by ID batch = Repository.GetMaterialBatch(archivedId); Assert.Equal(ep1.Id, batch.Material.Id); }
public void TestLocationsRepository() { Assert.Empty(Repository.GetAllStorageSites()); // Create sites StorageSite site1 = Repository.CreateStorageSite("Test Site 1"); StorageSite site2 = Repository.CreateStorageSite("Test Site 2"); Guid site1Id = site1.Id; Guid site2Id = site2.Id; // Get and check sites IEnumerable <StorageSite> sites = Repository.GetAllStorageSites(); Assert.Equal(2, sites.Count()); Assert.Contains(sites, s => s.Id == site1.Id && s.Name == site1.Name); Assert.Contains(sites, s => s.Id == site2.Id && s.Name == site2.Name); // Search by name sites = Repository.SearchStorageSitesByName("1"); Assert.Single(sites); Assert.Equal(site1Id, sites.First().Id); // Create areas Repository.CreateStorageArea(site1, "Area 1"); Repository.CreateStorageArea(site1, "Area 2"); Repository.CreateStorageArea(site2, "Area 3"); // Get and check sites sites = Repository.GetAllStorageSites(); Assert.Equal(2, sites.Count()); site1 = sites.Single(s => s.Id == site1Id); site2 = sites.Single(s => s.Id == site2Id); Assert.Equal(2, site1.Areas.Count); Assert.Single(site2.Areas); Assert.Contains(site1.Areas, a => a.Name == "Area 1"); Assert.Contains(site1.Areas, a => a.Name == "Area 2"); Assert.Contains(site2.Areas, a => a.Name == "Area 3"); // Get site by ID site2 = Repository.GetStorageSite(site2Id); Assert.Equal(site2Id, site2.Id); Assert.Equal("Test Site 2", site2.Name); // Update site name site1.Name = "NEW NAME"; Repository.UpdateStorageSite(site1); site1 = Repository.GetStorageSite(site1.Id); Assert.Equal("NEW NAME", site1.Name); // Update area name StorageArea area = site1.Areas.First(); area.Name = "NEW AREA NAME"; Repository.UpdateStorageArea(area); site1 = Repository.GetStorageSite(site1.Id); Assert.Contains(site1.Areas, a => a.Id == area.Id && area.Name == area.Name); // Delete site Repository.DeleteStorageSite(site1Id); Assert.Single(Repository.GetAllStorageSites()); }
public IActionResult CreateMaterialBatch([FromBody] BatchCreationRequest batchCreationRequest) { if (batchCreationRequest == null || batchCreationRequest.ExpirationDate == null || batchCreationRequest.StorageSiteId == null || batchCreationRequest.StorageAreaId == null || batchCreationRequest.CustomProps == null) { return(HandleBadRequest("Batch data missing for batch creation.")); } // Validate expiration date if (batchCreationRequest.ExpirationDate.Date <= DateTime.UtcNow.Date) { return(HandleBadRequest("A batch expiration date must be in the future.")); } // Validate batch number and quantity if (batchCreationRequest.BatchNumber <= 0 || batchCreationRequest.Quantity <= 0) { return(HandleBadRequest("The batch number and quantity need to be greater than 0!")); } // Batch locking on creation validation bool lockBatch = batchCreationRequest.IsLocked; if (lockBatch) { Role role = GetRole(); if (role != Role.Administrator && role != Role.ScientificAssistant) { return(Forbid()); } } try { string userId = GetSubject(); // Get material Material material = MaterialsService.GetMaterial(batchCreationRequest.MaterialId); // Get storage location StorageSite site = LocationsService.GetStorageSite(batchCreationRequest.StorageSiteId); StorageArea area = site.Areas.FirstOrDefault(a => a.Id == batchCreationRequest.StorageAreaId); if (area == null) { throw new StorageAreaNotFoundException(site.Id, batchCreationRequest.StorageAreaId); } StorageLocation storageLocation = new StorageLocation(site, area); // Proceed with creation and return new batch! MaterialBatch batch = InventoryService.CreateMaterialBatch(material, batchCreationRequest.ExpirationDate, storageLocation, batchCreationRequest.BatchNumber, batchCreationRequest.Quantity, batchCreationRequest.CustomProps, lockBatch, userId); return(Created(GetNewResourceUri(batch), batch)); } catch (MaterialNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (StorageSiteNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (StorageAreaNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (Exception exception) { return(HandleUnexpectedException(exception)); } }