initial commit

This commit is contained in:
2026-07-21 15:36:49 +07:00
commit 77f66132bc
2640 changed files with 850901 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\Application\Application.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure\Infrastructure.csproj" />
</ItemGroup>
</Project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
</PropertyGroup>
</Project>
@@ -0,0 +1,118 @@
using Application;
using ASPNET.BackEnd.Common.Handlers;
using Infrastructure;
using Infrastructure.DataAccessManager.EFCore;
using Infrastructure.SeedManager;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;
namespace ASPNET.BackEnd;
public static class BackEndConfiguration
{
public static IServiceCollection AddBackEndServices(this IServiceCollection services, IConfiguration configuration)
{
//>>> Application Layer
services.AddApplicationServices();
//>>> Infrastructure Layer
services.AddInfrastructureServices(configuration);
services.AddExceptionHandler<CustomExceptionHandler>();
//>>> Common
services.AddHttpContextAccessor();
services.AddCors(opt =>
{
opt.AddDefaultPolicy(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.WriteIndented = true;
});
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Indotalent API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
services.Configure<ApiBehaviorOptions>(x =>
{
x.SuppressModelStateInvalidFilter = true;
});
return services;
}
public static IEndpointRouteBuilder MapBackEndRoutes(this IEndpointRouteBuilder endpoints)
{
endpoints.MapControllers();
return endpoints;
}
public static IApplicationBuilder RegisterBackEndBuilder(
this IApplicationBuilder app,
IWebHostEnvironment environment,
IHost host,
IConfiguration configuration
)
{
// >>> Create database
host.CreateDatabase();
//seed database with system data
host.SeedSystemData();
//seed database with demo data
if (configuration.GetValue<bool>("IsDemoVersion"))
{
host.SeedDemoData();
}
if (environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Indotalent V1");
});
}
return app;
}
}
@@ -0,0 +1,16 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Common.Base;
[ApiController]
[Route("api/[controller]/[action]")]
public abstract class BaseApiController : ControllerBase
{
protected readonly ISender _sender;
protected BaseApiController(ISender sender)
{
_sender = sender;
}
}
@@ -0,0 +1,54 @@
using ASPNET.BackEnd.Common.Models;
using Microsoft.AspNetCore.Diagnostics;
namespace ASPNET.BackEnd.Common.Handlers;
public class CustomExceptionHandler : IExceptionHandler
{
private readonly Dictionary<Type, Func<HttpContext, Exception, Task>> _exceptionHandlers;
public CustomExceptionHandler()
{
_exceptionHandlers = new()
{
{ typeof(Exception), HandleException },
};
}
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
var exceptionType = exception.GetType();
if (_exceptionHandlers.ContainsKey(exceptionType))
{
await _exceptionHandlers[exceptionType].Invoke(httpContext, exception);
return true;
}
else
{
await HandleException(httpContext, exception);
return true;
}
}
private async Task HandleException(HttpContext httpContext, Exception ex)
{
var statusCode = httpContext.Response.StatusCode != 200
? httpContext.Response.StatusCode
: StatusCodes.Status500InternalServerError;
var errorMessage = ex.Message;
var result = new ApiErrorResult
{
Code = statusCode,
Message = $"Exception: {errorMessage}",
Error = new Error(ex.InnerException?.Message, ex.Source, ex.StackTrace, ex.GetType().Name)
};
httpContext.Response.ContentType = "application/json";
await httpContext.Response.WriteAsJsonAsync(result);
}
}
@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Diagnostics;
namespace ASPNET.BackEnd.Common.Middlewares;
public class GlobalApiExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
public GlobalApiExceptionHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext, IExceptionHandler customExceptionHandler)
{
try
{
await _next(httpContext);
switch (httpContext.Response.StatusCode)
{
case StatusCodes.Status401Unauthorized:
await customExceptionHandler.TryHandleAsync(
httpContext,
new UnauthorizedAccessException("Unauthorized - Token missing or invalid"),
CancellationToken.None
);
break;
case StatusCodes.Status403Forbidden:
await customExceptionHandler.TryHandleAsync(
httpContext,
new Exception("Forbidden - Access denied"),
CancellationToken.None
);
break;
default:
// Let other status codes pass through
break;
}
}
catch (Exception ex)
{
await customExceptionHandler.TryHandleAsync(httpContext, ex, CancellationToken.None);
}
}
}
@@ -0,0 +1,8 @@
namespace ASPNET.BackEnd.Common.Models;
public class ApiErrorResult
{
public int? Code { get; init; }
public string? Message { get; init; }
public Error? Error { get; init; }
}
@@ -0,0 +1,8 @@
namespace ASPNET.BackEnd.Common.Models;
public class ApiSuccessResult<T>
{
public int? Code { get; init; }
public string? Message { get; init; }
public T? Content { get; init; }
}
@@ -0,0 +1,23 @@
namespace ASPNET.BackEnd.Common.Models;
public class Error
{
public Error(
string? innerException,
string? source,
string? stackTrace,
string? exceptionType)
{
Ref = "https://datatracker.ietf.org/doc/html/rfc9110";
InnerException = innerException;
Source = source?.Trim();
StackTrace = stackTrace?.Trim();
ExceptionType = exceptionType;
}
public string Ref { get; set; }
public string? ExceptionType { get; init; }
public string? InnerException { get; init; }
public string? Source { get; init; }
public string? StackTrace { get; init; }
}
@@ -0,0 +1,139 @@
using Application.Features.BudgetManager.Commands;
using Application.Features.BudgetManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class BudgetController : BaseApiController
{
public BudgetController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateBudget")]
public async Task<ActionResult<ApiSuccessResult<CreateBudgetResult>>> CreateBudgetAsync(CreateBudgetRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateBudgetResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateBudgetAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateBudget")]
public async Task<ActionResult<ApiSuccessResult<UpdateBudgetResult>>> UpdateBudgetAsync(UpdateBudgetRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateBudgetResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateBudgetAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteBudget")]
public async Task<ActionResult<ApiSuccessResult<DeleteBudgetResult>>> DeleteBudgetAsync(DeleteBudgetRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteBudgetResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteBudgetAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetBudgetList")]
public async Task<ActionResult<ApiSuccessResult<GetBudgetListResult>>> GetBudgetListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetBudgetListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetBudgetListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetBudgetListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetBudgetStatusList")]
public async Task<ActionResult<ApiSuccessResult<GetBudgetStatusListResult>>> GetBudgetStatusListAsync(
CancellationToken cancellationToken
)
{
var request = new GetBudgetStatusListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetBudgetStatusListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetBudgetStatusListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetBudgetSingle")]
public async Task<ActionResult<ApiSuccessResult<GetBudgetSingleResult>>> GetBudgetSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetBudgetSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetBudgetSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetBudgetSingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetBudgetByCampaignIdList")]
public async Task<ActionResult<ApiSuccessResult<GetBudgetByCampaignIdListResult>>> GetBudgetByCampaignIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string campaignId
)
{
var request = new GetBudgetByCampaignIdListRequest { CampaignId = campaignId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetBudgetByCampaignIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetBudgetByCampaignIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,121 @@
using Application.Features.CampaignManager.Commands;
using Application.Features.CampaignManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class CampaignController : BaseApiController
{
public CampaignController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateCampaign")]
public async Task<ActionResult<ApiSuccessResult<CreateCampaignResult>>> CreateCampaignAsync(CreateCampaignRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateCampaignResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateCampaignAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateCampaign")]
public async Task<ActionResult<ApiSuccessResult<UpdateCampaignResult>>> UpdateCampaignAsync(UpdateCampaignRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateCampaignResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateCampaignAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteCampaign")]
public async Task<ActionResult<ApiSuccessResult<DeleteCampaignResult>>> DeleteCampaignAsync(DeleteCampaignRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteCampaignResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteCampaignAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCampaignList")]
public async Task<ActionResult<ApiSuccessResult<GetCampaignListResult>>> GetCampaignListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetCampaignListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCampaignListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCampaignListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCampaignStatusList")]
public async Task<ActionResult<ApiSuccessResult<GetCampaignStatusListResult>>> GetCampaignStatusListAsync(
CancellationToken cancellationToken
)
{
var request = new GetCampaignStatusListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCampaignStatusListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCampaignStatusListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCampaignSingle")]
public async Task<ActionResult<ApiSuccessResult<GetCampaignSingleResult>>> GetCampaignSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetCampaignSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCampaignSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCampaignSingleAsync)}",
Content = response
});
}
}
@@ -0,0 +1,73 @@
using Application.Features.CompanyManager.Commands;
using Application.Features.CompanyManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class CompanyController : BaseApiController
{
public CompanyController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("UpdateCompany")]
public async Task<ActionResult<ApiSuccessResult<UpdateCompanyResult>>> UpdateCompanyAsync(UpdateCompanyRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateCompanyResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateCompanyAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCompanySingle")]
public async Task<ActionResult<ApiSuccessResult<GetCompanySingleResult>>> GetCompanySingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetCompanySingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCompanySingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCompanySingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCompanyList")]
public async Task<ActionResult<ApiSuccessResult<GetCompanyListResult>>> GetCompanyListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetCompanyListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCompanyListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCompanyListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.CustomerCategoryManager.Commands;
using Application.Features.CustomerCategoryManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class CustomerCategoryController : BaseApiController
{
public CustomerCategoryController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateCustomerCategory")]
public async Task<ActionResult<ApiSuccessResult<CreateCustomerCategoryResult>>> CreateCustomerCategoryAsync(CreateCustomerCategoryRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateCustomerCategoryResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateCustomerCategoryAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateCustomerCategory")]
public async Task<ActionResult<ApiSuccessResult<UpdateCustomerCategoryResult>>> UpdateCustomerCategoryAsync(UpdateCustomerCategoryRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateCustomerCategoryResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateCustomerCategoryAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteCustomerCategory")]
public async Task<ActionResult<ApiSuccessResult<DeleteCustomerCategoryResult>>> DeleteCustomerCategoryAsync(DeleteCustomerCategoryRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteCustomerCategoryResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteCustomerCategoryAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCustomerCategoryList")]
public async Task<ActionResult<ApiSuccessResult<GetCustomerCategoryListResult>>> GetCustomerCategoryListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetCustomerCategoryListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCustomerCategoryListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCustomerCategoryListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,101 @@
using Application.Features.CustomerContactManager.Commands;
using Application.Features.CustomerContactManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class CustomerContactController : BaseApiController
{
public CustomerContactController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateCustomerContact")]
public async Task<ActionResult<ApiSuccessResult<CreateCustomerContactResult>>> CreateCustomerContactAsync(CreateCustomerContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateCustomerContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateCustomerContactAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateCustomerContact")]
public async Task<ActionResult<ApiSuccessResult<UpdateCustomerContactResult>>> UpdateCustomerContactAsync(UpdateCustomerContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateCustomerContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateCustomerContactAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteCustomerContact")]
public async Task<ActionResult<ApiSuccessResult<DeleteCustomerContactResult>>> DeleteCustomerContactAsync(DeleteCustomerContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteCustomerContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteCustomerContactAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCustomerContactList")]
public async Task<ActionResult<ApiSuccessResult<GetCustomerContactListResult>>> GetCustomerContactListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetCustomerContactListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCustomerContactListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCustomerContactListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCustomerContactByCustomerIdList")]
public async Task<ActionResult<ApiSuccessResult<GetCustomerContactByCustomerIdListResult>>> GetCustomerContactByCustomerIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string customerId
)
{
var request = new GetCustomerContactByCustomerIdListRequest { CustomerId = customerId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCustomerContactByCustomerIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCustomerContactByCustomerIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.CustomerManager.Commands;
using Application.Features.CustomerManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class CustomerController : BaseApiController
{
public CustomerController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateCustomer")]
public async Task<ActionResult<ApiSuccessResult<CreateCustomerResult>>> CreateCustomerAsync(CreateCustomerRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateCustomerResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateCustomerAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateCustomer")]
public async Task<ActionResult<ApiSuccessResult<UpdateCustomerResult>>> UpdateCustomerAsync(UpdateCustomerRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateCustomerResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateCustomerAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteCustomer")]
public async Task<ActionResult<ApiSuccessResult<DeleteCustomerResult>>> DeleteCustomerAsync(DeleteCustomerRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteCustomerResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteCustomerAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCustomerList")]
public async Task<ActionResult<ApiSuccessResult<GetCustomerListResult>>> GetCustomerListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetCustomerListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCustomerListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCustomerListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.CustomerGroupManager.Commands;
using Application.Features.CustomerGroupManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class CustomerGroupController : BaseApiController
{
public CustomerGroupController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateCustomerGroup")]
public async Task<ActionResult<ApiSuccessResult<CreateCustomerGroupResult>>> CreateCustomerGroupAsync(CreateCustomerGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateCustomerGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateCustomerGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateCustomerGroup")]
public async Task<ActionResult<ApiSuccessResult<UpdateCustomerGroupResult>>> UpdateCustomerGroupAsync(UpdateCustomerGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateCustomerGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateCustomerGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteCustomerGroup")]
public async Task<ActionResult<ApiSuccessResult<DeleteCustomerGroupResult>>> DeleteCustomerGroupAsync(DeleteCustomerGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteCustomerGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteCustomerGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCustomerGroupList")]
public async Task<ActionResult<ApiSuccessResult<GetCustomerGroupListResult>>> GetCustomerGroupListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetCustomerGroupListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCustomerGroupListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCustomerGroupListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,170 @@
using Application.Features.DashboardManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class DashboardController : BaseApiController
{
public DashboardController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpGet("GetCRMDashboard")]
public async Task<ActionResult<ApiSuccessResult<GetCRMDashboardResult>>> GetCRMDashboardAsync(
CancellationToken cancellationToken
)
{
var request = new GetCRMDashboardRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCRMDashboardResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCRMDashboardAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadPipelineFunnel")]
public async Task<ActionResult<ApiSuccessResult<GetLeadPipelineFunnelResult>>> GetLeadPipelineFunnelAsync(
CancellationToken cancellationToken
)
{
var request = new GetLeadPipelineFunnelRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadPipelineFunnelResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadPipelineFunnelAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesTeamLeadClosing")]
public async Task<ActionResult<ApiSuccessResult<GetSalesTeamLeadClosingResult>>> GetSalesTeamLeadClosingAsync(
CancellationToken cancellationToken
)
{
var request = new GetSalesTeamLeadClosingRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesTeamLeadClosingResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesTeamLeadClosingAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCampaignByStatus")]
public async Task<ActionResult<ApiSuccessResult<GetCampaignByStatusResult>>> GetCampaignByStatusAsync(
CancellationToken cancellationToken
)
{
var request = new GetCampaignByStatusRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCampaignByStatusResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCampaignByStatusAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadActivityByType")]
public async Task<ActionResult<ApiSuccessResult<GetLeadActivityByTypeResult>>> GetLeadActivityByTypeAsync(
CancellationToken cancellationToken
)
{
var request = new GetLeadActivityByTypeRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadActivityByTypeResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadActivityByTypeAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetCardsDashboard")]
public async Task<ActionResult<ApiSuccessResult<GetCardsDashboardResult>>> GetCardsDashboardAsync(
CancellationToken cancellationToken
)
{
var request = new GetCardsDashboardRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetCardsDashboardResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetCardsDashboardAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesDashboard")]
public async Task<ActionResult<ApiSuccessResult<GetSalesDashboardResult>>> GetSalesDashboardAsync(
CancellationToken cancellationToken
)
{
var request = new GetSalesDashboardRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesDashboardResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesDashboardAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetPurchaseDashboard")]
public async Task<ActionResult<ApiSuccessResult<GetPurchaseDashboardResult>>> GetPurchaseDashboardAsync(
CancellationToken cancellationToken
)
{
var request = new GetPurchaseDashboardRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetPurchaseDashboardResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetPurchaseDashboardAsync)}",
Content = response
});
}
}
@@ -0,0 +1,139 @@
using Application.Features.ExpenseManager.Commands;
using Application.Features.ExpenseManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class ExpenseController : BaseApiController
{
public ExpenseController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateExpense")]
public async Task<ActionResult<ApiSuccessResult<CreateExpenseResult>>> CreateExpenseAsync(CreateExpenseRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateExpenseResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateExpenseAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateExpense")]
public async Task<ActionResult<ApiSuccessResult<UpdateExpenseResult>>> UpdateExpenseAsync(UpdateExpenseRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateExpenseResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateExpenseAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteExpense")]
public async Task<ActionResult<ApiSuccessResult<DeleteExpenseResult>>> DeleteExpenseAsync(DeleteExpenseRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteExpenseResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteExpenseAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetExpenseList")]
public async Task<ActionResult<ApiSuccessResult<GetExpenseListResult>>> GetExpenseListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetExpenseListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetExpenseListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetExpenseListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetExpenseStatusList")]
public async Task<ActionResult<ApiSuccessResult<GetExpenseStatusListResult>>> GetExpenseStatusListAsync(
CancellationToken cancellationToken
)
{
var request = new GetExpenseStatusListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetExpenseStatusListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetExpenseStatusListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetExpenseSingle")]
public async Task<ActionResult<ApiSuccessResult<GetExpenseSingleResult>>> GetExpenseSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetExpenseSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetExpenseSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetExpenseSingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetExpenseByCampaignIdList")]
public async Task<ActionResult<ApiSuccessResult<GetExpenseByCampaignIdListResult>>> GetExpenseByCampaignIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string campaignId
)
{
var request = new GetExpenseByCampaignIdListRequest { CampaignId = campaignId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetExpenseByCampaignIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetExpenseByCampaignIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,93 @@
using Application.Features.FileDocumentManager.Commands;
using Application.Features.FileDocumentManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using Infrastructure.FileDocumentManager;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class FileDocumentController : BaseApiController
{
public FileDocumentController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("UploadDocument")]
public async Task<ActionResult<CreateDocumentResult>> UploadDocumentAsync(IFormFile file, CancellationToken cancellationToken)
{
if (file == null || file.Length == 0)
{
return BadRequest("Invalid file.");
}
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream, cancellationToken);
var fileData = memoryStream.ToArray();
var extension = Path.GetExtension(file.FileName).TrimStart('.');
var command = new CreateDocumentRequest
{
OriginalFileName = file.FileName,
Extension = extension,
Data = fileData,
Size = fileData.Length
};
var result = await _sender.Send(command, cancellationToken);
if (result?.DocumentName == null)
{
return StatusCode(500, "An error occurred while uploading the document.");
}
return Ok(new ApiSuccessResult<CreateDocumentResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UploadDocumentAsync)}",
Content = result
});
}
}
[Authorize]
[HttpGet("GetDocument")]
public async Task<IActionResult> GetDocumentAsync(
[FromQuery] string documentName,
CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(documentName) || Path.GetExtension(documentName) == string.Empty)
{
documentName = "nodocument.txt";
}
var request = new GetDocumentRequest
{
DocumentName = documentName
};
var result = await _sender.Send(request, cancellationToken);
if (result?.Data == null)
{
return NotFound("Document not found.");
}
var extension = Path.GetExtension(documentName).ToLower();
var mimeType = FileDocumentHelper.GetMimeType(extension);
return File(result.Data, mimeType);
}
}
@@ -0,0 +1,93 @@
using Application.Features.FileImageManager.Commands;
using Application.Features.FileImageManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using Infrastructure.FileImageManager;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class FileImageController : BaseApiController
{
public FileImageController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("UploadImage")]
public async Task<ActionResult<CreateImageResult>> UploadImageAsync(IFormFile file, CancellationToken cancellationToken)
{
if (file == null || file.Length == 0)
{
return BadRequest("Invalid file.");
}
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream, cancellationToken);
var fileData = memoryStream.ToArray();
var extension = Path.GetExtension(file.FileName).TrimStart('.');
var command = new CreateImageRequest
{
OriginalFileName = file.FileName,
Extension = extension,
Data = fileData,
Size = fileData.Length
};
var result = await _sender.Send(command, cancellationToken);
if (result?.ImageName == null)
{
return StatusCode(500, "An error occurred while uploading the image.");
}
return Ok(new ApiSuccessResult<CreateImageResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UploadImageAsync)}",
Content = result
});
}
}
[Authorize]
[HttpGet("GetImage")]
public async Task<IActionResult> GetImageAsync(
[FromQuery] string imageName,
CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(imageName) || Path.GetExtension(imageName) == string.Empty)
{
imageName = "noimage.png";
}
var request = new GetImageRequest
{
ImageName = imageName
};
var result = await _sender.Send(request, cancellationToken);
if (result?.Data == null)
{
return NotFound("Image not found.");
}
var extension = Path.GetExtension(imageName).ToLower();
var mimeType = FileImageHelper.GetMimeType(extension);
return File(result.Data, mimeType);
}
}
@@ -0,0 +1,140 @@
using Application.Features.DeliveryOrderManager.Queries;
using Application.Features.LeadActivityManager.Commands;
using Application.Features.LeadActivityManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class LeadActivityController : BaseApiController
{
public LeadActivityController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateLeadActivity")]
public async Task<ActionResult<ApiSuccessResult<CreateLeadActivityResult>>> CreateLeadActivityAsync(CreateLeadActivityRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateLeadActivityResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateLeadActivityAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateLeadActivity")]
public async Task<ActionResult<ApiSuccessResult<UpdateLeadActivityResult>>> UpdateLeadActivityAsync(UpdateLeadActivityRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateLeadActivityResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateLeadActivityAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteLeadActivity")]
public async Task<ActionResult<ApiSuccessResult<DeleteLeadActivityResult>>> DeleteLeadActivityAsync(DeleteLeadActivityRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteLeadActivityResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteLeadActivityAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadActivityList")]
public async Task<ActionResult<ApiSuccessResult<GetLeadActivityListResult>>> GetLeadActivityListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetLeadActivityListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadActivityListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadActivityListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadActivitySingle")]
public async Task<ActionResult<ApiSuccessResult<GetLeadActivitySingleResult>>> GetLeadActivitySingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetLeadActivitySingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadActivitySingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadActivitySingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadActivityByLeadIdList")]
public async Task<ActionResult<ApiSuccessResult<GetLeadActivityByLeadIdListResult>>> GetLeadActivityByLeadIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string leadId
)
{
var request = new GetLeadActivityByLeadIdListRequest { LeadId = leadId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadActivityByLeadIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadActivityByLeadIdListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadActivityTypeList")]
public async Task<ActionResult<ApiSuccessResult<GetLeadActivityTypeListResult>>> GetLeadActivityTypeListAsync(
CancellationToken cancellationToken
)
{
var request = new GetLeadActivityTypeListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadActivityTypeListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadActivityTypeListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,121 @@
using Application.Features.LeadContactManager.Commands;
using Application.Features.LeadContactManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class LeadContactController : BaseApiController
{
public LeadContactController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateLeadContact")]
public async Task<ActionResult<ApiSuccessResult<CreateLeadContactResult>>> CreateLeadContactAsync(CreateLeadContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateLeadContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateLeadContactAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateLeadContact")]
public async Task<ActionResult<ApiSuccessResult<UpdateLeadContactResult>>> UpdateLeadContactAsync(UpdateLeadContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateLeadContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateLeadContactAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteLeadContact")]
public async Task<ActionResult<ApiSuccessResult<DeleteLeadContactResult>>> DeleteLeadContactAsync(DeleteLeadContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteLeadContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteLeadContactAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadContactList")]
public async Task<ActionResult<ApiSuccessResult<GetLeadContactListResult>>> GetLeadContactListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetLeadContactListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadContactListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadContactListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadContactSingle")]
public async Task<ActionResult<ApiSuccessResult<GetLeadContactSingleResult>>> GetLeadContactSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetLeadContactSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadContactSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadContactSingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadContactByLeadIdList")]
public async Task<ActionResult<ApiSuccessResult<GetLeadContactByLeadIdListResult>>> GetLeadContactByLeadIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string leadId
)
{
var request = new GetLeadContactByLeadIdListRequest { LeadId = leadId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadContactByLeadIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadContactByLeadIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,160 @@
using Application.Features.CampaignManager.Queries;
using Application.Features.LeadManager.Commands;
using Application.Features.LeadManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class LeadController : BaseApiController
{
public LeadController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateLead")]
public async Task<ActionResult<ApiSuccessResult<CreateLeadResult>>> CreateLeadAsync(CreateLeadRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateLeadResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateLeadAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateLead")]
public async Task<ActionResult<ApiSuccessResult<UpdateLeadResult>>> UpdateLeadAsync(UpdateLeadRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateLeadResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateLeadAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteLead")]
public async Task<ActionResult<ApiSuccessResult<DeleteLeadResult>>> DeleteLeadAsync(DeleteLeadRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteLeadResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteLeadAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadList")]
public async Task<ActionResult<ApiSuccessResult<GetLeadListResult>>> GetLeadListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetLeadListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadSingle")]
public async Task<ActionResult<ApiSuccessResult<GetLeadSingleResult>>> GetLeadSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetLeadSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadSingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetLeadByCampaignIdList")]
public async Task<ActionResult<ApiSuccessResult<GetLeadByCampaignIdListResult>>> GetLeadByCampaignIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetLeadByCampaignIdListRequest { CampaignId = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetLeadByCampaignIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetLeadByCampaignIdListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetPipelineStageList")]
public async Task<ActionResult<ApiSuccessResult<GetPipelineStageListResult>>> GetPipelineStageListAsync(
CancellationToken cancellationToken
)
{
var request = new GetPipelineStageListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetPipelineStageListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetPipelineStageListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetClosingStatusList")]
public async Task<ActionResult<ApiSuccessResult<GetClosingStatusListResult>>> GetClosingStatusListAsync(
CancellationToken cancellationToken
)
{
var request = new GetClosingStatusListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetClosingStatusListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetClosingStatusListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,41 @@
using Application.Features.NumberSequenceManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class NumberSequenceController : BaseApiController
{
public NumberSequenceController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpGet("GetNumberSequenceList")]
public async Task<ActionResult<ApiSuccessResult<GetNumberSequenceListResult>>> GetNumberSequenceListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetNumberSequenceListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetNumberSequenceListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetNumberSequenceListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.ProductManager.Commands;
using Application.Features.ProductManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class ProductController : BaseApiController
{
public ProductController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateProduct")]
public async Task<ActionResult<ApiSuccessResult<CreateProductResult>>> CreateProductAsync(CreateProductRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateProductResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateProductAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateProduct")]
public async Task<ActionResult<ApiSuccessResult<UpdateProductResult>>> UpdateProductAsync(UpdateProductRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateProductResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateProductAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteProduct")]
public async Task<ActionResult<ApiSuccessResult<DeleteProductResult>>> DeleteProductAsync(DeleteProductRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteProductResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteProductAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetProductList")]
public async Task<ActionResult<ApiSuccessResult<GetProductListResult>>> GetProductListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetProductListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetProductListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetProductListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.ProductGroupManager.Commands;
using Application.Features.ProductGroupManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class ProductGroupController : BaseApiController
{
public ProductGroupController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateProductGroup")]
public async Task<ActionResult<ApiSuccessResult<CreateProductGroupResult>>> CreateProductGroupAsync(CreateProductGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateProductGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateProductGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateProductGroup")]
public async Task<ActionResult<ApiSuccessResult<UpdateProductGroupResult>>> UpdateProductGroupAsync(UpdateProductGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateProductGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateProductGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteProductGroup")]
public async Task<ActionResult<ApiSuccessResult<DeleteProductGroupResult>>> DeleteProductGroupAsync(DeleteProductGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteProductGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteProductGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetProductGroupList")]
public async Task<ActionResult<ApiSuccessResult<GetProductGroupListResult>>> GetProductGroupListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetProductGroupListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetProductGroupListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetProductGroupListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,119 @@
using Application.Features.PurchaseOrderManager.Commands;
using Application.Features.PurchaseOrderManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class PurchaseOrderController : BaseApiController
{
public PurchaseOrderController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreatePurchaseOrder")]
public async Task<ActionResult<ApiSuccessResult<CreatePurchaseOrderResult>>> CreatePurchaseOrderAsync(CreatePurchaseOrderRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreatePurchaseOrderResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreatePurchaseOrderAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdatePurchaseOrder")]
public async Task<ActionResult<ApiSuccessResult<UpdatePurchaseOrderResult>>> UpdatePurchaseOrderAsync(UpdatePurchaseOrderRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdatePurchaseOrderResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdatePurchaseOrderAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeletePurchaseOrder")]
public async Task<ActionResult<ApiSuccessResult<DeletePurchaseOrderResult>>> DeletePurchaseOrderAsync(DeletePurchaseOrderRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeletePurchaseOrderResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeletePurchaseOrderAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetPurchaseOrderList")]
public async Task<ActionResult<ApiSuccessResult<GetPurchaseOrderListResult>>> GetPurchaseOrderListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetPurchaseOrderListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetPurchaseOrderListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetPurchaseOrderListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetPurchaseOrderStatusList")]
public async Task<ActionResult<ApiSuccessResult<GetPurchaseOrderStatusListResult>>> GetPurchaseOrderStatusListAsync(
CancellationToken cancellationToken
)
{
var request = new GetPurchaseOrderStatusListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetPurchaseOrderStatusListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetPurchaseOrderStatusListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetPurchaseOrderSingle")]
public async Task<ActionResult<ApiSuccessResult<GetPurchaseOrderSingleResult>>> GetPurchaseOrderSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetPurchaseOrderSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetPurchaseOrderSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetPurchaseOrderSingleAsync)}",
Content = response
});
}
}
@@ -0,0 +1,101 @@
using Application.Features.PurchaseOrderItemManager.Commands;
using Application.Features.PurchaseOrderItemManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class PurchaseOrderItemController : BaseApiController
{
public PurchaseOrderItemController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreatePurchaseOrderItem")]
public async Task<ActionResult<ApiSuccessResult<CreatePurchaseOrderItemResult>>> CreatePurchaseOrderItemAsync(CreatePurchaseOrderItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreatePurchaseOrderItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreatePurchaseOrderItemAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdatePurchaseOrderItem")]
public async Task<ActionResult<ApiSuccessResult<UpdatePurchaseOrderItemResult>>> UpdatePurchaseOrderItemAsync(UpdatePurchaseOrderItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdatePurchaseOrderItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdatePurchaseOrderItemAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeletePurchaseOrderItem")]
public async Task<ActionResult<ApiSuccessResult<DeletePurchaseOrderItemResult>>> DeletePurchaseOrderItemAsync(DeletePurchaseOrderItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeletePurchaseOrderItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeletePurchaseOrderItemAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetPurchaseOrderItemList")]
public async Task<ActionResult<ApiSuccessResult<GetPurchaseOrderItemListResult>>> GetPurchaseOrderItemListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetPurchaseOrderItemListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetPurchaseOrderItemListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetPurchaseOrderItemListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetPurchaseOrderItemByPurchaseOrderIdList")]
public async Task<ActionResult<ApiSuccessResult<GetPurchaseOrderItemByPurchaseOrderIdListResult>>> GetPurchaseOrderItemByPurchaseOrderIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string purchaseOrderId
)
{
var request = new GetPurchaseOrderItemByPurchaseOrderIdListRequest { PurchaseOrderId = purchaseOrderId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetPurchaseOrderItemByPurchaseOrderIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetPurchaseOrderItemByPurchaseOrderIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,118 @@
using Application.Features.SalesOrderManager.Commands;
using Application.Features.SalesOrderManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class SalesOrderController : BaseApiController
{
public SalesOrderController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateSalesOrder")]
public async Task<ActionResult<ApiSuccessResult<CreateSalesOrderResult>>> CreateSalesOrderAsync(CreateSalesOrderRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateSalesOrderResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateSalesOrderAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateSalesOrder")]
public async Task<ActionResult<ApiSuccessResult<UpdateSalesOrderResult>>> UpdateSalesOrderAsync(UpdateSalesOrderRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateSalesOrderResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateSalesOrderAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteSalesOrder")]
public async Task<ActionResult<ApiSuccessResult<DeleteSalesOrderResult>>> DeleteSalesOrderAsync(DeleteSalesOrderRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteSalesOrderResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteSalesOrderAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesOrderList")]
public async Task<ActionResult<ApiSuccessResult<GetSalesOrderListResult>>> GetSalesOrderListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetSalesOrderListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesOrderListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesOrderListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesOrderStatusList")]
public async Task<ActionResult<ApiSuccessResult<GetSalesOrderStatusListResult>>> GetSalesOrderStatusListAsync(
CancellationToken cancellationToken
)
{
var request = new GetSalesOrderStatusListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesOrderStatusListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesOrderStatusListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesOrderSingle")]
public async Task<ActionResult<ApiSuccessResult<GetSalesOrderSingleResult>>> GetSalesOrderSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetSalesOrderSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesOrderSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesOrderSingleAsync)}",
Content = response
});
}
}
@@ -0,0 +1,101 @@
using Application.Features.SalesOrderItemManager.Commands;
using Application.Features.SalesOrderItemManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class SalesOrderItemController : BaseApiController
{
public SalesOrderItemController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateSalesOrderItem")]
public async Task<ActionResult<ApiSuccessResult<CreateSalesOrderItemResult>>> CreateSalesOrderItemAsync(CreateSalesOrderItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateSalesOrderItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateSalesOrderItemAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateSalesOrderItem")]
public async Task<ActionResult<ApiSuccessResult<UpdateSalesOrderItemResult>>> UpdateSalesOrderItemAsync(UpdateSalesOrderItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateSalesOrderItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateSalesOrderItemAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteSalesOrderItem")]
public async Task<ActionResult<ApiSuccessResult<DeleteSalesOrderItemResult>>> DeleteSalesOrderItemAsync(DeleteSalesOrderItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteSalesOrderItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteSalesOrderItemAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesOrderItemList")]
public async Task<ActionResult<ApiSuccessResult<GetSalesOrderItemListResult>>> GetSalesOrderItemListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetSalesOrderItemListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesOrderItemListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesOrderItemListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesOrderItemBySalesOrderIdList")]
public async Task<ActionResult<ApiSuccessResult<GetSalesOrderItemBySalesOrderIdListResult>>> GetSalesOrderItemBySalesOrderIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string salesOrderId
)
{
var request = new GetSalesOrderItemBySalesOrderIdListRequest { SalesOrderId = salesOrderId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesOrderItemBySalesOrderIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesOrderItemBySalesOrderIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,121 @@
using Application.Features.SalesRepresentativeManager.Commands;
using Application.Features.SalesRepresentativeManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class SalesRepresentativeController : BaseApiController
{
public SalesRepresentativeController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateSalesRepresentative")]
public async Task<ActionResult<ApiSuccessResult<CreateSalesRepresentativeResult>>> CreateSalesRepresentativeAsync(CreateSalesRepresentativeRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateSalesRepresentativeResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateSalesRepresentativeAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateSalesRepresentative")]
public async Task<ActionResult<ApiSuccessResult<UpdateSalesRepresentativeResult>>> UpdateSalesRepresentativeAsync(UpdateSalesRepresentativeRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateSalesRepresentativeResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateSalesRepresentativeAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteSalesRepresentative")]
public async Task<ActionResult<ApiSuccessResult<DeleteSalesRepresentativeResult>>> DeleteSalesRepresentativeAsync(DeleteSalesRepresentativeRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteSalesRepresentativeResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteSalesRepresentativeAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesRepresentativeList")]
public async Task<ActionResult<ApiSuccessResult<GetSalesRepresentativeListResult>>> GetSalesRepresentativeListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetSalesRepresentativeListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesRepresentativeListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesRepresentativeListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesRepresentativeSingle")]
public async Task<ActionResult<ApiSuccessResult<GetSalesRepresentativeSingleResult>>> GetSalesRepresentativeSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetSalesRepresentativeSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesRepresentativeSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesRepresentativeSingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesRepresentativeBySalesTeamIdList")]
public async Task<ActionResult<ApiSuccessResult<GetSalesRepresentativeBySalesTeamIdListResult>>> GetSalesRepresentativeBySalesTeamIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetSalesRepresentativeBySalesTeamIdListRequest { SalesTeamId = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesRepresentativeBySalesTeamIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesRepresentativeBySalesTeamIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,102 @@
using Application.Features.SalesTeamManager.Commands;
using Application.Features.SalesTeamManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class SalesTeamController : BaseApiController
{
public SalesTeamController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateSalesTeam")]
public async Task<ActionResult<ApiSuccessResult<CreateSalesTeamResult>>> CreateSalesTeamAsync(CreateSalesTeamRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateSalesTeamResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateSalesTeamAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateSalesTeam")]
public async Task<ActionResult<ApiSuccessResult<UpdateSalesTeamResult>>> UpdateSalesTeamAsync(UpdateSalesTeamRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateSalesTeamResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateSalesTeamAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteSalesTeam")]
public async Task<ActionResult<ApiSuccessResult<DeleteSalesTeamResult>>> DeleteSalesTeamAsync(DeleteSalesTeamRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteSalesTeamResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteSalesTeamAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesTeamList")]
public async Task<ActionResult<ApiSuccessResult<GetSalesTeamListResult>>> GetSalesTeamListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetSalesTeamListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesTeamListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesTeamListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetSalesTeamSingle")]
public async Task<ActionResult<ApiSuccessResult<GetSalesTeamSingleResult>>> GetSalesTeamSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetSalesTeamSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetSalesTeamSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetSalesTeamSingleAsync)}",
Content = response
});
}
}
@@ -0,0 +1,356 @@
using Application.Features.SecurityManager.Commands;
using Application.Features.SecurityManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class SecurityController : BaseApiController
{
private readonly IConfiguration _configuration;
public SecurityController(ISender sender, IConfiguration configuration) : base(sender)
{
_configuration = configuration;
}
[AllowAnonymous]
[HttpPost("Login")]
public async Task<ActionResult<ApiSuccessResult<LoginResult>>> LoginAsync(LoginRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<LoginResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(LoginAsync)}",
Content = response
});
}
[AllowAnonymous]
[HttpPost("Logout")]
public async Task<ActionResult<ApiSuccessResult<LogoutResult>>> LogoutAsync(LogoutRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<LogoutResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(LogoutAsync)}",
Content = response
});
}
[AllowAnonymous]
[HttpPost("Register")]
public async Task<ActionResult<ApiSuccessResult<RegisterResult>>> RegisterAsync(
RegisterRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<RegisterResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(RegisterAsync)}",
Content = response
});
}
[AllowAnonymous]
[HttpGet("ConfirmEmail")]
public async Task<ActionResult<ApiSuccessResult<ConfirmEmailResult>>> ConfirmEmailAsync(
[FromQuery] string email,
[FromQuery] string code,
CancellationToken cancellationToken
)
{
var request = new ConfirmEmailRequest { Email = email, Code = code };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<ConfirmEmailResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(ConfirmEmailAsync)}",
Content = response
});
}
[AllowAnonymous]
[HttpPost("ForgotPassword")]
public async Task<ActionResult<ApiSuccessResult<ForgotPasswordResult>>> ForgotPasswordAsync(
ForgotPasswordRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<ForgotPasswordResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(ForgotPasswordAsync)}",
Content = response
});
}
[AllowAnonymous]
[HttpGet("ForgotPasswordConfirmation")]
public async Task<ActionResult<ApiSuccessResult<ForgotPasswordConfirmationResult>>> ForgotPasswordConfirmationAsync(
[FromQuery] string email,
[FromQuery] string code,
[FromQuery] string tempPassword,
CancellationToken cancellationToken)
{
var request = new ForgotPasswordConfirmationRequest { Email = email, TempPassword = tempPassword, Code = code };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<ForgotPasswordConfirmationResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(ForgotPasswordConfirmationAsync)}",
Content = response
});
}
[AllowAnonymous]
[HttpPost("RefreshToken")]
public async Task<ActionResult<ApiSuccessResult<RefreshTokenResult>>> RefreshTokenAsync(RefreshTokenRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<RefreshTokenResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(RefreshTokenAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("ValidateToken")]
public async Task<ActionResult<ApiSuccessResult<ValidateTokenResult>>> ValidateTokenAsync(
ValidateTokenRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<ValidateTokenResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(ValidateTokenAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetMyProfileList")]
public async Task<ActionResult<ApiSuccessResult<GetMyProfileListResult>>> GetMyProfileListAsync(
[FromQuery] string userId,
CancellationToken cancellationToken
)
{
var request = new GetMyProfileListRequest { UserId = userId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetMyProfileListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetMyProfileListAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateMyProfile")]
public async Task<ActionResult<ApiSuccessResult<UpdateMyProfileResult>>> UpdateMyProfileAsync(
UpdateMyProfileRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateMyProfileResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateMyProfileAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateMyProfilePassword")]
public async Task<ActionResult<ApiSuccessResult<UpdateMyProfilePasswordResult>>> UpdateMyProfilePasswordAsync(
UpdateMyProfilePasswordRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateMyProfilePasswordResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateMyProfilePasswordAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetRoleList")]
public async Task<ActionResult<ApiSuccessResult<GetRoleListResult>>> GetRoleListAsync(
CancellationToken cancellationToken
)
{
var request = new GetRoleListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetRoleListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetRoleListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetUserList")]
public async Task<ActionResult<ApiSuccessResult<GetUserListResult>>> GetUserListAsync(
CancellationToken cancellationToken
)
{
var request = new GetUserListRequest { };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetUserListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetUserListAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("CreateUser")]
public async Task<ActionResult<ApiSuccessResult<CreateUserResult>>> CreateUserAsync(
CreateUserRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateUserResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateUserAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateUser")]
public async Task<ActionResult<ApiSuccessResult<UpdateUserResult>>> UpdateUserAsync(
UpdateUserRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateUserResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateUserAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteUser")]
public async Task<ActionResult<ApiSuccessResult<DeleteUserResult>>> DeleteUserAsync(
DeleteUserRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteUserResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteUserAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdatePasswordUser")]
public async Task<ActionResult<ApiSuccessResult<UpdatePasswordUserResult>>> UpdatePasswordUserAsync(
UpdatePasswordUserRequest request,
CancellationToken cancellationToken
)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdatePasswordUserResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdatePasswordUserAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("GetUserRoles")]
public async Task<ActionResult<ApiSuccessResult<GetUserRolesResult>>> GetUserRolesAsync(GetUserRolesRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetUserRolesResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetUserRolesAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateUserRole")]
public async Task<ActionResult<ApiSuccessResult<UpdateUserRoleResult>>> UpdateUserRoleAsync(UpdateUserRoleRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateUserRoleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateUserRoleAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateMyProfileAvatar")]
public async Task<ActionResult<ApiSuccessResult<UpdateMyProfileAvatarResult>>> UpdateMyProfileAvatarAsync(UpdateMyProfileAvatarRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateMyProfileAvatarResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateMyProfileAvatarAsync)}",
Content = response
});
}
}
@@ -0,0 +1,84 @@
using Application.Features.TaxManager.Commands;
using Application.Features.TaxManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class TaxController : BaseApiController
{
public TaxController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateTax")]
public async Task<ActionResult<ApiSuccessResult<CreateTaxResult>>> CreateTaxAsync(CreateTaxRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateTaxResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateTaxAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateTax")]
public async Task<ActionResult<ApiSuccessResult<UpdateTaxResult>>> UpdateTaxAsync(UpdateTaxRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateTaxResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateTaxAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteTax")]
public async Task<ActionResult<ApiSuccessResult<DeleteTaxResult>>> DeleteTaxAsync(DeleteTaxRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteTaxResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteTaxAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetTaxList")]
public async Task<ActionResult<ApiSuccessResult<GetTaxListResult>>> GetTaxListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetTaxListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetTaxListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetTaxListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,101 @@
using Application.Features.TodoManager.Commands;
using Application.Features.TodoManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class TodoController : BaseApiController
{
public TodoController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateTodo")]
public async Task<ActionResult<ApiSuccessResult<CreateTodoResult>>> CreateTodoAsync(CreateTodoRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateTodoResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateTodoAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateTodo")]
public async Task<ActionResult<ApiSuccessResult<UpdateTodoResult>>> UpdateTodoAsync(UpdateTodoRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateTodoResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateTodoAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteTodo")]
public async Task<ActionResult<ApiSuccessResult<DeleteTodoResult>>> DeleteTodoAsync(DeleteTodoRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteTodoResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteTodoAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetTodoSingle")]
public async Task<ActionResult<ApiSuccessResult<GetTodoSingleResult>>> GetTodoSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetTodoSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetTodoSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetTodoSingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetTodoList")]
public async Task<ActionResult<ApiSuccessResult<GetTodoListResult>>> GetTodoListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetTodoListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetTodoListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetTodoListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,101 @@
using Application.Features.TodoItemManager.Commands;
using Application.Features.TodoItemManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class TodoItemController : BaseApiController
{
public TodoItemController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateTodoItem")]
public async Task<ActionResult<ApiSuccessResult<CreateTodoItemResult>>> CreateTodoItemAsync(CreateTodoItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateTodoItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateTodoItemAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateTodoItem")]
public async Task<ActionResult<ApiSuccessResult<UpdateTodoItemResult>>> UpdateTodoItemAsync(UpdateTodoItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateTodoItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateTodoItemAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteTodoItem")]
public async Task<ActionResult<ApiSuccessResult<DeleteTodoItemResult>>> DeleteTodoItemAsync(DeleteTodoItemRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteTodoItemResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteTodoItemAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetTodoItemSingle")]
public async Task<ActionResult<ApiSuccessResult<GetTodoItemSingleResult>>> GetTodoItemSingleAsync(
CancellationToken cancellationToken,
[FromQuery] string id
)
{
var request = new GetTodoItemSingleRequest { Id = id };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetTodoItemSingleResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetTodoItemSingleAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetTodoItemList")]
public async Task<ActionResult<ApiSuccessResult<GetTodoItemListResult>>> GetTodoItemListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetTodoItemListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetTodoItemListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetTodoItemListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.UnitMeasureManager.Commands;
using Application.Features.UnitMeasureManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class UnitMeasureController : BaseApiController
{
public UnitMeasureController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateUnitMeasure")]
public async Task<ActionResult<ApiSuccessResult<CreateUnitMeasureResult>>> CreateUnitMeasureAsync(CreateUnitMeasureRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateUnitMeasureResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateUnitMeasureAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateUnitMeasure")]
public async Task<ActionResult<ApiSuccessResult<UpdateUnitMeasureResult>>> UpdateUnitMeasureAsync(UpdateUnitMeasureRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateUnitMeasureResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateUnitMeasureAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteUnitMeasure")]
public async Task<ActionResult<ApiSuccessResult<DeleteUnitMeasureResult>>> DeleteUnitMeasureAsync(DeleteUnitMeasureRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteUnitMeasureResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteUnitMeasureAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetUnitMeasureList")]
public async Task<ActionResult<ApiSuccessResult<GetUnitMeasureListResult>>> GetUnitMeasureListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetUnitMeasureListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetUnitMeasureListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetUnitMeasureListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.VendorCategoryManager.Commands;
using Application.Features.VendorCategoryManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class VendorCategoryController : BaseApiController
{
public VendorCategoryController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateVendorCategory")]
public async Task<ActionResult<ApiSuccessResult<CreateVendorCategoryResult>>> CreateVendorCategoryAsync(CreateVendorCategoryRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateVendorCategoryResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateVendorCategoryAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateVendorCategory")]
public async Task<ActionResult<ApiSuccessResult<UpdateVendorCategoryResult>>> UpdateVendorCategoryAsync(UpdateVendorCategoryRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateVendorCategoryResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateVendorCategoryAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteVendorCategory")]
public async Task<ActionResult<ApiSuccessResult<DeleteVendorCategoryResult>>> DeleteVendorCategoryAsync(DeleteVendorCategoryRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteVendorCategoryResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteVendorCategoryAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetVendorCategoryList")]
public async Task<ActionResult<ApiSuccessResult<GetVendorCategoryListResult>>> GetVendorCategoryListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetVendorCategoryListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetVendorCategoryListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetVendorCategoryListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,100 @@
using Application.Features.VendorContactManager.Commands;
using Application.Features.VendorContactManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class VendorContactController : BaseApiController
{
public VendorContactController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateVendorContact")]
public async Task<ActionResult<ApiSuccessResult<CreateVendorContactResult>>> CreateVendorContactAsync(CreateVendorContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateVendorContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateVendorContactAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateVendorContact")]
public async Task<ActionResult<ApiSuccessResult<UpdateVendorContactResult>>> UpdateVendorContactAsync(UpdateVendorContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateVendorContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateVendorContactAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteVendorContact")]
public async Task<ActionResult<ApiSuccessResult<DeleteVendorContactResult>>> DeleteVendorContactAsync(DeleteVendorContactRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteVendorContactResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteVendorContactAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetVendorContactList")]
public async Task<ActionResult<ApiSuccessResult<GetVendorContactListResult>>> GetVendorContactListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetVendorContactListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetVendorContactListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetVendorContactListAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetVendorContactByVendorIdList")]
public async Task<ActionResult<ApiSuccessResult<GetVendorContactByVendorIdListResult>>> GetVendorContactByVendorIdListAsync(
CancellationToken cancellationToken,
[FromQuery] string vendorId
)
{
var request = new GetVendorContactByVendorIdListRequest { VendorId = vendorId };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetVendorContactByVendorIdListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetVendorContactByVendorIdListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.VendorManager.Commands;
using Application.Features.VendorManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class VendorController : BaseApiController
{
public VendorController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateVendor")]
public async Task<ActionResult<ApiSuccessResult<CreateVendorResult>>> CreateVendorAsync(CreateVendorRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateVendorResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateVendorAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateVendor")]
public async Task<ActionResult<ApiSuccessResult<UpdateVendorResult>>> UpdateVendorAsync(UpdateVendorRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateVendorResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateVendorAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteVendor")]
public async Task<ActionResult<ApiSuccessResult<DeleteVendorResult>>> DeleteVendorAsync(DeleteVendorRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteVendorResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteVendorAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetVendorList")]
public async Task<ActionResult<ApiSuccessResult<GetVendorListResult>>> GetVendorListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetVendorListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetVendorListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetVendorListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,83 @@
using Application.Features.VendorGroupManager.Commands;
using Application.Features.VendorGroupManager.Queries;
using ASPNET.BackEnd.Common.Base;
using ASPNET.BackEnd.Common.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET.BackEnd.Controllers;
[Route("api/[controller]")]
public class VendorGroupController : BaseApiController
{
public VendorGroupController(ISender sender) : base(sender)
{
}
[Authorize]
[HttpPost("CreateVendorGroup")]
public async Task<ActionResult<ApiSuccessResult<CreateVendorGroupResult>>> CreateVendorGroupAsync(CreateVendorGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<CreateVendorGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(CreateVendorGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("UpdateVendorGroup")]
public async Task<ActionResult<ApiSuccessResult<UpdateVendorGroupResult>>> UpdateVendorGroupAsync(UpdateVendorGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<UpdateVendorGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(UpdateVendorGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpPost("DeleteVendorGroup")]
public async Task<ActionResult<ApiSuccessResult<DeleteVendorGroupResult>>> DeleteVendorGroupAsync(DeleteVendorGroupRequest request, CancellationToken cancellationToken)
{
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<DeleteVendorGroupResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(DeleteVendorGroupAsync)}",
Content = response
});
}
[Authorize]
[HttpGet("GetVendorGroupList")]
public async Task<ActionResult<ApiSuccessResult<GetVendorGroupListResult>>> GetVendorGroupListAsync(
CancellationToken cancellationToken,
[FromQuery] bool isDeleted = false
)
{
var request = new GetVendorGroupListRequest { IsDeleted = isDeleted };
var response = await _sender.Send(request, cancellationToken);
return Ok(new ApiSuccessResult<GetVendorGroupListResult>
{
Code = StatusCodes.Status200OK,
Message = $"Success executing {nameof(GetVendorGroupListAsync)}",
Content = response
});
}
}
@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace ASPNET.FrontEnd;
public static class FrontEndConfiguration
{
public static IServiceCollection AddFrontEndServices(this IServiceCollection services)
{
services.AddRazorPages(options =>
{
options.RootDirectory = "/FrontEnd/Pages";
options.Conventions.ConfigureFilter(new PageAuthorizationFilter());
});
return services;
}
public static IEndpointRouteBuilder MapFrontEndRoutes(this IEndpointRouteBuilder endpoints)
{
endpoints.MapRazorPages()
.WithStaticAssets();
return endpoints;
}
}
@@ -0,0 +1,106 @@
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
namespace ASPNET.FrontEnd;
public class PageAuthorizationFilter : IPageFilter
{
private static readonly string[] PublicPagePrefixes = new[]
{
"/Accounts/",
"/Shared/"
};
private static readonly Dictionary<string, string> PageRoleMapping = new(StringComparer.OrdinalIgnoreCase)
{
{ "/Dashboards/DefaultDashboard", "Dashboards" },
{ "/Campaigns/CampaignList", "Campaigns" },
{ "/Budgets/BudgetList", "Budgets" },
{ "/Expenses/ExpenseList", "Expenses" },
{ "/Leads/LeadList", "Leads" },
{ "/LeadContacts/LeadContactList", "LeadContacts" },
{ "/LeadActivities/LeadActivityList", "LeadActivities" },
{ "/SalesTeams/SalesTeamList", "SalesTeams" },
{ "/SalesRepresentatives/SalesRepresentativeList", "SalesRepresentatives" },
{ "/CustomerGroups/CustomerGroupList", "CustomerGroups" },
{ "/CustomerCategories/CustomerCategoryList", "CustomerCategories" },
{ "/Customers/CustomerList", "Customers" },
{ "/CustomerContacts/CustomerContactList", "CustomerContacts" },
{ "/VendorGroups/VendorGroupList", "VendorGroups" },
{ "/VendorCategories/VendorCategoryList", "VendorCategories" },
{ "/Vendors/VendorList", "Vendors" },
{ "/VendorContacts/VendorContactList", "VendorContacts" },
{ "/Products/ProductList", "Products" },
{ "/ProductGroups/ProductGroupList", "ProductGroups" },
{ "/PurchaseOrders/PurchaseOrderList", "PurchaseOrders" },
{ "/PurchaseOrders/PurchaseOrderPdf", "PurchaseOrders" },
{ "/SalesOrders/SalesOrderList", "SalesOrders" },
{ "/SalesOrders/SalesOrderPdf", "SalesOrders" },
{ "/SalesReports/SalesReportList", "SalesReports" },
{ "/PurchaseReports/PurchaseReportList", "PurchaseReports" },
{ "/TodoItems/TodoItemList", "TodoItems" },
{ "/Todos/TodoList", "Todos" },
{ "/Companies/MyCompany", "Companies" },
{ "/Taxs/TaxList", "Taxs" },
{ "/NumberSequences/NumberSequenceList", "NumberSequences" },
{ "/UnitMeasures/UnitMeasureList", "UnitMeasures" },
{ "/Profiles/MyProfile", "Profiles" },
{ "/Users/UserList", "Users" },
{ "/Roles/RoleList", "Roles" },
};
public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
{
var pagePath = context.ActionDescriptor.ViewEnginePath;
// Skip public pages (Accounts, Shared)
foreach (var prefix in PublicPagePrefixes)
{
if (pagePath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
return;
}
// Skip root pages (Index, _ViewImports, _ViewStart)
if (pagePath.Equals("/Index", StringComparison.OrdinalIgnoreCase) ||
pagePath.Equals("/_ViewImports", StringComparison.OrdinalIgnoreCase) ||
pagePath.Equals("/_ViewStart", StringComparison.OrdinalIgnoreCase))
return;
if (PageRoleMapping.TryGetValue(pagePath, out var requiredRole))
{
var user = context.HttpContext.User;
if (user?.Identity?.IsAuthenticated != true)
{
context.HttpContext.Response.Redirect("/Accounts/Login");
context.Result = new Microsoft.AspNetCore.Mvc.RedirectResult("/Accounts/Login");
return;
}
var hasRole = user.Claims.Any(c =>
c.Type == ClaimTypes.Role &&
string.Equals(c.Value, requiredRole, StringComparison.OrdinalIgnoreCase));
if (!hasRole)
{
context.HttpContext.Response.Redirect("/Accounts/Login?unauthorized=true");
context.Result = new Microsoft.AspNetCore.Mvc.RedirectResult("/Accounts/Login?unauthorized=true");
return;
}
}
else
{
// Page not in mapping - redirect to login as a safety measure
var user = context.HttpContext.User;
if (user?.Identity?.IsAuthenticated != true)
{
context.HttpContext.Response.Redirect("/Accounts/Login");
context.Result = new Microsoft.AspNetCore.Mvc.RedirectResult("/Accounts/Login");
return;
}
}
}
public void OnPageHandlerExecuted(PageHandlerExecutedContext context) { }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { }
}
@@ -0,0 +1,32 @@
@page
@{
ViewData["Title"] = "Email Confirm";
}
<div id="app" class="container-fluid" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<div class="row">
<div class="col-md-12 text-center mb-3">
<h3 class="text-dark">Email Confirm</h3>
<a asp-page="/Index" class="">
<p><i class="fas fa-home me-2 text-warning"></i><span class="text-dark">INDOTALENT</span></p>
</a>
</div>
<div class="col-md-12">
<p>Please wait...</p>
<p>Email confirmation is in progress.</p>
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/EmailConfirm.cshtml.js"></script>
}
@@ -0,0 +1,71 @@
const App = {
setup() {
const state = Vue.reactive({
isSubmitting: false,
});
const emailConfirmation = async (email, code) => {
try {
const response = await AxiosManager.get(`/Security/ConfirmEmail?email=${email}&code=${code}`, {});
return response;
} catch (error) {
console.error('Error during emailConfirmation:', error);
throw error;
}
}
Vue.onMounted(async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const params = new URLSearchParams(window.location.search);
const email = params.get('email');
const code = params.get('code');
if (email && code) {
const response = await emailConfirmation(email, code);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Email Confirmation Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/Accounts/Login';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Email Confirmation Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} else {
Swal.fire({
icon: 'error',
title: 'Email Confirmation Failed',
text: 'Email or code is missing in the URL query string.',
confirmButtonText: 'Try Again'
});
}
} catch (e) {
console.error('page init error:', e);
} finally {
state.isSubmitting = false;
}
});
return {
state
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,67 @@
@page
@{
ViewData["Title"] = "Forgot Password";
}
<div class="container-fluid" id="app" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<form v-on:submit.prevent="handleSubmit">
<div class="input-group mb-3">
<input id="Email"
name="Email"
type="email"
class="form-control"
placeholder="name@example.com"
v-model="state.email"
v-on:input="state.errors.email = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<label v-if="state.errors.email" class="text-danger">{{ state.errors.email }}</label>
<div class="row">
<div class="col-8">
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary btn-block">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Reset' }}</span>
</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i>
Sign up using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i>
Sign up using Google+
</a>
</div>
<p class="mb-1">
<a asp-page="/Accounts/Login" class="text-center">I already have a membership</a>
</p>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/ForgotPassword.cshtml.js"></script>
}
@@ -0,0 +1,87 @@
const App = {
setup() {
const state = Vue.reactive({
email: '',
isSubmitting: false,
errors: {
email: ''
}
});
const validateForm = () => {
state.errors.email = '';
let isValid = true;
if (!state.email) {
state.errors.email = 'Email is required.';
isValid = false;
} else if (!/\S+@\S+\.\S+/.test(state.email)) {
state.errors.email = 'Please enter a valid email address.';
isValid = false;
}
return isValid;
};
const forgotPassword = async (email) => {
try {
const response = await AxiosManager.post('/Security/ForgotPassword', {
email
});
return response;
} catch (error) {
throw error;
}
}
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) return;
const response = await forgotPassword(state.email);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Reset Password Successful',
text: 'Please check your email. You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Reset Password Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,32 @@
@page
@{
ViewData["Title"] = "Forgot Password Confirmation";
}
<div class="container-fluid" id="app" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<div class="row">
<div class="col-md-12 text-center mb-3">
<h3 class="text-dark">Forgot Password Confirm</h3>
<a asp-page="/Index" class="">
<p><i class="fas fa-home me-2 text-warning"></i><span class="text-dark">INDOTALENT</span></p>
</a>
</div>
<div class="col-md-12">
<p>Please wait...</p>
<p>Password reset is in progress.</p>
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/ForgotPasswordConfirmation.cshtml.js"></script>
}
@@ -0,0 +1,71 @@
const App = {
setup() {
const state = Vue.reactive({
isSubmitting: false,
});
const forgotPasswordConfirmation = async (email, code, tempPassword) => {
try {
const response = await AxiosManager.get(`/Security/ForgotPasswordConfirmation?email=${email}&code=${code}&tempPassword=${tempPassword}`, {});
return response;
} catch (error) {
console.error('Error during ForgotPasswordConfirmation:', error);
throw error;
}
}
Vue.onMounted(async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const params = new URLSearchParams(window.location.search);
const email = params.get('email');
const code = params.get('code');
const tempPassword = params.get('tempPassword');
if (email && code && tempPassword) {
const response = await forgotPasswordConfirmation(email, code, tempPassword);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Password Reset Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/Accounts/Login';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Password Reset Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} else {
Swal.fire({
icon: 'error',
title: 'Password Reset Failed',
text: 'Email or code is missing in the URL query string.',
confirmButtonText: 'Try Again'
});
}
} catch (e) {
console.error('page init error:', e);
} finally {
state.isSubmitting = false;
}
});
return {
state
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,91 @@
@page
@{
ViewData["Title"] = "Login";
}
<div id="app" class="container-fluid" v-cloak>
<div class="card-body login-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<form v-on:submit.prevent="handleSubmit">
<div class="input-group mb-3">
<input id="Email"
name="Email"
type="email"
class="form-control"
placeholder="name@example.com"
v-model="state.email"
v-on:input="state.errors.email = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<label v-if="state.errors.email" class="text-danger">{{ state.errors.email }}</label>
<div class="input-group mb-3">
<input id="Password"
name="Password"
type="password"
class="form-control"
placeholder="Password"
v-model="state.password"
v-on:input="state.errors.password = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<label v-if="state.errors.password" class="text-danger">{{ state.errors.password }}</label>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary btn-block">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Log In' }}</span>
</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center mb-3">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i> Sign in using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i> Sign in using Google+
</a>
</div>
<!-- /.social-auth-links -->
<p class="mb-1">
<a asp-page="/Accounts/ForgotPassword">Forgot Password</a>
</p>
<p class="mb-0">
<a asp-page="/Accounts/Register" class="text-center">Register a new membership</a>
</p>
</div>
</div>
@section scripts {
<script type ="module" src="~/FrontEnd/Pages/Accounts/Login.cshtml.js"></script>
}
@@ -0,0 +1,92 @@
const App = {
setup() {
const state = Vue.reactive({
email: '',
password: '',
isSubmitting: false,
errors: {
email: '',
password: ''
}
});
const validateForm = () => {
state.errors.email = '';
state.errors.password = '';
let isValid = true;
if (!state.email) {
state.errors.email = 'Email is required.';
isValid = false;
} else if (!/\S+@\S+\.\S+/.test(state.email)) {
state.errors.email = 'Please enter a valid email address.';
isValid = false;
}
if (!state.password) {
state.errors.password = 'Password is required.';
isValid = false;
} else if (state.password.length < 6) {
state.errors.password = 'Password must be at least 6 characters.';
isValid = false;
}
return isValid;
};
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = await AxiosManager.post('/Security/Login', {
email: state.email,
password: state.password
});
if (response.data.code === 200) {
StorageManager.saveLoginResult(response.data);
Swal.fire({
icon: 'success',
title: 'Login Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/Profiles/MyProfile';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Login Failed',
text: response.data.message || 'Please check your credentials.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,42 @@
@page
@{
ViewData["Title"] = "Logout";
}
<div class="container-fluid" id="app" v-cloak>
<div class="card-body login-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<div class="social-auth-links text-center mb-3">
<div class="row">
<div class="col-md-12">
<form v-on:submit.prevent="handleSubmit">
<div class="form-group mb-2 text-center">
<p>Are you sure you want to log out?</p>
<p>Click the button below to confirm and log out completely.</p>
</div>
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary w-100 mb-2">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Log Out' }}</span>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/Logout.cshtml.js"></script>
}
@@ -0,0 +1,66 @@
const App = {
setup() {
const state = Vue.reactive({
isSubmitting: false,
});
const logout = async () => {
try {
const response = await AxiosManager.post('/Security/Logout', {
userId: StorageManager.getUserId()
});
return response;
} catch (error) {
throw error;
}
}
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const response = await logout();
if (response.data.code === 200) {
StorageManager.clearStorage();
Swal.fire({
icon: 'success',
title: 'Logout Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Logout Failed',
text: response.data.message ?? 'Logout Failed.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,149 @@
@page
@{
ViewData["Title"] = "Register";
}
<div id="app" class="container-fluid" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<form v-on:submit.prevent="handleSubmit">
<div class="input-group mb-3">
<input id="Email"
name="Email"
type="email"
placeholder="Enter Email"
class="form-control"
v-model="state.email"
v-on:input="state.errors.email = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<label v-if="state.errors.email" class="text-danger small">{{ state.errors.email }}</label>
<div class="input-group mb-3">
<input id="CompanyName"
name="CompanyName"
type="text"
placeholder="Enter Company Name"
class="form-control"
v-model="state.companyName">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-edit"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input id="FirstName"
name="FirstName"
type="text"
placeholder="Enter First Name"
class="form-control"
v-model="state.firstName"
v-on:input="state.errors.firstName = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-edit"></span>
</div>
</div>
</div>
<label v-if="state.errors.firstName" class="text-danger small">{{ state.errors.firstName }}</label>
<div class="input-group mb-3">
<input id="LastName"
name="LastName"
type="text"
placeholder="Enter Last Name"
class="form-control"
v-model="state.lastName"
v-on:input="state.errors.lastName = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-edit"></span>
</div>
</div>
</div>
<label v-if="state.errors.lastName" class="text-danger small">{{ state.errors.lastName }}</label>
<div class="input-group mb-3">
<input id="Password"
name="Password"
type="password"
placeholder="Enter Password"
class="form-control"
v-model="state.password"
v-on:input="state.errors.password = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<label v-if="state.errors.password" class="text-danger small">{{ state.errors.password }}</label>
<div class="input-group mb-3">
<input id="ConfirmPassword"
name="ConfirmPassword"
type="password"
placeholder="Re-type Password"
class="form-control"
v-model="state.confirmPassword"
v-on:input="state.errors.confirmPassword = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<label v-if="state.errors.confirmPassword" class="text-danger small">{{ state.errors.confirmPassword }}</label>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary btn-block">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Register' }}</span>
</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i>
Sign up using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i>
Sign up using Google+
</a>
</div>
<p class="mb-1">
<a asp-page="/Accounts/ForgotPassword">I forgot my password</a>
</p>
<p class="mb-1">
<a asp-page="/Accounts/Login" class="text-center">I already have a membership</a>
</p>
</div>
</div>
@section scripts {
<script type="module" src="~/FrontEnd/Pages/Accounts/Register.cshtml.js"></script>
}
@@ -0,0 +1,123 @@
const App = {
setup() {
const state = Vue.reactive({
email: '',
password: '',
confirmPassword: '',
firstName: '',
lastName: '',
companyName: '',
isSubmitting: false,
errors: {
email: '',
password: '',
confirmPassword: '',
firstName: '',
lastName: ''
}
});
const validateForm = () => {
// Reset errors
state.errors.email = '';
state.errors.password = '';
state.errors.confirmPassword = '';
state.errors.firstName = '';
state.errors.lastName = '';
let isValid = true;
if (!state.email) {
state.errors.email = 'Email is required.';
isValid = false;
} else if (!/\S+@\S+\.\S+/.test(state.email)) {
state.errors.email = 'Please enter a valid email address.';
isValid = false;
}
if (!state.password) {
state.errors.password = 'Password is required.';
isValid = false;
} else if (state.password.length < 6) {
state.errors.password = 'Password must be at least 6 characters.';
isValid = false;
}
if (!state.confirmPassword) {
state.errors.confirmPassword = 'Confirm Password is required.';
isValid = false;
} else if (state.password !== state.confirmPassword) {
state.errors.confirmPassword = 'Passwords do not match.';
isValid = false;
}
if (!state.firstName) {
state.errors.firstName = 'First Name is required.';
isValid = false;
}
if (!state.lastName) {
state.errors.lastName = 'Last Name is required.';
isValid = false;
}
return isValid;
};
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) return;
const response = await AxiosManager.post('/Security/Register', {
email: state.email,
password: state.password,
confirmPassword: state.confirmPassword,
firstName: state.firstName,
lastName: state.lastName,
companyName: state.companyName
});
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Register Successful',
text: 'Please check your email. You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Register Failed',
text: response.data.message || 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,3 @@
@{
Layout = "~/FrontEnd/Pages/Shared/AdminLTE/_Auth.cshtml";
}
@@ -0,0 +1,100 @@
@page
@{
ViewData["Title"] = "Budget List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="Title">Title</label>
<input ref="titleRef" type="text" v-model="state.title">
<label class="text-danger">{{ state.errors.title }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="BudgetDate">Budget Date</label>
<input ref="budgetDateRef" />
<label class="text-danger">{{ state.errors.budgetDate }}</label>
</div>
<div class="col-md-6">
<label for="Amount">Amount</label>
<input ref="amountRef" type="text" step="0.01" v-model="state.amount">
<label class="text-danger">{{ state.errors.amount }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CampaignId">Campaign</label>
<div ref="campaignIdRef"></div>
<label class="text-danger">{{ state.errors.campaignId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Budgets/BudgetList.cshtml.js"></script>
}
@@ -0,0 +1,570 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
campaignListLookupData: [],
statusListLookupData: [],
mainTitle: null,
id: '',
number: '',
budgetDate: '',
title: '',
amount: '',
description: '',
campaignId: null,
status: null,
errors: {
budgetDate: '',
title: '',
amount: '',
campaignId: '',
status: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const budgetDateRef = Vue.ref(null);
const titleRef = Vue.ref(null);
const amountRef = Vue.ref(null);
const campaignIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.budgetDate = '';
state.errors.title = '';
state.errors.amount = '';
state.errors.campaignId = '';
state.errors.status = '';
let isValid = true;
if (!state.budgetDate) {
state.errors.budgetDate = 'Budget date is required.';
isValid = false;
}
if (!state.campaignId) {
state.errors.campaignId = 'Campaign is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
if (!state.title) {
state.errors.title = 'Title is required.';
isValid = false;
}
if (state.amount === null || state.amount === '' || isNaN(state.amount)) {
state.errors.amount = 'Amount is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.budgetDate = '';
state.title = '';
state.amount = '';
state.description = '';
state.campaignId = null;
state.status = null;
state.errors = {
budgetDate: '',
title: '',
amount: '',
campaignId: '',
status: ''
};
};
const budgetDatePicker = {
obj: null,
create: () => {
budgetDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.budgetDate ? new Date(state.budgetDate) : null,
change: (e) => {
state.budgetDate = DateFormatManager.preserveClientDate(e.value);
}
});
budgetDatePicker.obj.appendTo(budgetDateRef.value);
},
refresh: () => {
if (budgetDatePicker.obj) {
budgetDatePicker.obj.value = state.budgetDate ? new Date(state.budgetDate) : null;
}
}
};
Vue.watch(
() => state.budgetDate,
(newVal, oldVal) => {
budgetDatePicker.refresh();
state.errors.budgetDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const campaignListLookup = {
obj: null,
create: () => {
if (state.campaignListLookupData && Array.isArray(state.campaignListLookupData)) {
campaignListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.campaignListLookupData,
fields: { value: 'id', text: 'number' },
placeholder: 'Select Campaign',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('number', 'startsWith', e.text, true);
}
e.updateData(state.campaignListLookupData, query);
},
change: (e) => {
state.campaignId = e.value;
}
});
campaignListLookup.obj.appendTo(campaignIdRef.value);
}
},
refresh: () => {
if (campaignListLookup.obj) {
campaignListLookup.obj.value = state.campaignId
}
},
};
Vue.watch(
() => state.campaignId,
(newVal, oldVal) => {
campaignListLookup.refresh();
state.errors.campaignId = '';
}
);
const statusListLookup = {
obj: null,
create: () => {
if (state.statusListLookupData && Array.isArray(state.statusListLookupData)) {
statusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.statusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
statusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (statusListLookup.obj) {
statusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
statusListLookup.refresh();
state.errors.status = '';
}
);
const titleText = {
obj: null,
create: () => {
titleText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Title',
});
titleText.obj.appendTo(titleRef.value);
},
refresh: () => {
if (titleText.obj) {
titleText.obj.value = state.title;
}
}
};
Vue.watch(
() => state.title,
(newVal, oldVal) => {
titleText.refresh();
state.errors.title = '';
}
);
const amountText = {
obj: null,
create: () => {
amountText.obj = new ej.inputs.NumericTextBox({
placeholder: 'Enter Amount',
format: 'n2',
min: 0,
});
amountText.obj.appendTo(amountRef.value);
},
refresh: () => {
if (amountText.obj) {
amountText.obj.value = parseFloat(state.amount) || 0;
}
}
};
Vue.watch(
() => state.amount,
(newVal, oldVal) => {
amountText.refresh();
state.errors.amount = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Budget/GetBudgetList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (budgetDate, title, amount, description, status, campaignId, createdById) => {
try {
const response = await AxiosManager.post('/Budget/CreateBudget', {
budgetDate, title, amount, description, status, campaignId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, budgetDate, title, amount, description, status, campaignId, updatedById) => {
try {
const response = await AxiosManager.post('/Budget/UpdateBudget', {
id, budgetDate, title, amount, description, status, campaignId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Budget/DeleteBudget', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getCampaignListLookupData: async () => {
try {
const response = await AxiosManager.get('/Campaign/GetCampaignList', {});
return response;
} catch (error) {
throw error;
}
},
getBudgetStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/Budget/GetBudgetStatusList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
budgetDate: new Date(item.budgetDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateCampaignListLookupData: async () => {
const response = await services.getCampaignListLookupData();
state.campaignListLookupData = response?.data?.content?.data;
},
populateBudgetStatusListLookupData: async () => {
const response = await services.getBudgetStatusListLookupData();
state.statusListLookupData = response?.data?.content?.data;
},
onMainModalHidden: () => {
state.errors.budgetDate = '';
state.errors.title = '';
state.errors.amount = '';
state.errors.campaignId = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.budgetDate, state.title, state.amount, state.description, state.status, state.campaignId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.budgetDate, state.title, state.amount, state.description, state.status, state.campaignId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Budgets']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden());
await methods.populateCampaignListLookupData();
await methods.populateBudgetStatusListLookupData();
numberText.create();
budgetDatePicker.create();
titleText.create();
amountText.create();
campaignListLookup.create();
statusListLookup.create();
} catch (e) {
console.error('page init error:', e);
} finally {
hideSpinnerAndShowContent();
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden());
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'title', headerText: 'Title', width: 200, minWidth: 200 },
{ field: 'budgetDate', headerText: 'Budget Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'campaignName', headerText: 'Campaign', width: 150, minWidth: 150 },
{
field: 'amount',
headerText: 'Amount',
width: 100,
minWidth: 100,
format: 'N2'
},
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'title', 'budgetDate', 'campaignNumber', 'amount', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Budget';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Budget';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.budgetDate = selectedRecord.budgetDate ? new Date(selectedRecord.budgetDate) : null;
state.title = selectedRecord.title ?? '';
state.amount = selectedRecord.amount ?? '';
state.description = selectedRecord.description ?? '';
state.campaignId = selectedRecord.campaignId ?? '';
state.status = String(selectedRecord.status ?? '');
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Budget?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.budgetDate = selectedRecord.budgetDate ? new Date(selectedRecord.budgetDate) : null;
state.title = selectedRecord.title ?? '';
state.amount = selectedRecord.amount ?? '';
state.description = selectedRecord.description ?? '';
state.campaignId = selectedRecord.campaignId ?? '';
state.status = String(selectedRecord.status ?? '');
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
numberRef,
budgetDateRef,
titleRef,
amountRef,
campaignIdRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,151 @@
@page
@{
ViewData["Title"] = "Campaign List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card mb-2">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="Title">Title</label>
<input ref="titleRef" type="text" v-model="state.title">
<label class="text-danger">{{ state.errors.title }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CampaignDateStart">Start Date</label>
<input ref="campaignDateStartRef" />
<label class="text-danger">{{ state.errors.campaignDateStart }}</label>
</div>
<div class="col-md-6">
<label for="CampaignDateFinish">Finish Date</label>
<input ref="campaignDateFinishRef" />
<label class="text-danger">{{ state.errors.campaignDateFinish }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="TargetRevenueAmount">Target Revenue Amount</label>
<input ref="targetRevenueAmountRef" type="text" step="0.01" v-model="state.targetRevenueAmount">
<label class="text-danger">{{ state.errors.targetRevenueAmount }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
</div>
</div>
</div>
</div>
<div class="card mb-2">
<div class="card-header">
<h5>Sales Team</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="SalesTeamId">Sales Team</label>
<div ref="salesTeamIdRef"></div>
<label class="text-danger" v-text="state.errors.salesTeamId"></label>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-2">
<div class="col-md-12 mb-2">
<div class="card">
<div class="card-header">
<h5>Budget</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="budgetGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 mb-2">
<div class="card">
<div class="card-header">
<h5>Expense</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="expenseGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Campaigns/CampaignList.cshtml.js"></script>
}
@@ -0,0 +1,855 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
salesTeamListLookupData: [],
statusListLookupData: [],
budgetData: [],
expenseData: [],
mainTitle: null,
id: '',
number: '',
salesTeamId: null,
campaignDateStart: '',
campaignDateFinish: '',
title: '',
targetRevenueAmount: '',
description: '',
status: null,
errors: {
salesTeamId: '',
campaignDateStart: '',
campaignDateFinish: '',
title: '',
targetRevenueAmount: '',
status: ''
},
showComplexDiv: false,
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const budgetGridRef = Vue.ref(null);
const expenseGridRef = Vue.ref(null);
const campaignDateStartRef = Vue.ref(null);
const campaignDateFinishRef = Vue.ref(null);
const titleRef = Vue.ref(null);
const targetRevenueAmountRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const salesTeamIdRef = Vue.ref(null);
const validateForm = function () {
state.errors.campaignDateStart = '';
state.errors.campaignDateFinish = '';
state.errors.title = '';
state.errors.targetRevenueAmount = '';
state.errors.status = '';
state.errors.salesTeamId = '';
let isValid = true;
if (!state.campaignDateStart) {
state.errors.campaignDateStart = 'Start date is required.';
isValid = false;
}
if (!state.campaignDateFinish) {
state.errors.campaignDateFinish = 'Finish date is required.';
isValid = false;
}
if (!state.title) {
state.errors.title = 'Title is required.';
isValid = false;
}
if (state.targetRevenueAmount === null || state.targetRevenueAmount === '' || isNaN(state.targetRevenueAmount)) {
state.errors.targetRevenueAmount = 'Target revenue amount is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
if (!state.salesTeamId) {
state.errors.salesTeamId = 'Sales team is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.campaignDateStart = '';
state.campaignDateFinish = '';
state.title = '';
state.salesTeamId = null;
state.targetRevenueAmount = '';
state.description = '';
state.status = null;
state.errors = {
campaignDateStart: '',
campaignDateFinish: '',
title: '',
salesTeamId: '',
targetRevenueAmount: '',
status: ''
};
state.budgetData = [];
state.expenseData = [];
};
const campaignDateStartPicker = {
obj: null,
create: () => {
campaignDateStartPicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.campaignDateStart ? new Date(state.campaignDateStart) : null,
change: (e) => {
state.campaignDateStart = DateFormatManager.preserveClientDate(e.value);
}
});
campaignDateStartPicker.obj.appendTo(campaignDateStartRef.value);
},
refresh: () => {
if (campaignDateStartPicker.obj) {
campaignDateStartPicker.obj.value = state.campaignDateStart ? new Date(state.campaignDateStart) : null;
}
}
};
Vue.watch(
() => state.campaignDateStart,
(newVal, oldVal) => {
campaignDateStartPicker.refresh();
state.errors.campaignDateStart = '';
}
);
const campaignDateFinishPicker = {
obj: null,
create: () => {
campaignDateFinishPicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.campaignDateFinish ? new Date(state.campaignDateFinish) : null,
change: (e) => {
state.campaignDateFinish = DateFormatManager.preserveClientDate(e.value);
}
});
campaignDateFinishPicker.obj.appendTo(campaignDateFinishRef.value);
},
refresh: () => {
if (campaignDateFinishPicker.obj) {
campaignDateFinishPicker.obj.value = state.campaignDateFinish ? new Date(state.campaignDateFinish) : null;
}
}
};
Vue.watch(
() => state.campaignDateFinish,
(newVal, oldVal) => {
campaignDateFinishPicker.refresh();
state.errors.campaignDateFinish = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const statusListLookup = {
obj: null,
create: () => {
if (state.statusListLookupData && Array.isArray(state.statusListLookupData)) {
statusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.statusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
statusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (statusListLookup.obj) {
statusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
statusListLookup.refresh();
state.errors.status = '';
}
);
const salesTeamListLookup = {
obj: null,
create: () => {
if (state.salesTeamListLookupData && Array.isArray(state.salesTeamListLookupData)) {
salesTeamListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.salesTeamListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Sales Team',
change: (e) => {
state.salesTeamId = e.value;
}
});
salesTeamListLookup.obj.appendTo(salesTeamIdRef.value);
} else {
console.error('Sales Team list lookup data is not available or invalid.');
}
},
refresh: () => {
if (salesTeamListLookup.obj) {
salesTeamListLookup.obj.value = state.salesTeamId;
}
},
};
Vue.watch(
() => state.salesTeamId,
(newVal, oldVal) => {
salesTeamListLookup.refresh();
state.errors.salesTeamId = '';
}
);
const titleText = {
obj: null,
create: () => {
titleText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Title',
});
titleText.obj.appendTo(titleRef.value);
},
refresh: () => {
if (titleText.obj) {
titleText.obj.value = state.title;
}
}
};
Vue.watch(
() => state.title,
(newVal, oldVal) => {
titleText.refresh();
state.errors.title = '';
}
);
const targetRevenueAmountText = {
obj: null,
create: () => {
targetRevenueAmountText.obj = new ej.inputs.NumericTextBox({
placeholder: 'Enter Target Revenue Amount',
format: 'N2',
min: 0
});
targetRevenueAmountText.obj.appendTo(targetRevenueAmountRef.value);
},
refresh: () => {
if (targetRevenueAmountText.obj) {
targetRevenueAmountText.obj.value = parseFloat(state.targetRevenueAmount) || 0;
}
}
};
Vue.watch(
() => state.targetRevenueAmount,
(newVal, oldVal) => {
targetRevenueAmountText.refresh();
state.errors.targetRevenueAmount = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Campaign/GetCampaignList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (salesTeamId, campaignDateStart, campaignDateFinish, title, targetRevenueAmount, description, status, createdById) => {
try {
const response = await AxiosManager.post('/Campaign/CreateCampaign', {
salesTeamId, campaignDateStart, campaignDateFinish, title, targetRevenueAmount, description, status, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, salesTeamId, campaignDateStart, campaignDateFinish, title, targetRevenueAmount, description, status, updatedById) => {
try {
const response = await AxiosManager.post('/Campaign/UpdateCampaign', {
id, salesTeamId, campaignDateStart, campaignDateFinish, title, targetRevenueAmount, description, status, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Campaign/DeleteCampaign', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getSalesTeamListLookupData: async () => {
try {
const response = await AxiosManager.get('/SalesTeam/GetSalesTeamList', {});
return response;
} catch (error) {
throw error;
}
},
getCampaignStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/Campaign/GetCampaignStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getBudgetData: async (campaignId) => {
try {
const response = await AxiosManager.get('/Budget/GetBudgetByCampaignIdList?campaignId=' + campaignId, {});
return response;
} catch (error) {
throw error;
}
},
getExpenseData: async (campaignId) => {
try {
const response = await AxiosManager.get('/Expense/GetExpenseByCampaignIdList?campaignId=' + campaignId, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateSalesTeamListLookupData: async () => {
const response = await services.getSalesTeamListLookupData();
state.salesTeamListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
campaignDateStart: new Date(item.campaignDateStart),
campaignDateFinish: new Date(item.campaignDateFinish),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateCampaignStatusListLookupData: async () => {
const response = await services.getCampaignStatusListLookupData();
state.statusListLookupData = response?.data?.content?.data;
},
populateBudgetData: async (campaignId) => {
try {
const response = await services.getBudgetData(campaignId);
state.budgetData = response?.data?.content?.data.map(item => ({
...item,
budgetDate: new Date(item.budgetDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
} catch (error) {
state.budgetData = [];
}
},
populateExpenseData: async (campaignId) => {
try {
const response = await services.getExpenseData(campaignId);
state.expenseData = response?.data?.content?.data.map(item => ({
...item,
expenseDate: new Date(item.expenseDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
} catch (error) {
state.expenseData = [];
}
},
onMainModalHidden: () => {
state.errors.campaignDateStart = '';
state.errors.campaignDateFinish = '';
state.errors.title = '';
state.errors.salesTeamId = '';
state.errors.targetRevenueAmount = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.salesTeamId, state.campaignDateStart, state.campaignDateFinish, state.title, state.targetRevenueAmount, state.description, state.status, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.salesTeamId, state.campaignDateStart, state.campaignDateFinish, state.title, state.targetRevenueAmount, state.description, state.status, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Campaign';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateBudgetData(state.id);
budgetGrid.refresh();
await methods.populateExpenseData(state.id);
expenseGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Campaigns']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateSalesTeamListLookupData();
salesTeamListLookup.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden());
await methods.populateCampaignStatusListLookupData();
numberText.create();
titleText.create();
targetRevenueAmountText.create();
campaignDateStartPicker.create();
campaignDateFinishPicker.create();
statusListLookup.create();
await budgetGrid.create(state.budgetData);
await expenseGrid.create(state.expenseData);
} catch (e) {
console.error('page init error:', e);
} finally {
hideSpinnerAndShowContent();
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden());
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: { columns: ['salesTeamName'] },
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'title', headerText: 'Title', width: 200, minWidth: 200 },
{ field: 'campaignDateStart', headerText: 'Start Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'campaignDateFinish', headerText: 'Finish Date', width: 150, format: 'yyyy-MM-dd' },
{
field: 'targetRevenueAmount',
headerText: 'Target Revenue',
width: 100,
minWidth: 100,
format: 'N2'
},
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'salesTeamName', headerText: 'Sales Team', width: 200, minWidth: 200 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'title', 'campaignDateStart', 'campaignDateFinish', 'targetRevenueAmount', 'statusName', 'salesTeamName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Campaign';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Campaign';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.campaignDateStart = selectedRecord.campaignDateStart ? new Date(selectedRecord.campaignDateStart) : null;
state.campaignDateFinish = selectedRecord.campaignDateFinish ? new Date(selectedRecord.campaignDateFinish) : null;
state.title = selectedRecord.title ?? '';
state.targetRevenueAmount = selectedRecord.targetRevenueAmount ?? '';
state.description = selectedRecord.description ?? '';
state.status = String(selectedRecord.status ?? '');
state.salesTeamId = selectedRecord.salesTeamId ?? null;
await methods.populateBudgetData(selectedRecord.id);
budgetGrid.refresh();
await methods.populateExpenseData(selectedRecord.id);
expenseGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Campaign?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.campaignDateStart = selectedRecord.campaignDateStart ? new Date(selectedRecord.campaignDateStart) : null;
state.campaignDateFinish = selectedRecord.campaignDateFinish ? new Date(selectedRecord.campaignDateFinish) : null;
state.title = selectedRecord.title ?? '';
state.targetRevenueAmount = selectedRecord.targetRevenueAmount ?? '';
state.description = selectedRecord.description ?? '';
state.status = String(selectedRecord.status ?? '');
state.salesTeamId = selectedRecord.salesTeamId ?? null;
await methods.populateBudgetData(selectedRecord.id);
budgetGrid.refresh();
await methods.populateExpenseData(selectedRecord.id);
expenseGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const budgetGrid = {
obj: null,
create: async (dataSource) => {
budgetGrid.obj = new ej.grids.Grid({
height: 200,
dataSource: dataSource,
editSettings: { allowEditing: false, allowAdding: false, allowDeleting: false, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'number', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'title', headerText: 'Title', width: 200, minWidth: 200 },
{ field: 'budgetDate', headerText: 'Budget Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'statusName', headerText: 'Status', width: 200, minWidth: 200 },
{
field: 'amount',
headerText: 'Amount',
width: 100,
minWidth: 100,
format: 'N2'
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (budgetGrid.obj.getSelectedRecords().length == 1) {
budgetGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
budgetGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (budgetGrid.obj.getSelectedRecords().length == 1) {
budgetGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
budgetGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (budgetGrid.obj.getSelectedRecords().length) {
budgetGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'BudgetGrid_excelexport') {
budgetGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
}
});
budgetGrid.obj.appendTo(budgetGridRef.value);
},
refresh: () => {
budgetGrid.obj.setProperties({ dataSource: state.budgetData });
}
};
const expenseGrid = {
obj: null,
create: async (dataSource) => {
expenseGrid.obj = new ej.grids.Grid({
height: 200,
dataSource: dataSource,
editSettings: { allowEditing: false, allowAdding: false, allowDeleting: false, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'number', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'title', headerText: 'Title', width: 200, minWidth: 200 },
{ field: 'expenseDate', headerText: 'Expense Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'statusName', headerText: 'Status', width: 200, minWidth: 200 },
{
field: 'amount',
headerText: 'Amount',
width: 100,
minWidth: 100,
format: 'N2'
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (expenseGrid.obj.getSelectedRecords().length == 1) {
expenseGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
expenseGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (expenseGrid.obj.getSelectedRecords().length == 1) {
expenseGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
expenseGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (expenseGrid.obj.getSelectedRecords().length) {
expenseGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'ExpenseGrid_excelexport') {
expenseGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
}
});
expenseGrid.obj.appendTo(expenseGridRef.value);
},
refresh: () => {
expenseGrid.obj.setProperties({ dataSource: state.expenseData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
budgetGridRef,
expenseGridRef,
numberRef,
campaignDateStartRef,
campaignDateFinishRef,
titleRef,
salesTeamIdRef,
targetRevenueAmountRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,159 @@
@page
@{
ViewData["Title"] = "My Company";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row mb-0">
<!-- Main Info -->
<div class="col-md-12">
<div class="card mb-3">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
<div class="col-md-6">
<label for="Currency">Currency</label>
<input ref="currencyRef" v-model="state.currency" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.currency }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea ref="descriptionRef" v-model="state.description" class="form-control" rows="3"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-0">
<!-- Address -->
<div class="col-md-12">
<div class="card mb-3">
<div class="card-header">
<h5>Address</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Street">Street</label>
<input ref="streetRef" v-model="state.street" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.street }}</label>
</div>
<div class="col-md-6">
<label for="City">City</label>
<input ref="cityRef" v-model="state.city" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.city }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="State">State</label>
<input ref="stateRef" v-model="state.state" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.state }}</label>
</div>
<div class="col-md-6">
<label for="ZipCode">Zip Code</label>
<input ref="zipCodeRef" v-model="state.zipCode" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.zipCode }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Country">Country</label>
<input ref="countryRef" v-model="state.country" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.country }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-0">
<!-- Communication -->
<div class="col-md-12">
<div class="card mb-3">
<div class="card-header">
<h5>Communication</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="PhoneNumber">Phone Number</label>
<input ref="phoneNumberRef" v-model="state.phoneNumber" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.phoneNumber }}</label>
</div>
<div class="col-md-6">
<label for="FaxNumber">Fax Number</label>
<input ref="faxNumberRef" v-model="state.faxNumber" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.faxNumber }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="EmailAddress">Email Address</label>
<input ref="emailAddressRef" v-model="state.emailAddress" type="email" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.emailAddress }}</label>
</div>
<div class="col-md-6">
<label for="Website">Website</label>
<input ref="websiteRef" v-model="state.website" type="url" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.website }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Companies/MyCompany.cshtml.js"></script>
}
@@ -0,0 +1,596 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: 'Edit Company',
id: '',
name: '',
description: '',
currency: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
phoneNumber: '',
faxNumber: '',
emailAddress: '',
website: '',
errors: {
name: '',
currency: '',
street: '',
city: '',
state: '',
zipCode: '',
phoneNumber: '',
emailAddress: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const currencyRef = Vue.ref(null);
const streetRef = Vue.ref(null);
const cityRef = Vue.ref(null);
const stateRef = Vue.ref(null);
const zipCodeRef = Vue.ref(null);
const countryRef = Vue.ref(null);
const phoneNumberRef = Vue.ref(null);
const faxNumberRef = Vue.ref(null);
const emailAddressRef = Vue.ref(null);
const websiteRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Company/GetCompanyList', {});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (
id, name, description, currency, street, city, state, zipCode, country,
phoneNumber, faxNumber, emailAddress, website, updatedById
) => {
try {
const response = await AxiosManager.post('/Company/UpdateCompany', {
id,
name,
description,
currency,
street,
city,
state,
zipCode,
country,
phoneNumber,
faxNumber,
emailAddress,
website,
updatedById
});
return response;
} catch (error) {
throw error;
}
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 150, minWidth: 150 },
{ field: 'currency', headerText: 'Currency', width: 150, minWidth: 150 },
{ field: 'street', headerText: 'Street', width: 150, minWidth: 150 },
{ field: 'phoneNumber', headerText: 'Phone#', width: 150, minWidth: 150 },
{ field: 'emailAddress', headerText: 'Email', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'currency', 'street', 'phoneNumber', 'emailAddress', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
state.currency = selectedRecord.currency ?? '';
state.street = selectedRecord.street ?? '';
state.city = selectedRecord.city ?? '';
state.state = selectedRecord.state ?? '';
state.zipCode = selectedRecord.zipCode ?? '';
state.country = selectedRecord.country ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.faxNumber = selectedRecord.faxNumber ?? '';
state.emailAddress = selectedRecord.emailAddress ?? '';
state.website = selectedRecord.website ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
const formattedData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
state.mainData = formattedData;
},
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const currencyText = {
obj: null,
create: () => {
currencyText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Currency',
});
currencyText.obj.appendTo(currencyRef.value);
},
refresh: () => {
if (currencyText.obj) {
currencyText.obj.value = state.currency;
}
}
};
const streetText = {
obj: null,
create: () => {
streetText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Street',
});
streetText.obj.appendTo(streetRef.value);
},
refresh: () => {
if (streetText.obj) {
streetText.obj.value = state.street;
}
}
};
const cityText = {
obj: null,
create: () => {
cityText.obj = new ej.inputs.TextBox({
placeholder: 'Enter City',
});
cityText.obj.appendTo(cityRef.value);
},
refresh: () => {
if (cityText.obj) {
cityText.obj.value = state.city;
}
}
};
const stateText = {
obj: null,
create: () => {
stateText.obj = new ej.inputs.TextBox({
placeholder: 'Enter State',
});
stateText.obj.appendTo(stateRef.value);
},
refresh: () => {
if (stateText.obj) {
stateText.obj.value = state.state;
}
}
};
const zipCodeText = {
obj: null,
create: () => {
zipCodeText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Zip Code',
});
zipCodeText.obj.appendTo(zipCodeRef.value);
},
refresh: () => {
if (zipCodeText.obj) {
zipCodeText.obj.value = state.zipCode;
}
}
};
const countryText = {
obj: null,
create: () => {
countryText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Country',
});
countryText.obj.appendTo(countryRef.value);
},
refresh: () => {
if (countryText.obj) {
countryText.obj.value = state.country;
}
}
};
const phoneNumberText = {
obj: null,
create: () => {
phoneNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Phone Number',
});
phoneNumberText.obj.appendTo(phoneNumberRef.value);
},
refresh: () => {
if (phoneNumberText.obj) {
phoneNumberText.obj.value = state.phoneNumber;
}
}
};
const faxNumberText = {
obj: null,
create: () => {
faxNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Fax Number',
});
faxNumberText.obj.appendTo(faxNumberRef.value);
},
refresh: () => {
if (faxNumberText.obj) {
faxNumberText.obj.value = state.faxNumber;
}
}
};
const emailAddressText = {
obj: null,
create: () => {
emailAddressText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Email Address',
});
emailAddressText.obj.appendTo(emailAddressRef.value);
},
refresh: () => {
if (emailAddressText.obj) {
emailAddressText.obj.value = state.emailAddress;
}
}
};
const websiteText = {
obj: null,
create: () => {
websiteText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Website',
});
websiteText.obj.appendTo(websiteRef.value);
},
refresh: () => {
if (websiteText.obj) {
websiteText.obj.value = state.website;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.currency,
(newVal, oldVal) => {
state.errors.currency = '';
currencyText.refresh();
}
);
Vue.watch(
() => state.street,
(newVal, oldVal) => {
state.errors.street = '';
streetText.refresh();
}
);
Vue.watch(
() => state.city,
(newVal, oldVal) => {
state.errors.city = '';
cityText.refresh();
}
);
Vue.watch(
() => state.state,
(newVal, oldVal) => {
state.errors.state = '';
stateText.refresh();
}
);
Vue.watch(
() => state.zipCode,
(newVal, oldVal) => {
state.errors.zipCode = '';
zipCodeText.refresh();
}
);
Vue.watch(
() => state.country,
(newVal, oldVal) => {
countryText.refresh();
}
);
Vue.watch(
() => state.phoneNumber,
(newVal, oldVal) => {
state.errors.phoneNumber = '';
phoneNumberText.refresh();
}
);
Vue.watch(
() => state.faxNumber,
(newVal, oldVal) => {
faxNumberText.refresh();
}
);
Vue.watch(
() => state.emailAddress,
(newVal, oldVal) => {
state.errors.emailAddress = '';
emailAddressText.refresh();
}
);
Vue.watch(
() => state.website,
(newVal, oldVal) => {
websiteText.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
// Validation
let isValid = true;
Object.keys(state.errors).forEach(field => {
state.errors[field] = '';
if (!state[field] && ['name', 'currency', 'street', 'city', 'state', 'zipCode', 'phoneNumber', 'emailAddress'].includes(field)) {
state.errors[field] = `${field.charAt(0).toUpperCase() + field.slice(1)} is required.`;
isValid = false;
}
});
if (!isValid) return;
const response = await services.updateMainData(
state.id,
state.name,
state.description,
state.currency,
state.street,
state.city,
state.state,
state.zipCode,
state.country,
state.phoneNumber,
state.faxNumber,
state.emailAddress,
state.website,
StorageManager.getUserId()
);
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Page will be refreshed...',
timer: 1000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
location.reload();
}, 1000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Companies']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
currencyText.create();
streetText.create();
cityText.create();
stateText.create();
zipCodeText.create();
countryText.create();
phoneNumberText.create();
faxNumberText.create();
emailAddressText.create();
websiteText.create();
mainModal.create();
mainModalRef.value.addEventListener('hidden.bs.modal', () => {
Object.keys(state).forEach(key => {
if (typeof state[key] === 'string') {
state[key] = '';
}
});
state.errors = {
name: '',
currency: '',
street: '',
city: '',
state: '',
zipCode: '',
phoneNumber: '',
emailAddress: ''
};
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', () => { });
});
return {
state,
mainGridRef,
mainModalRef,
nameRef,
currencyRef,
streetRef,
cityRef,
stateRef,
zipCodeRef,
countryRef,
phoneNumberRef,
faxNumberRef,
emailAddressRef,
websiteRef,
handler
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,71 @@
@page
@{
ViewData["Title"] = "Customer Category List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/CustomerCategories/CustomerCategoryList.cshtml.js"></script>
}
@@ -0,0 +1,306 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
description: '',
errors: {
name: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/CustomerCategory/GetCustomerCategoryList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, description, createdById) => {
try {
const response = await AxiosManager.post('/CustomerCategory/CreateCustomerCategory', {
name, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, description, updatedById) => {
try {
const response = await AxiosManager.post('/CustomerCategory/UpdateCustomerCategory', {
id, name, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/CustomerCategory/DeleteCustomerCategory', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
}
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
let isValid = true;
// name validation
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!isValid) return;
const response = state.id === ''
? await services.createMainData(state.name, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.description = '';
state.errors = {
name: ''
};
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowCategorying: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Customer Category';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Customer Category';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Customer Category?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['CustomerCategories']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
mainModal.create();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
mainModalRef,
nameRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,99 @@
@page
@{
ViewData["Title"] = "Customer Contact List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" class="form-control" placeholder="" readonly />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="PhoneNumber">PhoneNumber</label>
<input ref="phoneNumberRef" v-model="state.phoneNumber" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.phoneNumber"></label>
</div>
<div class="col-md-6">
<label for="EmailAddress">EmailAddress</label>
<input ref="emailAddressRef" v-model="state.emailAddress" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.emailAddress"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="JobTitle">JobTitle</label>
<input ref="jobTitleRef" v-model="state.jobTitle" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.jobTitle"></label>
</div>
<div class="col-md-6">
<label for="CustomerId">Customer</label>
<div ref="customerIdRef"></div>
<label class="text-danger" v-text="state.errors.customerId"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/CustomerContacts/CustomerContactList.cshtml.js"></script>
}
@@ -0,0 +1,548 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
customerListLookupData: [],
mainTitle: null,
id: '',
name: '',
jobTitle: '',
phoneNumber: '',
emailAddress: '',
description: '',
customerId: null,
errors: {
name: '',
jobTitle: '',
phoneNumber: '',
emailAddress: '',
customerId: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const jobTitleRef = Vue.ref(null);
const phoneNumberRef = Vue.ref(null);
const emailAddressRef = Vue.ref(null);
const customerIdRef = Vue.ref(null);
const validateForm = function () {
state.errors.name = '';
state.errors.jobTitle = '';
state.errors.phoneNumber = '';
state.errors.emailAddress = '';
state.errors.customerId = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!state.jobTitle) {
state.errors.jobTitle = 'Job Title is required.';
isValid = false;
}
if (!state.phoneNumber) {
state.errors.phoneNumber = 'Phone number is required.';
isValid = false;
}
if (!state.emailAddress) {
state.errors.emailAddress = 'Email address is required.';
isValid = false;
}
if (!state.customerId) {
state.errors.customerId = 'Customer is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.number = '';
state.jobTitle = '';
state.phoneNumber = '';
state.emailAddress = '';
state.description = '';
state.customerId = null;
state.errors = {
name: '',
jobTitle: '',
phoneNumber: '',
emailAddress: '',
customerId: ''
};
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/CustomerContact/GetCustomerContactList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, jobTitle, phoneNumber, emailAddress, description, customerId, createdById) => {
try {
const response = await AxiosManager.post('/CustomerContact/CreateCustomerContact', {
name, jobTitle, phoneNumber, emailAddress, description, customerId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, jobTitle, phoneNumber, emailAddress, description, customerId, updatedById) => {
try {
const response = await AxiosManager.post('/CustomerContact/UpdateCustomerContact', {
id, name, jobTitle, phoneNumber, emailAddress, description, customerId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/CustomerContact/DeleteCustomerContact', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getCustomerListLookupData: async () => {
try {
const response = await AxiosManager.get('/Customer/GetCustomerList', {});
return response;
} catch (error) {
throw error;
}
}
};
const methods = {
populateCustomerListLookupData: async () => {
const response = await services.getCustomerListLookupData();
state.customerListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name'
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
},
refresh: () => {
if (numberText.obj) {
numberText.obj.value = state.number;
}
}
};
const jobTitleText = {
obj: null,
create: () => {
jobTitleText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Job Title'
});
jobTitleText.obj.appendTo(jobTitleRef.value);
},
refresh: () => {
if (jobTitleText.obj) {
jobTitleText.obj.value = state.jobTitle;
}
}
};
const phoneNumberText = {
obj: null,
create: () => {
phoneNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Phone Number'
});
phoneNumberText.obj.appendTo(phoneNumberRef.value);
},
refresh: () => {
if (phoneNumberText.obj) {
phoneNumberText.obj.value = state.phoneNumber;
}
}
};
const emailAddressText = {
obj: null,
create: () => {
emailAddressText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Email Address'
});
emailAddressText.obj.appendTo(emailAddressRef.value);
},
refresh: () => {
if (emailAddressText.obj) {
emailAddressText.obj.value = state.emailAddress;
}
}
};
const customerListLookup = {
obj: null,
create: () => {
if (state.customerListLookupData && Array.isArray(state.customerListLookupData)) {
customerListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.customerListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Customer',
change: (e) => {
state.customerId = e.value;
}
});
customerListLookup.obj.appendTo(customerIdRef.value);
} else {
console.error('Customer list lookup data is not available or invalid.');
}
},
refresh: () => {
if (customerListLookup.obj) {
customerListLookup.obj.value = state.customerId;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.jobTitle,
(newVal, oldVal) => {
state.errors.jobTitle = '';
jobTitleText.refresh();
}
);
Vue.watch(
() => state.phoneNumber,
(newVal, oldVal) => {
state.errors.phoneNumber = '';
phoneNumberText.refresh();
}
);
Vue.watch(
() => state.emailAddress,
(newVal, oldVal) => {
state.errors.emailAddress = '';
emailAddressText.refresh();
}
);
Vue.watch(
() => state.customerId,
(newVal, oldVal) => {
state.errors.customerId = '';
customerListLookup.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.jobTitle, state.phoneNumber, state.emailAddress, state.description, state.customerId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.jobTitle, state.phoneNumber, state.emailAddress, state.description, state.customerId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Customer Contact';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.name = response?.data?.content?.data.name ?? '';
state.jobTitle = response?.data?.content?.data.jobTitle ?? '';
state.phoneNumber = response?.data?.content?.data.phoneNumber ?? '';
state.emailAddress = response?.data?.content?.data.emailAddress ?? '';
state.description = response?.data?.content?.data.description ?? '';
state.customerId = response?.data?.content?.data.customerId ?? '';
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['CustomerContacts']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateCustomerListLookupData();
customerListLookup.create();
nameText.create();
numberText.create();
jobTitleText.create();
phoneNumberText.create();
emailAddressText.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', () => {
resetFormState();
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', resetFormState);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['customerName']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'customerName', headerText: 'Customer', width: 150, minWidth: 150 },
{ field: 'jobTitle', headerText: 'Job Title', width: 150, minWidth: 150 },
{ field: 'phoneNumber', headerText: 'Phone', width: 150, minWidth: 150 },
{ field: 'emailAddress', headerText: 'Email', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'customerName', 'jobTitle', 'phoneNumber', 'emailAddress', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Customer Contact';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Customer Contact';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.jobTitle = selectedRecord.jobTitle ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.emailAddress = selectedRecord.emailAddress ?? '';
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Customer Contact?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.jobTitle = selectedRecord.jobTitle ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.emailAddress = selectedRecord.emailAddress ?? '';
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
nameRef,
numberRef,
jobTitleRef,
phoneNumberRef,
emailAddressRef,
customerIdRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,71 @@
@page
@{
ViewData["Title"] = "Customer Group List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/CustomerGroups/CustomerGroupList.cshtml.js"></script>
}
@@ -0,0 +1,306 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
description: '',
errors: {
name: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/CustomerGroup/GetCustomerGroupList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, description, createdById) => {
try {
const response = await AxiosManager.post('/CustomerGroup/CreateCustomerGroup', {
name, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, description, updatedById) => {
try {
const response = await AxiosManager.post('/CustomerGroup/UpdateCustomerGroup', {
id, name, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/CustomerGroup/DeleteCustomerGroup', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
}
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
let isValid = true;
// name validation
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!isValid) return;
const response = state.id === ''
? await services.createMainData(state.name, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.description = '';
state.errors = {
name: ''
};
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Customer Group';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Customer Group';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Customer Group?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['CustomerGroups']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
mainModal.create();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
mainModalRef,
nameRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,228 @@
@page
@{
ViewData["Title"] = "Customer List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="card mb-3">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" class="form-control" placeholder="" readonly />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CustomerGroupId">Customer Group</label>
<div ref="customerGroupIdRef"></div>
<label class="text-danger" v-text="state.errors.customerGroupId"></label>
</div>
<div class="col-md-6">
<label for="CustomerCategoryId">Customer Category</label>
<div ref="customerCategoryIdRef"></div>
<label class="text-danger" v-text="state.errors.customerCategoryId"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Address</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Street">Street</label>
<input ref="streetRef" v-model="state.street" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.street"></label>
</div>
<div class="col-md-6">
<label for="City">City</label>
<input ref="cityRef" v-model="state.city" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.city"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="State">State</label>
<input ref="stateRef" v-model="state.state" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.state"></label>
</div>
<div class="col-md-6">
<label for="ZipCode">Zip Code</label>
<input ref="zipCodeRef" v-model="state.zipCode" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.zipCode"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Country">Country</label>
<input ref="countryRef" v-model="state.country" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.country"></label>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Communication</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="PhoneNumber">Phone Number</label>
<input ref="phoneNumberRef" v-model="state.phoneNumber" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.phoneNumber"></label>
</div>
<div class="col-md-6">
<label for="FaxNumber">Fax Number</label>
<input ref="faxNumberRef" v-model="state.faxNumber" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.faxNumber"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="EmailAddress">Email</label>
<input ref="emailAddressRef" v-model="state.emailAddress" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.emailAddress"></label>
</div>
<div class="col-md-6">
<label for="Website">Website</label>
<input ref="websiteRef" v-model="state.website" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.website"></label>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Social Media</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-4">
<label for="WhatsApp">WhatsApp</label>
<input ref="whatsAppRef" v-model="state.whatsApp" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.whatsApp"></label>
</div>
<div class="col-md-4">
<label for="LinkedIn">LinkedIn</label>
<input ref="linkedInRef" v-model="state.linkedIn" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.linkedIn"></label>
</div>
<div class="col-md-4">
<label for="Facebook">Facebook</label>
<input ref="facebookRef" v-model="state.facebook" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.facebook"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-4">
<label for="Instagram">Instagram</label>
<input ref="instagramRef" v-model="state.instagram" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.instagram"></label>
</div>
<div class="col-md-4">
<label for="TwitterX">Twitter/X</label>
<input ref="twitterXRef" v-model="state.twitterX" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.twitterX"></label>
</div>
<div class="col-md-4">
<label for="TikTok">TikTok</label>
<input ref="tikTokRef" v-model="state.tikTok" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.tikTok"></label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" ref="manageContactModalRef" id="ManageContactModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.manageContactTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Customer Contact</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Customers/CustomerList.cshtml.js"></script>
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,218 @@
@page
@{
ViewData["Title"] = "Default Dashboard";
}
<div id="app" v-cloak>
<div class="form-card" id="formcard">
<div class="container-fluid pt-3 px-3">
<div class="row g-3 mb-1 align-items-stretch">
<div class="col-6">
<div class="row g-3">
<div class="col-6">
<div class="card overflow-hidden" style="min-width: 12rem">
<div class="bg-holder bg-card">
</div>
<div class="card-body position-relative d-flex flex-column justify-content-center text-center">
<h6>Campaign</h6>
<div class="display-4 fs-5 mb-2 fw-normal font-sans-serif text-warning" ref="campaignTotalAmountRef" align="center"></div>
<a class="fw-semi-bold fs-10 text-nowrap" href="/Campaigns/CampaignList">See all<span class="fas fa-angle-right ms-1" data-fa-transform="down-1"></span></a>
</div>
</div>
</div>
<div class="col-6">
<div class="card overflow-hidden" style="min-width: 12rem">
<div class="bg-holder bg-card">
</div>
<div class="card-body position-relative d-flex flex-column justify-content-center text-center">
<h6>Lead</h6>
<div class="display-4 fs-5 mb-2 fw-normal font-sans-serif text-warning" ref="leadTotalAmountRef" align="center"></div>
<a class="fw-semi-bold fs-10 text-nowrap" href="/Leads/LeadList">See all<span class="fas fa-angle-right ms-1" data-fa-transform="down-1"></span></a>
</div>
</div>
</div>
</div>
<div class="row mt-0 g-3">
<div class="col-6">
<div class="card overflow-hidden" style="min-width: 12rem">
<div class="bg-holder bg-card">
</div>
<div class="card-body position-relative d-flex flex-column justify-content-center text-center">
<h6>Budget</h6>
<div class="display-4 fs-5 mb-2 fw-normal font-sans-serif text-warning" ref="budgetTotalAmountRef" align="center"></div>
<a class="fw-semi-bold fs-10 text-nowrap" href="/Budgets/BudgetList">See all<span class="fas fa-angle-right ms-1" data-fa-transform="down-1"></span></a>
</div>
</div>
</div>
<div class="col-6">
<div class="card overflow-hidden" style="min-width: 12rem">
<div class="bg-holder bg-card">
</div>
<div class="card-body position-relative d-flex flex-column justify-content-center text-center">
<h6>Expense</h6>
<div class="display-4 fs-5 mb-2 fw-normal font-sans-serif text-warning" ref="expenseTotalAmountRef" align="center"></div>
<a class="fw-semi-bold fs-10 text-nowrap" href="/Expenses/ExpenseList">See all<span class="fas fa-angle-right ms-1" data-fa-transform="down-1"></span></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="card h-100 overflow-hidden d-flex flex-column" style="min-width: 12rem">
<div class="bg-holder bg-card">
</div>
<div class="card-body position-relative d-flex flex-column justify-content-center text-center">
<h6>Closed Won</h6>
<div class="display-4 fs-5 mb-2 fw-normal font-sans-serif text-warning" ref="closedTotalAmountRef" align="center"></div>
<a class="fw-semi-bold fs-10 text-nowrap" href="/Leads/LeadList">See all<span class="fas fa-angle-right ms-1" data-fa-transform="down-1"></span></a>
<p>Lead overview</p>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-3 px-3">
<div class="row g-2">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Lead Pipeline</h6>
<a href="/Leads/LeadList">Leads</a>
</div>
<div ref="leadPipelineFunnelRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Lead Closing</h6>
<a href="/Leads/LeadList">Leads</a>
</div>
<div ref="salesTeamLeadClosingRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-3 px-3">
<div class="row g-2">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Campaign By Status</h6>
<a href="/Campaigns/CampaignList">Campaigns</a>
</div>
<div ref="campaignByStatusRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Lead Activity By Type</h6>
<a href="/LeadActivities/LeadActivityList">Lead Activities</a>
</div>
<div ref="leadActivityByTypeRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-6 col-xl-6">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-chart-line fa-3x" style="color: #E94649;"></i>
<div class="ms-3">
<p class="mb-2">Sales</p>
<h6 class="mb-0 text-end"><span ref="cardSalesQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-6">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-shopping-cart fa-3x text-primary"></i>
<div class="ms-3">
<p class="mb-2">Purchase</p>
<h6 class="mb-0 text-end"><span ref="cardPurchaseQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Customer Group</h6>
<a href="/SalesReports/SalesReportList">Sales</a>
</div>
<div ref="customerGroupChartRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Vendor Group</h6>
<a href="/PurchaseReports/PurchaseReportList">Purchases</a>
</div>
<div ref="vendorGroupChartRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Customer Category</h6>
<a href="/SalesReports/SalesReportList">Sales</a>
</div>
<div ref="customerCategoryChartRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Vendor Category</h6>
<a href="/PurchaseReports/PurchaseReportList">Purchases</a>
</div>
<div ref="vendorCategoryChartRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Latest Sales</h6>
<a href="/SalesOrders/SalesOrderList">Sales</a>
</div>
<div ref="salesOrderGridRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Latest Purchase</h6>
<a href="/PurchaseOrders/PurchaseOrderList">Purchases</a>
</div>
<div ref="purchaseOrderGridRef" align="center"></div>
</div>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Dashboards/DefaultDashboard.cshtml.js"></script>
}
@@ -0,0 +1,514 @@
const App = {
setup() {
const state = Vue.reactive({
cardsData: {},
salesData: {},
purchaseData: {},
inventoryData: {},
crmData: {},
currency: '...',
});
const cardSalesQtyRef = Vue.ref(null);
const cardPurchaseQtyRef = Vue.ref(null);
const salesOrderGridRef = Vue.ref(null);
const purchaseOrderGridRef = Vue.ref(null);
const customerGroupChartRef = Vue.ref(null);
const vendorGroupChartRef = Vue.ref(null);
const customerCategoryChartRef = Vue.ref(null);
const vendorCategoryChartRef = Vue.ref(null);
const campaignTotalAmountRef = Vue.ref(null);
const leadTotalAmountRef = Vue.ref(null);
const budgetTotalAmountRef = Vue.ref(null);
const expenseTotalAmountRef = Vue.ref(null);
const closedTotalAmountRef = Vue.ref(null);
const leadPipelineFunnelRef = Vue.ref(null);
const salesTeamLeadClosingRef = Vue.ref(null);
const campaignByStatusRef = Vue.ref(null);
const leadActivityByTypeRef = Vue.ref(null);
const services = {
getCardsData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetCardsDashboard', {});
return response;
} catch (error) {
throw error;
}
},
getSalesData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetSalesDashboard', {});
return response;
} catch (error) {
throw error;
}
},
getPurchaseData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetPurchaseDashboard', {});
return response;
} catch (error) {
throw error;
}
},
getCRMData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetCRMDashboard', {});
return response;
} catch (error) {
throw error;
}
},
getLeadPipelineFunnelData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetLeadPipelineFunnel', {});
return response;
} catch (error) {
throw error;
}
},
getSalesTeamLeadClosingData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetSalesTeamLeadClosing', {});
return response;
} catch (error) {
throw error;
}
},
getCampaignByStatusData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetCampaignByStatus', {});
return response;
} catch (error) {
throw error;
}
},
getLeadActivityByTypeData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetLeadActivityByType', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateCardsData: async () => {
const response = await services.getCardsData();
state.cardsData = response?.data?.content?.data;
methods.populateCards();
},
populateSalesData: async () => {
const response = await services.getSalesData();
state.salesData = response?.data?.content?.data;
methods.populateSalesOrderGrid();
methods.populateSalesByCustomerGroupChart();
methods.populateSalesByCustomerCategoryChart();
},
populatePurchaseData: async () => {
const response = await services.getPurchaseData();
state.purchaseData = response?.data?.content?.data;
methods.populatePurchaseOrderGrid();
methods.populatePurchaseByVendorGroupChart();
methods.populatePurchaseByVendorCategoryChart();
},
populateCards: () => {
const cardsDashboard = state.cardsData?.cardsDashboard;
if (cardsDashboard) {
cardSalesQtyRef.value.textContent = cardsDashboard.salesTotal || 0;
cardPurchaseQtyRef.value.textContent = cardsDashboard.purchaseTotal || 0;
} else {
console.error('CardsDashboard data is not available.');
}
},
populateSalesOrderGrid: () => {
const salesOrderDashboard = state.salesData?.salesOrderDashboard ?? [];
new ej.grids.Grid({
dataSource: salesOrderDashboard,
allowFiltering: false,
allowSorting: true,
allowSelection: false,
allowGrouping: false,
allowTextWrap: false,
allowResizing: false,
allowPaging: true,
allowExcelExport: false,
sortSettings: { columns: [{ field: 'orderDate', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 10 },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'salesOrder.orderDate', headerText: 'Order Date', width: 70, type: 'dateTime', format: 'yyyy-MM-dd', textAlign: 'Left' },
{ field: 'salesOrder.number', headerText: '#Number', width: 90 },
{ field: 'product.name', headerText: 'Product', width: 150 },
{ field: 'total', headerText: 'Total', width: 70, type: 'number', format: 'N2', textAlign: 'Right' },
],
}, salesOrderGridRef.value);
},
populatePurchaseOrderGrid: () => {
const purchaseOrderDashboard = state.purchaseData?.purchaseOrderDashboard ?? [];
new ej.grids.Grid({
dataSource: purchaseOrderDashboard,
allowFiltering: false,
allowSorting: true,
allowSelection: false,
allowGrouping: false,
allowTextWrap: false,
allowResizing: false,
allowPaging: true,
allowExcelExport: false,
sortSettings: { columns: [{ field: 'orderDate', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 10 },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'purchaseOrder.orderDate', headerText: 'Order Date', width: 70, type: 'dateTime', format: 'yyyy-MM-dd', textAlign: 'Left' },
{ field: 'purchaseOrder.number', headerText: '#Number', width: 90 },
{ field: 'product.name', headerText: 'Product', width: 150 },
{ field: 'total', headerText: 'Total', width: 70, type: 'number', format: 'N2', textAlign: 'Right' },
],
}, purchaseOrderGridRef.value);
},
populateSalesByCustomerGroupChart: () => {
const salesByCustomerGroupDashboard = state.salesData?.salesByCustomerGroupDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: salesByCustomerGroupDashboard,
title: 'Sales by Customer Group',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
customerGroupChartRef.value);
},
populatePurchaseByVendorGroupChart: () => {
const purchaseByVendorGroupDashboard = state.purchaseData?.purchaseByVendorGroupDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: purchaseByVendorGroupDashboard,
title: 'Purchase by Vendor Group',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
vendorGroupChartRef.value);
},
populateSalesByCustomerCategoryChart: () => {
const salesByCustomerCategoryDashboard = state.salesData?.salesByCustomerCategoryDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: salesByCustomerCategoryDashboard,
title: 'Sales by Customer Category',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
customerCategoryChartRef.value);
},
populatePurchaseByVendorCategoryChart: () => {
const purchaseByVendorCategoryDashboard = state.purchaseData?.purchaseByVendorCategoryDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: purchaseByVendorCategoryDashboard,
title: 'Purchase by Vendor Category',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
vendorCategoryChartRef.value);
},
formatWithM: (value) => {
const formatted = NumberFormatManager.formatToLocaleNoDecimal((value ?? 0) / 1000000);
return `${formatted}M`;
},
populateCRMData: async () => {
const response = await services.getCRMData();
state.crmData = response?.data?.content?.data;
methods.populateCRM();
},
populateCRM: () => {
const crmDashboard = state.crmData?.crmDashboard;
if (crmDashboard) {
campaignTotalAmountRef.value.textContent = methods.formatWithM(crmDashboard.campaignTotalAmount);
leadTotalAmountRef.value.textContent = methods.formatWithM(crmDashboard.leadTotalAmount);
budgetTotalAmountRef.value.textContent = methods.formatWithM(crmDashboard.budgetTotalAmount);
expenseTotalAmountRef.value.textContent = methods.formatWithM(crmDashboard.expenseTotalAmount);
closedTotalAmountRef.value.textContent = methods.formatWithM(crmDashboard.closedTotalAmount);
} else {
console.error('CRMDashboard data is not available.');
}
},
populateLeadPipelineFunnelData: async () => {
methods.populateLeadPipelineFunnel();
},
populateLeadPipelineFunnel: async () => {
const response = await services.getLeadPipelineFunnelData();
const leadPipelineFunnelData = response?.data?.content?.data ?? [];
new ej.charts.AccumulationChart({
series: [{
type: 'Funnel',
dataSource: leadPipelineFunnelData,
xName: 'x', yName: 'y',
dataLabel: { name: 'text', visible: true, position: 'Inside', font: { fontWeight: '600' }, connectorStyle: { length: '20px' } },
gapRatio: 0.03,
neckWidth: '50%', neckHeight: '30%',
width: '100%', height: '100%'
}
],
legendSettings: { visible: false },
title: 'Lead Pipeline Funnel',
}, leadPipelineFunnelRef.value);
},
populateSalesTeamLeadClosingPie: async () => {
const response = await services.getSalesTeamLeadClosingData();
const salesTeamLeadClosingData = response?.data?.content?.data ?? [];
new ej.charts.AccumulationChart({
enableSmartLabels: true,
selectionMode: 'Point',
annotations: [{
content: '<div><strong></strong></div>',
region: "Series",
x: "52%",
y: "50%"
}],
series: [
{
dataSource: salesTeamLeadClosingData,
xName: 'x', yName: 'y', startAngle: 30,
innerRadius: '50%', radius: ej.base.Browser.isDevice ? '80%' : '85%',
dataLabel: {
visible: true, position: 'Inside',
font: { fontWeight: '600', color: '#ffffff' },
},
}
],
legendSettings: {
visible: true, toggleVisibility: false,
position: 'Bottom',
maximumColumns: ej.base.Browser.isDevice ? 2 : 3,
fixedWidth: true
},
title: 'Sales Team Achievement',
enableBorderOnMouseMove: false,
textRender: function (args) {
args.series.dataLabel.font.size = '13px';
args.text = args.text + '%';
},
pointRender: function (args) {
var selectedTheme = location.hash.split('/')[1];
selectedTheme = selectedTheme ? selectedTheme : 'Fluent2';
if (selectedTheme === 'fluent2') {
args.fill = fluent2Colors[args.point.index % 10];
}
},
}, salesTeamLeadClosingRef.value);
},
populateCampaignByStatus: async () => {
const response = await services.getCampaignByStatusData();
const campaignByStatusData = response?.data?.content?.data ?? [];
new ej.charts.AccumulationChart({
series: [{
type: 'Pie',
dataSource: campaignByStatusData,
animation: { enable: true },
xName: 'x',
yName: 'y',
innerRadius: '50%',
dataLabel: {
visible: true,
position: 'Outside',
name: 'x',
connectorStyle: { width: 0 },
},
borderRadius: 8,
border: { width: 3 }
}],
tooltip: {
enable: true,
header: '<b>Campaign Status</b>', format: '${point.x}: <b>${point.y}%</b>',
enableHighlight: true
},
title: 'Campaign By Status',
enableSmartLabels: true,
enableBorderOnMouseMove: false,
legendSettings: {
visible: false
},
annotations: [{
content: '<div><strong></strong></div>',
region: "Series",
x: "52%",
y: "50%"
}],
load: function (args) {
var selectedTheme = location.hash.split('/')[1];
selectedTheme = selectedTheme ? selectedTheme : 'Fluent2';
args.accumulation.theme = (selectedTheme.charAt(0).toUpperCase() +
selectedTheme.slice(1)).replace(/-dark/i, 'Dark').replace(/contrast/i, 'Contrast').replace(/-highContrast/i, 'HighContrast');
},
pointRender: function (args) {
var selectedTheme = location.hash.split('/')[1];
selectedTheme = selectedTheme ? selectedTheme : 'Fluent2';
if (selectedTheme.indexOf('dark') > -1) {
if (selectedTheme.indexOf('material') > -1) {
args.border.color = '#303030';
}
else if (selectedTheme.indexOf('bootstrap5') > -1) {
args.border.color = '#212529';
}
else if (selectedTheme.indexOf('bootstrap') > -1) {
args.border.color = '#1A1A1A';
}
else if (selectedTheme.indexOf('fabric') > -1) {
args.border.color = '#201f1f';
}
else if (selectedTheme.indexOf('fluent') > -1) {
args.border.color = '#252423';
}
else if (selectedTheme.indexOf('bootstrap') > -1) {
args.border.color = '#1A1A1A';
}
else if (selectedTheme.indexOf('tailwind') > -1) {
args.border.color = '#1F2937';
}
else {
args.border.color = '#222222';
}
}
else if (selectedTheme.indexOf('highcontrast') > -1) {
args.border.color = '#000000';
}
else {
args.border.color = '#FFFFFF';
}
}
}, campaignByStatusRef.value);
},
populateLeadActivityByType: async () => {
const response = await services.getLeadActivityByTypeData();
const leadActivityByTypeData = response?.data?.content?.data ?? [];
new ej.charts.AccumulationChart({
series: [{
type: 'Pyramid',
dataSource: leadActivityByTypeData,
xName: 'x', yName: 'y',
dataLabel: { name: 'text', visible: true, position: 'Inside', font: { fontWeight: '600' }, connectorStyle: { length: '20px' } },
gapRatio: 0.03,
neckWidth: '50%', neckHeight: '30%',
width: '100%', height: '100%'
}
],
legendSettings: { visible: false },
title: 'Lead Activity By Type',
}, leadActivityByTypeRef.value);
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Dashboards']);
await SecurityManager.validateToken();
await methods.populateCardsData();
await methods.populateSalesData();
await methods.populatePurchaseData();
await methods.populateCRMData();
await methods.populateLeadPipelineFunnel();
await methods.populateSalesTeamLeadClosingPie();
await methods.populateCampaignByStatus();
await methods.populateLeadActivityByType();
} catch (e) {
console.error('page init error:', e);
}
});
return {
cardSalesQtyRef,
cardPurchaseQtyRef,
salesOrderGridRef,
purchaseOrderGridRef,
customerGroupChartRef,
vendorGroupChartRef,
customerCategoryChartRef,
vendorCategoryChartRef,
state,
methods,
campaignTotalAmountRef,
leadTotalAmountRef,
budgetTotalAmountRef,
expenseTotalAmountRef,
closedTotalAmountRef,
leadPipelineFunnelRef,
salesTeamLeadClosingRef,
campaignByStatusRef,
leadActivityByTypeRef,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,100 @@
@page
@{
ViewData["Title"] = "Expense List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="Title">Title</label>
<input ref="titleRef" type="text" v-model="state.title">
<label class="text-danger">{{ state.errors.title }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="ExpenseDate">Expense Date</label>
<input ref="expenseDateRef" />
<label class="text-danger">{{ state.errors.expenseDate }}</label>
</div>
<div class="col-md-6">
<label for="Amount">Amount</label>
<input ref="amountRef" type="text" step="0.01" v-model="state.amount">
<label class="text-danger">{{ state.errors.amount }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CampaignId">Campaign</label>
<div ref="campaignIdRef"></div>
<label class="text-danger">{{ state.errors.campaignId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Expenses/ExpenseList.cshtml.js"></script>
}
@@ -0,0 +1,572 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
campaignListLookupData: [],
statusListLookupData: [],
mainTitle: null,
id: '',
number: '',
expenseDate: '',
title: '',
amount: '',
description: '',
campaignId: null,
status: null,
errors: {
expenseDate: '',
title: '',
amount: '',
campaignId: '',
status: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const expenseDateRef = Vue.ref(null);
const titleRef = Vue.ref(null);
const amountRef = Vue.ref(null);
const campaignIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.expenseDate = '';
state.errors.title = '';
state.errors.amount = '';
state.errors.campaignId = '';
state.errors.status = '';
let isValid = true;
if (!state.expenseDate) {
state.errors.expenseDate = 'Expense date is required.';
isValid = false;
}
if (!state.campaignId) {
state.errors.campaignId = 'Campaign is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
if (!state.title) {
state.errors.title = 'Title is required.';
isValid = false;
}
if (state.amount === null || state.amount === '' || isNaN(state.amount)) {
state.errors.amount = 'Amount is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.expenseDate = '';
state.title = '';
state.amount = '';
state.description = '';
state.campaignId = null;
state.status = null;
state.errors = {
expenseDate: '',
title: '',
amount: '',
campaignId: '',
status: ''
};
};
const expenseDatePicker = {
obj: null,
create: () => {
expenseDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.expenseDate ? new Date(state.expenseDate) : null,
change: (e) => {
state.expenseDate = DateFormatManager.preserveClientDate(e.value);
}
});
expenseDatePicker.obj.appendTo(expenseDateRef.value);
},
refresh: () => {
if (expenseDatePicker.obj) {
expenseDatePicker.obj.value = state.expenseDate ? new Date(state.expenseDate) : null;
}
}
};
Vue.watch(
() => state.expenseDate,
(newVal, oldVal) => {
expenseDatePicker.refresh();
state.errors.expenseDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const campaignListLookup = {
obj: null,
create: () => {
if (state.campaignListLookupData && Array.isArray(state.campaignListLookupData)) {
campaignListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.campaignListLookupData,
fields: { value: 'id', text: 'number' },
placeholder: 'Select Campaign',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('number', 'startsWith', e.text, true);
}
e.updateData(state.campaignListLookupData, query);
},
change: (e) => {
state.campaignId = e.value;
}
});
campaignListLookup.obj.appendTo(campaignIdRef.value);
}
},
refresh: () => {
if (campaignListLookup.obj) {
campaignListLookup.obj.value = state.campaignId
}
},
};
Vue.watch(
() => state.campaignId,
(newVal, oldVal) => {
campaignListLookup.refresh();
state.errors.campaignId = '';
}
);
const statusListLookup = {
obj: null,
create: () => {
if (state.statusListLookupData && Array.isArray(state.statusListLookupData)) {
statusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.statusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
statusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (statusListLookup.obj) {
statusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
statusListLookup.refresh();
state.errors.status = '';
}
);
const titleText = {
obj: null,
create: () => {
titleText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Title',
});
titleText.obj.appendTo(titleRef.value);
},
refresh: () => {
if (titleText.obj) {
titleText.obj.value = state.title;
}
}
};
Vue.watch(
() => state.title,
(newVal, oldVal) => {
titleText.refresh();
state.errors.title = '';
}
);
const amountText = {
obj: null,
create: () => {
amountText.obj = new ej.inputs.NumericTextBox({
placeholder: 'Enter Amount',
format: 'N2',
min: 0,
max: 1000000000,
step: 0.01,
});
amountText.obj.appendTo(amountRef.value);
},
refresh: () => {
if (amountText.obj) {
amountText.obj.value = parseFloat(state.amount) || 0;
}
}
};
Vue.watch(
() => state.amount,
(newVal, oldVal) => {
amountText.refresh();
state.errors.amount = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Expense/GetExpenseList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (expenseDate, title, amount, description, status, campaignId, createdById) => {
try {
const response = await AxiosManager.post('/Expense/CreateExpense', {
expenseDate, title, amount, description, status, campaignId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, expenseDate, title, amount, description, status, campaignId, updatedById) => {
try {
const response = await AxiosManager.post('/Expense/UpdateExpense', {
id, expenseDate, title, amount, description, status, campaignId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Expense/DeleteExpense', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getCampaignListLookupData: async () => {
try {
const response = await AxiosManager.get('/Campaign/GetCampaignList', {});
return response;
} catch (error) {
throw error;
}
},
getExpenseStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/Expense/GetExpenseStatusList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
expenseDate: new Date(item.expenseDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateCampaignListLookupData: async () => {
const response = await services.getCampaignListLookupData();
state.campaignListLookupData = response?.data?.content?.data;
},
populateExpenseStatusListLookupData: async () => {
const response = await services.getExpenseStatusListLookupData();
state.statusListLookupData = response?.data?.content?.data;
},
onMainModalHidden: () => {
state.errors.expenseDate = '';
state.errors.title = '';
state.errors.amount = '';
state.errors.campaignId = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.expenseDate, state.title, state.amount, state.description, state.status, state.campaignId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.expenseDate, state.title, state.amount, state.description, state.status, state.campaignId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Expenses']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden());
await methods.populateCampaignListLookupData();
await methods.populateExpenseStatusListLookupData();
numberText.create();
expenseDatePicker.create();
titleText.create();
amountText.create();
campaignListLookup.create();
statusListLookup.create();
} catch (e) {
console.error('page init error:', e);
} finally {
hideSpinnerAndShowContent();
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden());
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'title', headerText: 'Title', width: 200, minWidth: 200 },
{ field: 'expenseDate', headerText: 'Expense Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'campaignName', headerText: 'Campaign', width: 150, minWidth: 150 },
{
field: 'amount',
headerText: 'Amount',
width: 100,
minWidth: 100,
format: 'N2'
},
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'title', 'expenseDate', 'campaignName', 'amount', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Expense';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Expense';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.expenseDate = selectedRecord.expenseDate ? new Date(selectedRecord.expenseDate) : null;
state.title = selectedRecord.title ?? '';
state.amount = selectedRecord.amount ?? '';
state.description = selectedRecord.description ?? '';
state.campaignId = selectedRecord.campaignId ?? '';
state.status = String(selectedRecord.status ?? '');
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Expense?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.expenseDate = selectedRecord.expenseDate ? new Date(selectedRecord.expenseDate) : null;
state.title = selectedRecord.title ?? '';
state.amount = selectedRecord.amount ?? '';
state.description = selectedRecord.description ?? '';
state.campaignId = selectedRecord.campaignId ?? '';
state.status = String(selectedRecord.status ?? '');
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
numberRef,
expenseDateRef,
titleRef,
amountRef,
campaignIdRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,13 @@
@page
@{
Layout = "~/FrontEnd/Pages/Shared/_Layout.cshtml";
ViewData["Title"] = "Home page";
}
<div class="lock-overlay">
<h1 class="lock-welcome">FREE CRM</h1>
<a asp-area="" asp-page="/Accounts/Login" class="lock-login">
<i class="fas fa-lock lock-icon"></i>
</a>
</div>
@@ -0,0 +1,103 @@
@page
@{
ViewData["Title"] = "Lead Activity List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Lead Activity Info</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="LeadId">Lead</label>
<div ref="leadIdRef"></div>
<label class="text-danger">{{ state.errors.leadId }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Summary">Summary</label>
<input ref="summaryRef" v-model="state.summary" required>
<label class="text-danger">{{ state.errors.summary }}</label>
</div>
<div class="col-md-6">
<label for="Type">Activity Type</label>
<div ref="typeRef"></div>
<label class="text-danger">{{ state.errors.type }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="FromDate">From Date</label>
<input ref="fromDateRef" />
<label class="text-danger">{{ state.errors.fromDate }}</label>
</div>
<div class="col-md-6">
<label for="ToDate">To Date</label>
<input ref="toDateRef" />
<label class="text-danger">{{ state.errors.toDate }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/LeadActivities/LeadActivityList.cshtml.js"></script>
}
@@ -0,0 +1,536 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
leadListLookupData: [],
leadActivityTypeListLookupData: [],
mainTitle: null,
id: '',
leadId: null,
number: '',
summary: '',
description: '',
fromDate: null,
toDate: null,
type: null,
errors: {
leadId: '',
summary: '',
fromDate: '',
toDate: '',
type: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const leadIdRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const summaryRef = Vue.ref(null);
const fromDateRef = Vue.ref(null);
const toDateRef = Vue.ref(null);
const typeRef = Vue.ref(null);
const validateForm = function () {
state.errors.leadId = '';
state.errors.summary = '';
state.errors.fromDate = '';
state.errors.toDate = '';
state.errors.type = '';
let isValid = true;
if (!state.leadId) {
state.errors.leadId = 'Lead is required.';
isValid = false;
}
if (!state.summary) {
state.errors.summary = 'Summary is required.';
isValid = false;
}
if (!state.fromDate) {
state.errors.fromDate = 'From Date is required.';
isValid = false;
}
if (!state.toDate) {
state.errors.toDate = 'To Date is required.';
isValid = false;
}
if (!state.type) {
state.errors.type = 'Type is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.leadId = null;
state.number = '';
state.summary = '';
state.description = '';
state.fromDate = null;
state.toDate = null;
state.type = null;
state.errors = {
leadId: '',
summary: '',
fromDate: '',
toDate: '',
type: ''
};
};
const services = {
getMainData: async () => {
const response = await AxiosManager.get('/LeadActivity/GetLeadActivityList', {});
return response;
},
createMainData: async (leadId, summary, description, fromDate, toDate, type, createdById) => {
const response = await AxiosManager.post('/LeadActivity/CreateLeadActivity', {
leadId, summary, description, fromDate, toDate, type, createdById
});
return response;
},
updateMainData: async (id, leadId, summary, description, fromDate, toDate, type, updatedById) => {
const response = await AxiosManager.post('/LeadActivity/UpdateLeadActivity', {
id, leadId, summary, description, fromDate, toDate, type, updatedById
});
return response;
},
deleteMainData: async (id, deletedById) => {
const response = await AxiosManager.post('/LeadActivity/DeleteLeadActivity', {
id, deletedById
});
return response;
},
getLeadListLookupData: async () => {
const response = await AxiosManager.get('/Lead/GetLeadList', {});
return response;
},
getLeadActivityTypeListLookupData: async () => {
const response = await AxiosManager.get('/LeadActivity/GetLeadActivityTypeList', {});
return response;
}
};
const methods = {
populateLeadListLookupData: async () => {
const response = await services.getLeadListLookupData();
state.leadListLookupData = response?.data?.content?.data;
},
populateLeadActivityTypeListLookupData: async () => {
const response = await services.getLeadActivityTypeListLookupData();
state.leadActivityTypeListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
fromDate: item.fromDate ? new Date(item.fromDate) : null,
toDate: item.toDate ? new Date(item.toDate) : null,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
handleFormSubmit: async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.leadId, state.summary, state.description, state.fromDate, state.toDate, state.type, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.leadId, state.summary, state.description, state.fromDate, state.toDate, state.type, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Lead Activity';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.leadId = response?.data?.content?.data.leadId ?? null;
state.summary = response?.data?.content?.data.summary ?? '';
state.description = response?.data?.content?.data.description ?? '';
state.fromDate = response?.data?.content?.data.fromDate ? new Date(response.data.content.data.fromDate) : null;
state.toDate = response?.data?.content?.data.toDate ? new Date(response.data.content.data.toDate) : null;
state.type = String(response?.data?.content?.data.type ?? '');
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 1000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
onMainModalHidden: () => {
state.errors.leadId = '';
state.errors.summary = '';
state.errors.fromDate = '';
state.errors.toDate = '';
state.errors.type = '';
}
};
const leadListLookup = {
obj: null,
create: () => {
if (state.leadListLookupData && Array.isArray(state.leadListLookupData)) {
leadListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.leadListLookupData,
fields: { value: 'id', text: 'title' },
placeholder: 'Select a Lead',
change: (e) => {
state.leadId = e.value;
}
});
leadListLookup.obj.appendTo(leadIdRef.value);
}
},
refresh: () => {
if (leadListLookup.obj) {
leadListLookup.obj.value = state.leadId;
}
}
};
const leadActivityTypeListLookup = {
obj: null,
create: () => {
if (state.leadActivityTypeListLookupData && Array.isArray(state.leadActivityTypeListLookupData)) {
leadActivityTypeListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.leadActivityTypeListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select an Activity Type',
change: (e) => {
state.type = e.value;
}
});
leadActivityTypeListLookup.obj.appendTo(typeRef.value);
}
},
refresh: () => {
if (leadActivityTypeListLookup.obj) {
leadActivityTypeListLookup.obj.value = state.type;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
}
};
const summaryText = {
obj: null,
create: () => {
summaryText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Summary'
});
summaryText.obj.appendTo(summaryRef.value);
}
};
const fromDatePicker = {
obj: null,
create: () => {
fromDatePicker.obj = new ej.calendars.DatePicker({
format: 'yyyy-MM-dd',
value: state.fromDate,
change: (e) => {
state.fromDate = DateFormatManager.preserveClientDate(e.value);
}
});
fromDatePicker.obj.appendTo(fromDateRef.value);
},
refresh: () => {
if (fromDatePicker.obj) {
fromDatePicker.obj.value = state.fromDate ? new Date(state.fromDate) : null;
}
}
};
const toDatePicker = {
obj: null,
create: () => {
toDatePicker.obj = new ej.calendars.DatePicker({
format: 'yyyy-MM-dd',
value: state.toDate,
change: (e) => {
state.toDate = DateFormatManager.preserveClientDate(e.value);
}
});
toDatePicker.obj.appendTo(toDateRef.value);
},
refresh: () => {
if (toDatePicker.obj) {
toDatePicker.obj.value = state.toDate ? new Date(state.toDate) : null;
}
}
};
Vue.watch(
() => state.leadId,
(newVal, oldVal) => {
state.errors.leadId = '';
leadListLookup.refresh();
}
);
Vue.watch(
() => state.summary,
(newVal, oldVal) => {
state.errors.summary = '';
}
);
Vue.watch(
() => state.fromDate,
(newVal, oldVal) => {
fromDatePicker.refresh();
state.errors.fromDate = '';
}
);
Vue.watch(
() => state.toDate,
(newVal, oldVal) => {
toDatePicker.refresh();
state.errors.toDate = '';
}
);
Vue.watch(
() => state.type,
(newVal, oldVal) => {
state.errors.type = '';
leadActivityTypeListLookup.refresh();
}
);
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: { columns: ['leadTitle'] },
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150 },
{ field: 'summary', headerText: 'Summary', width: 200 },
{ field: 'leadTitle', headerText: 'Lead', width: 200 },
{ field: 'fromDate', headerText: 'From Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'toDate', headerText: 'To Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'typeName', headerText: 'Activity Type', width: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' }
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'summary', 'leadTitle', 'fromDate', 'toDate', 'typeName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Lead Activity';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Lead Activity';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.leadId = selectedRecord.leadId ?? null;
state.summary = selectedRecord.summary ?? '';
state.description = selectedRecord.description ?? '';
state.fromDate = selectedRecord.fromDate ? new Date(selectedRecord.fromDate) : null;
state.toDate = selectedRecord.toDate ? new Date(selectedRecord.toDate) : null;
state.type = String(selectedRecord.type ?? '');
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Lead Activity?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.leadId = selectedRecord.leadId ?? null;
state.summary = selectedRecord.summary ?? '';
state.description = selectedRecord.description ?? '';
state.fromDate = selectedRecord.fromDate ? new Date(selectedRecord.fromDate) : null;
state.toDate = selectedRecord.toDate ? new Date(selectedRecord.toDate) : null;
state.type = String(selectedRecord.type ?? '');
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['LeadActivities']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateLeadListLookupData();
leadListLookup.create();
await methods.populateLeadActivityTypeListLookupData();
leadActivityTypeListLookup.create();
numberText.create();
summaryText.create();
fromDatePicker.create();
toDatePicker.create();
mainModal.create();
} catch (e) {
console.error('page init error:', e);
} finally {
hideSpinnerAndShowContent();
}
});
return {
mainGridRef,
mainModalRef,
leadIdRef,
numberRef,
summaryRef,
fromDateRef,
toDateRef,
typeRef,
state,
handler: {
handleSubmit: methods.handleFormSubmit
}
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,188 @@
@page
@{
ViewData["Title"] = "Lead Contact List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="card mb-3">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="LeadId">Lead</label>
<div ref="leadIdRef"></div>
<label class="text-danger" v-text="state.errors.leadId"></label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" class="form-control" placeholder="" readonly />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="FullName">Full Name</label>
<input ref="fullNameRef" v-model="state.fullName" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.fullName"></label>
</div>
<div class="col-md-6">
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Address</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="AddressStreet">Street</label>
<input ref="addressStreetRef" v-model="state.addressStreet" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.addressStreet"></label>
</div>
<div class="col-md-6">
<label for="AddressCity">City</label>
<input ref="addressCityRef" v-model="state.addressCity" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.addressCity"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="AddressState">State</label>
<input ref="addressStateRef" v-model="state.addressState" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.addressState"></label>
</div>
<div class="col-md-6">
<label for="AddressZipCode">Zip Code</label>
<input ref="addressZipCodeRef" v-model="state.addressZipCode" class="form-control" placeholder="" />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="AddressCountry">Country</label>
<input ref="addressCountryRef" v-model="state.addressCountry" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Communication</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="MobileNumber">Mobile Number</label>
<input ref="mobileNumberRef" v-model="state.mobileNumber" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.mobileNumber"></label>
</div>
<div class="col-md-6">
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="PhoneNumber">Phone Number</label>
<input ref="phoneNumberRef" v-model="state.phoneNumber" class="form-control" placeholder="" />
</div>
<div class="col-md-6">
<label for="FaxNumber">Fax Number</label>
<input ref="faxNumberRef" v-model="state.faxNumber" class="form-control" placeholder="" />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Email">Email</label>
<input ref="emailRef" v-model="state.email" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.email"></label>
</div>
<div class="col-md-6">
<label for="Website">Website</label>
<input ref="websiteRef" v-model="state.website" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Social Media</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="WhatsApp">WhatsApp</label>
<input ref="whatsAppRef" v-model="state.whatsApp" class="form-control" placeholder="" />
</div>
<div class="col-md-6">
<label for="LinkedIn">LinkedIn</label>
<input ref="linkedInRef" v-model="state.linkedIn" class="form-control" placeholder="" />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Facebook">Facebook</label>
<input ref="facebookRef" v-model="state.facebook" class="form-control" placeholder="" />
</div>
<div class="col-md-6">
<label for="Twitter">Twitter</label>
<input ref="twitterRef" v-model="state.twitter" class="form-control" placeholder="" />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Instagram">Instagram</label>
<input ref="instagramRef" v-model="state.instagram" class="form-control" placeholder="" />
</div>
<div class="col-md-6">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/LeadContacts/LeadContactList.cshtml.js"></script>
}
@@ -0,0 +1,820 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
leadListLookupData: [],
mainTitle: null,
id: '',
leadId: null,
number: '',
fullName: '',
description: '',
addressStreet: '',
addressCity: '',
addressState: '',
addressZipCode: '',
addressCountry: '',
phoneNumber: '',
faxNumber: '',
mobileNumber: '',
email: '',
website: '',
whatsApp: '',
linkedIn: '',
facebook: '',
twitter: '',
instagram: '',
errors: {
leadId: '',
fullName: '',
addressStreet: '',
addressCity: '',
addressState: '',
mobileNumber: '',
email: '',
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const leadIdRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const fullNameRef = Vue.ref(null);
const addressStreetRef = Vue.ref(null);
const addressCityRef = Vue.ref(null);
const addressStateRef = Vue.ref(null);
const addressZipCodeRef = Vue.ref(null);
const addressCountryRef = Vue.ref(null);
const phoneNumberRef = Vue.ref(null);
const faxNumberRef = Vue.ref(null);
const mobileNumberRef = Vue.ref(null);
const emailRef = Vue.ref(null);
const websiteRef = Vue.ref(null);
const whatsAppRef = Vue.ref(null);
const linkedInRef = Vue.ref(null);
const facebookRef = Vue.ref(null);
const twitterRef = Vue.ref(null);
const instagramRef = Vue.ref(null);
const services = {
getMainData: async () => {
const response = await AxiosManager.get('/LeadContact/GetLeadContactList', {});
return response;
},
createMainData: async (leadId, fullName, description, addressStreet, addressCity, addressState, addressZipCode, addressCountry, phoneNumber, faxNumber, mobileNumber, email, website, whatsApp, linkedIn, facebook, twitter, instagram, createdById) => {
const response = await AxiosManager.post('/LeadContact/CreateLeadContact', {
leadId, fullName, description, addressStreet, addressCity, addressState, addressZipCode, addressCountry, phoneNumber, faxNumber, mobileNumber, email, website, whatsApp, linkedIn, facebook, twitter, instagram, createdById
});
return response;
},
updateMainData: async (id, leadId, fullName, description, addressStreet, addressCity, addressState, addressZipCode, addressCountry, phoneNumber, faxNumber, mobileNumber, email, website, whatsApp, linkedIn, facebook, twitter, instagram, updatedById) => {
const response = await AxiosManager.post('/LeadContact/UpdateLeadContact', {
id, leadId, fullName, description, addressStreet, addressCity, addressState, addressZipCode, addressCountry, phoneNumber, faxNumber, mobileNumber, email, website, whatsApp, linkedIn, facebook, twitter, instagram, updatedById
});
return response;
},
deleteMainData: async (id, deletedById) => {
const response = await AxiosManager.post('/LeadContact/DeleteLeadContact', {
id, deletedById
});
return response;
},
getLeadListLookupData: async () => {
const response = await AxiosManager.get('/Lead/GetLeadList', {});
return response;
}
};
const methods = {
populateLeadListLookupData: async () => {
const response = await services.getLeadListLookupData();
state.leadListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const leadListLookup = {
obj: null,
create: () => {
if (state.leadListLookupData && Array.isArray(state.leadListLookupData)) {
leadListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.leadListLookupData,
fields: { value: 'id', text: 'title' },
placeholder: 'Select a Lead',
change: (e) => {
state.leadId = e.value;
}
});
leadListLookup.obj.appendTo(leadIdRef.value);
}
},
refresh: () => {
if (leadListLookup.obj) {
leadListLookup.obj.value = state.leadId;
}
},
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
},
refresh: () => {
if (numberText.obj) {
numberText.obj.value = state.number;
}
}
};
const fullNameText = {
obj: null,
create: () => {
fullNameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Full Name'
});
fullNameText.obj.appendTo(fullNameRef.value);
},
refresh: () => {
if (fullNameText.obj) {
fullNameText.obj.value = state.fullName;
}
}
};
const addressStreetText = {
obj: null,
create: () => {
addressStreetText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Street'
});
addressStreetText.obj.appendTo(addressStreetRef.value);
},
refresh: () => {
if (addressStreetText.obj) {
addressStreetText.obj.value = state.addressStreet;
}
}
};
const addressCityText = {
obj: null,
create: () => {
addressCityText.obj = new ej.inputs.TextBox({
placeholder: 'Enter City'
});
addressCityText.obj.appendTo(addressCityRef.value);
},
refresh: () => {
if (addressCityText.obj) {
addressCityText.obj.value = state.addressCity;
}
}
};
const addressStateText = {
obj: null,
create: () => {
addressStateText.obj = new ej.inputs.TextBox({
placeholder: 'Enter State'
});
addressStateText.obj.appendTo(addressStateRef.value);
},
refresh: () => {
if (addressStateText.obj) {
addressStateText.obj.value = state.addressState;
}
}
};
const addressZipCodeText = {
obj: null,
create: () => {
addressZipCodeText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Zip Code'
});
addressZipCodeText.obj.appendTo(addressZipCodeRef.value);
},
refresh: () => {
if (addressZipCodeText.obj) {
addressZipCodeText.obj.value = state.addressZipCode;
}
}
};
const addressCountryText = {
obj: null,
create: () => {
addressCountryText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Country'
});
addressCountryText.obj.appendTo(addressCountryRef.value);
},
refresh: () => {
if (addressCountryText.obj) {
addressCountryText.obj.value = state.addressCountry;
}
}
};
const phoneNumberText = {
obj: null,
create: () => {
phoneNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Phone Number'
});
phoneNumberText.obj.appendTo(phoneNumberRef.value);
},
refresh: () => {
if (phoneNumberText.obj) {
phoneNumberText.obj.value = state.phoneNumber;
}
}
};
const faxNumberText = {
obj: null,
create: () => {
faxNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Fax Number'
});
faxNumberText.obj.appendTo(faxNumberRef.value);
},
refresh: () => {
if (faxNumberText.obj) {
faxNumberText.obj.value = state.faxNumber;
}
}
};
const mobileNumberText = {
obj: null,
create: () => {
mobileNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Mobile Number'
});
mobileNumberText.obj.appendTo(mobileNumberRef.value);
},
refresh: () => {
if (mobileNumberText.obj) {
mobileNumberText.obj.value = state.mobileNumber;
}
}
};
const emailText = {
obj: null,
create: () => {
emailText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Email'
});
emailText.obj.appendTo(emailRef.value);
},
refresh: () => {
if (emailText.obj) {
emailText.obj.value = state.email;
}
}
};
const websiteText = {
obj: null,
create: () => {
websiteText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Website'
});
websiteText.obj.appendTo(websiteRef.value);
},
refresh: () => {
if (websiteText.obj) {
websiteText.obj.value = state.website;
}
}
};
const whatsAppText = {
obj: null,
create: () => {
whatsAppText.obj = new ej.inputs.TextBox({
placeholder: 'Enter WhatsApp'
});
whatsAppText.obj.appendTo(whatsAppRef.value);
},
refresh: () => {
if (whatsAppText.obj) {
whatsAppText.obj.value = state.whatsApp;
}
}
};
const linkedInText = {
obj: null,
create: () => {
linkedInText.obj = new ej.inputs.TextBox({
placeholder: 'Enter LinkedIn'
});
linkedInText.obj.appendTo(linkedInRef.value);
},
refresh: () => {
if (linkedInText.obj) {
linkedInText.obj.value = state.linkedIn;
}
}
};
const facebookText = {
obj: null,
create: () => {
facebookText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Facebook'
});
facebookText.obj.appendTo(facebookRef.value);
},
refresh: () => {
if (facebookText.obj) {
facebookText.obj.value = state.facebook;
}
}
};
const twitterText = {
obj: null,
create: () => {
twitterText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Twitter'
});
twitterText.obj.appendTo(twitterRef.value);
},
refresh: () => {
if (twitterText.obj) {
twitterText.obj.value = state.twitter;
}
}
};
const instagramText = {
obj: null,
create: () => {
instagramText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Instagram'
});
instagramText.obj.appendTo(instagramRef.value);
},
refresh: () => {
if (instagramText.obj) {
instagramText.obj.value = state.instagram;
}
}
};
Vue.watch(
() => state.leadId,
(newVal, oldVal) => {
leadListLookup.refresh();
state.errors.leadId = '';
}
);
Vue.watch(
() => state.number,
(newVal, oldVal) => {
numberText.refresh();
}
);
Vue.watch(
() => state.fullName,
(newVal, oldVal) => {
state.errors.fullName = '';
fullNameText.refresh();
}
);
Vue.watch(
() => state.addressStreet,
(newVal, oldVal) => {
state.errors.addressStreet = '';
addressStreetText.refresh();
}
);
Vue.watch(
() => state.addressCity,
(newVal, oldVal) => {
state.errors.addressCity = '';
addressCityText.refresh();
}
);
Vue.watch(
() => state.addressState,
(newVal, oldVal) => {
state.errors.addressState = '';
addressStateText.refresh();
}
);
Vue.watch(
() => state.mobileNumber,
(newVal, oldVal) => {
state.errors.mobileNumber = '';
mobileNumberText.refresh();
}
);
Vue.watch(
() => state.email,
(newVal, oldVal) => {
state.errors.email = '';
emailText.refresh();
}
);
const handler = {
handleSubmit: async function () {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
let isValid = true;
if (!state.leadId) {
state.errors.leadId = 'Lead is required.';
isValid = false;
}
if (!state.fullName) {
state.errors.fullName = 'Full Name is required.';
isValid = false;
}
if (!state.addressStreet) {
state.errors.addressStreet = 'Street is required.';
isValid = false;
}
if (!state.addressCity) {
state.errors.addressCity = 'City is required.';
isValid = false;
}
if (!state.addressState) {
state.errors.addressState = 'State is required.';
isValid = false;
}
if (!state.mobileNumber) {
state.errors.mobileNumber = 'Mobile Number is required.';
isValid = false;
}
if (!state.email) {
state.errors.email = 'Email is required.';
isValid = false;
}
try {
if (!isValid) {
return;
}
const response = state.id === ''
? await services.createMainData(state.leadId, state.fullName, state.description, state.addressStreet, state.addressCity, state.addressState, state.addressZipCode, state.addressCountry, state.phoneNumber, state.faxNumber, state.mobileNumber, state.email, state.website, state.whatsApp, state.linkedIn, state.facebook, state.twitter, state.instagram, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.leadId, state.fullName, state.description, state.addressStreet, state.addressCity, state.addressState, state.addressZipCode, state.addressCountry, state.phoneNumber, state.faxNumber, state.mobileNumber, state.email, state.website, state.whatsApp, state.linkedIn, state.facebook, state.twitter, state.instagram, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Lead Contact';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.leadId = response?.data?.content?.data.leadId ?? '';
state.fullName = response?.data?.content?.data.fullName ?? '';
state.description = response?.data?.content?.data.description ?? '';
state.addressStreet = response?.data?.content?.data.addressStreet ?? '';
state.addressCity = response?.data?.content?.data.addressCity ?? '';
state.addressState = response?.data?.content?.data.addressState ?? '';
state.addressZipCode = response?.data?.content?.data.addressZipCode ?? '';
state.addressCountry = response?.data?.content?.data.addressCountry ?? '';
state.phoneNumber = response?.data?.content?.data.phoneNumber ?? '';
state.faxNumber = response?.data?.content?.data.faxNumber ?? '';
state.mobileNumber = response?.data?.content?.data.mobileNumber ?? '';
state.email = response?.data?.content?.data.email ?? '';
state.website = response?.data?.content?.data.website ?? '';
state.whatsApp = response?.data?.content?.data.whatsApp ?? '';
state.linkedIn = response?.data?.content?.data.linkedIn ?? '';
state.facebook = response?.data?.content?.data.facebook ?? '';
state.twitter = response?.data?.content?.data.twitter ?? '';
state.instagram = response?.data?.content?.data.instagram ?? '';
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 1000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
const resetFormState = () => {
state.id = '';
state.leadId = null;
state.number = '';
state.fullName = '';
state.description = '';
state.addressStreet = '';
state.addressCity = '';
state.addressState = '';
state.addressZipCode = '';
state.addressCountry = '';
state.phoneNumber = '';
state.faxNumber = '';
state.mobileNumber = '';
state.email = '';
state.website = '';
state.whatsApp = '';
state.linkedIn = '';
state.facebook = '';
state.twitter = '';
state.instagram = '';
state.errors = {
leadId: '',
fullName: '',
addressStreet: '',
addressCity: '',
addressState: '',
mobileNumber: '',
email: '',
};
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: { columns: ['leadTitle'] },
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150 },
{ field: 'fullName', headerText: 'Full Name', width: 200 },
{ field: 'leadTitle', headerText: 'Lead', width: 200 },
{ field: 'addressStreet', headerText: 'Street', width: 200 },
{ field: 'addressCity', headerText: 'City', width: 150 },
{ field: 'addressState', headerText: 'State', width: 150 },
{ field: 'mobileNumber', headerText: 'Mobile', width: 200 },
{ field: 'email', headerText: 'Email', width: 200 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' }
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'fullName', 'leadTitle', 'addressStreet', 'addressCity', 'addressState', 'mobileNumber', 'email', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Lead Contact';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Lead Contact';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.leadId = selectedRecord.leadId ?? '';
state.fullName = selectedRecord.fullName ?? '';
state.description = selectedRecord.description ?? '';
state.addressStreet = selectedRecord.addressStreet ?? '';
state.addressCity = selectedRecord.addressCity ?? '';
state.addressState = selectedRecord.addressState ?? '';
state.addressZipCode = selectedRecord.addressZipCode ?? '';
state.addressCountry = selectedRecord.addressCountry ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.faxNumber = selectedRecord.faxNumber ?? '';
state.mobileNumber = selectedRecord.mobileNumber ?? '';
state.email = selectedRecord.email ?? '';
state.website = selectedRecord.website ?? '';
state.whatsApp = selectedRecord.whatsApp ?? '';
state.linkedIn = selectedRecord.linkedIn ?? '';
state.facebook = selectedRecord.facebook ?? '';
state.twitter = selectedRecord.twitter ?? '';
state.instagram = selectedRecord.instagram ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Lead Contact?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.leadId = selectedRecord.leadId ?? '';
state.fullName = selectedRecord.fullName ?? '';
state.description = selectedRecord.description ?? '';
state.addressStreet = selectedRecord.addressStreet ?? '';
state.addressCity = selectedRecord.addressCity ?? '';
state.addressState = selectedRecord.addressState ?? '';
state.addressZipCode = selectedRecord.addressZipCode ?? '';
state.addressCountry = selectedRecord.addressCountry ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.faxNumber = selectedRecord.faxNumber ?? '';
state.mobileNumber = selectedRecord.mobileNumber ?? '';
state.email = selectedRecord.email ?? '';
state.website = selectedRecord.website ?? '';
state.whatsApp = selectedRecord.whatsApp ?? '';
state.linkedIn = selectedRecord.linkedIn ?? '';
state.facebook = selectedRecord.facebook ?? '';
state.twitter = selectedRecord.twitter ?? '';
state.instagram = selectedRecord.instagram ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['LeadContacts']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateLeadListLookupData();
leadListLookup.create();
numberText.create();
fullNameText.create();
addressStreetText.create();
addressCityText.create();
addressStateText.create();
addressZipCodeText.create();
addressCountryText.create();
phoneNumberText.create();
faxNumberText.create();
mobileNumberText.create();
emailText.create();
websiteText.create();
whatsAppText.create();
linkedInText.create();
facebookText.create();
twitterText.create();
instagramText.create();
mainModal.create();
} catch (e) {
console.error('page init error:', e);
} finally {
hideSpinnerAndShowContent();
}
});
return {
mainGridRef,
mainModalRef,
leadIdRef,
numberRef,
fullNameRef,
addressStreetRef,
addressCityRef,
addressStateRef,
addressZipCodeRef,
addressCountryRef,
phoneNumberRef,
faxNumberRef,
mobileNumberRef,
emailRef,
websiteRef,
whatsAppRef,
linkedInRef,
facebookRef,
twitterRef,
instagramRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,361 @@
@page
@{
ViewData["Title"] = "Lead List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="card mb-3">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="Title">Title</label>
<input ref="titleRef" v-model="state.title" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.title"></label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" class="form-control" placeholder="" readonly />
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CompanyName">Company Name</label>
<input ref="companyNameRef" v-model="state.companyName" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.companyName"></label>
</div>
<div class="col-md-6">
<label for="CampaignId">Campaign</label>
<div ref="campaignIdRef"></div>
<label class="text-danger" v-text="state.errors.campaignId"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="CompanyDescription">Company Description</label>
<textarea v-model="state.companyDescription" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Company Address</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="CompanyAddressStreet">Street</label>
<input ref="companyAddressStreetRef" v-model="state.companyAddressStreet" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.companyAddressStreet"></label>
</div>
<div class="col-md-6">
<label for="CompanyAddressCity">City</label>
<input ref="companyAddressCityRef" v-model="state.companyAddressCity" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.companyAddressCity"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CompanyAddressState">State</label>
<input ref="companyAddressStateRef" v-model="state.companyAddressState" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.companyAddressState"></label>
</div>
<div class="col-md-6">
<label for="CompanyAddressZipCode">Zip Code</label>
<input ref="companyAddressZipCodeRef" v-model="state.companyAddressZipCode" class="form-control" placeholder="" />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CompanyAddressCountry">Country</label>
<input ref="companyAddressCountryRef" v-model="state.companyAddressCountry" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Company Communication</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="CompanyPhoneNumber">Phone Number</label>
<input ref="companyPhoneNumberRef" v-model="state.companyPhoneNumber" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.companyPhoneNumber"></label>
</div>
<div class="col-md-6">
<label for="CompanyFaxNumber">Fax Number</label>
<input ref="companyFaxNumberRef" v-model="state.companyFaxNumber" class="form-control" placeholder="" />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CompanyEmail">Email</label>
<input ref="companyEmailRef" v-model="state.companyEmail" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.companyEmail"></label>
</div>
<div class="col-md-6">
<label for="CompanyWebsite">Website</label>
<input ref="companyWebsiteRef" v-model="state.companyWebsite" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Company Social Media</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-4">
<label for="CompanyWhatsApp">WhatsApp</label>
<input ref="companyWhatsAppRef" v-model="state.companyWhatsApp" class="form-control" placeholder="" />
</div>
<div class="col-md-4">
<label for="CompanyLinkedIn">LinkedIn</label>
<input ref="companyLinkedInRef" v-model="state.companyLinkedIn" class="form-control" placeholder="" />
</div>
<div class="col-md-4">
<label for="CompanyFacebook">Facebook</label>
<input ref="companyFacebookRef" v-model="state.companyFacebook" class="form-control" placeholder="" />
</div>
</div>
<div class="row mb-2">
<div class="col-md-4">
<label for="CompanyInstagram">Instagram</label>
<input ref="companyInstagramRef" v-model="state.companyInstagram" class="form-control" placeholder="" />
</div>
<div class="col-md-4">
<label for="CompanyTwitter">Twitter</label>
<input ref="companyTwitterRef" v-model="state.companyTwitter" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>BANT Score</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="BudgetScore">Budget Score</label>
<input type="text" ref="budgetScoreRef" v-model="state.budgetScore" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.budgetScore"></label>
</div>
<div class="col-md-6">
<label for="AuthorityScore">Authority Score</label>
<input type="text" ref="authorityScoreRef" v-model="state.authorityScore" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.authorityScore"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="NeedScore">Need Score</label>
<input type="text" ref="needScoreRef" v-model="state.needScore" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.needScore"></label>
</div>
<div class="col-md-6">
<label for="TimelineScore">Timeline Score</label>
<input type="text" ref="timelineScoreRef" v-model="state.timelineScore" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.timelineScore"></label>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Dates</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-4">
<label for="DateProspecting">Prospecting Date</label>
<input ref="dateProspectingRef" />
<label class="text-danger" v-text="state.errors.dateProspecting"></label>
</div>
<div class="col-md-4">
<label for="DateClosingEstimation">Estimated Closing Date</label>
<input ref="dateClosingEstimationRef" />
<label class="text-danger" v-text="state.errors.dateClosingEstimation"></label>
</div>
<div class="col-md-4">
<label for="DateClosingActual">Actual Closing Date</label>
<input ref="dateClosingActualRef" />
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Goals</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="AmountTargeted">Targeted Amount</label>
<input type="text" ref="amountTargetedRef" v-model="state.amountTargeted" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.amountTargeted"></label>
</div>
<div class="col-md-6">
<label for="AmountClosed">Closed Amount</label>
<input type="text" ref="amountClosedRef" v-model="state.amountClosed" class="form-control" placeholder="" required />
<label class="text-danger" v-text="state.errors.amountClosed"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="PipelineStage">Pipeline Stage</label>
<div ref="pipelineStageRef"></div>
<label class="text-danger" v-text="state.errors.pipelineStage"></label>
</div>
<div class="col-md-6">
<label for="ClosingStatus">Closing Status</label>
<div ref="closingStatusRef"></div>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="ClosingNote">Closing Note</label>
<textarea v-model="state.closingNote" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Sales Team</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row mb-2">
<div class="col-md-6">
<label for="SalesTeamId">Sales Team</label>
<div ref="salesTeamIdRef"></div>
<label class="text-danger" v-text="state.errors.salesTeamId"></label>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" ref="manageContactModalRef" id="ManageContactModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.manageContactTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Lead Contacts</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="contactsGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" ref="manageActivityModalRef" id="ManageActivityModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.manageActivityTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-body-tertiary">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Lead Activities</h5>
</div>
<div class="card-body bg-body-tertiary">
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="activitiesGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Leads/LeadList.cshtml.js"></script>
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,18 @@
@page
@{
ViewData["Title"] = "Number Sequence List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/NumberSequences/NumberSequenceList.cshtml.js"></script>
}
@@ -0,0 +1,114 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/NumberSequence/GetNumberSequenceList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
const formattedData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
state.mainData = formattedData;
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'entityName', headerText: 'Entity Name', width: 200, minWidth: 200 },
{ field: 'prefix', headerText: 'Prefix', width: 100, minWidth: 100 },
{ field: 'suffix', headerText: 'Suffix', width: 100, minWidth: 100 },
{ field: 'lastUsedCount', headerText: 'Last Used Count', width: 100, minWidth: 100 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['entityName', 'prefix', 'suffix', 'lastUsedCount', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => { },
rowDeselected: () => { },
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['NumberSequences']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
mainGridRef
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,71 @@
@page
@{
ViewData["Title"] = "Product Group List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/ProductGroups/ProductGroupList.cshtml.js"></script>
}
@@ -0,0 +1,342 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
description: '',
errors: {
name: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
const validateForm = function () {
state.errors.name = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.description = '';
state.errors = {
name: ''
};
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/ProductGroup/GetProductGroupList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, description, createdById) => {
try {
const response = await AxiosManager.post('/ProductGroup/CreateProductGroup', {
name, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, description, updatedById) => {
try {
const response = await AxiosManager.post('/ProductGroup/UpdateProductGroup', {
id, name, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/ProductGroup/DeleteProductGroup', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Product Group';
state.id = response?.data?.content?.data.id ?? '';
state.name = response?.data?.content?.data.name ?? '';
state.description = response?.data?.content?.data.description ?? '';
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['ProductGroups']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', () => {
resetFormState();
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', resetFormState);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Product Group';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Product Group';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Product Group?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
nameRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,100 @@
@page
@{
ViewData["Title"] = "Product List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="UnitPrice">Unit Price</label>
<input ref="unitPriceRef" v-model="state.unitPrice">
<label class="text-danger">{{ state.errors.unitPrice }}</label>
</div>
<div class="col-md-6">
<label for="UnitMeasureId">Unit Measure</label>
<div ref="unitMeasureIdRef"></div>
<label class="text-danger">{{ state.errors.unitMeasureId }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="ProductGroupId">Product Group</label>
<div ref="productGroupIdRef"></div>
<label class="text-danger">{{ state.errors.productGroupId }}</label>
</div>
<div class="col-md-6">
<div class="form-check mt-4">
<input v-model="state.physical" id="Physical" name="Physical" type="checkbox" class="form-check-input">
<label for="Physical" class="form-check-label">Is Physical Product?</label>
</div>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Products/ProductList.cshtml.js"></script>
}
@@ -0,0 +1,555 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
productGroupListLookupData: [],
unitMeasureListLookupData: [],
mainTitle: null,
id: '',
name: '',
number: '',
unitPrice: '',
description: '',
productGroupId: null,
unitMeasureId: null,
physical: false,
errors: {
name: '',
unitPrice: '',
productGroupId: '',
unitMeasureId: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const productGroupIdRef = Vue.ref(null);
const unitMeasureIdRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const unitPriceRef = Vue.ref(null);
const validateForm = function () {
state.errors.name = '';
state.errors.unitPrice = '';
state.errors.productGroupId = '';
state.errors.unitMeasureId = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!state.unitPrice) {
state.errors.unitPrice = 'Unit price is required.';
isValid = false;
} else if (!/^\d+(\.\d{1,2})?$/.test(state.unitPrice)) {
state.errors.unitPrice = 'Unit price must be a numeric value with up to two decimal places.';
isValid = false;
}
if (!state.productGroupId) {
state.errors.productGroupId = 'ProductGroup is required.';
isValid = false;
}
if (!state.unitMeasureId) {
state.errors.unitMeasureId = 'UnitMeasure is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.number = '';
state.unitPrice = '';
state.description = '';
state.productGroupId = null;
state.unitMeasureId = null;
state.physical = false;
state.errors = {
name: '',
unitPrice: '',
productGroupId: '',
unitMeasureId: ''
};
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, unitPrice, physical, description, productGroupId, unitMeasureId, createdById) => {
try {
const response = await AxiosManager.post('/Product/CreateProduct', {
name, unitPrice, physical, description, productGroupId, unitMeasureId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, unitPrice, physical, description, productGroupId, unitMeasureId, updatedById) => {
try {
const response = await AxiosManager.post('/Product/UpdateProduct', {
id, name, unitPrice, physical, description, productGroupId, unitMeasureId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Product/DeleteProduct', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductGroupListLookupData: async () => {
try {
const response = await AxiosManager.get('/ProductGroup/GetProductGroupList', {});
return response;
} catch (error) {
throw error;
}
},
getUnitMeasureListLookupData: async () => {
try {
const response = await AxiosManager.get('/UnitMeasure/GetUnitMeasureList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateProductGroupListLookupData: async () => {
const response = await services.getProductGroupListLookupData();
state.productGroupListLookupData = response?.data?.content?.data;
},
populateUnitMeasureListLookupData: async () => {
const response = await services.getUnitMeasureListLookupData();
state.unitMeasureListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const productGroupListLookup = {
obj: null,
create: () => {
if (state.productGroupListLookupData && Array.isArray(state.productGroupListLookupData)) {
productGroupListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.productGroupListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Product Group',
popupHeight: '200px',
change: (e) => {
state.productGroupId = e.value;
}
});
productGroupListLookup.obj.appendTo(productGroupIdRef.value);
} else {
console.error('ProductGroup list lookup data is not available or invalid.');
}
},
refresh: () => {
if (productGroupListLookup.obj) {
productGroupListLookup.obj.value = state.productGroupId;
}
},
};
const unitMeasureListLookup = {
obj: null,
create: () => {
if (state.unitMeasureListLookupData && Array.isArray(state.unitMeasureListLookupData)) {
unitMeasureListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.unitMeasureListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Unit Measure',
popupHeight: '200px',
change: (e) => {
state.unitMeasureId = e.value;
}
});
unitMeasureListLookup.obj.appendTo(unitMeasureIdRef.value);
} else {
console.error('UnitMeasure list lookup data is not available or invalid.');
}
},
refresh: () => {
if (unitMeasureListLookup.obj) {
unitMeasureListLookup.obj.value = state.unitMeasureId;
}
},
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
},
refresh: () => {
if (numberText.obj) {
numberText.obj.value = state.number;
}
}
};
const unitPriceNumber = {
obj: null,
create: () => {
unitPriceNumber.obj = new ej.inputs.NumericTextBox({
format: 'n2',
placeholder: 'Enter Unit Price',
min: 0,
step: 0.01,
validateDecimalOnType: true
});
unitPriceNumber.obj.appendTo(unitPriceRef.value);
},
refresh: () => {
if (unitPriceNumber.obj) {
unitPriceNumber.obj.value = state.unitPrice;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.number,
(newVal, oldVal) => {
numberText.refresh();
}
);
Vue.watch(
() => state.unitPrice,
(newVal, oldVal) => {
state.errors.unitPrice = '';
unitPriceNumber.refresh();
}
);
Vue.watch(
() => state.productGroupId,
(newVal, oldVal) => {
state.errors.productGroupId = '';
productGroupListLookup.refresh();
}
);
Vue.watch(
() => state.unitMeasureId,
(newVal, oldVal) => {
state.errors.unitMeasureId = '';
unitMeasureListLookup.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.unitPrice, state.physical, state.description, state.productGroupId, state.unitMeasureId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.unitPrice, state.physical, state.description, state.productGroupId, state.unitMeasureId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Product';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.name = response?.data?.content?.data.name ?? '';
state.unitPrice = response?.data?.content?.data.unitPrice ?? '';
state.description = response?.data?.content?.data.description ?? '';
state.productGroupId = response?.data?.content?.data.productGroupId ?? '';
state.unitMeasureId = response?.data?.content?.data.unitMeasureId ?? '';
state.physical = response?.data?.content?.data.physical ?? false;
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Products']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateProductGroupListLookupData();
productGroupListLookup.create();
await methods.populateUnitMeasureListLookupData();
unitMeasureListLookup.create();
nameText.create();
numberText.create();
unitPriceNumber.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', () => {
resetFormState();
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', resetFormState);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['productGroupName']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 200, minWidth: 200 },
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'productGroupName', headerText: 'Product Group', width: 150, minWidth: 150 },
{ field: 'unitPrice', headerText: 'Unit Price', width: 150, minWidth: 150, format: 'N2' },
{ field: 'unitMeasureName', headerText: 'Unit Measure', width: 150, minWidth: 150 },
{ field: 'physical', headerText: 'Physical Product', width: 200, minWidth: 200, textAlign: 'Center', type: 'boolean', displayAsCheckBox: true },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'name', 'productGroupName', 'unitPrice', 'unitMeasureName', 'physical', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Product';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Product';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.unitPrice = selectedRecord.unitPrice ?? '';
state.description = selectedRecord.description ?? '';
state.productGroupId = selectedRecord.productGroupId ?? '';
state.unitMeasureId = selectedRecord.unitMeasureId ?? '';
state.physical = selectedRecord.physical ?? false;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Product?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.unitPrice = selectedRecord.unitPrice ?? '';
state.description = selectedRecord.description ?? '';
state.productGroupId = selectedRecord.productGroupId ?? '';
state.unitMeasureId = selectedRecord.unitMeasureId ?? '';
state.physical = selectedRecord.physical ?? false;
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
productGroupIdRef,
unitMeasureIdRef,
nameRef,
numberRef,
unitPriceRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,166 @@
@page
@{
ViewData["Title"] = "My Profile";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.userId" id="UserId" name="UserId" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-0">
<div class="col-md-6">
<label for="FirstName">First Name</label>
<input ref="firstNameRef" v-model="state.firstName" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.firstName }}</label>
</div>
<div class="col-md-6">
<label for="LastName">Last Name</label>
<input ref="lastNameRef" v-model="state.lastName" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.lastName }}</label>
</div>
</div>
<div class="row mb-0">
<div class="col-12">
<label for="CompanyName">Company Name</label>
<textarea ref="companyNameRef" v-model="state.companyName" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
<!-- Modal untuk Change Password -->
<div class="modal fade" ref="changePasswordModalRef" id="ChangePasswordModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.changePasswordTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.userId" id="UserId" name="UserId" />
<form id="ChangePasswordForm">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary text-white">
Old Password
</div>
<div class="card-body">
<div class="mb-3">
<label for="OldPassword">Old Password</label>
<input ref="oldPasswordRef" v-model="state.oldPassword" type="password" class="form-control" placeholder="Enter old password">
<label class="text-danger">{{ state.errors.oldPassword }}</label>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header bg-success text-white">
New Password
</div>
<div class="card-body">
<div class="mb-3">
<label for="NewPassword">New Password</label>
<input ref="newPasswordRef" v-model="state.newPassword" type="password" class="form-control" placeholder="Enter new password">
<label class="text-danger">{{ state.errors.newPassword }}</label>
</div>
<div class="mb-3">
<label for="ConfirmNewPassword">Confirm New Password</label>
<input ref="confirmNewPasswordRef" v-model="state.confirmNewPassword" type="password" class="form-control" placeholder="Confirm new password">
<label class="text-danger">{{ state.errors.confirmNewPassword }}</label>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="ChangePasswordSaveButton" class="btn btn-primary" v-on:click="handler.handleChangePassword">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">Save</span>
<span v-else>Saving...</span>
</button>
</div>
</div>
</div>
</div>
<!-- Modal untuk Change Avatar -->
<div class="modal fade" ref="changeAvatarModalRef" id="ChangeAvatarModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.changeAvatarTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.userId" id="UserId" name="UserId" />
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Uploader Area</h5>
</div>
<div class="card-body">
<form ref="imageUploadRef" id="ImageUpload" class="dropzone"></form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Profiles/MyProfile.cshtml.js"></script>
}
@@ -0,0 +1,465 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
userId: '',
firstName: '',
lastName: '',
companyName: '',
oldPassword: '',
newPassword: '',
confirmNewPassword: '',
mainTitle: 'Edit MyProfile',
changePasswordTitle: 'Change Password',
changeAvatarTitle: 'Change Avatar',
errors: {
firstName: '',
lastName: '',
oldPassword: '',
newPassword: '',
confirmNewPassword: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const changePasswordModalRef = Vue.ref(null);
const changeAvatarModalRef = Vue.ref(null);
const firstNameRef = Vue.ref(null);
const lastNameRef = Vue.ref(null);
const companyNameRef = Vue.ref(null);
const oldPasswordRef = Vue.ref(null);
const newPasswordRef = Vue.ref(null);
const confirmNewPasswordRef = Vue.ref(null);
const imageUploadRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Security/GetMyProfileList?userId=' + StorageManager.getUserId(), {});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (userId, firstName, lastName, companyName) => {
try {
const response = await AxiosManager.post('/Security/UpdateMyProfile', {
userId, firstName, lastName, companyName
});
return response;
} catch (error) {
throw error;
}
},
updatePasswordData: async (userId, oldPassword, newPassword, confirmNewPassword) => {
try {
const response = await AxiosManager.post('/Security/UpdateMyProfilePassword', {
userId, oldPassword, newPassword, confirmNewPassword
});
return response;
} catch (error) {
throw error;
}
},
uploadImage: async (file) => {
const formData = new FormData();
formData.append('file', file);
try {
const response = await AxiosManager.post('/FileImage/UploadImage', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
return response;
} catch (error) {
throw error;
}
},
updateAvatarData: async (userId, avatar) => {
try {
const response = await AxiosManager.post('/Security/UpdateMyProfileAvatar', {
userId, avatar
});
return response;
} catch (error) {
throw error;
}
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'firstName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'firstName', headerText: 'First Name', width: 200, minWidth: 200 },
{ field: 'lastName', headerText: 'Last Name', width: 200, minWidth: 200 },
{ field: 'companyName', headerText: 'Company Name', width: 400, minWidth: 400 },
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ type: 'Separator' },
{ text: 'Change Password', tooltipText: 'Change Password', id: 'ChangePasswordCustom' },
{ text: 'Change Avatar', tooltipText: 'Change Avatar', id: 'ChangeAvatarCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], false);
mainGrid.obj.autoFitColumns(['firstName', 'lastName', 'companyName']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'EditCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.userId = selectedRecord.id ?? '';
state.firstName = selectedRecord.firstName ?? '';
state.lastName = selectedRecord.lastName ?? '';
state.companyName = selectedRecord.companyName ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'ChangePasswordCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.userId = selectedRecord.id ?? '';
changePasswordModal.obj.show();
}
}
if (args.item.id === 'ChangeAvatarCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.userId = selectedRecord.id ?? '';
changeAvatarModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const handler = {
handleSubmit: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
state.errors.firstName = '';
state.errors.lastName = '';
let isValid = true;
// Validasi firstName
if (!state.firstName) {
state.errors.firstName = 'First Name is required.';
isValid = false;
}
// Validasi lastName
if (!state.lastName) {
state.errors.lastName = 'Last Name is required.';
isValid = false;
}
if (!isValid) {
state.isSubmitting = false;
return;
}
try {
const response = await services.updateMainData(state.userId, state.firstName, state.lastName, state.companyName);
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
handleChangePassword: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
state.errors.oldPassword = '';
state.errors.newPassword = '';
state.errors.confirmNewPassword = '';
let isValid = true;
// old password validation
if (!state.oldPassword) {
state.errors.oldPassword = 'Old Password is required.';
isValid = false;
} else if (state.oldPassword.length < 6) {
state.errors.oldPassword = 'Old Password must be at least 6 characters.';
isValid = false;
}
// new password validation
if (!state.newPassword) {
state.errors.newPassword = 'New Password is required.';
isValid = false;
} else if (state.newPassword.length < 6) {
state.errors.newPassword = 'New Password must be at least 6 characters.';
isValid = false;
}
// confirm new password validation
if (!state.confirmNewPassword) {
state.errors.confirmNewPassword = 'Confirm New Password is required.';
isValid = false;
} else if (state.confirmNewPassword.length < 6) {
state.errors.confirmNewPassword = 'Confirm New Password must be at least 6 characters.';
isValid = false;
}
if (!isValid) {
state.isSubmitting = false;
return;
}
try {
const response = await services.updatePasswordData(state.userId, state.oldPassword, state.newPassword, state.confirmNewPassword);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
changePasswordModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
handleFileUpload: async (file) => {
try {
const response = await services.uploadImage(file);
if (response.status === 200) {
const imageName = response?.data?.content?.imageName;
await services.updateAvatarData(state.userId, imageName);
StorageManager.saveAvatar(imageName);
Swal.fire({
icon: "success",
title: "Upload Successful",
text: "Your image has been uploaded successfully!",
text: 'Page will be refreshed...',
timer: 1000,
showConfirmButton: false
});
setTimeout(() => {
changeAvatarModal.obj.hide();
location.reload();
}, 1000);
} else {
Swal.fire({
icon: "error",
title: "Upload Failed",
text: response.message ?? "An error occurred during upload."
});
}
} catch (error) {
Swal.fire({
icon: "error",
title: "Upload Failed",
text: "An unexpected error occurred."
});
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data;
},
};
Vue.onMounted(async () => {
Dropzone.autoDiscover = false;
try {
await SecurityManager.authorizePage(['Profiles']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
changePasswordModal.create();
changeAvatarModal.create();
initDropzone();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
let dropzoneInitialized = false;
const initDropzone = () => {
if (!dropzoneInitialized && imageUploadRef.value) {
dropzoneInitialized = true;
const dropzoneInstance = new Dropzone(imageUploadRef.value, {
url: "api/FileImage/UploadImage",
paramName: "file",
maxFilesize: 5,
acceptedFiles: "image/*",
addRemoveLinks: true,
dictDefaultMessage: "Drag and drop an image here to upload",
autoProcessQueue: false,
init: function () {
this.on("addedfile", async function (file) {
await handler.handleFileUpload(file);
});
}
});
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const changePasswordModal = {
obj: null,
create: () => {
changePasswordModal.obj = new bootstrap.Modal(changePasswordModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const changeAvatarModal = {
obj: null,
create: () => {
changeAvatarModal.obj = new bootstrap.Modal(changeAvatarModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
state,
mainGridRef,
mainModalRef,
changePasswordModalRef,
changeAvatarModalRef,
firstNameRef,
lastNameRef,
companyNameRef,
oldPasswordRef,
newPasswordRef,
confirmNewPasswordRef,
imageUploadRef,
handler
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,142 @@
@page
@{
ViewData["Title"] = "Purchase Order List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderDate">Order Date</label>
<input ref="orderDateRef" />
<label class="text-danger">{{ state.errors.orderDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="VendorId">Vendor</label>
<div ref="vendorIdRef"></div>
<label class="text-danger">{{ state.errors.vendorId }}</label>
</div>
<div class="col-md-6">
<label for="TaxId">Tax</label>
<div ref="taxIdRef"></div>
<label class="text-danger">{{ state.errors.taxId }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderStatus">Order Status</label>
<div ref="orderStatusRef"></div>
<label class="text-danger">{{ state.errors.orderStatus }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Purchase Order Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Payment Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Subtotal</span>
<span id="SubTotalAmount">{{ state.subTotalAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Tax</span>
<span id="TaxAmount">{{ state.taxAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Amount</span>
<span id="TotalAmount" class="fw-bold text-success">{{ state.totalAmount }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseOrders/PurchaseOrderList.cshtml.js"></script>
}
@@ -0,0 +1,988 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
vendorListLookupData: [],
taxListLookupData: [],
purchaseOrderStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
mainTitle: null,
id: '',
number: '',
orderDate: '',
description: '',
vendorId: null,
taxId: null,
orderStatus: null,
errors: {
orderDate: '',
vendorId: '',
taxId: '',
orderStatus: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
subTotalAmount: '0.00',
taxAmount: '0.00',
totalAmount: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const orderDateRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const vendorIdRef = Vue.ref(null);
const taxIdRef = Vue.ref(null);
const orderStatusRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const validateForm = function () {
state.errors.orderDate = '';
state.errors.vendorId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
let isValid = true;
if (!state.orderDate) {
state.errors.orderDate = 'Order date is required.';
isValid = false;
}
if (!state.vendorId) {
state.errors.vendorId = 'Vendor is required.';
isValid = false;
}
if (!state.taxId) {
state.errors.taxId = 'Tax is required.';
isValid = false;
}
if (!state.orderStatus) {
state.errors.orderStatus = 'Order status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.orderDate = '';
state.description = '';
state.vendorId = null;
state.taxId = null;
state.orderStatus = null;
state.errors = {
orderDate: '',
vendorId: '',
taxId: '',
orderStatus: '',
description: ''
};
state.secondaryData = [];
state.subTotalAmount = '0.00';
state.taxAmount = '0.00';
state.totalAmount = '0.00';
state.showComplexDiv = false;
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/PurchaseOrder/GetPurchaseOrderList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (orderDate, description, orderStatus, taxId, vendorId, createdById) => {
try {
const response = await AxiosManager.post('/PurchaseOrder/CreatePurchaseOrder', {
orderDate, description, orderStatus, taxId, vendorId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, orderDate, description, orderStatus, taxId, vendorId, updatedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrder/UpdatePurchaseOrder', {
id, orderDate, description, orderStatus, taxId, vendorId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrder/DeletePurchaseOrder', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getVendorListLookupData: async () => {
try {
const response = await AxiosManager.get('/Vendor/GetVendorList', {});
return response;
} catch (error) {
throw error;
}
},
getTaxListLookupData: async () => {
try {
const response = await AxiosManager.get('/Tax/GetTaxList', {});
return response;
} catch (error) {
throw error;
}
},
getPurchaseOrderStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/PurchaseOrder/GetPurchaseOrderStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (purchaseOrderId) => {
try {
const response = await AxiosManager.get('/PurchaseOrderItem/GetPurchaseOrderItemByPurchaseOrderIdList?purchaseOrderId=' + purchaseOrderId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (unitPrice, quantity, summary, productId, purchaseOrderId, createdById) => {
try {
const response = await AxiosManager.post('/PurchaseOrderItem/CreatePurchaseOrderItem', {
unitPrice, quantity, summary, productId, purchaseOrderId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, unitPrice, quantity, summary, productId, purchaseOrderId, updatedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrderItem/UpdatePurchaseOrderItem', {
id, unitPrice, quantity, summary, productId, purchaseOrderId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrderItem/DeletePurchaseOrderItem', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
}
};
const methods = {
populateVendorListLookupData: async () => {
const response = await services.getVendorListLookupData();
state.vendorListLookupData = response?.data?.content?.data;
},
populateTaxListLookupData: async () => {
const response = await services.getTaxListLookupData();
state.taxListLookupData = response?.data?.content?.data;
},
populatePurchaseOrderStatusListLookupData: async () => {
const response = await services.getPurchaseOrderStatusListLookupData();
state.purchaseOrderStatusListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
orderDate: new Date(item.orderDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateSecondaryData: async (purchaseOrderId) => {
try {
const response = await services.getSecondaryData(purchaseOrderId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshPaymentSummary(purchaseOrderId);
} catch (error) {
state.secondaryData = [];
}
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data;
},
refreshPaymentSummary: async (id) => {
const record = state.mainData.find(item => item.id === id);
if (record) {
state.subTotalAmount = NumberFormatManager.formatToLocale(record.beforeTaxAmount ?? 0);
state.taxAmount = NumberFormatManager.formatToLocale(record.taxAmount ?? 0);
state.totalAmount = NumberFormatManager.formatToLocale(record.afterTaxAmount ?? 0);
}
},
handleFormSubmit: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
if (!validateForm()) {
state.isSubmitting = false;
return;
}
try {
const response = state.id === ''
? await services.createMainData(state.orderDate, state.description, state.orderStatus, state.taxId, state.vendorId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.orderDate, state.description, state.orderStatus, state.taxId, state.vendorId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Purchase Order';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.orderDate = response?.data?.content?.data.orderDate ? new Date(response.data.content.data.orderDate) : null;
state.description = response?.data?.content?.data.description ?? '';
state.vendorId = response?.data?.content?.data.vendorId ?? '';
state.taxId = response?.data?.content?.data.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(response?.data?.content?.data.orderStatus ?? '');
state.showComplexDiv = true;
await methods.refreshPaymentSummary(state.id);
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 1000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
onMainModalHidden: () => {
state.errors.orderDate = '';
state.errors.vendorId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
taxListLookup.trackingChange = false;
}
};
const vendorListLookup = {
obj: null,
create: () => {
if (state.vendorListLookupData && Array.isArray(state.vendorListLookupData)) {
vendorListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.vendorListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Vendor',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('name', 'startsWith', e.text, true);
}
e.updateData(state.vendorListLookupData, query);
},
change: (e) => {
state.vendorId = e.value;
}
});
vendorListLookup.obj.appendTo(vendorIdRef.value);
}
},
refresh: () => {
if (vendorListLookup.obj) {
vendorListLookup.obj.value = state.vendorId;
}
}
};
const taxListLookup = {
obj: null,
trackingChange: false,
create: () => {
if (state.taxListLookupData && Array.isArray(state.taxListLookupData)) {
taxListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.taxListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Tax',
change: async (e) => {
state.taxId = e.value;
if (e.isInteracted && taxListLookup.trackingChange) {
await methods.handleFormSubmit();
}
}
});
taxListLookup.obj.appendTo(taxIdRef.value);
}
},
refresh: () => {
if (taxListLookup.obj) {
taxListLookup.obj.value = state.taxId;
}
}
};
const purchaseOrderStatusListLookup = {
obj: null,
create: () => {
if (state.purchaseOrderStatusListLookupData && Array.isArray(state.purchaseOrderStatusListLookupData)) {
purchaseOrderStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.purchaseOrderStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select an Order Status',
change: (e) => {
state.orderStatus = e.value;
}
});
purchaseOrderStatusListLookup.obj.appendTo(orderStatusRef.value);
}
},
refresh: () => {
if (purchaseOrderStatusListLookup.obj) {
purchaseOrderStatusListLookup.obj.value = state.orderStatus;
}
}
};
const orderDatePicker = {
obj: null,
create: () => {
orderDatePicker.obj = new ej.calendars.DatePicker({
format: 'yyyy-MM-dd',
value: state.orderDate ? new Date(state.orderDate) : null,
change: (e) => {
state.orderDate = DateFormatManager.preserveClientDate(e.value);
}
});
orderDatePicker.obj.appendTo(orderDateRef.value);
},
refresh: () => {
if (orderDatePicker.obj) {
orderDatePicker.obj.value = state.orderDate ? new Date(state.orderDate) : null;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
}
};
Vue.watch(
() => state.orderDate,
(newVal, oldVal) => {
orderDatePicker.refresh();
state.errors.orderDate = '';
}
);
Vue.watch(
() => state.vendorId,
(newVal, oldVal) => {
vendorListLookup.refresh();
state.errors.vendorId = '';
}
);
Vue.watch(
() => state.taxId,
(newVal, oldVal) => {
taxListLookup.refresh();
state.errors.taxId = '';
}
);
Vue.watch(
() => state.orderStatus,
(newVal, oldVal) => {
purchaseOrderStatusListLookup.refresh();
state.errors.orderStatus = '';
}
);
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: { columns: ['vendorName'] },
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'orderDate', headerText: 'PO Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'vendorName', headerText: 'Vendor', width: 200, minWidth: 200 },
{ field: 'orderStatusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'taxName', headerText: 'Tax', width: 150, minWidth: 150 },
{ field: 'afterTaxAmount', headerText: 'Total Amount', width: 150, minWidth: 150, format: 'N2' },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'orderDate', 'vendorName', 'orderStatusName', 'taxName', 'afterTaxAmount', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Purchase Order';
resetFormState();
state.secondaryData = [];
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Purchase Order';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.vendorId = selectedRecord.vendorId ?? '';
state.taxId = selectedRecord.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = true;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Purchase Order?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.vendorId = selectedRecord.vendorId ?? '';
state.taxId = selectedRecord.taxId ?? '';
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = false;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/PurchaseOrders/PurchaseOrderPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'productName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
let productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: () => {
productObj.destroy();
},
write: (args) => {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.productId,
change: (e) => {
const selectedProduct = state.productListLookupData.find(item => item.id === e.value);
if (selectedProduct) {
args.rowData.productId = selectedProduct.id;
if (numberObj) {
numberObj.value = selectedProduct.number;
}
if (priceObj) {
priceObj.value = selectedProduct.unitPrice;
}
if (summaryObj) {
summaryObj.value = selectedProduct.description;
}
if (quantityObj) {
quantityObj.value = 1;
const total = selectedProduct.unitPrice * quantityObj.value;
if (totalObj) {
totalObj.value = total;
}
}
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'unitPrice',
headerText: 'Unit Price',
width: 200, validationRules: { required: true }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let priceElem = document.createElement('input');
return priceElem;
},
read: () => {
return priceObj.value;
},
destroy: () => {
priceObj.destroy();
},
write: (args) => {
priceObj = new ej.inputs.NumericTextBox({
value: args.rowData.unitPrice ?? 0,
change: (e) => {
if (quantityObj && totalObj) {
const total = e.value * quantityObj.value;
totalObj.value = total;
}
}
});
priceObj.appendTo(args.element);
}
}
},
{
field: 'quantity',
headerText: 'Quantity',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let quantityElem = document.createElement('input');
return quantityElem;
},
read: () => {
return quantityObj.value;
},
destroy: () => {
quantityObj.destroy();
},
write: (args) => {
quantityObj = new ej.inputs.NumericTextBox({
value: args.rowData.quantity ?? 0,
change: (e) => {
if (priceObj && totalObj) {
const total = e.value * priceObj.value;
totalObj.value = total;
}
}
});
quantityObj.appendTo(args.element);
}
}
},
{
field: 'total',
headerText: 'Total',
width: 200, validationRules: { required: false }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let totalElem = document.createElement('input');
return totalElem;
},
read: () => {
return totalObj.value;
},
destroy: () => {
totalObj.destroy();
},
write: (args) => {
totalObj = new ej.inputs.NumericTextBox({
value: args.rowData.total ?? 0,
readonly: true
});
totalObj.appendTo(args.element);
}
}
},
{
field: 'productNumber',
headerText: 'Product Number',
allowEditing: false,
width: 180,
edit: {
create: () => {
let numberElem = document.createElement('input');
return numberElem;
},
read: () => {
return numberObj.value;
},
destroy: () => {
numberObj.destroy();
},
write: (args) => {
numberObj = new ej.inputs.TextBox();
numberObj.value = args.rowData.productNumber;
numberObj.readonly = true;
numberObj.appendTo(args.element);
}
}
},
{
field: 'summary',
headerText: 'Summary',
width: 200,
edit: {
create: () => {
let summaryElem = document.createElement('input');
return summaryElem;
},
read: () => {
return summaryObj.value;
},
destroy: () => {
summaryObj.destroy();
},
write: (args) => {
summaryObj = new ej.inputs.TextBox();
summaryObj.value = args.rowData.summary;
summaryObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
const purchaseOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.createSecondaryData(data?.unitPrice, data?.quantity, data?.summary, data?.productId, purchaseOrderId, userId);
await methods.populateSecondaryData(purchaseOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'save' && args.action === 'edit') {
const purchaseOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.updateSecondaryData(data?.id, data?.unitPrice, data?.quantity, data?.summary, data?.productId, purchaseOrderId, userId);
await methods.populateSecondaryData(purchaseOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'delete') {
const purchaseOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data[0];
await services.deleteSecondaryData(data?.id, userId);
await methods.populateSecondaryData(purchaseOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
}
await methods.populateMainData();
mainGrid.refresh();
await methods.refreshPaymentSummary(state.id);
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseOrders']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateVendorListLookupData();
vendorListLookup.create();
await methods.populateTaxListLookupData();
taxListLookup.create();
await methods.populatePurchaseOrderStatusListLookupData();
purchaseOrderStatusListLookup.create();
orderDatePicker.create();
numberText.create();
await methods.populateProductListLookupData();
await secondaryGrid.create(state.secondaryData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
return {
mainGridRef,
mainModalRef,
orderDateRef,
numberRef,
vendorIdRef,
taxIdRef,
orderStatusRef,
secondaryGridRef,
state,
methods,
handler: {
handleSubmit: methods.handleFormSubmit
}
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,245 @@
@page
@{
ViewData["Title"] = "Purchase Order PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Purchase Order</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Vendor Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.vendor.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.vendorAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.vendor.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.vendor.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Order Information</th>
</tr>
<tr>
<td><strong>Order Number:</strong></td>
<td>{{ state.orderNumber }}</td>
</tr>
<tr>
<td><strong>Order Date:</strong></td>
<td>{{ state.orderDate }}</td>
</tr>
<tr>
<td><strong>Currency:</strong></td>
<td>{{ state.orderCurrency }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Product Number</th>
<th>Product Name</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.items" :key="item.productNumber">
<td>{{ item?.product?.number }}</td>
<td>{{ item?.product?.name }}</td>
<td>{{ item?.unitPrice }}</td>
<td>{{ item?.quantity }}</td>
<td>{{ item?.total }}</td>
</tr>
</tbody>
</table>
<div class="payment-summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold;">Subtotal:</td>
<td style="text-align: right;">{{ state.subTotal }}</td>
</tr>
<tr>
<td style="font-weight: bold;">Tax:</td>
<td style="text-align: right;">{{ state.tax }}</td>
</tr>
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Amount:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.totalAmount }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.payment-summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.payment-summary .column {
width: 48%;
}
.payment-summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseOrders/PurchaseOrderPdf.cshtml.js"></script>
}
@@ -0,0 +1,145 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
vendor: {
name: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
emailAddress: '',
phoneNumber: ''
},
vendorAddress: '',
orderNumber: '',
orderDate: '',
orderCurrency: '',
subTotal: '',
tax: '',
totalAmount: '',
items: [],
isDownloading: false
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/PurchaseOrder/GetPurchaseOrderSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
const pdfData = response?.data?.content?.data || {};
state.items = pdfData.purchaseOrderItemList || [];
state.vendor = pdfData.vendor || {};
state.orderNumber = pdfData.number || '';
state.orderDate = DateFormatManager.formatToLocale(pdfData.orderDate) || '';
state.orderCurrency = StorageManager.getCompany()?.currency || '';
state.subTotal = NumberFormatManager.formatToLocale(pdfData.beforeTaxAmount) || '';
state.tax = NumberFormatManager.formatToLocale(pdfData.taxAmount) || '';
state.totalAmount = NumberFormatManager.formatToLocale(pdfData.afterTaxAmount) || '';
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
state.vendorAddress = [
state.vendor.street,
state.vendor.city,
state.vendor.state,
state.vendor.zipCode,
state.vendor.country
].filter(Boolean).join(', ');
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`purchase-order-${state.orderNumber || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseOrders']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,18 @@
@page
@{
ViewData["Title"] = "Purchase Report List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseReports/PurchaseReportList.cshtml.js"></script>
}
@@ -0,0 +1,130 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: []
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/PurchaseOrderItem/GetPurchaseOrderItemList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['purchaseOrderNumber']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'purchaseOrderNumber', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'vendorName', headerText: 'Vendor', width: 200, minWidth: 200 },
{ field: 'purchaseOrderNumber', headerText: 'PurchaseOrder', width: 200, minWidth: 200 },
{ field: 'productNumber', headerText: 'Product Number', width: 200, minWidth: 200 },
{ field: 'productName', headerText: 'Product Name', width: 200, minWidth: 200 },
{ field: 'unitPrice', headerText: 'Unit Price', width: 150, minWidth: 150, format: 'N2' },
{ field: 'quantity', headerText: 'Quantity', width: 150, minWidth: 150 },
{ field: 'total', headerText: 'Total', width: 150, minWidth: 150, format: 'N2' },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
aggregates: [
{
columns: [
{
type: 'Sum',
field: 'total',
groupCaptionTemplate: 'Total: ${Sum}',
format: 'N2'
}
]
}
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['vendorName', 'purchaseOrderNumber', 'productNumber', 'productName', 'unitPrice', 'quantity', 'total', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => { },
rowDeselected: () => { },
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseReports']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
state,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,18 @@
@page
@{
ViewData["Title"] = "Role List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Roles/RoleList.cshtml.js"></script>
}
@@ -0,0 +1,109 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: []
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Security/GetRoleList', {});
return response;
} catch (error) {
throw error;
}
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'name', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 300, minWidth: 300 },
],
toolbar: [
'ExcelExport', 'Search',
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['name']);
},
excelExportComplete: () => { },
rowSelected: () => { },
rowDeselected: () => { },
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data;
},
init: async () => {
try {
await SecurityManager.authorizePage(['Roles']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
},
};
Vue.onMounted(() => {
methods.init();
});
return {
state,
mainGridRef
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,142 @@
@page
@{
ViewData["Title"] = "Sales Order List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderDate">Order Date</label>
<input ref="orderDateRef" />
<label class="text-danger">{{ state.errors.orderDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CustomerId">Customer</label>
<div ref="customerIdRef"></div>
<label class="text-danger">{{ state.errors.customerId }}</label>
</div>
<div class="col-md-6">
<label for="TaxId">Tax</label>
<div ref="taxIdRef"></div>
<label class="text-danger">{{ state.errors.taxId }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderStatus">Order Status</label>
<div ref="orderStatusRef"></div>
<label class="text-danger">{{ state.errors.orderStatus }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Sales Order Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Payment Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Subtotal</span>
<span id="SubTotalAmount">{{ state.subTotalAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Tax</span>
<span id="TaxAmount">{{ state.taxAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Amount</span>
<span id="TotalAmount" class="fw-bold text-success">{{ state.totalAmount }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/SalesOrders/SalesOrderList.cshtml.js"></script>
}
@@ -0,0 +1,988 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
customerListLookupData: [],
taxListLookupData: [],
salesOrderStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
mainTitle: null,
id: '',
number: '',
orderDate: '',
description: '',
customerId: null,
taxId: null,
orderStatus: null,
errors: {
orderDate: '',
customerId: '',
taxId: '',
orderStatus: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
subTotalAmount: '0.00',
taxAmount: '0.00',
totalAmount: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const orderDateRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const customerIdRef = Vue.ref(null);
const taxIdRef = Vue.ref(null);
const orderStatusRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const validateForm = function () {
state.errors.orderDate = '';
state.errors.customerId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
let isValid = true;
if (!state.orderDate) {
state.errors.orderDate = 'Order date is required.';
isValid = false;
}
if (!state.customerId) {
state.errors.customerId = 'Customer is required.';
isValid = false;
}
if (!state.taxId) {
state.errors.taxId = 'Tax is required.';
isValid = false;
}
if (!state.orderStatus) {
state.errors.orderStatus = 'Order status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.orderDate = '';
state.description = '';
state.customerId = null;
state.taxId = null;
state.orderStatus = null;
state.errors = {
orderDate: '',
customerId: '',
taxId: '',
orderStatus: '',
description: ''
};
state.secondaryData = [];
state.subTotalAmount = '0.00';
state.taxAmount = '0.00';
state.totalAmount = '0.00';
state.showComplexDiv = false;
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/SalesOrder/GetSalesOrderList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (orderDate, description, orderStatus, taxId, customerId, createdById) => {
try {
const response = await AxiosManager.post('/SalesOrder/CreateSalesOrder', {
orderDate, description, orderStatus, taxId, customerId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, orderDate, description, orderStatus, taxId, customerId, updatedById) => {
try {
const response = await AxiosManager.post('/SalesOrder/UpdateSalesOrder', {
id, orderDate, description, orderStatus, taxId, customerId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/SalesOrder/DeleteSalesOrder', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getCustomerListLookupData: async () => {
try {
const response = await AxiosManager.get('/Customer/GetCustomerList', {});
return response;
} catch (error) {
throw error;
}
},
getTaxListLookupData: async () => {
try {
const response = await AxiosManager.get('/Tax/GetTaxList', {});
return response;
} catch (error) {
throw error;
}
},
getSalesOrderStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/SalesOrder/GetSalesOrderStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (salesOrderId) => {
try {
const response = await AxiosManager.get('/SalesOrderItem/GetSalesOrderItemBySalesOrderIdList?salesOrderId=' + salesOrderId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (unitPrice, quantity, summary, productId, salesOrderId, createdById) => {
try {
const response = await AxiosManager.post('/SalesOrderItem/CreateSalesOrderItem', {
unitPrice, quantity, summary, productId, salesOrderId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, unitPrice, quantity, summary, productId, salesOrderId, updatedById) => {
try {
const response = await AxiosManager.post('/SalesOrderItem/UpdateSalesOrderItem', {
id, unitPrice, quantity, summary, productId, salesOrderId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/SalesOrderItem/DeleteSalesOrderItem', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
}
};
const methods = {
populateCustomerListLookupData: async () => {
const response = await services.getCustomerListLookupData();
state.customerListLookupData = response?.data?.content?.data;
},
populateTaxListLookupData: async () => {
const response = await services.getTaxListLookupData();
state.taxListLookupData = response?.data?.content?.data;
},
populateSalesOrderStatusListLookupData: async () => {
const response = await services.getSalesOrderStatusListLookupData();
state.salesOrderStatusListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
orderDate: new Date(item.orderDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateSecondaryData: async (salesOrderId) => {
try {
const response = await services.getSecondaryData(salesOrderId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshPaymentSummary(salesOrderId);
} catch (error) {
state.secondaryData = [];
}
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data;
},
refreshPaymentSummary: async (id) => {
const record = state.mainData.find(item => item.id === id);
if (record) {
state.subTotalAmount = NumberFormatManager.formatToLocale(record.beforeTaxAmount ?? 0);
state.taxAmount = NumberFormatManager.formatToLocale(record.taxAmount ?? 0);
state.totalAmount = NumberFormatManager.formatToLocale(record.afterTaxAmount ?? 0);
}
},
handleFormSubmit: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
if (!validateForm()) {
state.isSubmitting = false;
return;
}
try {
const response = state.id === ''
? await services.createMainData(state.orderDate, state.description, state.orderStatus, state.taxId, state.customerId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.orderDate, state.description, state.orderStatus, state.taxId, state.customerId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Sales Order';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.orderDate = response?.data?.content?.data.orderDate ? new Date(response.data.content.data.orderDate) : null;
state.description = response?.data?.content?.data.description ?? '';
state.customerId = response?.data?.content?.data.customerId ?? '';
state.taxId = response?.data?.content?.data.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(response?.data?.content?.data.orderStatus ?? '');
state.showComplexDiv = true;
await methods.refreshPaymentSummary(state.id);
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 1000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
onMainModalHidden: () => {
state.errors.orderDate = '';
state.errors.customerId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
taxListLookup.trackingChange = false;
}
};
const customerListLookup = {
obj: null,
create: () => {
if (state.customerListLookupData && Array.isArray(state.customerListLookupData)) {
customerListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.customerListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Customer',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('name', 'startsWith', e.text, true);
}
e.updateData(state.customerListLookupData, query);
},
change: (e) => {
state.customerId = e.value;
}
});
customerListLookup.obj.appendTo(customerIdRef.value);
}
},
refresh: () => {
if (customerListLookup.obj) {
customerListLookup.obj.value = state.customerId;
}
}
};
const taxListLookup = {
obj: null,
trackingChange: false,
create: () => {
if (state.taxListLookupData && Array.isArray(state.taxListLookupData)) {
taxListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.taxListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Tax',
change: async (e) => {
state.taxId = e.value;
if (e.isInteracted && taxListLookup.trackingChange) {
await methods.handleFormSubmit();
}
}
});
taxListLookup.obj.appendTo(taxIdRef.value);
}
},
refresh: () => {
if (taxListLookup.obj) {
taxListLookup.obj.value = state.taxId;
}
}
};
const salesOrderStatusListLookup = {
obj: null,
create: () => {
if (state.salesOrderStatusListLookupData && Array.isArray(state.salesOrderStatusListLookupData)) {
salesOrderStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.salesOrderStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select an Order Status',
change: (e) => {
state.orderStatus = e.value;
}
});
salesOrderStatusListLookup.obj.appendTo(orderStatusRef.value);
}
},
refresh: () => {
if (salesOrderStatusListLookup.obj) {
salesOrderStatusListLookup.obj.value = state.orderStatus;
}
}
};
const orderDatePicker = {
obj: null,
create: () => {
orderDatePicker.obj = new ej.calendars.DatePicker({
format: 'yyyy-MM-dd',
value: state.orderDate ? new Date(state.orderDate) : null,
change: (e) => {
state.orderDate = DateFormatManager.preserveClientDate(e.value);
}
});
orderDatePicker.obj.appendTo(orderDateRef.value);
},
refresh: () => {
if (orderDatePicker.obj) {
orderDatePicker.obj.value = state.orderDate ? new Date(state.orderDate) : null;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
}
};
Vue.watch(
() => state.orderDate,
(newVal, oldVal) => {
orderDatePicker.refresh();
state.errors.orderDate = '';
}
);
Vue.watch(
() => state.customerId,
(newVal, oldVal) => {
customerListLookup.refresh();
state.errors.customerId = '';
}
);
Vue.watch(
() => state.taxId,
(newVal, oldVal) => {
taxListLookup.refresh();
state.errors.taxId = '';
}
);
Vue.watch(
() => state.orderStatus,
(newVal, oldVal) => {
salesOrderStatusListLookup.refresh();
state.errors.orderStatus = '';
}
);
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: { columns: ['customerName'] },
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'orderDate', headerText: 'SO Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'customerName', headerText: 'Customer', width: 200, minWidth: 200 },
{ field: 'orderStatusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'taxName', headerText: 'Tax', width: 150, minWidth: 150 },
{ field: 'afterTaxAmount', headerText: 'Total Amount', width: 150, minWidth: 150, format: 'N2' },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'orderDate', 'customerName', 'orderStatusName', 'taxName', 'afterTaxAmount', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Sales Order';
resetFormState();
state.secondaryData = [];
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Sales Order';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
state.taxId = selectedRecord.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = true;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Sales Order?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
state.taxId = selectedRecord.taxId ?? '';
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = false;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/SalesOrders/SalesOrderPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'productName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
let productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: () => {
productObj.destroy();
},
write: (args) => {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.productId,
change: (e) => {
const selectedProduct = state.productListLookupData.find(item => item.id === e.value);
if (selectedProduct) {
args.rowData.productId = selectedProduct.id;
if (numberObj) {
numberObj.value = selectedProduct.number;
}
if (priceObj) {
priceObj.value = selectedProduct.unitPrice;
}
if (summaryObj) {
summaryObj.value = selectedProduct.description;
}
if (quantityObj) {
quantityObj.value = 1;
const total = selectedProduct.unitPrice * quantityObj.value;
if (totalObj) {
totalObj.value = total;
}
}
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'unitPrice',
headerText: 'Unit Price',
width: 200, validationRules: { required: true }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let priceElem = document.createElement('input');
return priceElem;
},
read: () => {
return priceObj.value;
},
destroy: () => {
priceObj.destroy();
},
write: (args) => {
priceObj = new ej.inputs.NumericTextBox({
value: args.rowData.unitPrice ?? 0,
change: (e) => {
if (quantityObj && totalObj) {
const total = e.value * quantityObj.value;
totalObj.value = total;
}
}
});
priceObj.appendTo(args.element);
}
}
},
{
field: 'quantity',
headerText: 'Quantity',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let quantityElem = document.createElement('input');
return quantityElem;
},
read: () => {
return quantityObj.value;
},
destroy: () => {
quantityObj.destroy();
},
write: (args) => {
quantityObj = new ej.inputs.NumericTextBox({
value: args.rowData.quantity ?? 0,
change: (e) => {
if (priceObj && totalObj) {
const total = e.value * priceObj.value;
totalObj.value = total;
}
}
});
quantityObj.appendTo(args.element);
}
}
},
{
field: 'total',
headerText: 'Total',
width: 200, validationRules: { required: false }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let totalElem = document.createElement('input');
return totalElem;
},
read: () => {
return totalObj.value;
},
destroy: () => {
totalObj.destroy();
},
write: (args) => {
totalObj = new ej.inputs.NumericTextBox({
value: args.rowData.total ?? 0,
readonly: true
});
totalObj.appendTo(args.element);
}
}
},
{
field: 'productNumber',
headerText: 'Product Number',
allowEditing: false,
width: 180,
edit: {
create: () => {
let numberElem = document.createElement('input');
return numberElem;
},
read: () => {
return numberObj.value;
},
destroy: () => {
numberObj.destroy();
},
write: (args) => {
numberObj = new ej.inputs.TextBox();
numberObj.value = args.rowData.productNumber;
numberObj.readonly = true;
numberObj.appendTo(args.element);
}
}
},
{
field: 'summary',
headerText: 'Summary',
width: 200,
edit: {
create: () => {
let summaryElem = document.createElement('input');
return summaryElem;
},
read: () => {
return summaryObj.value;
},
destroy: () => {
summaryObj.destroy();
},
write: (args) => {
summaryObj = new ej.inputs.TextBox();
summaryObj.value = args.rowData.summary;
summaryObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
const salesOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.createSecondaryData(data?.unitPrice, data?.quantity, data?.summary, data?.productId, salesOrderId, userId);
await methods.populateSecondaryData(salesOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'save' && args.action === 'edit') {
const salesOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.updateSecondaryData(data?.id, data?.unitPrice, data?.quantity, data?.summary, data?.productId, salesOrderId, userId);
await methods.populateSecondaryData(salesOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'delete') {
const salesOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data[0];
await services.deleteSecondaryData(data?.id, userId);
await methods.populateSecondaryData(salesOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
}
await methods.populateMainData();
mainGrid.refresh();
await methods.refreshPaymentSummary(state.id);
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['SalesOrders']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateCustomerListLookupData();
customerListLookup.create();
await methods.populateTaxListLookupData();
taxListLookup.create();
await methods.populateSalesOrderStatusListLookupData();
salesOrderStatusListLookup.create();
orderDatePicker.create();
numberText.create();
await methods.populateProductListLookupData();
await secondaryGrid.create(state.secondaryData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
return {
mainGridRef,
mainModalRef,
orderDateRef,
numberRef,
customerIdRef,
taxIdRef,
orderStatusRef,
secondaryGridRef,
state,
methods,
handler: {
handleSubmit: methods.handleFormSubmit
}
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,241 @@
@page
@{
ViewData["Title"] = "Sales Order PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Sales Order</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Customer Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.customer.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.customerAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.customer.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.customer.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Order Information</th>
</tr>
<tr>
<td><strong>Order Number:</strong></td>
<td>{{ state.orderNumber }}</td>
</tr>
<tr>
<td><strong>Order Date:</strong></td>
<td>{{ state.orderDate }}</td>
</tr>
<tr>
<td><strong>Currency:</strong></td>
<td>{{ state.orderCurrency }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Product Number</th>
<th>Product Name</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.items" :key="item.productNumber">
<td>{{ item?.product?.number }}</td>
<td>{{ item?.product?.name }}</td>
<td>{{ item?.unitPrice }}</td>
<td>{{ item?.quantity }}</td>
<td>{{ item?.total }}</td>
</tr>
</tbody>
</table>
<div class="payment-summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold;">Subtotal:</td>
<td style="text-align: right;">{{ state.subTotal }}</td>
</tr>
<tr>
<td style="font-weight: bold;">Tax:</td>
<td style="text-align: right;">{{ state.tax }}</td>
</tr>
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Amount:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.totalAmount }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.payment-summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.payment-summary .column {
width: 48%;
}
.payment-summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/SalesOrders/SalesOrderPdf.cshtml.js"></script>
}

Some files were not shown because too many files have changed in this diff Show More