c_agri_trade/project_code/frontend/src/features/tenant/TenantMembersView.tsx

249 lines
10 KiB
TypeScript

import React, { useEffect, useState } from 'react';
import { tenantStore } from '../../stores/tenantStore';
import { apiClient } from '../../services/api';
/**
* Tenant Members & Roles Management View.
*
* Fulfills FR-TENANTMEMBERSHIPCONTEXT-001 (UC-019 / SCREEN-TENANT-002).
* Enables Tenant Administrators to manage user memberships within their tenant boundary.
*/
export interface Member {
membership_id: string;
tenant_id: string;
user_id: string;
email: string;
role: string;
status: 'ACTIVE' | 'REVOKED';
created_at: string;
}
const PRD_ROLES = [
'Tenant Administrator',
'Mandi Buyer',
'Purchase Manager',
'Yard Supervisor',
'Quality Officer',
'Sales Executive',
'Sales Manager',
'Logistics Coordinator',
'Accounts Executive',
'Partner / MD',
];
export const TenantMembersView: React.FC = () => {
const [activeTenantId, setActiveTenantId] = useState<string | null>(tenantStore.getState().activeTenantId);
const [activeBusinessName, setActiveBusinessName] = useState<string | null>(tenantStore.getState().activeBusinessName);
const [members, setMembers] = useState<Member[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Invite Modal
const [showInviteModal, setShowInviteModal] = useState(false);
const [inviteEmail, setInviteEmail] = useState('');
const [inviteRole, setInviteRole] = useState(PRD_ROLES[1]); // Default Mandi Buyer
useEffect(() => {
const unsub = tenantStore.subscribe(() => {
const state = tenantStore.getState();
setActiveTenantId(state.activeTenantId);
setActiveBusinessName(state.activeBusinessName);
});
return () => unsub();
}, []);
useEffect(() => {
if (activeTenantId) {
fetchMembers(activeTenantId);
}
}, [activeTenantId]);
const fetchMembers = async (tenantId: string) => {
setLoading(true);
setError(null);
const resp = await apiClient<{ memberships: Member[] }>(`/api/v1/tenants/${tenantId}/memberships`);
setLoading(false);
if (resp.status === 200 && resp.data?.memberships) {
setMembers(resp.data.memberships);
} else {
setError(resp.error || 'Failed to load member roster.');
}
};
const handleInvite = async (e: React.FormEvent) => {
e.preventDefault();
if (!activeTenantId) return;
setLoading(true);
const resp = await apiClient(`/api/v1/tenants/${activeTenantId}/memberships`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: inviteEmail, role: inviteRole }),
});
setLoading(false);
if (resp.status === 201) {
setShowInviteModal(false);
setInviteEmail('');
fetchMembers(activeTenantId);
} else {
setError(resp.error || 'Failed to assign membership.');
}
};
const handleRevoke = async (membershipId: string) => {
if (!activeTenantId) return;
if (!confirm('Are you sure you want to revoke this user membership?')) return;
setLoading(true);
const resp = await apiClient(`/api/v1/tenants/${activeTenantId}/memberships/${membershipId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'REVOKED' }),
});
setLoading(false);
if (resp.status === 200) {
fetchMembers(activeTenantId);
} else {
setError(resp.error || 'Failed to revoke membership.');
}
};
return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8" data-testid="tenant-members-view">
<div className="sm:flex sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Enterprise Members & Roles</h1>
<p className="mt-1 text-sm text-gray-500">
Governed member roster for <strong>{activeBusinessName || 'Active Firm'}</strong> (FR-TENANTMEMBERSHIPCONTEXT-001).
</p>
</div>
<div className="mt-4 sm:mt-0">
<button
type="button"
onClick={() => setShowInviteModal(true)}
disabled={!activeTenantId}
className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 disabled:opacity-50"
>
Assign Member Role
</button>
</div>
</div>
{error && (
<div className="mt-4 bg-red-50 border-l-4 border-red-400 p-4">
<p className="text-sm text-red-700">{error}</p>
</div>
)}
{/* Members Table */}
<div className="mt-8 flex flex-col">
<div className="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
<div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
<table className="min-w-full divide-y divide-gray-300">
<thead className="bg-gray-50">
<tr>
<th className="py-3.5 pl-4 pr-3 text-left text-xs font-semibold text-gray-900 sm:pl-6">Member Email</th>
<th className="px-3 py-3.5 text-left text-xs font-semibold text-gray-900">PRD Business Role</th>
<th className="px-3 py-3.5 text-left text-xs font-semibold text-gray-900">Membership Status</th>
<th className="px-3 py-3.5 text-left text-xs font-semibold text-gray-900">Added Date</th>
<th className="relative py-3.5 pl-3 pr-4 sm:pr-6"><span className="sr-only">Actions</span></th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200 bg-white">
{members.map((m) => (
<tr key={m.membership_id}>
<td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">{m.email}</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-700">
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
{m.role}
</span>
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
<span className={`inline-flex px-2 text-xs font-semibold leading-5 rounded-full ${
m.status === 'ACTIVE' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
}`}>
{m.status}
</span>
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{new Date(m.created_at).toLocaleDateString()}
</td>
<td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
{m.status === 'ACTIVE' && (
<button
onClick={() => handleRevoke(m.membership_id)}
className="text-red-600 hover:text-red-900"
>
Revoke Access
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
{/* Invite Member Modal */}
{showInviteModal && (
<div className="fixed z-10 inset-0 overflow-y-auto">
<div className="flex items-center justify-center min-h-screen px-4 text-center sm:block sm:p-0">
<div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onClick={() => setShowInviteModal(false)} />
<div className="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full sm:p-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">Assign Enterprise Role</h3>
<form onSubmit={handleInvite} className="mt-4 space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700">User Email Address</label>
<input
type="email"
required
value={inviteEmail}
onChange={(e) => setInviteEmail(e.target.value)}
placeholder="colleague@tradingfirm.com"
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700">Governed PRD Role</label>
<select
value={inviteRole}
onChange={(e) => setInviteRole(e.target.value)}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm"
>
{PRD_ROLES.map((r) => (
<option key={r} value={r}>{r}</option>
))}
</select>
</div>
<div className="mt-5 sm:grid sm:grid-cols-2 sm:gap-3">
<button
type="button"
onClick={() => setShowInviteModal(false)}
className="w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:text-sm"
>
Cancel
</button>
<button
type="submit"
disabled={loading}
className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-emerald-600 text-base font-medium text-white hover:bg-emerald-700 sm:text-sm"
>
Confirm Assignment
</button>
</div>
</form>
</div>
</div>
</div>
)}
</div>
);
};