This commit is contained in:
mmrbnjd
2024-05-08 17:25:02 +03:30
parent d74f3dadf3
commit 716f02baa1
14 changed files with 376 additions and 179 deletions

View File

@@ -6,6 +6,13 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="Common\DTOs\**" />
<Content Remove="Common\DTOs\**" />
<EmbeddedResource Remove="Common\DTOs\**" />
<None Remove="Common\DTOs\**" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Melipayamak.RestClient" Version="1.0.0" /> <PackageReference Include="Melipayamak.RestClient" Version="1.0.0" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" /> <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
@@ -24,10 +31,6 @@
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Common\DTOs\" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Shared\Shared.csproj" /> <ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup> </ItemGroup>

View File

@@ -0,0 +1,8 @@
namespace Back.Common
{
public enum eActionValidation
{
add,
update
}
}

View File

@@ -1,8 +1,12 @@
using Back.Services; using Back.Common;
using Back.Services;
using Back.Validations; using Back.Validations;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Service;
using Shared.DTOs; using Shared.DTOs;
using System.Net;
using System.Reflection.Emit;
namespace Back.Controllers namespace Back.Controllers
{ {
@@ -14,11 +18,11 @@ namespace Back.Controllers
private readonly CheckPermission _checkPermission; private readonly CheckPermission _checkPermission;
private readonly servUser _servUser; private readonly servUser _servUser;
private readonly servCustomer _servCus; private readonly servCustomer _servCus;
private readonly AddCustomerValidation _addCustomerValidation; private readonly AddOrCustomerValidation _addorupdateCustomerValidation;
public CustomerController(CheckPermission checkPermission, servUser servUser public CustomerController(CheckPermission checkPermission, servUser servUser
, servCustomer servCus, AddCustomerValidation addCustomerValidation) , servCustomer servCus, AddOrCustomerValidation addorupdateCustomerValidation)
{ {
_addCustomerValidation = addCustomerValidation; _addorupdateCustomerValidation = addorupdateCustomerValidation;
_checkPermission = checkPermission; _checkPermission = checkPermission;
_servUser = servUser; _servUser = servUser;
_servCus = servCus; _servCus = servCus;
@@ -30,7 +34,7 @@ namespace Back.Controllers
var UserID = claim.Value; var UserID = claim.Value;
var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID)); var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
if (!await _checkPermission.AllowSYSGetCustomer(Convert.ToInt32(UserID), user.RolUsers.First().CompanyID)) return Forbid( "شما دسترسی به خواندن اطلاعات مشتری را نداربد"); if (!await _checkPermission.AllowSYSGetCustomer(Convert.ToInt32(UserID), user.RolUsers.First().CompanyID)) return Forbid("شما دسترسی به خواندن اطلاعات مشتری را نداربد");
return Ok(await _servCus.GetCustomers(user.RolUsers.First().CompanyID, itemSerch)); return Ok(await _servCus.GetCustomers(user.RolUsers.First().CompanyID, itemSerch));
@@ -43,11 +47,11 @@ namespace Back.Controllers
var UserID = claim.Value; var UserID = claim.Value;
var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID)); var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
var resultValidationmodel = await _addCustomerValidation.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID,item)); var resultValidationmodel = await _addorupdateCustomerValidation.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, item, eActionValidation.add));
if (!resultValidationmodel.IsValid) if (!resultValidationmodel.IsValid)
return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList()); return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());
return Ok(_servCus.AddCustomer(new Data.Models.Customer return Ok(await _servCus.AddOrUpdateCustomer(new Data.Models.Customer
{ {
Address = item.Address, Address = item.Address,
BranchID = item.BranchID, BranchID = item.BranchID,
@@ -62,7 +66,59 @@ namespace Back.Controllers
Phone = item.Phone, Phone = item.Phone,
ZipCode = item.ZipCode, ZipCode = item.ZipCode,
IsDeleted = false IsDeleted = false
})) ; }));
}
[HttpPut("Update")]
public async Task<ActionResult<bool>> Update(RCustomer item)
{
//-----GetUserAndCompany
var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
var UserID = claim.Value;
var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
//-----Validaton
var resultValidationmodel = await _addorupdateCustomerValidation.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, item, eActionValidation.update));
if (!resultValidationmodel.IsValid)
return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());
//-----Get Cus
var cus = await _servCus.GetCustomerByCustomerID(item.ID.Value, user.RolUsers.First().CompanyID);
if (cus == null)
return BadRequest(new List<string> { "Cus notFound..." });
//-----change Cus
cus.Address = item.Address;
cus.BranchID = item.BranchID;
cus.CompanyID = user.RolUsers.First().CompanyID;
cus.CustomerType = item.CustomerType;
cus.EconomicCode = item.EconomicCode;
cus.Email = item.Email;
cus.FullName = item.FullName;
cus.Info = item.Info;
cus.MeliCode = item.MeliCode;
cus.PassportNumber = item.PassportNumber;
cus.Phone = item.Phone;
cus.ZipCode = item.ZipCode;
cus.IsDeleted = false;
//----Update and sendResult
return Ok(await _servCus.AddOrUpdateCustomer(cus));
}
[HttpDelete("Delete/{ID}")]
public async Task<ActionResult<bool>> Delete(int ID)
{
//-----GetUserAndCompany
var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
var UserID = claim.Value;
var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
//-----Get Cus
var cus = await _servCus.GetCustomerByCustomerID(ID, user.RolUsers.First().CompanyID);
if (cus == null)
return NotFound();
//----Update and sendResult
return Ok(await _servCus.DeleteCustomer(cus));
} }
} }
} }

