WIP separation Web et API

This commit is contained in:
Paul Schneider 2025-02-12 20:41:14 +00:00
commit 49826eae4a
55 changed files with 68 additions and 95 deletions

View file

@ -0,0 +1,154 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Workflow;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/activity")]
[AllowAnonymous]
public class ActivityApiController : Controller
{
private ApplicationDbContext _context;
public ActivityApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/ActivityApi
[HttpGet]
public IEnumerable<Activity> GetActivities()
{
return _context.Activities.Include(a=>a.Forms).Where( a => !a.Hidden );
}
// GET: api/ActivityApi/5
[HttpGet("{id}", Name = "GetActivity")]
public async Task<IActionResult> GetActivity([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
if (activity == null)
{
return NotFound();
}
// Also return hidden ones
// hidden doesn't mean disabled
return Ok(activity);
}
// PUT: api/ActivityApi/5
[HttpPut("{id}"),Authorize("AdministratorOnly")]
public async Task<IActionResult> PutActivity([FromRoute] string id, [FromBody] Activity activity)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != activity.Code)
{
return BadRequest();
}
_context.Entry(activity).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!ActivityExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ActivityApi
[HttpPost,Authorize("AdministratorOnly")]
public async Task<IActionResult> PostActivity([FromBody] Activity activity)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Activities.Add(activity);
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateException)
{
if (ActivityExists(activity.Code))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetActivity", new { id = activity.Code }, activity);
}
// DELETE: api/ActivityApi/5
[HttpDelete("{id}"),Authorize("AdministratorOnly")]
public async Task<IActionResult> DeleteActivity([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
if (activity == null)
{
return NotFound();
}
_context.Activities.Remove(activity);
await _context.SaveChangesAsync(User.GetUserId());
return Ok(activity);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool ActivityExists(string id)
{
return _context.Activities.Count(e => e.Code == id) > 0;
}
}
}

View file

