diff --git a/api/Hmcr.Api/Controllers/ActivityRuleController.cs b/api/Hmcr.Api/Controllers/ActivityRuleController.cs new file mode 100644 index 00000000..fc0349c4 --- /dev/null +++ b/api/Hmcr.Api/Controllers/ActivityRuleController.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Hmcr.Api.Controllers.Base; +using Hmcr.Domain.Services; +using Hmcr.Model; +using Hmcr.Model.Dtos.ActivityRule; +using Hmcr.Model.Dtos.User; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace Hmcr.Api.Controllers +{ + [ApiVersion("1.0")] + [Route("api/activityrule")] + [ApiController] + public class ActivityRuleController : HmcrControllerBase + { + private IActivityRuleService _activityRuleSvc; + public ActivityRuleController(IActivityRuleService activityRuleSvc) + { + _activityRuleSvc = activityRuleSvc; + } + + [HttpGet("roadlength")] + public async Task>> GetRoadLengthRulesAsync() + { + return Ok(await _activityRuleSvc.GetRoadLengthRulesAsync()); + } + + [HttpGet("surfacetype")] + public async Task>> GetSurfaceTypeRulesAsync() + { + return Ok(await _activityRuleSvc.GetSurfaceTypeRulesAsync()); + } + + [HttpGet("roadclass")] + public async Task>> GetRoadClassRulesAsync() + { + return Ok(await _activityRuleSvc.GetRoadClassRulesAsync()); + } + } +} diff --git a/api/Hmcr.Api/Startup.cs b/api/Hmcr.Api/Startup.cs index 71e748dd..3047267a 100644 --- a/api/Hmcr.Api/Startup.cs +++ b/api/Hmcr.Api/Startup.cs @@ -15,7 +15,6 @@ namespace Hmcr.Api { public class Startup { - public IConfiguration Configuration { get; } private IWebHostEnvironment _env; @@ -45,7 +44,8 @@ public void ConfigureServices(IServiceCollection services) } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISubmissionObjectJobService jobService, - IServiceScopeFactory serviceScopeFactory, IServiceAreaService svcAreaService, ICodeLookupRepository codeLookupRepo, IFieldValidatorService validator) + IServiceScopeFactory serviceScopeFactory, IServiceAreaService svcAreaService, ICodeLookupRepository codeLookupRepo, + IActivityRuleRepository activityRuleRepo, IFieldValidatorService validator) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); @@ -60,6 +60,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISubmiss app.UseHmcrSwagger(env, Configuration.GetSection("Constants:SwaggerApiUrl").Value); validator.CodeLookup = codeLookupRepo.LoadCodeLookupCache(); + validator.ActivityCodeRuleLookup = activityRuleRepo.LoadActivityCodeRuleCache(); } } } diff --git a/api/Hmcr.Chris/ChrisServiceCollectionExtensions.cs b/api/Hmcr.Chris/ChrisServiceCollectionExtensions.cs index 84363d34..7b18c49d 100644 --- a/api/Hmcr.Chris/ChrisServiceCollectionExtensions.cs +++ b/api/Hmcr.Chris/ChrisServiceCollectionExtensions.cs @@ -41,6 +41,18 @@ public static void AddChrisHttpClient(this IServiceCollection services, IConfigu client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicAuth); }); + services.AddHttpClient(client => + { + client.BaseAddress = new Uri(config.GetValue("CHRIS:OASUrl")); + client.Timeout = new TimeSpan(0, 0, 45); + client.DefaultRequestHeaders.Clear(); + + var userId = config.GetValue("ServiceAccount:User"); + var password = config.GetValue("ServiceAccount:Password"); + var basicAuth = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{userId}:{password}")); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicAuth); + }); + services.AddScoped(); } } diff --git a/api/Hmcr.Chris/Hmcr.Chris.csproj b/api/Hmcr.Chris/Hmcr.Chris.csproj index cb61ee16..f257989a 100644 --- a/api/Hmcr.Chris/Hmcr.Chris.csproj +++ b/api/Hmcr.Chris/Hmcr.Chris.csproj @@ -7,6 +7,7 @@ + @@ -16,6 +17,9 @@ Always + + Always + diff --git a/api/Hmcr.Chris/InventoryApi.cs b/api/Hmcr.Chris/InventoryApi.cs new file mode 100644 index 00000000..3f971dfb --- /dev/null +++ b/api/Hmcr.Chris/InventoryApi.cs @@ -0,0 +1,85 @@ +using Hmcr.Chris.Models; +using Microsoft.Extensions.Configuration; +using System.Collections.Generic; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; + +namespace Hmcr.Chris +{ + public interface IInventoryApi + { + Task> GetSurfaceTypeAssociatedWithLine(string lineStringCoordinates); + Task GetSurfaceTypeAssociatedWithPoint(string lineStringCoordinates); + + //TODO: implement MC calls to CHRIS + + } + + public class InventoryApi : IInventoryApi + { + private HttpClient _client; + private InventoryQueries _queries; + private IApi _api; + private string _path; + + /// + /// Chris Query typeName values, used to call the Get Inventory + /// Assoc with Work Activity Query. + /// + public static class InventoryQueryTypeName + { + public const string SURF_ASSOC_WITH_LINE = "SURF_ASSOCIATED_WITH_LINE"; + public const string SURF_ASSOC_WITH_POINT = "SURF_ASSOCIATED_WITH_POINT"; + public const string MC_ASSOC_WITH_LINE = "MC_ASSOCIATED_WITH_LINE"; + public const string MC_ASSOC_WITH_POINT = "MC_ASSOCIATED_WITH_POINT"; + } + + public InventoryApi(HttpClient client, IApi api, IConfiguration config) + { + _client = client; + _queries = new InventoryQueries(); + _api = api; + _path = config.GetValue("CHRIS:OASPath"); + } + + public async Task GetSurfaceTypeAssociatedWithPoint(string lineStringCoordinates) + { + var body = string.Format(_queries.SurfaceTypeAssocWithPointQuery, lineStringCoordinates, InventoryQueryTypeName.SURF_ASSOC_WITH_POINT); + + var contents = await (await _api.PostWithRetry(_client, _path, body)).Content.ReadAsStringAsync(); + + var results = JsonSerializer.Deserialize>(contents); + + SurfaceType surfaceType = new SurfaceType(); + if (results.features.Length > 0) + { + surfaceType.Type = results.features[0].properties.SURFACE_TYPE; + } + + return surfaceType; + } + + public async Task> GetSurfaceTypeAssociatedWithLine(string lineStringCoordinates) + { + var body = string.Format(_queries.SurfaceTypeAssocWithLineQuery, lineStringCoordinates, InventoryQueryTypeName.SURF_ASSOC_WITH_LINE); + + var contents = await (await _api.PostWithRetry(_client, _path, body)).Content.ReadAsStringAsync(); + + var results = JsonSerializer.Deserialize>(contents); + + var surfaceTypes = new List(); + + foreach (var feature in results.features) + { + SurfaceType surfaceType = new SurfaceType(); + surfaceType.Length = feature.properties.CLIPPED_LENGTH_KM; + surfaceType.Type = feature.properties.SURFACE_TYPE; + + surfaceTypes.Add(surfaceType); + } + + return surfaceTypes; + } + } +} diff --git a/api/Hmcr.Chris/InventoryQueries.cs b/api/Hmcr.Chris/InventoryQueries.cs new file mode 100644 index 00000000..d4015b52 --- /dev/null +++ b/api/Hmcr.Chris/InventoryQueries.cs @@ -0,0 +1,30 @@ +using System.IO; +using System.Reflection; + +namespace Hmcr.Chris +{ + public class InventoryQueries + { + private string _surfaceTypeAssocWithLineQuery; + private string _surfaceTypeAssocWithPointQuery; + + public string SurfaceTypeAssocWithLineQuery + { + get + { + var folder = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "XmlTemplates"); + return _surfaceTypeAssocWithLineQuery ?? (_surfaceTypeAssocWithLineQuery = File.ReadAllText(Path.Combine(folder, "GetInventoryAssocWithWorkActivity.xml"))); + } + } + + public string SurfaceTypeAssocWithPointQuery + { + get + { + var folder = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "XmlTemplates"); + return _surfaceTypeAssocWithPointQuery ?? (_surfaceTypeAssocWithPointQuery = File.ReadAllText(Path.Combine(folder, "GetInventoryAssocWithWorkActivity.xml"))); + } + } + + } +} diff --git a/api/Hmcr.Chris/Models/Property.cs b/api/Hmcr.Chris/Models/Property.cs index 2c1a8556..e5dc0b39 100644 --- a/api/Hmcr.Chris/Models/Property.cs +++ b/api/Hmcr.Chris/Models/Property.cs @@ -7,5 +7,7 @@ public class Property public string NE_DESCR { get; set; } public float MEASURE { get; set; } public double POINT_VARIANCE { get; set; } + public string SURFACE_TYPE { get; set; } + public double CLIPPED_LENGTH_KM { get; set; } } } diff --git a/api/Hmcr.Chris/Models/SurfaceType.cs b/api/Hmcr.Chris/Models/SurfaceType.cs new file mode 100644 index 00000000..3d4f8ba9 --- /dev/null +++ b/api/Hmcr.Chris/Models/SurfaceType.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Hmcr.Chris.Models +{ + public class SurfaceType + { + + public Geometry geometry { get; set; } + /// + /// Length in Meters + /// + public double Length { get; set; } + + public string Type { get; set; } + + } + public class SurfaceType + { + + public Geometry geometry { get; set; } + /// + /// Length in Meters + /// + public double Length { get; set; } + + public string Type { get; set; } + + } +} diff --git a/api/Hmcr.Chris/XmlTemplates/GetInventoryAssocWithWorkActivity.xml b/api/Hmcr.Chris/XmlTemplates/GetInventoryAssocWithWorkActivity.xml new file mode 100644 index 00000000..72be03d3 --- /dev/null +++ b/api/Hmcr.Chris/XmlTemplates/GetInventoryAssocWithWorkActivity.xml @@ -0,0 +1,14 @@ + + + \ No newline at end of file diff --git a/api/Hmcr.Data/Database/Entities/AppDbContext.cs b/api/Hmcr.Data/Database/Entities/AppDbContext.cs index db60b222..1fa4d3bc 100644 --- a/api/Hmcr.Data/Database/Entities/AppDbContext.cs +++ b/api/Hmcr.Data/Database/Entities/AppDbContext.cs @@ -17,6 +17,7 @@ public AppDbContext(DbContextOptions options) public virtual DbSet HmrActivityCodes { get; set; } public virtual DbSet HmrActivityCodeHists { get; set; } + public virtual DbSet HmrActivityCodeRules { get; set; } public virtual DbSet HmrCodeLookups { get; set; } public virtual DbSet HmrCodeLookupHists { get; set; } public virtual DbSet HmrContractTerms { get; set; } @@ -39,6 +40,8 @@ public AppDbContext(DbContextOptions options) public virtual DbSet HmrRolePermissions { get; set; } public virtual DbSet HmrRolePermissionHists { get; set; } public virtual DbSet HmrServiceAreas { get; set; } + public virtual DbSet HmrServiceAreaActivities { get; set; } + public virtual DbSet HmrServiceAreaActivityHists { get; set; } public virtual DbSet HmrServiceAreaHists { get; set; } public virtual DbSet HmrServiceAreaUsers { get; set; } public virtual DbSet HmrServiceAreaUserHists { get; set; } @@ -212,12 +215,34 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .IsUnicode(false) .HasComment(" Classification of maintenance activities which specifies detail of submission or reporting requirements (ie: Routine, Quantified, Additional). Routine - reoccuring maintenace activities that require less detailed reporting Quantified - maintenance activities that require more detailed reporting Additional - activities that exceed agreement threasholds"); + entity.Property(e => e.MaxValue) + .HasColumnName("MAX_VALUE") + .HasColumnType("numeric(11, 2)"); + + entity.Property(e => e.MinValue) + .HasColumnName("MIN_VALUE") + .HasColumnType("numeric(11, 2)"); + + entity.Property(e => e.ReportingFrequency).HasColumnName("REPORTING_FREQUENCY"); + + entity.Property(e => e.RoadClassRule) + .HasColumnName("ROAD_CLASS_RULE") + .HasColumnType("numeric(9, 0)"); + + entity.Property(e => e.RoadLengthRule) + .HasColumnName("ROAD_LENGTH_RULE") + .HasColumnType("numeric(9, 0)"); + entity.Property(e => e.SpThresholdLevel) .HasColumnName("SP_THRESHOLD_LEVEL") .HasMaxLength(30) .IsUnicode(false) .HasComment("Determines the tolerated spatial variance allowed when comparing submitted activity coordinates vs the related Highway Unique road segment. Each level is defined within the CODE_LOOKUP table under the THRSHLD_SP_VAR code"); + entity.Property(e => e.SurfaceTypeRule) + .HasColumnName("SURFACE_TYPE_RULE") + .HasColumnType("numeric(9, 0)"); + entity.Property(e => e.UnitOfMeasure) .IsRequired() .HasColumnName("UNIT_OF_MEASURE") @@ -230,6 +255,24 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasForeignKey(d => d.LocationCodeId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("HMR_ACT_CODE_LOC_CODE_FK"); + + entity.HasOne(d => d.RoadClassRuleNavigation) + .WithMany(p => p.HmrActivityCodeRoadClassRuleNavigations) + .HasForeignKey(d => d.RoadClassRule) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__HMR_ACTIV__ROAD___1C3D2329"); + + entity.HasOne(d => d.RoadLengthRuleNavigation) + .WithMany(p => p.HmrActivityCodeRoadLengthRuleNavigations) + .HasForeignKey(d => d.RoadLengthRule) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__HMR_ACTIV__ROAD___1D314762"); + + entity.HasOne(d => d.SurfaceTypeRuleNavigation) + .WithMany(p => p.HmrActivityCodeSurfaceTypeRuleNavigations) + .HasForeignKey(d => d.SurfaceTypeRule) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__HMR_ACTIV__SURFA__1E256B9B"); }); modelBuilder.Entity(entity => @@ -356,11 +399,33 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMaxLength(12) .IsUnicode(false); + entity.Property(e => e.MaxValue) + .HasColumnName("MAX_VALUE") + .HasColumnType("numeric(11, 2)"); + + entity.Property(e => e.MinValue) + .HasColumnName("MIN_VALUE") + .HasColumnType("numeric(11, 2)"); + + entity.Property(e => e.ReportingFrequency).HasColumnName("REPORTING_FREQUENCY"); + + entity.Property(e => e.RoadClassRule) + .HasColumnName("ROAD_CLASS_RULE") + .HasColumnType("numeric(9, 0)"); + + entity.Property(e => e.RoadLengthRule) + .HasColumnName("ROAD_LENGTH_RULE") + .HasColumnType("numeric(9, 0)"); + entity.Property(e => e.SpThresholdLevel) .HasColumnName("SP_THRESHOLD_LEVEL") .HasMaxLength(30) .IsUnicode(false); + entity.Property(e => e.SurfaceTypeRule) + .HasColumnName("SURFACE_TYPE_RULE") + .HasColumnType("numeric(9, 0)"); + entity.Property(e => e.UnitOfMeasure) .IsRequired() .HasColumnName("UNIT_OF_MEASURE") @@ -368,6 +433,73 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .IsUnicode(false); }); + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.ActivityCodeRuleId) + .HasName("PK__HMR_ACTI__E4140F7D40BB464E"); + + entity.ToTable("HMR_ACTIVITY_CODE_RULE"); + + entity.Property(e => e.ActivityCodeRuleId) + .HasColumnName("ACTIVITY_CODE_RULE_ID") + .HasColumnType("numeric(9, 0)") + .HasDefaultValueSql("(NEXT VALUE FOR [HMR_ACTIVITY_CODE_RULE_ID_SEQ])"); + + entity.Property(e => e.ActivityRuleExecName) + .IsRequired() + .HasColumnName("ACTIVITY_RULE_EXEC_NAME") + .HasMaxLength(150) + .IsUnicode(false); + + entity.Property(e => e.ActivityRuleName) + .IsRequired() + .HasColumnName("ACTIVITY_RULE_NAME") + .HasMaxLength(150); + + entity.Property(e => e.ActivityRuleSet) + .IsRequired() + .HasColumnName("ACTIVITY_RULE_SET") + .HasMaxLength(20) + .IsUnicode(false); + + entity.Property(e => e.ConcurrencyControlNumber) + .HasColumnName("CONCURRENCY_CONTROL_NUMBER") + .HasDefaultValueSql("((1))"); + + entity.Property(e => e.DbAuditCreateTimestamp) + .HasColumnName("DB_AUDIT_CREATE_TIMESTAMP") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + + entity.Property(e => e.DbAuditCreateUserid) + .IsRequired() + .HasColumnName("DB_AUDIT_CREATE_USERID") + .HasMaxLength(30) + .IsUnicode(false) + .HasDefaultValueSql("(user_name())"); + + entity.Property(e => e.DbAuditLastUpdateTimestamp) + .HasColumnName("DB_AUDIT_LAST_UPDATE_TIMESTAMP") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + + entity.Property(e => e.DbAuditLastUpdateUserid) + .IsRequired() + .HasColumnName("DB_AUDIT_LAST_UPDATE_USERID") + .HasMaxLength(30) + .IsUnicode(false) + .HasDefaultValueSql("(user_name())"); + + entity.Property(e => e.DisplayOrder) + .HasColumnName("DISPLAY_ORDER") + .HasColumnType("numeric(3, 0)"); + + entity.Property(e => e.EndDate) + .HasColumnName("END_DATE") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + }); + modelBuilder.Entity(entity => { entity.HasKey(e => e.CodeLookupId) @@ -462,6 +594,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasColumnName("END_DATE") .HasColumnType("datetime") .HasComment("The latest date submissions will be accepted."); + + entity.Property(e => e.IsIntegerOnly).HasColumnName("IS_INTEGER_ONLY"); }); modelBuilder.Entity(entity => @@ -545,13 +679,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) entity.Property(e => e.EndDateHist) .HasColumnName("END_DATE_HIST") .HasColumnType("datetime"); + + entity.Property(e => e.IsIntegerOnly).HasColumnName("IS_INTEGER_ONLY"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e.ContractTermId) - .HasName("HMR_CNRT_TRM_PK") - .IsClustered(false); + .HasName("HMR_CNRT_TRM_PK"); entity.ToTable("HMR_CONTRACT_TERM"); @@ -2319,6 +2454,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasColumnName("END_OFFSET") .HasColumnType("numeric(7, 3)"); + entity.Property(e => e.EndVariance) + .HasColumnName("END_VARIANCE") + .HasColumnType("numeric(25, 20)"); + entity.Property(e => e.EstimatedRockfallDate) .HasColumnName("ESTIMATED_ROCKFALL_DATE") .HasColumnType("date"); @@ -2358,6 +2497,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMaxLength(255) .IsUnicode(false); + entity.Property(e => e.IsOverSpThreshold) + .IsRequired() + .HasColumnName("IS_OVER_SP_THRESHOLD") + .HasMaxLength(1) + .IsUnicode(false); + entity.Property(e => e.Landmark) .HasColumnName("LANDMARK") .HasMaxLength(8) @@ -2440,6 +2585,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasColumnName("START_OFFSET") .HasColumnType("numeric(7, 3)"); + entity.Property(e => e.StartVariance) + .HasColumnName("START_VARIANCE") + .HasColumnType("numeric(25, 20)"); + entity.Property(e => e.SubmissionObjectId) .HasColumnName("SUBMISSION_OBJECT_ID") .HasColumnType("numeric(9, 0)"); @@ -2458,6 +2607,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasColumnName("VEHICLE_DAMAGE") .HasMaxLength(1) .IsUnicode(false); + + entity.Property(e => e.WarningSpThreshold) + .HasColumnName("WARNING_SP_THRESHOLD") + .HasColumnType("numeric(12, 6)"); }); modelBuilder.Entity(entity => @@ -2994,6 +3147,218 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasConstraintName("HMR_SRV_AREA_DISTRICT_FK"); }); + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.ServiceAreaActivityId) + .HasName("PK__HMR_SERV__56CBEAEDB516F420"); + + entity.ToTable("HMR_SERVICE_AREA_ACTIVITY"); + + entity.HasIndex(e => e.ActivityCodeId) + .HasName("IDX_HMR_SVC_AR_ACT_ACT_CD"); + + entity.HasIndex(e => e.ServiceAreaNumber) + .HasName("IDX_HMR_SVC_AR_ACT_SVC_AREA"); + + entity.HasIndex(e => new { e.ServiceAreaNumber, e.ActivityCodeId }) + .HasName("UQ__HMR_SERV__307B5DE2F252A57E") + .IsUnique(); + + entity.Property(e => e.ServiceAreaActivityId) + .HasColumnName("SERVICE_AREA_ACTIVITY_ID") + .HasColumnType("numeric(9, 0)") + .HasDefaultValueSql("(NEXT VALUE FOR [HMR_SERVICE_AREA_ACTIVITY_ID_SEQ])"); + + entity.Property(e => e.ActivityCodeId) + .HasColumnName("ACTIVITY_CODE_ID") + .HasColumnType("numeric(9, 0)"); + + entity.Property(e => e.AppCreateTimestamp) + .HasColumnName("APP_CREATE_TIMESTAMP") + .HasColumnType("datetime"); + + entity.Property(e => e.AppCreateUserDirectory) + .IsRequired() + .HasColumnName("APP_CREATE_USER_DIRECTORY") + .HasMaxLength(12) + .IsUnicode(false); + + entity.Property(e => e.AppCreateUserGuid).HasColumnName("APP_CREATE_USER_GUID"); + + entity.Property(e => e.AppCreateUserid) + .IsRequired() + .HasColumnName("APP_CREATE_USERID") + .HasMaxLength(30) + .IsUnicode(false); + + entity.Property(e => e.AppLastUpdateTimestamp) + .HasColumnName("APP_LAST_UPDATE_TIMESTAMP") + .HasColumnType("datetime"); + + entity.Property(e => e.AppLastUpdateUserDirectory) + .IsRequired() + .HasColumnName("APP_LAST_UPDATE_USER_DIRECTORY") + .HasMaxLength(12) + .IsUnicode(false); + + entity.Property(e => e.AppLastUpdateUserGuid).HasColumnName("APP_LAST_UPDATE_USER_GUID"); + + entity.Property(e => e.AppLastUpdateUserid) + .IsRequired() + .HasColumnName("APP_LAST_UPDATE_USERID") + .HasMaxLength(30) + .IsUnicode(false); + + entity.Property(e => e.ConcurrencyControlNumber) + .HasColumnName("CONCURRENCY_CONTROL_NUMBER") + .HasDefaultValueSql("((1))"); + + entity.Property(e => e.DbAuditCreateTimestamp) + .HasColumnName("DB_AUDIT_CREATE_TIMESTAMP") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + + entity.Property(e => e.DbAuditCreateUserid) + .IsRequired() + .HasColumnName("DB_AUDIT_CREATE_USERID") + .HasMaxLength(30) + .IsUnicode(false) + .HasDefaultValueSql("(user_name())"); + + entity.Property(e => e.DbAuditLastUpdateTimestamp) + .HasColumnName("DB_AUDIT_LAST_UPDATE_TIMESTAMP") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + + entity.Property(e => e.DbAuditLastUpdateUserid) + .IsRequired() + .HasColumnName("DB_AUDIT_LAST_UPDATE_USERID") + .HasMaxLength(30) + .IsUnicode(false) + .HasDefaultValueSql("(user_name())"); + + entity.Property(e => e.EndDate) + .HasColumnName("END_DATE") + .HasColumnType("datetime"); + + entity.Property(e => e.ServiceAreaNumber) + .HasColumnName("SERVICE_AREA_NUMBER") + .HasColumnType("numeric(9, 0)"); + + entity.HasOne(d => d.ActivityCode) + .WithMany(p => p.HmrServiceAreaActivities) + .HasForeignKey(d => d.ActivityCodeId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__HMR_SERVI__ACTIV__3AC1AA49"); + + entity.HasOne(d => d.ServiceAreaNumberNavigation) + .WithMany(p => p.HmrServiceAreaActivities) + .HasForeignKey(d => d.ServiceAreaNumber) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__HMR_SERVI__SERVI__39CD8610"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.ServiceAreaActivityHistId) + .HasName("PK__HMR_SERV__08C5944CE2D33CB5"); + + entity.ToTable("HMR_SERVICE_AREA_ACTIVITY_HIST"); + + entity.Property(e => e.ServiceAreaActivityHistId) + .HasColumnName("SERVICE_AREA_ACTIVITY_HIST_ID") + .HasDefaultValueSql("(NEXT VALUE FOR [HMR_SERVICE_AREA_ACTIVITY_H_ID_SEQ])"); + + entity.Property(e => e.ActivityCodeId) + .HasColumnName("ACTIVITY_CODE_ID") + .HasColumnType("numeric(9, 0)"); + + entity.Property(e => e.AppCreateTimestamp) + .HasColumnName("APP_CREATE_TIMESTAMP") + .HasColumnType("datetime"); + + entity.Property(e => e.AppCreateUserDirectory) + .IsRequired() + .HasColumnName("APP_CREATE_USER_DIRECTORY") + .HasMaxLength(12) + .IsUnicode(false); + + entity.Property(e => e.AppCreateUserGuid).HasColumnName("APP_CREATE_USER_GUID"); + + entity.Property(e => e.AppCreateUserid) + .IsRequired() + .HasColumnName("APP_CREATE_USERID") + .HasMaxLength(30) + .IsUnicode(false); + + entity.Property(e => e.AppLastUpdateTimestamp) + .HasColumnName("APP_LAST_UPDATE_TIMESTAMP") + .HasColumnType("datetime"); + + entity.Property(e => e.AppLastUpdateUserDirectory) + .IsRequired() + .HasColumnName("APP_LAST_UPDATE_USER_DIRECTORY") + .HasMaxLength(12) + .IsUnicode(false); + + entity.Property(e => e.AppLastUpdateUserGuid).HasColumnName("APP_LAST_UPDATE_USER_GUID"); + + entity.Property(e => e.AppLastUpdateUserid) + .IsRequired() + .HasColumnName("APP_LAST_UPDATE_USERID") + .HasMaxLength(30) + .IsUnicode(false); + + entity.Property(e => e.ConcurrencyControlNumber) + .HasColumnName("CONCURRENCY_CONTROL_NUMBER") + .HasDefaultValueSql("((1))"); + + entity.Property(e => e.DbAuditCreateTimestamp) + .HasColumnName("DB_AUDIT_CREATE_TIMESTAMP") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + + entity.Property(e => e.DbAuditCreateUserid) + .IsRequired() + .HasColumnName("DB_AUDIT_CREATE_USERID") + .HasMaxLength(30) + .IsUnicode(false) + .HasDefaultValueSql("(user_name())"); + + entity.Property(e => e.DbAuditLastUpdateTimestamp) + .HasColumnName("DB_AUDIT_LAST_UPDATE_TIMESTAMP") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + + entity.Property(e => e.DbAuditLastUpdateUserid) + .IsRequired() + .HasColumnName("DB_AUDIT_LAST_UPDATE_USERID") + .HasMaxLength(30) + .IsUnicode(false) + .HasDefaultValueSql("(user_name())"); + + entity.Property(e => e.EffectiveDateHist) + .HasColumnName("EFFECTIVE_DATE_HIST") + .HasColumnType("datetime") + .HasDefaultValueSql("(getutcdate())"); + + entity.Property(e => e.EndDate) + .HasColumnName("END_DATE") + .HasColumnType("datetime"); + + entity.Property(e => e.EndDateHist) + .HasColumnName("END_DATE_HIST") + .HasColumnType("datetime"); + + entity.Property(e => e.ServiceAreaActivityId) + .HasColumnName("SERVICE_AREA_ACTIVITY_ID") + .HasColumnType("numeric(9, 0)"); + + entity.Property(e => e.ServiceAreaNumber) + .HasColumnName("SERVICE_AREA_NUMBER") + .HasColumnType("numeric(9, 0)"); + }); + modelBuilder.Entity(entity => { entity.HasKey(e => e.ServiceAreaHistId) @@ -5610,9 +5975,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMaxLength(255) .IsUnicode(false); - entity.Property(e => e.IsOverSpTolerance) + entity.Property(e => e.IsOverSpThreshold) .IsRequired() - .HasColumnName("IS_OVER_SP_TOLERANCE") + .HasColumnName("IS_OVER_SP_THRESHOLD") .HasMaxLength(1) .IsUnicode(false); @@ -5666,6 +6031,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMaxLength(1) .IsUnicode(false); + entity.Property(e => e.SpatialVariance) + .HasColumnName("SPATIAL_VARIANCE") + .HasColumnType("numeric(25, 20)"); + entity.Property(e => e.Species) .HasColumnName("SPECIES") .HasColumnType("numeric(2, 0)"); @@ -5684,6 +6053,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMaxLength(30) .IsUnicode(false); + entity.Property(e => e.WarningSpThreshold) + .HasColumnName("WARNING_SP_THRESHOLD") + .HasColumnType("numeric(12, 6)"); + entity.Property(e => e.WildlifeRecordId) .HasColumnName("WILDLIFE_RECORD_ID") .HasColumnType("numeric(9, 0)"); @@ -5892,7 +6265,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasColumnName("SITE_NUMBER") .HasMaxLength(8) .IsUnicode(false) - .HasComment("Contains a site type code followed by a The Ministry site number. Site types are provided by the Province, are four to six digits preceded by: A – Avalanche B – Arrestor Bed/Dragnet Barrier D – Debris and/or Rockfall L – Landscape R – Rest Area S – Signalized Intersection T – Traffic Patrol W – Weather Station X – Railway Crossing"); + .HasComment("Contains a site type code followed by a The Ministry site number. Site types are provided by the Province, are four to six digits preceded by: A � Avalanche B � Arrestor Bed/Dragnet Barrier D � Debris and/or Rockfall L � Landscape R � Rest Area S � Signalized Intersection T � Traffic Patrol W � Weather Station X � Railway Crossing"); entity.Property(e => e.StartDate) .HasColumnName("START_DATE") @@ -5916,7 +6289,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) entity.Property(e => e.StructureNumber) .HasColumnName("STRUCTURE_NUMBER") - .HasMaxLength(30) + .HasMaxLength(5) .IsUnicode(false) .HasComment("From list of Bridge Structure Road (BSR) structures provided by the Province. Is only applicable at defined BSR structures. BSR structures include; bridges, culverts over 3m, retaining walls."); @@ -6160,7 +6533,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) entity.Property(e => e.StructureNumber) .HasColumnName("STRUCTURE_NUMBER") - .HasMaxLength(30) + .HasMaxLength(5) .IsUnicode(false); entity.Property(e => e.SubmissionObjectId) @@ -6270,9 +6643,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMaxLength(255) .IsUnicode(false); - entity.Property(e => e.IsOverSpTolerance) + entity.Property(e => e.IsOverSpThreshold) .IsRequired() - .HasColumnName("IS_OVER_SP_TOLERANCE") + .HasColumnName("IS_OVER_SP_THRESHOLD") .HasMaxLength(1) .IsUnicode(false); @@ -6336,7 +6709,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) entity.Property(e => e.StructureNumber) .HasColumnName("STRUCTURE_NUMBER") - .HasMaxLength(30) + .HasMaxLength(5) .IsUnicode(false); entity.Property(e => e.SubmissionObjectId) @@ -6362,6 +6735,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasColumnName("VALUE_OF_WORK") .HasColumnType("numeric(9, 2)"); + entity.Property(e => e.WarningSpThreshold) + .HasColumnName("WARNING_SP_THRESHOLD") + .HasColumnType("numeric(12, 6)"); + entity.Property(e => e.WorkLength) .HasColumnName("WORK_LENGTH") .HasColumnType("numeric(25, 20)"); @@ -6383,6 +6760,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMin(1) .HasMax(2147483647); + modelBuilder.HasSequence("HMR_ACTIVITY_CODE_RULE_ID_SEQ") + .HasMin(1) + .HasMax(999999999); + modelBuilder.HasSequence("HMR_CNT_TRM_ID_SEQ") .HasMin(1) .HasMax(999999999); @@ -6459,6 +6840,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMin(1) .HasMax(2147483647); + modelBuilder.HasSequence("HMR_SERVICE_AREA_ACTIVITY_H_ID_SEQ") + .HasMin(1) + .HasMax(999999999); + + modelBuilder.HasSequence("HMR_SERVICE_AREA_ACTIVITY_ID_SEQ") + .HasMin(1) + .HasMax(999999999); + modelBuilder.HasSequence("HMR_SERVICE_AREA_H_ID_SEQ") .HasMin(1) .HasMax(2147483647); diff --git a/api/Hmcr.Data/Database/Entities/HmrActivityCode.cs b/api/Hmcr.Data/Database/Entities/HmrActivityCode.cs index 11571e03..a5f5605e 100644 --- a/api/Hmcr.Data/Database/Entities/HmrActivityCode.cs +++ b/api/Hmcr.Data/Database/Entities/HmrActivityCode.cs @@ -5,6 +5,11 @@ namespace Hmcr.Data.Database.Entities { public partial class HmrActivityCode { + public HmrActivityCode() + { + HmrServiceAreaActivities = new HashSet(); + } + public decimal ActivityCodeId { get; set; } public string ActivityNumber { get; set; } public string ActivityName { get; set; } @@ -29,7 +34,17 @@ public partial class HmrActivityCode public DateTime DbAuditCreateTimestamp { get; set; } public string DbAuditLastUpdateUserid { get; set; } public DateTime DbAuditLastUpdateTimestamp { get; set; } + public decimal RoadClassRule { get; set; } + public decimal RoadLengthRule { get; set; } + public decimal SurfaceTypeRule { get; set; } + public decimal? MinValue { get; set; } + public decimal? MaxValue { get; set; } + public int? ReportingFrequency { get; set; } public virtual HmrLocationCode LocationCode { get; set; } + public virtual HmrActivityCodeRule RoadClassRuleNavigation { get; set; } + public virtual HmrActivityCodeRule RoadLengthRuleNavigation { get; set; } + public virtual HmrActivityCodeRule SurfaceTypeRuleNavigation { get; set; } + public virtual ICollection HmrServiceAreaActivities { get; set; } } } diff --git a/api/Hmcr.Data/Database/Entities/HmrActivityCodeHist.cs b/api/Hmcr.Data/Database/Entities/HmrActivityCodeHist.cs index 8b5e7d2e..3e13fc63 100644 --- a/api/Hmcr.Data/Database/Entities/HmrActivityCodeHist.cs +++ b/api/Hmcr.Data/Database/Entities/HmrActivityCodeHist.cs @@ -32,5 +32,11 @@ public partial class HmrActivityCodeHist public DateTime DbAuditCreateTimestamp { get; set; } public string DbAuditLastUpdateUserid { get; set; } public DateTime DbAuditLastUpdateTimestamp { get; set; } + public decimal RoadClassRule { get; set; } + public decimal RoadLengthRule { get; set; } + public decimal SurfaceTypeRule { get; set; } + public decimal? MinValue { get; set; } + public decimal? MaxValue { get; set; } + public int? ReportingFrequency { get; set; } } } diff --git a/api/Hmcr.Data/Database/Entities/HmrActivityCodeRule.cs b/api/Hmcr.Data/Database/Entities/HmrActivityCodeRule.cs new file mode 100644 index 00000000..06757583 --- /dev/null +++ b/api/Hmcr.Data/Database/Entities/HmrActivityCodeRule.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; + +namespace Hmcr.Data.Database.Entities +{ + public partial class HmrActivityCodeRule + { + public HmrActivityCodeRule() + { + HmrActivityCodeRoadClassRuleNavigations = new HashSet(); + HmrActivityCodeRoadLengthRuleNavigations = new HashSet(); + HmrActivityCodeSurfaceTypeRuleNavigations = new HashSet(); + } + + public decimal ActivityCodeRuleId { get; set; } + public string ActivityRuleSet { get; set; } + public string ActivityRuleName { get; set; } + public string ActivityRuleExecName { get; set; } + public decimal? DisplayOrder { get; set; } + public DateTime? EndDate { get; set; } + public long ConcurrencyControlNumber { get; set; } + public string DbAuditCreateUserid { get; set; } + public DateTime DbAuditCreateTimestamp { get; set; } + public string DbAuditLastUpdateUserid { get; set; } + public DateTime DbAuditLastUpdateTimestamp { get; set; } + + public virtual ICollection HmrActivityCodeRoadClassRuleNavigations { get; set; } + public virtual ICollection HmrActivityCodeRoadLengthRuleNavigations { get; set; } + public virtual ICollection HmrActivityCodeSurfaceTypeRuleNavigations { get; set; } + } +} diff --git a/api/Hmcr.Data/Database/Entities/HmrCodeLookup.cs b/api/Hmcr.Data/Database/Entities/HmrCodeLookup.cs index 96473433..6cca393c 100644 --- a/api/Hmcr.Data/Database/Entities/HmrCodeLookup.cs +++ b/api/Hmcr.Data/Database/Entities/HmrCodeLookup.cs @@ -18,5 +18,6 @@ public partial class HmrCodeLookup public DateTime DbAuditCreateTimestamp { get; set; } public string DbAuditLastUpdateUserid { get; set; } public DateTime DbAuditLastUpdateTimestamp { get; set; } + public bool IsIntegerOnly { get; set; } } } diff --git a/api/Hmcr.Data/Database/Entities/HmrCodeLookupHist.cs b/api/Hmcr.Data/Database/Entities/HmrCodeLookupHist.cs index a7aa4dfa..97bc8c61 100644 --- a/api/Hmcr.Data/Database/Entities/HmrCodeLookupHist.cs +++ b/api/Hmcr.Data/Database/Entities/HmrCodeLookupHist.cs @@ -21,5 +21,6 @@ public partial class HmrCodeLookupHist public DateTime DbAuditCreateTimestamp { get; set; } public string DbAuditLastUpdateUserid { get; set; } public DateTime DbAuditLastUpdateTimestamp { get; set; } + public bool IsIntegerOnly { get; set; } } } diff --git a/api/Hmcr.Data/Database/Entities/HmrRockfallReportVw.cs b/api/Hmcr.Data/Database/Entities/HmrRockfallReportVw.cs index 96fd73ea..c8546df9 100644 --- a/api/Hmcr.Data/Database/Entities/HmrRockfallReportVw.cs +++ b/api/Hmcr.Data/Database/Entities/HmrRockfallReportVw.cs @@ -15,8 +15,12 @@ public partial class HmrRockfallReportVw public TimeSpan? EstimatedRockfallTime { get; set; } public decimal? StartLatitude { get; set; } public decimal? StartLongitude { get; set; } + public decimal? StartVariance { get; set; } public decimal? EndLatitude { get; set; } public decimal? EndLongitude { get; set; } + public decimal? EndVariance { get; set; } + public decimal? WarningSpThreshold { get; set; } + public string IsOverSpThreshold { get; set; } public string HighwayUnique { get; set; } public string HighwayUniqueName { get; set; } public decimal? HighwayUniqueLength { get; set; } diff --git a/api/Hmcr.Data/Database/Entities/HmrServiceArea.cs b/api/Hmcr.Data/Database/Entities/HmrServiceArea.cs index 8ced7ca7..da8b3580 100644 --- a/api/Hmcr.Data/Database/Entities/HmrServiceArea.cs +++ b/api/Hmcr.Data/Database/Entities/HmrServiceArea.cs @@ -9,6 +9,7 @@ public HmrServiceArea() { HmrContractTerms = new HashSet(); HmrRockfallReports = new HashSet(); + HmrServiceAreaActivities = new HashSet(); HmrServiceAreaUsers = new HashSet(); HmrSubmissionObjects = new HashSet(); HmrWildlifeReports = new HashSet(); @@ -29,6 +30,7 @@ public HmrServiceArea() public virtual HmrDistrict DistrictNumberNavigation { get; set; } public virtual ICollection HmrContractTerms { get; set; } public virtual ICollection HmrRockfallReports { get; set; } + public virtual ICollection HmrServiceAreaActivities { get; set; } public virtual ICollection HmrServiceAreaUsers { get; set; } public virtual ICollection HmrSubmissionObjects { get; set; } public virtual ICollection HmrWildlifeReports { get; set; } diff --git a/api/Hmcr.Data/Database/Entities/HmrServiceAreaActivity.cs b/api/Hmcr.Data/Database/Entities/HmrServiceAreaActivity.cs new file mode 100644 index 00000000..9ee42b74 --- /dev/null +++ b/api/Hmcr.Data/Database/Entities/HmrServiceAreaActivity.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; + +namespace Hmcr.Data.Database.Entities +{ + public partial class HmrServiceAreaActivity + { + public decimal ServiceAreaActivityId { get; set; } + public decimal ActivityCodeId { get; set; } + public decimal ServiceAreaNumber { get; set; } + public DateTime? EndDate { get; set; } + public long ConcurrencyControlNumber { get; set; } + public string AppCreateUserid { get; set; } + public DateTime AppCreateTimestamp { get; set; } + public Guid AppCreateUserGuid { get; set; } + public string AppCreateUserDirectory { get; set; } + public string AppLastUpdateUserid { get; set; } + public DateTime AppLastUpdateTimestamp { get; set; } + public Guid AppLastUpdateUserGuid { get; set; } + public string AppLastUpdateUserDirectory { get; set; } + public string DbAuditCreateUserid { get; set; } + public DateTime DbAuditCreateTimestamp { get; set; } + public string DbAuditLastUpdateUserid { get; set; } + public DateTime DbAuditLastUpdateTimestamp { get; set; } + + public virtual HmrActivityCode ActivityCode { get; set; } + public virtual HmrServiceArea ServiceAreaNumberNavigation { get; set; } + } +} diff --git a/api/Hmcr.Data/Database/Entities/HmrServiceAreaActivityHist.cs b/api/Hmcr.Data/Database/Entities/HmrServiceAreaActivityHist.cs new file mode 100644 index 00000000..38848d92 --- /dev/null +++ b/api/Hmcr.Data/Database/Entities/HmrServiceAreaActivityHist.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; + +namespace Hmcr.Data.Database.Entities +{ + public partial class HmrServiceAreaActivityHist + { + public long ServiceAreaActivityHistId { get; set; } + public DateTime EffectiveDateHist { get; set; } + public DateTime? EndDateHist { get; set; } + public decimal ServiceAreaActivityId { get; set; } + public decimal ActivityCodeId { get; set; } + public decimal ServiceAreaNumber { get; set; } + public DateTime? EndDate { get; set; } + public long ConcurrencyControlNumber { get; set; } + public string AppCreateUserid { get; set; } + public DateTime AppCreateTimestamp { get; set; } + public Guid AppCreateUserGuid { get; set; } + public string AppCreateUserDirectory { get; set; } + public string AppLastUpdateUserid { get; set; } + public DateTime AppLastUpdateTimestamp { get; set; } + public Guid AppLastUpdateUserGuid { get; set; } + public string AppLastUpdateUserDirectory { get; set; } + public string DbAuditCreateUserid { get; set; } + public DateTime DbAuditCreateTimestamp { get; set; } + public string DbAuditLastUpdateUserid { get; set; } + public DateTime DbAuditLastUpdateTimestamp { get; set; } + } +} diff --git a/api/Hmcr.Data/Database/Entities/HmrWildlifeReportVw.cs b/api/Hmcr.Data/Database/Entities/HmrWildlifeReportVw.cs index 281a5745..072de368 100644 --- a/api/Hmcr.Data/Database/Entities/HmrWildlifeReportVw.cs +++ b/api/Hmcr.Data/Database/Entities/HmrWildlifeReportVw.cs @@ -14,7 +14,9 @@ public partial class HmrWildlifeReportVw public string TimeOfKill { get; set; } public decimal? Latitude { get; set; } public decimal? Longitude { get; set; } - public string IsOverSpTolerance { get; set; } + public decimal? SpatialVariance { get; set; } + public decimal? WarningSpThreshold { get; set; } + public string IsOverSpThreshold { get; set; } public string HighwayUnique { get; set; } public string HighwayUniqueName { get; set; } public decimal? HighwayUniqueLength { get; set; } diff --git a/api/Hmcr.Data/Database/Entities/HmrWorkReportVw.cs b/api/Hmcr.Data/Database/Entities/HmrWorkReportVw.cs index b1e128eb..f76087bd 100644 --- a/api/Hmcr.Data/Database/Entities/HmrWorkReportVw.cs +++ b/api/Hmcr.Data/Database/Entities/HmrWorkReportVw.cs @@ -31,8 +31,9 @@ public partial class HmrWorkReportVw public decimal? EndLatitude { get; set; } public decimal? EndLongitude { get; set; } public decimal? EndVariance { get; set; } + public decimal? WarningSpThreshold { get; set; } public decimal? WorkLength { get; set; } - public string IsOverSpTolerance { get; set; } + public string IsOverSpThreshold { get; set; } public string StructureNumber { get; set; } public string SiteNumber { get; set; } public decimal? ValueOfWork { get; set; } diff --git a/api/Hmcr.Data/Mappings/EntityToModelProfile.cs b/api/Hmcr.Data/Mappings/EntityToModelProfile.cs index d54df836..5ecba541 100644 --- a/api/Hmcr.Data/Mappings/EntityToModelProfile.cs +++ b/api/Hmcr.Data/Mappings/EntityToModelProfile.cs @@ -2,6 +2,7 @@ using Hmcr.Data.Database.Entities; using Hmcr.Model; using Hmcr.Model.Dtos.ActivityCode; +using Hmcr.Model.Dtos.ActivityRule; using Hmcr.Model.Dtos.CodeLookup; using Hmcr.Model.Dtos.ContractTerm; using Hmcr.Model.Dtos.District; @@ -16,6 +17,7 @@ using Hmcr.Model.Dtos.RolePermission; using Hmcr.Model.Dtos.ServiceArea; using Hmcr.Model.Dtos.ServiceAreaUser; +using Hmcr.Model.Dtos.ServiceAreaActivity; using Hmcr.Model.Dtos.SubmissionObject; using Hmcr.Model.Dtos.SubmissionRow; using Hmcr.Model.Dtos.SubmissionStatus; @@ -111,7 +113,9 @@ public EntityToModelProfile() CreateMap(); CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/api/Hmcr.Data/Mappings/ModelToEntityProfile.cs b/api/Hmcr.Data/Mappings/ModelToEntityProfile.cs index 510b2d26..7115eed4 100644 --- a/api/Hmcr.Data/Mappings/ModelToEntityProfile.cs +++ b/api/Hmcr.Data/Mappings/ModelToEntityProfile.cs @@ -14,6 +14,7 @@ using Hmcr.Model.Dtos.RolePermission; using Hmcr.Model.Dtos.ServiceArea; using Hmcr.Model.Dtos.ServiceAreaUser; +using Hmcr.Model.Dtos.ServiceAreaActivity; using Hmcr.Model.Dtos.SubmissionObject; using Hmcr.Model.Dtos.SubmissionRow; using Hmcr.Model.Dtos.SubmissionStatus; @@ -23,6 +24,7 @@ using Hmcr.Model.Dtos.WildlifeReport; using Hmcr.Model.Dtos.WorkReport; using Hmcr.Model.Dtos.ActivityCode; +using Hmcr.Model.Dtos.ActivityRule; namespace Hmcr.Data.Mappings { @@ -30,8 +32,8 @@ public class ModelToEntityProfile : Profile { public ModelToEntityProfile() { - SourceMemberNamingConvention = new PascalCaseNamingConvention(); - DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention(); + //SourceMemberNamingConvention = new PascalCaseNamingConvention(); + //DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention(); SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); DestinationMemberNamingConvention = new PascalCaseNamingConvention(); @@ -96,6 +98,10 @@ public ModelToEntityProfile() CreateMap(); CreateMap(); + + CreateMap(); + + CreateMap (); } } } diff --git a/api/Hmcr.Data/Repositories/ActivityCodeRepository.cs b/api/Hmcr.Data/Repositories/ActivityCodeRepository.cs index 80090bab..7c182cc1 100644 --- a/api/Hmcr.Data/Repositories/ActivityCodeRepository.cs +++ b/api/Hmcr.Data/Repositories/ActivityCodeRepository.cs @@ -3,6 +3,7 @@ using Hmcr.Data.Repositories.Base; using Hmcr.Model.Dtos; using Hmcr.Model.Dtos.ActivityCode; +using Hmcr.Model.Dtos.ServiceArea; using Hmcr.Model.Utils; using Microsoft.EntityFrameworkCore; using System; @@ -65,14 +66,24 @@ public async Task CreateActivityCodeAsync(ActivityCodeCreateDto Mapper.Map(activityCode, activityCodeEntity); + //TODO: add in saving of Service Areas + foreach (var areaNumber in activityCode.ServiceAreaNumbers) + { + activityCodeEntity.HmrServiceAreaActivities + .Add(new HmrServiceAreaActivity + { + ServiceAreaNumber = areaNumber + }); + } await DbSet.AddAsync(activityCodeEntity); - + return activityCodeEntity; } public async Task GetActivityCodeAsync(decimal id) { var activityCodeEntity = await DbSet.AsNoTracking() + .Include(x => x.HmrServiceAreaActivities) .FirstOrDefaultAsync(ac => ac.ActivityCodeId == id); if (activityCodeEntity == null) @@ -82,6 +93,13 @@ public async Task GetActivityCodeAsync(decimal id) activityCode.IsReferenced = await _workReportRepo.IsActivityNumberInUseAsync(activityCode.ActivityNumber); + var serviceAreasNumbers = + activityCodeEntity + .HmrServiceAreaActivities //new table + .Select(s => s.ServiceAreaNumber) + .ToList(); + activityCode.ServiceAreaNumbers = serviceAreasNumbers; + return activityCode; } @@ -138,18 +156,26 @@ public async Task> GetActivityCodesAsync(string[ public async Task UpdateActivityCodeAsync(ActivityCodeUpdateDto activityCode) { var activityCodeEntity = await DbSet + .Include(x => x.HmrServiceAreaActivities) .FirstAsync(ac => ac.ActivityCodeId == activityCode.ActivityCodeId); activityCode.EndDate = activityCode.EndDate?.Date; Mapper.Map(activityCode, activityCodeEntity); + + SyncActivityCodeServiceAreas(activityCode, activityCodeEntity); } public async Task DeleteActivityCodeAsync(decimal id) { var activityCodeEntity = await DbSet + .Include(x => x.HmrServiceAreaActivities) .FirstAsync(ac => ac.ActivityCodeId == id); + foreach( var areaToDelete in activityCodeEntity.HmrServiceAreaActivities) + { DbContext.Remove(areaToDelete); + } + DbSet.Remove(activityCodeEntity); } @@ -166,5 +192,31 @@ private async IAsyncEnumerable FindActivityNumbersInUseAync(IEnumerable< yield return activityNumber; } } + + private void SyncActivityCodeServiceAreas(ActivityCodeUpdateDto activityCodeUpdateDto, HmrActivityCode activityCodeEntity) + { + var areasToDelete = + activityCodeEntity.HmrServiceAreaActivities.Where(s => !activityCodeUpdateDto.ServiceAreaNumbers.Contains(s.ServiceAreaNumber)).ToList(); + + for (var i = areasToDelete.Count() - 1; i >= 0; i--) + { + DbContext.Remove(areasToDelete[i]); + } + + var existingAreaNumbers = activityCodeEntity.HmrServiceAreaActivities.Select(s => s.ServiceAreaNumber); + + var newAreaNumbers = activityCodeUpdateDto.ServiceAreaNumbers.Where(r => !existingAreaNumbers.Contains(r)); + + foreach (var areaNumber in newAreaNumbers) + { + activityCodeEntity.HmrServiceAreaActivities + .Add(new HmrServiceAreaActivity + { + ServiceAreaNumber = areaNumber, + ActivityCodeId = activityCodeEntity.ActivityCodeId + }); + } + } + } } diff --git a/api/Hmcr.Data/Repositories/ActivityRuleRepository.cs b/api/Hmcr.Data/Repositories/ActivityRuleRepository.cs new file mode 100644 index 00000000..142a2ddf --- /dev/null +++ b/api/Hmcr.Data/Repositories/ActivityRuleRepository.cs @@ -0,0 +1,79 @@ +using AutoMapper; +using Hmcr.Data.Database.Entities; +using Hmcr.Data.Repositories.Base; +using Hmcr.Model.Dtos.ActivityRule; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Dynamic.Core; +using System.Threading.Tasks; + +namespace Hmcr.Data.Repositories +{ + public interface IActivityRuleRepository + { + Task> GetRoadLengthRulesAsync(); + Task> GetSurfaceTypeRulesAsync(); + Task> GetRoadClassRulesAsync(); + Task> GetDefaultRules(); + IEnumerable LoadActivityCodeRuleCache(); + } + + public class ActivityRuleRepository : HmcrRepositoryBase, IActivityRuleRepository + { + public ActivityRuleRepository(AppDbContext dbContext, IMapper mapper) + : base(dbContext, mapper) + { + } + + public IEnumerable LoadActivityCodeRuleCache() + { + return DbSet.AsNoTracking() + .Where(x => x.EndDate == null || DateTime.Today < x.EndDate) + .Select(x => + new ActivityCodeRuleCache + { + ActivityCodeRuleId = x.ActivityCodeRuleId, + ActivityRuleSet = x.ActivityRuleSet, + ActivityRuleName = x.ActivityRuleName, + ActivityRuleExecName = x.ActivityRuleExecName + } + ).ToArray(); + } + + public async Task> GetRoadLengthRulesAsync() + { + var activityRules = await DbSet.AsNoTracking() + .Where(s => s.ActivityRuleSet.ToUpper() == "ROAD_LENGTH") + .ToListAsync(); + + return Mapper.Map>(activityRules); + } + public async Task> GetSurfaceTypeRulesAsync() + { + var activityRules = await DbSet.AsNoTracking() + .Where(s => s.ActivityRuleSet.ToUpper() == "SURFACE_TYPE") + .ToListAsync(); + + return Mapper.Map>(activityRules); + } + public async Task> GetRoadClassRulesAsync() + { + var activityRules = await DbSet.AsNoTracking() + .Where(s => s.ActivityRuleSet.ToUpper() == "ROAD_CLASS") + .ToListAsync(); + + return Mapper.Map>(activityRules); + } + + public async Task> GetDefaultRules() + { + var activityRules = await DbSet.AsNoTracking() + .Where(s => s.ActivityRuleName.ToUpper() == "NOT APPLICABLE") + .ToListAsync(); + + return Mapper.Map>(activityRules); + } + } +} diff --git a/api/Hmcr.Domain/Hangfire/Base/ReportJobServiceBase.cs b/api/Hmcr.Domain/Hangfire/Base/ReportJobServiceBase.cs index 50488f22..3fff3a36 100644 --- a/api/Hmcr.Domain/Hangfire/Base/ReportJobServiceBase.cs +++ b/api/Hmcr.Domain/Hangfire/Base/ReportJobServiceBase.cs @@ -162,6 +162,36 @@ protected void SetErrorDetail(HmrSubmissionRow submissionRow, Dictionary> warnings) + { + //warning can only be set for a row + if (submissionRow != null) + { + if (submissionRow.WarningDetail != null) + { + var newWarnings = System.Text.Json.JsonSerializer.Deserialize(submissionRow.WarningDetail); + foreach (var warning in warnings) + { + newWarnings.FieldMessages.Add(new FieldMessage + { + Field = warning.Key.WordToWords(), + Messages = warning.Value + }); + } + submissionRow.WarningDetail = newWarnings.ToString(); + } else + { + //we need to check for + submissionRow.RowStatusId = _statusService.RowError; + submissionRow.WarningDetail = warnings.GetWarningDetail(); + } + + + + + } + } + protected async Task CommitAndSendEmailAsync() { MethodLogger.LogEntry(_logger, _enableMethodLog, _methodLogHeader); @@ -217,6 +247,7 @@ protected decimal GetRowNum(string row) protected void SetVarianceWarningDetail(HmrSubmissionRow row, string rfiSegment, string start, string end, string thresholdLevel) { + var warnings = new Dictionary>(); var threshold = _lookupService.GetThresholdLevel(thresholdLevel); var threasholdInKm = threshold.Warning / 1000M; @@ -225,11 +256,20 @@ protected void SetVarianceWarningDetail(HmrSubmissionRow row, string rfiSegment, if (row.StartVariance != null && row.StartVariance > threasholdInKm) { - row.WarningDetail = string.Format(RowWarning.VarianceWarning, "Start", start, rfiSegment, threshold.Warning); + //row.WarningDetail = string.Format(RowWarning.VarianceWarning, "Start", start, rfiSegment, threshold.Warning); + warnings.AddItem("Start GPS Variance", string.Format("{0} {1} is is not on the Highway Unique [{2}] within the warning threshold [{3}] metres", + "Start", start, rfiSegment, threshold.Warning)); } else if (row.EndVariance != null && row.EndVariance > threasholdInKm) { - row.WarningDetail = string.Format(RowWarning.VarianceWarning, "End", end, rfiSegment, threshold.Warning); + //row.WarningDetail = string.Format(RowWarning.VarianceWarning, "End", end, rfiSegment, threshold.Warning); + warnings.AddItem("End GPS Variance", string.Format("{0} {1} is is not on the Highway Unique [{2}] within the warning threshold [{3}] metres", + "End", end, rfiSegment, threshold.Warning)); + } + + if (warnings.Count > 0) + { + SetWarningDetail(row, warnings); } } diff --git a/api/Hmcr.Domain/Hangfire/WorkReportJobService.cs b/api/Hmcr.Domain/Hangfire/WorkReportJobService.cs index f3d561bc..5f21999d 100644 --- a/api/Hmcr.Domain/Hangfire/WorkReportJobService.cs +++ b/api/Hmcr.Domain/Hangfire/WorkReportJobService.cs @@ -94,14 +94,15 @@ public override async Task ProcessSubmission(SubmissionDto submissionDto) continue; } - untypedRow.FeatureType = activityCode.FeatureType ?? FeatureType.None; - untypedRow.SpThresholdLevel = activityCode.SpThresholdLevel; - + //set activity code rules and location code + SetActivityCodeRulesIntoUntypedRow(untypedRow, activityCode); + //this also sets RowType (D2, D3, D4) var entityName = GetValidationEntityName(untypedRow, activityCode); _validator.Validate(entityName, untypedRow, errors); - + + //stage 2 validation PerformFieldValidation(errors, untypedRow, activityCode); if (errors.Count > 0) @@ -128,6 +129,7 @@ public override async Task ProcessSubmission(SubmissionDto submissionDto) CopyCalculatedFieldsFormUntypedRow(typedRows, untypedRows); + //stage 3 validation? PerformAdditionalValidation(typedRows); } @@ -137,6 +139,8 @@ public override async Task ProcessSubmission(SubmissionDto submissionDto) return true; } + //stage 4 validation starts + var workReports = PerformSpatialValidationAndConversionBatchAsync(typedRows); _logger.LogInformation($"{_methodLogHeader} PerformSpatialValidationAndConversionAsync 100%"); @@ -147,7 +151,17 @@ public override async Task ProcessSubmission(SubmissionDto submissionDto) return true; } + //perform surfacetype lookup and validation + workReports = PerformSurfaceTypeValidationBatchAsync(workReports); + + if (_submission.SubmissionStatusId != _statusService.FileInProgress) + { + await CommitAndSendEmailAsync(); + return true; + } + _submission.SubmissionStatusId = _statusService.FileSuccess; + //stage 4 validation ends await foreach (var entity in _workReportRepo.SaveWorkReportAsnyc(_submission, workReports)) { } @@ -156,6 +170,242 @@ public override async Task ProcessSubmission(SubmissionDto submissionDto) return true; } + private List PerformSurfaceTypeValidationBatchAsync(List workReports) + { + MethodLogger.LogEntry(_logger, _enableMethodLog, _methodLogHeader, $"Total Record: {workReports.Count}"); + + //get surface type not applicable id + var notApplicableSurfaceTypeId = _validator.ActivityCodeRuleLookup + .Where(x => x.ActivityRuleSet == ActivityRuleType.SurfaceType) + .Where(x => x.ActivityRuleExecName == SurfaceTypeRules.NA) + .FirstOrDefault().ActivityCodeRuleId; + + //grouping the rows + var groups = new List>(); + var currentGroup = new List(); + + var count = 0; + foreach (var workReport in workReports) + { + currentGroup.Add(workReport); + count++; + + if (count % 10 == 0) + { + groups.Add(currentGroup); + currentGroup = new List(); + } + } + + if (currentGroup.Count > 0) + { + groups.Add(currentGroup); + } + + var updatedWorkReports = new ConcurrentBag(); + var progress = 0; + + foreach (var group in groups) + { + var tasklist = new List(); + + //don't batch if not location code C + foreach (var row in group.Where(x => x.WorkReportTyped.ActivityCodeValidation.LocationCode == "C")) + { + if (row.WorkReportTyped.ActivityCodeValidation.SurfaceTypeRuleId != notApplicableSurfaceTypeId) + { + tasklist.Add(Task.Run(async () => updatedWorkReports.Add(await PerformSurfaceTypeValidationAsync(row)))); + } + } + + Task.WaitAll(tasklist.ToArray()); + + progress += 10; + + if (progress % 500 == 0) + { + _logger.LogInformation($"{_methodLogHeader} PerformSurfaceTypeValidationAsync {progress}"); + } + } + + return updatedWorkReports.ToList(); + } + + private async Task PerformSurfaceTypeValidationAsync(WorkReportGeometry row) + { + var errors = new Dictionary>(); + var typedRow = row.WorkReportTyped; + var geometry = row.Geometry; + var submissionRow = _submissionRows[(decimal)typedRow.RowNum]; + typedRow.RoadFeatures = new List(); + + //build Geometry linestring + var geometryLineString = ""; + foreach (Coordinate coordinate in geometry.Coordinates) + { + geometryLineString += coordinate.X + "\\," + coordinate.Y; + geometryLineString += (coordinate != geometry.Coordinates.Last()) ? "\\," : ""; + } + + //surface type calls are different between Point & Line + if (typedRow.FeatureType == FeatureType.Point) + { + var result = await _spatialService.GetSurfaceTypeAssocWithPointAsync(geometryLineString); + + if (result.result == SpValidationResult.Fail) + { + SetErrorDetail(submissionRow, errors, _statusService.FileLocationError); + } + else if (result.result == SpValidationResult.Success) + { + if (result.surfaceType.Type != null) //only add if type was returned + { + typedRow.RoadFeatures.Add(new WorkReportRoadFeature(result.surfaceType.Type, result.surfaceType.Length)); + } + + PerformSurfaceTypeValidation(typedRow); + } + } + else if (typedRow.FeatureType == FeatureType.Line) + { + var result = await _spatialService.GetSurfaceTypeAssocWithLineAsync(geometryLineString); + + if (result.result == SpValidationResult.Fail) + { + SetErrorDetail(submissionRow, errors, _statusService.FileLocationError); + } + else if (result.result == SpValidationResult.Success) + { + var distinctTypes = result.surfaceTypes.Select(x => x.Type).Distinct().ToList(); + foreach (string type in distinctTypes) + { + var totalLengthOfType = result.surfaceTypes.Where(x => x.Type == type).Sum(x => x.Length); + typedRow.RoadFeatures.Add(new WorkReportRoadFeature(type, totalLengthOfType)); + } + + PerformSurfaceTypeValidation(typedRow); + } + } + + return row; + } + + private void PerformSurfaceTypeValidation(WorkReportTyped typedRow) + { + var warnings = new Dictionary>(); + var submissionRow = _submissionRows[(decimal)typedRow.RowNum]; + + //get total length of path + var totalLength = typedRow.RoadFeatures.Sum(x => x.SurfaceLength); + + //determine path length; paved, non-paved, unconstructed, other + var pavedLength = typedRow.RoadFeatures.Where(x => x.SurfaceType == RoadSurface.HOT_MIX || + x.SurfaceType == RoadSurface.COLD_MIX || x.SurfaceType == RoadSurface.CONCRETE || + x.SurfaceType == RoadSurface.SURFACE_TREATED).Sum(x => x.SurfaceLength); + + var unpavedLength = typedRow.RoadFeatures.Where(x => x.SurfaceType == RoadSurface.GRAVEL || + x.SurfaceType == RoadSurface.DIRT).Sum(x => x.SurfaceLength); + + var unconstructedLength = typedRow.RoadFeatures.Where(x => x.SurfaceType == RoadSurface.CLEARED || + x.SurfaceType == RoadSurface.UNCLEARED).Sum(x => x.SurfaceLength); + + var otherLength = typedRow.RoadFeatures.Where(x => x.SurfaceType == RoadSurface.OTHER || + x.SurfaceType == RoadSurface.UNKNOWN).Sum(x => x.SurfaceLength); + + var surfaceTypeRule = typedRow.ActivityCodeValidation.SurfaceTypeRuleExec; + + if (typedRow.FeatureType == FeatureType.Line) { + switch (surfaceTypeRule) + { + case SurfaceTypeRules.PavedSurface: + case SurfaceTypeRules.PavedStructure: + if ((pavedLength / totalLength) >= .8) + { + //nothing wrong + } + else + { + if (surfaceTypeRule == SurfaceTypeRules.PavedStructure) + { + //structure checking + } + else if (surfaceTypeRule == SurfaceTypeRules.PavedSurface) + { + warnings.AddItem("Surface Type Validation", $"Rule is {SurfaceTypeRules.PavedSurface} on Line and paved surface less than 80%"); + } + } + + break; + case SurfaceTypeRules.NonPavedSurface: + if ((unpavedLength / totalLength) >= .8) + { + //nothing wrong + } + else + { + warnings.AddItem("Surface Type Validation", $"Rule is {SurfaceTypeRules.NonPavedSurface} on Line and unpaved surface less than 80%"); + } + + break; + case SurfaceTypeRules.Unconstructed: + if ((unconstructedLength / totalLength) >= .2) + { + warnings.AddItem("Surface Type Validation", $"Rule is {SurfaceTypeRules.Unconstructed} on Line and unconstructed surface is more than 20%"); + } + + break; + } + + } else if (typedRow.FeatureType == FeatureType.Point) + { + switch (surfaceTypeRule) + { + case SurfaceTypeRules.PavedSurface: + case SurfaceTypeRules.PavedStructure: + if (pavedLength > 0) + { + //nothign wrong + } + else + { + if (unpavedLength > 0 && surfaceTypeRule == SurfaceTypeRules.PavedStructure) + { + //structure checking + } + else if (unpavedLength > 0 && surfaceTypeRule == SurfaceTypeRules.PavedSurface) + { + warnings.AddItem("Surface Type Validation", $"Rule is {SurfaceTypeRules.NonPavedSurface}, unpaved surface found on Point"); + } + } + + break; + case SurfaceTypeRules.NonPavedSurface: + if (unpavedLength > 0) + { + //nothing wrong + } + else if (pavedLength > 0) + { + warnings.AddItem("Surface Type Validation", $"Rule is {SurfaceTypeRules.NonPavedSurface}, paved surface found on Point"); + } + + break; + case SurfaceTypeRules.Unconstructed: + if (unconstructedLength > 0) + { + warnings.AddItem("Surface Type Validation", $"Rule is {SurfaceTypeRules.Unconstructed}, unconstructed surface found on Point"); + } + + break; + } + } + + if (warnings.Count > 0) + { + SetWarningDetail(submissionRow, warnings); + } + } + private void PerformFieldValidation(Dictionary> errors, WorkReportCsvDto untypedRow, ActivityCodeDto activityCode) { if (activityCode.LocationCode.LocationCode == "C" && activityCode.ActivityNumber.StartsWith('6')) @@ -257,9 +507,41 @@ private void CopyCalculatedFieldsFormUntypedRow(List typedRows, typedRow.SpatialData = untypedRow.SpatialData; typedRow.RowId = untypedRow.RowId; typedRow.SpThresholdLevel = untypedRow.SpThresholdLevel; + + //move activity rules and location code from untyped to typed + typedRow.ActivityCodeValidation.LocationCode = untypedRow.ActivityCodeValidation.LocationCode; + typedRow.ActivityCodeValidation.RoadLengthRuleId = untypedRow.ActivityCodeValidation.RoadLengthRuleId; + typedRow.ActivityCodeValidation.RoadLenghRuleExec = untypedRow.ActivityCodeValidation.RoadLenghRuleExec; + typedRow.ActivityCodeValidation.SurfaceTypeRuleId = untypedRow.ActivityCodeValidation.SurfaceTypeRuleId; + typedRow.ActivityCodeValidation.SurfaceTypeRuleExec = untypedRow.ActivityCodeValidation.SurfaceTypeRuleExec; + typedRow.ActivityCodeValidation.RoadClassRuleId = untypedRow.ActivityCodeValidation.RoadClassRuleId; + typedRow.ActivityCodeValidation.RoadClassRuleExec = untypedRow.ActivityCodeValidation.RoadClassRuleExec; } } + private void SetActivityCodeRulesIntoUntypedRow(WorkReportCsvDto untypedRow, ActivityCodeDto activityCode) + { + untypedRow.FeatureType = activityCode.FeatureType ?? FeatureType.None; + untypedRow.SpThresholdLevel = activityCode.SpThresholdLevel; + //set activity code rules and location code + untypedRow.ActivityCodeValidation.LocationCode = activityCode.LocationCode.LocationCode; + + untypedRow.ActivityCodeValidation.RoadLengthRuleId = activityCode.RoadLengthRule; + untypedRow.ActivityCodeValidation.RoadLenghRuleExec = _validator.ActivityCodeRuleLookup + .Where(x => x.ActivityCodeRuleId == activityCode.RoadLengthRule) + .FirstOrDefault().ActivityRuleExecName; + + untypedRow.ActivityCodeValidation.SurfaceTypeRuleId = activityCode.SurfaceTypeRule; + untypedRow.ActivityCodeValidation.SurfaceTypeRuleExec = _validator.ActivityCodeRuleLookup + .Where(x => x.ActivityCodeRuleId == activityCode.SurfaceTypeRule) + .FirstOrDefault().ActivityRuleExecName; + + untypedRow.ActivityCodeValidation.RoadClassRuleId = activityCode.RoadClassRule; + untypedRow.ActivityCodeValidation.RoadClassRuleExec = _validator.ActivityCodeRuleLookup + .Where(x => x.ActivityCodeRuleId == activityCode.RoadClassRule) + .FirstOrDefault().ActivityRuleExecName; + } + private List PerformSpatialValidationAndConversionBatchAsync(List typedRows) { MethodLogger.LogEntry(_logger, _enableMethodLog, _methodLogHeader, $"Total Record: {typedRows.Count}"); diff --git a/api/Hmcr.Domain/Services/ActivityCodeService.cs b/api/Hmcr.Domain/Services/ActivityCodeService.cs index 5816538c..8eb6c821 100644 --- a/api/Hmcr.Domain/Services/ActivityCodeService.cs +++ b/api/Hmcr.Domain/Services/ActivityCodeService.cs @@ -3,6 +3,7 @@ using Hmcr.Model; using Hmcr.Model.Dtos; using Hmcr.Model.Dtos.ActivityCode; +using Hmcr.Model.Dtos.ActivityRule; using Hmcr.Model.Utils; using System.Collections.Generic; using System.Threading.Tasks; @@ -26,15 +27,17 @@ public class ActivityCodeService : IActivityCodeService private IUnitOfWork _unitOfWork; private IWorkReportRepository _workReportRepo; private ILocationCodeRepository _locationCodeRepo; + private IActivityRuleRepository _activityRuleRepo; public ActivityCodeService(IActivityCodeRepository activityCodeRepo, IFieldValidatorService validatorService, IUnitOfWork unitOfWork, - IWorkReportRepository workReportRepo, ILocationCodeRepository locationCodeRepo) + IWorkReportRepository workReportRepo, ILocationCodeRepository locationCodeRepo, IActivityRuleRepository activityRuleRepo) { _activityCodeRepo = activityCodeRepo; _validatorService = validatorService; _unitOfWork = unitOfWork; _workReportRepo = workReportRepo; _locationCodeRepo = locationCodeRepo; + _activityRuleRepo = activityRuleRepo; } public async Task<(decimal id, Dictionary> Errors)> CreateActivityCodeAsync(ActivityCodeCreateDto activityCode) @@ -52,7 +55,7 @@ public ActivityCodeService(IActivityCodeRepository activityCodeRepo, IFieldValid } var newLocationCode = (await _locationCodeRepo.GetLocationCode(activityCode.LocationCodeId)).LocationCode; - + var entityName = GetEntityName(newLocationCode); _validatorService.Validate(entityName, activityCode, errors); @@ -61,9 +64,26 @@ public ActivityCodeService(IActivityCodeRepository activityCodeRepo, IFieldValid // location code is A or B, FeatureType is forced to null and SiteNumRequired is forced to false if (newLocationCode != "C") { + IEnumerable activityRuleDefaults = await _activityRuleRepo.GetDefaultRules(); + activityCode.FeatureType = null; activityCode.SpThresholdLevel = null; activityCode.IsSiteNumRequired = false; + foreach (ActivityCodeRuleDto activityRule in activityRuleDefaults) + { + if (activityRule.ActivityRuleSet == "ROAD_LENGTH") + { + activityCode.RoadLengthRule = activityRule.ActivityCodeRuleId; + } + else if (activityRule.ActivityRuleSet == "ROAD_CLASS") + { + activityCode.RoadClassRule = activityRule.ActivityCodeRuleId; + } + else if (activityRule.ActivityRuleSet == "SURFACE_TYPE") + { + activityCode.SurfaceTypeRule = activityRule.ActivityCodeRuleId; + } + } } if (errors.Count > 0) @@ -142,7 +162,7 @@ public async Task> GetActivityCodesAsync(string[ { errors.AddItem(Fields.LocationCodeId, $"LocationCode can only be changed to A"); } - + var entityName = GetEntityName(newLocationCode); _validatorService.Validate(entityName, activityCode, errors); @@ -151,15 +171,32 @@ public async Task> GetActivityCodesAsync(string[ // location code is A or B, FeatureType is forced to null and SiteNumRequired is forced to false if (newLocationCode != "C") { + IEnumerable activityRuleDefaults = await _activityRuleRepo.GetDefaultRules(); + activityCode.FeatureType = null; activityCode.SpThresholdLevel = null; activityCode.IsSiteNumRequired = false; + foreach (ActivityCodeRuleDto activityRule in activityRuleDefaults) + { + if (activityRule.ActivityRuleSet == "ROAD_LENGTH") + { + activityCode.RoadLengthRule = activityRule.ActivityCodeRuleId; + } + else if (activityRule.ActivityRuleSet == "ROAD_CLASS") + { + activityCode.RoadClassRule = activityRule.ActivityCodeRuleId; + } + else if (activityRule.ActivityRuleSet == "SURFACE_TYPE") + { + activityCode.SurfaceTypeRule = activityRule.ActivityCodeRuleId; + } + } } if (errors.Count > 0) { return (false, errors); - } + } await _activityCodeRepo.UpdateActivityCodeAsync(activityCode); _unitOfWork.Commit(); diff --git a/api/Hmcr.Domain/Services/ActivityRuleService.cs b/api/Hmcr.Domain/Services/ActivityRuleService.cs new file mode 100644 index 00000000..9e8d95f3 --- /dev/null +++ b/api/Hmcr.Domain/Services/ActivityRuleService.cs @@ -0,0 +1,43 @@ +using Hmcr.Data.Database; +using Hmcr.Data.Repositories; +using Hmcr.Model.Dtos.ActivityRule; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Hmcr.Domain.Services +{ + public interface IActivityRuleService + { + Task> GetRoadLengthRulesAsync(); + Task> GetSurfaceTypeRulesAsync(); + Task> GetRoadClassRulesAsync(); + } + + public class ActivityRuleService : IActivityRuleService + { + private IActivityRuleRepository _activityRuleRepo; + private IUnitOfWork _unitOfWork; + + public ActivityRuleService(IActivityRuleRepository activityRuleRepo, IUnitOfWork unitOfWork) + { + _activityRuleRepo = activityRuleRepo; + _unitOfWork = unitOfWork; + } + + public async Task> GetRoadLengthRulesAsync() + { + return await _activityRuleRepo.GetRoadLengthRulesAsync(); + } + + public async Task> GetSurfaceTypeRulesAsync() + { + return await _activityRuleRepo.GetSurfaceTypeRulesAsync(); + } + + public async Task> GetRoadClassRulesAsync() + { + return await _activityRuleRepo.GetRoadClassRulesAsync(); + } + + } +} diff --git a/api/Hmcr.Domain/Services/FieldValidatorService.cs b/api/Hmcr.Domain/Services/FieldValidatorService.cs index d86e89bf..cb4d2d8d 100644 --- a/api/Hmcr.Domain/Services/FieldValidatorService.cs +++ b/api/Hmcr.Domain/Services/FieldValidatorService.cs @@ -1,5 +1,6 @@ using Hmcr.Model; using Hmcr.Model.Dtos.CodeLookup; +using Hmcr.Model.Dtos.ActivityRule; using Hmcr.Model.Utils; using System; using System.Collections.Generic; @@ -14,12 +15,15 @@ public interface IFieldValidatorService void Validate(string entityName, string fieldName, T value, Dictionary> errors, int rowNum = 0); void Validate(string entityName, T entity, Dictionary> errors, int rowNum = 0, params string[] fieldsToSkip); IEnumerable CodeLookup { get; set; } + + IEnumerable ActivityCodeRuleLookup { get; set; } } public class FieldValidatorService : IFieldValidatorService { List _rules; RegexDefs _regex; public IEnumerable CodeLookup { get; set; } + public IEnumerable ActivityCodeRuleLookup { get; set; } public FieldValidatorService(RegexDefs regex) { _rules = new List(); diff --git a/api/Hmcr.Domain/Services/SpatialService.cs b/api/Hmcr.Domain/Services/SpatialService.cs index a41ac296..9fce8afa 100644 --- a/api/Hmcr.Domain/Services/SpatialService.cs +++ b/api/Hmcr.Domain/Services/SpatialService.cs @@ -19,11 +19,14 @@ public interface ISpatialService (decimal offset, string rfiSegment, string rfiSegmentName, string thresholdLevel, Dictionary> errors); Task<(SpValidationResult result, decimal snappedStartOffset, decimal snappedEndOffset, Point startPoint, Point endPoint, List lines, RfiSegment rfiSegment)> ValidateLrsLineAsync(decimal startOffset, decimal endOffset, string rfiSegment, string rfiSegmentName, string thresholdLevel, Dictionary> errors); + Task<(SpValidationResult result, List surfaceTypes)> GetSurfaceTypeAssocWithLineAsync(string geometryLineString); + Task<(SpValidationResult result, SurfaceType surfaceType)> GetSurfaceTypeAssocWithPointAsync(string geometryLineString); } public class SpatialService : ISpatialService { private IOasApi _oasApi; + private IInventoryApi _inventoryApi; private IFieldValidatorService _validator; private ILookupCodeService _lookupService; @@ -31,11 +34,12 @@ public class SpatialService : ISpatialService private IEnumerable _nonSpHighwayUniques = null; private IEnumerable NonSpHighwayUniques => _nonSpHighwayUniques ??= _validator.CodeLookup.Where(x => x.CodeSet == CodeSet.NonSpHighwayUnique).Select(x => x.CodeValue).ToArray().ToLowercase(); - public SpatialService(IOasApi oasApi, IFieldValidatorService validator, ILookupCodeService lookupService) + public SpatialService(IOasApi oasApi, IFieldValidatorService validator, ILookupCodeService lookupService, IInventoryApi inventoryApi) { _oasApi = oasApi; _validator = validator; _lookupService = lookupService; + _inventoryApi = inventoryApi; } public async Task<(SpValidationResult result, LrsPointResult lrsResult, RfiSegment rfiSegment)> ValidateGpsPointAsync @@ -158,7 +162,7 @@ public SpatialService(IOasApi oasApi, IFieldValidatorService validator, ILookupC return (SpValidationResult.Success, snappedOffset, point, rfiResult.segment); } - public async Task<(SpValidationResult result, decimal snappedStartOffset, decimal snappedEndOffset, Point startPoint, Point endPoint, List lines, RfiSegment rfiSegment)> + public async Task<(SpValidationResult result, decimal snappedStartOffset, decimal snappedEndOffset, Point startPoint, Point endPoint, List lines, RfiSegment rfiSegment)> ValidateLrsLineAsync(decimal startOffset, decimal endOffset, string rfiSegment, string rfiSegmentName, string thresholdLevel, Dictionary> errors) { var snappedStartOffset = startOffset; @@ -175,7 +179,7 @@ public SpatialService(IOasApi oasApi, IFieldValidatorService validator, ILookupC { return (SpValidationResult.Fail, rfiResult.segment.Length, rfiResult.segment.Length, null, null, null, rfiResult.segment); } - snappedStartOffset = startTolCheck.snappedOffset; + snappedStartOffset = startTolCheck.snappedOffset; //Get point by snappedStartOffset. Otherwise, it will raise an exception when the offset is greater than length of the road var startPoint = await _oasApi.GetPointFromOffsetMeasureOnRfiSegmentAsync(rfiSegment, snappedStartOffset); @@ -241,6 +245,20 @@ public SpatialService(IOasApi oasApi, IFieldValidatorService validator, ILookupC return (SpValidationResult.Success, rfiDetail); } + public async Task<(SpValidationResult result, List surfaceTypes)> GetSurfaceTypeAssocWithLineAsync(string geometryLineString) + { + var surfaceTypes = await _inventoryApi.GetSurfaceTypeAssociatedWithLine(geometryLineString); + + return (SpValidationResult.Success, surfaceTypes); + } + + public async Task<(SpValidationResult result, SurfaceType surfaceType)> GetSurfaceTypeAssocWithPointAsync(string geometryLineString) + { + var surfaceType = await _inventoryApi.GetSurfaceTypeAssociatedWithPoint(geometryLineString); + + return (SpValidationResult.Success, surfaceType); + } + private (bool withinTolerance, decimal snappedOffset) GetSnappedOffset(RfiSegment segment, decimal offset, string rfiSegment, string rfiSegmentName, string thresholdLevel, Dictionary> errors) { @@ -250,7 +268,7 @@ public SpatialService(IOasApi oasApi, IFieldValidatorService validator, ILookupC { var threshold = _lookupService.GetThresholdLevel(thresholdLevel); - if (segment.Length + threshold.Error / 1000M < offset) + if (segment.Length + threshold.Error / 1000M < offset) { errors.AddItem($"Offset", $"Offset [{offset}] is not on the {rfiSegmentName} [{rfiSegment}] within the tolerance [{threshold.Error}] metres"); return (false, snappedOffset); diff --git a/api/Hmcr.Hangfire/Startup.cs b/api/Hmcr.Hangfire/Startup.cs index 91fafe4e..c8c2a587 100644 --- a/api/Hmcr.Hangfire/Startup.cs +++ b/api/Hmcr.Hangfire/Startup.cs @@ -43,7 +43,8 @@ public void ConfigureServices(IServiceCollection services) } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISubmissionObjectJobService jobService, - IServiceScopeFactory serviceScopeFactory, IServiceAreaService svcAreaService, ICodeLookupRepository codeLookupRepo, IFieldValidatorService validator) + IServiceScopeFactory serviceScopeFactory, IServiceAreaService svcAreaService, ICodeLookupRepository codeLookupRepo, + IActivityRuleRepository activityRuleRepo, IFieldValidatorService validator) { if (env.IsDevelopment()) { @@ -67,6 +68,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISubmiss //Inject Code Lookup validator.CodeLookup = codeLookupRepo.LoadCodeLookupCache(); + validator.ActivityCodeRuleLookup = activityRuleRepo.LoadActivityCodeRuleCache(); minutes = Configuration.GetValue("Hangfire:EmailJobIntervalInMinutes"); minutes = minutes < 1 ? 30 : minutes; diff --git a/api/Hmcr.Model/Constants.cs b/api/Hmcr.Model/Constants.cs index 3db0b3fe..1a4e3eb2 100644 --- a/api/Hmcr.Model/Constants.cs +++ b/api/Hmcr.Model/Constants.cs @@ -323,6 +323,36 @@ public static class FeatureType public const string PointLine = "Point/Line"; } + public static class ActivityRuleType + { + public const string RoadLength = "ROAD_LENGTH"; + public const string SurfaceType = "SURFACE_TYPE"; + public const string RoadClass = "ROAD_CLASS"; + } + + public static class SurfaceTypeRules + { + public const string NA = "NOT_APPLICABLE"; + public const string PavedStructure = "GPS_PAVED_STRUCTURE"; + public const string PavedSurface = "GPS_PAVED_SURFACE"; + public const string NonPavedSurface = "GPS_NON_PAVED_SURFACE"; + public const string Unconstructed = "GPS_NOT_UNCONSTRUCTED"; + } + + public static class RoadSurface + { + public const string HOT_MIX = "1"; + public const string COLD_MIX = "2"; + public const string CONCRETE = "3"; + public const string SURFACE_TREATED = "4"; + public const string GRAVEL = "5"; + public const string DIRT = "6"; + public const string CLEARED = "E"; + public const string UNCLEARED = "F"; + public const string OTHER = "7"; + public const string UNKNOWN = "Z"; + } + /// /// Spatial Data /// None - Non-Location specific reporting Fields diff --git a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeCreateDto.cs b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeCreateDto.cs index e72f9176..4698832f 100644 --- a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeCreateDto.cs +++ b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeCreateDto.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace Hmcr.Model.Dtos.ActivityCode { @@ -13,5 +14,12 @@ public class ActivityCodeCreateDto public string SpThresholdLevel { get; set; } public bool IsSiteNumRequired { get; set; } public DateTime? EndDate { get; set; } + public decimal RoadLengthRule { get; set; } + public decimal SurfaceTypeRule { get; set; } + public decimal RoadClassRule { get; set; } + public IList ServiceAreaNumbers { get; set; } + public decimal? MinValue { get; set; } + public decimal? MaxValue { get; set; } + public int? ReportingFrequency { get; set; } } } \ No newline at end of file diff --git a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeDto.cs b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeDto.cs index 99de416a..98073301 100644 --- a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeDto.cs +++ b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeDto.cs @@ -1,5 +1,6 @@ using Hmcr.Model.Dtos.LocationCode; using System; +using System.Collections.Generic; using System.Text.Json.Serialization; namespace Hmcr.Model.Dtos.ActivityCode @@ -21,6 +22,15 @@ public class ActivityCodeDto public bool IsActive => EndDate == null || EndDate > DateTime.Today; public LocationCodeDto LocationCode { get; set; } + + public decimal RoadLengthRule { get; set; } + public decimal SurfaceTypeRule { get; set; } + public decimal RoadClassRule { get; set; } + public IList ServiceAreaNumbers { get; set; } + + public decimal? MinValue { get; set; } + public decimal? MaxValue { get; set; } + public int? ReportingFrequency { get; set; } } } diff --git a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeSearchDto.cs b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeSearchDto.cs index b81b5b0f..acf339be 100644 --- a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeSearchDto.cs +++ b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeSearchDto.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text.Json.Serialization; namespace Hmcr.Model.Dtos.ActivityCode @@ -19,5 +20,14 @@ public class ActivityCodeSearchDto public DateTime? EndDate { get; set; } public bool IsActive => EndDate == null || EndDate > DateTime.Today; public bool IsReferenced { get; set; } + + public decimal RoadLengthRule { get; set; } + public decimal SurfaceTypeRule { get; set; } + public decimal RoadClassRule { get; set; } + public IList ServiceAreaNumbers { get; set; } + + public decimal? MinValue { get; set; } + public decimal? MaxValue { get; set; } + public int? ReportingFrequency { get; set; } } } diff --git a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeUpdateDto.cs b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeUpdateDto.cs index 77bf714d..d64dd663 100644 --- a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeUpdateDto.cs +++ b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeUpdateDto.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text.Json.Serialization; namespace Hmcr.Model.Dtos.ActivityCode @@ -13,5 +14,13 @@ public class ActivityCodeUpdateDto public string SpThresholdLevel { get; set; } public bool IsSiteNumRequired { get; set; } public DateTime? EndDate { get; set; } + public decimal RoadLengthRule { get; set; } + public decimal SurfaceTypeRule { get; set; } + public decimal RoadClassRule { get; set; } + public IList ServiceAreaNumbers { get; set; } + + public decimal? MinValue { get; set; } + public decimal? MaxValue { get; set; } + public int? ReportingFrequency { get; set; } } } diff --git a/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeValidationDto.cs b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeValidationDto.cs new file mode 100644 index 00000000..f2d2d950 --- /dev/null +++ b/api/Hmcr.Model/Dtos/ActivityCode/ActivityCodeValidationDto.cs @@ -0,0 +1,24 @@ +using Hmcr.Model.Dtos.LocationCode; +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Hmcr.Model.Dtos.ActivityCode +{ + public class ActivityCodeValidationDto + { + public string LocationCode { get; set; } + + public decimal RoadLengthRuleId { get; set; } + public string RoadLenghRuleExec { get; set; } + public decimal SurfaceTypeRuleId { get; set; } + public string SurfaceTypeRuleExec { get; set; } + public decimal RoadClassRuleId { get; set; } + public string RoadClassRuleExec { get; set; } + public virtual IList ServiceAreaNumbers { get; set; } + + public decimal? MinimumValue { get; set; } + public decimal? MaximumValue { get; set; } + public decimal? ReportingFrequency { get; set; } + } +} diff --git a/api/Hmcr.Model/Dtos/ActivityCodeRule/ActivityCodeRuleCache.cs b/api/Hmcr.Model/Dtos/ActivityCodeRule/ActivityCodeRuleCache.cs new file mode 100644 index 00000000..4daf4077 --- /dev/null +++ b/api/Hmcr.Model/Dtos/ActivityCodeRule/ActivityCodeRuleCache.cs @@ -0,0 +1,16 @@ +using System; +using System.Text.Json.Serialization; + +namespace Hmcr.Model.Dtos.ActivityRule +{ + public class ActivityCodeRuleCache + { + [JsonPropertyName("id")] + public decimal ActivityCodeRuleId { get; set; } + [JsonPropertyName("name")] + public string ActivityRuleSet { get; set; } + public string ActivityRuleName { get; set; } + public string ActivityRuleExecName { get; set; } + + } +} \ No newline at end of file diff --git a/api/Hmcr.Model/Dtos/ActivityCodeRule/ActivityCodeRuleDto.cs b/api/Hmcr.Model/Dtos/ActivityCodeRule/ActivityCodeRuleDto.cs new file mode 100644 index 00000000..9099814d --- /dev/null +++ b/api/Hmcr.Model/Dtos/ActivityCodeRule/ActivityCodeRuleDto.cs @@ -0,0 +1,18 @@ +using System; +using System.Text.Json.Serialization; + +namespace Hmcr.Model.Dtos.ActivityRule +{ + public class ActivityCodeRuleDto + { + [JsonPropertyName("id")] + public decimal ActivityCodeRuleId { get; set; } + [JsonPropertyName("name")] + public string ActivityRuleName { get; set; } + public string ActivityRuleSet { get; set; } + public string ActivityRuleExecName { get; set; } + public decimal DisplayOrder { get; set; } + public DateTime? EndDate { get; set; } + + } +} diff --git a/api/Hmcr.Model/Dtos/ServiceAreaActivity/ServiceAreaActivityDto.cs b/api/Hmcr.Model/Dtos/ServiceAreaActivity/ServiceAreaActivityDto.cs new file mode 100644 index 00000000..b8f003c8 --- /dev/null +++ b/api/Hmcr.Model/Dtos/ServiceAreaActivity/ServiceAreaActivityDto.cs @@ -0,0 +1,18 @@ +using Hmcr.Model.Dtos.ServiceArea; +using Hmcr.Model.Dtos.ServiceAreaActivity; +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.Json.Serialization; + +namespace Hmcr.Model.Dtos.ServiceAreaActivity +{ + public class ServiceAreaActivityDto + { + [JsonPropertyName("id")] + public decimal ServiceAreaActivityId { get; set; } + public decimal ActivityCodeId { get; set; } + public decimal ServiceAreaNumber { get; set; } + public DateTime? EndDate { get; set; } + } +} diff --git a/api/Hmcr.Model/Dtos/WorkReport/WorkReportCsvDto.cs b/api/Hmcr.Model/Dtos/WorkReport/WorkReportCsvDto.cs index ab6513f4..0a9931d8 100644 --- a/api/Hmcr.Model/Dtos/WorkReport/WorkReportCsvDto.cs +++ b/api/Hmcr.Model/Dtos/WorkReport/WorkReportCsvDto.cs @@ -1,4 +1,5 @@ -using System; +using Hmcr.Model.Dtos.ActivityCode; +using System; namespace Hmcr.Model.Dtos.WorkReport { @@ -43,5 +44,8 @@ public class WorkReportCsvDto : IReportCsvDto /// public SpatialData SpatialData { get; set; } public string SpThresholdLevel { get; set; } + + public ActivityCodeValidationDto ActivityCodeValidation { get; set; } + } } diff --git a/api/Hmcr.Model/Dtos/WorkReport/WorkReportRoadFeature.cs b/api/Hmcr.Model/Dtos/WorkReport/WorkReportRoadFeature.cs new file mode 100644 index 00000000..b6962876 --- /dev/null +++ b/api/Hmcr.Model/Dtos/WorkReport/WorkReportRoadFeature.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Hmcr.Model.Dtos.WorkReport +{ + public class WorkReportRoadFeature + { + public string SurfaceType { get; set; } + public double SurfaceLength { get; set; } + + public WorkReportRoadFeature(string surfaceType, double surfaceLength) + { + SurfaceType = surfaceType; + SurfaceLength = surfaceLength; + } + } +} \ No newline at end of file diff --git a/api/Hmcr.Model/Dtos/WorkReport/WorkReportTyped.cs b/api/Hmcr.Model/Dtos/WorkReport/WorkReportTyped.cs index 3a891b6e..b9457473 100644 --- a/api/Hmcr.Model/Dtos/WorkReport/WorkReportTyped.cs +++ b/api/Hmcr.Model/Dtos/WorkReport/WorkReportTyped.cs @@ -1,4 +1,6 @@ -using System; +using Hmcr.Model.Dtos.ActivityCode; +using System; +using System.Collections.Generic; namespace Hmcr.Model.Dtos.WorkReport { @@ -50,5 +52,11 @@ public class WorkReportTyped /// public SpatialData SpatialData { get; set; } public string SpThresholdLevel { get; set; } + + /// + /// Road feature data retrieved from CHRIS + /// + public virtual IList RoadFeatures { get; set; } + public ActivityCodeValidationDto ActivityCodeValidation { get; set; } } } diff --git a/api/Hmcr.Model/EmailBody.cs b/api/Hmcr.Model/EmailBody.cs index 01d5fce3..38c14dee 100644 --- a/api/Hmcr.Model/EmailBody.cs +++ b/api/Hmcr.Model/EmailBody.cs @@ -51,7 +51,7 @@ private string SetHtmlBody(bool success, bool isFileError = false, string errorD else if (isFileError && !string.IsNullOrEmpty(errorDetailJson)) { - var errorDetail = JsonSerializer.Deserialize(errorDetailJson, _jsonOptions); + var errorDetail = JsonSerializer.Deserialize(errorDetailJson, _jsonOptions); htmlBody.Append("
  • Status Detail
  • "); diff --git a/api/Hmcr.Model/FieldMessage.cs b/api/Hmcr.Model/FieldMessage.cs index 813cc899..35e132e4 100644 --- a/api/Hmcr.Model/FieldMessage.cs +++ b/api/Hmcr.Model/FieldMessage.cs @@ -1,12 +1,15 @@ using System; using System.Collections.Generic; using System.Text; +using System.Text.Json.Serialization; namespace Hmcr.Model { public class FieldMessage { + [JsonPropertyName("field")] public string Field { get; set; } + [JsonPropertyName("messages")] public List Messages { get; set; } } } diff --git a/api/Hmcr.Model/ErrorDetail.cs b/api/Hmcr.Model/MessageDetail.cs similarity index 55% rename from api/Hmcr.Model/ErrorDetail.cs rename to api/Hmcr.Model/MessageDetail.cs index 3e05bba9..c56d5256 100644 --- a/api/Hmcr.Model/ErrorDetail.cs +++ b/api/Hmcr.Model/MessageDetail.cs @@ -1,37 +1,41 @@ using Hmcr.Model.Utils; using System.Collections.Generic; using System.Text.Json; +using System.Text.Json.Serialization; namespace Hmcr.Model { - public class ErrorDetail + + public class MessageDetail { private static JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { WriteIndented = false, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + [JsonPropertyName("fieldMessages")] public List FieldMessages { get; set; } - - public ErrorDetail() + + public MessageDetail() { - + FieldMessages = new List(); } - public ErrorDetail(Dictionary> errors) + public MessageDetail(Dictionary> messages) { FieldMessages = new List(); - foreach (var error in errors) + foreach (var message in messages) { FieldMessages.Add(new FieldMessage { - Field = error.Key.WordToWords(), - Messages = error.Value + Field = message.Key.WordToWords(), + Messages = message.Value }); } } public override string ToString() { - return JsonSerializer.Serialize(this, _jsonOptions); + return JsonSerializer.Serialize(this, _jsonOptions); } + } } diff --git a/api/Hmcr.Model/Utils/StringExtensions.cs b/api/Hmcr.Model/Utils/StringExtensions.cs index d63f1b77..3804ede8 100644 --- a/api/Hmcr.Model/Utils/StringExtensions.cs +++ b/api/Hmcr.Model/Utils/StringExtensions.cs @@ -89,10 +89,16 @@ public static void AddItem(this Dictionary> dictionary, str public static string GetErrorDetail(this Dictionary> errors) { - var fileErrorDetail = new ErrorDetail(errors); + var fileErrorDetail = new MessageDetail(errors); return fileErrorDetail.ToString(); } + public static string GetWarningDetail(this Dictionary> warnings) + { + var fileWarningDetail = new MessageDetail(warnings); + return fileWarningDetail.ToString(); + } + public static bool IsIdirUser(this string str) { return str.ToUpperInvariant() == UserTypeDto.INTERNAL; diff --git a/client/src/js/Api.js b/client/src/js/Api.js index f9063f81..fa0e1279 100644 --- a/client/src/js/Api.js +++ b/client/src/js/Api.js @@ -67,6 +67,10 @@ export const postActivityCode = (data) => instance.post(Constants.API_PATHS.ACTI export const putActivityCode = (id, data) => instance.put(`${Constants.API_PATHS.ACTIVITY_CODES}/${id}`, data); export const deleteActivityCode = (id) => instance.delete(`${Constants.API_PATHS.ACTIVITY_CODES}/${id}`); +export const getRoadLengthRules = () => instance.get(Constants.API_PATHS.RULE_ROAD_LENGTH); +export const getSurfaceTypeRules = () => instance.get(Constants.API_PATHS.RULE_SURFACE_TYPE); +export const getRoadClassRules = () => instance.get(Constants.API_PATHS.RULE_ROAD_CLASS); + export const getReportExport = (params) => instance.get(Constants.API_PATHS.REPORT_EXPORT, { params: { ...params } }); export const getExportSupportedFormats = () => instance.get(Constants.API_PATHS.SUPPORTED_FORMATS); diff --git a/client/src/js/Constants.js b/client/src/js/Constants.js index 186359e7..9b03084d 100644 --- a/client/src/js/Constants.js +++ b/client/src/js/Constants.js @@ -3,10 +3,14 @@ export const API_URL = window.RUNTIME_REACT_APP_API_HOST //In non-dev environmen : `${window.location.protocol}//${process.env.REACT_APP_CLIENT_ORIGIN}/api`; //For dev environment, proxy (setupProxy.js) is set up to avoid the same origin policy const CODE_LOOKUP = '/codelookup'; +const ACTIVITY_RULE = '/activityrule'; export const API_PATHS = { ACTIVITY_CODES: '/activitycodes', ACTIVITY_CODES_LITE: '/activitycodes/lite', + RULE_ROAD_LENGTH: `${ACTIVITY_RULE}/roadlength`, + RULE_SURFACE_TYPE: `${ACTIVITY_RULE}/surfacetype`, + RULE_ROAD_CLASS: `${ACTIVITY_RULE}/roadclass`, CODE_LOOKUP: CODE_LOOKUP, MAINTENANCE_TYPES: `${CODE_LOOKUP}/maintenancetypes`, UNIT_OF_MEASURES: `${CODE_LOOKUP}/unitofmeasures`, diff --git a/client/src/js/actions/codeLookupsActions.js b/client/src/js/actions/codeLookupsActions.js index 4a0b97d2..88a1e087 100644 --- a/client/src/js/actions/codeLookupsActions.js +++ b/client/src/js/actions/codeLookupsActions.js @@ -5,10 +5,34 @@ import { FETCH_LOCATION_CODES, FETCH_ACTIVITY_CODES_DROPDOWN, FETCH_THRESHOLD_LEVELS, + FETCH_ROAD_LENGTH_RULES, + FETCH_SURFACE_TYPE_RULES, + FETCH_ROAD_CLASS_RULES } from './types'; import * as api from '../Api'; +export const fetchRoadLengthRules = () => (dispatch) => { + return api.getRoadLengthRules().then((response) => { + const data = response.data; + dispatch({ type: FETCH_ROAD_LENGTH_RULES, payload: data }); + }); +}; + +export const fetchSurfaceTypeRules = () => (dispatch) => { + return api.getSurfaceTypeRules().then((response) => { + const data = response.data; + dispatch({ type: FETCH_SURFACE_TYPE_RULES, payload: data }); + }); +}; + +export const fetchRoadClassRules = () => (dispatch) => { + return api.getRoadClassRules().then((response) => { + const data = response.data; + dispatch({ type: FETCH_ROAD_CLASS_RULES, payload: data }); + }); +}; + export const fetchMaintenanceTypes = () => (dispatch) => { return api.getMaintenanceTypes().then((response) => { const data = response.data; diff --git a/client/src/js/actions/types.js b/client/src/js/actions/types.js index bd71183a..380c2086 100644 --- a/client/src/js/actions/types.js +++ b/client/src/js/actions/types.js @@ -14,6 +14,10 @@ export const FETCH_THRESHOLD_LEVELS = 'FETCH_THRESHOLD_LEVELS'; export const FETCH_SUBMISSION_STREAMS = 'FETCH_SUBMISSION_STREAMS'; export const FETCH_SUBMISSION_STATUSES = 'FETCH_SUBMISSION_STATUSES'; +export const FETCH_ROAD_LENGTH_RULES = 'FETCH_ROAD_LENGTH_RULES'; +export const FETCH_SURFACE_TYPE_RULES = 'FETCH_SURFACE_TYPE_RULES'; +export const FETCH_ROAD_CLASS_RULES = 'FETCH_ROAD_CLASS_RULES'; + // Global Error Dialog export const SHOW_ERROR_DIALOG_MODAL = 'SHOW_ERROR_DIALOG_MODAL'; export const HIDE_ERROR_DIALOG_MODAL = 'HIDE_ERROR_DIALOG_MODAL'; diff --git a/client/src/js/components/ActivityAdmin.js b/client/src/js/components/ActivityAdmin.js index 1d41420f..07d615e0 100644 --- a/client/src/js/components/ActivityAdmin.js +++ b/client/src/js/components/ActivityAdmin.js @@ -20,7 +20,7 @@ import { showValidationErrorDialog } from '../actions'; import * as Constants from '../Constants'; import * as api from '../Api'; -import { buildStatusIdArray } from '../utils'; +import { buildStatusIdArray,isValueNotEmpty,toNumberOrNull,toStringOrEmpty,toStringWithCommasOrEmpty,isValueEmpty } from '../utils'; const defaultSearchFormValues = { searchText: '', maintenanceTypeIds: [], statusId: [Constants.ACTIVE_STATUS.ACTIVE] }; @@ -41,7 +41,7 @@ const tableColumns = [ { heading: 'Active', key: 'isActive', nosort: true }, ]; -const ActivityAdmin = ({ maintenanceTypes, locationCodes, unitOfMeasures, showValidationErrorDialog }) => { +const ActivityAdmin = ({ maintenanceTypes, locationCodes, unitOfMeasures,showValidationErrorDialog }) => { const location = useLocation(); const searchData = useSearchData(defaultSearchOptions); const [searchInitialValues, setSearchInitialValues] = useState(defaultSearchFormValues); @@ -105,12 +105,24 @@ const ActivityAdmin = ({ maintenanceTypes, locationCodes, unitOfMeasures, showVa values.featureType = null; values.isSiteNumRequired = false; values.thresholdLevels = null; + values.roadClassRule = 0; + values.roadLengthRule = 0; + values.surfaceTypeRule = 0; + } + values.minValue = toNumberOrNull(values.minValue); + values.maxValue = toNumberOrNull(values.maxValue); + values.reportingFrequency = toNumberOrNull(values.reportingFrequency ); + if(isValueNotEmpty(values.minValue) && isValueEmpty(values.maxValue)) + { + values.maxValue = (['site','num','ea'].includes(values.unitOfMeasure)) ? 999999999:999999999.99; } - if (formType === Constants.FORM_TYPE.ADD) { api .postActivityCode(values) .then(() => { + values.minValue = toStringWithCommasOrEmpty(values.minValue); + values.maxValue = toStringWithCommasOrEmpty(values.maxValue); + values.reportingFrequency = toStringOrEmpty(values.reportingFrequency ); formModal.closeForm(); searchData.refresh(); }) @@ -120,6 +132,9 @@ const ActivityAdmin = ({ maintenanceTypes, locationCodes, unitOfMeasures, showVa api .putActivityCode(values.id, values) .then(() => { + values.minValue = toStringWithCommasOrEmpty(values.minValue); + values.maxValue = toStringWithCommasOrEmpty(values.maxValue); + values.reportingFrequency = toStringOrEmpty(values.reportingFrequency ); formModal.closeForm(); searchData.refresh(); }) @@ -129,7 +144,7 @@ const ActivityAdmin = ({ maintenanceTypes, locationCodes, unitOfMeasures, showVa } }; - const formModal = useFormModal('Activity', , handleEditFormSubmit); + const formModal = useFormModal('Activity', , handleEditFormSubmit,'xl'); const data = searchData.data.map((item) => ({ ...item, diff --git a/client/src/js/components/Main.js b/client/src/js/components/Main.js index 6c71ca58..8ccba6cf 100644 --- a/client/src/js/components/Main.js +++ b/client/src/js/components/Main.js @@ -16,6 +16,9 @@ import { fetchSubmissionStatuses, fetchSubmissionStreams, fetchThresholdLevels, + fetchRoadLengthRules, + fetchSurfaceTypeRules, + fetchRoadClassRules } from '../actions'; const Main = ({ @@ -32,6 +35,9 @@ const Main = ({ fetchSubmissionStatuses, fetchSubmissionStreams, fetchThresholdLevels, + fetchRoadLengthRules, + fetchSurfaceTypeRules, + fetchRoadClassRules }) => { const [loading, setLoading] = useState(true); @@ -48,6 +54,9 @@ const Main = ({ fetchSubmissionStatuses(), fetchSubmissionStreams(), fetchThresholdLevels(), + fetchRoadLengthRules(), + fetchSurfaceTypeRules(), + fetchRoadClassRules() ]).then(() => setLoading(false)); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); @@ -78,4 +87,7 @@ export default connect(mapStateToProps, { fetchSubmissionStatuses, fetchSubmissionStreams, fetchThresholdLevels, + fetchRoadLengthRules, + fetchSurfaceTypeRules, + fetchRoadClassRules })(Main); diff --git a/client/src/js/components/forms/EditActivityFormFields.js b/client/src/js/components/forms/EditActivityFormFields.js index 321c59e9..b9311f92 100644 --- a/client/src/js/components/forms/EditActivityFormFields.js +++ b/client/src/js/components/forms/EditActivityFormFields.js @@ -4,12 +4,51 @@ import * as Yup from 'yup'; import moment from 'moment'; import SingleDateField from '../ui/SingleDateField'; +import MultiSelect from '../ui/MultiSelect'; import SingleDropdownField from '../ui/SingleDropdownField'; import PageSpinner from '../ui/PageSpinner'; +import FieldSet from '../ui/FieldSet'; + import { FormRow, FormInput, FormCheckboxInput } from './FormInputs'; import * as api from '../../Api'; import * as Constants from '../../Constants'; +import { Row,Col} from 'reactstrap'; +import { isInteger} from 'lodash'; +import {isValueEmpty,isValueNotEmpty,toStringOrEmpty,toStringWithCommasOrEmpty,isValidDecimal} from '../../utils' + +const tipAnalyticalValidation = [
      +
    • Analytical Validations provide warnings when the activity accomplishment does not meet the defined parameters.
    • +
    • Minimum Value and Maximum Value check the accomplishment for an activity is within numerical limits, as defined. + No tolerances are added to the Minimum Value or Maximum Value calculations.
    • +
    • Reporting Frequency checks if the activity was reported in the same location, with locational specificity based on the activity location code, + within the defined period. A tolerance of 100 metres is added to the start and end points for Location Code C activities to validate against previously + reported instances. No time-based tolerance is added to the Reporting Frequency calculation. Users can manually incorporate into the defined Reporting + Frequency a time-based tolerance (e.g. by setting the minimum number of days to ‘20’ for an activity that should be completed monthly).
    • +
    ]; + +const tipHighwayAttributeValidation = [
      +
    • Highway Attribute Validations provide warnings for Location Code C activities when the features of the reported + location and/or accomplishment do not meet the defined parameters.
    • +
    • Road Length checks the accomplishment against the road length (either Road KM or Lane KM), + or against Guardrail Length [NTD: to confirm Guardrail vs Barrier vernacular based on what types of + guardrail/barrier will be included], as defined in each individual rule. Several rules account for the road length + to be multiplied by one or more factors to accommodate non kilometre-based units of measure. Multiplying factors + include conversion factors (e.g. 1km=1,000m), application rates (e.g. 2.0 litres/m2) or lane width factors to calculate surface area + (e.g. lane width = 3.5m). A 10% tolerance is added to the Total Road KM (to a 200m maximum) and Total Lane KM (to a 500m maximum) + and Barrier Length (to a 200m maximum) for the validation calculations. Point items are calculated with + an estimated Road KM length of 40m (30m as permitted by the Reporting Manual and 10m tolerance), with Lane KM calculated based + on the number of lanes at the point.
    • +
    • Surface Type checks that the location of the record has the appropriate surface type based on the selected rule. + For point items, the surface type must match the point exactly and no tolerance is incorporated. For line items, + a tolerance of 80% is incorporated (i.e. if the rule is “GPS on Paved Surface” and 80% or more of the surface types + within the start and end GPS points are paved, then the record is accepted). Paved surfaces include CHRIS surface types 1-4; + non-paved surfaces include CHRIS surface types 5-6; unconstructed roads have a CHRIS surface type of E or F.
    • +
    • Road Class checks that the location of the record has the appropriate summer or winter road + classifications based on the selected rule. For point items, the classification must match exactly and no tolerance + is incorporated. For line items, a tolerance of 80% is incorporated (i.e. if the rule is “Not Class 8 or F” and 80% or + more of the maintenance class within the start and end GPS points are not 8 or F, then the record is accepted).
    • +
    ]; const defaultValues = { activityNumber: '', @@ -19,7 +58,14 @@ const defaultValues = { locationCodeId: '', featureType: '', spThresholdLevel: '', + minValue: '', + maxValue: '', + reportingFrequency: '', + roadLengthRule: '', + surfaceTypeRule: '', + roadClassRule: '', isSiteNumRequired: false, + serviceAreaNumbers: [], endDate: null, }; @@ -33,8 +79,125 @@ const validationSchema = Yup.object({ unitOfMeasure: Yup.string().required('Required').max(12), maintenanceType: Yup.string().required('Required').max(12), locationCodeId: Yup.number().required('Required'), + serviceAreaNumbers: Yup.array().required('At least one Service Area must be selected'), + minValue: Yup.number() + .transform((_value, originalValue) => { + if(isValueEmpty(originalValue.replace(/,/g, ''))) return null; + return Number(originalValue.replace(/,/g, '')); + }) + .min(0,'Must be greater than or equal to 0') + .nullable() + .typeError('Must be number') + .test( + 'datamin', + function() { + if (isValueEmpty(this.parent.minValue)) + { + return true; + } + if(this.parent.minValue > 999999999.99) + { + return this.createError({ + message: 'Must be less than or equal to 999,999,999.99', + path: 'minValue', + }); + } + if(!isValidDecimal(this.parent.minValue,2)) + { + return this.createError({ + message: 'Must be less than or equal to two decimal positions', + path: 'minValue', + }); + } + if(isValueNotEmpty(this.parent.maxValue)) + { + if(Number(this.parent.maxValue) !== 0 && this.parent.maxValue < this.parent.minValue) + { + return this.createError({ + message: 'Must be less than or equal to the Maximum value', + path: 'minValue', + }); + } + } + if (['site','num','ea'].includes(this.parent.unitOfMeasure)) + { + if(!isInteger(this.parent.minValue)) + { + return this.createError({ + message: 'Must be whole number', + path: 'minValue', + }); + } + } + return true; + } + ), + maxValue: Yup.number() + .transform((_value, originalValue) => { + if(isValueEmpty(originalValue.replace(/,/g, ''))) return null; + return Number(originalValue.replace(/,/g, '')); + }) + .nullable() + .typeError('Must be number') + .test( + 'datamax', + function() { + if (isValueEmpty(this.parent.maxValue)) + { + return true; + } + if(Number(this.parent.maxValue) <=0) + { + return this.createError({ + message: 'Must be greater than 0', + path: 'maxValue', + }); + } + if(Number(this.parent.maxValue) > 999999999.99) + { + return this.createError({ + message: 'Must be less than or equal to 999,999,999.99', + path: 'maxValue', + }); + } + if(!isValidDecimal(this.parent.maxValue,2)) + { + return this.createError({ + message: 'Must be less than or equal to two decimal positions', + path: 'maxValue', + }); + } + + if (isValueNotEmpty(this.parent.minValue)) + { + if(Number(this.parent.maxValue) !== 0 && this.parent.maxValue < this.parent.minValue) + { + return this.createError({ + message: 'Must be greater than or equal to the Minimum value', + path: 'maxValue', + }); + } + } + if (['site','num','ea'].includes(this.parent.unitOfMeasure)) + { + if(!isInteger(this.parent.maxValue)) + { + return this.createError({ + message: 'Must be whole number', + path: 'maxValue', + }); + } + } + return true; + } + ), + reportingFrequency: Yup.number() + .min(0,'Must be greater than or equal to 0') + .max(366,'Must be less than or equal to 366') + .nullable() + .typeError('Must be whole number') + .integer('Must be whole number'), }); - const EditActivityFormFields = ({ setInitialValues, formValues, @@ -46,13 +209,19 @@ const EditActivityFormFields = ({ locationCodes, featureTypes, thresholdLevels, + roadLengthRules, + surfaceTypeRules, + roadClassRules, + serviceAreas, }) => { const [loading, setLoading] = useState(true); const [validLocationCodeValues, setValidLocationCodeValues] = useState(locationCodes); const [disableLocationCodeEdit, setDisableLocationCodeEdit] = useState(false); const [validFeatureTypeValues, setValidFeatureTypeValues] = useState(featureTypes); const locationCodeCId = locationCodes.find((code) => code.name === 'C').id; - + const roadLengthRuleDefaultId = roadLengthRules.find((rlr) => rlr.name === 'Not Applicable').id; + const surfaceTypeRuleDefaultId = surfaceTypeRules.find((str) => str.name === 'Not Applicable').id; + const roadClassRuleDefaultId =roadClassRules.find((rcr) => rcr.name === 'Not Applicable').id; useEffect(() => { // Add validation for point line feature when location code is C. // Need to get the id value of location code C @@ -76,28 +245,32 @@ const EditActivityFormFields = ({ }); setValidationSchema(defaultValidationSchema); - setLoading(true); if (formType === Constants.FORM_TYPE.ADD) { + defaultValues.roadLengthRule = roadLengthRuleDefaultId; + defaultValues.surfaceTypeRule = surfaceTypeRuleDefaultId; + defaultValues.roadClassRule = roadClassRuleDefaultId; setInitialValues(defaultValues); setLoading(false); } else { api.getActivityCode(activityId).then((response) => { setInitialValues({ ...response.data, - endDate: response.data.endDate ? moment(response.data.endDate) : null, + endDate: response.data.endDate ? moment(response.data.endDate): null, + minValue: toStringWithCommasOrEmpty(response.data.minValue), + maxValue: toStringWithCommasOrEmpty(response.data.maxValue), + reportingFrequency: toStringOrEmpty(response.data.reportingFrequency), }); - + setValidLocationCodeValues(() => { if (formType === Constants.FORM_TYPE.EDIT) { if (response.data.locationCodeId === locationCodes.find((code) => code.name === 'B').id) return locationCodes.filter((location) => location.name !== 'C'); } - return locationCodes; }); - + setDisableLocationCodeEdit(() => { if (formType === Constants.FORM_TYPE.EDIT) { if (response.data.locationCodeId === locationCodes.find((code) => code.name === 'A').id) return true; @@ -117,7 +290,6 @@ const EditActivityFormFields = ({ (feature) => feature.id === pointLineType || feature.id === response.data.featureType ); } - return featureTypes; }); @@ -129,64 +301,133 @@ const EditActivityFormFields = ({ }, []); if (loading || formValues === null) return ; - + return ( - - - - - - - - - - - - - - - - {formValues.locationCodeId === locationCodeCId && ( - - - + + + + + + + + + + + + + + + + - + + + - - + + + + + + + + + - - )} - - - + + +
    + + + + + + + + + +
    + + + {formValues.locationCodeId === locationCodeCId && ( + + + + + + + + + + + + + + +
    + + + + + + + + + +
    + +
    + +
    + )} + + + + + + + + + +
    ); }; @@ -198,6 +439,13 @@ const mapStateToProps = (state) => { locationCodes: state.codeLookups.locationCodes, featureTypes: state.codeLookups.featureTypes, thresholdLevels: state.codeLookups.thresholdLevels, + roadLengthRules: state.codeLookups.roadLengthRules, + surfaceTypeRules: state.codeLookups.surfaceTypeRules, + roadClassRules: state.codeLookups.roadClassRules, + serviceAreas: Object.values(state.serviceAreas), + minValue: state.codeLookups.minValue, + maxValue: state.codeLookups.maxValue, + reportingFrequency: state.codeLookups.reportingFrequency, }; }; diff --git a/client/src/js/components/hooks/useFormModal.js b/client/src/js/components/hooks/useFormModal.js index e18362de..5d76331e 100644 --- a/client/src/js/components/hooks/useFormModal.js +++ b/client/src/js/components/hooks/useFormModal.js @@ -6,7 +6,7 @@ import SubmitButton from '../ui/SubmitButton'; import * as Constants from '../../Constants'; -const useFormModal = (formTitle, formFieldsChildElement, handleFormSubmit) => { +const useFormModal = (formTitle, formFieldsChildElement, handleFormSubmit,modSize) => { // This is needed until Formik fixes its own setSubmitting function const [submitting, setSubmitting] = useState(false); const [initialValues, setInitialValues] = useState(null); @@ -31,10 +31,10 @@ const useFormModal = (formTitle, formFieldsChildElement, handleFormSubmit) => { const onFormSubmit = (values) => handleFormSubmit(values, formType); const title = formType === Constants.FORM_TYPE.ADD ? `Add ${formTitle}` : `Edit ${formTitle}`; - + modSize = (modSize===null )?'sm':modSize; const formModal = () => { return ( - + {title} { + const { legendname,children,targetId,tips } = props; + const tipId = (targetId===undefined||targetId===null||targetId==='')?'TooltipForFieldsetId':targetId; + const [tooltipOpen, setTooltipOpen] = useState(false); + const toggle = () => setTooltipOpen(!tooltipOpen); + return ( +
    + {legendname} + + + +
    {tips}
    +
    + {children} +
    + ); +} +export default FieldSet; \ No newline at end of file diff --git a/client/src/js/components/ui/MouseoverTooltip.js b/client/src/js/components/ui/MouseoverTooltip.js index 6a151970..cfeae4a6 100644 --- a/client/src/js/components/ui/MouseoverTooltip.js +++ b/client/src/js/components/ui/MouseoverTooltip.js @@ -10,7 +10,7 @@ const MouseoverTooltip = (props) => { setIsOpen(true)} onMouseOut={() => setIsOpen(false)} style={{ cursor: 'pointer' }} diff --git a/client/src/js/components/ui/MultiSelect.js b/client/src/js/components/ui/MultiSelect.js index ddbdf49c..6f8d6aac 100644 --- a/client/src/js/components/ui/MultiSelect.js +++ b/client/src/js/components/ui/MultiSelect.js @@ -3,12 +3,14 @@ import { CustomInput, FormFeedback } from 'reactstrap'; import { FieldArray, useField, useFormikContext } from 'formik'; const MultiSelect = (props) => { - const { items, name, handleBlur, showSelectAll } = props; + const { items, name, handleBlur, showSelectAll,selectClass } = props; // eslint-disable-next-line const [field, meta] = useField(props); + const selectClassName= (selectClass===null ||selectClass===undefined||selectClass==='')?"form-control multi-select":selectClass; + const { values, setFieldValue } = useFormikContext(); const selectedValues = values[name]; - + const [selectAll, setSelectAll] = useState(false); const handleItemSelected = (checked, itemId, push, remove) => { @@ -38,7 +40,7 @@ const MultiSelect = (props) => { return (
    diff --git a/client/src/js/reducers/codeLookupsReducer.js b/client/src/js/reducers/codeLookupsReducer.js index 26b4c98b..a052e603 100644 --- a/client/src/js/reducers/codeLookupsReducer.js +++ b/client/src/js/reducers/codeLookupsReducer.js @@ -7,6 +7,9 @@ import { FETCH_LOCATION_CODES, FETCH_ACTIVITY_CODES_DROPDOWN, FETCH_THRESHOLD_LEVELS, + FETCH_ROAD_LENGTH_RULES, + FETCH_SURFACE_TYPE_RULES, + FETCH_ROAD_CLASS_RULES } from '../actions/types'; const defaultState = { @@ -16,6 +19,9 @@ const defaultState = { locationCodes: [], activityCodes: [], thresholdLevels: [], + roadLengthRules: [], + surfaceTypeRules: [], + roadClassRules: [], }; export default (state = defaultState, action) => { @@ -32,6 +38,12 @@ export default (state = defaultState, action) => { return { ...state, activityCodes: action.payload }; case FETCH_THRESHOLD_LEVELS: return { ...state, thresholdLevels: action.payload }; + case FETCH_ROAD_LENGTH_RULES: + return { ...state, roadLengthRules: _.orderBy(action.payload, ['displayOrder']) }; + case FETCH_SURFACE_TYPE_RULES: + return { ...state, surfaceTypeRules: _.orderBy(action.payload, ['displayOrder']) }; + case FETCH_ROAD_CLASS_RULES: + return { ...state, roadClassRules: _.orderBy(action.payload, ['displayOrder']) }; default: return state; } diff --git a/client/src/js/utils.js b/client/src/js/utils.js index 8e19c4dd..37c86786 100644 --- a/client/src/js/utils.js +++ b/client/src/js/utils.js @@ -60,3 +60,40 @@ export const buildStatusIdArray = (isActive) => { return [Constants.ACTIVE_STATUS.ACTIVE, Constants.ACTIVE_STATUS.INACTIVE]; }; + +export const isValueEmpty=(v)=>{ + if(v === null || v === undefined || v === '') return true; + return false; +}; + +export const isValueNotEmpty=(v)=>{ + if(v !== null && v !== undefined && v !== '') return true; + return false; +}; + +export const toNumberOrNull=(v)=>{ + return isValueNotEmpty(removeStringCommas(v)) ? _.toNumber(removeStringCommas(v)): null; +}; +export const toStringOrEmpty=(v)=>{ + return isValueNotEmpty(v) ? _.toString(v): ''; +}; +export const toStringWithCommasOrEmpty=(v)=>{ + return isValueNotEmpty(v) ? _.toString(addCommasToNumber(v)): ''; +}; +export const removeStringCommas=(v)=>{ + return v.toString().replace(/,/g, ''); +} +export const addCommasToNumber=(n) =>{ + if(isValueEmpty(n)) return n; + let s = removeStringCommas(n).split('.'); + if (s[0].length >= 4) s[0] = s[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,'); + return s.join('.'); +} +export const isValidDecimal=(v,digits) =>{ + if(isValueEmpty(v)) return true; + const d = _.toInteger(digits); + let s = Number(removeStringCommas(v)).toString().split('.'); + if(s.length <2) return true; + if (s[1].length <= d) return true; + return false; +} diff --git a/client/src/scss/_forms.scss b/client/src/scss/_forms.scss index 406c975b..533d2d1e 100644 --- a/client/src/scss/_forms.scss +++ b/client/src/scss/_forms.scss @@ -29,3 +29,57 @@ overflow: hidden; } } + +.form-control.fieldset{ + border: 1px solid; + padding: 0.375rem 0.75rem; + height: auto; + margin-bottom: 2.25rem; +} +.form-control.legend{ + border: none; + width: auto; +} +.col.colmargin1{ + margin-top:1.25rem +} +.form-control.servicearea-large { + background-color: #fff; + background-clip: padding-box; + border: 1px solid #ced4da; + border-radius: 0.25rem; + height: unset; + max-height: 174px; + overflow-y: auto; + padding: 0.375rem 0.75rem; +} +.form-control.servicearea-large.is-invalid { + border-color: #d93e45; +} +.fieldset-tooltip [class$="inner"] { + padding:0.5rem 0.75rem; + background-color: #fff; + border: 1px solid #737373; + color:black; + max-width: 400px; + height: 160px; + font-size: 0.875rem; + font-weight: 400; + text-align: left; + text-decoration: none; + word-spacing: normal; + word-break: normal; + white-space: normal; + background-clip: padding-box; + border: 1px solid rgba(0,0,0,.2); + box-shadow: 0 1px 3px rgba(0,0,0,.12), 0 1px 2px rgba(0,0,0,.24); +} + +.fieldset-tooltip> div.show { + opacity: 1; +} +.fieldset-tooltip-body { + overflow-y: auto; + max-width: 380px; + height: 140px; +} \ No newline at end of file diff --git a/database/V24.0/1_HMR_PDM-ddl_ALTER_APP_HMR_V24_IS2.1.sql b/database/V24.0/1_HMR_PDM-ddl_ALTER_APP_HMR_V24_IS2.1.sql new file mode 100644 index 00000000..fd131e80 --- /dev/null +++ b/database/V24.0/1_HMR_PDM-ddl_ALTER_APP_HMR_V24_IS2.1.sql @@ -0,0 +1,651 @@ +-- Script generated by Aqua Data Studio Schema Synchronization for MS SQL Server 2016 on Wed Oct 07 16:12:21 PDT 2020 +-- Execute this script on: +-- HMR_DEV/dbo - This database/schema will be modified +-- to synchronize it with MS SQL Server 2016: +-- HMR V24.0/dbo + +-- We recommend backing up the database prior to executing the script. +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +SET XACT_ABORT ON +GO +SET TRANSACTION ISOLATION LEVEL SERIALIZABLE +GO +BEGIN TRANSACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_ACT_CODE_A_S_IUD_TR +PRINT N'Drop trigger dbo.HMR_ACT_CODE_A_S_IUD_TR' +GO +DROP TRIGGER [dbo].[HMR_ACT_CODE_A_S_IUD_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_ACT_CODE_I_S_I_TR +PRINT N'Drop trigger dbo.HMR_ACT_CODE_I_S_I_TR' +GO +DROP TRIGGER [dbo].[HMR_ACT_CODE_I_S_I_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_ACT_CODE_I_S_U_TR +PRINT N'Drop trigger dbo.HMR_ACT_CODE_I_S_U_TR' +GO +DROP TRIGGER [dbo].[HMR_ACT_CODE_I_S_U_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop view dbo.HMR_WILDLIFE_REPORT_VW +PRINT N'Drop view dbo.HMR_WILDLIFE_REPORT_VW' +GO +DROP VIEW [dbo].[HMR_WILDLIFE_REPORT_VW] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop view dbo.HMR_ROCKFALL_REPORT_VW +PRINT N'Drop view dbo.HMR_ROCKFALL_REPORT_VW' +GO +DROP VIEW [dbo].[HMR_ROCKFALL_REPORT_VW] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop view dbo.HMR_WORK_REPORT_VW +PRINT N'Drop view dbo.HMR_WORK_REPORT_VW' +GO +DROP VIEW [dbo].[HMR_WORK_REPORT_VW] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop procedure dbo.hmr_error_handling +PRINT N'Drop procedure dbo.hmr_error_handling' +GO +DROP PROCEDURE [dbo].[hmr_error_handling] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create sequence dbo.HMR_ACTIVITY_RULE_CODE_ID_SEQ +PRINT N'Create sequence dbo.HMR_ACTIVITY_RULE_CODE_ID_SEQ' +GO +CREATE SEQUENCE [dbo].[HMR_ACTIVITY_RULE_CODE_ID_SEQ] + AS bigint + START WITH 1 + INCREMENT BY 1 + MINVALUE 1 + MAXVALUE 999999999 + NO CYCLE + CACHE 50 +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create table dbo.HMRX_TableDefinitions +PRINT N'Create table dbo.HMRX_TableDefinitions' +GO +CREATE TABLE [dbo].[HMRX_TableDefinitions] ( + [TABLE_NAME] nvarchar(255) NULL, + [TABLE_ALIAS] nvarchar(255) NULL, + [HIST] nvarchar(1) NULL, + [DESCRIPTION] nvarchar(max) NULL + ) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create sequence dbo.HMR_ACTIVITY_RULE_ID_SEQ +PRINT N'Create sequence dbo.HMR_ACTIVITY_RULE_ID_SEQ' +GO +CREATE SEQUENCE [dbo].[HMR_ACTIVITY_RULE_ID_SEQ] + AS bigint + START WITH 1 + INCREMENT BY 1 + MINVALUE 1 + MAXVALUE 999999999 + NO CYCLE + CACHE 50 +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create procedure dbo.hmr_error_handling +PRINT N'Create procedure dbo.hmr_error_handling' +GO +/* ---------------------------------------------------------------------- */ +/* Add procedures */ +/* ---------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- */ +/* Add procedures */ +/* ---------------------------------------------------------------------- */ + +CREATE PROCEDURE [dbo].[hmr_error_handling] AS + + begin + DECLARE @errmsg nvarchar(2048), + @severity tinyint, + @state tinyint, + @errno int, + @proc sysname, + @lineno int + + SELECT @errmsg = error_message(), @severity = error_severity(), + @state = error_state(), @errno = error_number(), + @proc = error_procedure(), @lineno = error_line() + + IF @errmsg NOT LIKE '***%' + BEGIN + SELECT @errmsg = '*** ' + coalesce(quotename(@proc), '') + + ', Line ' + ltrim(str(@lineno)) + '. Errno ' + + ltrim(str(@errno)) + ': ' + @errmsg + END + + RAISERROR('%s', @severity, @state, @errmsg) + end +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create sequence dbo.HMR_ACTIVITY_CODE_RULE_ID_SEQ +PRINT N'Create sequence dbo.HMR_ACTIVITY_CODE_RULE_ID_SEQ' +GO +CREATE SEQUENCE [dbo].[HMR_ACTIVITY_CODE_RULE_ID_SEQ] + AS bigint + START WITH 1 + INCREMENT BY 1 + MINVALUE 1 + MAXVALUE 999999999 + NO CYCLE + CACHE 50 +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create table dbo.HMR_ACTIVITY_CODE_RULE +PRINT N'Create table dbo.HMR_ACTIVITY_CODE_RULE' +GO +CREATE TABLE [dbo].[HMR_ACTIVITY_CODE_RULE] ( + [ACTIVITY_CODE_RULE_ID] numeric(9,0) NOT NULL DEFAULT (NEXT VALUE FOR [HMR_ACTIVITY_CODE_RULE_ID_SEQ]), + [ACTIVITY_RULE_SET] varchar(20) NOT NULL, + [ACTIVITY_RULE_NAME] nvarchar(150) NOT NULL, + [ACTIVITY_RULE_EXEC_NAME] varchar(150) NOT NULL, + [DISPLAY_ORDER] numeric(3,0) NULL, + [END_DATE] datetime NULL DEFAULT (getutcdate()), + [CONCURRENCY_CONTROL_NUMBER] bigint NOT NULL DEFAULT ((1)), + [DB_AUDIT_CREATE_USERID] varchar(30) NOT NULL DEFAULT (user_name()), + [DB_AUDIT_CREATE_TIMESTAMP] datetime NOT NULL DEFAULT (getutcdate()), + [DB_AUDIT_LAST_UPDATE_USERID] varchar(30) NOT NULL DEFAULT (user_name()), + [DB_AUDIT_LAST_UPDATE_TIMESTAMP] datetime NOT NULL DEFAULT (getutcdate()), + PRIMARY KEY CLUSTERED([ACTIVITY_CODE_RULE_ID]) + ON [PRIMARY]) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Alter table dbo.HMR_ACTIVITY_CODE +PRINT N'Alter table dbo.HMR_ACTIVITY_CODE' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD [ROAD_CLASS_RULE] numeric(9,0) NOT NULL DEFAULT ((0)), + [ROAD_LENGTH_RULE] numeric(9,0) NOT NULL DEFAULT ((0)), + [SURFACE_TYPE_RULE] numeric(9,0) NOT NULL DEFAULT ((0)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Alter table dbo.HMR_ACTIVITY_CODE_HIST +PRINT N'Alter table dbo.HMR_ACTIVITY_CODE_HIST' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE_HIST] + ADD [ROAD_CLASS_RULE] numeric(9,0) NOT NULL DEFAULT ((0)), + [ROAD_LENGTH_RULE] numeric(9,0) NOT NULL DEFAULT ((0)), + [SURFACE_TYPE_RULE] numeric(9,0) NOT NULL DEFAULT ((0)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create view dbo.HMR_WORK_REPORT_VW +PRINT N'Create view dbo.HMR_WORK_REPORT_VW' +GO +/* ---------------------------------------------------------------------- */ +/* Add views */ +/* ---------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- */ +/* Add views */ +/* ---------------------------------------------------------------------- */ + +/* Update 23/04/2020 + +i) Added spatial warning thresholds + +*/ + + +CREATE VIEW [dbo].[HMR_WORK_REPORT_VW] AS + SELECT + wrkrpt.WORK_REPORT_ID + ,'WORK_REPORT' AS REPORT_TYPE + ,wrkrpt.RECORD_TYPE + ,CAST(wrkrpt.[SERVICE_AREA] AS numeric) AS SERVICE_AREA + ,wrkrpt.RECORD_NUMBER + ,wrkrpt.TASK_NUMBER + ,wrkrpt.ACTIVITY_NUMBER + ,actcode.ACTIVITY_NAME + ,wrkrpt.START_DATE + ,wrkrpt.END_DATE + ,wrkrpt.ACCOMPLISHMENT + ,wrkrpt.UNIT_OF_MEASURE + ,wrkrpt.POSTED_DATE + ,wrkrpt.HIGHWAY_UNIQUE + ,wrkrpt.HIGHWAY_UNIQUE_NAME + ,wrkrpt.HIGHWAY_UNIQUE_LENGTH + ,wrkrpt.LANDMARK + ,wrkrpt.START_OFFSET + ,wrkrpt.END_OFFSET + ,wrkrpt.START_LATITUDE + ,wrkrpt.START_LONGITUDE + ,subm_rw.START_VARIANCE + ,wrkrpt.END_LATITUDE + ,wrkrpt.END_LONGITUDE + ,subm_rw.END_VARIANCE + ,subm_rw.WARNING_SP_THRESHOLD + ,wrkrpt.WORK_LENGTH + ,CASE + WHEN ISNULL(subm_rw.START_VARIANCE,0) > ISNULL(subm_rw.WARNING_SP_THRESHOLD,0) + OR ISNULL(subm_rw.END_VARIANCE,0) > ISNULL(subm_rw.WARNING_SP_THRESHOLD,0) + THEN 'Y' ELSE 'N' + END IS_OVER_SP_THRESHOLD + ,wrkrpt.STRUCTURE_NUMBER + ,wrkrpt.SITE_NUMBER + ,wrkrpt.VALUE_OF_WORK + ,wrkrpt.COMMENTS + ,wrkrpt.GEOMETRY + ,wrkrpt.SUBMISSION_OBJECT_ID + ,CAST(subm_obj.[FILE_NAME] AS varchar) AS FILE_NAME + ,wrkrpt.ROW_NUM + ,CAST(subm_stat.[STATUS_CODE] + ' - ' + subm_stat.[DESCRIPTION] AS varchar) AS VALIDATION_STATUS + ,CAST(wrkrpt.APP_CREATE_TIMESTAMP AS datetime) AS APP_CREATE_TIMESTAMP_UTC + ,CAST(wrkrpt.APP_LAST_UPDATE_TIMESTAMP AS datetime) AS APP_LAST_UPDATE_TIMESTAMP_UTC + FROM HMR_WORK_REPORT wrkrpt + INNER JOIN HMR_SUBMISSION_OBJECT subm_obj ON wrkrpt.SUBMISSION_OBJECT_ID = subm_obj.SUBMISSION_OBJECT_ID + LEFT OUTER JOIN HMR_ACTIVITY_CODE actcode ON wrkrpt.ACTIVITY_NUMBER = actcode.ACTIVITY_NUMBER + LEFT OUTER JOIN HMR_SUBMISSION_ROW subm_rw ON wrkrpt.ROW_ID = subm_rw.ROW_ID + LEFT OUTER JOIN HMR_SUBMISSION_STATUS subm_stat ON subm_rw.ROW_STATUS_ID = subm_stat.STATUS_ID +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create view dbo.HMR_ROCKFALL_REPORT_VW +PRINT N'Create view dbo.HMR_ROCKFALL_REPORT_VW' +GO +/* Update 23/04/2020 + +i) Added spatial warning thresholds + +*/ + + +CREATE VIEW [dbo].[HMR_ROCKFALL_REPORT_VW] AS +SELECT + rckflrpt.[ROCKFALL_REPORT_ID] + ,'ROCKFALL_REPORT' AS REPORT_TYPE + ,CAST(rckflrpt.[RECORD_TYPE] AS varchar) AS RECORD_TYPE + ,CAST(rckflrpt.[SERVICE_AREA] AS numeric) AS SERVICE_AREA + ,rckflrpt.[MCRR_INCIDENT_NUMBER] + ,rckflrpt.[ESTIMATED_ROCKFALL_DATE] + ,rckflrpt.[ESTIMATED_ROCKFALL_TIME] + ,rckflrpt.[START_LATITUDE] + ,rckflrpt.[START_LONGITUDE] + ,subm_rw.[START_VARIANCE] + ,rckflrpt.[END_LATITUDE] + ,rckflrpt.[END_LONGITUDE] + ,subm_rw.[END_VARIANCE] + ,subm_rw.[WARNING_SP_THRESHOLD] + ,CASE + WHEN ISNULL(subm_rw.START_VARIANCE,0) > ISNULL(subm_rw.WARNING_SP_THRESHOLD,0) + OR ISNULL(subm_rw.END_VARIANCE,0) > ISNULL(subm_rw.WARNING_SP_THRESHOLD,0) + THEN 'Y' ELSE 'N' + END IS_OVER_SP_THRESHOLD + ,rckflrpt.[HIGHWAY_UNIQUE] + ,rckflrpt.[HIGHWAY_UNIQUE_NAME] + ,rckflrpt.[HIGHWAY_UNIQUE_LENGTH] + ,rckflrpt.[LANDMARK] + ,rckflrpt.[LANDMARK_NAME] + ,rckflrpt.[START_OFFSET] + ,rckflrpt.[END_OFFSET] + ,rckflrpt.[DIRECTION_FROM_LANDMARK] + ,rckflrpt.[LOCATION_DESCRIPTION] + ,rckflrpt.[TRAVELLED_LANES_VOLUME] + ,rckflrpt.[OTHER_TRAVELLED_LANES_VOLUME] + ,rckflrpt.[DITCH_VOLUME] + ,rckflrpt.[OTHER_DITCH_VOLUME] + ,rckflrpt.[HEAVY_PRECIP] + ,rckflrpt.[FREEZE_THAW] + ,rckflrpt.[DITCH_SNOW_ICE] + ,rckflrpt.[VEHICLE_DAMAGE] + ,rckflrpt.[COMMENTS] + ,rckflrpt.[REPORTER_NAME] + ,rckflrpt.[MC_PHONE_NUMBER] + ,usr.[BUSINESS_LEGAL_NAME] AS MC_NAME + ,rckflrpt.[REPORT_DATE] + ,rckflrpt.[GEOMETRY] + ,rckflrpt.SUBMISSION_OBJECT_ID + ,CAST(subm_obj.[FILE_NAME] AS varchar) AS FILE_NAME + ,rckflrpt.[ROW_NUM] + ,CAST(subm_stat.[STATUS_CODE] + ' - ' + subm_stat.[DESCRIPTION] AS varchar) AS VALIDATION_STATUS + ,CAST(rckflrpt.APP_CREATE_TIMESTAMP AS datetime) AS APP_CREATE_TIMESTAMP_UTC + ,CAST(rckflrpt.APP_LAST_UPDATE_TIMESTAMP AS datetime) AS APP_LAST_UPDATE_TIMESTAMP_UTC + FROM HMR_ROCKFALL_REPORT rckflrpt + INNER JOIN HMR_SUBMISSION_OBJECT subm_obj ON rckflrpt.SUBMISSION_OBJECT_ID = subm_obj.SUBMISSION_OBJECT_ID + LEFT OUTER JOIN HMR_SUBMISSION_ROW subm_rw ON rckflrpt.ROW_ID = subm_rw.ROW_ID + LEFT OUTER JOIN HMR_SUBMISSION_STATUS subm_stat ON subm_rw.ROW_STATUS_ID = subm_stat.STATUS_ID + LEFT OUTER JOIN HMR_SYSTEM_USER usr ON rckflrpt.APP_CREATE_USER_GUID = usr.APP_CREATE_USER_GUID +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create view dbo.HMR_WILDLIFE_REPORT_VW +PRINT N'Create view dbo.HMR_WILDLIFE_REPORT_VW' +GO +/* Update 23/04/2020 + +i) Added spatial warning thresholds + +*/ + +CREATE VIEW [dbo].[HMR_WILDLIFE_REPORT_VW] AS + SELECT + wldlfrpt.[WILDLIFE_RECORD_ID] + ,'WILDLIFE_REPORT' AS REPORT_TYPE + ,wldlfrpt.[RECORD_TYPE] + ,CAST(wldlfrpt.[SERVICE_AREA] AS numeric) AS SERVICE_AREA + ,wldlfrpt.[ACCIDENT_DATE] + ,wldlfrpt.[TIME_OF_KILL] + ,wldlfrpt.[LATITUDE] + ,wldlfrpt.[LONGITUDE] + ,subm_rw.[START_VARIANCE] AS SPATIAL_VARIANCE + ,subm_rw.[WARNING_SP_THRESHOLD] + ,CASE + WHEN ISNULL(subm_rw.START_VARIANCE,0) > ISNULL(subm_rw.WARNING_SP_THRESHOLD,0) + OR ISNULL(subm_rw.END_VARIANCE,0) > ISNULL(subm_rw.WARNING_SP_THRESHOLD,0) + THEN 'Y' ELSE 'N' + END IS_OVER_SP_THRESHOLD + ,wldlfrpt.[HIGHWAY_UNIQUE] + ,wldlfrpt.[HIGHWAY_UNIQUE_NAME] + ,wldlfrpt.[HIGHWAY_UNIQUE_LENGTH] + ,wldlfrpt.[LANDMARK] + ,wldlfrpt.[OFFSET] + ,wldlfrpt.[NEAREST_TOWN] + ,wldlfrpt.[WILDLIFE_SIGN] + ,wldlfrpt.[QUANTITY] + ,wldlfrpt.[SPECIES] + ,wldlfrpt.[SEX] + ,wldlfrpt.[AGE] + ,wldlfrpt.[COMMENT] + ,wldlfrpt.[GEOMETRY] + ,CAST(wldlfrpt.[SUBMISSION_OBJECT_ID] AS numeric) AS SUBMISSION_OBJECT_ID + ,CAST(subm_obj.[FILE_NAME] AS varchar) AS FILE_NAME + ,wldlfrpt.[ROW_NUM] + ,CAST(subm_stat.[STATUS_CODE] + ' - ' + subm_stat.[DESCRIPTION] AS varchar) AS VALIDATION_STATUS + ,CAST(wldlfrpt.APP_CREATE_TIMESTAMP AS datetime) AS APP_CREATE_TIMESTAMP_UTC + ,CAST(wldlfrpt.APP_LAST_UPDATE_TIMESTAMP AS datetime) AS APP_LAST_UPDATE_TIMESTAMP_UTC + FROM [dbo].[HMR_WILDLIFE_REPORT] wldlfrpt + INNER JOIN HMR_SUBMISSION_OBJECT subm_obj ON wldlfrpt.SUBMISSION_OBJECT_ID = subm_obj.SUBMISSION_OBJECT_ID + LEFT OUTER JOIN HMR_SUBMISSION_ROW subm_rw ON wldlfrpt.ROW_ID = subm_rw.ROW_ID + LEFT OUTER JOIN HMR_SUBMISSION_STATUS subm_stat ON subm_rw.ROW_STATUS_ID = subm_stat.STATUS_ID +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CODE_I_S_U_TR +PRINT N'Create trigger dbo.HMR_ACT_CODE_I_S_U_TR' +GO +CREATE TRIGGER [dbo].[HMR_ACT_CODE_I_S_U_TR] ON HMR_ACTIVITY_CODE INSTEAD OF UPDATE AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- validate concurrency control + if exists (select 1 from inserted, deleted where inserted.CONCURRENCY_CONTROL_NUMBER != deleted.CONCURRENCY_CONTROL_NUMBER+1 AND inserted.ACTIVITY_CODE_ID = deleted.ACTIVITY_CODE_ID) + raiserror('CONCURRENCY FAILURE.',16,1) + + + -- update statement + update HMR_ACTIVITY_CODE + set "ACTIVITY_CODE_ID" = inserted."ACTIVITY_CODE_ID", + "ACTIVITY_NUMBER" = inserted."ACTIVITY_NUMBER", + "ACTIVITY_NAME" = inserted."ACTIVITY_NAME", + "UNIT_OF_MEASURE" = inserted."UNIT_OF_MEASURE", + "MAINTENANCE_TYPE" = inserted."MAINTENANCE_TYPE", + "LOCATION_CODE_ID" = inserted."LOCATION_CODE_ID", + "FEATURE_TYPE" = inserted."FEATURE_TYPE", + "SP_THRESHOLD_LEVEL" = inserted."SP_THRESHOLD_LEVEL", + "IS_SITE_NUM_REQUIRED" = inserted."IS_SITE_NUM_REQUIRED", + "ACTIVITY_APPLICATION" = inserted."ACTIVITY_APPLICATION", + "END_DATE" = inserted."END_DATE", + "ROAD_CLASS_RULE" = inserted."ROAD_CLASS_RULE", + "ROAD_LENGTH_RULE" = inserted."ROAD_LENGTH_RULE", + "SURFACE_TYPE_RULE" = inserted."SURFACE_TYPE_RULE", + "CONCURRENCY_CONTROL_NUMBER" = inserted."CONCURRENCY_CONTROL_NUMBER", + "APP_LAST_UPDATE_USERID" = inserted."APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP" = inserted."APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID" = inserted."APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY" = inserted."APP_LAST_UPDATE_USER_DIRECTORY" + , DB_AUDIT_LAST_UPDATE_TIMESTAMP = getutcdate() + , DB_AUDIT_LAST_UPDATE_USERID = user_name() + from HMR_ACTIVITY_CODE + inner join inserted + on (HMR_ACTIVITY_CODE.ACTIVITY_CODE_ID = inserted.ACTIVITY_CODE_ID); + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CODE_I_S_I_TR +PRINT N'Create trigger dbo.HMR_ACT_CODE_I_S_I_TR' +GO +CREATE TRIGGER [dbo].[HMR_ACT_CODE_I_S_I_TR] ON HMR_ACTIVITY_CODE INSTEAD OF INSERT AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM inserted) + RETURN; + + + insert into HMR_ACTIVITY_CODE ("ACTIVITY_CODE_ID", + "ACTIVITY_NUMBER", + "ACTIVITY_NAME", + "UNIT_OF_MEASURE", + "MAINTENANCE_TYPE", + "LOCATION_CODE_ID", + "FEATURE_TYPE", + "SP_THRESHOLD_LEVEL", + "IS_SITE_NUM_REQUIRED", + "ACTIVITY_APPLICATION", + "END_DATE", + "ROAD_CLASS_RULE", + "ROAD_LENGTH_RULE", + "SURFACE_TYPE_RULE", + "CONCURRENCY_CONTROL_NUMBER", + "APP_CREATE_USERID", + "APP_CREATE_TIMESTAMP", + "APP_CREATE_USER_GUID", + "APP_CREATE_USER_DIRECTORY", + "APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY") + select "ACTIVITY_CODE_ID", + "ACTIVITY_NUMBER", + "ACTIVITY_NAME", + "UNIT_OF_MEASURE", + "MAINTENANCE_TYPE", + "LOCATION_CODE_ID", + "FEATURE_TYPE", + "SP_THRESHOLD_LEVEL", + "IS_SITE_NUM_REQUIRED", + "ACTIVITY_APPLICATION", + "END_DATE", + "ROAD_CLASS_RULE", + "ROAD_LENGTH_RULE", + "SURFACE_TYPE_RULE", + "CONCURRENCY_CONTROL_NUMBER", + "APP_CREATE_USERID", + "APP_CREATE_TIMESTAMP", + "APP_CREATE_USER_GUID", + "APP_CREATE_USER_DIRECTORY", + "APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY" + from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CODE_A_S_IUD_TR +PRINT N'Create trigger dbo.HMR_ACT_CODE_A_S_IUD_TR' +GO +/* ---------------------------------------------------------------------- */ +/* Add triggers */ +/* ---------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- */ +/* Add triggers */ +/* ---------------------------------------------------------------------- */ + +CREATE TRIGGER [dbo].[HMR_ACT_CODE_A_S_IUD_TR] ON HMR_ACTIVITY_CODE FOR INSERT, UPDATE, DELETE AS +SET NOCOUNT ON +BEGIN TRY +DECLARE @curr_date datetime; +SET @curr_date = getutcdate(); + IF NOT EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- historical + IF EXISTS(SELECT * FROM deleted) + update HMR_ACTIVITY_CODE_HIST set END_DATE_HIST = @curr_date where ACTIVITY_CODE_ID in (select ACTIVITY_CODE_ID from deleted) and END_DATE_HIST is null; + + IF EXISTS(SELECT * FROM inserted) + insert into HMR_ACTIVITY_CODE_HIST ([ACTIVITY_CODE_ID], [ACTIVITY_NUMBER], [ACTIVITY_NAME], [UNIT_OF_MEASURE], [MAINTENANCE_TYPE], [LOCATION_CODE_ID], [FEATURE_TYPE], [SP_THRESHOLD_LEVEL], [IS_SITE_NUM_REQUIRED], [ACTIVITY_APPLICATION], [END_DATE], [ROAD_CLASS_RULE], [ROAD_LENGTH_RULE], [SURFACE_TYPE_RULE], [CONCURRENCY_CONTROL_NUMBER], [APP_CREATE_USERID], [APP_CREATE_TIMESTAMP], [APP_CREATE_USER_GUID], [APP_CREATE_USER_DIRECTORY], [APP_LAST_UPDATE_USERID], [APP_LAST_UPDATE_TIMESTAMP], [APP_LAST_UPDATE_USER_GUID], [APP_LAST_UPDATE_USER_DIRECTORY], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], ACTIVITY_CODE_HIST_ID, END_DATE_HIST, EFFECTIVE_DATE_HIST) + select [ACTIVITY_CODE_ID], [ACTIVITY_NUMBER], [ACTIVITY_NAME], [UNIT_OF_MEASURE], [MAINTENANCE_TYPE], [LOCATION_CODE_ID], [FEATURE_TYPE], [SP_THRESHOLD_LEVEL], [IS_SITE_NUM_REQUIRED], [ACTIVITY_APPLICATION], [END_DATE], [ROAD_CLASS_RULE], [ROAD_LENGTH_RULE], [SURFACE_TYPE_RULE], [CONCURRENCY_CONTROL_NUMBER], [APP_CREATE_USERID], [APP_CREATE_TIMESTAMP], [APP_CREATE_USER_GUID], [APP_CREATE_USER_DIRECTORY], [APP_LAST_UPDATE_USERID], [APP_LAST_UPDATE_TIMESTAMP], [APP_LAST_UPDATE_USER_GUID], [APP_LAST_UPDATE_USER_DIRECTORY], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], (next value for [dbo].[HMR_ACTIVITY_CODE_H_ID_SEQ]) as [ACTIVITY_CODE_HIST_ID], null as [END_DATE_HIST], @curr_date as [EFFECTIVE_DATE_HIST] from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CD_RL_I_S_U_TR +PRINT N'Create trigger dbo.HMR_ACT_CD_RL_I_S_U_TR' +GO +CREATE TRIGGER [dbo].[HMR_ACT_CD_RL_I_S_U_TR] ON HMR_ACTIVITY_CODE_RULE INSTEAD OF UPDATE AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- validate concurrency control + if exists (select 1 from inserted, deleted where inserted.CONCURRENCY_CONTROL_NUMBER != deleted.CONCURRENCY_CONTROL_NUMBER+1 AND inserted.ACTIVITY_CODE_RULE_ID = deleted.ACTIVITY_CODE_RULE_ID) + raiserror('CONCURRENCY FAILURE.',16,1) + + + -- update statement + update HMR_ACTIVITY_CODE_RULE + set "ACTIVITY_CODE_RULE_ID" = inserted."ACTIVITY_CODE_RULE_ID", + "ACTIVITY_RULE_SET" = inserted."ACTIVITY_RULE_SET", + "ACTIVITY_RULE_NAME" = inserted."ACTIVITY_RULE_NAME", + "ACTIVITY_RULE_EXEC_NAME" = inserted."ACTIVITY_RULE_EXEC_NAME", + "DISPLAY_ORDER" = inserted."DISPLAY_ORDER", + "END_DATE" = inserted."END_DATE", + "CONCURRENCY_CONTROL_NUMBER" = inserted."CONCURRENCY_CONTROL_NUMBER" + , DB_AUDIT_LAST_UPDATE_TIMESTAMP = getutcdate() + , DB_AUDIT_LAST_UPDATE_USERID = user_name() + from HMR_ACTIVITY_CODE_RULE + inner join inserted + on (HMR_ACTIVITY_CODE_RULE.ACTIVITY_CODE_RULE_ID = inserted.ACTIVITY_CODE_RULE_ID); + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CD_RL_I_S_I_TR +PRINT N'Create trigger dbo.HMR_ACT_CD_RL_I_S_I_TR' +GO +CREATE TRIGGER [dbo].[HMR_ACT_CD_RL_I_S_I_TR] ON HMR_ACTIVITY_CODE_RULE INSTEAD OF INSERT AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM inserted) + RETURN; + + + insert into HMR_ACTIVITY_CODE_RULE ( + "ACTIVITY_CODE_RULE_ID", + "ACTIVITY_RULE_SET", + "ACTIVITY_RULE_NAME", + "ACTIVITY_RULE_EXEC_NAME", + "DISPLAY_ORDER", + "END_DATE", + "CONCURRENCY_CONTROL_NUMBER") + select "ACTIVITY_CODE_RULE_ID", + "ACTIVITY_RULE_SET", + "ACTIVITY_RULE_NAME", + "ACTIVITY_RULE_EXEC_NAME", + "DISPLAY_ORDER", + "END_DATE", + "CONCURRENCY_CONTROL_NUMBER" + from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +COMMIT TRANSACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO +DECLARE @Success AS BIT +SET @Success = 1 +SET NOEXEC OFF +IF (@Success = 1) PRINT 'The database update succeeded' +ELSE BEGIN + IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION + PRINT 'The database update failed' +END +GO diff --git a/database/V24.0/2_HMR_PDM-dml_INSERT_HMR_ACTIVITY_CODE_RULES_V24_IS2.1.sql b/database/V24.0/2_HMR_PDM-dml_INSERT_HMR_ACTIVITY_CODE_RULES_V24_IS2.1.sql new file mode 100644 index 00000000..e9bc2673 --- /dev/null +++ b/database/V24.0/2_HMR_PDM-dml_INSERT_HMR_ACTIVITY_CODE_RULES_V24_IS2.1.sql @@ -0,0 +1,145 @@ +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_CODE_RULE_ID], [ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + (0, '','Default','DEFAULT',0) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH','Not Applicable','NOT_APPLICABLE',1) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [TBD Application Rate] * [Lane KM]','RATE_LANE_KM',2) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [2.0] * [Lane KM] * [3.5]','RATE_LANE_KM_35',3) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [3.0] * [Lane KM] * [6.0]','RATE_LANE_KM_60', 4) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Lane KM * 1000.0] * [3.5]','LANE_METERS_35',5) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Road KM Non-Paved]','ROAD_KM_NONPAVED',6) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Lane KM Paved] * 2.0','LANE_KM_PAVED_20',7) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Road KM] * 2.0','ROAD_KM_20',8) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Road KM * 1000.0] * 2.0','ROAD_METERS_20',9) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Road KM] * 2.0','ROAD_KM_20',10) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Road KM]','ROAD_KM',11) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Road KM * 1000.0]','ROAD_METERS',12) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Lane KM]','LANE_KM',13) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Lane KM * 1000.0]','LANE_METERS',14) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_LENGTH',N'[Qty] ≤ [Barrier Length * 1000.0]','BARRIER_LEN_METERS',15) +GO + + + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('SURFACE_TYPE','Not Applicable','NOT_APPLICABLE',1) +GO +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('SURFACE_TYPE','GPS on Paved Surface/within 100m of Structure','GPS_PAVED_STRUCTURE',2) +GO +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('SURFACE_TYPE','GPS on Paved Surface','GPS_PAVED_SURFACE',3) +GO +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('SURFACE_TYPE','GPS on Non-Paved Surface','GPS_NON_PAVED_SURFACE',4) +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_CLASS','Not Applicable','NOT_APPLICABLE',1) +GO +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_CLASS','Class 8 or F Only','CLASS_8_OR_F',2) +GO +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_CLASS','Not Class 8 or F','NOT_CLASS_8_OR_F',3) +GO +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('ROAD_CLASS','All Classes','ALL_CLASSES',4) +GO \ No newline at end of file diff --git a/database/V24.0/3_HMR_PDM-ddl_ALTER_ACTIVITY_CODE_FOREIGN_KEYS_V24_IS2.1.sql b/database/V24.0/3_HMR_PDM-ddl_ALTER_ACTIVITY_CODE_FOREIGN_KEYS_V24_IS2.1.sql new file mode 100644 index 00000000..b6e42ae1 --- /dev/null +++ b/database/V24.0/3_HMR_PDM-ddl_ALTER_ACTIVITY_CODE_FOREIGN_KEYS_V24_IS2.1.sql @@ -0,0 +1,41 @@ +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +-- Create foreign key constraint dbo.HMR_ACT_CD_RL_RD_CLSS_FK +PRINT N'Create foreign key constraint dbo.HMR_ACT_CD_RL_RD_CLSS_FK' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD FOREIGN KEY([ROAD_CLASS_RULE]) + REFERENCES [dbo].[HMR_ACTIVITY_CODE_RULE]([ACTIVITY_CODE_RULE_ID]) + ON DELETE NO ACTION + ON UPDATE NO ACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create foreign key constraint dbo.HMR_ACT_CD_RL_RD_LNGTH_FK +PRINT N'Create foreign key constraint dbo.HMR_ACT_CD_RL_RD_LNGTH_FK' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD FOREIGN KEY([ROAD_LENGTH_RULE]) + REFERENCES [dbo].[HMR_ACTIVITY_CODE_RULE]([ACTIVITY_CODE_RULE_ID]) + ON DELETE NO ACTION + ON UPDATE NO ACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create foreign key constraint dbo.HMR_ACT_CD_RL_SRFC_TYP_FK +PRINT N'Create foreign key constraint dbo.HMR_ACT_CD_RL_SRFC_TYP_FK' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD FOREIGN KEY([SURFACE_TYPE_RULE]) + REFERENCES [dbo].[HMR_ACTIVITY_CODE_RULE]([ACTIVITY_CODE_RULE_ID]) + ON DELETE NO ACTION + ON UPDATE NO ACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO \ No newline at end of file diff --git a/database/V24.0/4_HMR_PDM-dml_HMR_CODE_LOOKUP_ACTIVITY_RULE_TYPES_V24_IS2.1.sql b/database/V24.0/4_HMR_PDM-dml_HMR_CODE_LOOKUP_ACTIVITY_RULE_TYPES_V24_IS2.1.sql new file mode 100644 index 00000000..5c84aa49 --- /dev/null +++ b/database/V24.0/4_HMR_PDM-dml_HMR_CODE_LOOKUP_ACTIVITY_RULE_TYPES_V24_IS2.1.sql @@ -0,0 +1,16 @@ +-- ************************************************************** +-- Insert the Activity Rule codes into the HMR_CODE_LOOKUP table. +-- ************************************************************** + +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +INSERT INTO [dbo].[HMR_CODE_LOOKUP]([CODE_SET], [CODE_NAME], [CODE_VALUE_TEXT], [CODE_VALUE_FORMAT]) VALUES('ACTIVITY_RULE', 'ROAD_LENGTH', 'Road Length', 'STRING'); +GO +INSERT INTO [dbo].[HMR_CODE_LOOKUP]([CODE_SET], [CODE_NAME], [CODE_VALUE_TEXT], [CODE_VALUE_FORMAT]) VALUES('ACTIVITY_RULE', 'SURFACE_TYPE', 'Surface Type', 'STRING'); +GO +INSERT INTO [dbo].[HMR_CODE_LOOKUP]([CODE_SET], [CODE_NAME], [CODE_VALUE_TEXT], [CODE_VALUE_FORMAT]) VALUES('ACTIVITY_RULE', 'ROAD_CLASS', 'Road Class', 'STRING'); +GO diff --git a/database/V24.0/5_HMR_ALTER_PDM-ddl-ROLE_APP_PROXY-V24_IS2.1.sql b/database/V24.0/5_HMR_ALTER_PDM-ddl-ROLE_APP_PROXY-V24_IS2.1.sql new file mode 100644 index 00000000..20af0acd --- /dev/null +++ b/database/V24.0/5_HMR_ALTER_PDM-ddl-ROLE_APP_PROXY-V24_IS2.1.sql @@ -0,0 +1,184 @@ +-- ============================================= +-- Author: Ben Driver +-- Create date: 2020-03-02 +-- Updates: +-- +-- +-- Description: +-- - Role creation for APPLICATION_PROXY role +-- ============================================= + +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +-- Create ROLE + +if not exists (select 1 from sys.database_principals where name='HMR_APPLICATION_PROXY' and Type = 'R') + begin + CREATE ROLE HMR_APPLICATION_PROXY AUTHORIZATION db_securityadmin; + end +GO + +GRANT select ON dbo.HMR_ACTIVITY_CODE TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ACTIVITY_CODE_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_CODE_LOOKUP TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_CODE_LOOKUP_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_CONTRACT_TERM TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_CONTRACT_TERM_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_DISTRICT TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_FEEDBACK_MESSAGE TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_LOCATION_CODE TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_LOCATION_CODE_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_MIME_TYPE TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_PARTY TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_PARTY_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_PERMISSION TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_PERMISSION_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_REGION TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ROCKFALL_REPORT TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ROCKFALL_REPORT_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ROLE TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ROLE_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ROLE_PERMISSION TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ROLE_PERMISSION_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SERVICE_AREA TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SERVICE_AREA_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SERVICE_AREA_USER TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SERVICE_AREA_USER_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_STREAM_ELEMENT TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_STREAM_ELEMENT_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SUBMISSION_OBJECT TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SUBMISSION_ROW TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SUBMISSION_ROW_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SUBMISSION_STATUS TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SUBMISSION_STREAM TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SUBMISSION_STREAM_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SYSTEM_USER TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SYSTEM_USER_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_SYSTEM_VALIDATION TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_USER_ROLE TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_USER_ROLE_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_WILDLIFE_REPORT TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_WILDLIFE_REPORT_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_WORK_REPORT TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_WORK_REPORT_HIST TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_ROCKFALL_REPORT_VW TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_WILDLIFE_REPORT_VW TO HMR_APPLICATION_PROXY; +GRANT select ON dbo.HMR_WORK_REPORT_VW TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ACTIVITY_CODE TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ACTIVITY_CODE_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_CODE_LOOKUP TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_CODE_LOOKUP_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_CONTRACT_TERM TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_CONTRACT_TERM_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_DISTRICT TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_FEEDBACK_MESSAGE TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_LOCATION_CODE TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_LOCATION_CODE_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_MIME_TYPE TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_PARTY TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_PARTY_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_PERMISSION TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_PERMISSION_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_REGION TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ROCKFALL_REPORT TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ROCKFALL_REPORT_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ROLE TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ROLE_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ROLE_PERMISSION TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_ROLE_PERMISSION_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SERVICE_AREA TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SERVICE_AREA_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SERVICE_AREA_USER TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SERVICE_AREA_USER_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_STREAM_ELEMENT TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_STREAM_ELEMENT_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SUBMISSION_OBJECT TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SUBMISSION_ROW TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SUBMISSION_ROW_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SUBMISSION_STATUS TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SUBMISSION_STREAM TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SUBMISSION_STREAM_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SYSTEM_USER TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SYSTEM_USER_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_SYSTEM_VALIDATION TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_USER_ROLE TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_USER_ROLE_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_WILDLIFE_REPORT TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_WILDLIFE_REPORT_HIST TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_WORK_REPORT TO HMR_APPLICATION_PROXY; +GRANT insert, update ON dbo.HMR_WORK_REPORT_HIST TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_ACTIVITY_CODE TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_CODE_LOOKUP TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_CONTRACT_TERM TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_DISTRICT TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_FEEDBACK_MESSAGE TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_LOCATION_CODE TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_MIME_TYPE TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_PARTY TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_PERMISSION TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_REGION TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_ROCKFALL_REPORT TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_ROLE TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_ROLE_PERMISSION TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SERVICE_AREA TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SERVICE_AREA_USER TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_STREAM_ELEMENT TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SUBMISSION_OBJECT TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SUBMISSION_ROW TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SUBMISSION_STATUS TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SUBMISSION_STREAM TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SYSTEM_USER TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_SYSTEM_VALIDATION TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_USER_ROLE TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_WILDLIFE_REPORT TO HMR_APPLICATION_PROXY; +GRANT delete ON dbo.HMR_WORK_REPORT TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.FDBK_MSG_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_ACT_CODE_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_ACTIVITY_CODE_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_CNT_TRM_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_CODE_LKUP_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_CODE_LOOKUP_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_CONTRACT_TERM_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_DIST_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_LOC_CODE_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_LOCATION_CODE_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_MIME_TYPE_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_PARTY_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_PERM_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_PERMISSION_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_PRTY_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_RCKF_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_REG_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_RL_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_RL_PERM_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_ROCKFALL_REPORT_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_ROLE_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_ROLE_PERMISSION_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SERVICE_AREA_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SERVICE_AREA_USER_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SRV_ARA_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SRV_AREA_USR_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_STR_ELMT_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_STREAM_ELEMENT_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SUBM_OBJ_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SUBM_RW_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SUBM_STAT_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SUBM_STR_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SUBMISSION_ROW_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SUBMISSION_STREAM_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_SYSTEM_USER_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_USER_ROLE_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_USR_RL_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_WILDLIFE_REPORT_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_WLDLF_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_WORK_REPORT_H_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.HMR_WRK_RPT_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.SYS_USR_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT update ON dbo.SYS_VLD_ID_SEQ TO HMR_APPLICATION_PROXY; +GRANT execute ON dbo.hmr_error_handling TO HMR_APPLICATION_PROXY; + +GO diff --git a/database/V24.0/6_HMR_ALTER_PDM-ddl-ROLE_GIS_READ-V24_IS2.1.sql b/database/V24.0/6_HMR_ALTER_PDM-ddl-ROLE_GIS_READ-V24_IS2.1.sql new file mode 100644 index 00000000..fd325f25 --- /dev/null +++ b/database/V24.0/6_HMR_ALTER_PDM-ddl-ROLE_GIS_READ-V24_IS2.1.sql @@ -0,0 +1,31 @@ +-- ============================================= +-- Author: Ben Driver +-- Create date: 2020-03-02 +-- Updates: +-- +-- +-- Description: +-- - Role creation for GIS_READ role +-- ============================================= + +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +-- Create ROLE + +if not exists (select 1 from sys.database_principals where name='HMR_GIS_READ' and Type = 'R') + begin + CREATE ROLE HMR_GIS_READ AUTHORIZATION db_securityadmin; + end + +-- GRANT select on views + +GRANT select ON dbo.HMR_ROCKFALL_REPORT_VW TO HMR_GIS_READ; +GRANT select ON dbo.HMR_WILDLIFE_REPORT_VW TO HMR_GIS_READ; +GRANT select ON dbo.HMR_WORK_REPORT_VW TO HMR_GIS_READ; + +GO + diff --git a/database/V24.0/7_HMR_ALTER_PDM-ddl-ROLE_READ_ONLY-V24_IS2.1.sql b/database/V24.0/7_HMR_ALTER_PDM-ddl-ROLE_READ_ONLY-V24_IS2.1.sql new file mode 100644 index 00000000..360688d1 --- /dev/null +++ b/database/V24.0/7_HMR_ALTER_PDM-ddl-ROLE_READ_ONLY-V24_IS2.1.sql @@ -0,0 +1,74 @@ +-- ============================================= +-- Author: Ben Driver +-- Create date: 2020-03-02 +-- Updates: +-- +-- +-- Description: +-- - Role creation for READ_ONLY role +-- ============================================= + +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +-- Create ROLE + +if not exists (select 1 from sys.database_principals where name='HMR_READ_ONLY' and Type = 'R') + begin + CREATE ROLE HMR_READ_ONLY AUTHORIZATION db_securityadmin; + end + +-- GRANT select on tables + +GRANT select ON dbo.HMR_ACTIVITY_CODE TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ACTIVITY_CODE_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_CODE_LOOKUP TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_CODE_LOOKUP_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_CONTRACT_TERM TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_CONTRACT_TERM_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_DISTRICT TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_FEEDBACK_MESSAGE TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_LOCATION_CODE TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_LOCATION_CODE_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_MIME_TYPE TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_PARTY TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_PARTY_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_PERMISSION TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_PERMISSION_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_REGION TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ROCKFALL_REPORT TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ROCKFALL_REPORT_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ROLE TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ROLE_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ROLE_PERMISSION TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ROLE_PERMISSION_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SERVICE_AREA TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SERVICE_AREA_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SERVICE_AREA_USER TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SERVICE_AREA_USER_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_STREAM_ELEMENT TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_STREAM_ELEMENT_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SUBMISSION_OBJECT TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SUBMISSION_ROW TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SUBMISSION_ROW_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SUBMISSION_STATUS TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SUBMISSION_STREAM TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SUBMISSION_STREAM_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SYSTEM_USER TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SYSTEM_USER_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_SYSTEM_VALIDATION TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_USER_ROLE TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_USER_ROLE_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_WILDLIFE_REPORT TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_WILDLIFE_REPORT_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_WORK_REPORT TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_WORK_REPORT_HIST TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_ROCKFALL_REPORT_VW TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_WILDLIFE_REPORT_VW TO HMR_READ_ONLY; +GRANT select ON dbo.HMR_WORK_REPORT_VW TO HMR_READ_ONLY; + +GO + diff --git a/database/V25.0/1_HMR_PDM-ddl_ALTER_APP_HMR_V25_IS2.2.sql b/database/V25.0/1_HMR_PDM-ddl_ALTER_APP_HMR_V25_IS2.2.sql new file mode 100644 index 00000000..0a2e1b8a --- /dev/null +++ b/database/V25.0/1_HMR_PDM-ddl_ALTER_APP_HMR_V25_IS2.2.sql @@ -0,0 +1,705 @@ +-- Script generated by Aqua Data Studio Schema Synchronization for MS SQL Server 2016 on Tue Oct 20 10:33:19 PDT 2020 +-- Execute this script on: +-- HMR V24.0/dbo - This database/schema will be modified +-- to synchronize it with MS SQL Server 2016: +-- HMR V25.0/dbo + +-- We recommend backing up the database prior to executing the script. + +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +SET XACT_ABORT ON +GO +SET TRANSACTION ISOLATION LEVEL SERIALIZABLE +GO +BEGIN TRANSACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_CODE_LKUP_A_S_IUD_TR +PRINT N'Drop trigger dbo.HMR_CODE_LKUP_A_S_IUD_TR' +GO +DROP TRIGGER [dbo].[HMR_CODE_LKUP_A_S_IUD_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_ACT_CODE_A_S_IUD_TR +PRINT N'Drop trigger dbo.HMR_ACT_CODE_A_S_IUD_TR' +GO +DROP TRIGGER [dbo].[HMR_ACT_CODE_A_S_IUD_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_ACT_CODE_I_S_I_TR +PRINT N'Drop trigger dbo.HMR_ACT_CODE_I_S_I_TR' +GO +DROP TRIGGER [dbo].[HMR_ACT_CODE_I_S_I_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_ACT_CODE_I_S_U_TR +PRINT N'Drop trigger dbo.HMR_ACT_CODE_I_S_U_TR' +GO +DROP TRIGGER [dbo].[HMR_ACT_CODE_I_S_U_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_CODE_LKUP_I_S_I_TR +PRINT N'Drop trigger dbo.HMR_CODE_LKUP_I_S_I_TR' +GO +DROP TRIGGER [dbo].[HMR_CODE_LKUP_I_S_I_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Drop trigger dbo.HMR_CODE_LKUP_I_S_U_TR +PRINT N'Drop trigger dbo.HMR_CODE_LKUP_I_S_U_TR' +GO +DROP TRIGGER [dbo].[HMR_CODE_LKUP_I_S_U_TR] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create sequence dbo.HMR_SERVICE_AREA_ACTIVITY_ID_SEQ +PRINT N'Create sequence dbo.HMR_SERVICE_AREA_ACTIVITY_ID_SEQ' +GO +CREATE SEQUENCE [dbo].[HMR_SERVICE_AREA_ACTIVITY_ID_SEQ] + AS bigint + START WITH 1 + INCREMENT BY 1 + MINVALUE 1 + MAXVALUE 999999999 + NO CYCLE + CACHE 50 +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Alter table dbo.HMR_ACTIVITY_CODE +PRINT N'Alter table dbo.HMR_ACTIVITY_CODE' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD [MIN_VALUE] numeric(11,2) NULL, + [MAX_VALUE] numeric(11,2) NULL, + [REPORTING_FREQUENCY] int NULL +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create check constraint dbo.CC_HMR_ACTIVITY_CODE_REPORTING_FREQUENCY +PRINT N'Create check constraint dbo.CC_HMR_ACTIVITY_CODE_REPORTING_FREQUENCY' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD CHECK ([REPORTING_FREQUENCY]>=(0) AND [REPORTING_FREQUENCY]<=(366)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create check constraint dbo.CC_HMR_ACTIVITY_CODE_MIN_VALUE +PRINT N'Create check constraint dbo.CC_HMR_ACTIVITY_CODE_MIN_VALUE' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD CHECK ([MIN_VALUE]>=(0) AND [MIN_VALUE]<=(999999999.99)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create check constraint dbo.CC_HMR_ACTIVITY_CODE_MAX_VALUE +PRINT N'Create check constraint dbo.CC_HMR_ACTIVITY_CODE_MAX_VALUE' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE] + ADD CHECK ([MAX_VALUE]>=(0) AND [MAX_VALUE]<=(999999999.99)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create table dbo.HMR_SERVICE_AREA_ACTIVITY +PRINT N'Create table dbo.HMR_SERVICE_AREA_ACTIVITY' +GO +CREATE TABLE [dbo].[HMR_SERVICE_AREA_ACTIVITY] ( + [SERVICE_AREA_ACTIVITY_ID] numeric(9,0) NOT NULL DEFAULT (NEXT VALUE FOR [HMR_SERVICE_AREA_ACTIVITY_ID_SEQ]), + [ACTIVITY_CODE_ID] numeric(9,0) NOT NULL, + [SERVICE_AREA_NUMBER] numeric(9,0) NOT NULL, + [END_DATE] datetime NULL, + [CONCURRENCY_CONTROL_NUMBER] bigint NOT NULL DEFAULT ((1)), + [APP_CREATE_USERID] varchar(30) NOT NULL, + [APP_CREATE_TIMESTAMP] datetime NOT NULL, + [APP_CREATE_USER_GUID] uniqueidentifier NOT NULL, + [APP_CREATE_USER_DIRECTORY] varchar(12) NOT NULL, + [APP_LAST_UPDATE_USERID] varchar(30) NOT NULL, + [APP_LAST_UPDATE_TIMESTAMP] datetime NOT NULL, + [APP_LAST_UPDATE_USER_GUID] uniqueidentifier NOT NULL, + [APP_LAST_UPDATE_USER_DIRECTORY] varchar(12) NOT NULL, + [DB_AUDIT_CREATE_USERID] varchar(30) NOT NULL DEFAULT (user_name()), + [DB_AUDIT_CREATE_TIMESTAMP] datetime NOT NULL DEFAULT (getutcdate()), + [DB_AUDIT_LAST_UPDATE_USERID] varchar(30) NOT NULL DEFAULT (user_name()), + [DB_AUDIT_LAST_UPDATE_TIMESTAMP] datetime NOT NULL DEFAULT (getutcdate()), + PRIMARY KEY CLUSTERED([SERVICE_AREA_ACTIVITY_ID]) + ON [PRIMARY]) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create unique constraint dbo.TUC_HMR_SERVICE_AREA_ACTIVITY_1 +PRINT N'Create unique constraint dbo.TUC_HMR_SERVICE_AREA_ACTIVITY_1' +GO +ALTER TABLE [dbo].[HMR_SERVICE_AREA_ACTIVITY] + ADD UNIQUE ([SERVICE_AREA_NUMBER], [ACTIVITY_CODE_ID]) + WITH ( + DATA_COMPRESSION = NONE + ) ON [PRIMARY] +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create sequence dbo.HMR_SERVICE_AREA_ACTIVITY_H_ID_SEQ +PRINT N'Create sequence dbo.HMR_SERVICE_AREA_ACTIVITY_H_ID_SEQ' +GO +CREATE SEQUENCE [dbo].[HMR_SERVICE_AREA_ACTIVITY_H_ID_SEQ] + AS bigint + START WITH 1 + INCREMENT BY 1 + MINVALUE 1 + MAXVALUE 999999999 + NO CYCLE + CACHE 50 +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create table dbo.HMR_SERVICE_AREA_ACTIVITY_HIST +PRINT N'Create table dbo.HMR_SERVICE_AREA_ACTIVITY_HIST' +GO +CREATE TABLE [dbo].[HMR_SERVICE_AREA_ACTIVITY_HIST] ( + [SERVICE_AREA_ACTIVITY_HIST_ID] bigint NOT NULL DEFAULT (NEXT VALUE FOR [HMR_SERVICE_AREA_ACTIVITY_H_ID_SEQ]), + [EFFECTIVE_DATE_HIST] datetime NOT NULL DEFAULT (getutcdate()), + [END_DATE_HIST] datetime NULL, + [SERVICE_AREA_ACTIVITY_ID] numeric(9,0) NOT NULL, + [ACTIVITY_CODE_ID] numeric(9,0) NOT NULL, + [SERVICE_AREA_NUMBER] numeric(9,0) NOT NULL, + [END_DATE] datetime NULL, + [CONCURRENCY_CONTROL_NUMBER] bigint NOT NULL DEFAULT ((1)), + [APP_CREATE_USERID] varchar(30) NOT NULL, + [APP_CREATE_TIMESTAMP] datetime NOT NULL, + [APP_CREATE_USER_GUID] uniqueidentifier NOT NULL, + [APP_CREATE_USER_DIRECTORY] varchar(12) NOT NULL, + [APP_LAST_UPDATE_USERID] varchar(30) NOT NULL, + [APP_LAST_UPDATE_TIMESTAMP] datetime NOT NULL, + [APP_LAST_UPDATE_USER_GUID] uniqueidentifier NOT NULL, + [APP_LAST_UPDATE_USER_DIRECTORY] varchar(12) NOT NULL, + [DB_AUDIT_CREATE_USERID] varchar(30) NOT NULL DEFAULT (user_name()), + [DB_AUDIT_CREATE_TIMESTAMP] datetime NOT NULL DEFAULT (getutcdate()), + [DB_AUDIT_LAST_UPDATE_USERID] varchar(30) NOT NULL DEFAULT (user_name()), + [DB_AUDIT_LAST_UPDATE_TIMESTAMP] datetime NOT NULL DEFAULT (getutcdate()), + PRIMARY KEY CLUSTERED([SERVICE_AREA_ACTIVITY_HIST_ID]) + ON [PRIMARY]) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Alter table dbo.HMR_CODE_LOOKUP +PRINT N'Alter table dbo.HMR_CODE_LOOKUP' +GO +ALTER TABLE [dbo].[HMR_CODE_LOOKUP] + ADD [IS_INTEGER_ONLY] bit NOT NULL DEFAULT ((0)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Alter table dbo.HMR_ACTIVITY_CODE_HIST +PRINT N'Alter table dbo.HMR_ACTIVITY_CODE_HIST' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE_HIST] + ADD [MIN_VALUE] numeric(11,2) NULL, + [MAX_VALUE] numeric(11,2) NULL, + [REPORTING_FREQUENCY] int NULL +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create check constraint dbo.CC_HMR_ACTIVITY_CODE_HIST_MAX_VALUE +PRINT N'Create check constraint dbo.CC_HMR_ACTIVITY_CODE_HIST_MAX_VALUE' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE_HIST] + ADD CHECK ([MAX_VALUE]>=(0) AND [MAX_VALUE]<=(999999999.99)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create check constraint dbo.CC_HMR_ACTIVITY_CODE_HIST_MIN_VALUE +PRINT N'Create check constraint dbo.CC_HMR_ACTIVITY_CODE_HIST_MIN_VALUE' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE_HIST] + ADD CHECK ([MIN_VALUE]>=(0) AND [MIN_VALUE]<=(999999999.99)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create check constraint dbo.CC_HMR_ACTIVITY_CODE_HIST_REPORTING_FREQUENCY +PRINT N'Create check constraint dbo.CC_HMR_ACTIVITY_CODE_HIST_REPORTING_FREQUENCY' +GO +ALTER TABLE [dbo].[HMR_ACTIVITY_CODE_HIST] + ADD CHECK ([REPORTING_FREQUENCY]>=(0) AND [REPORTING_FREQUENCY]<=(366)) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Alter table dbo.HMR_CODE_LOOKUP_HIST +PRINT N'Alter table dbo.HMR_CODE_LOOKUP_HIST' +GO +ALTER TABLE [dbo].[HMR_CODE_LOOKUP_HIST] + ADD [IS_INTEGER_ONLY] bit NOT NULL DEFAULT 0 +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create index dbo.IDX_HMR_SVC_AR_ACT_ACT_CD +PRINT N'Create index dbo.IDX_HMR_SVC_AR_ACT_ACT_CD' +GO +CREATE NONCLUSTERED INDEX [IDX_HMR_SVC_AR_ACT_ACT_CD] + ON [dbo].[HMR_SERVICE_AREA_ACTIVITY]([ACTIVITY_CODE_ID]) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create index dbo.IDX_HMR_SVC_AR_ACT_SVC_AREA +PRINT N'Create index dbo.IDX_HMR_SVC_AR_ACT_SVC_AREA' +GO +CREATE NONCLUSTERED INDEX [IDX_HMR_SVC_AR_ACT_SVC_AREA] + ON [dbo].[HMR_SERVICE_AREA_ACTIVITY]([SERVICE_AREA_NUMBER]) +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create foreign key constraint dbo.HMR_SERVICE_AREA_HMR_SERVICE_AREA_ACTIVITY +PRINT N'Create foreign key constraint dbo.HMR_SERVICE_AREA_HMR_SERVICE_AREA_ACTIVITY' +GO +ALTER TABLE [dbo].[HMR_SERVICE_AREA_ACTIVITY] + ADD FOREIGN KEY([SERVICE_AREA_NUMBER]) + REFERENCES [dbo].[HMR_SERVICE_AREA]([SERVICE_AREA_NUMBER]) + ON DELETE NO ACTION + ON UPDATE NO ACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create foreign key constraint dbo.HMR_ACTIVITY_CODE_HMR_SERVICE_AREA_ACTIVITY +PRINT N'Create foreign key constraint dbo.HMR_ACTIVITY_CODE_HMR_SERVICE_AREA_ACTIVITY' +GO +ALTER TABLE [dbo].[HMR_SERVICE_AREA_ACTIVITY] + ADD FOREIGN KEY([ACTIVITY_CODE_ID]) + REFERENCES [dbo].[HMR_ACTIVITY_CODE]([ACTIVITY_CODE_ID]) + ON DELETE NO ACTION + ON UPDATE NO ACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_SVC_AR_ACT_A_S_IUD_TR +PRINT N'Create trigger dbo.HMR_SVC_AR_ACT_A_S_IUD_TR' +GO +CREATE TRIGGER [dbo].[HMR_SVC_AR_ACT_A_S_IUD_TR] ON HMR_SERVICE_AREA_ACTIVITY FOR INSERT, UPDATE, DELETE AS +SET NOCOUNT ON +BEGIN TRY +DECLARE @curr_date datetime; +SET @curr_date = getutcdate(); + IF NOT EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- historical + IF EXISTS(SELECT * FROM deleted) + update HMR_SERVICE_AREA_ACTIVITY_HIST set END_DATE_HIST = @curr_date where SERVICE_AREA_ACTIVITY_ID in (select SERVICE_AREA_ACTIVITY_ID from deleted) and END_DATE_HIST is null; + + IF EXISTS(SELECT * FROM inserted) + insert into HMR_SERVICE_AREA_ACTIVITY_HIST ([SERVICE_AREA_ACTIVITY_ID], [ACTIVITY_CODE_ID], [SERVICE_AREA_NUMBER], [END_DATE], [CONCURRENCY_CONTROL_NUMBER], [APP_CREATE_USERID], [APP_CREATE_TIMESTAMP], [APP_CREATE_USER_GUID], [APP_CREATE_USER_DIRECTORY], [APP_LAST_UPDATE_USERID], [APP_LAST_UPDATE_TIMESTAMP], [APP_LAST_UPDATE_USER_GUID], [APP_LAST_UPDATE_USER_DIRECTORY], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], SERVICE_AREA_ACTIVITY_HIST_ID, END_DATE_HIST, EFFECTIVE_DATE_HIST) + select [SERVICE_AREA_ACTIVITY_ID], [ACTIVITY_CODE_ID], [SERVICE_AREA_NUMBER], [END_DATE], [CONCURRENCY_CONTROL_NUMBER], [APP_CREATE_USERID], [APP_CREATE_TIMESTAMP], [APP_CREATE_USER_GUID], [APP_CREATE_USER_DIRECTORY], [APP_LAST_UPDATE_USERID], [APP_LAST_UPDATE_TIMESTAMP], [APP_LAST_UPDATE_USER_GUID], [APP_LAST_UPDATE_USER_DIRECTORY], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], (next value for [dbo].[HMR_SERVICE_AREA_ACTIVITY_H_ID_SEQ]) as [SERVICE_AREA_ACTIVITY_HIST_ID], null as [END_DATE_HIST], @curr_date as [EFFECTIVE_DATE_HIST] from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_CODE_LKUP_I_S_U_TR +PRINT N'Create trigger dbo.HMR_CODE_LKUP_I_S_U_TR' +GO +CREATE TRIGGER [dbo].[HMR_CODE_LKUP_I_S_U_TR] ON HMR_CODE_LOOKUP INSTEAD OF UPDATE AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- validate concurrency control + if exists (select 1 from inserted, deleted where inserted.CONCURRENCY_CONTROL_NUMBER != deleted.CONCURRENCY_CONTROL_NUMBER+1 AND inserted.CODE_LOOKUP_ID = deleted.CODE_LOOKUP_ID) + raiserror('CONCURRENCY FAILURE.',16,1) + + + -- update statement + update HMR_CODE_LOOKUP + set "CODE_LOOKUP_ID" = inserted."CODE_LOOKUP_ID", + "CODE_SET" = inserted."CODE_SET", + "CODE_NAME" = inserted."CODE_NAME", + "CODE_VALUE_TEXT" = inserted."CODE_VALUE_TEXT", + "CODE_VALUE_NUM" = inserted."CODE_VALUE_NUM", + "CODE_VALUE_FORMAT" = inserted."CODE_VALUE_FORMAT", + "DISPLAY_ORDER" = inserted."DISPLAY_ORDER", + "END_DATE" = inserted."END_DATE", + "IS_INTEGER_ONLY" = inserted."IS_INTEGER_ONLY", + "CONCURRENCY_CONTROL_NUMBER" = inserted."CONCURRENCY_CONTROL_NUMBER" + , DB_AUDIT_LAST_UPDATE_TIMESTAMP = getutcdate() + , DB_AUDIT_LAST_UPDATE_USERID = user_name() + from HMR_CODE_LOOKUP + inner join inserted + on (HMR_CODE_LOOKUP.CODE_LOOKUP_ID = inserted.CODE_LOOKUP_ID); + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_CODE_LKUP_I_S_I_TR +PRINT N'Create trigger dbo.HMR_CODE_LKUP_I_S_I_TR' +GO +CREATE TRIGGER [dbo].[HMR_CODE_LKUP_I_S_I_TR] ON HMR_CODE_LOOKUP INSTEAD OF INSERT AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM inserted) + RETURN; + + + insert into HMR_CODE_LOOKUP ("CODE_LOOKUP_ID", + "CODE_SET", + "CODE_NAME", + "CODE_VALUE_TEXT", + "CODE_VALUE_NUM", + "CODE_VALUE_FORMAT", + "DISPLAY_ORDER", + "END_DATE", + "IS_INTEGER_ONLY", + "CONCURRENCY_CONTROL_NUMBER") + select "CODE_LOOKUP_ID", + "CODE_SET", + "CODE_NAME", + "CODE_VALUE_TEXT", + "CODE_VALUE_NUM", + "CODE_VALUE_FORMAT", + "DISPLAY_ORDER", + "END_DATE", + "IS_INTEGER_ONLY", + "CONCURRENCY_CONTROL_NUMBER" + from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CODE_I_S_U_TR +PRINT N'Create trigger dbo.HMR_ACT_CODE_I_S_U_TR' +GO +CREATE TRIGGER [dbo].[HMR_ACT_CODE_I_S_U_TR] ON HMR_ACTIVITY_CODE INSTEAD OF UPDATE AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- validate concurrency control + if exists (select 1 from inserted, deleted where inserted.CONCURRENCY_CONTROL_NUMBER != deleted.CONCURRENCY_CONTROL_NUMBER+1 AND inserted.ACTIVITY_CODE_ID = deleted.ACTIVITY_CODE_ID) + raiserror('CONCURRENCY FAILURE.',16,1) + + + -- update statement + update HMR_ACTIVITY_CODE + set "ACTIVITY_CODE_ID" = inserted."ACTIVITY_CODE_ID", + "ACTIVITY_NUMBER" = inserted."ACTIVITY_NUMBER", + "ACTIVITY_NAME" = inserted."ACTIVITY_NAME", + "UNIT_OF_MEASURE" = inserted."UNIT_OF_MEASURE", + "MAINTENANCE_TYPE" = inserted."MAINTENANCE_TYPE", + "LOCATION_CODE_ID" = inserted."LOCATION_CODE_ID", + "FEATURE_TYPE" = inserted."FEATURE_TYPE", + "SP_THRESHOLD_LEVEL" = inserted."SP_THRESHOLD_LEVEL", + "IS_SITE_NUM_REQUIRED" = inserted."IS_SITE_NUM_REQUIRED", + "ACTIVITY_APPLICATION" = inserted."ACTIVITY_APPLICATION", + "END_DATE" = inserted."END_DATE", + "ROAD_CLASS_RULE" = inserted."ROAD_CLASS_RULE", + "ROAD_LENGTH_RULE" = inserted."ROAD_LENGTH_RULE", + "SURFACE_TYPE_RULE" = inserted."SURFACE_TYPE_RULE", + "MIN_VALUE" = inserted."MIN_VALUE", + "MAX_VALUE" = inserted."MAX_VALUE", + "REPORTING_FREQUENCY" = inserted."REPORTING_FREQUENCY", + "CONCURRENCY_CONTROL_NUMBER" = inserted."CONCURRENCY_CONTROL_NUMBER", + "APP_LAST_UPDATE_USERID" = inserted."APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP" = inserted."APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID" = inserted."APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY" = inserted."APP_LAST_UPDATE_USER_DIRECTORY" + , DB_AUDIT_LAST_UPDATE_TIMESTAMP = getutcdate() + , DB_AUDIT_LAST_UPDATE_USERID = user_name() + from HMR_ACTIVITY_CODE + inner join inserted + on (HMR_ACTIVITY_CODE.ACTIVITY_CODE_ID = inserted.ACTIVITY_CODE_ID); + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_SVC_AR_ACT_I_S_I_TR +PRINT N'Create trigger dbo.HMR_SVC_AR_ACT_I_S_I_TR' +GO +CREATE TRIGGER [dbo].[HMR_SVC_AR_ACT_I_S_I_TR] ON HMR_SERVICE_AREA_ACTIVITY INSTEAD OF INSERT AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM inserted) + RETURN; + + insert into HMR_SERVICE_AREA_ACTIVITY ("SERVICE_AREA_ACTIVITY_ID", + "ACTIVITY_CODE_ID", + "SERVICE_AREA_NUMBER", + "END_DATE", + "CONCURRENCY_CONTROL_NUMBER", + "APP_CREATE_USERID", + "APP_CREATE_TIMESTAMP", + "APP_CREATE_USER_GUID", + "APP_CREATE_USER_DIRECTORY", + "APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY") + select "SERVICE_AREA_ACTIVITY_ID", + "ACTIVITY_CODE_ID", + "SERVICE_AREA_NUMBER", + "END_DATE", + "CONCURRENCY_CONTROL_NUMBER", + "APP_CREATE_USERID", + "APP_CREATE_TIMESTAMP", + "APP_CREATE_USER_GUID", + "APP_CREATE_USER_DIRECTORY", + "APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY" + from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CODE_I_S_I_TR +PRINT N'Create trigger dbo.HMR_ACT_CODE_I_S_I_TR' +GO +CREATE TRIGGER [dbo].[HMR_ACT_CODE_I_S_I_TR] ON HMR_ACTIVITY_CODE INSTEAD OF INSERT AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM inserted) + RETURN; + + + insert into HMR_ACTIVITY_CODE ("ACTIVITY_CODE_ID", + "ACTIVITY_NUMBER", + "ACTIVITY_NAME", + "UNIT_OF_MEASURE", + "MAINTENANCE_TYPE", + "LOCATION_CODE_ID", + "FEATURE_TYPE", + "SP_THRESHOLD_LEVEL", + "IS_SITE_NUM_REQUIRED", + "ACTIVITY_APPLICATION", + "END_DATE", + "ROAD_CLASS_RULE", + "ROAD_LENGTH_RULE", + "SURFACE_TYPE_RULE", + "MIN_VALUE", + "MAX_VALUE", + "REPORTING_FREQUENCY", + "CONCURRENCY_CONTROL_NUMBER", + "APP_CREATE_USERID", + "APP_CREATE_TIMESTAMP", + "APP_CREATE_USER_GUID", + "APP_CREATE_USER_DIRECTORY", + "APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY") + select "ACTIVITY_CODE_ID", + "ACTIVITY_NUMBER", + "ACTIVITY_NAME", + "UNIT_OF_MEASURE", + "MAINTENANCE_TYPE", + "LOCATION_CODE_ID", + "FEATURE_TYPE", + "SP_THRESHOLD_LEVEL", + "IS_SITE_NUM_REQUIRED", + "ACTIVITY_APPLICATION", + "END_DATE", + "ROAD_CLASS_RULE", + "ROAD_LENGTH_RULE", + "SURFACE_TYPE_RULE", + "MIN_VALUE", + "MAX_VALUE", + "REPORTING_FREQUENCY", + "CONCURRENCY_CONTROL_NUMBER", + "APP_CREATE_USERID", + "APP_CREATE_TIMESTAMP", + "APP_CREATE_USER_GUID", + "APP_CREATE_USER_DIRECTORY", + "APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY" + from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_ACT_CODE_A_S_IUD_TR +PRINT N'Create trigger dbo.HMR_ACT_CODE_A_S_IUD_TR' +GO +/* ---------------------------------------------------------------------- */ +/* Add triggers */ +/* ---------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- */ +/* Add triggers */ +/* ---------------------------------------------------------------------- */ + +CREATE TRIGGER [dbo].[HMR_ACT_CODE_A_S_IUD_TR] ON HMR_ACTIVITY_CODE FOR INSERT, UPDATE, DELETE AS +SET NOCOUNT ON +BEGIN TRY +DECLARE @curr_date datetime; +SET @curr_date = getutcdate(); + IF NOT EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- historical + IF EXISTS(SELECT * FROM deleted) + update HMR_ACTIVITY_CODE_HIST set END_DATE_HIST = @curr_date where ACTIVITY_CODE_ID in (select ACTIVITY_CODE_ID from deleted) and END_DATE_HIST is null; + + IF EXISTS(SELECT * FROM inserted) + insert into HMR_ACTIVITY_CODE_HIST ([ACTIVITY_CODE_ID], [ACTIVITY_NUMBER], [ACTIVITY_NAME], [UNIT_OF_MEASURE], [MAINTENANCE_TYPE], [LOCATION_CODE_ID], [FEATURE_TYPE], [SP_THRESHOLD_LEVEL], [IS_SITE_NUM_REQUIRED], [ACTIVITY_APPLICATION], [END_DATE], [ROAD_CLASS_RULE], [ROAD_LENGTH_RULE], [SURFACE_TYPE_RULE], [MIN_VALUE], [MAX_VALUE], [REPORTING_FREQUENCY], [CONCURRENCY_CONTROL_NUMBER], [APP_CREATE_USERID], [APP_CREATE_TIMESTAMP], [APP_CREATE_USER_GUID], [APP_CREATE_USER_DIRECTORY], [APP_LAST_UPDATE_USERID], [APP_LAST_UPDATE_TIMESTAMP], [APP_LAST_UPDATE_USER_GUID], [APP_LAST_UPDATE_USER_DIRECTORY], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], ACTIVITY_CODE_HIST_ID, END_DATE_HIST, EFFECTIVE_DATE_HIST) + select [ACTIVITY_CODE_ID], [ACTIVITY_NUMBER], [ACTIVITY_NAME], [UNIT_OF_MEASURE], [MAINTENANCE_TYPE], [LOCATION_CODE_ID], [FEATURE_TYPE], [SP_THRESHOLD_LEVEL], [IS_SITE_NUM_REQUIRED], [ACTIVITY_APPLICATION], [END_DATE], [ROAD_CLASS_RULE], [ROAD_LENGTH_RULE], [SURFACE_TYPE_RULE], [MIN_VALUE], [MAX_VALUE], [REPORTING_FREQUENCY], [CONCURRENCY_CONTROL_NUMBER], [APP_CREATE_USERID], [APP_CREATE_TIMESTAMP], [APP_CREATE_USER_GUID], [APP_CREATE_USER_DIRECTORY], [APP_LAST_UPDATE_USERID], [APP_LAST_UPDATE_TIMESTAMP], [APP_LAST_UPDATE_USER_GUID], [APP_LAST_UPDATE_USER_DIRECTORY], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], (next value for [dbo].[HMR_ACTIVITY_CODE_H_ID_SEQ]) as [ACTIVITY_CODE_HIST_ID], null as [END_DATE_HIST], @curr_date as [EFFECTIVE_DATE_HIST] from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_CODE_LKUP_A_S_IUD_TR +PRINT N'Create trigger dbo.HMR_CODE_LKUP_A_S_IUD_TR' +GO +CREATE TRIGGER [dbo].[HMR_CODE_LKUP_A_S_IUD_TR] ON HMR_CODE_LOOKUP FOR INSERT, UPDATE, DELETE AS +SET NOCOUNT ON +BEGIN TRY +DECLARE @curr_date datetime; +SET @curr_date = getutcdate(); + IF NOT EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- historical + IF EXISTS(SELECT * FROM deleted) + update HMR_CODE_LOOKUP_HIST set END_DATE_HIST = @curr_date where CODE_LOOKUP_ID in (select CODE_LOOKUP_ID from deleted) and END_DATE_HIST is null; + + IF EXISTS(SELECT * FROM inserted) + insert into HMR_CODE_LOOKUP_HIST ([CODE_LOOKUP_ID], [CODE_SET], [CODE_NAME], [CODE_VALUE_TEXT], [CODE_VALUE_NUM], [CODE_VALUE_FORMAT], [DISPLAY_ORDER], [END_DATE], [IS_INTEGER_ONLY], [CONCURRENCY_CONTROL_NUMBER], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], CODE_LOOKUP_HIST_ID, END_DATE_HIST, EFFECTIVE_DATE_HIST) + select [CODE_LOOKUP_ID], [CODE_SET], [CODE_NAME], [CODE_VALUE_TEXT], [CODE_VALUE_NUM], [CODE_VALUE_FORMAT], [DISPLAY_ORDER], [END_DATE], [IS_INTEGER_ONLY], [CONCURRENCY_CONTROL_NUMBER], [DB_AUDIT_CREATE_USERID], [DB_AUDIT_CREATE_TIMESTAMP], [DB_AUDIT_LAST_UPDATE_USERID], [DB_AUDIT_LAST_UPDATE_TIMESTAMP], (next value for [dbo].[HMR_CODE_LOOKUP_H_ID_SEQ]) as [CODE_LOOKUP_HIST_ID], null as [END_DATE_HIST], @curr_date as [EFFECTIVE_DATE_HIST] from inserted; + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +-- Create trigger dbo.HMR_SVC_AR_ACT_I_S_U_TR +PRINT N'Create trigger dbo.HMR_SVC_AR_ACT_I_S_U_TR' +GO +CREATE TRIGGER [dbo].[HMR_SVC_AR_ACT_I_S_U_TR] ON HMR_SERVICE_AREA_ACTIVITY INSTEAD OF UPDATE AS +SET NOCOUNT ON +BEGIN TRY + IF NOT EXISTS(SELECT * FROM deleted) + RETURN; + + -- validate concurrency control + if exists (select 1 from inserted, deleted where inserted.CONCURRENCY_CONTROL_NUMBER != deleted.CONCURRENCY_CONTROL_NUMBER+1 AND inserted.SERVICE_AREA_ACTIVITY_ID = deleted.SERVICE_AREA_ACTIVITY_ID) + raiserror('CONCURRENCY FAILURE.',16,1) + + + -- update statement + update HMR_SERVICE_AREA_ACTIVITY + set "SERVICE_AREA_ACTIVITY_ID" = inserted."SERVICE_AREA_ACTIVITY_ID", + "ACTIVITY_CODE_ID" = inserted."ACTIVITY_CODE_ID", + "SERVICE_AREA_NUMBER" = inserted."SERVICE_AREA_NUMBER", + "END_DATE" = inserted."END_DATE", + "CONCURRENCY_CONTROL_NUMBER" = inserted."CONCURRENCY_CONTROL_NUMBER", + "APP_LAST_UPDATE_USERID" = inserted."APP_LAST_UPDATE_USERID", + "APP_LAST_UPDATE_TIMESTAMP" = inserted."APP_LAST_UPDATE_TIMESTAMP", + "APP_LAST_UPDATE_USER_GUID" = inserted."APP_LAST_UPDATE_USER_GUID", + "APP_LAST_UPDATE_USER_DIRECTORY" = inserted."APP_LAST_UPDATE_USER_DIRECTORY" + , DB_AUDIT_LAST_UPDATE_TIMESTAMP = getutcdate() + , DB_AUDIT_LAST_UPDATE_USERID = user_name() + from HMR_SERVICE_AREA_ACTIVITY + inner join inserted + on (HMR_SERVICE_AREA_ACTIVITY.SERVICE_AREA_ACTIVITY_ID = inserted.SERVICE_AREA_ACTIVITY_ID); + +END TRY +BEGIN CATCH + IF @@trancount > 0 ROLLBACK TRANSACTION + EXEC hmr_error_handling +END CATCH; +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO + +COMMIT TRANSACTION +GO +IF @@ERROR <> 0 SET NOEXEC ON +GO +DECLARE @Success AS BIT +SET @Success = 1 +SET NOEXEC OFF +IF (@Success = 1) PRINT 'The database update succeeded' +ELSE BEGIN + IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION + PRINT 'The database update failed' +END +GO diff --git a/database/V25.0/2_HMR_PDM-dml_SERVICE_AREA_ACTIVITY_V25_IS2.2.sql b/database/V25.0/2_HMR_PDM-dml_SERVICE_AREA_ACTIVITY_V25_IS2.2.sql new file mode 100644 index 00000000..63d3ded9 --- /dev/null +++ b/database/V25.0/2_HMR_PDM-dml_SERVICE_AREA_ACTIVITY_V25_IS2.2.sql @@ -0,0 +1,31 @@ +-- ***************************************************************************** +-- Populate the HMR_SERVICE_AREA_ACTIVITY table by assigning all service areas +-- to all activity codes by default. +-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +-- Author Date Comment +-- ------------ ----------- -------------------------------------------------- +-- Doug Filteau 2020-Oct-14 Initial version. +-- ***************************************************************************** + +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +INSERT INTO [dbo].[HMR_SERVICE_AREA_ACTIVITY] + (ACTIVITY_CODE_ID, SERVICE_AREA_NUMBER, APP_CREATE_USERID, APP_CREATE_TIMESTAMP, APP_CREATE_USER_GUID, APP_CREATE_USER_DIRECTORY, APP_LAST_UPDATE_USERID, APP_LAST_UPDATE_TIMESTAMP, APP_LAST_UPDATE_USER_GUID, APP_LAST_UPDATE_USER_DIRECTORY) + SELECT ACT.ACTIVITY_CODE_ID + , SVC.SERVICE_AREA_NUMBER + , 'sa' + , getutcdate() + , '00000001-0000-0000-0000-000000000000' + , 'WIN AUTH' + , 'sa' + , getutcdate() + , '00000001-0000-0000-0000-000000000000' + , 'WIN AUTH' + FROM [dbo].[HMR_ACTIVITY_CODE] ACT + , (SELECT SERVICE_AREA_NUMBER + FROM [dbo].[HMR_SERVICE_AREA]) SVC; +GO diff --git a/database/V25.0/3_HMR_PDM-dml_INSERT_HMR_ACTIVITY_CODE_RULE_V25_IS2.2.sql b/database/V25.0/3_HMR_PDM-dml_INSERT_HMR_ACTIVITY_CODE_RULE_V25_IS2.2.sql new file mode 100644 index 00000000..2f3dc077 --- /dev/null +++ b/database/V25.0/3_HMR_PDM-dml_INSERT_HMR_ACTIVITY_CODE_RULE_V25_IS2.2.sql @@ -0,0 +1,11 @@ +USE HMR_DEV; -- uncomment appropriate instance +--USE HMR_TST; +--USE HMR_UAT; +--USE HMR_PRD; +GO + +INSERT INTO [dbo].[HMR_ACTIVITY_CODE_RULE] + ([ACTIVITY_RULE_SET],[ACTIVITY_RULE_NAME],[ACTIVITY_RULE_EXEC_NAME],[DISPLAY_ORDER]) + VALUES + ('SURFACE_TYPE','GPS Not on Unconstructed','GPS_NOT_UNCONSTRUCTED',5) +GO \ No newline at end of file diff --git a/openshift/configmaps/api-appsettings.yaml b/openshift/configmaps/api-appsettings.yaml index 43adfbdd..a75275d9 100644 --- a/openshift/configmaps/api-appsettings.yaml +++ b/openshift/configmaps/api-appsettings.yaml @@ -9,7 +9,7 @@ objects: { "AllowedHosts": "*", "Constants": { - "Version": "1.2.6.0", + "Version": "1.3.2.0", "SwaggerApiUrl": "/swagger/v1/swagger.json" }, "Serilog": {