View File

@@ -39,7 +39,7 @@ builder.Services.AddScoped<servUser>();
builder.Services.AddScoped<servTaxPayer>(); builder.Services.AddScoped<servTaxPayer>();
builder.Services.AddScoped<servCustomer>(); builder.Services.AddScoped<servCustomer>();
builder.Services.AddScoped<CompanyRegistrationValidation>(); builder.Services.AddScoped<CompanyRegistrationValidation>();
builder.Services.AddScoped<AddCustomerValidation>(); builder.Services.AddScoped<AddOrCustomerValidation>();
builder.Services.AddScoped(c => new mpNuget.RestClient("09119660045", "C54S2")); builder.Services.AddScoped(c => new mpNuget.RestClient("09119660045", "C54S2"));
string origins = "OriginTaxPayer"; string origins = "OriginTaxPayer";

View File

@@ -58,24 +58,24 @@ namespace Back.Services
PassportNumber = s.PassportNumber, PassportNumber = s.PassportNumber,
CustomerType= s.CustomerType CustomerType= s.CustomerType
// CompanyID=s.CompanyID // CompanyID=s.CompanyID
}) }).OrderByDescending(o=>o.ID)
.Paging(itemSerch.PageIndex, itemSerch.PageSize); .Paging(itemSerch.PageIndex, itemSerch.PageSize);
} }
//public async Task<Customer> GetCustomerByCustomerID(int CustomerID, int CompanyID) public async Task<Customer?> GetCustomerByCustomerID(int CustomerID, int CompanyID)
//{ {
// return await _repositores.GET<Customer>() return await _repoCus
// .Where(w => w.ID == CustomerID && w.CompanyID==CompanyID && !w.IsDeleted).FirstOrDefaultAsync(); .Get(w => w.ID == CustomerID && w.CompanyID == CompanyID && !w.IsDeleted).FirstOrDefaultAsync();
//} }
//public async Task<Customer> GetCustomerByCustomerID(int CustomerID) //public async Task<Customer> GetCustomerByCustomerID(int CustomerID)
//{ //{
// return await _repositores.GET<Customer>() // return await _repositores.GET<Customer>()
// .Where(w => w.ID == CustomerID && !w.IsDeleted).FirstOrDefaultAsync(); // .Where(w => w.ID == CustomerID && !w.IsDeleted).FirstOrDefaultAsync();
//} //}
//public async Task<bool> ExistCustomerByCustomerID(int CustomerID, int CompanyID) public async Task<bool> ExistCustomerByCustomerID(int CustomerID, int CompanyID)
//{ {
// return await _repositores.GET<Customer>() return await _repoCus
// .AnyAsync(w => w.ID == CustomerID && w.CompanyID == CompanyID && !w.IsDeleted); .Get(w => w.ID == CustomerID && w.CompanyID == CompanyID && !w.IsDeleted).AnyAsync();
//} }
//public async Task<CUCustomer> GetCustomerByCustomerIDByDTO(int CustomerID) //public async Task<CUCustomer> GetCustomerByCustomerIDByDTO(int CustomerID)
//{ //{
// return await _repositores.GET<Customer>() // return await _repositores.GET<Customer>()
@@ -98,7 +98,7 @@ namespace Back.Services
// }) // })
// .FirstOrDefaultAsync(); // .FirstOrDefaultAsync();
//} //}
public async Task<bool> AddCustomer(Customer item) public async Task<bool> AddOrUpdateCustomer(Customer item)
{ {
try try
{ {
@@ -113,7 +113,7 @@ namespace Back.Services
//}; //};
//_contextMongodb.InsertItem(log); //_contextMongodb.InsertItem(log);
if (item.ID == null || item.ID == 0) if (item.ID == null || item.ID <= 0)
{ {
var ret = await _repoCus.AddBoolResultAsync(item); var ret = await _repoCus.AddBoolResultAsync(item);
await _checkPermission.ExtensionofAccess(item.CompanyID, 5, "-1"); await _checkPermission.ExtensionofAccess(item.CompanyID, 5, "-1");
@@ -140,41 +140,40 @@ namespace Back.Services
} }
} }
//public async Task<bool> DeleteCustomer(Customer item) public async Task<bool> DeleteCustomer(Customer item)
//{ {
// try try
// { {
// item.IsDeleted = true; item.IsDeleted = true;
// _repositores.UPDATE(item); return await _repoCus.UpdateAsync(item);
// SysLog log = new SysLog() //SysLog log = new SysLog()
// { //{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier, // TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(), // Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/DeleteCustomer", // Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/DeleteCustomer",
// Value = JsonConvert.SerializeObject(item.ID), // Value = JsonConvert.SerializeObject(item.ID),
// Route = _httpContextAccessor.HttpContext.Request.Path, // Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User" // Type = "User"
// }; //};
// _contextMongodb.InsertItem(log); //_contextMongodb.InsertItem(log);
// return true; }
// } catch (Exception ex)
// catch (Exception ex) {
// { //SysLog log = new SysLog()
// SysLog log = new SysLog() //{
// { // TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier, // Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Datetime = DateTime.Now.ConvertMiladiToShamsi(), // Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/DeleteCustomer",
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/DeleteCustomer", // Value = ex.Message,
// Value = ex.Message, // Route = _httpContextAccessor.HttpContext.Request.Path,
// Route = _httpContextAccessor.HttpContext.Request.Path, // Type = "catch"
// Type = "catch" //};
// }; //_contextMongodb.InsertItem(log);
// _contextMongodb.InsertItem(log); return false;
// return false;
// } }
//} }
} }

