Allow amateur performer profiles

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-08 02:29:09 +00:00
commit 0728d2a3f7
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
20 changed files with 217 additions and 29 deletions

View file

@ -18,6 +18,7 @@
* [PostIt/Calls] Support direct IPv6 SRTP calls using global, ULA and loopback addresses, shared endpoint validation, IPv6 UDP sockets and bracketed reception URLs. Exclude scoped/link-local, multicast, unspecified and IPv4-mapped addresses; verify real bidirectional IPv6 audio/video, wrong-key rejection and port lifecycle with LibVLC.
* [PostIt/Calls] Allow directly assigned public IPv4 addresses for direct SRTP calls, alongside LAN/VPN and loopback addresses. Share unicast validation between interface discovery, media and server signaling; continue rejecting unspecified, link-local, multicast, reserved and IPv6 addresses. Keep explicit address-disclosure consent and no automatic NAT traversal.
* [PostIt] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection.
* [Performers] Allow performer profiles without a business registration for amateur use; keep activities available while disabling estimate issuance and new invoicing in the UI and server APIs.
## [1.0.8-rc34] - unstable

View file

@ -156,6 +156,21 @@ public class ProviderOngoingRequestsPageViewModelTests
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
[Fact]
public async Task CreateEstimateForSelectedCommand_is_disabled_for_an_amateur_profile()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var estimateClient = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(
client, estimateClient: estimateClient, canIssueEstimates: false);
await vm.InitializeAsync();
vm.SelectedQuery = vm.Queries[0];
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
private sealed class StubProviderApi : IYavscApiClient
{
public HttpClient Http { get; } = new();

View file

@ -27,6 +27,7 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
private readonly EstimateApiClient? _estimateClient;
private readonly Settings? _settings;
private List<BillingQuerySummaryDto> _allQueries = new();
public bool CanIssueEstimates { get; }
[ObservableProperty]
public partial ObservableCollection<BillingQuerySummaryDto> Queries { get; set; } = new();
@ -75,11 +76,13 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
public ProviderOngoingRequestsPageViewModel(
BillingApiClient billingClient,
Settings? settings = null,
EstimateApiClient? estimateClient = null)
EstimateApiClient? estimateClient = null,
bool canIssueEstimates = true)
{
_billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient));
_estimateClient = estimateClient;
_settings = settings;
CanIssueEstimates = canIssueEstimates;
if (_settings is not null)
{
@ -225,7 +228,8 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
}
}
private bool CanCreateEstimateForSelected() => SelectedQuery is not null && _estimateClient is not null;
private bool CanCreateEstimateForSelected()
=> SelectedQuery is not null && _estimateClient is not null && CanIssueEstimates;
[RelayCommand(CanExecute = nameof(CanCreateEstimateForSelected))]
public async Task CreateEstimateForSelectedAsync()
@ -242,6 +246,12 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
return;
}
if (!CanIssueEstimates)
{
this.SetWarningStatus("Un identifiant d'entreprise est nécessaire pour émettre un devis.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Threading;
@ -9,6 +10,7 @@ using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Services;
using PostIt.ViewModels.Chat;
using Yavsc.Abstract.Workflow;
using Yavsc.Abstract.Models.Messaging;
using Yavsc.Api.Client;
@ -218,7 +220,11 @@ public class HomePageViewModel : ViewModelBase
var estimateClient = app.ServiceProvider?.GetRequiredService<EstimateApiClient>();
var vm = new ProviderOngoingRequestsPageViewModel(billingClient, Settings, estimateClient);
var profileEndpoint = new Uri(new Uri(Api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "account/performer-profile").ToString();
var profile = await Api.CallAsync<PerformerProfileSettings>(HttpMethod.Get, profileEndpoint).ConfigureAwait(true);
var vm = new ProviderOngoingRequestsPageViewModel(
billingClient, Settings, estimateClient,
canIssueEstimates: profile?.CanIssueEstimates == true);
await vm.InitializeAsync();
await app.PushPageAsync(vm);
}

View file

@ -44,9 +44,11 @@ public partial class PerformerConfigurationPageViewModel : ViewModelBase
[ObservableProperty]
public partial string ExerciseCountryCode { get; set; } = "fr";
[ObservableProperty]
[ObservableProperty, NotifyPropertyChangedFor(nameof(IsAmateur))]
public partial string SIREN { get; set; } = string.Empty;
public bool IsAmateur => string.IsNullOrWhiteSpace(SIREN);
[ObservableProperty]
public partial string Website { get; set; } = string.Empty;

View file

@ -28,11 +28,14 @@
Opacity="0.7" />
</Grid>
<TextBlock Grid.Row="2"
Text="Astuce: sélectionnez une ligne puis ouvrez le détail ou l'édition directe."
Opacity="0.65"
FontSize="11"
Margin="0,0,0,8" />
<StackPanel Grid.Row="2" Spacing="3" Margin="0,0,0,8">
<TextBlock Text="Astuce: sélectionnez une ligne puis ouvrez le détail ou l'édition directe."
Opacity="0.65"
FontSize="11" />
<TextBlock Text="Profil amateur : l’émission de devis et la facturation sont désactivées tant qu’un identifiant d’entreprise n’est pas renseigné."
IsVisible="{Binding !CanIssueEstimates}"
TextWrapping="Wrap" />
</StackPanel>
<Grid Grid.Row="3" RowDefinitions="*,Auto">
<ListBox Grid.Row="0"

View file

@ -23,7 +23,10 @@
<TextBox Text="{Binding ExerciseCountryCode, Mode=TwoWay}"
PlaceholderText="Code pays (fr, en...)"/>
<TextBox Text="{Binding SIREN, Mode=TwoWay}"
PlaceholderText="SIREN"/>
PlaceholderText="SIREN / SIRET (facultatif)"/>
<TextBlock Text="Sans identifiant d’entreprise, votre profil reste utilisable comme amateur. L’émission de devis et la facturation sont alors désactivées."
IsVisible="{Binding IsAmateur}"
TextWrapping="Wrap"/>
<TextBox Text="{Binding Website, Mode=TwoWay}"
PlaceholderText="Site web"/>

View file

@ -1,15 +1,18 @@
#nullable enable
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using Yavsc.Models.Workflow;
namespace Yavsc.Abstract.Workflow;
public sealed class PerformerProfileSettings
public sealed class PerformerProfileSettings : IValidatableObject
{
public string PerformerId { get; set; } = string.Empty;
public string UserName { get; set; } = string.Empty;
public string ExerciseCountryCode { get; set; } = "fr";
public string SIREN { get; set; } = string.Empty;
public bool CanIssueEstimates => !string.IsNullOrWhiteSpace(SIREN);
public string WebSite { get; set; } = string.Empty;
/// <summary>Owner-only PayPal recipient. Null preserves the existing setting; empty disables donations.</summary>
[MaxLength(127)]
@ -19,4 +22,24 @@ public sealed class PerformerProfileSettings
public bool AcceptPublicContact { get; set; }
public bool UseGeoLocalizationToReduceDistanceWithClients { get; set; }
public List<string> SelectedActivityCodes { get; set; } = new();
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var countryCode = PerformerCodeInputValidationCatalog.NormalizeCountryCode(
string.IsNullOrWhiteSpace(ExerciseCountryCode) ? "fr" : ExerciseCountryCode);
var rule = PerformerCodeInputValidationCatalog.GetRule(countryCode);
if (rule is null)
{
yield return new ValidationResult(
"Le pays d'exercice doit etre l'un des suivants: fr, en, pt.",
new[] { nameof(ExerciseCountryCode) });
yield break;
}
if (!string.IsNullOrWhiteSpace(SIREN)
&& !Regex.IsMatch(SIREN.Trim(), rule.RegularExpression, RegexOptions.CultureInvariant))
{
yield return new ValidationResult(rule.ErrorMessage, new[] { nameof(SIREN) });
}
}
}

View file

@ -66,7 +66,7 @@ namespace Yavsc.Controllers
// PUT: api/Estimate/5
[HttpPut("{id}"), Produces("application/json")]
public IActionResult PutEstimate(long id, [FromBody] Estimate estimate)
public async Task<IActionResult> PutEstimate(long id, [FromBody] Estimate estimate)
{
if (!ModelState.IsValid)
@ -88,6 +88,11 @@ namespace Yavsc.Controllers
}
}
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
{
return Conflict(new { Error = "A business registration is required to issue or edit estimates." });
}
var entry = _context.Attach(estimate);
try
{
@ -110,7 +115,7 @@ namespace Yavsc.Controllers
// POST: api/Estimate
[HttpPost, Produces("application/json")]
public IActionResult PostEstimate([FromBody] Estimate estimate)
public async Task<IActionResult> PostEstimate([FromBody] Estimate estimate)
{
var uid = User.GetUserId();
if (estimate.OwnerId == null) estimate.OwnerId = uid;
@ -124,6 +129,11 @@ namespace Yavsc.Controllers
}
}
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
{
return Conflict(new { Error = "A business registration is required to issue estimates." });
}
if (estimate.CommandId != null)
{
var query = _context.NominativeServiceCommands
@ -334,5 +344,19 @@ namespace Yavsc.Controllers
{
return _context.Estimates.Count(e => e.Id == id) > 0;
}
private Task<bool> CanIssueEstimatesAsync(string? performerId)
{
if (string.IsNullOrWhiteSpace(performerId))
{
return Task.FromResult(false);
}
return _context.Performers
.AsNoTracking()
.AnyAsync(profile => profile.PerformerId == performerId
&& profile.SIREN != null
&& profile.SIREN.Trim() != "");
}
}
}

