mirror of
https://github.com/Sea-Haven-Industries/shoc-backend.git
synced 2026-09-30 07:13:12 +00:00
198 lines
9.3 KiB
C#
198 lines
9.3 KiB
C#
using Api.SeaHavenIndustries.Helper;
|
|
using Data.SeaHavenIndustries;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.ResponseCompression;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using Microsoft.OpenApi.Models;
|
|
using System.Text;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
ConfigurationManager configuration = builder.Configuration;
|
|
|
|
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
|
|
|
|
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
|
|
{
|
|
options.User.RequireUniqueEmail = false;
|
|
})
|
|
.AddEntityFrameworkStores<ApplicationDbContext>()
|
|
.AddDefaultTokenProviders();
|
|
|
|
builder.Services.AddControllers().AddJsonOptions(options =>
|
|
{
|
|
options.JsonSerializerOptions.MaxDepth = 264; // or any other desired value
|
|
});
|
|
builder.Services.AddResponseCompression(opts =>
|
|
{
|
|
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
|
|
new[] { "application/octet-stream" });
|
|
});
|
|
builder.Services.AddCors(option =>
|
|
option.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
|
|
// Helper services
|
|
builder.Services.AddScoped<SendMessage>();
|
|
builder.Services.AddScoped<Api.SeaHavenIndustries.Helper.VendorPortalTokenService>();
|
|
builder.Services.AddSingleton<Api.SeaHavenIndustries.Helper.ZipCodeDistance>(sp =>
|
|
{
|
|
var zipService = new Api.SeaHavenIndustries.Helper.ZipCodeDistance();
|
|
var env = sp.GetRequiredService<IWebHostEnvironment>();
|
|
var csvPath = Path.Combine(env.WebRootPath, "zipcodes.csv");
|
|
if (File.Exists(csvPath)) zipService.Load(csvPath);
|
|
return zipService;
|
|
});
|
|
|
|
// ========================================================================
|
|
// MULTI-TIER ARCHITECTURE - Dependency Injection Registration
|
|
// ========================================================================
|
|
|
|
// Data Services (Data Access Layer)
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IContactDataService, SeaHaven.DataServices.Implementation.ContactDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IWorkOrderDataService, SeaHaven.DataServices.Implementation.WorkOrderDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.ILocationDataService, SeaHaven.DataServices.Implementation.LocationDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IEmployeeDataService, SeaHaven.DataServices.Implementation.EmployeeDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IAccountDataService, SeaHaven.DataServices.Implementation.AccountDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IVendorDataService, SeaHaven.DataServices.Implementation.VendorDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IDispatchDataService, SeaHaven.DataServices.Implementation.DispatchDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IFollowUpDataService, SeaHaven.DataServices.Implementation.FollowUpDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IPMScheduleDataService, SeaHaven.DataServices.Implementation.PMScheduleDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.IAssetDataService, SeaHaven.DataServices.Implementation.AssetDataService>();
|
|
builder.Services.AddScoped<SeaHaven.DataServices.Interfaces.ICategoryDataService, SeaHaven.DataServices.Implementation.CategoryDataService>();
|
|
|
|
// Business Services (Business Logic Layer) - Only register services that exist
|
|
builder.Services.AddScoped<SeaHaven.Services.Interfaces.IContactService, SeaHaven.Services.Implementation.ContactService>();
|
|
builder.Services.AddScoped<SeaHaven.Services.Interfaces.IWorkOrderService, SeaHaven.Services.Implementation.WorkOrderService>();
|
|
// TODO: Add other business services as they are implemented
|
|
// - LocationService, EmployeeService, AccountService, VendorService, DispatchService
|
|
// - FollowUpService, PMScheduleService, AssetService, CategoryService
|
|
|
|
// ========================================================================
|
|
|
|
builder.Services.AddAuthentication(options =>
|
|
{
|
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
})
|
|
.AddJwtBearer(options =>
|
|
{
|
|
options.SaveToken = true;
|
|
options.RequireHttpsMetadata = false;
|
|
options.TokenValidationParameters = new TokenValidationParameters()
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidateAudience = true,
|
|
ValidAudience = configuration["JWT:ValidAudience"],
|
|
ValidIssuer = configuration["JWT:ValidIssuer"],
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"]))
|
|
};
|
|
});
|
|
builder.Services.AddEndpointsApiExplorer();
|
|
builder.Services.AddSwaggerGen(c =>
|
|
{
|
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Seahaven", Version = "v1" });
|
|
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
|
|
{
|
|
Name = "Authorization",
|
|
Type = SecuritySchemeType.ApiKey,
|
|
Scheme = "Bearer",
|
|
BearerFormat = "JWT",
|
|
In = ParameterLocation.Header,
|
|
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
|
|
});
|
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
{
|
|
{
|
|
new OpenApiSecurityScheme
|
|
{
|
|
Reference = new OpenApiReference
|
|
{
|
|
Type = ReferenceType.SecurityScheme,
|
|
Id = "Bearer"
|
|
}
|
|
},
|
|
new string[] {}
|
|
}
|
|
});
|
|
});
|
|
|
|
var app = builder.Build();
|
|
|
|
// Configure the HTTP request pipeline.
|
|
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
|
|
{
|
|
app.UseSwagger();
|
|
app.UseSwaggerUI(c =>
|
|
{
|
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sari");
|
|
c.RoutePrefix = string.Empty;
|
|
});
|
|
}
|
|
|
|
if (!app.Environment.IsDevelopment())
|
|
app.UseHttpsRedirection();
|
|
app.UseStaticFiles();
|
|
app.UseCors();
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
|
|
app.MapControllers();
|
|
|
|
//if (app.Environment.IsDevelopment())
|
|
//{
|
|
// using var scope = app.Services.CreateScope();
|
|
// var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
|
// var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
|
|
|
// if (!await roleManager.RoleExistsAsync("Admin"))
|
|
// await roleManager.CreateAsync(new IdentityRole("Admin"));
|
|
// if (!await roleManager.RoleExistsAsync("Dispatcher"))
|
|
// await roleManager.CreateAsync(new IdentityRole("Dispatcher"));
|
|
// if (!await roleManager.RoleExistsAsync("Manager"))
|
|
// await roleManager.CreateAsync(new IdentityRole("Manager"));
|
|
|
|
// var adminEmail = "admin@seahavenind.com";
|
|
// if (await userManager.FindByNameAsync(adminEmail) == null)
|
|
// {
|
|
// var admin = new ApplicationUser
|
|
// {
|
|
// UserName = adminEmail,
|
|
// Email = adminEmail,
|
|
// FirstName = "Admin",
|
|
// LastName = "User",
|
|
// EmailConfirmed = true,
|
|
// UniqueName = "Active",
|
|
// CreatedDate = DateTime.Now
|
|
// };
|
|
// var result = await userManager.CreateAsync(admin, "Admin@123");
|
|
// if (result.Succeeded)
|
|
// await userManager.AddToRoleAsync(admin, "Admin");
|
|
// }
|
|
|
|
// var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
|
// if (!db.DropdownOptions.Any())
|
|
// {
|
|
// var trades = new[] { "Plumbing", "Electrical", "HVAC", "Fire/Life Safety", "General", "Roofing", "Janitorial", "Painting", "Locksmith", "Carpentry" };
|
|
// for (int i = 0; i < trades.Length; i++)
|
|
// db.DropdownOptions.Add(new DropdownOption { Category = "Trade", Value = trades[i], SortOrder = i });
|
|
|
|
// var subTrades = new (string trade, string sub)[] {
|
|
// ("Plumbing", "Drain Cleaning"), ("Plumbing", "Pipe Repair"), ("Plumbing", "Fixture Install"), ("Plumbing", "Backflow Testing"),
|
|
// ("Electrical", "Lighting"), ("Electrical", "Panel/Breaker"), ("Electrical", "Wiring"), ("Electrical", "Generator"),
|
|
// ("HVAC", "AC Repair"), ("HVAC", "Heating"), ("HVAC", "Ductwork"), ("HVAC", "Controls/BMS"),
|
|
// ("Fire/Life Safety", "Sprinkler"), ("Fire/Life Safety", "Fire Alarm"), ("Fire/Life Safety", "Extinguisher"), ("Fire/Life Safety", "Fire Pump"),
|
|
// ("General", "Doors"), ("General", "Flooring"), ("General", "Drywall"), ("General", "Concrete"),
|
|
// };
|
|
// for (int i = 0; i < subTrades.Length; i++)
|
|
// db.DropdownOptions.Add(new DropdownOption { Category = "SubTrade", Value = subTrades[i].sub, ParentValue = subTrades[i].trade, SortOrder = i });
|
|
|
|
// var problems = new[] { "Leak", "No Power", "Not Cooling", "Not Heating", "Clogged", "Broken/Damaged", "Alarm Fault", "Preventive Maintenance", "Inspection", "Installation", "Other" };
|
|
// for (int i = 0; i < problems.Length; i++)
|
|
// db.DropdownOptions.Add(new DropdownOption { Category = "Problem", Value = problems[i], SortOrder = i });
|
|
|
|
// await db.SaveChangesAsync();
|
|
// }
|
|
//}
|
|
|
|
app.Run();
|