View File

@@ -1,61 +0,0 @@
using Back.Services;
using FluentValidation;
using Shared.DTOs;
namespace Back.Validations
{
public class AddCustomerValidation : AbstractValidator<Tuple<int, RCustomer>>
{
public AddCustomerValidation(CheckPermission _checkPermission)
{
CascadeMode = CascadeMode.Stop;
RuleFor(r => r.Item1)
.Custom((CompanyID, context) => {
if (! _checkPermission.AllowAddCustomerInCompany(CompanyID).Result)
context.AddFailure("اضافه کردن مشتری محدود شده است");
});
RuleFor(r => r.Item2.FullName)
.NotNull().WithMessage("نام نمی تواند خالی باشذ")
.NotEmpty().WithMessage("نام نمی تواند خالی باشذ")
.MinimumLength(5).WithMessage("حداقل کارکتر مجار نام 5 می باشد");
RuleFor(r => r.Item2.Phone)
.NotNull().WithMessage("تلفن نمی تواند خالی باشذ")
.NotEmpty().WithMessage("تلفن نمی تواند خالی باشذ")
.MinimumLength(8).WithMessage("حداقل کارکتر مجار تلفن 8 می باشد");
RuleFor(r => r.Item2.Email)
.Custom((model, context) => {
if (!string.IsNullOrEmpty(model) && (!model.Contains("@") || !model.Contains(".")))
context.AddFailure("فرمت پست الکترونیک صحبح نمی باشد");
});
RuleFor(r => r.Item2.EconomicCode)
.Custom((model, context) => {
if (!string.IsNullOrEmpty(model) && (model.Length<11 || model.Length > 14))
context.AddFailure("تعداد شماره اقتصادی صحبح نمی باشد");
});
RuleFor(r => r.Item2.BranchID)
.Custom((model, context) => {
if (!string.IsNullOrEmpty(model) && (model.Length > 10 ))
context.AddFailure("تعداد کد شعبه صحبح نمی باشد");
});
RuleFor(r => r.Item2.ZipCode)
.Custom((model, context) => {
if (!string.IsNullOrEmpty(model) && (model.Length !=10))
context.AddFailure("تعداد کد پستی صحبح نمی باشد");
});
RuleFor(r => r.Item2.MeliCode)
.Custom((model, context) => {
if (!string.IsNullOrEmpty(model) && (model.Length < 10 || model.Length > 12))
context.AddFailure("تعداد شناسه ملی صحبح نمی باشد");
});
RuleFor(r => r.Item2.PassportNumber)
.Custom((model, context) => {
if (!string.IsNullOrEmpty(model) && (model.Length!=9))
context.AddFailure("تعداد شماره گذرنامه صحبح نمی باشد");
});
}
}
}