@ -0,0 +1,184 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using System.Security.Claims;
using Yavsc.Helpers;
using Yavsc.ViewModels;
namespace Yavsc.ApiControllers
{
using Models;
using Services;
using Models.Messaging;
using ViewModels.Auth;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
[Route("api/bill"), Authorize]
public class BillingController : Controller
{
readonly ApplicationDbContext dbContext;
private readonly IStringLocalizer _localizer;
private readonly GoogleAuthSettings _googleSettings;
private readonly IYavscMessageSender _GCMSender;
private readonly IAuthorizationService authorizationService;
private readonly ILogger logger;
private readonly IBillingService billingService;
public BillingController(
IAuthorizationService authorizationService,
ILoggerFactory loggerFactory,
IStringLocalizer<Yavsc.YavscLocalization> SR,
ApplicationDbContext context,
IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender,
IBillingService billingService
)
{
_googleSettings=googleSettings.Value;
this.authorizationService = authorizationService;
dbContext = context;
logger = loggerFactory.CreateLogger<BillingController>();
this._localizer = SR;
_GCMSender=GCMSender;
this.billingService=billingService;
}
[HttpGet("facture-{billingCode}-{id}.pdf"), Authorize]
public async Task<IActionResult> GetPdf(string billingCode, long id)
{
var bill = await billingService.GetBillAsync(billingCode, id);
if ( authorizationService.AuthorizeAsync(User, bill, new ViewRequirement()).IsFaulted)
{
return new ChallengeResult();
}
var fi = bill.GetBillInfo(billingService);
if (!fi.Exists) return Ok(new { Error = "Not generated" });
return File(fi.OpenRead(), "application/x-pdf", fi.Name);
}
[HttpGet("facture-{billingCode}-{id}.tex"), Authorize]
public async Task<IActionResult> GetTex(string billingCode, long id)
{
var bill = await billingService.GetBillAsync(billingCode, id);
if (bill==null) {
logger.LogCritical ( $"# not found !! {id} in {billingCode}");
return this.NotFound();
}
logger.LogTrace(JsonConvert.SerializeObject(bill));
if (!(await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement())).Succeeded)
{
return new ChallengeResult();
}
Response.ContentType = "text/x-tex";
return ViewComponent("Bill",new object[] {  billingCode, bill , OutputFormat.LaTeX, true });
}
[HttpPost("genpdf/{billingCode}/{id}")]
public async Task<IActionResult> GeneratePdf(string billingCode, long id)
{
var bill = await billingService.GetBillAsync(billingCode, id);
if (bill==null) {
logger.LogCritical ( $"# not found !! {id} in {billingCode}");
return this.NotFound();
}
logger.LogWarning("Got bill ack:"+bill.GetIsAcquitted().ToString());
return ViewComponent("Bill",new object[] { billingCode, bill, OutputFormat.Pdf, true } );
}
[HttpPost("prosign/{billingCode}/{id}")]
public async Task<IActionResult> ProSign(string billingCode, long id)
{
var estimate = dbContext.Estimates.
Include(e=>e.Client).Include(e=>e.Client.DeviceDeclaration)
.Include(e=>e.Bill).Include(e=>e.Owner).Include(e=>e.Owner.Performer)
.FirstOrDefault(e=>e.Id == id);
if (estimate == null)
return new BadRequestResult();
if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{
return new ChallengeResult();
}
if (Request.Form.Files.Count!=1)
return new BadRequestResult();
User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"pro");
estimate.ProviderValidationDate = DateTime.Now;
dbContext.SaveChanges(User.GetUserId());
// Notify the client
var locstr = _localizer["EstimationMessageToClient"];
var yaev = new EstimationEvent(estimate,_localizer);
var regids = new [] { estimate.Client.Id };
bool gcmSent = false;
var grep = await _GCMSender.NotifyEstimateAsync(regids,yaev);
gcmSent = grep.success>0;
return Ok (new { ProviderValidationDate = estimate.ProviderValidationDate, GCMSent = gcmSent });
}
[HttpGet("prosign/{billingCode}/{id}")]
public async Task<IActionResult> GetProSign(string billingCode, long id)
{
// For authorization purpose
var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id);
if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{
return new ChallengeResult();
}
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ;
}
[HttpPost("clisign/{billingCode}/{id}")]
public async Task<IActionResult> CliSign(string billingCode, long id)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var estimate = dbContext.Estimates.Include( e=>e.Query
).Include(e=>e.Owner).Include(e=>e.Owner.Performer).Include(e=>e.Client)
.FirstOrDefault( e=> e.Id == id && e.Query.ClientId == uid );
if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{
return new ChallengeResult();
}
if (Request.Form.Files.Count!=1)
return new BadRequestResult();
User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"cli");
estimate.ClientValidationDate = DateTime.Now;
dbContext.SaveChanges(User.GetUserId());
return Ok (new { ClientValidationDate = estimate.ClientValidationDate });
}
[HttpGet("clisign/{billingCode}/{id}")]
public async Task<IActionResult> GetCliSign(string billingCode, long id)
{
// For authorization purpose
var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id);
if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{
return new ChallengeResult();
}
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ;
}
}
}

View file

