déplacé ou commenté

This commit is contained in:
Paul Schneider 2019-01-25 17:28:42 +00:00
commit 9507e7b960
18 changed files with 5 additions and 1 deletions

View file

@ -0,0 +1,190 @@
using System.IO;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using System.Web.Routing;
using System.Linq;
using Microsoft.Data.Entity;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.OptionsModel;
using System;
using System.Security.Claims;
namespace Yavsc.ApiControllers
{
using Models;
using Helpers;
using Services;
using Models.Messaging;
using ViewModels.Auth;
using Newtonsoft.Json;
using Yavsc.ViewModels;
using Yavsc.Abstract.FileSystem;
[Route("api/bill"), Authorize]
public class BillingController : Controller
{
ApplicationDbContext dbContext;
private IStringLocalizer _localizer;
private GoogleAuthSettings _googleSettings;
private IGoogleCloudMessageSender _GCMSender;
private IAuthorizationService authorizationService;
private ILogger logger;
private IBillingService billingService;
public BillingController(
IAuthorizationService authorizationService,
ILoggerFactory loggerFactory,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> SR,
ApplicationDbContext context,
IOptions<GoogleAuthSettings> googleSettings,
IGoogleCloudMessageSender 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 (!await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement()))
{
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.HttpNotFound();
}
logger.LogVerbose(JsonConvert.SerializeObject(bill));
if (!await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement()))
{
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.HttpNotFound();
}
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.Devices)
.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()))
{
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 = estimate.Client.Devices.Select(d => d.GCMRegistrationId).ToArray();
bool gcmSent = false;
if (regids.Length>0) {
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()))
{
return new ChallengeResult();
}
var filename = FileSystemHelpers.SignFileNameFormat("pro",billingCode,id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return HttpNotFound(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.GetUserId();
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()))
{
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()))
{
return new ChallengeResult();
}
var filename = FileSystemHelpers.SignFileNameFormat("pro",billingCode,id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return HttpNotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ;
}
}
}

View file

@ -0,0 +1,195 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
namespace Yavsc.Controllers
{
using System;
using Yavsc.Models;
using Yavsc.Models.Workflow;
using Yavsc.Models.Billing;
using Yavsc.Abstract.Identity;
[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.GetUserId();
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 HttpBadRequest(ModelState);
}
var uid = User.GetUserId();
RdvQuery bookQuery = _context.RdvQueries.Where(c => c.ClientId == uid || c.PerformerId == uid).Single(m => m.Id == id);
if (bookQuery == null)
{
return HttpNotFound();
}
return Ok(bookQuery);
}
// PUT: api/BookQueryApi/5
[HttpPut("{id}")]
public IActionResult PutBookQuery(long id, [FromBody] RdvQuery bookQuery)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
if (id != bookQuery.Id)
{
return HttpBadRequest();
}
var uid = User.GetUserId();
if (bookQuery.ClientId != uid)
return HttpNotFound();
_context.Entry(bookQuery).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!BookQueryExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/BookQueryApi
[HttpPost]
public IActionResult PostBookQuery([FromBody] RdvQuery bookQuery)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
var uid = User.GetUserId();
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 HttpStatusCodeResult(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 HttpBadRequest(ModelState);
}
var uid = User.GetUserId();
RdvQuery bookQuery = _context.RdvQueries.Single(m => m.Id == id);
if (bookQuery == null)
{
return HttpNotFound();
}
if (bookQuery.ClientId != uid) return HttpNotFound();
_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,213 @@
using System;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Yavsc.Models;
using Yavsc.Models.Billing;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/estimate"),Authorize()]
public class EstimateApiController : Controller
{
private ApplicationDbContext _context;
private 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 HttpStatusCodeResult(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 HttpBadRequest(ModelState);
}
Estimate estimate = _context.Estimates.Include(e=>e.Bill).Single(m => m.Id == id);
if (estimate == null)
{
return HttpNotFound();
}
if (UserIsAdminOrInThese(estimate.ClientId,estimate.OwnerId))
return Ok(estimate);
return new HttpStatusCodeResult(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 HttpBadRequest();
}
var uid = User.GetUserId();
if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
ModelState.AddModelError("OwnerId","You can only modify your own estimates");
return HttpBadRequest(ModelState);
}
}
var entry = _context.Attach(estimate);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!EstimateExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return Ok( new { Id = estimate.Id });
}
// POST: api/Estimate
[HttpPost,Produces("application/json")]
public IActionResult PostEstimate([FromBody] Estimate estimate)
{
var uid = User.GetUserId();
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 HttpBadRequest(ModelState);
}
}
if (estimate.CommandId!=null) {
var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId);
if (query == null) {
return HttpBadRequest(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 HttpStatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return Ok( new { Id = estimate.Id, Bill = estimate.Bill });
}
// DELETE: api/Estimate/5
[HttpDelete("{id}")]
public IActionResult DeleteEstimate(long id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
Estimate estimate = _context.Estimates.Include(e=>e.Bill).Single(m => m.Id == id);
if (estimate == null)
{
return HttpNotFound();
}
var uid = User.GetUserId();
if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
ModelState.AddModelError("OwnerId","You can only create your own estimates");
return HttpBadRequest(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,159 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
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.GetUserId();
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 HttpBadRequest(ModelState);
}
var uid = User.GetUserId();
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Where(x=>x.OwnerId==uid).Single(m => m.Id == id);
if (estimateTemplate == null)
{
return HttpNotFound();
}
return Ok(estimateTemplate);
}
// PUT: api/EstimateTemplatesApi/5
[HttpPut("{id}")]
public IActionResult PutEstimateTemplate(long id, [FromBody] EstimateTemplate estimateTemplate)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
if (id != estimateTemplate.Id)
{
return HttpBadRequest();
}
var uid = User.GetUserId();
if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName))
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden);
_context.Entry(estimateTemplate).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!EstimateTemplateExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/EstimateTemplatesApi
[HttpPost]
public IActionResult PostEstimateTemplate([FromBody] EstimateTemplate estimateTemplate)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
estimateTemplate.OwnerId=User.GetUserId();
_context.EstimateTemplates.Add(estimateTemplate);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (EstimateTemplateExists(estimateTemplate.Id))
{
return new HttpStatusCodeResult(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 HttpBadRequest(ModelState);
}
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Single(m => m.Id == id);
if (estimateTemplate == null)
{
return HttpNotFound();
}
var uid = User.GetUserId();
if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName))
return new HttpStatusCodeResult(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,42 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNet.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 HttpBadRequest("billingCode");
if (queryId==0) return HttpBadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing==null) return HttpBadRequest();
billing.Rejected = true;
billing.RejectedAt = DateTime.Now;
dbContext.SaveChanges();
return Ok();
}
}
}

View file

@ -0,0 +1,35 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Newtonsoft.Json;
using Yavsc.Helpers;
using Yavsc.Models;
namespace Yavsc.ApiControllers
{
[Route("api/payment")]
public class PaymentApiController : Controller
{
private ApplicationDbContext dbContext;
private 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);
}
}
}