View File

@@ -0,0 +1,97 @@
using Back.Common;
using Back.Services;
using FluentValidation;
using Shared.DTOs;
namespace Back.Validations
{
public class AddOrCustomerValidation : AbstractValidator<Tuple<int, RCustomer, eActionValidation>>
{
public AddOrCustomerValidation(CheckPermission _checkPermission, servCustomer servCustomer)
{
CascadeMode = CascadeMode.Stop;
When(r => r.Item3 == eActionValidation.add, () =>
{
RuleFor(r => r.Item1)
.Custom((CompanyID, context) =>
{
if (!_checkPermission.AllowAddCustomerInCompany(CompanyID).Result)
context.AddFailure("اضافه کردن مشتری محدود شده است");
});
});
When(r => r.Item3 == eActionValidation.update, () =>
{
RuleFor(r => r)
.Custom((model, context) =>
{
var companyid = model.Item1;
if (!model.Item2.ID.HasValue || model.Item2.ID <= 0)
context.AddFailure("شناسه مشتری نمی تواند خالی باشذ");
else
{
var customerid = model.Item2.ID.Value;
if (!servCustomer.ExistCustomerByCustomerID(customerid, companyid).Result)
context.AddFailure("مشتری با این شناسه یافت نشد");
}
});
});
RuleFor(r => r.Item2.FullName)
.NotNull().WithMessage("نام نمی تواند خالی باشذ")
.NotEmpty().WithMessage("نام نمی تواند خالی باشذ")
.MinimumLength(5).WithMessage("حداقل کارکتر مجار نام 5 می باشد");
RuleFor(r => r.Item2.Phone)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && model.Length <8)
context.AddFailure("حداقل کارکتر مجار تلفن 8 می باشد");
});
RuleFor(r => r.Item2.Email)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && (!model.Contains("@") || !model.Contains(".")))
context.AddFailure("فرمت پست الکترونیک صحبح نمی باشد");
});
RuleFor(r => r.Item2.EconomicCode)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && (model.Length < 11 || model.Length > 14))
context.AddFailure("تعداد کارکتر شماره اقتصادی صحبح نمی باشد");
});
RuleFor(r => r.Item2.BranchID)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && (model.Length > 10))
context.AddFailure("تعداد کارکتر کد شعبه صحبح نمی باشد");
});
RuleFor(r => r.Item2.ZipCode)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && (model.Length != 10))
context.AddFailure("تعداد کارکتر کد پستی صحبح نمی باشد");
});
RuleFor(r => r.Item2.MeliCode)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && (model.Length < 10 || model.Length > 12))
context.AddFailure("تعداد کارکتر شناسه ملی صحبح نمی باشد");
});
RuleFor(r => r.Item2.PassportNumber)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && (model.Length != 9))
context.AddFailure("تعداد کارکتر شماره گذرنامه صحبح نمی باشد");
});
RuleFor(r => r.Item2.Info)
.Custom((model, context) =>
{
if (!string.IsNullOrEmpty(model) && model.Length > 50)
context.AddFailure("تعداد کارکتر توضیحات بیش از 50 می باشد");
});
}
}
}

View File

