This commit is contained in:
Paul Schneider 2026-02-14 16:54:27 +00:00
commit 45514010f2
3505 changed files with 154 additions and 523 deletions

View file

@ -1,29 +0,0 @@
using System.Globalization;
using Yavsc.Billing;
using Yavsc.Models.Billing;
using Yavsc.Server.Helpers;
using Yavsc.Services;
namespace Yavsc.Helpers
{
public static class BillingHelpers
{
public static decimal Addition(this List<IBillItem> items) => items.Aggregate<IBillItem, decimal>(0m, (t, l) => t + l.Count * l.UnitaryCost);
public static decimal Addition(this List<CommandLine> items) => items.Select(i=>((IBillItem)i)).ToList().Addition();
public static string GetBillText(this IBillable query) {
string total = query.GetBillItems().Addition().ToString("C", CultureInfo.CurrentUICulture);
string bill = string.Join("\n", query.GetBillItems().Select(l=> $"{l.Name} {l.Description} : {l.UnitaryCost} € " + ((l.Count != 1) ? "*"+l.Count.ToString() : ""))) +
$"\n\nTotal: {total}";
return bill;
}
public static FileInfo GetBillInfo(this IBillable bill, IBillingService service)
{
var suffix = bill.GetIsAcquitted() ? "-ack":null;
var filename = bill.GetFileBaseName(service)+".pdf";
return new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
}
}
}

View file

@ -1,23 +0,0 @@
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace Yavsc.Helpers
{
using Models.societe.com;
using Yavsc.Server;
public static class ComapnyInfoHelpers { 
public static async Task<CompanyInfoMessage> CheckSiren(this HttpClient web,
string siren, CompanyInfoSettings api)
{
using (var request = new HttpRequestMessage(HttpMethod.Get,
string.Format(ServerConstants.CompanyInfoUrl,siren,api.ApiKey))) {
using (var response = await web.SendAsync(request)) {
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
return payload.ToObject<CompanyInfoMessage>();
}
}
}
}
}

View file