View file

@ -616,6 +616,12 @@ namespace Yavsc.WebApi.Controllers
return BadRequest(new { error = "Payload is required." });
}
model.SIREN = model.SIREN?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(model.ExerciseCountryCode))
{
model.ExerciseCountryCode = "fr";
}
var uid = User.GetUserId();
if (string.IsNullOrWhiteSpace(uid))
{
@ -652,11 +658,6 @@ namespace Yavsc.WebApi.Controllers
return NotFound();
}
if (string.IsNullOrWhiteSpace(model.ExerciseCountryCode))
{
model.ExerciseCountryCode = "fr";
}
var profile = await _dbContext.Performers.FirstOrDefaultAsync(p => p.PerformerId == uid);
if (profile is null)
{

View file

@ -608,6 +608,7 @@ namespace Yavsc.Controllers
var uid = user.Id;
var postedCountryCode = model.ExerciseCountryCode;
model.ExerciseCountryCode = NormalizeCountryCodeOrDefault(model.ExerciseCountryCode);
model.SIREN = model.SIREN?.Trim() ?? string.Empty;
// Model binding validated the raw posted payload before entering
// the action. If country was empty, we fallback to "fr" above,
@ -622,7 +623,7 @@ namespace Yavsc.Controllers
if (ModelState.IsValid)
{
var isFrenchPerformerCode = string.Equals(model.ExerciseCountryCode, "fr", StringComparison.Ordinal);
if (isFrenchPerformerCode)
if (isFrenchPerformerCode && !string.IsNullOrWhiteSpace(model.SIREN))
{
var exSiren = await _dbContext.ExceptionsSIREN.FirstOrDefaultAsync(
ex => ex.SIREN == model.SIREN

View file

@ -29,9 +29,10 @@ namespace Yavsc.Controllers
// GET: Estimate
public IActionResult Index()
public async Task<IActionResult> Index()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.CanIssueEstimates = await CanIssueEstimatesAsync(uid);
return View(_context.Estimates.Include(e=>e.Query)
.Include(e=>e.Query.PerformerProfile)
.Include(e=>e.Query.PerformerProfile.Performer)
@ -73,9 +74,14 @@ namespace Yavsc.Controllers
// GET: Estimate/Create
[Authorize]
public IActionResult Create()
public async Task<IActionResult> Create()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!await CanIssueEstimatesAsync(uid))
{
return RedirectToAction("SetActivity", "Manage");
}
IQueryable<RdvQuery> queries = _context.RdvQueries.Include(q=>q.Location).Where(bq=>bq.PerformerId == uid);
//.Select(bq=>new SelectListItem{ Text = bq.Client.UserName, Value = bq.Client.Id });
ViewBag.Clients = queries.Select(q=>q.Client).Distinct();
@ -93,6 +99,11 @@ namespace Yavsc.Controllers
)
{
estimate.OwnerId = User.GetUserId();
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
{
return RedirectToAction("SetActivity", "Manage");
}
if (ModelState.IsValid)
{
_context.Estimates
@ -138,7 +149,7 @@ namespace Yavsc.Controllers
// GET: Estimate/Edit/5
public IActionResult Edit(long? id)
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
@ -152,6 +163,10 @@ namespace Yavsc.Controllers
{
return NotFound();
}
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
{
return RedirectToAction("SetActivity", "Manage");
}
return View(estimate);
}
@ -159,11 +174,15 @@ namespace Yavsc.Controllers
// POST: Estimate/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Estimate estimate)
public async Task<IActionResult> Edit(Estimate estimate)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimate.OwnerId!=uid&&estimate.ClientId!=uid
) return NotFound();
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
{
return RedirectToAction("SetActivity", "Manage");
}
if (ModelState.IsValid)
{
_context.Update(estimate);
@ -203,5 +222,19 @@ namespace Yavsc.Controllers
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
private Task<bool> CanIssueEstimatesAsync(string? performerId)
{
if (string.IsNullOrWhiteSpace(performerId))
{
return Task.FromResult(false);
}
return _context.Performers
.AsNoTracking()
.AnyAsync(profile => profile.PerformerId == performerId
&& profile.SIREN != null
&& profile.SIREN.Trim() != "");
}
}
}

View file

@ -7,7 +7,14 @@
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
@if ((bool?)ViewBag.CanIssueEstimates == true)
{
<a asp-action="Create">Create New</a>
}
else
{
<span>Un identifiant d'entreprise est nécessaire pour émettre ou modifier des devis.</span>
}
</p>
<table class="table">
<tr>

View file

@ -84,10 +84,10 @@
</div>
<div class="form-group">
<label asp-for="SIREN" class="col-md-2 control-label">SIREN</label>
<label asp-for="SIREN" class="col-md-2 control-label">Identifiant d'entreprise (SIREN/SIRET, facultatif)</label>
<div class="col-md-10">
<input asp-for="SIREN" class="form-control" />
<small class="form-text text-muted">Sans identifiant, votre profil reste utilisable comme amateur, mais l'émission de devis et la facturation sont désactivées.</small>
<span asp-validation-for="SIREN" class="text-danger"></span>
</div>
</div>

View file

@ -28,7 +28,7 @@ namespace Yavsc.Models.Workflow
[RegularExpression("^[A-Za-z]{2}$", ErrorMessage = "Country code must be a 2-letter code.")]
public string ExerciseCountryCode { get; set; } = "fr";
[Required,YaStringLength(14),Display(Name="SIREN")]
[YaStringLength(14),Display(Name="Identifiant d'entreprise (SIREN/SIRET)")]
public string SIREN { get; set; }
public long OrganizationAddressId { get; set; }

View file

@ -38,6 +38,10 @@ public sealed class InvoicingService(ApplicationDbContext db, IPayPalTransaction
RequirePerformer(actorId, command.InvoicePerformerId!, administrator);
return await ResponseAsync(command, ct);
}
var performerProfile = await db.Performers.AsNoTracking()
.SingleOrDefaultAsync(profile => profile.PerformerId == estimate.OwnerId, ct);
if (string.IsNullOrWhiteSpace(performerProfile?.SIREN))
throw new InvoiceOperationException(409, "A business registration is required to issue invoices.");
if (command.InvoiceEstimateId.HasValue || command.AmountDue.HasValue || command.AmountPaid != 0m)
throw new InvoiceOperationException(409, "This command already has an invoice or a balance requiring reconciliation.");
if (command.ClientId != estimate.ClientId || command.PerformerId != estimate.OwnerId)

View file

@ -152,6 +152,30 @@ public sealed class EstimateApiControllerTests : IClassFixture<ApiWebServerFixtu
Assert.Equal("alice", estimate.OwnerId);
}
[Fact]
public async Task PostEstimate_is_rejected_for_a_performer_without_a_business_registration()
{
var commandId = SeedPendingCommand();
using (var scope = _fixture.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Performers.Single(profile => profile.PerformerId == "alice").SIREN = "";
db.SaveChanges();
}
using var http = NewClient("alice");
var response = await http.PostAsJsonAsync(
"/api/v1/estimate",
NewEstimatePayload(commandId, clientId: "bob"),
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
using var checkScope = _fixture.Services.CreateScope();
var checkDb = checkScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
Assert.Empty(checkDb.Estimates);
Assert.Null(checkDb.RdvQueries.Single(query => query.Id == commandId).ValidationDate);
}
[Fact]
public async Task PostEstimate_for_another_owner_is_rejected()
{

View file

@ -131,6 +131,26 @@ public sealed class InvoiceApiTests(ApiWebServerFixture fixture) : IClassFixture
Assert.Null(db.RdvQueries.Single(q => q.Id == commandId).AmountDue);
}
[Fact]
public async Task Amateur_performer_cannot_generate_an_invoice()
{
var (estimateId, commandId) = Seed();
using (var scope = fixture.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Performers.Single(profile => profile.PerformerId == "alice").SIREN = "";
db.SaveChanges();
}
using var http = Client();
var response = await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
using var checkScope = fixture.Services.CreateScope();
var checkDb = checkScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
Assert.Null(checkDb.RdvQueries.Single(query => query.Id == commandId).AmountDue);
}
[Theory]
[InlineData("wrong-signer")]
[InlineData("missing-date")]

View file

@ -55,11 +55,13 @@ public sealed class PerformerDonationSettingsTests(ApiWebServerFixture fixture)
var profile = await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct);
Assert.NotNull(profile);
Assert.Equal("", profile.DonationPayPalEmail);
Assert.False(profile.CanIssueEstimates);
profile.DonationPayPalEmail = "new@payments.example";
using var response = await client.PutAsJsonAsync(Endpoint, profile, Ct);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("new@payments.example",
(await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct))?.DonationPayPalEmail);
var saved = await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct);
Assert.Equal("new@payments.example", saved?.DonationPayPalEmail);
Assert.False(saved?.CanIssueEstimates);
}
[Theory]

View file

@ -51,6 +51,15 @@ public class PerformerCodeInputValidationTests
Assert.Empty(Validate(pt));
}
[Fact]
public void Validate_accepts_an_empty_business_code_for_amateur_performers()
{
var profile = CreateBaseProfile();
profile.SIREN = "";
Assert.Empty(Validate(profile));
}
private static PerformerProfile CreateBaseProfile()
{
return new PerformerProfile