@@ -16,16 +16,16 @@ namespace Shared.DTOs
[Display(Name = "نوع مشتری")] [Display(Name = "نوع مشتری")]
public string? CustomerTypeTitle { get; set; } public string? CustomerTypeTitle { get; set; }
[Display(Name = "تلفن")] [Display(Name = "تلفن")]
public string Phone { get; set; } public string? Phone { get; set; }
[Display(Name = "پست الکترونیک")] //[Display(Name = "پست الکترونیک")]
public string? Email { get; set; } public string? Email { get; set; }
[Display(Name = "آدرس")] [Display(Name = "آدرس")]
public string? Address { get; set; } public string? Address { get; set; }
[Display(Name = "کد اقتصادی")] [Display(Name = "کد اقتصادی")]
public string? EconomicCode { get; set; } public string? EconomicCode { get; set; }
[Display(Name = "کد شعبه")] //[Display(Name = "کد شعبه")]
public string? BranchID { get; set; }// public string? BranchID { get; set; }//
[Display(Name = "توضیحات")] //[Display(Name = "توضیحات")]
public string? Info { get; set; }// public string? Info { get; set; }//
//------------ //------------

View File

@@ -13,8 +13,8 @@
<div class="row g-3"> <div class="row g-3">
<div class="form-group col-md-6"> <div class="form-group col-md-6">
<label class="col-sm-4 col-form-label" style="color:red" for="inputFullName">نام کامل</label> <label class="col-sm-4 col-form-label" style="color:red" for="inputFullName">نام کامل</label>
<InputText @bind-Value="Cus.FullName" type="text" class="form-control" id="inputFullName" placeholder="نام کامل"/> <InputText @bind-Value="Cus.FullName" type="text" class="form-control" id="inputFullName" placeholder="نام کامل" />
</div> </div>
<div class="form-group col-md-6"> <div class="form-group col-md-6">
<label class="col-sm-4 col-form-label" style="color:red" for="inputcustomertype">نوع مشتری</label> <label class="col-sm-4 col-form-label" style="color:red" for="inputcustomertype">نوع مشتری</label>
<select @bind="ItemSearchCustomertype" class="form-control" aria-label="Default select example" id="inputcustomertype"> <select @bind="ItemSearchCustomertype" class="form-control" aria-label="Default select example" id="inputcustomertype">
@@ -26,46 +26,46 @@
</select> </select>
</div> </div>
</div> </div>
<div class="row g-3"> <div class="row g-3">
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">تلفن</label> <label class="col-sm-4 col-form-label">تلفن</label>
<InputText @bind-Value="Cus.Phone" type="text" class="form-control" id="inputPhone" placeholder="تلفن"/> <InputText @bind-Value="Cus.Phone" type="text" class="form-control" id="inputPhone" placeholder="تلفن" />
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">آدرس</label> <label class="col-sm-4 col-form-label">آدرس</label>
<InputText @bind-Value="Cus.Address" type="text" class="form-control" id="inputAddress" placeholder="آدرس"/> <InputText @bind-Value="Cus.Address" type="text" class="form-control" id="inputAddress" placeholder="آدرس" />
</div> </div>
</div> </div>
<div class="row g-3"> <div class="row g-3">
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">پست الکترونیک</label> <label class="col-sm-4 col-form-label">پست الکترونیک</label>
<InputText @bind-Value="Cus.Email" type="email" class="form-control" id="inputEmail" placeholder="پست الکترونیک"/> <InputText @bind-Value="Cus.Email" type="email" class="form-control" id="inputEmail" placeholder="پست الکترونیک" />
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">کد پستی</label> <label class="col-sm-4 col-form-label">کد پستی</label>
<InputText @bind-Value="Cus.ZipCode" type="text" class="form-control" id="inputZipCode" placeholder="کد پستی"/> <InputText @bind-Value="Cus.ZipCode" type="text" class="form-control" id="inputZipCode" placeholder="کد پستی" />
</div> </div>
</div> </div>
<div class="row g-3"> <div class="row g-3">
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">کد اقتصادی</label> <label class="col-sm-4 col-form-label">کد اقتصادی</label>
<InputText @bind-Value="Cus.EconomicCode" type="text" class="form-control" id="inputEconomicCode" placeholder="کد اقتصادی"/> <InputText @bind-Value="Cus.EconomicCode" type="text" class="form-control" id="inputEconomicCode" placeholder="کد اقتصادی" />
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">کد ملی</label> <label class="col-sm-4 col-form-label">کد ملی</label>
<InputText @bind-Value="Cus.MeliCode" type="text" class="form-control" id="inputMeliCode" placeholder="کدملی"/> <InputText @bind-Value="Cus.MeliCode" type="text" class="form-control" id="inputMeliCode" placeholder="کدملی" />
</div> </div>
</div> </div>
<div class="row g-3"> <div class="row g-3">
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">کد شعبه</label> <label class="col-sm-4 col-form-label">کد شعبه</label>
<InputText @bind-Value="Cus.BranchID" type="text" class="form-control" id="inputBranchID" placeholder="کد شعبه"/> <InputText @bind-Value="Cus.BranchID" type="text" class="form-control" id="inputBranchID" placeholder="کد شعبه" />
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<label class="col-sm-4 col-form-label">شماره گذرنامه</label> <label class="col-sm-4 col-form-label">شماره گذرنامه</label>
<InputText @bind-Value="Cus.PassportNumber" type="text" class="form-control" id="inputPassportNumber" placeholder="شماره گذرنامه"/> <InputText @bind-Value="Cus.PassportNumber" type="text" class="form-control" id="inputPassportNumber" placeholder="شماره گذرنامه" />
</div> </div>
</div> </div>
@@ -74,14 +74,14 @@
<label class="col-sm-4 col-form-label">توضیحات</label> <label class="col-sm-4 col-form-label">توضیحات</label>
<InputTextArea @bind-Value="Cus.Info" class="form-control" id="inputMeliInfo" placeholder="توضیحات" rows="3"></InputTextArea> <InputTextArea @bind-Value="Cus.Info" class="form-control" id="inputMeliInfo" placeholder="توضیحات" rows="3"></InputTextArea>
</div> </div>
</div> </div>
</form> </form>
@if (Cus.ID==-1) @if (Cus.ID == 0)
{ {
<Button class="mt-3" Color="ButtonColor.Success" @onclick="OnClickAdd" Type="ButtonType.Button"> <Button class="mt-3" Color="ButtonColor.Success" @onclick="OnClickAdd" Type="ButtonType.Button">
جدید جدید
@@ -93,7 +93,7 @@ else
ثبت تغییرات ثبت تغییرات
</Button> </Button>
<Button class="mt-3" Color="ButtonColor.Danger" @onclick="OnClickDelete" Type="ButtonType.Button"> <Button class="mt-3" Color="ButtonColor.Danger" @onclick="OnClickDelete" Type="ButtonType.Button">
حذف حذف
</Button> </Button>
} }
@@ -111,11 +111,19 @@ else
public ActionInResultComponent result { get; set; } public ActionInResultComponent result { get; set; }
protected override Task OnParametersSetAsync() protected override Task OnParametersSetAsync()
{ {
result = new ActionInResultComponent(); if (Cus.CustomerType != null)
ItemSearchCustomertype = (int)Cus.CustomerType;
result = new ActionInResultComponent()
{
Status = ComponentStatus.fild
};
Hidealert = true;
alertMessage = "";
return base.OnParametersSetAsync(); return base.OnParametersSetAsync();
} }
} }
@functions{ @functions {
private void ShowSuccessAlert(string msg) private void ShowSuccessAlert(string msg)
{ {
Hidealert = false; Hidealert = false;
@@ -130,38 +138,88 @@ else
alertIconName = IconName.ExclamationTriangleFill; alertIconName = IconName.ExclamationTriangleFill;
alertMessage = msg; alertMessage = msg;
} }
public async Task OnClickDelete(){ public async Task OnClickDelete()
result.Action = ComponentAction.delete;
await OnMultipleOfThree.InvokeAsync(result);
}
public async Task OnClickUpdate()
{ {
result.Action = ComponentAction.update;
await OnMultipleOfThree.InvokeAsync(result);
}
public async Task OnClickAdd()
{
if (ItemSearchCustomertype > 0)
Cus.CustomerType = (CustomerType)ItemSearchCustomertype;
Cus.ID = null;
var rsp = await hc.Delete($"Customer/Delete/{Cus.ID}");
var rsp = await hc.Post<RCustomer>("Customer/Add", Cus);
if (rsp.IsSuccessStatusCode) if (rsp.IsSuccessStatusCode)
{ {
var request = await rsp.Content.ReadFromJsonAsync<bool>(); var request = await rsp.Content.ReadFromJsonAsync<bool>();
if (request) if (request)
{ {
result.Action = ComponentAction.add; result.Status = ComponentStatus.success;
result.Action = ComponentAction.delete;
await OnMultipleOfThree.InvokeAsync(result); await OnMultipleOfThree.InvokeAsync(result);
} }
else ShowDangerAlert("خطایی در اجرای عملیات رخ داده"); else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
} }
else
else if (rsp.StatusCode == System.Net.HttpStatusCode.NotFound)
{ {
var request = await rsp.Content.ReadFromJsonAsync<List<string>>(); ShowDangerAlert("مشتری با این شناسه یافت نشد");
ShowDangerAlert(request[0]);
} }
else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
}
public async Task OnClickUpdate()
{
if (ItemSearchCustomertype > 0 && !string.IsNullOrEmpty(Cus.FullName))
{
if (ItemSearchCustomertype > 0)
Cus.CustomerType = (CustomerType)ItemSearchCustomertype;
var rsp = await hc.Put<RCustomer>("Customer/Update", Cus);
if (rsp.IsSuccessStatusCode)
{
var request = await rsp.Content.ReadFromJsonAsync<bool>();
if (request)
{
result.Status = ComponentStatus.success;
result.Action = ComponentAction.update;
await OnMultipleOfThree.InvokeAsync(result);
}
else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
}
else
{
var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
ShowDangerAlert(request[0]);
}
}
else ShowDangerAlert("فیلدهای قرمز باید مقدار دهی شوند");
}
public async Task OnClickAdd()
{
if (ItemSearchCustomertype > 0 && !string.IsNullOrEmpty(Cus.FullName))
{
if (ItemSearchCustomertype > 0)
Cus.CustomerType = (CustomerType)ItemSearchCustomertype;
Cus.ID = null;
var rsp = await hc.Post<RCustomer>("Customer/Add", Cus);
if (rsp.IsSuccessStatusCode)
{
var request = await rsp.Content.ReadFromJsonAsync<bool>();
if (request)
{
result.Status = ComponentStatus.success;
result.Action = ComponentAction.add;
await OnMultipleOfThree.InvokeAsync(result);
}
else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
}
else
{
var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
ShowDangerAlert(request[0]);
}
}
else ShowDangerAlert("فیلدهای قرمز باید مقدار دهی شوند");
} }
} }