@ -1,262 +0,0 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Html;
using Microsoft.Extensions.FileProviders;
using Yavsc.Models;
using Yavsc.Models.FileSystem;
using Yavsc.Models.Streaming;
using Yavsc.ViewModels;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Microsoft.AspNetCore.Http;
using Yavsc.Exceptions;
using Yavsc.Helpers;
using Yavsc.Abstract.Helpers;
namespace Yavsc.Server.Helpers
{
public static class FileSystemHelpers
{
public static async Task SaveAsAsync(this IFormFile formFile, string path)
{
if (formFile.Length > 0) {
using (Stream fileStream = new FileStream(path, FileMode.Create)) {
await formFile.CopyToAsync(fileStream);
}
}
}
public static FileReceivedInfo ReceiveProSignature(this ClaimsPrincipal user, string billingCode, long estimateId, IFormFile formFile, string signType)
{
var item = new FileReceivedInfo(
Config.SiteSetup.Bills,
AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, estimateId));
var fi = new FileInfo(item.FullName);
if (fi.Exists) item.Overridden = true;
using (var org = formFile.OpenReadStream())
{
using Image image = Image.Load(org);
image.Save(fi.FullName);
}
return item;
}
public static string GetAvatarUri(this ApplicationUser user)
{
return $"/{Config.SiteSetup.Avatars}/{user.UserName}.png";
}
public static string EnsureDestinationDirectory(
this ClaimsPrincipal user,
string subpath)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.Identity.Name);
if (!string.IsNullOrWhiteSpace(subpath))
{
if (!subpath.IsValidYavscPath())
{
throw new InvalidPathException();
}
root = Path.Combine(root, subpath);
}
var di = new DirectoryInfo(root);
if (!di.Exists) di.Create();
return di.FullName;
}
/// <summary>
/// Deletes user file.
/// User info is modified, but not save in db.
/// </summary>
/// <param name="user"></param>
/// <param name="fileName"></param>
public static void DeleteUserFile(this ApplicationUser user, string fileName)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var fi = new FileInfo(Path.Combine(root, fileName));
if (!fi.Exists) return ;
fi.Delete();
user.DiskUsage -= fi.Length;
}
public static FsOperationInfo DeleteUserDirOrFile(this ApplicationUser user, string dirName)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
if (string.IsNullOrEmpty(dirName))
return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.InvalidRequest, ErrorMessage = "specify a directory or file name"} ;
var di = new DirectoryInfo(Path.Combine(root, dirName));
if (!di.Exists) {
var fi = new FileInfo(Path.Combine(root, dirName));
if (!fi.Exists) return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.NotFound, ErrorMessage = "non existent"} ;
fi.Delete();
user.DiskUsage -= fi.Length;
}
else {
if (di.GetDirectories().Length>0 || di.GetFiles().Length>0)
return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.InvalidRequest, ErrorMessage = "dir is not empty, refusing to remove it"} ;
di.Delete();
}
return new FsOperationInfo { Done = true };
}
public static FsOperationInfo MoveUserDir(this ApplicationUser user, string fromDirName, string toDirName)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
if (string.IsNullOrEmpty(fromDirName))
return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.InvalidRequest , ErrorMessage = "specify a dir name "} ;
var di = new DirectoryInfo(Path.Combine(root, fromDirName));
if (!di.Exists) return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.NotFound, ErrorMessage = "fromDirName: non existent"} ;
if (string.IsNullOrEmpty(toDirName)) toDirName = ".";
var destPath = Path.Combine(root, toDirName);
var fout = new FileInfo(destPath);
if (fout.Exists) return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.InvalidRequest, ErrorMessage = "destination is a regular file" } ;
var dout = new DirectoryInfo(destPath);
if (dout.Exists) {
destPath = Path.Combine(destPath, dout.Name);
}
di.MoveTo(destPath);
return new FsOperationInfo { Done = true };
}
public static FsOperationInfo MoveUserFileToDir(this ApplicationUser user, string fileNameFrom, string fileNameDest)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var fi = new FileInfo(Path.Combine(root, fileNameFrom));
if (!fi.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.NotFound, ErrorMessage = "no file to move" } ;
string dest;
if (!string.IsNullOrEmpty(fileNameDest)) dest = Path.Combine(root, fileNameDest);
else dest = root;
var fo = new FileInfo(dest);
if (fo.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.DestExists , ErrorMessage = "destination file name is an existing file" } ;
var dout = new DirectoryInfo(dest);
if (!dout.Exists) dout.Create();
fi.MoveTo(Path.Combine(dout.FullName, fi.Name));
return new FsOperationInfo { Done = true };
}
public static FsOperationInfo MoveUserFile(this ApplicationUser user, string fileNameFrom, string fileNameDest)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var fi = new FileInfo(Path.Combine(root, fileNameFrom));
if (!fi.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.NotFound, ErrorMessage = "no file to move" } ;
var fo = new FileInfo(Path.Combine(root, fileNameDest));
if (fo.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.DestExists , ErrorMessage = "destination file name is an existing file" } ;
fi.MoveTo(fo.FullName);
return new FsOperationInfo { Done = true };
}
static string ParseFileNameFromDisposition(string disposition)
{
// form-data_ name=_file__ filename=_Constants.Private.cs_
var parts = disposition.Split(' ');
var filename = parts[2].Split('=')[1];
filename = filename.Substring(1,filename.Length-2);
return filename;
}
public static void AddQuota(this ApplicationUser user, int quota)
{
user.DiskQuota += quota;
}
public static FileReceivedInfo ReceiveUserFile(this ApplicationUser user, string root, IFormFile f, string destFileName = null)
{
return ReceiveUserFile(user, root, f.OpenReadStream(), destFileName ?? ParseFileNameFromDisposition(f.ContentDisposition), f.ContentType, CancellationToken.None);
}
public static FileReceivedInfo ReceiveUserFile(this ApplicationUser user, string root, Stream inputStream, string destFileName, string contentType, CancellationToken token)
{
// TODO lock user's disk usage for this scope,
// this process is not safe at concurrent access.
long usage = user.DiskUsage;
var item = new FileReceivedInfo
(root, AbstractFileSystemHelpers.FilterFileName(destFileName));
var fi = new FileInfo(Path.Combine(root, item.FileName));
if (fi.Exists)
{
item.Overridden = true;
usage -= fi.Length;
}
using (var dest = fi.OpenWrite())
{
using (inputStream)
{
const int blen = 1024;
byte[] buffer = new byte[blen];
int len = 0;
while (!token.IsCancellationRequested && (len=inputStream.Read(buffer, 0, blen))>0)
{
dest.Write(buffer, 0, len);
usage += len;
if (usage >= user.DiskQuota) break;
}
user.DiskUsage = usage;
dest.Close();
inputStream.Close();
}
}
if (usage >= user.DiskQuota) {
item.QuotaOffense = true;
}
user.DiskUsage = usage;
return item;
}
public static HtmlString FileLink(this RemoteFileInfo info, string username, string subpath)
{
return new HtmlString(
$"{Config.UserFilesOptions.RequestPath}/{username}/{subpath}/{info.Name}" );
}
public static RemoteFileInfo FileInfo(this ApplicationUser user, string path)
{
IFileInfo info = Config.UserFilesOptions.FileProvider.GetFileInfo($"{user.UserName}/{path}");
if (!info.Exists) return null;
return new RemoteFileInfo{ Name = info.Name, Size = info.Length, LastModified = info.LastModified.UtcDateTime };
}
public static FileReceivedInfo ReceiveAvatar(this ApplicationUser user, IFormFile formFile)
{
var item = new FileReceivedInfo
(Config.AvatarsOptions.RequestPath.ToUriComponent(),
user.UserName + ".png");
using (var org = formFile.OpenReadStream())
{
using Image image = Image.Load(org);
image.Mutate(x=>x.Resize(128,128));
image.Save(Path.Combine(Config.SiteSetup.Avatars,item.FileName));
image.Mutate(x=>x.Resize(64,64));
image.Save(Path.Combine(Config.SiteSetup.Avatars,user.UserName + ".s.png"));
image.Mutate(x=>x.Resize(32,32));
image.Save(Path.Combine(Config.SiteSetup.Avatars,user.UserName + ".xs.png"));
}
user.Avatar = $"{item.DestDir}/{item.FileName}";
return item;
}
public static string GetFileUrl (this LiveFlow flow)
{
// no server-side backup for this stream
return $"{Config.UserFilesOptions.RequestPath}/{flow.Owner.UserName}/live/"+GetFileName(flow);
}
public static string GetFileName (this LiveFlow flow)
{
var fileInfo = new FileInfo(flow.DifferedFileName);
var ext = fileInfo.Extension;
var namelen = flow.DifferedFileName.Length - ext.Length;
var basename = flow.DifferedFileName.Substring(0,namelen);
return $"{basename}-{flow.SequenceNumber}{ext}";
}
}
}