@ -0,0 +1,196 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Yavsc.Controllers
{
using System;
using Yavsc.Models;
using Yavsc.Models.Workflow;
using Yavsc.Models.Billing;
using Yavsc.Abstract.Identity;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
[Produces("application/json")]
[Route("api/bookquery"), Authorize(Roles = "Performer,Administrator")]
public class BookQueryApiController : Controller
{
private ApplicationDbContext _context;
private ILogger _logger;
public BookQueryApiController(ApplicationDbContext context, ILoggerFactory loggerFactory)
{
_context = context;
_logger = loggerFactory.CreateLogger<BookQueryApiController>();
}
// GET: api/BookQueryApi
/// <summary>
/// Book queries, by creation order
/// </summary>
/// <param name="maxId">returned Ids must be lower than this value</param>
/// <returns>book queries</returns>
[HttpGet]
public IEnumerable<RdvQueryProviderInfo> GetCommands(long maxId=long.MaxValue)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var now = DateTime.Now;
var result = _context.RdvQueries.Include(c => c.Location).
Include(c => c.Client).Where(c => c.PerformerId == uid && c.Id < maxId && c.EventDate > now
&& c.ValidationDate == null).
Select(c => new RdvQueryProviderInfo
{
Client = new ClientProviderInfo {
UserName = c.Client.UserName,
UserId = c.ClientId,
Avatar = c.Client.Avatar },
Location = c.Location,
EventDate = c.EventDate,
Id = c.Id,
Previsional = c.Previsional,
Reason = c.Reason,
ActivityCode = c.ActivityCode,
BillingCode = BillingCodes.Rdv
}).
OrderBy(c=>c.Id).
Take(25);
return result;
}
// GET: api/BookQueryApi/5
[HttpGet("{id}", Name = "GetBookQuery")]
public IActionResult GetBookQuery([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
RdvQuery bookQuery = _context.RdvQueries.Where(c => c.ClientId == uid || c.PerformerId == uid).Single(m => m.Id == id);
if (bookQuery == null)
{
return NotFound();
}
return Ok(bookQuery);
}
// PUT: api/BookQueryApi/5
[HttpPut("{id}")]
public IActionResult PutBookQuery(long id, [FromBody] RdvQuery bookQuery)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != bookQuery.Id)
{
return BadRequest();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (bookQuery.ClientId != uid)
return NotFound();
_context.Entry(bookQuery).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!BookQueryExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/BookQueryApi
[HttpPost]
public IActionResult PostBookQuery([FromBody] RdvQuery bookQuery)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (bookQuery.ClientId != uid)
{
ModelState.AddModelError("ClientId", "You must be the client at creating a book query");
return new BadRequestObjectResult(ModelState);
}
_context.RdvQueries.Add(bookQuery);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (BookQueryExists(bookQuery.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetBookQuery", new { id = bookQuery.Id }, bookQuery);
}
// DELETE: api/BookQueryApi/5
[HttpDelete("{id}")]
public IActionResult DeleteBookQuery(long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
RdvQuery bookQuery = _context.RdvQueries.Single(m => m.Id == id);
if (bookQuery == null)
{
return NotFound();
}
if (bookQuery.ClientId != uid) return NotFound();
_context.RdvQueries.Remove(bookQuery);
_context.SaveChanges(User.GetUserId());
return Ok(bookQuery);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool BookQueryExists(long id)
{
return _context.RdvQueries.Count(e => e.Id == id) > 0;
}
}
}

View file

@ -0,0 +1,217 @@
using System;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Billing;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/estimate"), Authorize]
public class EstimateApiController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger _logger;
public EstimateApiController(ApplicationDbContext context, ILoggerFactory loggerFactory)
{
_context = context;
_logger = loggerFactory.CreateLogger<EstimateApiController>();
}
bool UserIsAdminOrThis(string uid)
{
if (User.IsInRole(Constants.AdminGroupName)) return true;
return uid == User.GetUserId();
}
bool UserIsAdminOrInThese(string oid, string uid)
{
if (User.IsInRole(Constants.AdminGroupName)) return true;
var cuid = User.GetUserId();
return cuid == uid || cuid == oid;
}
// GET: api/Estimate{?ownerId=User.GetUserId()}
[HttpGet]
public IActionResult GetEstimates(string ownerId = null)
{
if (ownerId == null) ownerId = User.GetUserId();
else if (!UserIsAdminOrThis(ownerId)) // throw new Exception("Not authorized") ;
// or just do nothing
return new StatusCodeResult(StatusCodes.Status403Forbidden);
return Ok(_context.Estimates.Include(e => e.Bill).Where(e => e.OwnerId == ownerId));
}
// GET: api/Estimate/5
[HttpGet("{id}", Name = "GetEstimate")]
public IActionResult GetEstimate([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null)
{
return NotFound();
}
if (UserIsAdminOrInThese(estimate.ClientId, estimate.OwnerId))
return Ok(estimate);
return new StatusCodeResult(StatusCodes.Status403Forbidden);
}
// PUT: api/Estimate/5
[HttpPut("{id}"), Produces("application/json")]
public IActionResult PutEstimate(long id, [FromBody] Estimate estimate)
{
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
if (id != estimate.Id)
{
return BadRequest();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
ModelState.AddModelError("OwnerId", "You can only modify your own estimates");
return BadRequest(ModelState);
}
}
var entry = _context.Attach(estimate);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!EstimateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok(new { estimate.Id });
}
// POST: api/Estimate
[HttpPost, Produces("application/json")]
public IActionResult PostEstimate([FromBody] Estimate estimate)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimate.OwnerId == null) estimate.OwnerId = uid;
if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
ModelState.AddModelError("OwnerId", "You can only create your own estimates");
return BadRequest(ModelState);
}
}
if (estimate.CommandId != null)
{
var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId);
if (query == null)
{
return BadRequest(ModelState);
}
query.ValidationDate = DateTime.Now;
_context.SaveChanges(User.GetUserId());
_context.Entry(query).State = EntityState.Detached;
}
if (!ModelState.IsValid)
{
_logger.LogError(JsonConvert.SerializeObject(ModelState));
return Json(ModelState);
}
_context.Estimates.Add(estimate);
/* _context.AttachRange(estimate.Bill);
_context.Attach(estimate);
_context.Entry(estimate).State = EntityState.Added;
foreach (var line in estimate.Bill)
_context.Entry(line).State = EntityState.Added;
// foreach (var l in estimate.Bill) _context.Attach<CommandLine>(l);
*/
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (EstimateExists(estimate.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return Ok(new { estimate.Id, estimate.Bill });
}
// DELETE: api/Estimate/5
[HttpDelete("{id}")]
public IActionResult DeleteEstimate(long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
ModelState.AddModelError("OwnerId", "You can only create your own estimates");
return BadRequest(ModelState);
}
}
_context.Estimates.Remove(estimate);
_context.SaveChanges(User.GetUserId());
return Ok(estimate);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool EstimateExists(long id)
{
return _context.Estimates.Count(e => e.Id == id) > 0;
}
}
}

