feat: custom roles with per-permission matrix for café owners
- Owner can define named custom roles (e.g. Barista, Supervisor) with
color, description, and a fine-grained permission set (21 permissions
across 7 categories: admin, menu, staff, customer, reports, ops, kitchen)
- Employee assigned a custom role gets its permissions embedded in the
JWT at login (customPerms claim) and parsed by TenantMiddleware —
overrides the static EmployeeRole matrix for all API permission checks
- New endpoints: GET/POST/PATCH/DELETE /api/cafes/{id}/custom-roles and
PUT /api/cafes/{id}/employees/{id}/custom-role for assignment
- Dashboard Settings → Team & Staff → Custom Roles panel with grouped
checkbox matrix, group-level toggles, color preset picker, CRUD forms,
and employee-count display; translations in fa/en/ar
- EF migration adds CustomRoles table + nullable CustomRoleId FK on Employees
- POS slip now shows per-item notes on both thermal print and bill preview
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -44,9 +44,14 @@ public abstract class CafeApiControllerBase : ControllerBase
|
||||
return EnsureManager(tenant);
|
||||
}
|
||||
|
||||
/// <summary>Gate by an explicit capability from the role→permission matrix.</summary>
|
||||
/// <summary>Gate by an explicit capability from the role→permission matrix.
|
||||
/// When the employee has a custom role its permission set is used instead.</summary>
|
||||
protected IActionResult? EnsurePermission(ITenantContext tenant, Permission permission)
|
||||
{
|
||||
if (tenant.CustomPermissions is { } custom)
|
||||
return custom.Contains(permission)
|
||||
? null
|
||||
: Forbidden("FORBIDDEN", "You do not have permission to perform this action.");
|
||||
if (tenant.Role is { } role && RolePermissions.Has(role, permission))
|
||||
return null;
|
||||
return Forbidden("FORBIDDEN", "You do not have permission to perform this action.");
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Meezi.API.Models.CustomRoles;
|
||||
using Meezi.Core.Authorization;
|
||||
using Meezi.Core.Entities;
|
||||
using Meezi.Core.Interfaces;
|
||||
using Meezi.Infrastructure.Data;
|
||||
using Meezi.Shared;
|
||||
|
||||
namespace Meezi.API.Controllers;
|
||||
|
||||
[Route("api/cafes/{cafeId}/custom-roles")]
|
||||
public class CustomRolesController : CafeApiControllerBase
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
|
||||
public CustomRolesController(AppDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> List(string cafeId, ITenantContext tenant, CancellationToken ct)
|
||||
{
|
||||
if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
|
||||
if (EnsureOwner(tenant) is { } forbidden) return forbidden;
|
||||
|
||||
var roles = await _db.CustomRoles
|
||||
.AsNoTracking()
|
||||
.Where(r => r.CafeId == cafeId)
|
||||
.OrderBy(r => r.Name)
|
||||
.Select(r => new
|
||||
{
|
||||
r.Id,
|
||||
r.Name,
|
||||
r.Description,
|
||||
r.Color,
|
||||
r.PermissionsJson,
|
||||
EmployeeCount = _db.Employees.Count(e => e.CafeId == cafeId && e.CustomRoleId == r.Id && e.DeletedAt == null),
|
||||
r.CreatedAt,
|
||||
})
|
||||
.ToListAsync(ct);
|
||||
|
||||
var dtos = roles.Select(r => new CustomRoleDto(
|
||||
r.Id,
|
||||
r.Name,
|
||||
r.Description,
|
||||
r.Color,
|
||||
CustomRolePermissions.Parse(r.PermissionsJson).Select(p => p.ToString()).OrderBy(p => p).ToList(),
|
||||
r.EmployeeCount,
|
||||
r.CreatedAt)).ToList();
|
||||
|
||||
return Ok(new ApiResponse<IReadOnlyList<CustomRoleDto>>(true, dtos));
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public async Task<IActionResult> Get(string cafeId, string id, ITenantContext tenant, CancellationToken ct)
|
||||
{
|
||||
if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
|
||||
if (EnsureOwner(tenant) is { } forbidden) return forbidden;
|
||||
|
||||
var r = await _db.CustomRoles.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == id && x.CafeId == cafeId, ct);
|
||||
if (r is null) return NotFoundError("Custom role not found.");
|
||||
|
||||
var employeeCount = await _db.Employees
|
||||
.CountAsync(e => e.CafeId == cafeId && e.CustomRoleId == id && e.DeletedAt == null, ct);
|
||||
|
||||
return Ok(new ApiResponse<CustomRoleDto>(true, new CustomRoleDto(
|
||||
r.Id, r.Name, r.Description, r.Color,
|
||||
CustomRolePermissions.Parse(r.PermissionsJson).Select(p => p.ToString()).OrderBy(p => p).ToList(),
|
||||
employeeCount, r.CreatedAt)));
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(
|
||||
string cafeId,
|
||||
[FromBody] CreateCustomRoleRequest request,
|
||||
ITenantContext tenant,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
|
||||
if (EnsureOwner(tenant) is { } forbidden) return forbidden;
|
||||
|
||||
var name = request.Name?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return BadRequest(new ApiResponse<object>(false, null, new ApiError("VALIDATION_ERROR", "Name is required.", "Name")));
|
||||
|
||||
var permissions = ParseAndValidatePermissions(request.Permissions);
|
||||
|
||||
var role = new CustomRole
|
||||
{
|
||||
CafeId = cafeId,
|
||||
Name = name,
|
||||
Description = request.Description?.Trim(),
|
||||
Color = NormalizeColor(request.Color),
|
||||
PermissionsJson = CustomRolePermissions.Serialize(permissions),
|
||||
};
|
||||
|
||||
_db.CustomRoles.Add(role);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return CreatedAtAction(nameof(Get), new { cafeId, id = role.Id },
|
||||
new ApiResponse<CustomRoleDto>(true, ToDto(role, 0)));
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
public async Task<IActionResult> Update(
|
||||
string cafeId,
|
||||
string id,
|
||||
[FromBody] UpdateCustomRoleRequest request,
|
||||
ITenantContext tenant,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
|
||||
if (EnsureOwner(tenant) is { } forbidden) return forbidden;
|
||||
|
||||
var role = await _db.CustomRoles
|
||||
.FirstOrDefaultAsync(r => r.Id == id && r.CafeId == cafeId, ct);
|
||||
if (role is null) return NotFoundError("Custom role not found.");
|
||||
|
||||
if (request.Name is not null)
|
||||
{
|
||||
var name = request.Name.Trim();
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return BadRequest(new ApiResponse<object>(false, null, new ApiError("VALIDATION_ERROR", "Name cannot be empty.", "Name")));
|
||||
role.Name = name;
|
||||
}
|
||||
|
||||
if (request.Description is not null)
|
||||
role.Description = request.Description.Trim().Length > 0 ? request.Description.Trim() : null;
|
||||
|
||||
if (request.Color is not null)
|
||||
role.Color = NormalizeColor(request.Color);
|
||||
|
||||
if (request.Permissions is not null)
|
||||
role.PermissionsJson = CustomRolePermissions.Serialize(ParseAndValidatePermissions(request.Permissions));
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
var employeeCount = await _db.Employees
|
||||
.CountAsync(e => e.CafeId == cafeId && e.CustomRoleId == id && e.DeletedAt == null, ct);
|
||||
|
||||
return Ok(new ApiResponse<CustomRoleDto>(true, ToDto(role, employeeCount)));
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> Delete(
|
||||
string cafeId,
|
||||
string id,
|
||||
ITenantContext tenant,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
|
||||
if (EnsureOwner(tenant) is { } forbidden) return forbidden;
|
||||
|
||||
var role = await _db.CustomRoles
|
||||
.FirstOrDefaultAsync(r => r.Id == id && r.CafeId == cafeId, ct);
|
||||
if (role is null) return NotFoundError("Custom role not found.");
|
||||
|
||||
// Unassign employees before deletion so they fall back to their base role permissions.
|
||||
await _db.Employees
|
||||
.Where(e => e.CafeId == cafeId && e.CustomRoleId == id)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(e => e.CustomRoleId, (string?)null), ct);
|
||||
|
||||
role.DeletedAt = DateTime.UtcNow;
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return Ok(new ApiResponse<object>(true, null));
|
||||
}
|
||||
|
||||
// ── Employee custom-role assignment ───────────────────────────────────────
|
||||
|
||||
[HttpPut("/api/cafes/{cafeId}/employees/{employeeId}/custom-role")]
|
||||
public async Task<IActionResult> AssignToEmployee(
|
||||
string cafeId,
|
||||
string employeeId,
|
||||
[FromBody] AssignCustomRoleRequest request,
|
||||
ITenantContext tenant,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
|
||||
if (EnsureOwner(tenant) is { } forbidden) return forbidden;
|
||||
|
||||
var employee = await _db.Employees
|
||||
.FirstOrDefaultAsync(e => e.Id == employeeId && e.CafeId == cafeId && e.DeletedAt == null, ct);
|
||||
if (employee is null) return NotFoundError("Employee not found.");
|
||||
|
||||
if (request.CustomRoleId is not null)
|
||||
{
|
||||
var roleExists = await _db.CustomRoles
|
||||
.AnyAsync(r => r.Id == request.CustomRoleId && r.CafeId == cafeId && r.DeletedAt == null, ct);
|
||||
if (!roleExists)
|
||||
return NotFoundError("Custom role not found.");
|
||||
}
|
||||
|
||||
employee.CustomRoleId = request.CustomRoleId;
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return Ok(new ApiResponse<object>(true, null));
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static CustomRoleDto ToDto(CustomRole r, int employeeCount) => new(
|
||||
r.Id, r.Name, r.Description, r.Color,
|
||||
CustomRolePermissions.Parse(r.PermissionsJson).Select(p => p.ToString()).OrderBy(p => p).ToList(),
|
||||
employeeCount, r.CreatedAt);
|
||||
|
||||
private static IEnumerable<Permission> ParseAndValidatePermissions(IReadOnlyList<string>? names)
|
||||
{
|
||||
if (names is null) return [];
|
||||
return names
|
||||
.Where(n => Enum.TryParse<Permission>(n, ignoreCase: true, out _))
|
||||
.Select(n => Enum.Parse<Permission>(n, ignoreCase: true))
|
||||
.Distinct();
|
||||
}
|
||||
|
||||
private static string? NormalizeColor(string? color)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(color)) return null;
|
||||
var c = color.Trim();
|
||||
return c.StartsWith('#') ? c : null;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Meezi.Core.Authorization;
|
||||
using Meezi.Core.Constants;
|
||||
using Meezi.Core.Enums;
|
||||
using Meezi.Core.Interfaces;
|
||||
@@ -116,6 +117,16 @@ public class TenantMiddleware
|
||||
else
|
||||
_logger.LogWarning("Ignoring invalid or inactive branchId claim for cafe {CafeId}", cafeId);
|
||||
}
|
||||
|
||||
var customPermsClaim = context.User.FindFirst(MeeziClaimTypes.CustomPermissions)?.Value;
|
||||
if (!string.IsNullOrEmpty(customPermsClaim))
|
||||
{
|
||||
var set = new HashSet<Permission>();
|
||||
foreach (var name in customPermsClaim.Split(',', StringSplitOptions.RemoveEmptyEntries))
|
||||
if (Enum.TryParse<Permission>(name, ignoreCase: true, out var p))
|
||||
set.Add(p);
|
||||
scopedMerchant.CustomPermissions = set;
|
||||
}
|
||||
}
|
||||
|
||||
if (branchContext is BranchContext scopedBranch)
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace Meezi.API.Models.CustomRoles;
|
||||
|
||||
public record CustomRoleDto(
|
||||
string Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
string? Color,
|
||||
IReadOnlyList<string> Permissions,
|
||||
int EmployeeCount,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CreateCustomRoleRequest(
|
||||
string Name,
|
||||
string? Description = null,
|
||||
string? Color = null,
|
||||
IReadOnlyList<string>? Permissions = null);
|
||||
|
||||
public record UpdateCustomRoleRequest(
|
||||
string? Name = null,
|
||||
string? Description = null,
|
||||
string? Color = null,
|
||||
IReadOnlyList<string>? Permissions = null);
|
||||
|
||||
public record AssignCustomRoleRequest(string? CustomRoleId);
|
||||
@@ -558,7 +558,18 @@ public class AuthService : IAuthService
|
||||
{
|
||||
var resolution = await ResolveBranchAsync(employee, cafe, requestedBranchId, cancellationToken);
|
||||
|
||||
var accessToken = _jwtTokenService.CreateAccessToken(employee, cafe, resolution.EffectiveRole, resolution.ActiveBranchId);
|
||||
// Load custom role permissions when the employee has a custom role assigned.
|
||||
IReadOnlySet<Permission>? customPerms = null;
|
||||
if (!string.IsNullOrEmpty(employee.CustomRoleId))
|
||||
{
|
||||
var cr = await _db.CustomRoles
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(r => r.Id == employee.CustomRoleId && r.CafeId == cafe.Id && r.DeletedAt == null, cancellationToken);
|
||||
if (cr != null)
|
||||
customPerms = CustomRolePermissions.Parse(cr.PermissionsJson);
|
||||
}
|
||||
|
||||
var accessToken = _jwtTokenService.CreateAccessToken(employee, cafe, resolution.EffectiveRole, resolution.ActiveBranchId, customPerms);
|
||||
// On refresh, reuse the caller's refresh token (and slide its TTL below) instead
|
||||
// of minting a new one. A café often runs POS + KDS + queue display at once; if
|
||||
// refresh rotated the token, the first refresh would revoke it and every other
|
||||
@@ -580,8 +591,7 @@ public class AuthService : IAuthService
|
||||
TimeSpan.FromDays(refreshDays),
|
||||
cancellationToken);
|
||||
|
||||
var permissions = Meezi.Core.Authorization.RolePermissions
|
||||
.For(resolution.EffectiveRole)
|
||||
var permissions = (customPerms as IEnumerable<Permission> ?? RolePermissions.For(resolution.EffectiveRole))
|
||||
.Select(p => p.ToString())
|
||||
.OrderBy(p => p)
|
||||
.ToList();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Meezi.Core.Authorization;
|
||||
using Meezi.Core.Entities;
|
||||
using Meezi.Core.Enums;
|
||||
|
||||
@@ -11,8 +12,15 @@ public interface IJwtTokenService
|
||||
/// Issue a token scoped to an active branch. The <paramref name="effectiveRole"/>
|
||||
/// is the role the employee holds in <paramref name="activeBranchId"/> (or their
|
||||
/// café-wide role when <paramref name="activeBranchId"/> is null).
|
||||
/// When <paramref name="customPermissions"/> is non-null the token embeds those
|
||||
/// permissions as a claim that overrides the role matrix on the server side.
|
||||
/// </summary>
|
||||
string CreateAccessToken(Employee employee, Cafe cafe, EmployeeRole effectiveRole, string? activeBranchId);
|
||||
string CreateAccessToken(
|
||||
Employee employee,
|
||||
Cafe cafe,
|
||||
EmployeeRole effectiveRole,
|
||||
string? activeBranchId,
|
||||
IEnumerable<Permission>? customPermissions = null);
|
||||
|
||||
string CreateConsumerAccessToken(ConsumerAccount account, string language = "fa");
|
||||
string CreateRefreshToken();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Meezi.Core.Authorization;
|
||||
using Meezi.Core.Constants;
|
||||
using Meezi.Core.Entities;
|
||||
using Meezi.Core.Enums;
|
||||
@@ -21,7 +22,12 @@ public class JwtTokenService : IJwtTokenService
|
||||
public string CreateAccessToken(Employee employee, Cafe cafe) =>
|
||||
CreateAccessToken(employee, cafe, employee.Role, employee.BranchId);
|
||||
|
||||
public string CreateAccessToken(Employee employee, Cafe cafe, EmployeeRole effectiveRole, string? activeBranchId)
|
||||
public string CreateAccessToken(
|
||||
Employee employee,
|
||||
Cafe cafe,
|
||||
EmployeeRole effectiveRole,
|
||||
string? activeBranchId,
|
||||
IEnumerable<Permission>? customPermissions = null)
|
||||
{
|
||||
var key = _configuration["Jwt:Key"] ?? throw new InvalidOperationException("Jwt:Key is not configured.");
|
||||
var issuer = _configuration["Jwt:Issuer"] ?? "meezi";
|
||||
@@ -41,6 +47,13 @@ public class JwtTokenService : IJwtTokenService
|
||||
if (!string.IsNullOrEmpty(activeBranchId))
|
||||
claims.Add(new Claim(MeeziClaimTypes.BranchId, activeBranchId));
|
||||
|
||||
if (customPermissions != null)
|
||||
{
|
||||
var encoded = string.Join(",", customPermissions.Select(p => p.ToString()));
|
||||
if (!string.IsNullOrEmpty(encoded))
|
||||
claims.Add(new Claim(MeeziClaimTypes.CustomPermissions, encoded));
|
||||
}
|
||||
|
||||
var credentials = new SigningCredentials(
|
||||
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
|
||||
SecurityAlgorithms.HmacSha256);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Meezi.Core.Authorization;
|
||||
|
||||
/// <summary>Helpers for serialising/deserialising a custom role's permission set.</summary>
|
||||
public static class CustomRolePermissions
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web);
|
||||
|
||||
/// <summary>Parse the stored JSON array of permission names into a set.</summary>
|
||||
public static IReadOnlySet<Permission> Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return new HashSet<Permission>();
|
||||
try
|
||||
{
|
||||
var names = JsonSerializer.Deserialize<string[]>(json, JsonOpts) ?? [];
|
||||
var set = new HashSet<Permission>();
|
||||
foreach (var name in names)
|
||||
if (Enum.TryParse<Permission>(name, ignoreCase: true, out var p))
|
||||
set.Add(p);
|
||||
return set;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new HashSet<Permission>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Serialise a permission set to JSON for storage.</summary>
|
||||
public static string Serialize(IEnumerable<Permission> permissions) =>
|
||||
JsonSerializer.Serialize(permissions.Select(p => p.ToString()).ToArray(), JsonOpts);
|
||||
}
|
||||
@@ -9,6 +9,9 @@ public static class MeeziClaimTypes
|
||||
public const string BranchId = "branchId";
|
||||
public const string Actor = "actor";
|
||||
public const string Phone = "phone";
|
||||
/// <summary>Comma-separated list of <see cref="Meezi.Core.Authorization.Permission"/> names
|
||||
/// embedded when the employee has a custom role. Presence overrides the role-based matrix.</summary>
|
||||
public const string CustomPermissions = "customPerms";
|
||||
}
|
||||
|
||||
public static class MeeziActorKinds
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace Meezi.Core.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// A café-defined role template that overrides the standard <see cref="Meezi.Core.Enums.EmployeeRole"/>
|
||||
/// permission set. The owner creates named roles (e.g. "Barista", "Floor Supervisor") and assigns
|
||||
/// specific <see cref="Meezi.Core.Authorization.Permission"/> values to each one.
|
||||
/// When an employee has a <see cref="CustomRoleId"/>, their effective permissions come from here
|
||||
/// instead of the static <see cref="Meezi.Core.Authorization.RolePermissions"/> matrix.
|
||||
/// </summary>
|
||||
public class CustomRole : TenantEntity
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string? Description { get; set; }
|
||||
/// <summary>Optional hex color (e.g. "#F59E0B") for badge display in the UI.</summary>
|
||||
public string? Color { get; set; }
|
||||
/// <summary>JSON array of <see cref="Meezi.Core.Authorization.Permission"/> enum names.</summary>
|
||||
public string PermissionsJson { get; set; } = "[]";
|
||||
|
||||
public Cafe Cafe { get; set; } = null!;
|
||||
public ICollection<Employee> Employees { get; set; } = [];
|
||||
}
|
||||
@@ -26,6 +26,14 @@ public class Employee : TenantEntity
|
||||
public ICollection<EmployeeSchedule> Schedules { get; set; } = [];
|
||||
public ICollection<LeaveRequest> LeaveRequests { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Optional custom role defined by the café owner. When set, this role's permission set
|
||||
/// overrides the standard <see cref="RolePermissions"/> matrix for this employee.
|
||||
/// The base <see cref="Role"/> enum still controls café-wide vs. branch-scoped behaviour.
|
||||
/// </summary>
|
||||
public string? CustomRoleId { get; set; }
|
||||
public CustomRole? CustomRole { get; set; }
|
||||
|
||||
/// <summary>Per-branch role assignments (multi-branch staff). Owners are café-wide and may have none.</summary>
|
||||
public ICollection<EmployeeBranchRole> BranchRoles { get; set; } = [];
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Meezi.Core.Authorization;
|
||||
using Meezi.Core.Enums;
|
||||
|
||||
namespace Meezi.Core.Interfaces;
|
||||
@@ -14,4 +15,10 @@ public interface ITenantContext
|
||||
bool IsSystemAdmin { get; }
|
||||
bool IsAuthenticated { get; }
|
||||
bool IsCafeOwner => Role == EmployeeRole.Owner;
|
||||
/// <summary>
|
||||
/// When non-null the employee has a custom role. These permissions override the static
|
||||
/// <see cref="RolePermissions"/> matrix; the base <see cref="Role"/> still governs
|
||||
/// café-wide vs. branch-scoped behaviour.
|
||||
/// </summary>
|
||||
IReadOnlySet<Permission>? CustomPermissions { get; }
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ public class AppDbContext : DbContext
|
||||
public DbSet<Table> Tables => Set<Table>();
|
||||
public DbSet<TableSection> TableSections => Set<TableSection>();
|
||||
public DbSet<Employee> Employees => Set<Employee>();
|
||||
public DbSet<CustomRole> CustomRoles => Set<CustomRole>();
|
||||
public DbSet<EmployeeBranchRole> EmployeeBranchRoles => Set<EmployeeBranchRole>();
|
||||
public DbSet<MenuCategory> MenuCategories => Set<MenuCategory>();
|
||||
public DbSet<MenuItem> MenuItems => Set<MenuItem>();
|
||||
@@ -195,6 +196,17 @@ public class AppDbContext : DbContext
|
||||
e.HasQueryFilter(x => x.DeletedAt == null && (!_branchScoped || x.BranchId == _branchScopeId));
|
||||
});
|
||||
|
||||
modelBuilder.Entity<CustomRole>(e =>
|
||||
{
|
||||
e.HasKey(x => x.Id);
|
||||
e.Property(x => x.Name).HasMaxLength(100).IsRequired();
|
||||
e.Property(x => x.Description).HasMaxLength(500);
|
||||
e.Property(x => x.Color).HasMaxLength(20);
|
||||
e.Property(x => x.PermissionsJson).HasMaxLength(2000).IsRequired();
|
||||
e.HasOne(x => x.Cafe).WithMany().HasForeignKey(x => x.CafeId).OnDelete(DeleteBehavior.Cascade);
|
||||
e.HasQueryFilter(x => x.DeletedAt == null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Employee>(e =>
|
||||
{
|
||||
e.HasKey(x => x.Id);
|
||||
@@ -204,6 +216,7 @@ public class AppDbContext : DbContext
|
||||
e.HasIndex(x => x.BranchId);
|
||||
e.HasOne(x => x.Cafe).WithMany(c => c.Employees).HasForeignKey(x => x.CafeId).OnDelete(DeleteBehavior.Cascade);
|
||||
e.HasOne(x => x.Branch).WithMany(b => b.Staff).HasForeignKey(x => x.BranchId).OnDelete(DeleteBehavior.SetNull);
|
||||
e.HasOne(x => x.CustomRole).WithMany(r => r.Employees).HasForeignKey(x => x.CustomRoleId).OnDelete(DeleteBehavior.SetNull);
|
||||
e.HasQueryFilter(x => x.DeletedAt == null);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using Meezi.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Meezi.Infrastructure.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260620100000_AddCustomRoles")]
|
||||
public partial class AddCustomRoles : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "CustomRoles",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
CafeId = table.Column<string>(type: "text", nullable: false),
|
||||
Name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
Description = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
|
||||
Color = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: true),
|
||||
PermissionsJson = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: false, defaultValue: "[]"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_CustomRoles", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_CustomRoles_Cafes_CafeId",
|
||||
column: x => x.CafeId,
|
||||
principalTable: "Cafes",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_CustomRoles_CafeId",
|
||||
table: "CustomRoles",
|
||||
column: "CafeId");
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "CustomRoleId",
|
||||
table: "Employees",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Employees_CustomRoleId",
|
||||
table: "Employees",
|
||||
column: "CustomRoleId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Employees_CustomRoles_CustomRoleId",
|
||||
table: "Employees",
|
||||
column: "CustomRoleId",
|
||||
principalTable: "CustomRoles",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.SetNull);
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Employees_CustomRoles_CustomRoleId",
|
||||
table: "Employees");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Employees_CustomRoleId",
|
||||
table: "Employees");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CustomRoleId",
|
||||
table: "Employees");
|
||||
|
||||
migrationBuilder.DropTable(name: "CustomRoles");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -928,6 +928,46 @@ namespace Meezi.Infrastructure.Data.Migrations
|
||||
b.ToTable("DemoRequests");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Meezi.Core.Entities.CustomRole", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("CafeId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Color")
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("PermissionsJson")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CafeId");
|
||||
|
||||
b.ToTable("CustomRoles");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Meezi.Core.Entities.Employee", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
@@ -946,6 +986,9 @@ namespace Meezi.Infrastructure.Data.Migrations
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("CustomRoleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
@@ -976,6 +1019,8 @@ namespace Meezi.Infrastructure.Data.Migrations
|
||||
|
||||
b.HasIndex("BranchId");
|
||||
|
||||
b.HasIndex("CustomRoleId");
|
||||
|
||||
b.HasIndex("CafeId", "Phone")
|
||||
.IsUnique()
|
||||
.HasFilter("\"DeletedAt\" IS NULL");
|
||||
@@ -2812,6 +2857,17 @@ namespace Meezi.Infrastructure.Data.Migrations
|
||||
b.Navigation("Cafe");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Meezi.Core.Entities.CustomRole", b =>
|
||||
{
|
||||
b.HasOne("Meezi.Core.Entities.Cafe", "Cafe")
|
||||
.WithMany()
|
||||
.HasForeignKey("CafeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Cafe");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Meezi.Core.Entities.Employee", b =>
|
||||
{
|
||||
b.HasOne("Meezi.Core.Entities.Branch", "Branch")
|
||||
@@ -2825,9 +2881,16 @@ namespace Meezi.Infrastructure.Data.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Meezi.Core.Entities.CustomRole", "CustomRole")
|
||||
.WithMany("Employees")
|
||||
.HasForeignKey("CustomRoleId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("Branch");
|
||||
|
||||
b.Navigation("Cafe");
|
||||
|
||||
b.Navigation("CustomRole");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Meezi.Core.Entities.EmployeeBranchRole", b =>
|
||||
@@ -3343,6 +3406,11 @@ namespace Meezi.Infrastructure.Data.Migrations
|
||||
b.Navigation("Orders");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Meezi.Core.Entities.CustomRole", b =>
|
||||
{
|
||||
b.Navigation("Employees");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Meezi.Core.Entities.Employee", b =>
|
||||
{
|
||||
b.Navigation("Attendances");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Meezi.Core.Authorization;
|
||||
using Meezi.Core.Enums;
|
||||
using Meezi.Core.Interfaces;
|
||||
|
||||
@@ -13,4 +14,5 @@ public class TenantContext : ITenantContext
|
||||
public string? BranchId { get; set; }
|
||||
public bool IsSystemAdmin { get; set; }
|
||||
public bool IsAuthenticated => IsSystemAdmin || !string.IsNullOrEmpty(CafeId);
|
||||
public IReadOnlySet<Permission>? CustomPermissions { get; set; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user