View file

@ -1,21 +0,0 @@
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Yavsc.Models.Drawing;
namespace Yavsc.Helpers
{
public static class HtmlHelpers
{
public static HtmlString Color(this Color c)
{
if (c == null) return new HtmlString("#000");
return new HtmlString(String.Format("#{0:X2}{1:X2}{2:X2}", c.Red, c.Green, c.Blue));
}
public static string ToAbsolute(this HttpRequest request, string url)
{
var host = request.Host;
var isSecure = request.Headers[Constants.SshHeaderKey] == "on";
return (isSecure ? "https" : "http") + $"://{host}/{url}";
}
}
}

View file

@ -1,175 +0,0 @@
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Yavsc.Models.Billing;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PayPal.PayPalAPIInterfaceService.Model;
using PayPal.PayPalAPIInterfaceService;
using Yavsc.ViewModels.PayPal;
using Yavsc.Models;
using System.Linq;
using Yavsc.Models.Payment;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.Helpers
{
public static class PayPalHelpers
{
private static Dictionary<string,string> payPalProperties = null;
public static Dictionary<string,string> GetPayPalProperties() {
if (payPalProperties==null) {
payPalProperties = new Dictionary<string,string>();
var paypalSettings = Config.PayPalSettings;
// Don't do:
// payPalProperties.Add("mode", Startup.PayPalSettings.Mode);
// Instead, set the endpoint parameter.
if (paypalSettings.Mode == "production") {
// use nvp end point: https://api-3t.paypal.com/nvp
payPalProperties.Add("endpoint", "https://api-3t.paypal.com/nvp");
} else {
payPalProperties.Add("endpoint", "https://api-3t.sandbox.paypal.com/nvp");
}
payPalProperties.Add("clientId", paypalSettings.ClientId);
payPalProperties.Add("clientSecret", paypalSettings.ClientSecret);
int numClient = 0;
if (paypalSettings.Accounts!=null)
foreach (var account in paypalSettings.Accounts) {
numClient++;
payPalProperties.Add ($"account{numClient}.apiUsername",account.ApiUsername);
payPalProperties.Add ($"account{numClient}.apiPassword",account.ApiPassword);
payPalProperties.Add ($"account{numClient}.apiSignature",account.Signature);
}
}
return payPalProperties;
}
private static PayPalAPIInterfaceServiceService payPalService = null;
public static PayPalAPIInterfaceServiceService PayPalService {
get {
if (payPalService==null)
payPalService = new PayPal.PayPalAPIInterfaceService.PayPalAPIInterfaceServiceService(GetPayPalProperties());
return payPalService;
}}
public class PaymentUrls
{
public string ReturnUrl { get; set; }
public string CancelUrl { get; set; }
public string CGVUrl { get; set; }
}
public static PaymentUrls GetPaymentUrls(this HttpRequest request, string controllerName, string id)
{
var result = new PaymentUrls
{
ReturnUrl = request.ToAbsolute($"{controllerName}/PaymentConfirmation/{id}"),
CancelUrl = request.ToAbsolute($"{controllerName}/ClientCancel/{id}"),
CGVUrl = request.ToAbsolute($"{controllerName}/CGV")
};
return result;
}
public static SetExpressCheckoutResponseType CreatePayment(this HttpRequest request, string controllerName, NominativeServiceCommand query, string intent = "sale", ILogger logger = null)
{
var items = query.GetBillItems();
var total = items.Addition().ToString("F2");
var coreq = new SetExpressCheckoutReq {};
var urls = request.GetPaymentUrls(controllerName, query.Id.ToString());
var pitem = new PaymentDetailsItemType {};
coreq.SetExpressCheckoutRequest = new SetExpressCheckoutRequestType{
DetailLevel = new List<DetailLevelCodeType?> { DetailLevelCodeType.RETURNALL },
SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
{
PaymentDetails = new List<PaymentDetailsType>( new [] { new PaymentDetailsType{
OrderDescription = query.Description,
OrderTotal = new BasicAmountType {
currencyID = CurrencyCodeType.EUR,
value = total
},
PaymentDetailsItem = new List <PaymentDetailsItemType> (
items.Select(i => new PaymentDetailsItemType {
Amount = new BasicAmountType { currencyID = CurrencyCodeType.EUR, value = i.UnitaryCost.ToString("F2") },
Name = i.Name,
Quantity = i.Count,
Description = i.Description
})
)
}}),
InvoiceID = query.GetInvoiceId(),
// NOTE don't set OrderDescription : "You cannot pass both the new and deprecated order description.","ErrorCode":"11804
CancelURL = urls.CancelUrl,
ReturnURL = urls.ReturnUrl
}
};
var d = new SetExpressCheckoutRequestDetailsType();
logger.LogInformation($"Creating express checkout for {Config.PayPalSettings.MerchantAccountUserName} : "+JsonConvert.SerializeObject(coreq));
var response = PayPalService.SetExpressCheckout( coreq, Config.PayPalSettings.MerchantAccountUserName );
return response;
}
public static async Task<PaymentInfo> GetCheckoutInfo(
this ApplicationDbContext context,
string token)
{
return await CreatePaymentViewModel(context,token,GetExpressCheckoutDetails(token));
}
private static GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetails(string token)
{
GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq{
GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType {
Token = token
}
};
return PayPalService.GetExpressCheckoutDetails(req,Config.PayPalSettings.Accounts[0].ApiUsername);
}
public static async Task<PaymentInfo> ConfirmPayment(
this ApplicationDbContext context,
string userId,
string payerId,
string token)
{
var details = GetExpressCheckoutDetails(token);
var payment = await context.PayPalPayment.SingleOrDefaultAsync(p=>p.CreationToken == token);
if (payment == null)
{
payment = new PayPalPayment{
ExecutorId = userId,
PaypalPayerId = payerId,
CreationToken = token,
// NOTE: 1 order <=> 1 bill <=> 1 payment
OrderReference = details.GetExpressCheckoutDetailsResponseDetails.InvoiceID,
State = details.Ack.ToString()
};
context.PayPalPayment.Add(payment);
}
else {
payment.ExecutorId = userId;
payment.PaypalPayerId = payerId;
payment.State = details.Ack.ToString();
}
await context.SaveChangesAsync(userId);
// GetCheckoutInfo(,token);
return new PaymentInfo { DbContent = payment, DetailsFromPayPal = details };
}
public static async Task<PaymentInfo> CreatePaymentViewModel (
this ApplicationDbContext context,
string token, GetExpressCheckoutDetailsResponseType fromPayPal)
{
return new PaymentInfo {
DbContent = await context.PayPalPayment
.Include(p=>p.Executor)
.SingleOrDefaultAsync(
p=>p.CreationToken==token),
DetailsFromPayPal = fromPayPal
};
}
}
}