View file

@ -0,0 +1,157 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Billing;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/EstimateTemplatesApi")]
public class EstimateTemplatesApiController : Controller
{
private ApplicationDbContext _context;
public EstimateTemplatesApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/EstimateTemplatesApi
[HttpGet]
public IEnumerable<EstimateTemplate> GetEstimateTemplate()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
return _context.EstimateTemplates.Where(x=>x.OwnerId==uid);
}
// GET: api/EstimateTemplatesApi/5
[HttpGet("{id}", Name = "GetEstimateTemplate")]
public IActionResult GetEstimateTemplate([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Where(x=>x.OwnerId==uid).Single(m => m.Id == id);
if (estimateTemplate == null)
{
return NotFound();
}
return Ok(estimateTemplate);
}
// PUT: api/EstimateTemplatesApi/5
[HttpPut("{id}")]
public IActionResult PutEstimateTemplate(long id, [FromBody] EstimateTemplate estimateTemplate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != estimateTemplate.Id)
{
return BadRequest();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName))
return new StatusCodeResult(StatusCodes.Status403Forbidden);
_context.Entry(estimateTemplate).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!EstimateTemplateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/EstimateTemplatesApi
[HttpPost]
public IActionResult PostEstimateTemplate([FromBody] EstimateTemplate estimateTemplate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
estimateTemplate.OwnerId=User.GetUserId();
_context.EstimateTemplates.Add(estimateTemplate);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (EstimateTemplateExists(estimateTemplate.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetEstimateTemplate", new { id = estimateTemplate.Id }, estimateTemplate);
}
// DELETE: api/EstimateTemplatesApi/5
[HttpDelete("{id}")]
public IActionResult DeleteEstimateTemplate(long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Single(m => m.Id == id);
if (estimateTemplate == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName))
return new StatusCodeResult(StatusCodes.Status403Forbidden);
_context.EstimateTemplates.Remove(estimateTemplate);
_context.SaveChanges(User.GetUserId());
return Ok(estimateTemplate);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool EstimateTemplateExists(long id)
{
return _context.EstimateTemplates.Count(e => e.Id == id) > 0;
}
}
}