View File

@@ -23,8 +23,9 @@
@item.CustomAttributes.Where(w => w.AttributeType.Name == "DisplayAttribute").Select(s => s.NamedArguments.Where(w => w.MemberName == "Name").Select(ss => ss.TypedValue.Value).First()).First().ToString() @item.CustomAttributes.Where(w => w.AttributeType.Name == "DisplayAttribute").Select(s => s.NamedArguments.Where(w => w.MemberName == "Name").Select(ss => ss.TypedValue.Value).First()).First().ToString()
</th> </th>
} }
} }
<th>عملیات</th>
} }
</tr> </tr>
</thead> </thead>
@@ -32,20 +33,34 @@
@{ @{
foreach (var item in ModelinComponent) foreach (var item in ModelinComponent)
{ {
<tr> <tr>
@{ @{
properties = item.GetType().GetProperties(); properties = item.GetType().GetProperties();
int id = 0;
foreach (PropertyInfo property in properties) foreach (PropertyInfo property in properties)
{ {
if (property.Name.ToLower()=="id")
id =Convert.ToInt32(property.GetValue(item, null));
if (property.CustomAttributes.Any(w => w.AttributeType.Name == "DisplayAttribute")) if (property.CustomAttributes.Any(w => w.AttributeType.Name == "DisplayAttribute"))
{ {
<td>@property.GetValue(item, null)</td> <td>@property.GetValue(item, null)</td>
} }
} }
} if (id>0)
{
<td><button @onclick="()=>OnMultipleOfThree.InvokeAsync(Convert.ToInt32(id))" type="button" class="btn btn-link">ویرایش</button></td>
}
else
{
<td><button type="button" class="btn btn-link disabled">ویرایش</button></td>
}
}
</tr> </tr>
} }
} }
</tbody> </tbody>
</table> </table>
@@ -62,5 +77,5 @@
@code { @code {
[Parameter] [Parameter]
public List<T> ModelinComponent { get; set; } = new List<T>(); public List<T> ModelinComponent { get; set; } = new List<T>();
[Parameter] public EventCallback<int> OnMultipleOfThree { get; set; }
} }