View file

@ -1,139 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Yavsc.Server.Model;
namespace Yavsc.Server.Helpers
{
/// <summary>
/// Thanks to Stefan @ Stackoverflow
/// </summary>
public class RequestHelper
{
string WRPostMultipart(string url, Dictionary<string, object> parameters, string authorizationHeader = null)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
if (authorizationHeader != null)
request.Headers["Authorization"] = authorizationHeader;
if (parameters != null && parameters.Count > 0)
{
using (Stream requestStream = request.GetRequestStream())
{
using (WebResponse response = request.GetResponse())
{
foreach (KeyValuePair<string, object> pair in parameters)
{
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
if (pair.Value is FormFile)
{
FormFile file = pair.Value as FormFile;
string header = "Content-Disposition: form-data; name=\"" + pair.Key + "\"; filename=\"" + file.Name + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(bytes, 0, bytes.Length);
byte[] buffer = new byte[32768];
int bytesRead;
if (file.Stream == null)
{
// upload from file
using (FileStream fileStream = File.OpenRead(file.FilePath))
{
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
fileStream.Close();
}
}
else
{
// upload from given stream
while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
}
}
else
{
string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
requestStream.Write(bytes, 0, bytes.Length);
}
}
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
} // end WebResponse response
} // end using requestStream
}
else throw new ArgumentOutOfRangeException("no parameter found ");
}
public static async Task<string> PostMultipart(string url, FormFile[] formFiles, string access_token = null)
{
if (formFiles != null && formFiles.Length > 0)
{
var client = new HttpClient();
var formData = new MultipartFormDataContent();
if (access_token != null)
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
foreach (var formFile in formFiles)
{
HttpContent fileStreamContent = new StreamContent(formFile.Stream);
if (formFile.ContentType!=null)
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(formFile.ContentType);
else fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// fileStreamContent.Headers.ContentDisposition = formFile.ContentDisposition!=null? new ContentDispositionHeaderValue(
// formFile.ContentDisposition) : new ContentDispositionHeaderValue("form-data; name=\"file\"; filename=\"" + formFile.Name + "\"");
fileStreamContent.Headers.Add("Content-Disposition", formFile.ContentDisposition);
fileStreamContent.Headers.Add("Content-Length", formFile.Stream.Length.ToString());
//fileStreamContent.Headers.Add("FilePath", formFile.FilePath);
formData.Add(fileStreamContent, "file", formFile.Name);
}
var response = client.PostAsync(url, formData).Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return await response.Content.ReadAsStringAsync();
} // end if formFiles != null
return null;
}
}
}