View file

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Services;
using Yavsc.ViewModels.FrontOffice;
namespace Yavsc.ApiControllers
{
[Route("api/front")]
public class FrontOfficeApiController : Controller
{
ApplicationDbContext dbContext;
private IBillingService billing;
public FrontOfficeApiController(ApplicationDbContext context, IBillingService billing)
{
dbContext = context;
this.billing = billing;
}
[HttpGet("profiles/{actCode}")]
IEnumerable<PerformerProfileViewModel> Profiles(string actCode)
{
return dbContext.ListPerformers(billing, actCode);
}
[HttpPost("query/reject")]
public IActionResult RejectQuery(string billingCode, long queryId)
{
if (billingCode == null) return BadRequest("billingCode");
if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest();
billing.Decided = true;
billing.Accepted = false;
dbContext.SaveChanges();
return Ok();
}
[HttpPost("query/reject")]
public IActionResult AcceptQuery(string billingCode, long queryId)
{
if (billingCode == null) return BadRequest("billingCode");
if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest();
billing.Accepted = true;
billing.Decided = true;
dbContext.SaveChanges();
return Ok();
}
}
}

View file

@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Yavsc.Helpers;
using Yavsc.Models;
namespace Yavsc.ApiControllers
{
[Route("api/payment")]
public class PaymentApiController : Controller
{
private readonly ApplicationDbContext dbContext;
private readonly SiteSettings siteSettings;
private readonly ILogger _logger;
public PaymentApiController(
ApplicationDbContext dbContext,
IOptions<SiteSettings> siteSettingsReceiver,
ILoggerFactory loggerFactory)
{
this.dbContext = dbContext;
siteSettings = siteSettingsReceiver.Value;
_logger = loggerFactory.CreateLogger<PaymentApiController>();
}
public async Task<IActionResult> Info(string paymentId, string token)
{
var details = await dbContext.GetCheckoutInfo(token);
_logger.LogInformation(JsonConvert.SerializeObject(details));
return Ok(details);
}
}
}

View file

@ -0,0 +1,65 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
namespace Yavsc.Controllers
{
using Microsoft.EntityFrameworkCore;
using Models;
using Yavsc.Helpers;
using Yavsc.Services;
[Produces("application/json")]
[Route("api/performers")]
public class PerformersApiController : Controller
{
ApplicationDbContext dbContext;
private readonly IBillingService billing;
public PerformersApiController(ApplicationDbContext context, IBillingService billing)
{
dbContext = context;
this.billing = billing;
}
/// <summary>
/// Lists profiles on an activity code
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Authorize(Roles="Performer"),HttpGet("{id}")]
public IActionResult Get(string id)
{
var pfr = dbContext.Performers.Include(
p=>p.OrganizationAddress
).Include(
p=>p.Performer
).Include(
p=>p.Performer.Posts
).SingleOrDefault(p=> p.PerformerId == id);
if (id==null)
{
ModelState.AddModelError("id","Specifier un identifiant de prestataire valide");
}
else {
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole("Administrator"))
if (uid != id) return new ChallengeResult();
if (!pfr.Active)
{
ModelState.AddModelError("id","Prestataire désactivé.");
}
}
if (ModelState.IsValid) return Ok(pfr);
return new BadRequestObjectResult(ModelState);
}
[HttpGet("doing/{id}"),AllowAnonymous]
public IActionResult ListPerformers(string id)
{
return Ok(dbContext.ListPerformers(billing, id));
}
}
}

View file

@ -0,0 +1,146 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Market;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/ProductApi")]
public class ProductApiController : Controller
{
private readonly ApplicationDbContext _context;
public ProductApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/ProductApi
[HttpGet]
public IEnumerable<Product> GetProducts()
{
return _context.Products;
}
// GET: api/ProductApi/5
[HttpGet("{id}", Name = "GetProduct")]
public IActionResult GetProduct([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Product product = _context.Products.Single(m => m.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// PUT: api/ProductApi/5
[HttpPut("{id}"),Authorize(Constants.FrontOfficeGroupName)]
public IActionResult PutProduct(long id, [FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != product.Id)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ProductApi
[HttpPost,Authorize(Constants.FrontOfficeGroupName)]
public IActionResult PostProduct([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Products.Add(product);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (ProductExists(product.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
}
// DELETE: api/ProductApi/5
[HttpDelete("{id}"),Authorize(Constants.FrontOfficeGroupName)]
public IActionResult DeleteProduct(long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Product product = _context.Products.Single(m => m.Id == id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
_context.SaveChanges(User.GetUserId());
return Ok(product);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool ProductExists(long id)
{
return _context.Products.Count(e => e.Id == id) > 0;
}
}
}