yavsc/Yavsc/Controllers/Haircut/HairCutCommandController.cs

376 lines
16 KiB
C#

8 years ago
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
namespace Yavsc.Controllers
{
8 years ago
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Google.Messaging;
using Yavsc.Models.Relationship;
using Yavsc.Services;
using Newtonsoft.Json;
using Microsoft.AspNet.Http;
using Yavsc.Extensions;
using Yavsc.Models.Haircut;
using System.Globalization;
using Microsoft.AspNet.Mvc.Rendering;
using System.Collections.Generic;
using PayPal.Api;
8 years ago
8 years ago
public class HairCutCommandController : CommandController
{
public HairCutCommandController(ApplicationDbContext context,
IOptions<PayPalSettings> payPalSettings,
8 years ago
IOptions<GoogleAuthSettings> googleSettings,
IGoogleCloudMessageSender GCMSender,
UserManager<ApplicationUser> userManager,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
IEmailSender emailSender,
IOptions<SmtpSettings> smtpSettings,
IOptions<SiteSettings> siteSettings,
ILoggerFactory loggerFactory) : base(context,googleSettings,GCMSender,userManager,
localizer,emailSender,smtpSettings,siteSettings,loggerFactory)
{
this.payPalSettings = payPalSettings.Value;
8 years ago
}
PayPalSettings payPalSettings;
8 years ago
private async Task<HairCutQuery> GetQuery(long id)
{
return await _context.HairCutQueries
.Include(x => x.Location)
.Include(x => x.PerformerProfile)
.Include(x => x.Prestation)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.Regularisation)
8 years ago
.SingleAsync(m => m.Id == id);
}
public async Task<IActionResult> ClientCancel(long id)
{
HairCutQuery command = await GetQuery(id);
if (command == null)
{
return HttpNotFound();
}
return View (command);
}
public async Task<IActionResult> ClientCancelConfirm(long id)
{
var query = await GetQuery(id);if (query == null)
{
return HttpNotFound();
}
var uid = User.GetUserId();
if (query.ClientId!=uid)
return new ChallengeResult();
_context.HairCutQueries.Remove(query);
await _context.SaveChangesAsync();
return await Index();
}
/// <summary>
/// List client's queries
/// </summary>
/// <returns></returns>
8 years ago
public override async Task<IActionResult> Index()
{
var uid = User.GetUserId();
return View("Index", await _context.HairCutQueries
.Include(x => x.Client)
.Include(x => x.PerformerProfile)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.Location)
.Where(x=> x.ClientId == uid || x.PerformerId == uid)
.ToListAsync());
}
public async Task<IActionResult> Details(long id, string paymentId, string token, string PayerID)
8 years ago
{
HairCutQuery command = await _context.HairCutQueries
.Include(x => x.Location)
.Include(x => x.PerformerProfile)
.Include(x => x.Prestation)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.Regularisation)
.SingleAsync(m => m.Id == id);
if (command == null)
8 years ago
{
return HttpNotFound();
}
ViewBag.CreatePaymentUrl = Request.ToAbsolute("api/haircut/createpayment/"+id);
ViewBag.ExecutePaymentUrl = Request.ToAbsolute("api/payment/execute");
ViewBag.Urls=Request.GetPaymentUrls("HairCutCommand",id.ToString());
return View(command);
}
public async Task<IActionResult> Execute(long id, string paymentId, string token, string PayerID)
{
8 years ago
HairCutQuery command = await _context.HairCutQueries
.Include(x => x.Location)
.Include(x => x.PerformerProfile)
.Include(x => x.Prestation)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.Regularisation)
8 years ago
.SingleAsync(m => m.Id == id);
8 years ago
if (command == null)
{
return HttpNotFound();
}
var context = payPalSettings.CreateAPIContext();
var payment = Payment.Get(context,paymentId);
var execution = new PaymentExecution{ transactions = payment.transactions,
payer_id = PayerID };
var result = payment.Execute(context,execution);
8 years ago
return View(command);
}
7 years ago
/// <summary>
/// Crée une requête en coiffure à domicile
///
/// </summary>
/// <param name="model"></param>
/// <param name="taintIds"></param>
/// <returns></returns>
8 years ago
[HttpPost, Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateHairCutQuery(HairCutQuery model, string taintIds)
8 years ago
{
7 years ago
// TODO utiliser Markdown-av+tags
8 years ago
var uid = User.GetUserId();
var prid = model.PerformerId;
long[] longtaintIds = null;
List<HairTaint> colors = null;
if (taintIds!=null) {
longtaintIds = taintIds.Split(',').Select(s=>long.Parse(s)).ToArray();
colors = _context.HairTaint.Where(t=> longtaintIds.Contains(t.Id)).ToList();
// a Prestation is required
model.Prestation.Taints = colors.Select(c =>
new HairTaintInstance { Taint = c }).ToList();
8 years ago
}
8 years ago
if (string.IsNullOrWhiteSpace(uid)
|| string.IsNullOrWhiteSpace(prid))
throw new InvalidOperationException(
"This method needs a PerformerId"
);
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.Devices)
.FirstOrDefault(
x => x.PerformerId == model.PerformerId
8 years ago
);
model.PerformerProfile = pro;
8 years ago
// FIXME Why!!
// ModelState.ClearValidationState("PerformerProfile.Avatar");
// ModelState.ClearValidationState("Client.Avatar");
// ModelState.ClearValidationState("ClientId");
8 years ago
if (ModelState.IsValid)
{
if (model.Location!=null) {
var existingLocation = await _context.Locations.FirstOrDefaultAsync( x=>x.Address == model.Location.Address
&& x.Longitude == model.Location.Longitude && x.Latitude == model.Location.Latitude );
8 years ago
if (existingLocation!=null) {
model.Location=existingLocation;
}
else _context.Attach<Location>(model.Location);
}
var existingPrestation = await _context.HairPrestation.FirstOrDefaultAsync( x=> model.PrestationId == x.Id );
8 years ago
if (existingPrestation!=null) {
model.Prestation = existingPrestation;
}
else _context.Attach<HairPrestation>(model.Prestation);
8 years ago
_context.HairCutQueries.Add(model);
8 years ago
await _context.SaveChangesAsync(uid);
var brusherProfile = await _context.BrusherProfile.SingleAsync(p=>p.UserId == pro.PerformerId);
8 years ago
model.Client = await _context.Users.SingleAsync(u=>u.Id == model.ClientId);
7 years ago
model.SelectedProfile = brusherProfile;
8 years ago
var yaev = model.CreateEvent(_localizer, brusherProfile);
8 years ago
MessageWithPayloadResponse grep = null;
8 years ago
if (pro.AcceptPublicContact)
8 years ago
{
8 years ago
if (pro.AcceptNotifications) {
if (pro.Performer.Devices.Count > 0) {
var regids = model.PerformerProfile.Performer
8 years ago
.Devices.Select(d => d.GCMRegistrationId);
grep = await _GCMSender.NotifyHairCutQueryAsync(_googleSettings,regids,yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
// if (grep==null || grep.success<=0 || grep.failure>0)
ViewBag.GooglePayload=grep;
if (grep!=null)
_logger.LogWarning($"Performer: {model.PerformerProfile.Performer.UserName} success: {grep.success} failure: {grep.failure}");
8 years ago
}
await _emailSender.SendEmailAsync(
_siteSettings, _smtpSettings,
model.PerformerProfile.Performer.Email,
8 years ago
yaev.Topic+" "+yaev.Sender,
$"{yaev.Message}\r\n-- \r\n{yaev.Previsional}\r\n{yaev.EventDate}\r\n"
);
}
8 years ago
else {
// TODO if (AcceptProContact) try & find a bookmaker to send him this query
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a=>a.Code == model.ActivityCode);
8 years ago
ViewBag.GoogleSettings = _googleSettings;
var items = model.GetBillItems();
var addition = items.Addition();
7 years ago
ViewBag.Addition = addition.ToString("C",CultureInfo.CurrentUICulture);
ViewBag.CreatePaymentUrl = Request.ToAbsolute("api/haircut/createpayment/"+model.Id);
ViewBag.ExecutePaymentUrl = Request.ToAbsolute("api/payment/execute");
ViewBag.Urls=Request.GetPaymentUrls("HairCutCommand",model.Id.ToString());
return View("CommandConfirmation",model);
8 years ago
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a=>a.Code == model.ActivityCode);
8 years ago
ViewBag.GoogleSettings = _googleSettings;
SetViewData(model.ActivityCode,model.PerformerId,model.Prestation);
return View("HairCut",model);
8 years ago
}
public async Task<ActionResult> HairCut(string performerId, string activityCode)
8 years ago
{
HairPrestation pPrestation=null;
var prestaJson = HttpContext.Session.GetString("HairCutPresta") ;
if (prestaJson!=null) {
pPrestation = JsonConvert.DeserializeObject<HairPrestation>(prestaJson);
}
else {
pPrestation = new HairPrestation {};
}
var uid = User.GetUserId();
var user = await _userManager.FindByIdAsync(uid);
SetViewData(activityCode,performerId,pPrestation);
var perfer = _context.Performers.Include(
p=>p.Performer
).Single(p=>p.PerformerId == performerId);
var result = new HairCutQuery {
PerformerProfile = perfer,
PerformerId = perfer.PerformerId,
ClientId = uid,
Prestation = pPrestation,
Client = user
};
return View(result);
}
private void SetViewData (string activityCode, string performerId, HairPrestation pPrestation )
{
8 years ago
ViewBag.HairTaints = _context.HairTaint.Include(t=>t.Color);
ViewBag.HairTaintsItems = _context.HairTaint.Include(t=>t.Color).Select(
c=>
new SelectListItem {
Text = c.Color.Name+" "+c.Brand,
Value = c.Id.ToString()
}
);
8 years ago
ViewBag.HairTechnos = EnumExtensions.GetSelectList(typeof(HairTechnos),_localizer);
ViewBag.HairLength = EnumExtensions.GetSelectList(typeof(HairLength),_localizer);
ViewBag.Activity = _context.Activities.First(a => a.Code == activityCode);
7 years ago
ViewBag.Gender = EnumExtensions.GetSelectList(typeof(HairCutGenders),_localizer,HairCutGenders.Women);
8 years ago
ViewBag.HairDressings = EnumExtensions.GetSelectList(typeof(HairDressings),_localizer);
ViewBag.ColorsClass = ( pPrestation.Tech == HairTechnos.Color
|| pPrestation.Tech == HairTechnos.Mech ) ? "":"hidden";
ViewBag.TechClass = ( pPrestation.Gender == HairCutGenders.Women ) ? "":"hidden";
ViewData["PerfPrefs"] = _context.BrusherProfile.Single(p=>p.UserId == performerId);
8 years ago
}
8 years ago
[HttpPost, Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateHairMultiCutQuery(HairMultiCutQuery command)
{
8 years ago
var uid = User.GetUserId();
var prid = command.PerformerId;
if (string.IsNullOrWhiteSpace(uid)
|| string.IsNullOrWhiteSpace(prid))
throw new InvalidOperationException(
"This method needs a PerformerId"
);
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.Devices)
.FirstOrDefault(
x => x.PerformerId == command.PerformerId
);
var user = await _userManager.FindByIdAsync(uid);
command.Client = user;
command.ClientId = uid;
command.PerformerProfile = pro;
// FIXME Why!!
// ModelState.ClearValidationState("PerformerProfile.Avatar");
// ModelState.ClearValidationState("Client.Avatar");
// ModelState.ClearValidationState("ClientId");
ModelState.MarkFieldSkipped("ClientId");
8 years ago
if (ModelState.IsValid)
{
var existingLocation = _context.Locations.FirstOrDefault( x=>x.Address == command.Location.Address
8 years ago
&& x.Longitude == command.Location.Longitude && x.Latitude == command.Location.Latitude );
if (existingLocation!=null) {
command.Location=existingLocation;
}
else _context.Attach<Location>(command.Location);
_context.HairMultiCutQueries.Add(command, GraphBehavior.IncludeDependents);
_context.SaveChanges(User.GetUserId());
8 years ago
var brSettings = await _context.BrusherProfile.SingleAsync(
bp=>bp.UserId == command.PerformerId
);
var yaev = command.CreateEvent(_localizer,brSettings);
8 years ago
MessageWithPayloadResponse grep = null;
if (pro.AcceptNotifications
&& pro.AcceptPublicContact)
{
if (pro.Performer.Devices.Count > 0) {
var regids = command.PerformerProfile.Performer
.Devices.Select(d => d.GCMRegistrationId);
grep = await _GCMSender.NotifyHairCutQueryAsync(_googleSettings,regids,yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
// if (grep==null || grep.success<=0 || grep.failure>0)
ViewBag.GooglePayload=grep;
if (grep!=null)
_logger.LogWarning($"Performer: {command.PerformerProfile.Performer.UserName} success: {grep.success} failure: {grep.failure}");
await _emailSender.SendEmailAsync(
_siteSettings, _smtpSettings,
command.PerformerProfile.Performer.Email,
yaev.Topic+" "+yaev.Sender,
$"{yaev.Message}\r\n-- \r\n{yaev.Previsional}\r\n{yaev.EventDate}\r\n"
);
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a=>a.Code == command.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
return View("CommandConfirmation",command);
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a=>a.Code == command.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
return View("HairCut",command);
8 years ago
}
}
}