View file

@ -1,6 +0,0 @@
using Microsoft.Extensions.Localization;
public static class ResourcesHelpers {
public static IStringLocalizer GlobalLocalizer = null ;
}

View file

@ -1,82 +0,0 @@
//
// PostJson.cs
//
// Author:
// Paul Schneider <paulschneider@free.fr>
//
// Copyright (c) 2015 Paul Schneider
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Net;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System;
namespace Yavsc.Server.Helpers
{
/// <summary>
/// Simple json post method.
/// </summary>
public class SimpleJsonPostMethod : IDisposable
{
private readonly HttpWebRequest request=null;
/// <summary>
/// Initializes a new instance of the Yavsc.Helpers.SimpleJsonPostMethod class.
/// </summary>
/// <param name="pathToMethod">Path to method.</param>
public SimpleJsonPostMethod (string pathToMethod, string authorizationHeader = null, string method = "POST")
{
request = (HttpWebRequest) WebRequest.Create (pathToMethod);
request.Method = method;
request.Accept = "application/json";
request.ContentType = "application/json";
request.SendChunked = true;
request.TransferEncoding = "UTF-8";
if (authorizationHeader!=null)
request.Headers["Authorization"]=authorizationHeader;
}
public void Dispose()
{
request.Abort();
}
/// <summary>
/// Invoke the specified query.
/// </summary>
/// <param name="query">Query.</param>
public async Task<TAnswer> Invoke<TAnswer>(object query)
{
using (Stream streamQuery = await request.GetRequestStreamAsync()) {
using (StreamWriter writer = new StreamWriter(streamQuery)) {
writer.Write (JsonConvert.SerializeObject(query));
}}
TAnswer ans = default (TAnswer);
using (WebResponse response = await request.GetResponseAsync ()) {
using (Stream responseStream = response.GetResponseStream ()) {
using (StreamReader rdr = new StreamReader (responseStream)) {
ans = (TAnswer) JsonConvert.DeserializeObject<TAnswer> (rdr.ReadToEnd ());
}
}
response.Close();
}
return ans;
}
}
}

