put in ignore file

This commit is contained in:
2025-08-10 22:01:36 +10:00
parent c2bf5cad70
commit ba79e8f1c4
151 changed files with 21703 additions and 0 deletions
+53
View File
@@ -0,0 +1,53 @@
using System.Net.Mail;
namespace FamilyTreeAPI.Repository
{
public class Email
{
public static void SendMail(string smtpServer, string sender, string sendTo,
string header, string message, bool mailPriority = false)
{
if (string.IsNullOrEmpty(smtpServer) && string.IsNullOrEmpty(sender) && string.IsNullOrEmpty(sendTo))
return;
System.Net.Mail.SmtpClient client = new SmtpClient(smtpServer);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(sender);
var splitEmails = sendTo.Split(';');
foreach (string item in splitEmails)
{
mailMessage.To.Add(item);
}
if (mailPriority)
mailMessage.Priority = MailPriority.High;
// mailMessage.To.Add(sendTo);
mailMessage.Subject = header;
string text = message;
string signature = "";
try
{
text += "<br/>" + signature;
mailMessage.Body = text;
mailMessage.IsBodyHtml = true;
}
catch //(Exception ex)
{
// ErrorLogger.logError(ex, "CPA");
throw;
}
try
{
string userState = "send to fleet manager";
client.SendAsync(mailMessage, userState);
}
catch //(Exception ex)
{
throw;
}
}
}
}
@@ -0,0 +1,278 @@
using FamilyTreeAPI.Entities;
using FamilyTreeAPI.Interface;
using FamilyTreeAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace FamilyTreeAPI.Repository
{
public class LookupRepository: ILookup
{
private readonly FamilyTreeDBContext _context;
public LookupRepository(FamilyTreeDBContext context)
{
_context = context;
}
private bool checkDescription(string desc, string type, int id)
{
bool result = false;
if (!string.IsNullOrEmpty(desc))
{
string ldesc = desc.ToLower();
int count = _context.Lookups.Where(x => (x.Code ?? "").ToLower() == ldesc
&& id != x.Id
).ToList().Count();
result = count > 0;
}
return result;
}
public async Task<ResultModel<int>> SaveLookupAsync(LookupEditDto lookup)
{
int result = -1;
int statusCode = 0;
string desc = lookup.Description.Trim();
string error = "";
try
{
Lookup model = null!;
bool ok = !checkDescription(desc, lookup.Type, lookup.Id);
if (ok)
{
if (lookup.Id < 1)
{
model = new();
model.Code = lookup.CodeId;
model.Description = desc;
model.Type = lookup.Type;
model.Lactive = lookup.Active;
_context.Lookups.Add(model);
}
else
{
Lookup? model1 = await _context.Lookups.FindAsync(lookup.Id);
if (model1 != null)
{
model1.Description = desc;
model1.Code = lookup.CodeId;
model1.Lactive = lookup.Active;
}
}
await _context.SaveChangesAsync();
if (model != null)
result = model.Id;
statusCode = 1;
}
else
{
statusCode = 0;
error = "description is already in database";
}
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<int>()
{
Data = result,
StatusCode = statusCode,
Message = error
};
}
public async Task<ResultModel<LookupEditDto>> GetLookupEditByIdAsync(int id, string type)
{
List<LookupEditDto> resultList;
LookupEditDto item = null!;
int statusCode = 0;
string error = "";
try
{
resultList = await _context.Lookups.Where(x => x.Type == type
&& (x.Id == id))
.Select(item => new LookupEditDto
{
CodeId = string.IsNullOrEmpty(item.Code) ? "0": item.Code,
Active = item.Lactive ?? false,
Id = item.Id,
Description = item.Description ?? ""
})
.ToListAsync();
if (resultList.Count > 0)
item = resultList[0];
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<LookupEditDto>()
{
Data = item,
StatusCode = statusCode,
Message = error
};
}
public async Task<ResultModel<List<LookupDto>>> GetLookupAsync(string type)
{
List<LookupDto> resultList = new();
int statusCode = 0;
string error = "";
try
{
resultList = await _context.Lookups.Where(x => x.Type == type && ((x.Lactive ?? false) == true))
.Select(item => new LookupDto { Id = item.Id, CodeId = item.Code ?? "", Description = item.Description ?? "" })
.ToListAsync();
resultList.Sort((x, y) => x.Description.CompareTo(y.Description));
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<List<LookupDto>>()
{
Data = resultList,
StatusCode = statusCode,
Message = error
};
}
public async Task<ResultModel<Dictionary<string, LookupDto>>> GetLookupDicAsync(string type)
{
Dictionary<string, LookupDto> resultList = new();
int statusCode = 0;
string error = "";
try
{
resultList = await _context.Lookups.Where(x => x.Type == type && ((x.Lactive ?? false) == true))
.Select(item => new LookupDto { Id = item.Id, CodeId = item.Code ?? "", Description = item.Description ?? "" })
.ToDictionaryAsync(x => x.CodeId);
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<Dictionary<string, LookupDto>>()
{
Data = resultList,
StatusCode = statusCode,
Message = error
};
}
public async Task<ResultModel<List<LookupEditDto>>> GetLookupEditAsync(string type)
{
List<LookupEditDto> resultList = new();
int statusCode = 0;
string error = "";
try
{
resultList = await _context.Lookups.Where(x => x.Type == type)
.Select(item => new LookupEditDto
{
Id = item.Id,
Active = item.Lactive ?? false,
CodeId = item.Code ?? "",
Type = item.Type ?? "",
Description = item.Description ?? ""
})
.ToListAsync();
resultList.Sort((x, y) => x.Description.CompareTo(y.Description));
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<List<LookupEditDto>>()
{
Data = resultList,
StatusCode = statusCode,
Message = error
};
}
public async Task<ResultModel<List<LookupDto>>> GetPersonsAsync()
{
List<LookupDto> resultList = new();
int statusCode = 0;
string error = "";
try
{
resultList = await _context.Persons.Where(x => x.Alive == true)
.Select(item => new LookupDto { Id = item.Id, CodeId = item.Id.ToString(), Description = item.FirstName ?? "" })
.ToListAsync();
resultList.Sort((x, y) => x.Description.CompareTo(y.Description));
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<List<LookupDto>>()
{
Data = resultList,
StatusCode = statusCode,
Message = error
};
}
public async Task<ResultModel<List<LookupDto>>> GetStaffAsync()
{
List<LookupDto> resultList = new();
int statusCode = 0;
string error = "";
try
{
resultList = await _context.staff.Where(x => x.Sactive == true)
.Select(item => new LookupDto { Id = item.Id, CodeId = item.Firstname ?? "", Description = item.Lastname ?? "" })
.ToListAsync();
resultList.Sort((x, y) => x.Description.CompareTo(y.Description));
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<List<LookupDto>>()
{
Data = resultList,
StatusCode = statusCode,
Message = error
};
}
}
}
@@ -0,0 +1,657 @@
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Office.CustomUI;
using DocumentFormat.OpenXml.Office2010.Excel;
using FamilyTreeAPI.Entities;
using FamilyTreeAPI.Helper;
using FamilyTreeAPI.Interface;
using FamilyTreeAPI.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
namespace FamilyTreeAPI.Repository;
public partial class PersonRepository : IPerson
{
private readonly FamilyTreeDBContext _context;
private readonly IRelationShipd _relationship;
private readonly IHttpContextAccessor _httpContext;
private readonly IConfiguration _config;
const string dateFormat = "yyyy-MM-dd";
public PersonRepository(IConfiguration config, FamilyTreeDBContext context,
IRelationShipd relationship,
IHttpContextAccessor httpContext)
{
_context = context;
_relationship = relationship;
_config = config;
_httpContext = httpContext;
}
private PersonDto FillDto(Person model)
{
PersonDto dto = new();
dto.Id = model.Id;
dto.FirstName = model.FirstName;
dto.LastName = model.LastName;
dto.Email = model.Email;
dto.Address = model.Address;
dto.Phone = model.Phone;
dto.Alive = model.Alive;
dto.Image = model.Image;
dto.FatherId = model.FatherId;
dto.MotherId = model.MotherId;
dto.Sex = model.Sex;
dto.dob = Helpers.DateToStr(model.dob);
/*
dto.AddedOn = model.AddedOn;
dto.RoleType = model.RoleType;
*/
return dto;
}
private Person FillModel(Person model, PersonDto dto)
{
model.FirstName = dto.FirstName;
model.LastName = dto.LastName;
model.Email = dto.Email;
model.Address = dto.Address;
model.Phone = dto.Phone;
model.Alive = dto.Alive;
model.Image = dto.Image;
model.FatherId = dto.FatherId;
model.MotherId = dto.MotherId;
model.Sex = dto.Sex;
model.dob = Helpers.DateToDateTime(dto.dob);
return model;
}
public async Task<ResultModel<Dictionary<int, PersonDto>>> GetDicFamily()
{
Dictionary<int, PersonDto> list = new();
int statuscode = 0;
string error = "";
PersonDto item;
Person jitem;
try
{
//list = await _context.LoadStaffAsync(criteria);
var jlist = await _context.Persons.ToListAsync();
for (int i = 0; i < jlist.Count; i++)
{
jitem = jlist[i];
item = FillDto(jitem);
list.Add(item.Id,item);
}
statuscode = 1;
//list.Sort((x, y) => x.Code.CompareTo(y.Code));
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel< Dictionary<int, PersonDto> > ()
{
Data = list,
StatusCode = statuscode,
Message = error
};
}
private async Task<List<PersonDto>> GetChildrens(int FatherId, int MotherId)
{
List<PersonDto> list = new();
PersonDto item;
Person jitem;
var jlist = await _context.Persons.Where(x =>
(x.MotherId == FatherId && x.FatherId == MotherId) ||
(x.FatherId == FatherId && x.MotherId == MotherId)).ToListAsync();
for (int i = 0; i < jlist.Count; i++)
{
jitem = jlist[i];
item = FillDto(jitem);
list.Add(item);
}
return list;
}
public async Task<ResultModel<List<PersonDto>>> GetChildren(ChildCriteria criteria)
{
List<PersonDto> list = new();
int statuscode = 0;
string error = "";
PersonDto item;
Person jitem;
try
{
//list = await _context.LoadStaffAsync(criteria);
list = await GetChildrens(criteria.FatherId, criteria.MotherId);
statuscode = 1;
//list.Sort((x, y) => x.Code.CompareTo(y.Code));
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel<List<PersonDto>>()
{
Data = list,
StatusCode = statuscode,
Message = error
};
}
public async Task<ResultModel<List<PersonDto>>> GetPerson(PersonCriteria criteria)
{
List<PersonDto> list = new();
List<Person>? jlist;
int statuscode = 0;
string error = "";
PersonDto item;
Person jitem;
string firstName = criteria.FirstName;
string lastName = criteria.LastName;
int Id = criteria.Id;
try
{
//list = await _context.LoadStaffAsync(criteria);
if (!string.IsNullOrEmpty(firstName))
{
firstName = firstName.ToLower();
jlist = await _context.Persons.Where(x =>
EF.Functions.Like(x.FirstName.ToLower(),firstName + "%")).ToListAsync();
}
else if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName))
{
firstName = firstName.ToLower();
lastName = lastName.ToLower();
jlist = await _context.Persons.Where(x => EF.Functions.Like(x.FirstName.ToLower(),firstName + "%")
&& EF.Functions.Like(x.LastName.ToLower(),lastName + "%")).ToListAsync();
}
else
jlist = await _context.Persons.ToListAsync();
for (int i = 0; i < jlist.Count; i++)
{
jitem = jlist[i];
item = FillDto(jitem);
list.Add(item);
}
statuscode = 1;
//list.Sort((x, y) => x.Code.CompareTo(y.Code));
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel<List<PersonDto>>()
{
Data = list,
StatusCode = statuscode,
Message = error
};
}
private async Task<Person> GetPerson(int id)
{
Person rval = await _context.Persons.FindAsync(id);
return rval;
}
public async Task<ResultModel<TreeNode<string>>> GetByFamilyAsync(int id)
{
int statuscode = 0;
string error = "";
string key = "";
string data = "";
string type = "default";
string pName = "";
Person person;
TreeNode<string> citem;
TreeNode<string> child;
TreeNode<string> node = new();
node.Children = new();
PersonDto dto = new();
try
{
var item = await _context.Persons.FindAsync(id);
if (item == null)
{
statuscode = -1;
}
else
{
node.Label = item.FirstName;
node.Key = item.Id.ToString();
node.Type = type;
node.Expanded = true;
node.Data = item.Sex;
statuscode = 1;
dto = FillDto(item);
await GetPartnerChildrens(dto, node);
}
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel<TreeNode<string>> ()
{
Data = node,
StatusCode = statuscode,
Message = error
};
}
private async Task GetPartnerChildrens(PersonDto person, TreeNode<string> node)
{
/*****************************/
ResultModel<List<RelationShipDto>> rlist = await _relationship.GetByPersonIdAsync(person.Id);
List<RelationShipDto> relationShips = rlist.Data;
RelationShipDto relate;
string type = node.Type;
TreeNode<string> child;
PersonDto dto;
Person pe;
int fatherId, motherId;
fatherId = motherId = 0;
string data = person.Sex;
TreeNode<string> citem;
string pName = "";
string key = "";
for (int i = 0; i < relationShips.Count; i++)
{
relate = relationShips[i];
if (relate.PersonId == person.Id)
{
if (data == "M")
{
fatherId = relate.PersonId;
motherId = relate.RelatePersonId;
}
else
{
fatherId = relate.RelatePersonId;
motherId = relate.PersonId;
}
}
else
{
if (data == "M")
{
fatherId = relate.PersonId;
motherId = relate.RelatePersonId;
}
else
{
fatherId = relate.RelatePersonId;
motherId = relate.PersonId;
}
}
//get children
List<PersonDto> children = await GetChildrens(fatherId, motherId);
if (children.Count > 0)
{
if (person.Id != motherId)
{
//kham
if (motherId > 0)
{
pe = await GetPerson(motherId);
pName = pe.FirstName;
key = motherId.ToString();
data = "F";
}
}
else
{
if (fatherId > 0)
{
pe = await GetPerson(fatherId);
pName = pe.FirstName;
key = fatherId.ToString();
data = "M";
}
}
citem = new TreeNode<string>();
citem.Label = pName;
citem.Expanded = true;
citem.Data = data;
citem.Type = type;
citem.Key = key;
citem.Children = new List<TreeNode<string>>();
node.Children.Add(citem);
for (int j = 0; j < children.Count; j++)
{
dto = children[j];
child = new TreeNode<string>();
child.Expanded = true;
child.Type = type;
child.Label = dto.FirstName;
child.Key = dto.Id.ToString();
child.Data = dto.Sex;
child.Children = new();
citem.Children.Add(child);
//get child partner and repeat this.
await GetPartnerChildrens(dto, child);
}
}
}
/*****************************************/
}
public async Task<ResultModel<PersonDto>> GetByIdAsync(int id)
{
int statuscode = 0;
string error = "";
PersonDto dto = new();
try
{
var item = await _context.Persons.FindAsync(id);
if (item == null)
{
statuscode = -1;
}
else
{
dto = FillDto(item);
statuscode = 1;
ResultModel<List<RelationShipDto>> rlist = await _relationship.GetByPersonIdAsync(dto.Id);
dto.RelationShips = rlist.Data;
statuscode = rlist.StatusCode;
error = rlist.Message;
}
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel<PersonDto>()
{
Data = dto,
StatusCode = statuscode,
Message = error
};
}
private string GetDateTimeNow()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
/// <summary>
/// need filename to get extension file and family name for id combine to
/// name to table.
/// </summary>
/// <param name="fileName"></param>
/// <param name="familyId"></param>
/// <param name="base64"></param>
private string SaveFile(string fileName, int familyId, string base64)
{
string path = "";
int statusCode = 0;
string error = "";
string sdate = GetCurrentDateTime();
string filename, extention;
filename = extention = "";
int first = base64.IndexOf("base64,") +"base64,".Length;
int last = base64.Length;
string rbase = base64.Substring(first, last - first);
byte[] newBytes = Convert.FromBase64String(rbase);
path = _config["AppSettings:ImageFolder"];
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
extention = System.IO.Path.GetExtension(fileName);
filename = familyId + "_" + sdate + extention;
string fullpath = System.IO.Path.Combine(path, filename);
/*
using (var fileStream = new FileStream(fullpath, FileMode.Create))
{
StreamWriter writer = new StreamWriter(fileStream);
writer.Write(newBytes);
//writer.BaseStream.Write(bytes, 0, bytes.Length);
}
*/
using (MemoryStream ms = new MemoryStream(newBytes))
{
Image image = Image.FromStream(ms);
image.Save(fullpath);
}
return filename;
}
public async Task<ResultModel<int>> SaveAsync(PersonForSave container)
{
int result = default(int);
int statuscode = 0;
string error = "";
HttpContext? httpContext = _httpContext.HttpContext;
string loginName = "";
if (httpContext != null)
{
UserDto? user = (UserDto?)httpContext.Items["User"];
if (user != null)
loginName = user.FirstName + " " + user.LastName;
}
PersonDto item = container.Person;
try
{
Person model;
if (item.Id < 1)
{
model = new();
model = FillModel(model, item);
// model.Active = true;
// model.AddedBy = loginName;
// model.AddedOn = DateTime.Now;
_context.Persons.Add(model);
var successid = await _context.SaveChangesAsync();
result = model.Id;
if (!string.IsNullOrEmpty(container.FileName))
{
string image = SaveFile(container.FileName, result, container.FormData);
// update the image in table to new
model.Image = image;
await _context.SaveChangesAsync();
}
}
else
{
var model1 = await _context.Persons.FindAsync(item.Id);
if (model1 != null)
{
model1 = FillModel(model1, item);
result = item.Id;
if (!string.IsNullOrEmpty(container.FileName))
{
string image = SaveFile(container.FileName, result, container.FormData);
// update the image in table to new
model1.Image = image;
}
var successid = await _context.SaveChangesAsync();
}
// model.LastModified = DateTime.Now;
// model.LastModifiedId = loginName;
}
statuscode = 1;
if (item.RelationShips != null)
{
ResultModel<int> rresult = await this._relationship.SaveAsync(item.RelationShips);
statuscode = rresult.StatusCode;
error += rresult.Message;
}
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
//var dto = await Task.Run(() => result);
return new ResultModel<int>()
{
Data = result,
StatusCode = statuscode,
Message = error
};
}
public async Task<ResultModel<int>> DeleteAsync(int id)
{
int result = 1;
int statuscode = 0;
string error = "";
try
{
var model = await _context.Persons.FindAsync(id);
if (model != null)
_context.Persons.Remove(model);
var successCount = await _context.SaveChangesAsync();
statuscode = 1;
result = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
//var dto = await Task.Run(() => result);
return new ResultModel<int>()
{
Data = result,
StatusCode = statuscode,
Message = error
};
}
public Task<ResultModel<string>> UploadImage(UploadCriteria criteria) {
return UploadImagep(criteria);
}
private string GetCurrentDateTime()
{
DateTime now = DateTime.Now;
return now.ToString("yyyyMMdd");
}
private async Task<ResultModel<string>> UploadImagep(UploadCriteria criteria)
{
string path = "";
int statusCode = 0;
string error = "";
string sdate = GetCurrentDateTime();
string filename, extention;
filename = extention = "";
try
{
if (criteria.File.Length > 0)
{
path = _config["AppSettings:ImageFolder"];
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
extention = System.IO.Path.GetExtension(criteria.FileName);
filename = criteria.FamilyId + "_" + sdate + extention;
using (var fileStream = new FileStream(System.IO.Path.Combine(path, filename), FileMode.Create))
{
await criteria.File.CopyToAsync(fileStream);
}
statusCode = 1;
}
else
{
statusCode = -1;
error = "file contain is empty";
}
}
catch (Exception ex)
{
statusCode = -1;
error = ex.Message;
}
return new ResultModel<string>()
{
Data = filename,
StatusCode = statusCode,
Message = error
};
}
public ResultModel<int> DeleteUploadFile(DeleteFileCriteria criteria)
{
int result = -1;
int statusCode = 0;
string error = "";
var filePath = _config["AppSettings:ImageFolder"];
var myfile = filePath + "\\" + criteria.Filename;
try
{
File.Delete(myfile);
result = 1;
statusCode = 1;
Person? model = _context.Persons.Find(criteria.FamilyId);
if (model != null)
{
model.Image = null;
_context.SaveChanges();
}
}
catch (Exception e)
{
result = -1;
statusCode = -1;
error += e.Message;
}
return new ResultModel<int>()
{
Data = result,
StatusCode = statusCode,
Message = error
};
}
}
@@ -0,0 +1,139 @@
using FamilyTreeAPI.Entities;
using FamilyTreeAPI.Models;
using Microsoft.EntityFrameworkCore;
using System.Drawing.Text;
namespace FamilyTreeAPI.Repository;
public partial class PersonRepository
{
private TreeNode<string> PopulateItem(Person model)
{
TreeNode<string> treeNode = new();
treeNode.Label = model.FirstName;
treeNode.Data = model.Id.ToString();
treeNode.Key = model.Id.ToString();
treeNode.Children = new();
return treeNode;
}
private bool UseFamilyCriteria(FamilyCriteria criteria, Person person)
{
bool result = false;
if (criteria.UseFather && criteria.UseMother)
{
result = person.FatherId.GetValueOrDefault(0) == 0
&& person.MotherId.GetValueOrDefault(0) == 0;
}
else if (criteria.UseFather)
{
result = person.FatherId.GetValueOrDefault(0) == 0;
}
else if (criteria.UseMother)
{
result = person.MotherId.GetValueOrDefault(0) == 0;
}
return result;
}
private bool UseChildFamilyCriteria(FamilyCriteria criteria, int id, Person person)
{
bool result = false;
int parentId;
if (criteria.UseFather)
{
parentId = person.FatherId.GetValueOrDefault(0);
result = parentId == id;
}
else if (criteria.UseMother)
{
parentId = person.MotherId.GetValueOrDefault(0);
result = parentId == id;
}
return result;
}
private List<Person> SplitListOfTopLevel(List<Person> list, FamilyCriteria criteria)
{
List<Person> result = new();
Person item;
for (int i = list.Count - 1; i > -1; i--)
{
item = list[i];
if (UseFamilyCriteria(criteria,item))
{
result.Add(item);
list.RemoveAt(i);
}
}
return result;
}
private List<Person> GetParentId(List<Person> list,int id, FamilyCriteria criteria, Func<FamilyCriteria, int, Person, bool> conditionFn)
{
List<Person> result = new();
Person item;
for (int i = list.Count - 1; i > -1; i--)
{
item = list[i];
if (conditionFn(criteria,id, item))
{
result.Add(item);
list.RemoveAt(i);
}
}
return result;
}
private List<TreeNode<string>> PopulateChild(FamilyCriteria criteria,int id, List<Person> childList, Func<FamilyCriteria, int ,Person,bool> conditionFn)
{
Person person;
TreeNode<string> treeNode;
List<TreeNode<string>> list = new();
List<Person> children = GetParentId(childList,id, criteria, conditionFn);
for (int i = 0; i < children.Count; i++)
{
person = children[i];
treeNode = PopulateItem(person);
list.Add(treeNode);
// get children of this one too
treeNode.Children = PopulateChild(criteria, person.Id, childList, UseChildFamilyCriteria);
}
return list;
}
public async Task<ResultModel<List<TreeNode<string>>> > GetFamilyTreeBy(FamilyCriteria criteria)
{
int statusCode = -1;
string error = "";
Person person;
TreeNode<string> treeNode;
List<TreeNode<string>> data = new();
try
{
var personList = await _context.Persons.ToListAsync();
var topList = SplitListOfTopLevel(personList, criteria);
for (int i = 0; i < topList.Count; i++)
{
person = topList[i];
treeNode = PopulateItem(person);
data.Add(treeNode);
treeNode.Children = PopulateChild(criteria, person.Id, personList, UseChildFamilyCriteria);
}
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<List<TreeNode<string>>>
{
Data = data,
StatusCode = statusCode,
Message = error
};
}
}
@@ -0,0 +1,184 @@
using FamilyTreeAPI.Entities;
using FamilyTreeAPI.Interface;
using FamilyTreeAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace FamilyTreeAPI.Repository;
public class RelationShipRepository: IRelationShipd
{
private readonly FamilyTreeDBContext _context;
private readonly IHttpContextAccessor _httpContext;
private readonly IConfiguration _config;
public RelationShipRepository(IConfiguration config, FamilyTreeDBContext context, IHttpContextAccessor httpContext)
{
_context = context;
_config = config;
_httpContext = httpContext;
}
private RelationShip FillModel(RelationShipDto dto, RelationShip model)
{
model.RelatePersonId = dto.RelatePersonId;
model.PersonId = dto.PersonId;
return model;
}
private RelationShipDto FillDto(RelationShip model)
{
RelationShipDto dto = new();
dto.Id = model.Id;
dto.PersonId = model.PersonId;
dto.RelatePersonId = model.RelatePersonId;
return dto;
}
public async Task<ResultModel<int>> SaveAsync(List<RelationShipDto> list)
{
int statusCode = 0;
string error = "";
RelationShipDto item;
RelationShip model;
try
{
for (int i = 0; i < list.Count; i++)
{
item = list[i];
if (item.Id < 1)
{
model = new();
model = FillModel(item, model);
_context.RelationShips.Add(model);
}
else if (item.State == enumState.Modify)
{
RelationShip? RelationShip = await _context.RelationShips.FindAsync(item.Id);
if (RelationShip != null)
{
RelationShip = FillModel(item, RelationShip);
}
}
else if (item.State == enumState.Delete)
{
RelationShip? RelationShip = await _context.RelationShips.FindAsync(item.Id);
if (RelationShip != null)
{
_context.RelationShips.Remove(RelationShip);
}
}
}
statusCode = 1;
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<int>
{
StatusCode = statusCode,
Data = statusCode,
Message = error
};
}
public async Task<ResultModel<List<RelationShipDto>>> GetByPersonIdAsync(int personId)
{
string error = "";
int statusCode = -1;
List<RelationShipDto> list = new();
RelationShipDto dto;
RelationShip model;
try
{
var mlist = await _context.RelationShips.Where(x => x.PersonId == personId).ToListAsync();
for (int i = 0; i < mlist.Count; i++)
{
model = mlist[i];
dto = FillDto(model);
list.Add(dto);
}
var rlist = await _context.RelationShips.Where(x => x.RelatePersonId == personId).ToListAsync();
for (int i = 0; i < rlist.Count; i++)
{
model = rlist[i];
dto = FillDto(model);
list.Add(dto);
}
statusCode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<List<RelationShipDto>>
{
StatusCode = statusCode,
Data = list,
Message = error
};
}
public async Task<ResultModel<RelationShipDto>> GetByIdAsync(int Id)
{
string error = "";
int statusCode = -1;
RelationShipDto dto =new();
RelationShip? model;
try
{
model = await _context.RelationShips.FindAsync(Id);
if (model != null)
dto = FillDto(model);
}
catch (Exception ex)
{
error = ex.ToString();
statusCode = -1;
}
return new ResultModel<RelationShipDto>
{
StatusCode = statusCode,
Data = dto,
Message = error
};
}
public async Task<ResultModel<int>> DeleteAsync(int Id)
{
int result = -1;
string error = "";
int statusCode = -1;
try
{
RelationShip? RelationShip = await _context.RelationShips.FindAsync(Id);
if (RelationShip != null)
{
_context.RelationShips.Remove(RelationShip);
}
}
catch (Exception e)
{
error = e.ToString();
statusCode = -1;
}
return new ResultModel<int>
{
StatusCode = statusCode,
Data = result,
Message = error
};
}
}
@@ -0,0 +1,272 @@
using FamilyTreeAPI.Entities;
using FamilyTreeAPI.Interface;
using FamilyTreeAPI.Models;
using SpreadsheetLight;
using System.Linq;
using DocumentFormat.OpenXml.Spreadsheet;
namespace FamilyTreeAPI.Repository;
public class ReportRepository : IReport
{
private enum EnumStaffWork
{
Id = 0,
FirstName,
LastName,
StartDate,
startTime,
stopTime,
Task,
Job,
Hour
};
private readonly FamilyTreeDBContext _context;
//private readonly ILookup _lookup;
const string DateTimeFormat = "dd/MM/yyyy HH:mm";
const string TimeFormat = "HH:mm";
const string DateFormat = "dd/MM/yyyy";
private readonly IStaff _staff;
private Dictionary<int, StaffDto> _dstaff;
private readonly ILookup _lookup;
private string DisplayTime(DateTime date)
{
string result = "";
if (date != DateTime.MinValue)
result = date.ToString(TimeFormat);
return result;
}
private string DisplayDateTime(DateTime? date)
{
string result = "";
if (date != DateTime.MinValue)
result = date!.Value.ToString(DateFormat);
return result;
}
private string FormatTime(int hour)
{
string result;
if (hour < 10)
result = "0" + hour.ToString() + ":00";
else
result = hour.ToString() + ":00";
return result;
}
public ReportRepository(FamilyTreeDBContext context, ILookup lookup,IStaff staff)
{
_context = context;
_lookup = lookup;
_staff = staff;
}
// public async Task<ResultModel<FileContent>> GetStaffWorkReportAsync(StaffWorkCriteria criteria)
// {
// //var data = await _lookup.GetLookupDicAsync("TypeOfUse");
// //if (data != null)
// //{
// // this._ServiceTypeDic = data.Data;
// //}
// var rstaff = await _staff.GetDicStaffs();
// if (rstaff.StatusCode == 1)
// _dstaff = rstaff.Data;
// //data = await _lookup.GetLookupDicAsync("Status");
// //if (data != null)
// //{
// // this._StatusDic = data.Data;
// //}
// int statusCode = 1;
// int col = 1;
// int row = 1;
// SLDocument sl = new SLDocument();
// SLStyle styleRed = sl.CreateStyle();
// styleRed.SetFontColor(System.Drawing.Color.Red);
// //first sheetName
// sl.RenameWorksheet(SLDocument.DefaultFirstSheetName, "Staff Work Report");
// SLStyle style = sl.CreateStyle();
// style.SetFontUnderline(DocumentFormat.OpenXml.Spreadsheet.UnderlineValues.Single);
// style.SetFontBold(true);
// style.SetFont("Calibri", 14);
// sl.SetCellStyle(1, 3, style);
// sl.SetRowHeight(1, 1, 25);
// sl.SetCellValue(row++, 3, "Staff Work");
// // sl.SetCellValue(row, 3, "From Date: " + fromDate.ToString(DateFormat) + " - " + toDate.ToString(DateFormat));
// sl.SetCellValue(1, 6, " " + DateTime.Now.ToString("ddd dd/MM/yyyy HH:mm"));
// // sl.SetCellValue(row, 6, "Hospital: " + facility);
// int startTitleRow = 3;
// row = startTitleRow;
// //make the title bold
// style = sl.CreateStyle();
// style.Font.Bold = true;
// sl.SetRowStyle(startTitleRow, style);
// //set it height
// sl.SetRowHeight(startTitleRow, startTitleRow, 25);
// // add the title first
// sl.SetCellValue(row, (int)EnumStaffWork.Id, "Id");
// sl.SetCellValue(row, (int) EnumStaffWork.FirstName, "FirstName");
// sl.SetCellValue(row, (int) EnumStaffWork.LastName, "SurName");
// sl.SetCellValue(row, (int) EnumStaffWork.StartDate, "StartDate");
// sl.SetCellValue(row, (int)EnumStaffWork.startTime, "Start Time");
// sl.SetCellValue(row, (int)EnumStaffWork.stopTime, "Stop Time");
// sl.SetCellValue(row, (int)EnumStaffWork.Hour, "Hour");
// /*
// style = sl.CreateStyle();
// style.SetFontColor(System.Drawing.Color.Blue);
// sl.SetRowStyle(row, style);
// */
// sl.FreezePanes(row, 0); //frozen the row.
// //wrap text on is concession Expiry
// style = sl.CreateStyle();
// style.SetWrapText(true);
// sl.SetColumnStyle(4, style);
// //format date
// // style = sl.CreateStyle();
// //style.FormatCode = DateTimeFormat;
// // sl.SetColumnStyle(1, style);
// //make column width
// sl.SetColumnWidth((int)EnumStaffWork.Id, 10);
// sl.SetColumnWidth((int)EnumStaffWork.FirstName, 30);
// sl.SetColumnWidth((int)EnumStaffWork.LastName, 30);
// sl.SetColumnWidth((int)EnumStaffWork.StartDate, 25);
// sl.SetColumnWidth((int)EnumStaffWork.startTime, 10);
// sl.SetColumnWidth((int)EnumStaffWork.stopTime, 10);
// sl.SetColumnWidth((int)EnumStaffWork.Hour, 20);
// style = sl.CreateStyle();
// style.FormatCode = DateFormat;
// sl.SetColumnStyle(5, style);
// //style = sl.CreateStyle();
// //style.FormatCode = DateTimeFormat;
// //sl.SetColumnStyle(1, style);
// sl.SetColumnWidth(10, 20);
// int startRowFrom = startTitleRow + 1;
//// DateTime ttdate = toDate.ToLocalTime(); //add 1 days so if to inclusive todate 02/09
// var container = await _context.LoadStaffWorkAsync(criteria); //fromDate.ToLocalTime(), ttdate.AddDays(1), typeOfCall);
// var list = container;
// list.Sort((x, y) => x.StartDate.Value.CompareTo(y.StartDate.Value));
// StaffWorkViewDto item;
// DateTime startTime, stopTime;
// double hour =0;
// string fname, lname;
// StaffWorkDetailDto detail;
// for (int i = 0; i < list.Count; i++)
// {
// item = list[i];
// row = i + startRowFrom;
// (startTime, stopTime ) = GetSSTime(item);
// if (item.Details != null)
// for (int j = 0; j < item.Details.Count; j++)
// {
// detail = item.Details[j];
// hour += detail.TotalMinuts();
// }
// (fname, lname) = GetStaffName(item.StaffId.Value);
// sl.SetCellValue(row, (int)EnumStaffWork.StartDate, item.StartDate.Value);
// sl.SetCellValue(row, (int)EnumStaffWork.FirstName, fname);
// sl.SetCellValue(row, (int)EnumStaffWork.LastName, lname);
// sl.SetCellValue(row, (int)EnumStaffWork.startTime, startTime);
// sl.SetCellValue(row, (int)EnumStaffWork.stopTime, stopTime);
// sl.SetCellValue(row, (int)EnumStaffWork.Hour, hour/60);
// }
// byte[] array;
// // sl.SaveAs("C:\\Temp\\Report\\ConcessionValidationDate" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx");
// using (MemoryStream ws = new MemoryStream())
// {
// sl.SaveAs(ws);
// array = ws.ToArray();
// /*
// using (FileStream fs = new FileStream("c:\\temp\\Report\\conReport.xlsx",FileMode.Create,FileAccess.Write))
// {
// ws.WriteTo(fs);
// fs.Close();
// }
// */
// ws.Close();
// }
// var result = new FileContent
// {
// Content = array,
// FileName = "StaffWork_Report" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm") + ".xlsx",
// };
// return new ResultModel<FileContent>
// {
// Data = result,
// StatusCode = statusCode
// };
// }
private (string, string) GetStaffName(int staffId)
{
StaffDto staff;
if (_dstaff.ContainsKey(staffId))
{
staff = _dstaff[staffId];
return ( staff.Firstname ?? "" , staff.Lastname ?? "");
}
return ("","");
}
//private (DateTime firstTime, DateTime lastTime) GetSSTime(StaffWorkViewDto item)
//{
// DateTime sTime, lTime;
// DateTime? value;
// int count = 0;
// sTime = lTime = DateTime.Now;
// List<StaffWorkDetailDto> detail = item.Details ?? new();
// count = detail.Count;
// if (count > 0)
// {
// value = detail[0].StartTime;
// if (value.HasValue)
// {
// sTime = value.Value;
// }
// value = detail[count - 1].StopTime;
// if (value.HasValue)
// {
// lTime = value.Value;
// }
// }
// return (sTime, lTime);
//}
private string GetValue(string item, string text)
{
string result = item;
if (!string.IsNullOrEmpty(text))
result = text;
return result;
}
//private string GetPools(List<string> poolIds)
//{
// string result = "";
// string id;
// for (int i = 0; i < poolIds.Count; i++)
// {
// id = poolIds[i];
// if (this._PoolDic.ContainsKey(id))
// result += _PoolDic[id].Description + ",";
// }
// result = result.Remove(result.Length-1, 1);
// return result;
//}
}
+83
View File
@@ -0,0 +1,83 @@
using FamilyTreeAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace FamilyTreeAPI.Repository;
public class Seed
{
private readonly FamilyTreeDBContext _context;
public Seed(FamilyTreeDBContext context)
{
_context = context;
}
public int InsertOneUser()
{
int id = -1;
//password = password
string txt = " INSERT INTO staff ( " +
"firstname, lastname, email, phone, stype, srole, spassword, sactive) " +
"VALUES" +
" ( 'kham', 'vilaythong', 'kham.vilaythong@gmail.com', '009', 1, 2, 'cGFzc3dvcmQ=', true), " +
" ( 'sy', 'vilaythong', 'sy.vilaythong@gmail.com', '007', 1, 2, 'cGFzc3dvcmQ=', true), " +
" ( 'Hung', 'Nguyen', 'hung.gnuyen@gmail.com', '008', 1, 2, 'cGFzc3dvcmQ=', true); ";
string workertxt = "INSERT INTO person ( firstname, lastname,email,phone,address,dob ,alive, fatherId, image, sex)" +
"VALUES " +
" ('Ho 1','Tran', 'Ho.Tran@hotmail.com', '002', '1 Cabramatta','1960-09-01', true, 0,'', 'M'), " +
" ('Jimmy 2','Tran', 'Ho.Tran@hotmail.com', '003', '34 Cabramatta','1980-09-01', true, 1,'','M'), " +
" ('Joe 3','Tran', 'Joe.Tran@hotmail.com', '006', '32 Cabramatta','1980-10-01', true, 1,'','M'), " +
" ('John 4','Tran', 'John.Tran@hotmail.com', '008', '30 Cabramatta','1990-12-01', true, 3,'','M')," +
" ('Lee 5','Tran', 'Lee.Tran@hotmail.com', '030', '18 Cabramatta','2000-12-01', true, 2,'','M'), " +
" ('Len 6','Nguyen', 'Len.nguyen@hotmail.com', '001', '1 Home','1950-01-01', true, 0,'','M'), " +
" ('Son 7','Nguyen', 'son.Nguyen@hotmail.com', '001', '10 Home','1980-01-01', true,6,'','M'), " +
" ('Loa 8','Tran', 'Loa.Tran@hotmail.com', '020', '11 Cabramatta','2002-12-01', true, 3,'','M'), " +
" ('Du 9','Tran', 'Du.Tran@hotmail.com', '001', '12 Cabramatta','2002-12-01', true, 4,'','M'), " +
" ('Linh 10','Tran', 'Du.Tran@hotmail.com', '001', '12 Cabramatta','2002-12-01', true, 5,'','M'), " +
" ('COA 11','Tran', 'Du.Tran@hotmail.com', '001', '12 Cabramatta','2002-12-01', true, 8,'','M'), " +
" ('Hoa 12','Tran', 'Du.Tran@hotmail.com', '001', '12 Cabramatta','2002-12-01', true, 8,'','F'), " +
" ('Nhi 13','Tran', 'Du.Tran@hotmail.com', '001', '12 Cabramatta','2002-12-01', true, 8,'','F'), " +
" ('Mai 14','Tran', 'Du.Tran@hotmail.com', '001', '12 Cabramatta','2002-12-01', true, 8,'','F'), " +
" ('Trang 15','Tran', 'Du.Tran@hotmail.com', '001', '12 Cabramatta','2002-12-01', true, 7,'','F'), " +
" ('Tom 16','Tran', 'Ho.Tran@hotmail.com', '007', '34 Cabramatta','1999-01-01', true, 2,'','M');";
try
{
int count = _context.staff.Count();
if (count < 1)
{
var conn = _context.Database.GetDbConnection();
try
{
conn.Open();
var command = conn.CreateCommand();
command.CommandText = txt;
command.CommandType = System.Data.CommandType.Text;
command.ExecuteNonQuery();
command.CommandText = workertxt;
command.CommandType = System.Data.CommandType.Text;
command.ExecuteNonQuery();
id = 9;
}
catch
{
id = -1;
}
finally
{
conn.Close();
}
}
else
id = 1;
}
catch
{
id = -10;
}
return id;
}
}
@@ -0,0 +1,381 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FamilyTreeAPI.Models;
using FamilyTreeAPI.Entities;
using FamilyTreeAPI.Interface;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using Microsoft.AspNetCore.Http;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
namespace FamilyTreeAPI.Repository;
/* password = cGFzc3dvcmQ=
*
INSERT INTO public.staff(
firstname, lastname, email, phone, stype, srole, spassword, sactive)
VALUES ( 'kham', 'vilaythong', 'kham.vilaythong', '009', 1, 2, 'cGFzc3dvcmQ=', true);
*/
public class StaffRepository : IStaff
{
private readonly FamilyTreeDBContext _context;
private readonly IHttpContextAccessor _httpContext;
public StaffRepository(FamilyTreeDBContext context, IHttpContextAccessor httpContext)
{
_context = context;
_httpContext = httpContext;
}
private StaffDto FillDto(staff model)
{
StaffDto dto = new StaffDto();
dto.Firstname = model.Firstname;
dto.Lastname = model.Lastname;
dto.Type = model.Stype;
dto.Phone = model.Phone;
dto.Active = model.Sactive ?? false;
dto.Email = model.Email;
/*
dto.AddedOn = model.AddedOn;
dto.RoleType = model.RoleType;
*/
dto.RoleType = model.Srole;
dto.Id = model.Id;
return dto;
}
private staff FillModel(staff model, StaffDto dto)
{
if (!string.IsNullOrEmpty(dto.Firstname))
model.Firstname = dto.Firstname.Trim();
if (!string.IsNullOrEmpty(dto.Lastname))
model.Lastname = dto.Lastname.Trim();
if (!string.IsNullOrEmpty(dto.Phone))
model.Phone = dto.Phone.Trim();
if (dto.Id > 0)
model.Id = dto.Id;
if (!string.IsNullOrEmpty(dto.Password))
{
string password = dto.Password.Trim();
model.Spassword = Ultils.Base64Encode(password);
}
model.Email = dto.Email;
model.Srole = dto.RoleType;
model.Sactive = dto.Active;
return model;
}
public async Task<ResultModel<Dictionary<int,StaffDto>>> GetDicStaffs()
{
Dictionary<int,StaffDto> dlist = new();
int statuscode = 0;
string error = "";
StaffDto item;
staff model;
try
{
var list = await _context.staff.ToListAsync();
for (int i = 0; i< list.Count; i++)
{
model = list[i];
item = FillDto(model);
dlist.Add(item.Id, item);
}
statuscode = 1;
//list.Sort((x, y) => x.Code.CompareTo(y.Code));
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel<Dictionary<int,StaffDto>>()
{
Data = dlist,
StatusCode = statuscode,
Message = error
};
}
public async Task<ResultModel<List<StaffDto> >> GetStaff(StaffCriteria criteria)
{
List<StaffDto> list = new();
int statuscode = 0;
string error = "";
try
{
list = await _context.LoadStaffAsync(criteria);
statuscode = 1;
//list.Sort((x, y) => x.Code.CompareTo(y.Code));
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel<List<StaffDto>>()
{
Data = list,
StatusCode = statuscode,
Message = error
};
}
public async Task<ResultModel<StaffDto>> GetStaffById(int id)
{
int statuscode = 0;
string error = "";
StaffDto dto = new StaffDto();
try
{
var item = await _context.staff.FindAsync(id);
if (item == null)
{
statuscode = -1;
}
else
{
dto = FillDto(item);
statuscode = 1;
}
}
catch(Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
return new ResultModel<StaffDto>()
{
Data = dto,
StatusCode = statuscode,
Message = error
};
}
private string GetDateTimeNow()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
public async Task<ResultModel<int>> ResetPassword(ResetPassDto item)
{
int result = -1;
int statuscode = 0;
string error = "";
try
{
staff? model1 = await _context.staff.FindAsync(item.Id);
if (model1 != null)
{
if (!string.IsNullOrEmpty(item.Password))
{
string password = item.Password.Trim();
model1.Spassword = Ultils.Base64Encode(password);
}
// model.LastModified = DateTime.Now;
// model.LastModifiedId = loginName;
var successid = await _context.SaveChangesAsync();
result = item.Id;
}
statuscode = 1;
}
catch (Exception ex)
{
statuscode = -1;
error = ex.ToString();
}
return new ResultModel<int>()
{
Data = result,
StatusCode = statuscode,
Message = error
};
}
public async Task<ResultModel<int>> SaveStaff(StaffDto item)
{
int result = default(int);
int statuscode = 0;
string error = "";
HttpContext? httpContext = _httpContext.HttpContext;
string loginName = "";
if (httpContext != null)
{
UserDto? user = (UserDto?)httpContext.Items["User"];
if (user != null)
loginName = user.FirstName + " " + user.LastName;
}
try
{
if (item.Id < 1)
{
bool already = await CheckLoginAlready(item.Email.Trim());
if (already)
{
return new ResultModel<int>()
{
Data = 0,
StatusCode = 0,
Message = "user name already exist in Database"
};
}
}
staff model;
if (item.Id < 1)
{
model = new();
model = FillModel(model, item);
// model.Active = true;
// model.AddedBy = loginName;
// model.AddedOn = DateTime.Now;
_context.staff.Add(model);
await _context.SaveChangesAsync();
result = model.Id;
}
else
{
staff? model1 = await _context.staff.FindAsync(item.Id);
model1 = FillModel(model1, item);
// model.LastModified = DateTime.Now;
// model.LastModifiedId = loginName;
var successid = await _context.SaveChangesAsync();
result = item.Id;
}
statuscode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
//var dto = await Task.Run(() => result);
return new ResultModel<int>()
{
Data = result,
StatusCode = statuscode,
Message = error
};
}
private async Task<bool> CheckLoginAlready(string login)
{
bool result = false;
var model = await _context.staff.Where(x => x.Email == login).ToListAsync();
if (model.Count > 0)
result = true;
return result;
}
public async Task<ResultModel<int>> SaveStaffNew(StaffDto item)
{
int result = default(int);
int statuscode = 0;
string error = "";
try
{
if (item.Id < 1)
{
bool already = await CheckLoginAlready(item.Email.Trim());
if (already)
{
return new ResultModel<int>()
{
Data = 0,
StatusCode = 0,
Message = "user name already exist in db"
};
}
}
staff model;
if (item.Id < 1)
{
model = new();
model = FillModel(model, item);
// model.AddedOn = DateTime.Now;
// model.Active = true;
_context.staff.Add(model);
}
else
{
model = await _context.staff.FindAsync(item.Id);
model = FillModel(model, item);
}
var successid = await _context.SaveChangesAsync();
result = 1;
statuscode = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
//var dto = await Task.Run(() => result);
return new ResultModel<int>()
{
Data = result,
StatusCode = statuscode,
Message = error
};
}
public async Task<ResultModel<int>> Delete(int id)
{
int result = 1;
int statuscode = 0;
string error = "";
try
{
staff model;
model = await _context.staff.FindAsync(id);
// if (model != null)
// model.Active = false;
var successCount = await _context.SaveChangesAsync();
statuscode = 1;
result = 1;
}
catch (Exception ex)
{
error = ex.ToString();
statuscode = -1;
}
//var dto = await Task.Run(() => result);
return new ResultModel<int>()
{
Data = result,
StatusCode = statuscode,
Message = error
};
}
}
+251
View File
@@ -0,0 +1,251 @@
/**************************************/
CREATE TABLE IF NOT EXISTS public.client
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
clientname character(80) COLLATE pg_catalog."default",
contact character(80) COLLATE pg_catalog."default",
cactive boolean,
address character(120),
email character(80),
phone character(30),
CONSTRAINT client_pkey PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE IF EXISTS public.client
OWNER to postgres;
CREATE TABLE IF NOT EXISTS public.lookup
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
code character(10) COLLATE pg_catalog."default",
description character(80) COLLATE pg_catalog."default",
lactive boolean,
ltype character(20) COLLATE pg_catalog."default",
CONSTRAINT lookup_pkey PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE IF EXISTS public.lookup
OWNER to postgres;
-- Table: public.job
-- DROP TABLE IF EXISTS public.job;
CREATE TABLE IF NOT EXISTS public.job
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
code character(10) COLLATE pg_catalog."default",
description character(80) COLLATE pg_catalog."default",
jactive boolean,
CONSTRAINT job_pkey PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE IF EXISTS public.job
OWNER to postgres;
-- Table: public.servicetask
-- DROP TABLE IF EXISTS public.servicetask;
CREATE TABLE IF NOT EXISTS public.servicetask
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
assignto integer,
clientid integer,
code character(10) COLLATE pg_catalog."default",
description character(80) COLLATE pg_catalog."default",
sdate date,
serviceno character(20) COLLATE pg_catalog."default",
staffid integer,
status integer,
CONSTRAINT servicetask_pkey PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE IF EXISTS public.servicetask
OWNER to postgres;
-- Table: public.staffwork
-- DROP TABLE IF EXISTS public.staffwork;
CREATE TABLE IF NOT EXISTS public.staffwork
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
description character(80) COLLATE pg_catalog."default",
sactive boolean,
staffid integer,
startdate date,
CONSTRAINT staffwork_pkey PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE IF EXISTS public.staffwork
OWNER to postgres;
-- Table: public.staffworkdetail
-- DROP TABLE IF EXISTS public.staffworkdetail;
CREATE TABLE IF NOT EXISTS public.staffworkdetail
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
jobid integer,
sactive boolean,
starttime timestamp without time zone,
stoptime timestamp without time zone,
task character(80) COLLATE pg_catalog."default",
swid integer,
CONSTRAINT staffworkdetail_pkey PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE IF EXISTS public.staffworkdetail
OWNER to postgres;
/******************************************/
ALTER TABLE servicetask
ADD FOREIGN KEY (clientid) REFERENCES client(id);
ALTER TABLE servicetask
ADD FOREIGN KEY (staffid) REFERENCES staff(id);
ALTER TABLE servicetask
ADD FOREIGN KEY (assignto) REFERENCES staff(id);
ALTER TABLE staffwork
ADD FOREIGN KEY (staffid) REFERENCES staff(id);
ALTER TABLE staffworkdetail
ADD FOREIGN KEY (swid) REFERENCES staffwork(id);
ALTER TABLE staffworkdetail
ADD FOREIGN KEY (jobid) REFERENCES job(id);
/************************************/
CREATE OR REPLACE FUNCTION usp_search_user (
iemail character varying,
ifirstname character varying,
ilastname character varying)
RETURNS TABLE(id integer, fistname character varying, lastname character varying, email character varying, stype integer, sactive boolean, srole integer, spassword character varying)
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
ROWS 1000
AS $BODY$
begin
return query SELECT
e.id,
e.firstname,
e.lastname,
e.email,
e.stype,
e.sactive,
e.srole,
e.spassword
FROM staff e
WHERE (iemail = '' or e.email ilike iemail || '%')
and (ilastname = '' or e.lastname ilike ilastname || '%')
and (ifirstname = '' or e.firstname ilike ifirstname || '%');
end;
$BODY$;
CREATE OR REPLACE FUNCTION usp_staffwork_detail(
ifromdate date,
itodate date,
istaffid integer)
RETURNS TABLE(id integer, staffid integer, description character varying(80),
startdate date, sactive boolean, did integer, starttime timestamp, stoptime timestamp,
task character varying(80))
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
ROWS 1000
AS $BODY$
begin
return query SELECT
w.id,
w.staffid,
w.description,
w.startdate,
w.sactive,
d.id as did,
d.starttime,
d.stoptime,
d.task
FROM staffwork w,
staffworkdetail d
where w.id = d.swid
and (istaffid = 0 or w.staffid = istaffid)
and w.startdate >= ifromdate
and w.startdate <= itodate
order by id, did;
end;
$BODY$;
CREATE OR REPLACE FUNCTION usp_servicetask_sel(
ifromdate date,
itodate date,
istaffid integer,
iassignto integer,
iclientid integer
)
RETURNS TABLE(id integer,
staffid integer,
sdate date,
description character varying(80),
code character varying(10),
status integer,
assignTo integer,
clientid integer,
serviceno character varying(20))
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
ROWS 1000
AS $BODY$
begin
return query SELECT
s.id,
s.staffid,
s.sdate,
s.description,
s.code,
s.status,
s.assignto,
s.clientid,
s."serviceNo"
FROM servicetask s
where (istaffid < 1 or s.staffid = istaffid)
and (iassignto < 1 or s.assignto = iassignto)
and (iclientid < 1 or s.clientid = iclientid)
and s.sdate >= ifromdate
and s.sdate <= itodate
;
end;
$BODY$;
+16
View File
@@ -0,0 +1,16 @@
namespace FamilyTreeAPI.Repository
{
public class Ultils
{
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
}
}
@@ -0,0 +1,257 @@
//using BCryptNet = BCrypt.Net.BCrypt;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using FamilyTreeAPI.Interface;
using FamilyTreeAPI.Entities;
using System;
using FamilyTreeAPI.Models;
using Microsoft.AspNetCore.Http;
using System.Text.Json;
namespace FamilyTreeAPI.Repository;
public class UserServiceRepository : IUserService
{
private FamilyTreeDBContext _context;
private IJwtUtils _jwtUtils;
private readonly IHttpContextAccessor _httpcontext;
private readonly AppSettings _appSettings;
public UserServiceRepository(
FamilyTreeDBContext context,
IJwtUtils jwtUtils,
IHttpContextAccessor httpcontext,
IOptions<AppSettings> appSettings)
{
_context = context;
_jwtUtils = jwtUtils;
_appSettings = appSettings.Value;
this._httpcontext = httpcontext;
}
public Task<ResultModel<int>> Logout(string token, UserDto user, string remoteIpAddress)
{
/*
int retval = 1;
int statuscode = 1;
string str255 = token;
var histo = await _context.AdminLoginHistories.Where(x => x.UserId == user.Id
&& x.RecordIntegrity == token
&& x.LoginTyped == user.Username).ToListAsync();
if (histo.Count > 0)
{
histo[0].LogoutDatetime = DateTime.Now;
await _context.SaveChangesAsync();
}
*/
var result = new ResultModel<int>()
{
Data = 1,
StatusCode = 1
};
return Task.FromResult(result);
}
private bool checkLogin(staff user, string email, string password)
{
bool result = false;
// string dpassword = Ultils.Base64Encode(password);
result = user.Spassword == password;
return result;
}
public async Task<ResultModel<AuthenticateResponse>> Login(AuthenticateRequest model)
{
UserDto myUser = new();
AuthenticateResponse retval = null;
string error = "user name is not in DB or user Name profile is not generic";
int statuscode = 0;
try
{
//now check the adminuser table
myUser.Username = model.Username;
var user = _context.staff.
SingleOrDefault(x => x.Email == model.Username
&& true == x.Sactive);
if (user != null)
{
bool loginOK = checkLogin(user, model.Username, model.Password);
if (loginOK)
{
// myUser.Role = user.RoleType;
myUser.Id = user.Id;
myUser.Role = user.Srole ?? 0;
myUser.Email = user.Email;
myUser.Phone = user.Phone;
myUser.FirstName = user.Firstname;
myUser.LastName = user.Lastname;
//myUser.ValidationPointId = user.ValidationPointID ?? 0;
statuscode = 1;
}
else //not allow
{
statuscode = -1;
myUser.Role = 1;
myUser.Id = -1;
error = "user name cannot login email or password";
}
// validate
// if (user == null || !BCryptNet.Verify(model.Password, user.PasswordHash))
// authentication successful so generate jwt token
if (statuscode == 1)
{
var jwtToken = _jwtUtils.GenerateJwtToken(myUser);
retval = new AuthenticateResponse(myUser, jwtToken, myUser.Role);
error = "";
}
}
else
{
error = "user name or password is not correct";
}
}
catch (Exception ex)
{
retval = null;
error = ex.ToString();
statuscode = -1;
}
//writelog for login user.
// if (myUser != null)
// await AddToSession(myUser);
return new ResultModel<AuthenticateResponse>()
{
Data = retval,
StatusCode = statuscode,
Message = error
};
}
public async Task<ResultModel<AuthenticateResponse>> LoginApiAD(AuthenticateRequest model, string remoteIpAddress)
{
UserDto myUser = new();
AuthenticateResponse retval = null;
string error = "user name is not in DB or user Name profile is not generic";
int statuscode = 0;
string webAPIUrl = _appSettings.LoginWebAPI;
//KCO, D204KCO
//now check the adminuser table
//ward clerk
try
{
//now check the adminuser table
myUser.Username = model.Username;
var user = _context.staff.
SingleOrDefault(x => x.Email == model.Username
&& true == x.Sactive);
if (user != null)
{
bool loginOK = checkLogin(user,model.Username, model.Password);
if (loginOK)
{
// myUser.Role = user.RoleType;
myUser.Id = user.Id;
myUser.Role = user.Srole ?? 0;
myUser.Email = user.Email;
myUser.Phone = user.Phone;
myUser.FirstName = user.Firstname;
myUser.LastName = user.Lastname;
//myUser.ValidationPointId = user.ValidationPointID ?? 0;
statuscode = 1;
}
else // allow
{
statuscode = 1;
myUser.Role = 1;
myUser.Id = -1;
//error = "user name does not exist in adminUser";
}
// validate
// if (user == null || !BCryptNet.Verify(model.Password, user.PasswordHash))
// authentication successful so generate jwt token
if (statuscode == 1)
{
var jwtToken = _jwtUtils.GenerateJwtToken(myUser);
retval = new AuthenticateResponse(myUser, jwtToken, myUser.Role);
error = "";
}
}
else
{
error = "user name or password is not correct";
}
}
catch (Exception ex)
{
retval = null;
error = ex.ToString();
statuscode = -1;
}
//writelog for login user.
// if (myUser != null)
// await AddToSession(myUser);
return new ResultModel<AuthenticateResponse>()
{
Data = retval,
StatusCode = statuscode,
Message = error
};
}
//get like this
private async Task GetCurrentUser()
{
await _httpcontext.HttpContext.Session.LoadAsync();
string userString = _httpcontext.HttpContext.Session.GetString("user");
if (userString != null && userString != "")
{
var user = JsonSerializer.Deserialize<UserDto>(userString);
if (user != null)
{
// return user;
}
}
}
/*
private User LoginADStaff(ADConfig adConfig, string username, string password)
{
ADStaffLink staffLink = new ADStaffLink(adConfig);
MyADObject myADObj = staffLink.CheckADCredentials(username,password);
User user = new()
{
Username = myADObj.StafflinkNo,
Email = myADObj.Email,
FirstName = myADObj.FirstName,
LastName = myADObj.LastName
};
// myADObj.JobTitle;
return user;
// return null;
}
*/
}
@@ -0,0 +1,118 @@
/*
declare @id int
set @id = 7
delete from MotorAccess where mv_id = @id
delete from [dbo].[MotorVehicle]
where mv_id = @id
*/
CREATE OR REPLACE FUNCTION public.usp_search_user(
iemail character varying,
ifirstname character varying,
ilastname character varying)
RETURNS TABLE(id integer, fistname character varying, lastname character varying, email character varying, stype integer, sactive boolean, srole integer, spassword character varying)
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
ROWS 1000
AS $BODY$
begin
return query SELECT
e.id,
e.firstname,
e.lastname,
e.email,
e.stype,
e.sactive,
e.srole,
e.spassword
FROM staff e
WHERE (iemail = '' or e.email ilike iemail || '%')
and (ilastname = '' or e.lastname ilike ilastname || '%')
and (ifirstname = '' or e.firstname ilike ifirstname || '%');
end;
$BODY$;
CREATE OR REPLACE FUNCTION get_staff (
iemail character varying,
ifirstname character varying,
ilastname character varying
)
RETURNS TABLE (
id int,
firstname varchar,
lastname varchar,
email varchar,
stype INT,
sactive boolean,
srole INT,
spassword varchar )
AS $$
BEGIN
RETURN QUERY
e.id,
e.firstname,
e.lastname,
e.email,
e.stype,
e.sactive,
e.srole,
e.spassword
FROM staff e
WHERE (iemail = '' or e.email ilike iemail || '%')
and (ilastname = '' or e.lastname ilike ilastname || '%')
and (ifirstname = '' or e.firstname ilike ifirstname || '%');
END; $$
LANGUAGE 'plpgsql';
how to host under .net 8 web api under linux
1) create [webAPI_name].service
******************************************
# Example: /etc/systemd/system/yourwebapp.service
[Unit]
Description=Your .NET 8 Web API
After=network.target
[Service]
WorkingDirectory=/var/www/yourwebapp
ExecStart=/usr/bin/dotnet /var/www/yourwebapp/YourWebApi.dll
Restart=always
RestartSec=10
SyslogIdentifier=yourwebapp
User=www-data # or a dedicated user
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target
************************************************
2) start /stop the service under linux
***********************************************
sudo systemctl enable yourwebapp.service
sudo systemctl start yourwebapp.service
**********************************************
3) host under nginx or apache
************************************************
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:5000; # Kestrel's listening port
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
***********************************************************************