mirror of
https://github.com/Sea-Haven-Industries/shoc-backend.git
synced 2026-10-01 16:53:14 +00:00
452 lines
18 KiB
C#
452 lines
18 KiB
C#
using Data.SeaHavenIndustries;
|
|
using Microsoft.AspNetCore.Components.Forms;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.WebUtilities;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using OfficeOpenXml;
|
|
using PasswordGenerator;
|
|
using SeaHavenIndustries.Data.IRepository;
|
|
using SeaHavenIndustries.Helper;
|
|
using SeaHavenIndustries.Helper.ViewModels;
|
|
using SeaHavenIndustries.ViewModel;
|
|
using System.Data;
|
|
using System.Data.OleDb;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace SeaHavenIndustries.Data.Services
|
|
{
|
|
public class AccountService:IAccountRepository
|
|
{
|
|
private readonly ApplicationDbContext _context;
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
private UserManager<ApplicationUser> _userManager;
|
|
private List<RolesViewModel> roles = new List<RolesViewModel>();
|
|
private IConfiguration _configuration;
|
|
private readonly IWebHostEnvironment _hosting;
|
|
const string uploaddocPath = "/assets/UploadexcelDocuments/";
|
|
private readonly UploadFileHp _uploadFileHelper;
|
|
private readonly SendMessage _sendemail;
|
|
|
|
public AccountService(SendMessage sendemail, ApplicationDbContext context, IHttpContextAccessor httpContextAccessor, UserManager<ApplicationUser> userManager, IConfiguration configuration,IWebHostEnvironment hosting, UploadFileHp uploadFileHelper)
|
|
{
|
|
_context = context;
|
|
_httpContextAccessor = httpContextAccessor;
|
|
_userManager = userManager;
|
|
_configuration = configuration;
|
|
_hosting = hosting;
|
|
_uploadFileHelper = uploadFileHelper;
|
|
_sendemail = sendemail;
|
|
}
|
|
public async Task<List<RolesViewModel>> GetRoles()
|
|
{
|
|
var rolesData = await _context.Roles.ToListAsync();
|
|
var rolesViewModels = rolesData.Select(role => new RolesViewModel
|
|
{
|
|
RoleName = role.Name ?? "",
|
|
Id = role.Id
|
|
}).ToList();
|
|
return rolesViewModels;
|
|
}
|
|
public async Task<IEnumerable<UserRoleViewModel>> GetUsers()
|
|
{
|
|
var allUsers = await _context.Users.ToListAsync();
|
|
var filteredUsers = new List<UserRoleViewModel>();
|
|
foreach (var user in allUsers)
|
|
{
|
|
var roles = await _userManager.GetRolesAsync(user);
|
|
if (!roles.Contains("Admin"))
|
|
{
|
|
filteredUsers.Add(new UserRoleViewModel {RoleName=roles.First(),Email=user.Email,UserName=user.FirstName, Date = user.CreatedDate.Value.Date.ToString(), Status= user.UniqueName, Id=user.Id});
|
|
}
|
|
}
|
|
return filteredUsers;
|
|
}
|
|
public async Task<IQueryable<UserRoleViewModel>> GetUsersqueryable()
|
|
{
|
|
_context.ChangeTracker.Clear();
|
|
|
|
var allUsers = _context.Users.Select(s=> new UserRoleViewModel
|
|
{
|
|
RoleName = s.PhoneNumber,
|
|
Email = s.Email,
|
|
UserName = s.FirstName,
|
|
Date = s.CreatedDate != null ? s.CreatedDate.Value.Date.ToString("MMM dd yyyy") : "",
|
|
Status = s.UniqueName,
|
|
Id = s.Id
|
|
}).AsQueryable();
|
|
//var filteredUsers = new List<UserRoleViewModel>();
|
|
|
|
//foreach (var user in allUsers)
|
|
//{
|
|
// var roles = await _userManager.GetRolesAsync(user);
|
|
|
|
// //if (!roles.Contains("Admin"))
|
|
// //{
|
|
// var userViewModel = new UserRoleViewModel
|
|
// {
|
|
// RoleName =roles.Count()>0? roles.First():"",
|
|
// Email = user.Email,
|
|
// UserName = user.FirstName,
|
|
// Date =user.CreatedDate!=null? user.CreatedDate.Value.Date.ToString("MMM dd yyyy"):"",
|
|
// Status = user.UniqueName,
|
|
// Id = user.Id
|
|
// };
|
|
// filteredUsers.Add(userViewModel);
|
|
// //}
|
|
//}
|
|
|
|
return allUsers;
|
|
}
|
|
|
|
public static string GenerateRandomPassword(int length = 8)
|
|
{
|
|
const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+=<>?";
|
|
|
|
using (var rng = RandomNumberGenerator.Create())
|
|
{
|
|
var bytes = new byte[length];
|
|
rng.GetBytes(bytes);
|
|
|
|
var charArray = validChars.ToCharArray();
|
|
for (var i = 0; i < length; i++)
|
|
{
|
|
bytes[i] %= (byte)charArray.Length;
|
|
}
|
|
|
|
return new string(bytes.Select(b => charArray[b]).ToArray());
|
|
}
|
|
}
|
|
public async Task<string> AddUser(ApplicationUser model)
|
|
{
|
|
try
|
|
{
|
|
_context.ChangeTracker.Clear();
|
|
var exist = _context.Set<ApplicationUser>().Find(model.Id);
|
|
if (exist == null)
|
|
{
|
|
model.EmailConfirmed = true;
|
|
model.UserName = model.Email;
|
|
model.CreatedDate = DateTime.Now;
|
|
model.UniqueName = "Active";
|
|
|
|
var pwd = new Password(8).IncludeLowercase().IncludeUppercase().IncludeSpecial().IncludeNumeric();
|
|
var password = pwd.Next();
|
|
|
|
|
|
//var password = GenerateRandomPassword(8);
|
|
var result = await _userManager.CreateAsync(model, password);
|
|
if (result.Succeeded)
|
|
{
|
|
await _userManager.AddToRoleAsync(model, model.PhoneNumber ?? "");
|
|
}
|
|
else
|
|
{
|
|
return result.Errors.FirstOrDefault()?.Description ?? "error";
|
|
}
|
|
var request = _httpContextAccessor.HttpContext?.Request;
|
|
var domain = $"{request?.Scheme}://{request?.Host}";
|
|
string subject = "Login Information";
|
|
string greeting = $"Dear {model.FirstName},\n\n";
|
|
string loginLink = $"Click here to login:<a href='{domain}/Login'>{domain}/Login</a>\n";
|
|
string passwordInfo = $"Your password is: {password}\n\n";
|
|
string body = $"{greeting}\n\n{loginLink}\n\n{passwordInfo}";
|
|
await _sendemail.SendEMail(model?.Email ?? "", subject, body);
|
|
}
|
|
else
|
|
{
|
|
|
|
var exist1 = await _userManager.Users.FirstAsync(w=>w.Id== model.Id);
|
|
|
|
var existingRole = await _userManager.GetRolesAsync(exist1);
|
|
|
|
// Remove from roles if any exist
|
|
if (existingRole != null && existingRole.Any() && existingRole.FirstOrDefault()!=exist1.PhoneNumber)
|
|
{
|
|
await _userManager.RemoveFromRolesAsync(exist1, existingRole);
|
|
}
|
|
|
|
// Update user details
|
|
exist1.FirstName = model.FirstName;
|
|
exist1.LastName = model.LastName;
|
|
exist1.Contact = model.Contact;
|
|
exist1.PhoneNumber = model.PhoneNumber;
|
|
|
|
// Optionally, detach the entity if you're about to attach it again
|
|
_context.Entry(exist1).State = EntityState.Detached;
|
|
|
|
// Add to role after setting properties
|
|
await _userManager.AddToRoleAsync(exist1, model.PhoneNumber ?? "");
|
|
var result = await _userManager.UpdateAsync(exist1);
|
|
//await _context.SaveChangesAsync();
|
|
}
|
|
return "success";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return ex.Message;
|
|
}
|
|
}
|
|
public async Task<ApplicationUser> GetUserById(string Id)
|
|
{
|
|
var data = await _context.Users.Where(w => w.Id == Id).FirstOrDefaultAsync();
|
|
return data ?? new ApplicationUser();
|
|
}
|
|
public async Task<string> BlockUser(string id)
|
|
{
|
|
_context.ChangeTracker.Clear();
|
|
|
|
try
|
|
{
|
|
var data = await _context.Users.Where(w => w.Id == id).FirstOrDefaultAsync();
|
|
if(data != null)
|
|
{
|
|
var existworkorder=_context.workOrders.Where(w=>w.AssignTo.Contains(data.Id)).ToList();
|
|
foreach(var workorder in existworkorder)
|
|
{
|
|
var existdata=_context.workOrders.Where(w=>w.Id==workorder.Id).FirstOrDefault();
|
|
existdata.AssignTo = null;
|
|
}
|
|
var existworkordercomments=_context.Comments.Where(w=>w.UserId.Contains(data.Id)).ToList();
|
|
foreach(var workorderc in existworkordercomments)
|
|
{
|
|
var existdatacomm=_context.Comments.Where(w=>w.Id==workorderc.Id).FirstOrDefault();
|
|
existdatacomm.UserId = null;
|
|
}
|
|
var existtemplate=_context.Templates.Where(w=>w.AssignTo.Contains(data.Id)).ToList();
|
|
foreach(var workordert in existtemplate)
|
|
{
|
|
var existdattem=_context.Templates.Where(w=>w.Id==workordert.Id).FirstOrDefault();
|
|
existdattem.AssignTo = null;
|
|
}
|
|
var existtempexistuserrolelate=_context.UserRoles.Where(w=>w.UserId.Contains(data.Id)).ToList();
|
|
if(existtempexistuserrolelate.Count()>0)
|
|
{
|
|
_context.UserRoles.RemoveRange(existtempexistuserrolelate);
|
|
}
|
|
_context.Users.Remove(data);
|
|
}
|
|
_context.SaveChanges();
|
|
return "success";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return ex.Message;
|
|
}
|
|
}
|
|
public async Task<IEnumerable<Locations>> GetLocations()
|
|
{
|
|
var data = await _context.Locations.ToListAsync();
|
|
return data;
|
|
}
|
|
public async Task<IQueryable<Locations>> GetLocationsiqueryable()
|
|
{
|
|
var data = _context.Locations; // Assuming _context.Locations is already IQueryable<Locations>
|
|
return data;
|
|
}
|
|
public async Task<List<Locations>> SearchLocations()
|
|
{
|
|
var data = await _context.Locations.ToListAsync();
|
|
return data;
|
|
}
|
|
public async Task<string> AddLocation(Locations model)
|
|
{
|
|
_context.ChangeTracker.Clear();
|
|
|
|
try
|
|
{
|
|
var exist=_context.Locations.Where(w=>w.Id==model.Id).FirstOrDefault();
|
|
if(exist != null)
|
|
{
|
|
exist.Title=model.Title;
|
|
exist.Name=model.Name;
|
|
_context.Update(exist);
|
|
|
|
}
|
|
else
|
|
{
|
|
await _context.Locations.AddAsync(model);
|
|
}
|
|
await _context.SaveChangesAsync();
|
|
return "success";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return ex.Message;
|
|
}
|
|
}
|
|
public async Task<string> ImportLocation(IBrowserFile model)
|
|
{
|
|
using (var transaction = _context.Database.BeginTransaction())
|
|
{
|
|
try
|
|
{
|
|
var file = model;
|
|
string path = await Documentupload(file);
|
|
List<DataTable> sheetDataTables = ClassesDataTable(path);
|
|
foreach (var dt in sheetDataTables)
|
|
{
|
|
string sheetName = dt.TableName;
|
|
|
|
for (int i = 0; i < dt.Rows.Count; i++)
|
|
{
|
|
var sitename = dt.Rows[i][0];
|
|
var address = dt.Rows[i][1];
|
|
//var city = dt.Rows[i][2];
|
|
//var state = dt.Rows[i][3];
|
|
sitename = sitename;
|
|
var existbank = _context.Locations.Where(w => w.Title.ToLower() == sitename.ToString().ToLower()).FirstOrDefault();
|
|
if (existbank != null)
|
|
{
|
|
continue;
|
|
}
|
|
else
|
|
{
|
|
Locations locations = new Locations();
|
|
locations.Title = sitename.ToString();
|
|
locations.Name = address.ToString();
|
|
_context.Locations.Add(locations);
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
transaction.Commit();
|
|
return "success";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
transaction.Rollback();
|
|
return ex.Message;
|
|
}
|
|
|
|
}
|
|
}
|
|
public List<DataTable> ClassesDataTable(string path)
|
|
{
|
|
List<DataTable> dataTables = new List<DataTable>();
|
|
|
|
using (var package = new ExcelPackage(new FileInfo(path)))
|
|
{
|
|
foreach (var worksheet in package.Workbook.Worksheets)
|
|
{
|
|
DataTable dataTable = new DataTable(worksheet.Name);
|
|
|
|
foreach (var cell in worksheet.Cells["A1:AZ1"]) // Adjust the range as needed
|
|
{
|
|
dataTable.Columns.Add(cell.Text);
|
|
}
|
|
|
|
for (int row = 2; row <= worksheet.Dimension.End.Row; row++)
|
|
{
|
|
DataRow dataRow = dataTable.NewRow();
|
|
|
|
for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
|
|
{
|
|
dataRow[col - 1] = worksheet.Cells[row, col].Text;
|
|
}
|
|
|
|
dataTable.Rows.Add(dataRow);
|
|
}
|
|
|
|
dataTables.Add(dataTable);
|
|
}
|
|
}
|
|
|
|
return dataTables;
|
|
}
|
|
//public List<DataTable> ClassesDataTable(string path)
|
|
//{
|
|
// List<DataTable> dataTables = new List<DataTable>();
|
|
// var constr = _configuration.GetConnectionString("excelconnection");
|
|
|
|
// constr = string.Format(constr, path);
|
|
// using (OleDbConnection excelconn = new OleDbConnection(constr))
|
|
// {
|
|
// excelconn.Open();
|
|
// DataTable excelschema = excelconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
|
|
|
|
// foreach (DataRow row in excelschema.Rows)
|
|
// {
|
|
// string sheetName = row[2].ToString();
|
|
|
|
// using (OleDbCommand cmd = new OleDbCommand())
|
|
// {
|
|
// using (OleDbDataAdapter adapterexcel = new OleDbDataAdapter())
|
|
// {
|
|
// cmd.Connection = excelconn;
|
|
// cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
|
|
// DataTable datatable = new DataTable(sheetName); // Create a DataTable for each sheet
|
|
// adapterexcel.SelectCommand = cmd;
|
|
// adapterexcel.Fill(datatable);
|
|
// //return dataTables;
|
|
// dataTables.Add(datatable); // Add the DataTable to the list
|
|
// }
|
|
// }
|
|
// }
|
|
// }
|
|
// return dataTables;
|
|
//}
|
|
public async Task<string> Documentupload(IBrowserFile fromFiles)
|
|
{
|
|
string uploadpath = _hosting.WebRootPath;
|
|
string dest_path = uploadpath + uploaddocPath;
|
|
|
|
if (!Directory.Exists(dest_path))
|
|
{
|
|
Directory.CreateDirectory(dest_path);
|
|
}
|
|
//string sourcefile = Path.GetFileName(fromFiles);
|
|
string path = dest_path + fromFiles.Name;
|
|
using (FileStream filestream = new FileStream(path, FileMode.Create))
|
|
{
|
|
//fromFiles.CopyTo(filestream);
|
|
}
|
|
//Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
|
|
// Copy the file to the server
|
|
using (var fileStream = new FileStream(path, FileMode.Create))
|
|
{
|
|
await fromFiles.OpenReadStream(int.MaxValue).CopyToAsync(fileStream);
|
|
}
|
|
return path;
|
|
}
|
|
|
|
public async Task<Locations> GetLocationById(int Id)
|
|
{
|
|
var data = await _context.Locations.Where(w => w.Id == Id).FirstOrDefaultAsync();
|
|
return data ?? new Locations();
|
|
}
|
|
public async Task<string> DeleteLocation(int Id)
|
|
{
|
|
_context.ChangeTracker.Clear();
|
|
|
|
try
|
|
{
|
|
var data1 = await _context.Templates.ToListAsync();
|
|
_context.Templates.RemoveRange(data1);
|
|
var data = await _context.Locations.Where(w => w.Id==Id).ToListAsync();
|
|
_context.Locations.RemoveRange(data);
|
|
_context.SaveChanges();
|
|
return "success";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return ex.Message;
|
|
}
|
|
}
|
|
public async Task<string> tests3(IBrowserFile fileContent)
|
|
{
|
|
|
|
try
|
|
{
|
|
//var getpath= _uploadFileHelper.UploadFileAsync(fileContent);
|
|
return "success";
|
|
}
|
|
catch(Exception ex)
|
|
{
|
|
return ex.Message;
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|