View File

@@ -57,7 +57,7 @@
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<div class="col-auto"> <div class="col-auto">
<button type="submit" @onclick="()=>CustomerItem(null)" class="btn btn-primary">جدید</button> <button type="submit" @onclick="()=>CustomerItem(0)" class="btn btn-primary">جدید</button>
</div> </div>
</div> </div>
</div> </div>
@@ -77,7 +77,7 @@
@* data *@ @* data *@
@if (request != null) @if (request != null)
{ {
<LTable ModelinComponent="request?.list" /> <LTable ModelinComponent="request?.list" OnMultipleOfThree="EventCallback.Factory.Create<int>(this,CustomerItem)" />
@* pagination *@ @* pagination *@
<p style="color:red">@request?.RowCount آیتم یافت شد</p> <p style="color:red">@request?.RowCount آیتم یافت شد</p>
<nav aria-label="Page navigation"> <nav aria-label="Page navigation">
@@ -172,10 +172,10 @@
if (result.Action == ComponentAction.add) if (result.Action == ComponentAction.add)
{ {
if (result.Status==ComponentStatus.success) if (result.Status==ComponentStatus.success)
ShowSuccessAlert("مشتری جدید با موفقیت اضافه شد"); ShowSuccessAlert("مشتری جدید با موفقیت اضافه شد");
} }
else if (result.Action == ComponentAction.update) else if (result.Action == ComponentAction.update)
{ {
if (result.Status == ComponentStatus.success) if (result.Status == ComponentStatus.success)
ShowSuccessAlert("اطلاعات مشتری با موفقیت ویرایش شد"); ShowSuccessAlert("اطلاعات مشتری با موفقیت ویرایش شد");
@@ -183,23 +183,25 @@
else if (result.Action == ComponentAction.delete) else if (result.Action == ComponentAction.delete)
{ {
if (result.Status == ComponentStatus.success) if (result.Status == ComponentStatus.success)
ShowSuccessAlert("مشتری با موفقیت حذف شد"); ShowSuccessAlert("مشتری با موفقیت حذف شد");
} }
if (result.Status == ComponentStatus.success) if (result.Status == ComponentStatus.success)
await LoadCus(1); await LoadCus(1);
await modal.HideAsync(); await modal.HideAsync();
} }
public async Task CustomerItem(int? ID) public async Task CustomerItem(int ID)
{ {
var parameters = new Dictionary<string, object>(); var parameters = new Dictionary<string, object>();
if(ID == null) parameters.Add("Cus", new RCustomer(){ID=-1}); if(ID == 0) parameters.Add("Cus", new RCustomer(){ID=0});
else parameters.Add("Cus", request.list.Where(w=>w.ID==ID)); else parameters.Add("Cus", request.list.Where(w=>w.ID==ID).First().Clone());
parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<ActionInResultComponent>(this, CallBackCustomerItem)); parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<ActionInResultComponent>(this, CallBackCustomerItem));
await modal.ShowAsync<CustomerItem>(title: ID == null ? "مشتری جدید" : "ویرایش اطلاعات", parameters: parameters); await modal.ShowAsync<CustomerItem>(title: ID == null ? "مشتری جدید" : "ویرایش اطلاعات", parameters: parameters);
} }
} }