View file

@ -1,28 +0,0 @@
using System.Security.Claims;
namespace Yavsc.Server.Helpers
{
public static class UserHelpers
{
public static string GetUserId(this ClaimsPrincipal user)
{
return user.FindFirstValue("sub");
}
public static string GetUserName(this ClaimsPrincipal user)
{
return user.FindFirstValue("name");
}
public static bool IsSignedIn(this ClaimsPrincipal user)
{
return user.Identity.IsAuthenticated;
}
public static bool IsInMsRole(this ClaimsPrincipal user, string roleName)
{
return user.HasClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", roleName);
}
}
}

View file

@ -1,95 +0,0 @@
namespace Yavsc.Helpers
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Workflow;
using Yavsc.Billing;
using Yavsc.Models;
using Yavsc.Models.Billing;
using Yavsc.Models.Haircut;
using Yavsc.Models.Workflow;
using Yavsc.Services;
using Yavsc.ViewModels.FrontOffice;
public static class WorkflowHelpers
{
public static async Task<List<PerformerProfileViewModel>>
ListPerformersAsync(this ApplicationDbContext context,
IBillingService billing,
string actCode)
{
var actors = context.Performers
.Include(p => p.Activity)
.Include(p => p.Performer)
.Where(p => p.Active && p.Activity.Any(u => u.DoesCode == actCode)).OrderBy(x => x.Rate)
.ToArray();
List<PerformerProfileViewModel> result = new();
foreach (var a in actors)
{
var settings = await billing.GetPerformersSettingsAsync(actCode, a.PerformerId);
result.Add(new PerformerProfileViewModel(a, actCode, settings));
}
return result;
}
public static void RegisterBilling<T>(string code, Func<ApplicationDbContext, long,
IDecidableQuery> getter) where T : IBillable
{
if (BillingService.Billing.ContainsKey(code)
|| BillingService.GlobalBillingMap.ContainsKey(code))
{
throw new InvalidOperationException("Billing setup");
}
BillingService.Billing.Add(code, getter);
BillingService.GlobalBillingMap.Add(typeof(T).Name, code);
}
public static void ConfigureBillingService()
{
foreach (var a in System.AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var c in a.GetTypes())
{
if (c.IsClass && !c.IsAbstract &&
c.GetInterface("ISpecializationSettings") != null)
{
Config.ProfileTypes.Add(c);
}
}
}
foreach (var propertyInfo in typeof(ApplicationDbContext).GetProperties())
{
foreach (var attr in propertyInfo.CustomAttributes)
{
// something like a DbSet?
if (typeof(Yavsc.Attributes.ActivitySettingsAttribute).IsAssignableFrom(attr.AttributeType))
{
BillingService.UserSettings.Add(propertyInfo);
}
}
}
RegisterBilling<HairCutQuery>(BillingCodes.Brush, new Func<ApplicationDbContext, long, IDecidableQuery>
((db, id) =>
{
var query = db.HairCutQueries.Include(q => q.Prestation).Include(q => q.Regularisation).Single(q => q.Id == id);
query.SelectedProfile = db.BrusherProfile.Single(b => b.UserId == query.PerformerId);
return query;
}));
RegisterBilling<HairMultiCutQuery>(BillingCodes.MBrush, new Func<ApplicationDbContext, long, IDecidableQuery>
((db, id) => db.HairMultiCutQueries.Include(q => q.Regularisation).Single(q => q.Id == id)));
RegisterBilling<RdvQuery>(BillingCodes.Rdv, new Func<ApplicationDbContext, long, IDecidableQuery>
((db, id) => db.RdvQueries.Include(q => q.Regularisation).Single(q => q.Id == id)));
}
}
}