View File

@@ -0,0 +1,12 @@
namespace Front.Services
{
public static class ExMethod
{
public static T Clone<T>(this T obj)
{
var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return (T)inst?.Invoke(obj, null);
}
}
}

View File

@@ -24,6 +24,13 @@ namespace Front.Services
_nav.NavigateTo("/Sign-in/unon"); _nav.NavigateTo("/Sign-in/unon");
return request; return request;
} }
public async Task<HttpResponseMessage> Delete(string route)
{
var request = await _hc.DeleteAsync(route);
if (request.StatusCode == System.Net.HttpStatusCode.Unauthorized)
_nav.NavigateTo("/Sign-in/unon");
return request;
}
public async Task<HttpResponseMessage> Post<T>(string route,T mode) public async Task<HttpResponseMessage> Post<T>(string route,T mode)
{ {
var request = await _hc.PostAsJsonAsync(route,mode); var request = await _hc.PostAsJsonAsync(route,mode);

View File

@@ -9,6 +9,7 @@ namespace Front.Services
{ {
_user = user; _user = user;
} }
public async Task<bool> OnlineUser() public async Task<bool> OnlineUser()
{ {
if (_user != null && !string.IsNullOrEmpty(_user.Token) && _user.exitDate.AddMinutes(-5) > DateTime.Now) if (_user != null && !string.IsNullOrEmpty(_user.Token) && _user.exitDate.AddMinutes(-5) > DateTime.Now)