Merge pull request #78 from artslidd/develop

Develop
This commit is contained in:
Arthur Belleville 2026-04-23 19:18:20 +02:00 committed by GitHub
commit b6ce6909b7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
98 changed files with 5752 additions and 2773 deletions

View file

@ -1,330 +0,0 @@
version: 2.1
# Import the Node orb
orbs:
node: circleci/node@7.2.1
# Jobs
jobs:
# ============================================
# TEST PHASE
# ============================================
test-lint:
executor:
name: node/default
resource_class: small
tag: 'lts'
steps:
- checkout
- node/install-packages:
pkg-manager: pnpm
- run:
name: Run linting
command: pnpm run lint
test-typecheck:
executor:
name: node/default
resource_class: small
tag: 'lts'
steps:
- checkout
- node/install-packages:
pkg-manager: pnpm
cache-path: ~/.pnpm-store
- run:
name: Type check all packages
command: pnpm run typecheck
test-unit:
executor:
name: node/default
resource_class: medium
tag: 'lts'
steps:
- checkout
- node/install-packages:
pkg-manager: pnpm
cache-path: ~/.pnpm-store
- run:
name: Run unit tests
command: pnpm --filter @xtablo/main run test
test-api:
executor:
name: node/default
tag: 'lts'
resource_class: small
steps:
- checkout
- node/install-packages:
pkg-manager: pnpm
cache-path: ~/.pnpm-store
- run:
name: Run API checks
command: |
if [ "${RUN_API_INTEGRATION_TESTS:-0}" = "1" ]; then
pnpm --filter @xtablo/api run test
else
echo "Skipping API integration tests (set RUN_API_INTEGRATION_TESTS=1 to enable)."
pnpm --filter @xtablo/api run build
fi
# ============================================
# BUILD PHASE
# ============================================
build-apps:
docker:
- image: cimg/node:lts
resource_class: small
parameters:
environment:
type: string
default: "staging"
steps:
- checkout
- node/install-packages:
pkg-manager: pnpm
cache-path: ~/.pnpm-store
- run:
name: Build main app for << parameters.environment >>
command: |
cd apps/main
pnpm run build:<< parameters.environment >>
- run:
name: Build external app
command: |
cd apps/external
pnpm run build
- persist_to_workspace:
root: .
paths:
- apps/main/dist
- apps/external/dist
- store_artifacts:
path: apps/main/dist
destination: main-app-<< parameters.environment >>
- store_artifacts:
path: apps/external/dist
destination: external-app
build-api:
docker:
- image: cimg/node:lts
resource_class: small
steps:
- checkout
- node/install-packages:
pkg-manager: pnpm
cache-path: ~/.pnpm-store
- run:
name: Build API
command: pnpm --filter @xtablo/api run build
- persist_to_workspace:
root: .
paths:
- apps/api/dist
- store_artifacts:
path: apps/api/dist
destination: api
# ============================================
# DOCKER BUILD PHASE
# ============================================
build-docker-api:
machine:
image: ubuntu-2204:current
resource_class: medium
steps:
- checkout
- attach_workspace:
at: .
- run:
name: Build API Docker image
command: docker build -f apps/api/Dockerfile -t xtablo-api:${CIRCLE_SHA1} -t xtablo-api:latest .
- run:
name: Save Docker image
command: |
mkdir -p /tmp/docker-images
docker save xtablo-api:${CIRCLE_SHA1} -o /tmp/docker-images/api.tar
- persist_to_workspace:
root: /tmp
paths:
- docker-images/api.tar
# ============================================
# DEPLOY PHASE
# ============================================
deploy-staging:
docker:
- image: cimg/node:lts
resource_class: small
steps:
- checkout
- attach_workspace:
at: .
- node/install-packages:
pkg-manager: pnpm
cache-path: ~/.pnpm-store
- run:
name: Deploy main app to staging
command: |
cd apps/main
echo "Deploying main app to staging environment..."
npx wrangler deploy --env staging
- run:
name: Deploy external app to staging
command: |
cd apps/external
echo "Deploying external app to staging..."
# Add external app staging deployment if needed
# npx wrangler deploy --env staging
- run:
name: Deploy API to staging
command: |
echo "Deploying API to staging environment..."
# Add your API deployment commands here
# Example for Google Cloud Run:
# gcloud run deploy xtablo-api-staging --image gcr.io/${GCP_PROJECT}/xtablo-api:${CIRCLE_SHA1} --region us-central1
deploy-production:
docker:
- image: cimg/node:lts
resource_class: small
steps:
- checkout
- attach_workspace:
at: .
- node/install-packages:
pkg-manager: pnpm
cache-path: ~/.pnpm-store
- run:
name: Deploy main app to production
command: |
cd apps/main
echo "Deploying main app to production environment..."
npx wrangler deploy --env production
- run:
name: Deploy external app to production
command: |
cd apps/external
echo "Deploying external app to production..."
# Add external app production deployment if needed
# npx wrangler deploy --env production
- run:
name: Deploy API to production
command: |
echo "Deploying API to production environment..."
# Add your production API deployment commands here
# Example for Google Cloud Run:
# gcloud run deploy xtablo-api --image gcr.io/${GCP_PROJECT}/xtablo-api:${CIRCLE_SHA1} --region us-central1
# Workflows
workflows:
version: 2
# Run on all branches (except main and develop)
test-and-build:
when:
and:
- not:
equal: [ main, << pipeline.git.branch >> ]
- not:
equal: [ develop, << pipeline.git.branch >> ]
jobs:
# Test phase - run in parallel
- test-lint
- test-typecheck
- test-unit
- test-api
# Build phase - run after tests pass
- build-apps:
requires:
- test-lint
- test-typecheck
- test-unit
- build-api:
requires:
- test-api
- build-docker-api:
requires:
- build-api
# Staging deployment workflow (develop branch)
deploy-to-staging:
when:
equal: [ develop, << pipeline.git.branch >> ]
jobs:
# Test phase
- test-lint
- test-typecheck
- test-unit
- test-api
# Build phase for staging
- build-apps:
environment: "staging"
requires:
- test-lint
- test-typecheck
- test-unit
- build-api:
requires:
- test-api
- build-docker-api:
requires:
- build-api
# Deploy to staging
- deploy-staging:
requires:
- build-apps
- build-docker-api
# Production deployment workflow (main branch)
deploy-to-production:
when:
equal: [ main, << pipeline.git.branch >> ]
jobs:
# Test phase
- test-lint
- test-typecheck
- test-unit
- test-api
# Build phase for production
- build-apps:
environment: "prod"
requires:
- test-lint
- test-typecheck
- test-unit
- build-api:
requires:
- test-api
- build-docker-api:
requires:
- build-api
# Manual approval gate before production
- hold-for-approval:
type: approval
requires:
- build-apps
- build-docker-api
# Deploy to production
- deploy-production:
requires:
- hold-for-approval

View file

@ -38,7 +38,6 @@ node_modules
# CI/CD
.github
**/cloudbuild.yaml
**/.circleci
# Misc
**/.turbo
@ -48,4 +47,3 @@ node_modules
**/temp
**/.next
**/.nuxt

55
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,55 @@
name: xtablo-ci
on:
pull_request:
push:
branches:
- main
- develop
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
checks:
name: Checks
runs-on:
- self-hosted
- linux
- x64
timeout-minutes: 45
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v5
with:
version: 10.19.0
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 20
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile --child-concurrency=2
- name: Lint
run: pnpm turbo run lint --concurrency=2
- name: Typecheck
run: pnpm turbo run typecheck --concurrency=1
- name: Test main app
run: pnpm --filter @xtablo/main test -- --maxWorkers=1 --no-file-parallelism
- name: Test clients app
run: pnpm --filter @xtablo/clients test -- --maxWorkers=1 --no-file-parallelism
- name: Typecheck API
run: pnpm --filter @xtablo/api typecheck

View file

@ -24,9 +24,7 @@ describe("Middleware Tests", () => {
}),
});
const createBillingStateSupabaseMock = (input: {
ownerPlan?: string | null;
}) => {
const createBillingStateSupabaseMock = (input: { ownerPlan?: string | null }) => {
const ownerPlan = input.ownerPlan ?? "none";
return {
@ -325,10 +323,10 @@ describe("Middleware Tests", () => {
createProfilesSupabaseMock({
data: { is_temporary: true },
error: null,
}) as any
})
);
// biome-ignore lint/suspicious/noExplicitAny: Test-only context injection
(c as any).set("user", { id: "temp-user" } as any);
(c as any).set("user", { id: "temp-user" });
await next();
});
app.use(middlewareManager.regularUserCheck);
@ -352,10 +350,10 @@ describe("Middleware Tests", () => {
createProfilesSupabaseMock({
data: { is_temporary: false, is_client: true },
error: null,
}) as any
})
);
// biome-ignore lint/suspicious/noExplicitAny: Test-only context injection
(c as any).set("user", { id: "client-user" } as any);
(c as any).set("user", { id: "client-user" });
await next();
});
app.use(middlewareManager.regularUserCheck);
@ -381,10 +379,10 @@ describe("Middleware Tests", () => {
createProfilesSupabaseMock({
data: { is_temporary: true },
error: null,
}) as any
})
);
// biome-ignore lint/suspicious/noExplicitAny: Test-only context injection
(c as any).set("user", { id: "temp-user" } as any);
(c as any).set("user", { id: "temp-user" });
await next();
});
app.use(middlewareManager.billingCheckoutAccess);
@ -409,10 +407,10 @@ describe("Middleware Tests", () => {
"supabase",
createBillingStateSupabaseMock({
ownerPlan: "none",
}) as any
})
);
// biome-ignore lint/suspicious/noExplicitAny: Test-only context injection
(c as any).set("user", { id: "owner-user" } as any);
(c as any).set("user", { id: "owner-user" });
await next();
});
app.use(middlewareManager.activePlanAccess);
@ -435,10 +433,10 @@ describe("Middleware Tests", () => {
"supabase",
createBillingStateSupabaseMock({
ownerPlan: "solo",
}) as any
})
);
// biome-ignore lint/suspicious/noExplicitAny: Test-only context injection
(c as any).set("user", { id: "owner-user" } as any);
(c as any).set("user", { id: "owner-user" });
await next();
});
app.use(middlewareManager.activePlanAccess);

View file

@ -62,19 +62,23 @@ describe("Client Invites Endpoints", () => {
{ headers: { Authorization: `Bearer ${user.accessToken}` } }
);
const acceptInvite = (user: TestUserData, token: string) =>
client["client-invites"].accept[":token"].$post(
{ param: { token } },
{ headers: { Authorization: `Bearer ${user.accessToken}` } }
);
const getSetupInvite = (token: string) =>
client["client-invites"].setup[":token"].$get({
param: { token },
});
// ─── Helper: insert a client_invite row directly via admin ──────────────────
const completeSetupInvite = (token: string, password: string) =>
client["client-invites"].setup[":token"].$post({
param: { token },
json: { password },
});
const insertClientInvite = async (opts: {
tabloId: string;
invitedEmail: string;
invitedBy: string;
token: string;
inviteType?: string;
isPending?: boolean;
expiresAt?: string;
}) => {
@ -87,6 +91,7 @@ describe("Client Invites Endpoints", () => {
invited_email: opts.invitedEmail,
invited_by: opts.invitedBy,
invite_token: opts.token,
invite_type: opts.inviteType ?? "setup",
is_pending: opts.isPending ?? true,
expires_at: expiresAt,
})
@ -97,11 +102,9 @@ describe("Client Invites Endpoints", () => {
return data.id as number;
};
// ─── Cleanup helper ──────────────────────────────────────────────────────────
const cleanupInvitesByEmail = async (email: string) => {
await supabaseAdmin.from("client_invites").delete().eq("invited_email", email);
// Also clean up any client user that may have been created
const { data: usersData } = await supabaseAdmin.auth.admin.listUsers();
// biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime
const users = usersData as any;
@ -113,50 +116,118 @@ describe("Client Invites Endpoints", () => {
}
};
const createClientAccount = async (
email: string,
input?: { onboarded?: boolean; password?: string }
) => {
const password = input?.password ?? "client_password_123";
const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({
email,
password,
email_confirm: true,
user_metadata: { role: "client" },
});
if (authError || !authData?.user) {
throw new Error(`Failed to create client account: ${authError?.message}`);
}
const updates: Record<string, unknown> = { is_client: true };
if (input?.onboarded) {
updates.client_onboarded_at = new Date().toISOString();
}
const { error: profileError } = await supabaseAdmin
.from("profiles")
.update(updates)
.eq("id", authData.user.id);
if (profileError) {
throw new Error(`Failed to update client profile: ${profileError.message}`);
}
return authData.user;
};
// ════════════════════════════════════════════════════════════════════════════
// POST /:tabloId — Create client invite
// ════════════════════════════════════════════════════════════════════════════
describe("POST /client-invites/:tabloId", () => {
const testEmail = "test_client_invite_new@example.com";
const existingClientEmail = "test_existing_client_invite@example.com";
beforeEach(async () => {
await cleanupInvitesByEmail(testEmail);
await cleanupInvitesByEmail(existingClientEmail);
});
it("should create a client invite for a valid email (admin)", async () => {
it("creates a setup token for a first-time client invite", async () => {
const res = await postInvite(ownerUser, adminTabloId, testEmail);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.success).toBe(true);
expect(data.inviteMode).toBe("setup");
// Verify row was inserted
const { data: invite } = await supabaseAdmin
.from("client_invites")
.select("id, invited_email, is_pending")
.select("id, invited_email, is_pending, invite_token, invite_type")
.eq("tablo_id", adminTabloId)
.eq("invited_email", testEmail)
.single();
expect(invite).toBeDefined();
expect(invite?.is_pending).toBe(true);
expect(invite?.invite_token).toBeTruthy();
expect(invite?.invite_type).toBe("setup");
expect(mockSendMail).toHaveBeenCalledTimes(1);
expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain("/set-password?token=");
});
it("should reject temporary users before admin check", async () => {
// tempUser is NOT admin of adminTabloId (owner user owns it)
it("sends an access notification for an already-onboarded client", async () => {
await createClientAccount(existingClientEmail, { onboarded: true });
const res = await postInvite(ownerUser, adminTabloId, existingClientEmail);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.success).toBe(true);
expect(data.inviteMode).toBe("notification");
const { data: invite } = await supabaseAdmin
.from("client_invites")
.select("id")
.eq("tablo_id", adminTabloId)
.eq("invited_email", existingClientEmail)
.maybeSingle();
expect(invite).toBeNull();
expect(mockSendMail).toHaveBeenCalledTimes(1);
expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain(`/tablo/${adminTabloId}`);
});
it("rejects emails already used by a main-app account", async () => {
const res = await postInvite(ownerUser, adminTabloId, ownerUser.email);
expect(res.status).toBe(409);
const data = await res.json();
expect(data.error).toContain("already belongs");
});
it("rejects temporary users before admin check", async () => {
const res = await postInvite(tempUser, adminTabloId, testEmail);
expect(res.status).toBe(401);
});
it("should return 400 for an invalid email", async () => {
it("returns 400 for an invalid email", async () => {
const res = await postInvite(ownerUser, adminTabloId, "not-an-email");
expect(res.status).toBe(400);
const data = await res.json();
expect(data.error).toContain("valid email");
});
it("should return 400 for a missing email", async () => {
it("returns 400 for a missing email", async () => {
const res = client["client-invites"][":tabloId"].$post(
{ param: { tabloId: adminTabloId }, json: {} },
{ headers: { Authorization: `Bearer ${ownerUser.accessToken}` } }
@ -164,7 +235,7 @@ describe("Client Invites Endpoints", () => {
expect((await res).status).toBe(400);
});
it("should return 401 for unauthenticated requests", async () => {
it("returns 401 for unauthenticated requests", async () => {
const res = await client["client-invites"][":tabloId"].$post({
param: { tabloId: adminTabloId },
json: { email: testEmail },
@ -174,54 +245,50 @@ describe("Client Invites Endpoints", () => {
});
// ════════════════════════════════════════════════════════════════════════════
// POST /accept/:token — Accept a client invite
// GET/POST /setup/:token — Validate and complete a client setup invite
// ════════════════════════════════════════════════════════════════════════════
describe("POST /client-invites/accept/:token", () => {
it("should accept an invite and return tabloId", async () => {
const token = `test_accept_valid_${Date.now()}`;
describe("GET/POST /client-invites/setup/:token", () => {
const setupEmail = "test_client_setup@example.com";
// Insert invite for the owner user's email
beforeEach(async () => {
await cleanupInvitesByEmail(setupEmail);
});
it("returns invite metadata for a valid pending setup token", async () => {
const token = `test_setup_valid_${Date.now()}`;
await insertClientInvite({
tabloId: adminTabloId,
invitedEmail: ownerUser.email,
invitedEmail: setupEmail,
invitedBy: ownerUser.userId,
token,
});
try {
const res = await acceptInvite(ownerUser, token);
const res = await getSetupInvite(token);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.success).toBe(true);
expect(data.email).toBe(setupEmail);
expect(data.tabloId).toBe(adminTabloId);
// Verify invite is now not pending
const { data: invite } = await supabaseAdmin
.from("client_invites")
.select("is_pending")
.eq("invite_token", token)
.single();
expect(invite?.is_pending).toBe(false);
} finally {
await supabaseAdmin.from("client_invites").delete().eq("invite_token", token);
}
});
it("should return 410 for an expired invite", async () => {
it("returns 410 for an expired invite", async () => {
const token = `test_expired_${Date.now()}`;
const pastDate = new Date(Date.now() - 1000).toISOString(); // already expired
const pastDate = new Date(Date.now() - 1000).toISOString();
await insertClientInvite({
tabloId: adminTabloId,
invitedEmail: ownerUser.email,
invitedEmail: setupEmail,
invitedBy: ownerUser.userId,
token,
expiresAt: pastDate,
});
try {
const res = await acceptInvite(ownerUser, token);
const res = await getSetupInvite(token);
expect(res.status).toBe(410);
const data = await res.json();
expect(data.error).toContain("expired");
@ -230,35 +297,50 @@ describe("Client Invites Endpoints", () => {
}
});
it("should return 403 when email does not match the authenticated user", async () => {
const token = `test_email_mismatch_${Date.now()}`;
// Invite is for tempUser's email but we authenticate as ownerUser
it("completes password setup once and rejects reuse", async () => {
const token = `test_setup_complete_${Date.now()}`;
await createClientAccount(setupEmail);
await insertClientInvite({
tabloId: adminTabloId,
invitedEmail: tempUser.email,
invitedEmail: setupEmail,
invitedBy: ownerUser.userId,
token,
});
try {
const res = await acceptInvite(ownerUser, token); // wrong user
expect(res.status).toBe(403);
const res = await completeSetupInvite(token, "new_password_123");
expect(res.status).toBe(200);
const data = await res.json();
expect(data.success).toBe(true);
expect(data.email).toBe(setupEmail);
expect(data.tabloId).toBe(adminTabloId);
const reused = await completeSetupInvite(token, "new_password_456");
expect(reused.status).toBe(404);
} finally {
await supabaseAdmin.from("client_invites").delete().eq("invite_token", token);
}
});
it("should return 404 for a non-existent token", async () => {
const res = await acceptInvite(ownerUser, "nonexistent_token_xyz");
it("returns 404 for a non-existent token", async () => {
const res = await getSetupInvite("nonexistent_token_xyz");
expect(res.status).toBe(404);
});
it("should return 401 for unauthenticated requests", async () => {
const res = await client["client-invites"].accept[":token"].$post({
param: { token: "some_token" },
it("marks cancelled pending setup tokens unusable", async () => {
const token = `test_setup_cancelled_${Date.now()}`;
const inviteId = await insertClientInvite({
tabloId: adminTabloId,
invitedEmail: setupEmail,
invitedBy: ownerUser.userId,
token,
});
expect(res.status).toBe(401);
const cancelRes = await deleteInvite(ownerUser, adminTabloId, inviteId);
expect(cancelRes.status).toBe(200);
const res = await getSetupInvite(token);
expect(res.status).toBe(404);
});
});
@ -280,7 +362,7 @@ describe("Client Invites Endpoints", () => {
});
});
it("should return pending invites for an admin", async () => {
it("returns pending invites for an admin", async () => {
const res = await getPending(ownerUser, adminTabloId);
expect(res.status).toBe(200);
const data = await res.json();
@ -292,12 +374,12 @@ describe("Client Invites Endpoints", () => {
expect(found.is_pending).toBe(true);
});
it("should return 401 for a temporary user before admin check", async () => {
it("returns 401 for a temporary user before admin check", async () => {
const res = await getPending(tempUser, adminTabloId);
expect(res.status).toBe(401);
});
it("should return 401 for unauthenticated requests", async () => {
it("returns 401 for unauthenticated requests", async () => {
const res = await client["client-invites"][":tabloId"].pending.$get({
param: { tabloId: adminTabloId },
});
@ -316,8 +398,7 @@ describe("Client Invites Endpoints", () => {
await cleanupInvitesByEmail(cancelEmail);
});
it("should cancel a pending invite and revoke client access", async () => {
// First create a client user and tablo_access entry via the API
it("cancels a pending invite and revokes client access", async () => {
const token = `test_cancel_${Date.now()}`;
const inviteId = await insertClientInvite({
tabloId: adminTabloId,
@ -326,14 +407,11 @@ describe("Client Invites Endpoints", () => {
token,
});
// Create a mock profile to revoke (uses admin client to simulate client user existing)
// We'll skip verifying the user's actual auth account since we just need to test cancellation
const res = await deleteInvite(ownerUser, adminTabloId, inviteId);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.success).toBe(true);
// Verify invite is now not pending
const { data: invite } = await supabaseAdmin
.from("client_invites")
.select("is_pending")
@ -342,7 +420,7 @@ describe("Client Invites Endpoints", () => {
expect(invite?.is_pending).toBe(false);
});
it("should return 401 for a temporary user before admin check", async () => {
it("returns 401 for a temporary user before admin check", async () => {
const token = `test_cancel_nonadmin_${Date.now()}`;
const inviteId = await insertClientInvite({
tabloId: adminTabloId,
@ -355,19 +433,19 @@ describe("Client Invites Endpoints", () => {
expect(res.status).toBe(401);
});
it("should return 404 for a non-existent invite", async () => {
it("returns 404 for a non-existent invite", async () => {
const res = await deleteInvite(ownerUser, adminTabloId, 999999);
expect(res.status).toBe(404);
});
it("should return 400 for an already-cancelled invite", async () => {
it("returns 400 for an already-cancelled invite", async () => {
const token = `test_cancel_already_${Date.now()}`;
const inviteId = await insertClientInvite({
tabloId: adminTabloId,
invitedEmail: cancelEmail,
invitedBy: ownerUser.userId,
token,
isPending: false, // already cancelled
isPending: false,
});
const res = await deleteInvite(ownerUser, adminTabloId, inviteId);
@ -376,7 +454,7 @@ describe("Client Invites Endpoints", () => {
expect(data.error).toContain("pending");
});
it("should return 401 for unauthenticated requests", async () => {
it("returns 401 for unauthenticated requests", async () => {
const res = await client["client-invites"][":tabloId"][":inviteId"].$delete({
param: { tabloId: adminTabloId, inviteId: "1" },
});

View file

@ -1,5 +1,5 @@
import { createClient } from "@supabase/supabase-js";
import { randomUUID } from "node:crypto";
import { createClient } from "@supabase/supabase-js";
import { testClient } from "hono/testing";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createConfig } from "../../config.js";

View file

@ -85,10 +85,7 @@ export function createConfig(secrets?: Secrets): AppConfig {
? validateEnvVar("STRIPE_WEBHOOK_SECRET", process.env.STRIPE_WEBHOOK_SECRET)
: getStripeWebhookSecretFromEnv() || getStripeWebhookSecret(isStagingMode),
STRIPE_SOLO_PRICE_ID: validateEnvVar("STRIPE_SOLO_PRICE_ID", process.env.STRIPE_SOLO_PRICE_ID),
STRIPE_TEAM_PRICE_ID: validateEnvVar(
"STRIPE_TEAM_PRICE_ID",
process.env.STRIPE_TEAM_PRICE_ID
),
STRIPE_TEAM_PRICE_ID: validateEnvVar("STRIPE_TEAM_PRICE_ID", process.env.STRIPE_TEAM_PRICE_ID),
STRIPE_FOUNDER_PRICE_ID: validateEnvVar(
"STRIPE_FOUNDER_PRICE_ID",
process.env.STRIPE_FOUNDER_PRICE_ID

View file

@ -364,67 +364,196 @@ export const createInvitedUser = async (
return { success: true, userId: newUser.user.id };
};
/**
* Creates or finds a client user, marks them as is_client, and grants tablo access.
*/
export async function createClientUser(
supabase: SupabaseClient,
recipientEmail: string,
tabloId: string,
grantedBy: string
): Promise<{ success: boolean; error?: string; userId?: string }> {
// Check if user already exists
const { data: existingUsersData } = await supabase.auth.admin.listUsers();
type ClientAccount = {
email: string;
is_client: boolean;
client_onboarded_at: string | null;
userId: string;
};
type ClientAccountResult =
| { success: true; account: ClientAccount; wasCreated: boolean }
| { success: false; error: string };
const getAuthUserByEmail = async (supabase: SupabaseClient, email: string) => {
const { data: existingUsersData, error } = await supabase.auth.admin.listUsers();
if (error) {
return { user: null, error: error.message };
}
// biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime
const existingUsers = existingUsersData as any;
const existingUser = existingUsers?.users?.find(
// biome-ignore lint/suspicious/noExplicitAny: admin user type
(u: any) => u.email?.toLowerCase() === recipientEmail.toLowerCase()
(u: any) => u.email?.toLowerCase() === email.toLowerCase()
);
let userId: string;
return { user: existingUser ?? null, error: null };
};
if (existingUser) {
userId = existingUser.id;
// Mark as client if not already
await supabase
.from("profiles")
.update({ is_client: true })
.eq("id", userId)
.eq("is_client", false);
} else {
// Create new auth user (no password — magic link only)
const { data: authData, error: authError } = await supabase.auth.admin.createUser({
email: recipientEmail,
email_confirm: true,
user_metadata: { role: "client" },
});
if (authError || !authData?.user) {
return { success: false, error: authError?.message ?? "Failed to create user" };
}
userId = authData.user.id;
await supabase.from("profiles").update({ is_client: true }).eq("id", userId);
export async function hasCompletedClientOnboarding(
supabase: SupabaseClient,
userId: string
): Promise<{ completed: boolean; error?: string }> {
const { data: profile, error } = await supabase
.from("profiles")
.select("client_onboarded_at")
.eq("id", userId)
.maybeSingle();
if (error) {
return { completed: false, error: error.message };
}
// Grant tablo access if not already granted
const { data: existingAccess } = await supabase
return { completed: !!profile?.client_onboarded_at };
}
export async function findOrCreateClientAccount(
supabase: SupabaseClient,
recipientEmail: string
): Promise<ClientAccountResult> {
const normalizedEmail = recipientEmail.trim().toLowerCase();
const { user: existingUser, error: lookupError } = await getAuthUserByEmail(
supabase,
normalizedEmail
);
if (lookupError) {
return { success: false, error: lookupError };
}
if (existingUser) {
const { data: existingProfile, error: profileError } = await supabase
.from("profiles")
.select("email, is_client, client_onboarded_at")
.eq("id", existingUser.id)
.maybeSingle();
if (profileError) {
return { success: false, error: profileError.message };
}
if (!existingProfile) {
return { success: false, error: "Client profile not found" };
}
if (!existingProfile.is_client) {
return {
success: false,
error: "This email already belongs to a main app account",
};
}
return {
success: true,
wasCreated: false,
account: {
email: existingProfile.email ?? normalizedEmail,
is_client: existingProfile.is_client,
client_onboarded_at: existingProfile.client_onboarded_at,
userId: existingUser.id,
},
};
}
const { data: authData, error: authError } = await supabase.auth.admin.createUser({
email: normalizedEmail,
email_confirm: true,
user_metadata: { role: "client" },
});
if (authError || !authData?.user) {
return { success: false, error: authError?.message ?? "Failed to create client user" };
}
const { error: updateProfileError } = await supabase
.from("profiles")
.update({ is_client: true, client_onboarded_at: null })
.eq("id", authData.user.id);
if (updateProfileError) {
return { success: false, error: updateProfileError.message };
}
return {
success: true,
wasCreated: true,
account: {
email: normalizedEmail,
is_client: true,
client_onboarded_at: null,
userId: authData.user.id,
},
};
}
export async function ensureClientTabloAccess(
supabase: SupabaseClient,
tabloId: string,
userId: string,
grantedBy: string
): Promise<{ success: boolean; error?: string }> {
const { data: existingAccess, error: accessError } = await supabase
.from("tablo_access")
.select("id, is_active")
.eq("tablo_id", tabloId)
.eq("user_id", userId)
.single();
.maybeSingle();
if (accessError) {
return { success: false, error: accessError.message };
}
if (!existingAccess) {
await supabase.from("tablo_access").insert({
const { error: insertError } = await supabase.from("tablo_access").insert({
tablo_id: tabloId,
user_id: userId,
granted_by: grantedBy,
is_admin: false,
is_active: true,
});
} else if (!existingAccess.is_active) {
await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id);
if (insertError) {
return { success: false, error: insertError.message };
}
return { success: true };
}
return { success: true, userId };
if (!existingAccess.is_active) {
const { error: updateError } = await supabase
.from("tablo_access")
.update({ is_active: true })
.eq("id", existingAccess.id);
if (updateError) {
return { success: false, error: updateError.message };
}
}
return { success: true };
}
export async function createClientSetupInvite(
supabase: SupabaseClient,
input: {
tabloId: string;
invitedEmail: string;
invitedBy: string;
token: string;
expiresAt: string;
}
): Promise<{ success: boolean; error?: string }> {
const { error } = await supabase.from("client_invites").insert({
tablo_id: input.tabloId,
invited_email: input.invitedEmail,
invited_by: input.invitedBy,
invite_token: input.token,
invite_type: "setup",
is_pending: true,
expires_at: input.expiresAt,
});
if (error) {
return { success: false, error: error.message };
}
return { success: true };
}

View file

@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { resizeOrgIcon, buildOrgIconKey, ICON_SIZES, ORG_ICONS_BUCKET } from "./orgIcons.js";
import { describe, expect, it } from "vitest";
import { buildOrgIconKey, ICON_SIZES, resizeOrgIcon } from "./orgIcons.js";
describe("buildOrgIconKey", () => {
it("builds the correct R2 key for a given org and size", () => {
@ -32,7 +32,12 @@ describe("resizeOrgIcon", () => {
it("returns buffers for all required sizes from a valid PNG input", async () => {
const sharp = (await import("sharp")).default;
const input = await sharp({
create: { width: 512, height: 512, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 1 } },
create: {
width: 512,
height: 512,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 1 },
},
})
.png()
.toBuffer();
@ -49,7 +54,12 @@ describe("resizeOrgIcon", () => {
it("rejects images smaller than 512x512", async () => {
const sharp = (await import("sharp")).default;
const tooSmall = await sharp({
create: { width: 256, height: 256, channels: 4, background: { r: 0, g: 0, b: 255, alpha: 1 } },
create: {
width: 256,
height: 256,
channels: 4,
background: { r: 0, g: 0, b: 255, alpha: 1 },
},
})
.png()
.toBuffer();

View file

@ -1,19 +1,97 @@
import { Hono } from "hono";
import { createFactory } from "hono/factory";
import { checkTabloAdmin, createClientUser } from "../helpers/helpers.js";
import {
checkTabloAdmin,
createClientSetupInvite,
ensureClientTabloAccess,
findOrCreateClientAccount,
} from "../helpers/helpers.js";
import { generateToken } from "../helpers/token.js";
import { MiddlewareManager } from "../middlewares/middleware.js";
import type { AuthEnv } from "../types/app.types.js";
import type { AuthEnv, BaseEnv } from "../types/app.types.js";
const factory = createFactory<AuthEnv>();
const authFactory = createFactory<AuthEnv>();
const publicFactory = createFactory<BaseEnv>();
const CLIENT_INVITE_EXPIRY_HOURS = 72;
const getClientsUrl = () => process.env.CLIENTS_URL || "https://clients.xtablo.com";
const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
const findInviteByToken = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) =>
supabase
.from("client_invites")
.select(
"id, tablo_id, invited_email, invited_by, invite_type, is_pending, expires_at, used_at, cancelled_at, setup_completed_at"
)
.eq("invite_token", token)
.maybeSingle();
const validateSetupInvite = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) => {
const { data: invite, error } = await findInviteByToken(token, supabase);
if (error) {
return { status: 500 as const, body: { error: error.message } };
}
if (!invite || invite.invite_type !== "setup" || !invite.is_pending) {
return { status: 404 as const, body: { error: "Invite not found or already used" } };
}
if (invite.cancelled_at || invite.used_at || invite.setup_completed_at) {
return { status: 404 as const, body: { error: "Invite not found or already used" } };
}
if (invite.expires_at && new Date(invite.expires_at) < new Date()) {
return { status: 410 as const, body: { error: "This invite has expired" } };
}
return { status: 200 as const, invite };
};
const sendSetupEmail = async (
transporter: BaseEnv["Variables"]["transporter"],
input: { email: string; setupUrl: string }
) => {
await transporter.sendMail({
from: "Xtablo <noreply@xtablo.com>",
to: input.email,
subject: "Configurez votre accès client Xtablo",
html: `
<h2>Vous avez é invité sur Xtablo</h2>
<p>Bonjour,</p>
<p>Créez votre mot de passe via le lien ci-dessous pour accéder à votre espace client :</p>
<p><a href="${input.setupUrl}">Configurer mon mot de passe</a></p>
<p>Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures et ne peut être utilisé qu'une seule fois.</p>
`,
});
};
const sendAccessNotificationEmail = async (
transporter: BaseEnv["Variables"]["transporter"],
input: { email: string; tabloUrl: string }
) => {
await transporter.sendMail({
from: "Xtablo <noreply@xtablo.com>",
to: input.email,
subject: "Vous avez maintenant accès à un nouveau tablo",
html: `
<h2>Vous avez maintenant accès à un tablo</h2>
<p>Bonjour,</p>
<p>Votre accès a é ajouté. Utilisez le lien ci-dessous pour ouvrir directement le tablo :</p>
<p><a href="${input.tabloUrl}">Ouvrir le tablo</a></p>
<p>Si vous n'êtes pas connecté, vous serez redirigé vers la page de connexion.</p>
`,
});
};
/** POST /:tabloId — Create a client invite (admin only) */
const createClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
const user = c.get("user");
const supabase = c.get("supabase");
const transporter = c.get("transporter");
const tabloId = c.req.param("tabloId");
const body = await c.req.json();
@ -21,14 +99,42 @@ const createClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
.trim()
.toLowerCase();
if (!rawEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(rawEmail)) {
if (!rawEmail || !isValidEmail(rawEmail)) {
return c.json({ error: "A valid email is required" }, 400);
}
// Create / find the client user and grant tablo access
const result = await createClientUser(supabase, rawEmail, tabloId, user.id);
if (!result.success || !result.userId) {
return c.json({ error: result.error ?? "Failed to create client user" }, 500);
const accountResult = await findOrCreateClientAccount(supabase, rawEmail);
if ("error" in accountResult) {
const errorMessage = accountResult.error;
if (errorMessage.includes("already belongs")) {
return c.json({ error: errorMessage }, 409);
}
return c.json({ error: errorMessage }, 500);
}
const accessResult = await ensureClientTabloAccess(
supabase,
tabloId,
accountResult.account.userId,
user.id
);
if (!accessResult.success) {
return c.json({ error: accessResult.error ?? "Failed to grant client access" }, 500);
}
const clientsUrl = getClientsUrl();
if (accountResult.account.client_onboarded_at) {
try {
await sendAccessNotificationEmail(transporter, {
email: rawEmail,
tabloUrl: `${clientsUrl}/tablo/${tabloId}`,
});
} catch (emailError) {
console.error("Failed to send client access notification email:", emailError);
}
return c.json({ success: true, inviteMode: "notification" as const });
}
const token = generateToken();
@ -36,127 +142,134 @@ const createClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
Date.now() + CLIENT_INVITE_EXPIRY_HOURS * 60 * 60 * 1000
).toISOString();
const { error: insertError } = await supabase.from("client_invites").insert({
tablo_id: tabloId,
invited_email: rawEmail,
invited_by: user.id,
invite_token: token,
is_pending: true,
expires_at: expiresAt,
const inviteResult = await createClientSetupInvite(supabase, {
tabloId,
invitedEmail: rawEmail,
invitedBy: user.id,
token,
expiresAt,
});
if (insertError) {
if (insertError.code === "23505") {
if (!inviteResult.success) {
if (inviteResult.error?.includes("idx_client_invites_pending_setup_email_tablo")) {
return c.json({ error: "A pending invite already exists for this email and tablo" }, 409);
}
return c.json({ error: insertError.message }, 500);
return c.json({ error: inviteResult.error ?? "Failed to create setup invite" }, 500);
}
// Generate a Supabase magic link that redirects to the client portal callback
const clientsUrl = process.env.CLIENTS_URL || "https://clients.xtablo.com";
const redirectTo = `${clientsUrl}/auth/callback?token=${encodeURIComponent(token)}`;
const { data: linkData, error: magicLinkError } = await supabase.auth.admin.generateLink({
type: "magiclink",
email: rawEmail,
options: { redirectTo },
});
if (magicLinkError) {
console.error("Failed to generate magic link:", magicLinkError);
// Non-fatal: invite record is already created
} else if (linkData?.properties?.action_link) {
const transporter = c.get("transporter");
try {
await transporter.sendMail({
from: "Xtablo <noreply@xtablo.com>",
to: rawEmail,
subject: "Vous avez été invité sur Xtablo",
html: `
<h2>Vous avez é invité à collaborer sur un tablo</h2>
<p>Bonjour,</p>
<p>Cliquez sur le lien ci-dessous pour accéder à votre espace client :</p>
<p><a href="${linkData.properties.action_link}">Accéder à mon espace</a></p>
<p>Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures.</p>
`,
});
} catch (emailError) {
console.error("Failed to send client invite email:", emailError);
}
try {
await sendSetupEmail(transporter, {
email: rawEmail,
setupUrl: `${clientsUrl}/set-password?token=${encodeURIComponent(token)}`,
});
} catch (emailError) {
console.error("Failed to send client setup email:", emailError);
}
return c.json({ success: true });
return c.json({ success: true, inviteMode: "setup" as const });
});
/** POST /accept/:token — Accept a client invite */
const acceptClientInvite = (_middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
factory.createHandlers(async (c) => {
const user = c.get("user");
/** GET /setup/:token — Validate a setup invite token */
const getSetupInvite = () =>
publicFactory.createHandlers(async (c) => {
const supabase = c.get("supabase");
const token = c.req.param("token");
const { data: invite, error: inviteError } = await supabase
const validation = await validateSetupInvite(token, supabase);
if (validation.status !== 200) {
return c.json(validation.body, validation.status);
}
return c.json({
email: validation.invite.invited_email,
tabloId: validation.invite.tablo_id,
});
});
/** POST /setup/:token — Complete one-time password setup */
const completeSetupInvite = () =>
publicFactory.createHandlers(async (c) => {
const supabase = c.get("supabase");
const token = c.req.param("token");
const body = await c.req.json();
const password = String(body.password || "");
if (password.length < 8) {
return c.json({ error: "Password must be at least 8 characters long" }, 400);
}
const validation = await validateSetupInvite(token, supabase);
if (validation.status !== 200) {
return c.json(validation.body, validation.status);
}
const invite = validation.invite;
const { data: usersData, error: listUsersError } = await supabase.auth.admin.listUsers();
if (listUsersError) {
return c.json({ error: listUsersError.message }, 500);
}
// biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime
const users = usersData as any;
// biome-ignore lint/suspicious/noExplicitAny: admin user type
const clientUser = users?.users?.find((candidate: any) => {
return candidate.email?.toLowerCase() === invite.invited_email?.toLowerCase();
});
if (!clientUser?.id) {
return c.json({ error: "Client account not found" }, 404);
}
const { error: updateUserError } = await supabase.auth.admin.updateUserById(clientUser.id, {
password,
});
if (updateUserError) {
return c.json({ error: updateUserError.message }, 500);
}
const completedAt = new Date().toISOString();
const { error: updateProfileError } = await supabase
.from("profiles")
.update({ client_onboarded_at: completedAt, is_client: true })
.eq("id", clientUser.id);
if (updateProfileError) {
return c.json({ error: updateProfileError.message }, 500);
}
const { error: consumeInviteError } = await supabase
.from("client_invites")
.select("id, tablo_id, invited_email, invited_by, is_pending, expires_at")
.eq("invite_token", token)
.maybeSingle();
if (inviteError) {
return c.json({ error: inviteError.message }, 500);
.update({
is_pending: false,
used_at: completedAt,
setup_completed_at: completedAt,
})
.eq("id", invite.id)
.eq("is_pending", true);
if (consumeInviteError) {
return c.json({ error: consumeInviteError.message }, 500);
}
if (!invite || !invite.is_pending) {
return c.json({ error: "Invite not found or already used" }, 404);
}
// Check expiration
if (invite.expires_at && new Date(invite.expires_at) < new Date()) {
return c.json({ error: "This invite has expired" }, 410);
}
// Email must match the authenticated user
if (invite.invited_email?.toLowerCase() !== user.email?.toLowerCase()) {
return c.json({ error: "This invite was not issued to your account" }, 403);
}
// Mark invite as accepted
await supabase.from("client_invites").update({ is_pending: false }).eq("id", invite.id);
// Ensure tablo access is active
const { data: existingAccess } = await supabase
.from("tablo_access")
.select("id, is_active")
.eq("tablo_id", invite.tablo_id)
.eq("user_id", user.id)
.maybeSingle();
if (!existingAccess) {
await supabase.from("tablo_access").insert({
tablo_id: invite.tablo_id,
user_id: user.id,
granted_by: invite.invited_by,
is_admin: false,
is_active: true,
});
} else if (!existingAccess.is_active) {
await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id);
}
return c.json({ success: true, tabloId: invite.tablo_id });
return c.json({
success: true,
email: invite.invited_email,
tabloId: invite.tablo_id,
});
});
/** GET /:tabloId/pending — List pending client invites (admin only) */
const getPendingClientInvites = (
middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>
) =>
factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
const supabase = c.get("supabase");
const tabloId = c.req.param("tabloId");
const { data: invites, error } = await supabase
.from("client_invites")
.select("id, invited_email, expires_at, is_pending, created_at")
.select("id, invited_email, expires_at, is_pending, created_at, invite_type")
.eq("tablo_id", tabloId)
.eq("invite_type", "setup")
.eq("is_pending", true)
.order("created_at", { ascending: false });
@ -169,7 +282,7 @@ const getPendingClientInvites = (
/** DELETE /:tabloId/:inviteId — Cancel a client invite (admin only) */
const cancelClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
const supabase = c.get("supabase");
const tabloId = c.req.param("tabloId");
const inviteId = Number(c.req.param("inviteId"));
@ -180,7 +293,7 @@ const cancelClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
const { data: invite, error: inviteError } = await supabase
.from("client_invites")
.select("id, invited_email, is_pending")
.select("id, invited_email, is_pending, invite_type")
.eq("id", inviteId)
.eq("tablo_id", tabloId)
.maybeSingle();
@ -197,10 +310,10 @@ const cancelClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
return c.json({ error: "Invite is no longer pending" }, 400);
}
// Mark invite as cancelled
const cancelledAt = new Date().toISOString();
const { error: cancelError } = await supabase
.from("client_invites")
.update({ is_pending: false })
.update({ is_pending: false, cancelled_at: cancelledAt })
.eq("id", inviteId)
.eq("tablo_id", tabloId);
@ -208,7 +321,6 @@ const cancelClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
return c.json({ error: cancelError.message }, 500);
}
// Revoke tablo access for the client user
if (invite.invited_email) {
const { data: clientProfile } = await supabase
.from("profiles")
@ -233,9 +345,17 @@ export const getClientInvitesRouter = () => {
const middlewareManager = MiddlewareManager.getInstance();
router.post("/:tabloId", ...createClientInvite(middlewareManager));
router.post("/accept/:token", ...acceptClientInvite(middlewareManager));
router.get("/:tabloId/pending", ...getPendingClientInvites(middlewareManager));
router.delete("/:tabloId/:inviteId", ...cancelClientInvite(middlewareManager));
return router;
};
export const getPublicClientInvitesRouter = () => {
const router = new Hono<BaseEnv>();
router.get("/setup/:token", ...getSetupInvite());
router.post("/setup/:token", ...completeSetupInvite());
return router;
};

View file

@ -3,6 +3,7 @@ import type { AppConfig } from "../config.js";
import { MiddlewareManager } from "../middlewares/middleware.js";
import type { BaseEnv } from "../types/app.types.js";
import { getAuthenticatedRouter } from "./authRouter.js";
import { getPublicClientInvitesRouter } from "./clientInvites.js";
import { getMaybeAuthenticatedRouter } from "./maybeAuthRouter.js";
import { getPublicRouter } from "./public.js";
import { getStripeWebhookRouter } from "./stripe.js";
@ -31,6 +32,9 @@ export const getMainRouter = (config: AppConfig) => {
// webhooks
mainRouter.route("/stripe-webhook", getStripeWebhookRouter());
// public client onboarding routes
mainRouter.route("/client-invites", getPublicClientInvitesRouter());
// maybe authenticated routes (checked first to allow unauthenticated booking)
mainRouter.route("/", getMaybeAuthenticatedRouter());

View file

@ -28,44 +28,44 @@ const createTablo = (middlewareManager: ReturnType<typeof MiddlewareManager.getI
const supabase = c.get("supabase");
const data = await c.req.json();
const typedPayload = data as PostTablo;
const typedPayload = data as PostTablo;
const { data: profile, error: profileError } = await supabase
.from("profiles")
.select("organization_id")
.eq("id", user.id)
.single();
const { data: profile, error: profileError } = await supabase
.from("profiles")
.select("organization_id")
.eq("id", user.id)
.single();
if (profileError || !profile?.organization_id) {
return c.json({ error: "Failed to resolve your organization" }, 500);
}
if (profileError || !profile?.organization_id) {
return c.json({ error: "Failed to resolve your organization" }, 500);
}
const { data: insertedTablo, error } = await supabase
.from("tablos")
.insert({
...typedPayload,
owner_id: user.id,
organization_id: profile.organization_id,
events: undefined,
})
.select()
.single();
const { data: insertedTablo, error } = await supabase
.from("tablos")
.insert({
...typedPayload,
owner_id: user.id,
organization_id: profile.organization_id,
events: undefined,
})
.select()
.single();
if (error) {
return c.json({ error: error.message }, 500);
}
if (error) {
return c.json({ error: error.message }, 500);
}
const tabloData = insertedTablo as Tables<"tablos">;
const tabloData = insertedTablo as Tables<"tablos">;
if (typedPayload.events) {
const eventsToInsert = typedPayload.events.map((event) => ({
...event,
tablo_id: tabloData.id,
created_by: user.id,
}));
if (typedPayload.events) {
const eventsToInsert = typedPayload.events.map((event) => ({
...event,
tablo_id: tabloData.id,
created_by: user.id,
}));
await supabase.from("events").insert(eventsToInsert);
}
await supabase.from("events").insert(eventsToInsert);
}
return c.json({ message: "Tablo created successfully", tablo: tabloData });
}
);
@ -90,12 +90,7 @@ const updateTablo = (middlewareManager: ReturnType<typeof MiddlewareManager.getI
return c.json({ error: "You are not authorized to update this tablo" }, 403);
}
const { error } = await supabase
.from("tablos")
.update(tablo)
.eq("id", id)
.select()
.single();
const { error } = await supabase.from("tablos").update(tablo).eq("id", id).select().single();
if (error) {
return c.json({ error: error.message }, 500);
@ -213,13 +208,9 @@ const inviteToTablo = (
if (!recipientUser) {
// Create a new invited user and add them to the tablo
const result = await createInvitedUser(
supabase,
transporter,
recipientEmail,
sender.email,
{ isTemporary: true }
);
const result = await createInvitedUser(supabase, transporter, recipientEmail, sender.email, {
isTemporary: true,
});
if (!result.success) {
return c.json({ error: result.error }, 500);

View file

@ -147,47 +147,47 @@ const getTabloFile = factory.createHandlers(checkTabloMember, async (c) => {
const postTabloFile = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
factory.createHandlers(checkTabloMember, async (c) => {
const tabloId = c.req.param("tabloId");
const user = c.get("user");
// Get the file path - supports both wildcard (*) and named parameter (:fileName)
const filePath = c.req.param("path") || c.req.param("fileName");
const tabloId = c.req.param("tabloId");
const user = c.get("user");
// Get the file path - supports both wildcard (*) and named parameter (:fileName)
const filePath = c.req.param("path") || c.req.param("fileName");
if (!filePath) {
return c.json({ error: "File path is required" }, 400);
}
const s3_client = c.get("s3_client");
try {
const body = await c.req.json();
const { content, contentType = "text/plain" } = body;
if (!content) {
return c.json({ error: "Content is required" }, 400);
if (!filePath) {
return c.json({ error: "File path is required" }, 400);
}
await s3_client.send(
new PutObjectCommand({
Bucket: "tablo-data",
Key: `${tabloId}/${filePath}`,
Body: content,
ContentType: contentType,
Metadata: {
"uploaded-by": user.id,
},
})
);
fileNamesCache.delete(tabloId);
const s3_client = c.get("s3_client");
return c.json({
message: "File uploaded successfully",
fileName: filePath,
tabloId,
});
} catch (error) {
console.error("Error uploading file:", error);
return c.json({ error: "Failed to upload file" }, 500);
}
try {
const body = await c.req.json();
const { content, contentType = "text/plain" } = body;
if (!content) {
return c.json({ error: "Content is required" }, 400);
}
await s3_client.send(
new PutObjectCommand({
Bucket: "tablo-data",
Key: `${tabloId}/${filePath}`,
Body: content,
ContentType: contentType,
Metadata: {
"uploaded-by": user.id,
},
})
);
fileNamesCache.delete(tabloId);
return c.json({
message: "File uploaded successfully",
fileName: filePath,
tabloId,
});
} catch (error) {
console.error("Error uploading file:", error);
return c.json({ error: "Failed to upload file" }, 500);
}
});
const deleteTabloFile = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
@ -336,10 +336,7 @@ const getTabloFolders = factory.createHandlers(checkTabloMember, async (c) => {
// POST /tablo-data/:tabloId/folders - Create a new folder (admin only)
const createTabloFolder = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
factory.createHandlers(
middlewareManager.regularUserCheck,
checkTabloAdmin,
async (c) => {
factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
const tabloId = c.req.param("tabloId");
const s3_client = c.get("s3_client");
const user = c.get("user");
@ -380,15 +377,11 @@ const createTabloFolder = (middlewareManager: ReturnType<typeof MiddlewareManage
console.error("Error creating folder:", error);
return c.json({ error: "Failed to create folder" }, 500);
}
}
);
});
// PUT /tablo-data/:tabloId/folders/:folderId - Update a folder (admin only)
const updateTabloFolder = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
factory.createHandlers(
middlewareManager.regularUserCheck,
checkTabloAdmin,
async (c) => {
factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
const tabloId = c.req.param("tabloId");
const folderId = c.req.param("folderId");
const s3_client = c.get("s3_client");
@ -433,15 +426,11 @@ const updateTabloFolder = (middlewareManager: ReturnType<typeof MiddlewareManage
console.error("Error updating folder:", error);
return c.json({ error: "Failed to update folder" }, 500);
}
}
);
});
// DELETE /tablo-data/:tabloId/folders/:folderId - Delete a folder (admin only)
const deleteTabloFolder = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
factory.createHandlers(
middlewareManager.regularUserCheck,
checkTabloAdmin,
async (c) => {
factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => {
const tabloId = c.req.param("tabloId");
const folderId = c.req.param("folderId");
const s3_client = c.get("s3_client");
@ -469,8 +458,7 @@ const deleteTabloFolder = (middlewareManager: ReturnType<typeof MiddlewareManage
console.error("Error deleting folder:", error);
return c.json({ error: "Failed to delete folder" }, 500);
}
}
);
});
// ============================================
// ROUTER SETUP

View file

@ -785,7 +785,6 @@ const removeOrganizationMember = factory.createHandlers(async (c) => {
if (removeAccessError) {
return c.json({ error: "Failed to revoke member tablo permissions" }, 500);
}
}
const { error: inviteCleanupError } = await supabase

View file

@ -10,12 +10,13 @@ export { ChatRoom };
const app = new Hono<{ Bindings: Env }>();
// CORS — allow the main app origins
// CORS — allow the web app origins that embed chat
app.use("*", cors({
origin: [
"http://localhost:5173",
"https://app.xtablo.com",
"https://app-staging.xtablo.com",
"https://clients.xtablo.com",
],
allowHeaders: ["Authorization", "Content-Type"],
allowMethods: ["GET", "POST", "OPTIONS"],

View file

@ -1,4 +1,7 @@
VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co
VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM
VITE_API_URL=https://xablo-api-636270553187.europe-west1.run.app
VITE_CHAT_WS_URL=wss://chat.xtablo.com
VITE_CHAT_API_URL=https://chat.xtablo.com
VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app

View file

@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Xtablo — Client Portal</title>
<title>Xtablo — Portail client</title>
</head>
<body>
<div id="client-root"></div>

View file

@ -39,6 +39,7 @@
},
"dependencies": {
"@tanstack/react-query": "^5.69.0",
"@xtablo/auth-ui": "workspace:*",
"@xtablo/shared": "workspace:*",
"@xtablo/shared-types": "workspace:*",
"@xtablo/tablo-views": "workspace:*",

View file

@ -0,0 +1,56 @@
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { useEffect, useState } from "react";
import { Navigate, Outlet, useLocation } from "react-router-dom";
import { supabase } from "../lib/supabase";
export function ClientAuthGate() {
const { session } = useSession();
const location = useLocation();
const [isCheckingSession, setIsCheckingSession] = useState(true);
const [hasSession, setHasSession] = useState(false);
useEffect(() => {
let isMounted = true;
if (session) {
setHasSession(true);
setIsCheckingSession(false);
return () => {
isMounted = false;
};
}
supabase.auth
.getSession()
.then(({ data }) => {
if (!isMounted) return;
setHasSession(Boolean(data.session));
})
.finally(() => {
if (isMounted) {
setIsCheckingSession(false);
}
});
return () => {
isMounted = false;
};
}, [session]);
if (session || hasSession) {
return <Outlet />;
}
if (isCheckingSession) {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
</div>
);
}
const redirectUrl = `${location.pathname}${location.search}${location.hash}`;
localStorage.setItem("clients.redirectUrl", redirectUrl);
return <Navigate to="/login" replace />;
}

View file

@ -1,9 +1,11 @@
import { screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import AppRoutes from "../routes";
import { renderWithProviders } from "../test/testHelpers";
import { ClientLayout } from "./ClientLayout";
describe("ClientLayout", () => {
it("uses the main app style header shell and centered content container", () => {
it("uses the main app style header shell and scrolling main viewport", () => {
const { container } = renderWithProviders(<ClientLayout />);
const header = container.querySelector("header");
@ -16,8 +18,26 @@ describe("ClientLayout", () => {
expect(headerInner).toHaveClass("mx-auto");
const main = container.querySelector("main");
expect(main).toHaveClass("w-full");
expect(main).toHaveClass("max-w-7xl");
expect(main).toHaveClass("mx-auto");
expect(main).toHaveClass("flex-1");
expect(main).toHaveClass("overflow-auto");
expect(main).not.toHaveClass("max-w-7xl");
expect(main).not.toHaveClass("mx-auto");
const contentWrapper = main?.firstElementChild;
expect(contentWrapper).toHaveClass("mx-auto");
expect(contentWrapper).toHaveClass("w-full");
expect(contentWrapper).toHaveClass("max-w-7xl");
expect(contentWrapper).toHaveClass("px-4");
expect(contentWrapper).toHaveClass("sm:px-6");
});
it("redirects unauthenticated client routes to the login page", async () => {
renderWithProviders(<AppRoutes />, {
route: "/tablo/tablo-1",
testUser: undefined,
});
expect(await screen.findByTestId("auth-card-shell")).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "Connexion" })).toBeInTheDocument();
});
});

View file

@ -14,19 +14,7 @@ function getInitials(email: string): string {
export function ClientLayout() {
const { session } = useSession();
if (!session) {
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center space-y-3">
<p className="text-lg font-medium text-foreground">Accès non autorisé</p>
<p className="text-sm text-muted-foreground">
Veuillez utiliser le lien reçu dans votre email pour accéder à cette page.
</p>
</div>
</div>
);
}
if (!session) return null;
const email = session.user.email ?? "";
const initials = email ? getInitials(email) : "?";
@ -36,7 +24,7 @@ export function ClientLayout() {
};
return (
<div className="flex min-h-screen flex-col bg-background">
<div className="flex h-screen flex-col overflow-hidden bg-background">
<header className="h-[75px] shrink-0 border-b border-[#EAECF0] bg-navbar-background dark:border-gray-700">
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between gap-4 px-4 sm:px-6">
<span className="text-lg font-semibold text-foreground">Xtablo</span>
@ -54,8 +42,10 @@ export function ClientLayout() {
</div>
</header>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6 sm:px-6">
<Outlet />
<main className="flex-1 overflow-auto">
<div className="mx-auto w-full max-w-7xl px-4 sm:px-6">
<Outlet />
</div>
</main>
</div>
);

View file

@ -0,0 +1,15 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const productionEnv = readFileSync(resolve(process.cwd(), ".env.production"), "utf8");
describe("clients production env", () => {
it("points the API URL to staging while client portal testing is in progress and keeps chat endpoints configured", () => {
expect(productionEnv).toContain(
"VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app"
);
expect(productionEnv).toContain("VITE_CHAT_API_URL=https://chat.xtablo.com");
expect(productionEnv).toContain("VITE_CHAT_WS_URL=wss://chat.xtablo.com");
});
});

View file

@ -1,21 +1,24 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import bookingEn from "./locales/en/booking.json";
import bookingFr from "./locales/fr/booking.json";
import authEn from "../../main/src/locales/en/auth.json";
import chatEn from "../../main/src/locales/en/chat.json";
import commonEn from "../../main/src/locales/en/common.json";
import componentsEn from "../../main/src/locales/en/components.json";
import pagesEn from "../../main/src/locales/en/pages.json";
import tabloEn from "../../main/src/locales/en/tablo.json";
import authFr from "../../main/src/locales/fr/auth.json";
import chatFr from "../../main/src/locales/fr/chat.json";
import commonFr from "../../main/src/locales/fr/common.json";
import componentsFr from "../../main/src/locales/fr/components.json";
import pagesFr from "../../main/src/locales/fr/pages.json";
import tabloFr from "../../main/src/locales/fr/tablo.json";
import bookingEn from "./locales/en/booking.json";
import bookingFr from "./locales/fr/booking.json";
i18n.use(initReactI18next).init({
resources: {
fr: {
auth: authFr,
booking: bookingFr,
chat: chatFr,
common: commonFr,
@ -24,6 +27,7 @@ i18n.use(initReactI18next).init({
tablo: tabloFr,
},
en: {
auth: authEn,
booking: bookingEn,
chat: chatEn,
common: commonEn,

View file

@ -1,19 +1,21 @@
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
import bookingEn from "./locales/en/booking.json";
// Import translation files
import bookingFr from "./locales/fr/booking.json";
import authEn from "../../main/src/locales/en/auth.json";
import chatEn from "../../main/src/locales/en/chat.json";
import commonEn from "../../main/src/locales/en/common.json";
import componentsEn from "../../main/src/locales/en/components.json";
import pagesEn from "../../main/src/locales/en/pages.json";
import tabloEn from "../../main/src/locales/en/tablo.json";
import authFr from "../../main/src/locales/fr/auth.json";
import chatFr from "../../main/src/locales/fr/chat.json";
import commonFr from "../../main/src/locales/fr/common.json";
import componentsFr from "../../main/src/locales/fr/components.json";
import pagesFr from "../../main/src/locales/fr/pages.json";
import tabloFr from "../../main/src/locales/fr/tablo.json";
import bookingEn from "./locales/en/booking.json";
// Import translation files
import bookingFr from "./locales/fr/booking.json";
i18n
.use(LanguageDetector)
@ -21,6 +23,7 @@ i18n
.init({
resources: {
fr: {
auth: authFr,
booking: bookingFr,
chat: chatFr,
common: commonFr,
@ -29,6 +32,7 @@ i18n
tablo: tabloFr,
},
en: {
auth: authEn,
booking: bookingEn,
chat: chatEn,
common: commonEn,

View file

@ -2,6 +2,8 @@
@import "tw-animate-css";
@source "../../../packages/chat-ui/src/**/*.{ts,tsx}";
@source "../../../packages/tablo-views/src/**/*.{ts,tsx}";
@source "../../../packages/auth-ui/src/**/*.{ts,tsx}";
@custom-variant dark (&:is(.dark *));

View file

@ -5,8 +5,10 @@ import { describe, expect, it } from "vitest";
const mainCss = readFileSync(resolve(process.cwd(), "src/main.css"), "utf8");
describe("clients main.css", () => {
it("keeps the chat source and theme tokens aligned with the main app", () => {
it("keeps shared package sources and theme tokens aligned with the main app", () => {
expect(mainCss).toContain('@source "../../../packages/chat-ui/src/**/*.{ts,tsx}";');
expect(mainCss).toContain('@source "../../../packages/tablo-views/src/**/*.{ts,tsx}";');
expect(mainCss).toContain('@source "../../../packages/auth-ui/src/**/*.{ts,tsx}";');
expect(mainCss).toContain("--navbar-background: rgb(249, 250, 251);");
expect(mainCss).toContain("--color-navbar-background: var(--navbar-background);");
expect(mainCss).toContain("--str-chat__own-message-bubble-color: #804eec;");

View file

@ -1,66 +1,5 @@
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { useEffect, useRef, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Navigate } from "react-router-dom";
export function AuthCallback() {
const [searchParams] = useSearchParams();
const token = searchParams.get("token");
const { session } = useSession();
const navigate = useNavigate();
const [error, setError] = useState<string | null>(null);
const hasAccepted = useRef(false);
useEffect(() => {
if (!session || !token || hasAccepted.current) {
return;
}
hasAccepted.current = true;
const apiUrl = import.meta.env.VITE_API_URL as string;
fetch(`${apiUrl}/api/v1/client-invites/accept/${token}`, {
method: "POST",
headers: {
Authorization: `Bearer ${session.access_token}`,
"Content-Type": "application/json",
},
})
.then(async (res) => {
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error((body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation");
}
return res.json() as Promise<{ tabloId: string }>;
})
.then((data) => {
navigate(`/tablo/${data.tabloId}`, { replace: true });
})
.catch((err: unknown) => {
console.error("Accept invite error:", err);
setError(
"Une erreur est survenue lors de l'acceptation de l'invitation. Veuillez contacter la personne qui vous a invité."
);
});
}, [session, token, navigate]);
if (error) {
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center space-y-3 max-w-md px-4">
<p className="text-lg font-medium text-destructive">Erreur</p>
<p className="text-sm text-muted-foreground">{error}</p>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center space-y-3">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto" />
<p className="text-sm text-muted-foreground">Authentification en cours...</p>
</div>
</div>
);
return <Navigate to="/login" replace />;
}

View file

@ -1,6 +1,6 @@
import { useQuery } from "@tanstack/react-query";
import type { UserTablo } from "@xtablo/shared-types";
import { Navigate, Link } from "react-router-dom";
import { Link, Navigate } from "react-router-dom";
import { supabase } from "../lib/supabase";
function useClientTablosList() {
@ -51,9 +51,7 @@ export function ClientTabloListPage() {
to={`/tablo/${tablo.id}`}
className="block p-5 rounded-lg border border-border bg-card hover:bg-muted/50 transition-colors space-y-2"
>
{tablo.color && (
<div className={`w-8 h-8 rounded-lg ${tablo.color}`} />
)}
{tablo.color && <div className={`w-8 h-8 rounded-lg ${tablo.color}`} />}
<h2 className="font-semibold text-foreground">{tablo.name}</h2>
</Link>
))}

View file

@ -1,14 +1,114 @@
import { screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../test/testHelpers";
import { ClientTabloPage } from "./ClientTabloPage";
const {
apiGetMock,
apiPostMock,
apiPutMock,
apiDeleteMock,
updateTaskMock,
insertTaskMock,
deleteTaskMock,
supabaseFromMock,
} = vi.hoisted(() => {
const apiGetMock = vi.fn(async (url: string) => {
if (url.endsWith("/brief.pdf")) {
return {
status: 200,
data: { content: "test file content", contentType: "application/pdf" },
};
}
return { status: 200, data: { folders: [] } };
});
const apiPostMock = vi.fn(async () => ({
status: 200,
data: {
message: "ok",
fileName: "brief.pdf",
tabloId: "tablo-1",
folder: { id: "folder-1", name: "Livrable", description: "" },
},
}));
const apiPutMock = vi.fn(async () => ({
status: 200,
data: { folder: { id: "folder-1", name: "Livrable mis à jour", description: "Desc" } },
}));
const apiDeleteMock = vi.fn(async () => ({ status: 200, data: { message: "ok" } }));
const createUpdateBuilder = () => {
const builder = {
error: null as null,
eq: vi.fn(() => builder),
select: vi.fn(() => ({
single: async () => ({ data: { id: "task-1" }, error: null }),
})),
};
return builder;
};
const updateTaskMock = vi.fn(() => createUpdateBuilder());
const insertTaskMock = vi.fn(() => ({
select: () => ({
single: async () => ({ data: { id: "task-created" }, error: null }),
}),
}));
const deleteTaskMock = vi.fn(() => ({
eq: vi.fn(async () => ({ error: null })),
}));
const supabaseFromMock = vi.fn(() => ({
insert: insertTaskMock,
update: updateTaskMock,
delete: deleteTaskMock,
}));
return {
apiGetMock,
apiPostMock,
apiPutMock,
apiDeleteMock,
updateTaskMock,
insertTaskMock,
deleteTaskMock,
supabaseFromMock,
};
});
let latestTabloTasksSectionProps: Record<string, unknown> | null = null;
let latestEtapesSectionProps: Record<string, unknown> | null = null;
let latestRoadmapSectionProps: Record<string, unknown> | null = null;
let latestTabloFilesSectionProps: Record<string, unknown> | null = null;
vi.mock("@xtablo/shared", async (importOriginal) => {
const actual = await importOriginal<typeof import("@xtablo/shared")>();
return {
...actual,
buildApi: () => ({
create: () => ({
get: apiGetMock,
post: apiPostMock,
put: apiPutMock,
delete: apiDeleteMock,
}),
}),
};
});
vi.mock("../lib/supabase", () => ({
supabase: {
from: supabaseFromMock,
},
}));
vi.mock("@tanstack/react-query", async (importOriginal) => {
const actual = await importOriginal<typeof import("@tanstack/react-query")>();
return {
...actual,
useQuery: ({ queryKey }: { queryKey: string[] }) => {
useQuery: ({ queryKey, queryFn }: { queryKey: string[]; queryFn?: () => Promise<unknown> }) => {
if (queryKey[0] === "client-tablo-folders" && queryFn) {
void queryFn();
}
switch (queryKey[0]) {
case "client-tablo":
return {
@ -84,16 +184,314 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => {
return {
...actual,
EtapesSection: () => <div>Etapes section</div>,
RoadmapSection: () => <div>Roadmap section</div>,
EtapesSection: (props: Record<string, unknown>) => {
latestEtapesSectionProps = props;
return (
<div>
<div>Etapes section</div>
<button
type="button"
onClick={() =>
(
props.onCreateTask as
| ((task: {
tablo_id: string;
title: string;
status: string;
parent_task_id: string;
is_parent: boolean;
position: number;
}) => void)
| undefined
)?.({
tablo_id: "tablo-1",
title: "Task from etape",
status: "todo",
parent_task_id: "etape-1",
is_parent: false,
position: 0,
})
}
>
Créer tâche d'étape test
</button>
<button
type="button"
onClick={() =>
(
props.onTaskStatusChange as ((taskId: string, status: string) => void) | undefined
)?.("task-1", "done")
}
>
Terminer tâche d'étape test
</button>
</div>
);
},
RoadmapSection: (props: Record<string, unknown>) => {
latestRoadmapSectionProps = props;
return (
<div>
<div>Roadmap section</div>
<button
type="button"
onClick={() =>
(
props.onTaskStatusChange as ((taskId: string, status: string) => void) | undefined
)?.("task-1", "done")
}
>
Changer statut roadmap test
</button>
</div>
);
},
TabloDiscussionSection: () => <div>Discussion section</div>,
TabloEventsSection: () => <div>Events section</div>,
TabloFilesSection: () => <div>Files section</div>,
TabloTasksSection: () => <div>Tasks section</div>,
TabloFilesSection: (props: Record<string, unknown>) => {
latestTabloFilesSectionProps = props;
return (
<div>
<div>Files section</div>
<button
type="button"
onClick={() =>
(
props.onCreateFile as
| ((params: {
tabloId: string;
fileName: string;
data: { content: string; contentType: string };
}) => void)
| undefined
)?.({
tabloId: "tablo-1",
fileName: "brief.pdf",
data: {
content: "data:application/pdf;base64,AAAA",
contentType: "application/pdf",
},
})
}
>
Créer fichier test
</button>
<button
type="button"
onClick={() =>
(
props.onDownloadFile as
| ((params: { tabloId: string; fileName: string }) => void)
| undefined
)?.({ tabloId: "tablo-1", fileName: "brief.pdf" })
}
>
Télécharger fichier test
</button>
<button
type="button"
onClick={() =>
(
props.onCreateFolder as
| ((params: {
tabloId: string;
name: string;
description: string;
createdBy: string;
}) => void)
| undefined
)?.({
tabloId: "tablo-1",
name: "Livrable",
description: "Desc",
createdBy: "client-user-1",
})
}
>
Créer livrable test
</button>
<button
type="button"
onClick={() =>
(
props.onUpdateFolder as
| ((params: {
tabloId: string;
folderId: string;
name: string;
description: string;
}) => void)
| undefined
)?.({
tabloId: "tablo-1",
folderId: "folder-1",
name: "Livrable mis à jour",
description: "Desc",
})
}
>
Modifier livrable test
</button>
<button
type="button"
onClick={() =>
(
props.onDeleteFolder as
| ((params: { tabloId: string; folderId: string; folderName: string }) => void)
| undefined
)?.({
tabloId: "tablo-1",
folderId: "folder-1",
folderName: "Livrable",
})
}
>
Supprimer livrable test
</button>
</div>
);
},
TabloTasksSection: (props: Record<string, unknown>) => {
latestTabloTasksSectionProps = props;
return (
<div>
<div>Tasks section</div>
<button
type="button"
onClick={() =>
(props.onCreateTask as ((task: Record<string, unknown>) => void) | undefined)?.({
tablo_id: "tablo-1",
title: "Task from tasks tab",
status: "todo",
position: 1,
parent_task_id: "etape-1",
is_parent: false,
})
}
>
Créer tâche test
</button>
<button
type="button"
onClick={() =>
(props.onUpdateTask as ((task: Record<string, unknown>) => void) | undefined)?.({
id: "task-1",
tablo_id: "tablo-1",
title: "Updated task title",
})
}
>
Modifier tâche test
</button>
<button
type="button"
onClick={() =>
(props.onDeleteTask as ((taskId: string) => void) | undefined)?.("task-1")
}
>
Supprimer tâche test
</button>
<button
type="button"
onClick={() =>
(
props.onUpdateTaskPositions as
| ((updates: Array<{ id: string; position: number; status: string }>) => void)
| undefined
)?.([{ id: "task-1", position: 7, status: "done" }])
}
>
Déplacer la tâche test
</button>
</div>
);
},
};
});
describe("ClientTabloPage parity shell", () => {
beforeEach(() => {
window.URL.createObjectURL = vi.fn(() => "blob:test");
window.URL.revokeObjectURL = vi.fn();
HTMLAnchorElement.prototype.click = vi.fn();
apiGetMock.mockClear();
apiPostMock.mockClear();
apiPutMock.mockClear();
apiDeleteMock.mockClear();
updateTaskMock.mockClear();
insertTaskMock.mockClear();
deleteTaskMock.mockClear();
supabaseFromMock.mockClear();
latestTabloTasksSectionProps = null;
latestEtapesSectionProps = null;
latestRoadmapSectionProps = null;
latestTabloFilesSectionProps = null;
});
it("requests folders from the tablo-data API route", () => {
renderWithProviders(<ClientTabloPage />, {
route: "/tablo/tablo-1",
path: "/tablo/:tabloId",
});
expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders");
});
it("wires real task mutation callbacks throughout the client task surfaces", async () => {
const { user } = renderWithProviders(<ClientTabloPage />, {
route: "/tablo/tablo-1",
path: "/tablo/:tabloId",
});
await user.click(screen.getByRole("button", { name: "Étapes" }));
expect(latestEtapesSectionProps?.onCreateTask).toBeTypeOf("function");
expect(latestEtapesSectionProps?.onTaskStatusChange).toBeTypeOf("function");
await user.click(screen.getByRole("button", { name: "Créer tâche d'étape test" }));
await user.click(screen.getByRole("button", { name: "Terminer tâche d'étape test" }));
await user.click(screen.getByRole("button", { name: "Tâches" }));
expect(latestTabloTasksSectionProps?.onCreateTask).toBeTypeOf("function");
expect(latestTabloTasksSectionProps?.onUpdateTask).toBeTypeOf("function");
expect(latestTabloTasksSectionProps?.onDeleteTask).toBeTypeOf("function");
expect(latestTabloTasksSectionProps?.onUpdateTaskPositions).toBeTypeOf("function");
await user.click(screen.getByRole("button", { name: "Créer tâche test" }));
await user.click(screen.getByRole("button", { name: "Modifier tâche test" }));
await user.click(screen.getByRole("button", { name: "Supprimer tâche test" }));
await user.click(screen.getByRole("button", { name: "Déplacer la tâche test" }));
await user.click(screen.getByRole("button", { name: "Roadmap" }));
expect(latestRoadmapSectionProps?.onTaskStatusChange).toBeTypeOf("function");
await user.click(screen.getByRole("button", { name: "Changer statut roadmap test" }));
await waitFor(() => {
expect(supabaseFromMock).toHaveBeenCalledWith("tasks");
expect(insertTaskMock).toHaveBeenCalledTimes(2);
expect(insertTaskMock).toHaveBeenCalledWith(
expect.objectContaining({
tablo_id: "tablo-1",
title: "Task from etape",
status: "todo",
assignee_id: null,
position: 0,
parent_task_id: "etape-1",
is_parent: false,
description: null,
due_date: null,
})
);
expect(updateTaskMock).toHaveBeenCalledWith({ title: "Updated task title" });
expect(updateTaskMock).toHaveBeenCalledWith({ position: 7, status: "done" });
expect(updateTaskMock).toHaveBeenCalledWith({ status: "done" });
expect(deleteTaskMock).toHaveBeenCalledTimes(1);
});
});
it("renders the main-route style header metadata and discussion CTA", () => {
renderWithProviders(<ClientTabloPage />, {
route: "/tablo/tablo-1",
@ -102,9 +500,24 @@ describe("ClientTabloPage parity shell", () => {
expect(screen.getByText("Client Project")).toBeInTheDocument();
expect(screen.getAllByRole("button", { name: "Discussion" })).toHaveLength(2);
expect(screen.getByText("Rôle :")).toBeInTheDocument();
expect(screen.getByText("Créé le :")).toBeInTheDocument();
expect(screen.getByText("Progression :")).toBeInTheDocument();
expect(screen.getAllByText("Rôle").length).toBeGreaterThan(0);
expect(screen.getAllByText("Créé le").length).toBeGreaterThan(0);
expect(screen.getAllByText("Progression").length).toBeGreaterThan(0);
});
it("keeps the shared main-app header labels even when the client locale is english", () => {
renderWithProviders(<ClientTabloPage />, {
route: "/tablo/tablo-1",
path: "/tablo/:tabloId",
language: "en",
});
expect(screen.getAllByText("Rôle").length).toBeGreaterThan(0);
expect(screen.getAllByText("Créé le").length).toBeGreaterThan(0);
expect(screen.getAllByText("Progression").length).toBeGreaterThan(0);
expect(screen.queryByText("Role")).not.toBeInTheDocument();
expect(screen.queryByText("Created on")).not.toBeInTheDocument();
expect(screen.queryByText("Progress")).not.toBeInTheDocument();
});
it("keeps client restrictions by hiding invite and layout-edit controls", () => {
@ -114,7 +527,9 @@ describe("ClientTabloPage parity shell", () => {
});
expect(screen.queryByRole("button", { name: "Inviter" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Modifier la mise en page" })).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Modifier la mise en page" })
).not.toBeInTheDocument();
});
it("renders a read-only overview matching the main route cards", () => {
@ -128,4 +543,57 @@ describe("ClientTabloPage parity shell", () => {
expect(screen.getByText("Informations")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Ajouter" })).not.toBeInTheDocument();
});
it("lets the client quickly toggle a task from the overview card", async () => {
const { user } = renderWithProviders(<ClientTabloPage />, {
route: "/tablo/tablo-1",
path: "/tablo/:tabloId",
});
await user.click(screen.getByRole("button", { name: "Prepare proposal" }));
await waitFor(() => {
expect(updateTaskMock).toHaveBeenCalledWith({ status: "done" });
});
});
it("wires file and folder actions in the client files tab while keeping file deletion disabled", async () => {
const { user } = renderWithProviders(<ClientTabloPage />, {
route: "/tablo/tablo-1",
path: "/tablo/:tabloId",
});
await user.click(screen.getByRole("button", { name: "Fichiers" }));
expect(latestTabloFilesSectionProps?.isReadOnly).toBe(false);
expect(latestTabloFilesSectionProps?.onCreateFile).toBeTypeOf("function");
expect(latestTabloFilesSectionProps?.onDownloadFile).toBeTypeOf("function");
expect(latestTabloFilesSectionProps?.onCreateFolder).toBeTypeOf("function");
expect(latestTabloFilesSectionProps?.onUpdateFolder).toBeTypeOf("function");
expect(latestTabloFilesSectionProps?.onDeleteFolder).toBeTypeOf("function");
expect(latestTabloFilesSectionProps?.onDeleteFile).toBeUndefined();
await user.click(screen.getByRole("button", { name: "Créer fichier test" }));
await user.click(screen.getByRole("button", { name: "Télécharger fichier test" }));
await user.click(screen.getByRole("button", { name: "Créer livrable test" }));
await user.click(screen.getByRole("button", { name: "Modifier livrable test" }));
await user.click(screen.getByRole("button", { name: "Supprimer livrable test" }));
await waitFor(() => {
expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/file/brief.pdf", {
content: "data:application/pdf;base64,AAAA",
contentType: "application/pdf",
});
expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/brief.pdf");
expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders", {
name: "Livrable",
description: "Desc",
});
expect(apiPutMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders/folder-1", {
name: "Livrable mis à jour",
description: "Desc",
});
expect(apiDeleteMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders/folder-1");
});
});
});

View file

@ -1,39 +1,27 @@
import { useQuery } from "@tanstack/react-query";
import { cn } from "@xtablo/shared";
import { buildApi } from "@xtablo/shared";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { buildApi, cn } from "@xtablo/shared";
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types";
import {
CalendarIcon,
Compass,
Flame,
FolderIcon,
Gem,
Heart,
KanbanIcon,
LayoutDashboardIcon,
Leaf,
ListChecksIcon,
MapIcon,
MessageCircleIcon,
Sparkles,
Star,
Sun,
Waves,
Zap,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import type {
Etape,
KanbanTask,
KanbanTaskUpdate,
TabloFolder,
TaskStatus,
UserTablo,
} from "@xtablo/shared-types";
import {
EtapesSection,
RoadmapSection,
TabloDetailsShell,
type SingleTabloTabId,
SingleTabloView,
TabloDiscussionSection,
TabloEventsSection,
TabloFilesSection,
TabloTasksSection,
} from "@xtablo/tablo-views";
import { FolderIcon } from "lucide-react";
import { useState } from "react";
import { useParams } from "react-router-dom";
import { supabase } from "../lib/supabase";
const API_URL = import.meta.env.VITE_API_URL as string;
@ -151,48 +139,266 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined)
return useQuery<TabloFolder[]>({
queryKey: ["client-tablo-folders", tabloId],
queryFn: async () => {
const { data } = await api.get<{ folders: TabloFolder[] }>(`/api/v1/tablo-folders/${tabloId}`);
const { data } = await api.get<{ folders: TabloFolder[] }>(
`/api/v1/tablo-data/${tabloId}/folders`
);
return data.folders ?? [];
},
enabled: !!tabloId && !!accessToken,
});
}
function getTabloIcon(color: string | null | undefined) {
switch (color) {
case "bg-blue-500":
return Zap;
case "bg-green-500":
return Leaf;
case "bg-purple-500":
return Gem;
case "bg-red-500":
return Flame;
case "bg-yellow-500":
return Star;
case "bg-indigo-500":
return Compass;
case "bg-pink-500":
return Heart;
case "bg-teal-500":
return Waves;
case "bg-orange-500":
return Sun;
case "bg-cyan-500":
return Sparkles;
default:
return FolderIcon;
}
const invalidateClientFileQueries = (
queryClient: ReturnType<typeof useQueryClient>,
tabloId: string
) => {
queryClient.invalidateQueries({ queryKey: ["client-tablo-files", tabloId] });
queryClient.invalidateQueries({ queryKey: ["client-tablo-folders", tabloId] });
};
function useClientCreateFile(tabloId: string, accessToken: string | undefined) {
const api = useAuthedApi(accessToken);
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (params: {
tabloId: string;
fileName: string;
data: { content: string; contentType: string };
}) => {
const response = await api.post(
`/api/v1/tablo-data/${params.tabloId}/file/${params.fileName}`,
params.data
);
if (response.status !== 200) {
throw new Error("Failed to create file");
}
return response.data;
},
onSuccess: () => invalidateClientFileQueries(queryClient, tabloId),
});
}
function getTabloIconColor(color: string | null | undefined): string {
switch (color) {
case "bg-yellow-500":
case "bg-cyan-500":
return "text-gray-700";
default:
return "text-white";
}
function useClientDownloadFile(accessToken: string | undefined) {
const api = useAuthedApi(accessToken);
return useMutation({
mutationFn: async ({ tabloId, fileName }: { tabloId: string; fileName: string }) => {
const response = await api.get(`/api/v1/tablo-data/${tabloId}/${fileName}`);
if (response.status !== 200) {
throw new Error("Failed to download file");
}
const fileData = response.data as { content: string; contentType?: string };
let blob: Blob;
if (fileData.content.startsWith("data:")) {
const fileResponse = await fetch(fileData.content);
blob = await fileResponse.blob();
} else {
blob = new Blob([fileData.content], {
type: fileData.contentType || "application/octet-stream",
});
}
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
},
});
}
function useClientCreateFolder(tabloId: string, accessToken: string | undefined) {
const api = useAuthedApi(accessToken);
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (params: {
tabloId: string;
name: string;
description: string;
createdBy: string;
}) => {
const response = await api.post(`/api/v1/tablo-data/${params.tabloId}/folders`, {
name: params.name,
description: params.description,
});
if (response.status !== 200) {
throw new Error("Failed to create folder");
}
return response.data;
},
onSuccess: () => invalidateClientFileQueries(queryClient, tabloId),
});
}
function useClientUpdateFolder(tabloId: string, accessToken: string | undefined) {
const api = useAuthedApi(accessToken);
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (params: {
tabloId: string;
folderId: string;
name: string;
description: string;
}) => {
const response = await api.put(
`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`,
{
name: params.name,
description: params.description,
}
);
if (response.status !== 200) {
throw new Error("Failed to update folder");
}
return response.data;
},
onSuccess: () => invalidateClientFileQueries(queryClient, tabloId),
});
}
function useClientDeleteFolder(tabloId: string, accessToken: string | undefined) {
const api = useAuthedApi(accessToken);
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (params: { tabloId: string; folderId: string; folderName: string }) => {
const response = await api.delete(
`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`
);
if (response.status !== 200) {
throw new Error("Failed to delete folder");
}
return response.data;
},
onSuccess: () => invalidateClientFileQueries(queryClient, tabloId),
});
}
type ClientTaskCreateInput = {
tablo_id: string;
title: string;
status?: TaskStatus | string;
parent_task_id?: string | null;
is_parent?: boolean;
position?: number;
description?: string | null;
assignee_id?: string | null;
due_date?: string | null;
};
const invalidateClientTaskQueries = (
queryClient: ReturnType<typeof useQueryClient>,
tabloId: string
) => {
queryClient.invalidateQueries({ queryKey: ["client-tasks", tabloId] });
};
function useClientCreateTask(tabloId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (task: ClientTaskCreateInput) => {
const { data, error } = await supabase
.from("tasks")
.insert({
tablo_id: task.tablo_id,
title: task.title,
status: (task.status as TaskStatus | undefined) ?? "todo",
assignee_id: task.assignee_id ?? null,
position: task.position ?? 0,
parent_task_id: task.parent_task_id ?? null,
is_parent: task.is_parent ?? false,
description: task.description ?? null,
due_date: task.due_date ?? null,
})
.select()
.single();
if (error) throw error;
return data;
},
onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId),
});
}
function useClientUpdateTask(tabloId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
id,
tablo_id: _tabloId,
...updates
}: KanbanTaskUpdate & { id: string; tablo_id?: string }) => {
const { data, error } = await supabase
.from("tasks")
.update(updates)
.eq("id", id)
.select()
.single();
if (error) throw error;
return data;
},
onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId),
});
}
function useClientDeleteTask(tabloId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (taskId: string) => {
const { error } = await supabase.from("tasks").delete().eq("id", taskId);
if (error) throw error;
return taskId;
},
onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId),
});
}
function useClientUpdateTaskPositions(tabloId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (
updates: Array<{
id: string;
position: number;
status?: TaskStatus;
parent_task_id?: string | null;
}>
) => {
const results = await Promise.all(
updates.map(({ id, position, status, parent_task_id }) =>
supabase
.from("tasks")
.update({
position,
...(status && { status }),
...(parent_task_id !== undefined ? { parent_task_id } : {}),
})
.eq("id", id)
)
);
const errors = results.filter((result) => result.error);
if (errors.length > 0) {
throw new Error("Failed to update some task positions");
}
return updates;
},
onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId),
});
}
function getStatusConfig(status: string) {
@ -238,27 +444,12 @@ function getEtapeProgressStats(etapes: Etape[]) {
};
}
// ─── Tabs ─────────────────────────────────────────────────────────────────────
type TabId = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap";
const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [
{ id: "overview", label: "Aperçu", icon: LayoutDashboardIcon },
{ id: "etapes", label: "Étapes", icon: ListChecksIcon },
{ id: "tasks", label: "Tâches", icon: KanbanIcon },
{ id: "files", label: "Fichiers", icon: FolderIcon },
{ id: "discussion", label: "Discussion", icon: MessageCircleIcon },
{ id: "events", label: "Événements", icon: CalendarIcon },
{ id: "roadmap", label: "Roadmap", icon: MapIcon },
];
// ─── Page ─────────────────────────────────────────────────────────────────────
export function ClientTabloPage() {
const { t } = useTranslation(["pages", "chat"]);
const { tabloId } = useParams<{ tabloId: string }>();
const { session } = useSession();
const [activeTab, setActiveTab] = useState<TabId>("overview");
const [activeTab, setActiveTab] = useState<SingleTabloTabId>("overview");
const accessToken = session?.access_token;
const currentUserId = session?.user.id ?? "";
@ -266,10 +457,31 @@ export function ClientTabloPage() {
const { data: tablo, isLoading: tabloLoading } = useClientTablo(tabloId ?? "");
const { data: tasks = [] } = useClientTabloTasks(tabloId ?? "");
const { data: etapes = [] } = useClientTabloEtapes(tabloId ?? "");
const { data: events, isLoading: eventsLoading, error: eventsError } = useClientTabloEvents(tabloId ?? "");
const {
data: events,
isLoading: eventsLoading,
error: eventsError,
} = useClientTabloEvents(tabloId ?? "");
const { data: members = [] } = useClientTabloMembers(tabloId ?? "", accessToken);
const { data: filesData, isLoading: filesLoading, error: filesError } = useClientTabloFiles(tabloId ?? "", accessToken);
const { data: folders = [], isLoading: foldersLoading, error: foldersError } = useClientTabloFolders(tabloId ?? "", accessToken);
const {
data: filesData,
isLoading: filesLoading,
error: filesError,
} = useClientTabloFiles(tabloId ?? "", accessToken);
const {
data: folders = [],
isLoading: foldersLoading,
error: foldersError,
} = useClientTabloFolders(tabloId ?? "", accessToken);
const { mutate: createTask } = useClientCreateTask(tabloId ?? "");
const { mutate: updateTask } = useClientUpdateTask(tabloId ?? "");
const { mutate: deleteTask } = useClientDeleteTask(tabloId ?? "");
const { mutate: updateTaskPositions } = useClientUpdateTaskPositions(tabloId ?? "");
const { mutateAsync: createFile } = useClientCreateFile(tabloId ?? "", accessToken);
const { mutateAsync: downloadFile } = useClientDownloadFile(accessToken);
const { mutateAsync: createFolder } = useClientCreateFolder(tabloId ?? "", accessToken);
const { mutateAsync: updateFolder } = useClientUpdateFolder(tabloId ?? "", accessToken);
const { mutateAsync: deleteFolder } = useClientDeleteFolder(tabloId ?? "", accessToken);
const fileNames = (filesData?.fileNames ?? []).filter((f) => !f.startsWith("."));
@ -293,253 +505,212 @@ export function ClientTabloPage() {
const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status);
const progress = getEtapeProgressStats(etapes);
const isDiscussionView = activeTab === "discussion";
const TabloIcon = getTabloIcon(tablo.color);
const iconColor = getTabloIconColor(tablo.color);
const metadata = [
{
key: "role",
label: t("pages:tablo.details.roleLabel"),
value: (
<span className="text-foreground font-medium">{t("pages:tablo.role.guest")}</span>
),
},
{
key: "created-at",
label: t("pages:tablo.details.createdAtLabel"),
value: (
<span className="text-foreground">
{new Intl.DateTimeFormat("fr-FR", {
year: "numeric",
month: "short",
day: "2-digit",
}).format(new Date(tablo.created_at))}
</span>
),
},
{
key: "status",
label: t("pages:tablo.details.statusLabel"),
value: <span className={cn("px-3 py-1 rounded-full text-xs font-medium", badgeClass)}>{statusLabel}</span>,
},
{
key: "progress",
label: t("pages:tablo.details.progressLabel"),
value: (
<>
<div className="relative w-24 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
<div
className="absolute inset-y-0 left-0 bg-blue-500/40"
style={{ width: `${progress.startedPercentage}%` }}
/>
<div
className="absolute inset-y-0 left-0 bg-green-500"
style={{ width: `${progress.donePercentage}%` }}
/>
</div>
<span className="text-foreground font-medium">{progress.donePercentage}%</span>
</>
),
},
];
const headerVisual = (
<div
className={cn(
"w-12 h-12 rounded-lg flex items-center justify-center shrink-0 overflow-hidden",
!tablo.image && (tablo.color || "bg-gray-400")
)}
>
{tablo.image ? (
<img src={tablo.image} alt={tablo.name} className="w-full h-full object-cover" />
) : (
<TabloIcon className={cn("w-6 h-6", iconColor)} />
)}
</div>
);
const headerActions = (
<button
type="button"
onClick={() => setActiveTab("discussion")}
className="bg-[#804EEC] hover:bg-[#6f3fd4] text-white font-medium py-2.5 px-4 rounded-lg flex items-center justify-center gap-2 transition-colors flex-1 sm:flex-none min-h-[44px]"
>
<MessageCircleIcon className="w-5 h-5" />
{t("chat:discussionTitle")}
</button>
);
return (
<TabloDetailsShell
<SingleTabloView
tablo={tablo}
headerVisual={headerVisual}
headerActions={headerActions}
metadata={metadata}
tabs={TABS}
roleLabel="Invité"
statusLabel={statusLabel}
statusBadgeClass={badgeClass}
progress={progress}
activeTab={activeTab}
onTabChange={(tabId) => setActiveTab(tabId as TabId)}
isDiscussionView={isDiscussionView}
onTabChange={setActiveTab}
discussionAction={{ kind: "button", onClick: () => setActiveTab("discussion") }}
>
{activeTab === "overview" && (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
<div className="bg-white dark:bg-card rounded-xl border border-border p-6 sm:p-8 shadow-sm">
<h2 className="text-xl sm:text-2xl font-bold text-foreground mb-4">
Description du projet
</h2>
<p className="text-muted-foreground leading-relaxed text-sm sm:text-base">
Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les
onglets ci-dessus pour naviguer entre les différentes sections.
</p>
</div>
<div className="bg-white dark:bg-card rounded-xl border border-gray-100 dark:border-gray-700 shadow-sm overflow-hidden">
<div className="flex flex-col sm:flex-row sm:items-center justify-between px-4 sm:px-6 py-4 border-b border-gray-200 dark:border-gray-700 gap-3">
<h2 className="text-xl sm:text-2xl font-semibold text-gray-900 dark:text-gray-100">
Mes tâches
</h2>
</div>
<div className="divide-y divide-gray-200 dark:divide-gray-700">
{tasks.length === 0 ? (
<div className="p-6 text-center text-muted-foreground text-sm">
Aucune tâche
</div>
) : (
tasks.slice(0, 5).map((task) => (
<div key={task.id} className="flex items-center gap-3 p-4">
<div className="w-5 h-5 rounded-full border-2 border-gray-300 dark:border-gray-600 shrink-0" />
<p className="text-sm font-medium truncate text-gray-900 dark:text-gray-100">
{task.title}
</p>
</div>
))
)}
</div>
</div>
{activeTab === "overview" && (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
<div className="bg-white dark:bg-card rounded-xl border border-border p-6 sm:p-8 shadow-sm">
<h2 className="text-xl sm:text-2xl font-bold text-foreground mb-4">
Description du projet
</h2>
<p className="text-muted-foreground leading-relaxed text-sm sm:text-base">
Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les onglets
ci-dessus pour naviguer entre les différentes sections.
</p>
</div>
<div className="space-y-6">
<div className="bg-white dark:bg-card rounded-xl border border-border p-5 sm:p-6 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-bold text-foreground">Fichiers</h3>
</div>
<div className="space-y-3">
{fileNames.length === 0 ? (
<p className="text-sm text-muted-foreground">Aucun fichier</p>
) : (
fileNames.slice(0, 5).map((fileName) => (
<div
key={fileName}
className="flex items-start gap-3 p-3 rounded-lg transition-colors"
>
<div className="w-10 h-10 bg-red-100 dark:bg-red-900/30 rounded-lg flex items-center justify-center shrink-0">
<FolderIcon className="w-4 h-4 text-red-500" />
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-foreground text-sm truncate">{fileName}</p>
</div>
</div>
))
)}
</div>
<div className="bg-white dark:bg-card rounded-xl border border-gray-100 dark:border-gray-700 shadow-sm overflow-hidden">
<div className="flex flex-col sm:flex-row sm:items-center justify-between px-4 sm:px-6 py-4 border-b border-gray-200 dark:border-gray-700 gap-3">
<h2 className="text-xl sm:text-2xl font-semibold text-gray-900 dark:text-gray-100">
Mes tâches
</h2>
</div>
<div className="bg-white dark:bg-card rounded-xl border border-border p-5 sm:p-6 shadow-sm">
<h3 className="text-lg font-bold text-foreground mb-4">Informations</h3>
<dl className="space-y-3 text-sm">
<div className="flex justify-between">
<dt className="text-muted-foreground">Tâches</dt>
<dd className="font-medium text-foreground">{tasks.length}</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Fichiers</dt>
<dd className="font-medium text-foreground">{fileNames.length}</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Statut</dt>
<dd className={cn("px-2 py-0.5 rounded-full text-xs font-medium", badgeClass)}>
{statusLabel}
</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Rôle</dt>
<dd className="font-medium text-foreground">{t("pages:tablo.role.guest")}</dd>
</div>
</dl>
<div className="divide-y divide-gray-200 dark:divide-gray-700">
{tasks.length === 0 ? (
<div className="p-6 text-center text-muted-foreground text-sm">Aucune tâche</div>
) : (
tasks.slice(0, 5).map((task) => (
<button
key={task.id}
type="button"
onClick={() =>
updateTask({
id: task.id,
status: task.status === "done" ? "todo" : "done",
})
}
className="flex w-full items-center gap-3 p-4 text-left transition-colors hover:bg-gray-50 dark:hover:bg-gray-800"
>
<div
className={cn(
"w-5 h-5 rounded-full border-2 shrink-0",
task.status === "done"
? "bg-green-500 border-green-500"
: "border-gray-300 dark:border-gray-600"
)}
/>
<p
className={cn(
"text-sm font-medium truncate",
task.status === "done"
? "text-gray-400 line-through"
: "text-gray-900 dark:text-gray-100"
)}
>
{task.title}
</p>
</button>
))
)}
</div>
</div>
</div>
)}
{activeTab === "etapes" && (
<EtapesSection
etapes={etapes}
tabloTasks={tasks}
tabloId={tablo.id}
isAdmin={false}
onCreateTask={() => {}}
onCreateEtape={async () => {}}
/>
)}
<div className="space-y-6">
<div className="bg-white dark:bg-card rounded-xl border border-border p-5 sm:p-6 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-bold text-foreground">Fichiers</h3>
</div>
<div className="space-y-3">
{fileNames.length === 0 ? (
<p className="text-sm text-muted-foreground">Aucun fichier</p>
) : (
fileNames.slice(0, 5).map((fileName) => (
<div
key={fileName}
className="flex items-start gap-3 p-3 rounded-lg transition-colors"
>
<div className="w-10 h-10 bg-red-100 dark:bg-red-900/30 rounded-lg flex items-center justify-center shrink-0">
<FolderIcon className="w-4 h-4 text-red-500" />
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-foreground text-sm truncate">{fileName}</p>
</div>
</div>
))
)}
</div>
</div>
{activeTab === "tasks" && (
<TabloTasksSection
tablo={tablo}
isAdmin={false}
tasks={tasks}
members={members}
etapes={etapes}
currentUser={currentUser}
/>
)}
<div className="bg-white dark:bg-card rounded-xl border border-border p-5 sm:p-6 shadow-sm">
<h3 className="text-lg font-bold text-foreground mb-4">Informations</h3>
<dl className="space-y-3 text-sm">
<div className="flex justify-between">
<dt className="text-muted-foreground">Tâches</dt>
<dd className="font-medium text-foreground">{tasks.length}</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Fichiers</dt>
<dd className="font-medium text-foreground">{fileNames.length}</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Statut</dt>
<dd className={cn("px-2 py-0.5 rounded-full text-xs font-medium", badgeClass)}>
{statusLabel}
</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Rôle</dt>
<dd className="font-medium text-foreground">Invité</dd>
</div>
</dl>
</div>
</div>
</div>
)}
{activeTab === "files" && (
<TabloFilesSection
tablo={tablo}
isAdmin={false}
isReadOnly={true}
currentUserId={currentUserId}
fileNames={fileNames}
filesLoading={filesLoading}
filesError={filesError instanceof Error ? filesError : null}
folders={folders}
foldersLoading={foldersLoading}
foldersError={foldersError instanceof Error ? foldersError : null}
currentUser={currentUser}
members={members}
/>
)}
{activeTab === "etapes" && (
<EtapesSection
etapes={etapes}
tabloTasks={tasks}
tabloId={tablo.id}
isAdmin={false}
onCreateTask={(task) => createTask(task)}
onCreateEtape={async () => undefined}
onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })}
/>
)}
{activeTab === "discussion" && (
<TabloDiscussionSection
tablo={tablo}
isAdmin={false}
currentUserId={currentUserId}
members={members}
/>
)}
{activeTab === "tasks" && (
<TabloTasksSection
tablo={tablo}
isAdmin={false}
tasks={tasks}
members={members}
etapes={etapes}
currentUser={currentUser}
onCreateTask={(task) => createTask(task)}
onUpdateTask={(task) => updateTask(task)}
onDeleteTask={(taskId) => deleteTask(taskId)}
onUpdateTaskPositions={(updates) => updateTaskPositions(updates)}
/>
)}
{activeTab === "events" && (
<TabloEventsSection
tablo={tablo}
isAdmin={false}
isReadOnly={true}
events={events as Parameters<typeof TabloEventsSection>[0]["events"]}
isLoading={eventsLoading}
error={eventsError instanceof Error ? eventsError : null}
currentUser={currentUser}
members={members}
/>
)}
{activeTab === "files" && (
<TabloFilesSection
tablo={tablo}
isAdmin={false}
isReadOnly={false}
canUploadFiles={true}
canManageFolders={true}
canDeleteFiles={false}
currentUserId={currentUserId}
fileNames={fileNames}
filesLoading={filesLoading}
filesError={filesError instanceof Error ? filesError : null}
folders={folders}
foldersLoading={foldersLoading}
foldersError={foldersError instanceof Error ? foldersError : null}
currentUser={currentUser}
members={members}
onCreateFile={(params) => createFile(params)}
onDownloadFile={(params) => downloadFile(params)}
onCreateFolder={(params) => createFolder(params)}
onUpdateFolder={(params) => updateFolder(params)}
onDeleteFolder={(params) => deleteFolder(params)}
/>
)}
{activeTab === "roadmap" && (
<RoadmapSection
tabloTasks={tasks}
onDateClick={() => {}}
onTaskStatusChange={() => {}}
/>
)}
</TabloDetailsShell>
{activeTab === "discussion" && (
<TabloDiscussionSection
tablo={tablo}
isAdmin={false}
currentUserId={currentUserId}
members={members}
/>
)}
{activeTab === "events" && (
<TabloEventsSection
tablo={tablo}
isAdmin={false}
isReadOnly={true}
events={events as Parameters<typeof TabloEventsSection>[0]["events"]}
isLoading={eventsLoading}
error={eventsError instanceof Error ? eventsError : null}
currentUser={currentUser}
members={members}
/>
)}
{activeTab === "roadmap" && (
<RoadmapSection
tabloTasks={tasks}
onDateClick={() => undefined}
onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })}
/>
)}
</SingleTabloView>
);
}

View file

@ -0,0 +1,66 @@
import { fireEvent, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../test/testHelpers";
import { LoginPage } from "./LoginPage";
const { mockSignInWithPassword, mockNavigate } = vi.hoisted(() => ({
mockSignInWithPassword: vi.fn(),
mockNavigate: vi.fn(),
}));
vi.mock("../lib/supabase", () => ({
supabase: {
auth: {
signInWithPassword: mockSignInWithPassword,
},
},
}));
vi.mock("react-router-dom", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-router-dom")>();
return {
...actual,
useNavigate: () => mockNavigate,
};
});
describe("LoginPage", () => {
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
mockSignInWithPassword.mockResolvedValue({
data: { user: { email_confirmed_at: new Date().toISOString() } },
error: null,
});
});
it("renders the shared auth shell and form", () => {
renderWithProviders(<LoginPage />, { testUser: undefined });
expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument();
expect(screen.getByLabelText("Email")).toBeInTheDocument();
expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Connexion" })).toBeInTheDocument();
expect(screen.getAllByAltText("Xtablo")[0]).toHaveAttribute(
"src",
"https://assets.xtablo.com/logo_dark.png"
);
});
it("submits email/password login and resumes the stored redirect", async () => {
localStorage.setItem("clients.redirectUrl", "/tablo/tablo-42");
renderWithProviders(<LoginPage />, { testUser: undefined });
fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } });
fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } });
fireEvent.click(screen.getByRole("button", { name: "Connexion" }));
await waitFor(() => {
expect(mockSignInWithPassword).toHaveBeenCalledWith({
email: "client@example.com",
password: "password123",
});
expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-42");
});
});
});

View file

@ -0,0 +1,102 @@
import { AuthCardShell, AuthEmailPasswordForm, AuthInfoBanner } from "@xtablo/auth-ui";
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import { supabase } from "../lib/supabase";
export function LoginPage() {
const { t } = useTranslation(["auth", "common"]);
const { session } = useSession();
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState<string | null>(null);
if (session) {
const redirectUrl = localStorage.getItem("clients.redirectUrl");
if (redirectUrl) {
localStorage.removeItem("clients.redirectUrl");
navigate(redirectUrl);
} else {
navigate("/");
}
}
const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setIsPending(true);
setError(null);
const { error: signInError } = await supabase.auth.signInWithPassword({
email,
password,
});
if (signInError) {
setError(signInError.message);
setIsPending(false);
return;
}
const redirectUrl = localStorage.getItem("clients.redirectUrl");
if (redirectUrl) {
localStorage.removeItem("clients.redirectUrl");
navigate(redirectUrl);
} else {
navigate("/");
}
};
return (
<AuthCardShell
title={t("auth:login.title")}
topLeft={
<a
href="https://www.xtablo.com"
className="inline-flex items-center text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
</svg>
{t("auth:common.backHome")}
</a>
}
showThemeToggle
>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
<AuthEmailPasswordForm
email={email}
password={password}
onEmailChange={setEmail}
onPasswordChange={setPassword}
onSubmit={onSubmit}
submitLabel="Connexion"
emailLabel={t("common:labels.email")}
passwordLabel={t("common:labels.password")}
emailPlaceholder={t("auth:login.emailPlaceholder")}
passwordPlaceholder={t("auth:login.passwordPlaceholder")}
isPending={isPending}
extraContent={
<div className="flex items-center justify-end">
<Link
to="/reset-password"
className="text-sm text-[#804EEC] transition-colors hover:text-[#6f3fd4]"
>
{t("auth:login.forgotPassword")}
</Link>
</div>
}
/>
</div>
</AuthCardShell>
);
}

View file

@ -0,0 +1,42 @@
import { fireEvent, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../test/testHelpers";
import { ResetPasswordPage } from "./ResetPasswordPage";
const { mockResetPasswordForEmail } = vi.hoisted(() => ({
mockResetPasswordForEmail: vi.fn(),
}));
vi.mock("../lib/supabase", () => ({
supabase: {
auth: {
resetPasswordForEmail: mockResetPasswordForEmail,
},
},
}));
describe("ResetPasswordPage", () => {
beforeEach(() => {
vi.clearAllMocks();
mockResetPasswordForEmail.mockResolvedValue({ error: null });
});
it("renders the shared auth shell", () => {
renderWithProviders(<ResetPasswordPage />, { testUser: undefined });
expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument();
expect(screen.getByLabelText("Email")).toBeInTheDocument();
});
it("submits a password reset email", async () => {
renderWithProviders(<ResetPasswordPage />, { testUser: undefined });
fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } });
fireEvent.click(screen.getByRole("button", { name: "Envoyer le lien de réinitialisation" }));
await waitFor(() => {
expect(mockResetPasswordForEmail).toHaveBeenCalled();
expect(screen.getByText(/vérifiez votre boîte mail/i)).toBeInTheDocument();
});
});
});

View file

@ -0,0 +1,74 @@
import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { supabase } from "../lib/supabase";
export function ResetPasswordPage() {
const { t } = useTranslation(["auth", "common"]);
const [email, setEmail] = useState("");
const [error, setError] = useState<string | null>(null);
const [isPending, setIsPending] = useState(false);
const [isSubmitted, setIsSubmitted] = useState(false);
const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setIsPending(true);
setError(null);
const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo: `${window.location.origin}/set-password`,
});
if (resetError) {
setError(resetError.message);
setIsPending(false);
return;
}
setIsSubmitted(true);
setIsPending(false);
};
return (
<AuthCardShell
title={t("auth:resetPassword.title")}
description={t("auth:resetPassword.description")}
>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
{isSubmitted ? (
<div className="space-y-4">
<AuthInfoBanner message="Vérifiez votre boîte mail pour continuer." variant="success" />
<Link className="block" to="/login">
<Button className="w-full">Retour à la connexion</Button>
</Link>
</div>
) : (
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{t("common:labels.email")}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
placeholder={t("auth:resetPassword.emailPlaceholder")}
required
disabled={isPending}
/>
</div>
<Button className="w-full" type="submit" disabled={isPending}>
{t("auth:resetPassword.submit")}
</Button>
</form>
)}
</div>
</AuthCardShell>
);
}

View file

@ -0,0 +1,94 @@
import { fireEvent, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../test/testHelpers";
import { SetPasswordPage } from "./SetPasswordPage";
const { mockSignInWithPassword, mockUpdateUser, mockNavigate } = vi.hoisted(() => ({
mockSignInWithPassword: vi.fn(),
mockUpdateUser: vi.fn(),
mockNavigate: vi.fn(),
}));
vi.mock("../lib/supabase", () => ({
supabase: {
auth: {
signInWithPassword: mockSignInWithPassword,
updateUser: mockUpdateUser,
},
},
}));
vi.mock("react-router-dom", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-router-dom")>();
return {
...actual,
useNavigate: () => mockNavigate,
};
});
describe("SetPasswordPage", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn());
mockSignInWithPassword.mockResolvedValue({ data: {}, error: null });
mockUpdateUser.mockResolvedValue({ data: {}, error: null });
});
it("renders an invalid-token state when invite validation fails", async () => {
vi.mocked(fetch).mockResolvedValueOnce(
new Response(JSON.stringify({ error: "Invite not found or already used" }), { status: 404 })
);
renderWithProviders(<SetPasswordPage />, {
route: "/set-password?token=bad-token",
path: "/set-password",
testUser: undefined,
});
await waitFor(() => {
expect(screen.getByText(/lien invalide/i)).toBeInTheDocument();
});
});
it("submits invite-based password setup once", async () => {
vi.mocked(fetch)
.mockResolvedValueOnce(
new Response(JSON.stringify({ email: "client@example.com", tabloId: "tablo-1" }), {
status: 200,
})
)
.mockResolvedValueOnce(
new Response(
JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }),
{
status: 200,
}
)
);
renderWithProviders(<SetPasswordPage />, {
route: "/set-password?token=good-token",
path: "/set-password",
testUser: undefined,
});
await waitFor(() => {
expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument();
});
fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } });
fireEvent.change(screen.getByLabelText("Confirmer le mot de passe"), {
target: { value: "password123" },
});
fireEvent.click(screen.getByRole("button", { name: "Définir mon mot de passe" }));
await waitFor(() => {
expect(fetch).toHaveBeenCalledTimes(2);
expect(mockSignInWithPassword).toHaveBeenCalledWith({
email: "client@example.com",
password: "password123",
});
expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-1");
});
});
});

View file

@ -0,0 +1,205 @@
import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui";
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useSearchParams } from "react-router-dom";
import { supabase } from "../lib/supabase";
type InviteDetails = {
email: string;
tabloId: string;
};
type InviteState = "loading" | "ready" | "invalid";
function getApiUrl() {
return import.meta.env.VITE_API_URL ?? "";
}
async function parseError(response: Response) {
const body = (await response.json().catch(() => ({}))) as { error?: string; message?: string };
return body.error ?? body.message ?? "Une erreur est survenue.";
}
export function SetPasswordPage() {
const { t } = useTranslation("auth");
const { session } = useSession();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const token = searchParams.get("token");
const [inviteState, setInviteState] = useState<InviteState>(token ? "loading" : "ready");
const [inviteDetails, setInviteDetails] = useState<InviteDetails | null>(null);
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [isPending, setIsPending] = useState(false);
const isInviteFlow = Boolean(token);
const description = useMemo(
() =>
isInviteFlow
? "Définissez votre mot de passe pour accéder à votre espace client."
: t("updatePassword.description"),
[isInviteFlow, t]
);
useEffect(() => {
if (!token) {
return;
}
let isMounted = true;
fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`)
.then(async (response) => {
if (!response.ok) {
throw new Error(await parseError(response));
}
return (await response.json()) as InviteDetails;
})
.then((details) => {
if (!isMounted) return;
setInviteDetails(details);
setInviteState("ready");
})
.catch((err: unknown) => {
if (!isMounted) return;
setError(err instanceof Error ? err.message : "Lien invalide");
setInviteState("invalid");
});
return () => {
isMounted = false;
};
}, [token]);
const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setError(null);
if (password.length < 8) {
setError(t("signup.errors.passwordLength"));
return;
}
if (password !== confirmPassword) {
setError(t("signup.errors.passwordMatch"));
return;
}
setIsPending(true);
try {
if (token && inviteDetails) {
const response = await fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ password }),
});
if (!response.ok) {
throw new Error(await parseError(response));
}
const result = (await response.json()) as InviteDetails & { success: boolean };
const { error: signInError } = await supabase.auth.signInWithPassword({
email: result.email,
password,
});
if (signInError) {
throw signInError;
}
navigate(`/tablo/${result.tabloId}`);
return;
}
const { error: updateError } = await supabase.auth.updateUser({ password });
if (updateError) {
throw updateError;
}
navigate("/login");
} catch (err) {
setError(err instanceof Error ? err.message : "Une erreur est survenue.");
} finally {
setIsPending(false);
}
};
if (inviteState === "loading") {
return (
<AuthCardShell title="Définir votre mot de passe" description={description}>
<div className="flex justify-center py-8">
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
</div>
</AuthCardShell>
);
}
if (inviteState === "invalid") {
return (
<AuthCardShell title="Lien invalide" description="Ce lien ne peut plus être utilisé.">
<AuthInfoBanner message={error ?? "Lien invalide"} variant="error" />
</AuthCardShell>
);
}
const shouldShowRecoveryHint = !isInviteFlow && !session;
return (
<AuthCardShell
title={isInviteFlow ? "Définir votre mot de passe" : t("updatePassword.title")}
description={description}
>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
{shouldShowRecoveryHint ? (
<AuthInfoBanner
message="Utilisez le lien reçu par email pour définir ou réinitialiser votre mot de passe."
variant="info"
/>
) : null}
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="password">Mot de passe</Label>
<Input
id="password"
name="password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
required
disabled={isPending}
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirmer le mot de passe</Label>
<Input
id="confirmPassword"
name="confirmPassword"
type="password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
required
disabled={isPending}
/>
</div>
<Button className="w-full" type="submit" disabled={isPending}>
Définir mon mot de passe
</Button>
</form>
</div>
</AuthCardShell>
);
}

View file

@ -1,16 +1,25 @@
import { Route, Routes } from "react-router-dom";
import { ClientAuthGate } from "./components/ClientAuthGate";
import { ClientLayout } from "./components/ClientLayout";
import { AuthCallback } from "./pages/AuthCallback";
import { ClientTabloListPage } from "./pages/ClientTabloListPage";
import { ClientTabloPage } from "./pages/ClientTabloPage";
import { LoginPage } from "./pages/LoginPage";
import { ResetPasswordPage } from "./pages/ResetPasswordPage";
import { SetPasswordPage } from "./pages/SetPasswordPage";
export default function AppRoutes() {
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/reset-password" element={<ResetPasswordPage />} />
<Route path="/set-password" element={<SetPasswordPage />} />
<Route path="/auth/callback" element={<AuthCallback />} />
<Route element={<ClientLayout />}>
<Route path="/tablo/:tabloId" element={<ClientTabloPage />} />
<Route path="/" element={<ClientTabloListPage />} />
<Route element={<ClientAuthGate />}>
<Route element={<ClientLayout />}>
<Route path="/tablo/:tabloId" element={<ClientTabloPage />} />
<Route path="/" element={<ClientTabloListPage />} />
</Route>
</Route>
</Routes>
);

View file

@ -8,9 +8,15 @@ afterEach(() => {
});
global.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
observe() {
return undefined;
}
unobserve() {
return undefined;
}
disconnect() {
return undefined;
}
};
if (typeof Element !== "undefined") {

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { renderWithProviders } from "./testHelpers";
describe("client test harness", () => {

View file

@ -1,5 +1,5 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, type RenderResult } from "@testing-library/react";
import { type RenderResult, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext";
import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext";
@ -23,12 +23,16 @@ interface RenderWithProvidersOptions {
route?: string;
path?: string;
language?: string;
testUser?: typeof defaultUser | undefined;
}
export const renderWithProviders = (
ui: React.ReactNode,
{ route = "/", path, language = "fr" }: RenderWithProvidersOptions = {}
options: RenderWithProvidersOptions = {}
): RenderResult & { user: ReturnType<typeof userEvent.setup> } => {
const { route = "/", path, language = "fr" } = options;
const testUser = Object.hasOwn(options, "testUser") ? options.testUser : defaultUser;
testI18n.changeLanguage(language);
const testQueryClient = new QueryClient({
@ -55,7 +59,7 @@ export const renderWithProviders = (
<MemoryRouter initialEntries={[route]}>
<ThemeProvider>
<QueryClientProvider client={testQueryClient}>
<SessionTestProvider testUser={defaultUser}>{content}</SessionTestProvider>
<SessionTestProvider testUser={testUser}>{content}</SessionTestProvider>
</QueryClientProvider>
</ThemeProvider>
</MemoryRouter>

View file

@ -1,8 +1,8 @@
{
"compilerOptions": {
"target": "ES2020",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["vite/client"],
"module": "ESNext",
"skipLibCheck": true,
@ -18,6 +18,8 @@
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@xtablo/auth-ui": ["../../packages/auth-ui/src"],
"@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"],
"@xtablo/ui": ["../../packages/ui/src"],
"@xtablo/ui/*": ["../../packages/ui/src/*"],
"@xtablo/shared": ["../../packages/shared/src"],

View file

@ -1 +1 @@
{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"}
{"root":["./src/app.tsx","./src/envproduction.test.ts","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"}

View file

@ -5,7 +5,11 @@ import { defineConfig, type PluginOption } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig(({ mode }) => {
const plugins: PluginOption[] = [react(), tailwindcss(), tsconfigPaths({ ignoreConfigErrors: true })];
const plugins: PluginOption[] = [
react(),
tailwindcss(),
tsconfigPaths({ ignoreConfigErrors: true }),
];
if (mode !== "test" && process.env.VITEST !== "true") {
plugins.push(cloudflare({ inspectorPort: 9232 }));

View file

@ -100,6 +100,7 @@
"@types/react-router-dom": "^5.3.3",
"@typescript/native-preview": "7.0.0-dev.20251010.1",
"@xtablo/chat-ui": "workspace:*",
"@xtablo/auth-ui": "workspace:*",
"@xtablo/shared": "workspace:*",
"@xtablo/shared-types": "workspace:*",
"@xtablo/tablo-views": "workspace:*",

View file

@ -0,0 +1,67 @@
import { screen, waitFor } from "@testing-library/react";
import { AuthenticationGateway } from "@ui/components/AuthenticationGateway";
import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext";
import { Route, Routes } from "react-router-dom";
import { vi } from "vitest";
import { TestUserStoreProvider } from "../providers/UserStoreProvider";
import { renderWithRouter } from "../utils/testHelpers";
const { redirectClientUserToPortal } = vi.hoisted(() => ({
redirectClientUserToPortal: vi.fn(),
}));
vi.mock("../lib/clientPortal", () => ({
redirectClientUserToPortal,
}));
describe("AuthenticationGateway", () => {
it("redirects authenticated client users to the client portal instead of main auth pages", async () => {
renderWithRouter(
<TestUserStoreProvider
user={{
id: "123",
short_user_id: "123",
name: "Client User",
first_name: "Client",
last_name: "User",
email: "client@example.com",
avatar_url: null,
is_temporary: false,
is_client: true,
client_onboarded_at: new Date().toISOString(),
last_signed_in: null,
plan: "none" as const,
created_at: new Date().toISOString(),
}}
>
<SessionTestProvider
testUser={{
id: "123",
app_metadata: {},
user_metadata: {
full_name: "Client User",
email: "client@example.com",
email_verified: true,
first_name: "Client",
last_name: "User",
},
aud: "authenticated",
created_at: new Date().toISOString(),
}}
>
<Routes>
<Route element={<AuthenticationGateway />}>
<Route path="/login" element={<div>Login Page</div>} />
</Route>
</Routes>
</SessionTestProvider>
</TestUserStoreProvider>,
{ route: "/login" }
);
await waitFor(() => {
expect(redirectClientUserToPortal).toHaveBeenCalledWith("/");
});
expect(screen.queryByText("Login Page")).not.toBeInTheDocument();
});
});

View file

@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { Navigate, Outlet, useSearchParams } from "react-router-dom";
import { match } from "ts-pattern";
import { redirectClientUserToPortal } from "../lib/clientPortal";
import { useMaybeUser } from "../providers/UserStoreProvider";
import { LoadingSpinner } from "./LoadingSpinner";
@ -22,9 +23,11 @@ export const AuthenticationGateway = () => {
return () => clearTimeout(timer);
}, [user]);
let status: "loading" | "should-redirect" | "should-pass" = "loading";
let status: "loading" | "should-redirect" | "should-redirect-client" | "should-pass" = "loading";
if (isLoading) {
status = "loading";
} else if (user?.is_client) {
status = "should-redirect-client";
} else if (user) {
status = "should-redirect";
} else {
@ -34,6 +37,15 @@ export const AuthenticationGateway = () => {
return match(status)
.with("loading", () => <LoadingSpinner />)
.with("should-redirect", () => <Navigate to="/" replace />)
.with("should-redirect-client", () => <ClientPortalRedirect />)
.with("should-pass", () => <Outlet />)
.exhaustive();
};
const ClientPortalRedirect = () => {
useEffect(() => {
redirectClientUserToPortal("/");
}, []);
return <LoadingSpinner />;
};

View file

@ -2,8 +2,18 @@ import { screen, waitFor } from "@testing-library/react";
import { AuthenticationGateway } from "@ui/components/AuthenticationGateway";
import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext";
import { Route, Routes } from "react-router-dom";
import { vi } from "vitest";
import { TestUserStoreProvider } from "../providers/UserStoreProvider";
import { renderWithRouter } from "../utils/testHelpers";
const { redirectClientUserToPortal } = vi.hoisted(() => ({
redirectClientUserToPortal: vi.fn(),
}));
vi.mock("../lib/clientPortal", () => ({
redirectClientUserToPortal,
}));
describe("PublicRoute", () => {
it("shows loading state initially", () => {
renderWithRouter(
@ -38,29 +48,47 @@ describe("PublicRoute", () => {
it("redirect to home when user is authenticated", async () => {
renderWithRouter(
<SessionTestProvider
testUser={{
<TestUserStoreProvider
user={{
id: "123",
app_metadata: {},
user_metadata: {
full_name: "Test User",
email: "test@example.com",
email_verified: true,
first_name: "Test",
last_name: "User",
business_name: "Test Business",
},
aud: "authenticated",
short_user_id: "123",
name: "Test User",
first_name: "Test",
last_name: "User",
email: "test@example.com",
avatar_url: null,
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_signed_in: null,
plan: "none" as const,
created_at: new Date().toISOString(),
}}
>
<Routes>
<Route element={<AuthenticationGateway />}>
<Route path="/login" element={<div>Login Page</div>} />
</Route>
<Route path="/" element={<div>Home Page</div>} />
</Routes>
</SessionTestProvider>,
<SessionTestProvider
testUser={{
id: "123",
app_metadata: {},
user_metadata: {
full_name: "Test User",
email: "test@example.com",
email_verified: true,
first_name: "Test",
last_name: "User",
business_name: "Test Business",
},
aud: "authenticated",
created_at: new Date().toISOString(),
}}
>
<Routes>
<Route element={<AuthenticationGateway />}>
<Route path="/login" element={<div>Login Page</div>} />
</Route>
<Route path="/" element={<div>Home Page</div>} />
</Routes>
</SessionTestProvider>
</TestUserStoreProvider>,
{ route: "/login" }
);
@ -70,6 +98,56 @@ describe("PublicRoute", () => {
});
});
it("redirects authenticated client users to the client portal instead of main auth pages", async () => {
renderWithRouter(
<TestUserStoreProvider
user={{
id: "123",
short_user_id: "123",
name: "Client User",
first_name: "Client",
last_name: "User",
email: "client@example.com",
avatar_url: null,
is_temporary: false,
is_client: true,
client_onboarded_at: new Date().toISOString(),
last_signed_in: null,
plan: "none" as const,
created_at: new Date().toISOString(),
}}
>
<SessionTestProvider
testUser={{
id: "123",
app_metadata: {},
user_metadata: {
full_name: "Client User",
email: "client@example.com",
email_verified: true,
first_name: "Client",
last_name: "User",
},
aud: "authenticated",
created_at: new Date().toISOString(),
}}
>
<Routes>
<Route element={<AuthenticationGateway />}>
<Route path="/login" element={<div>Login Page</div>} />
</Route>
</Routes>
</SessionTestProvider>
</TestUserStoreProvider>,
{ route: "/login" }
);
await waitFor(() => {
expect(redirectClientUserToPortal).toHaveBeenCalledWith("/");
});
expect(screen.queryByText("Login Page")).not.toBeInTheDocument();
});
it("renders public content when user is not authenticated", async () => {
renderWithRouter(
<SessionTestProvider testUser={undefined}>

View file

@ -2,9 +2,18 @@ import { screen, waitFor } from "@testing-library/react";
import { ProtectedRoute } from "@ui/components/ProtectedRoute";
import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext";
import { Route, Routes } from "react-router-dom";
import { vi } from "vitest";
import { TestUserStoreProvider } from "../providers/UserStoreProvider";
import { renderWithRouter } from "../utils/testHelpers";
const { redirectClientUserToPortal } = vi.hoisted(() => ({
redirectClientUserToPortal: vi.fn(),
}));
vi.mock("../lib/clientPortal", () => ({
redirectClientUserToPortal,
}));
describe("ProtectedRoute", () => {
beforeEach(() => {
localStorage.setItem("xtablo-has-seen-landing-page", "true");
@ -85,6 +94,7 @@ describe("ProtectedRoute", () => {
last_name: "User",
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_signed_in: null,
plan: "none" as const,
created_at: new Date().toISOString(),
@ -126,4 +136,40 @@ describe("ProtectedRoute", () => {
expect(screen.getByText("Custom Login Page")).toBeInTheDocument();
});
});
it("redirects client users to the client portal instead of rendering main app content", async () => {
renderWithRouter(
<TestUserStoreProvider
user={{
id: "123",
name: "Client User",
email: "client@example.com",
avatar_url: "https://example.com/avatar.jpg",
short_user_id: "123",
first_name: "Client",
last_name: "User",
is_temporary: false,
is_client: true,
client_onboarded_at: new Date().toISOString(),
last_signed_in: null,
plan: "none" as const,
created_at: new Date().toISOString(),
}}
>
<SessionTestProvider>
<Routes>
<Route element={<ProtectedRoute />}>
<Route path="/" element={<div>Protected Content</div>} />
</Route>
</Routes>
</SessionTestProvider>
</TestUserStoreProvider>,
{ route: "/" }
);
await waitFor(() => {
expect(redirectClientUserToPortal).toHaveBeenCalledWith("/");
});
expect(screen.queryByText("Protected Content")).not.toBeInTheDocument();
});
});

View file

@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { Navigate, Outlet } from "react-router-dom";
import { match } from "ts-pattern";
import { redirectClientUserToPortal } from "../lib/clientPortal";
import { useMaybeUser } from "../providers/UserStoreProvider";
import { LoadingSpinner } from "./LoadingSpinner";
@ -28,7 +29,12 @@ export const ProtectedRoute = ({
return () => clearTimeout(timer);
}, [user, fallback]);
let status: "loading" | "should-land-user" | "should-redirect" | "should-pass" = "loading";
let status:
| "loading"
| "should-land-user"
| "should-redirect"
| "should-redirect-client"
| "should-pass" = "loading";
const isFirstTimeUser = localStorage.getItem("xtablo-has-seen-landing-page") === null;
@ -38,6 +44,8 @@ export const ProtectedRoute = ({
status = "should-land-user";
} else if (!user) {
status = "should-redirect";
} else if (user.is_client) {
status = "should-redirect-client";
} else if (onlyRegularUser && user.is_temporary) {
status = "should-redirect";
} else {
@ -56,6 +64,15 @@ export const ProtectedRoute = ({
.with("loading", () => <LoadingSpinner />)
.with("should-land-user", () => <Navigate to="/landing" replace />)
.with("should-redirect", () => <Navigate to={redirectUrl} replace />)
.with("should-redirect-client", () => <ClientPortalRedirect />)
.with("should-pass", () => <Outlet />)
.exhaustive();
};
const ClientPortalRedirect = () => {
useEffect(() => {
redirectClientUserToPortal("/");
}, []);
return <LoadingSpinner />;
};

View file

@ -29,6 +29,7 @@ import { useSubscription } from "../hooks/stripe";
const mockUseOrganization = vi.mocked(useOrganization);
const mockUseSubscription = vi.mocked(useSubscription);
type SubscriptionData = NonNullable<ReturnType<typeof useSubscription>["data"]>;
const baseUser: User = {
id: "user-1",
@ -40,6 +41,7 @@ const baseUser: User = {
avatar_url: null,
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_signed_in: null,
plan: "none",
created_at: new Date().toISOString(),
@ -146,8 +148,8 @@ describe("SubscriptionCard", () => {
status: "active",
current_period_end: Math.floor(Date.now() / 1000) + 86400 * 30,
cancel_at_period_end: false,
};
renderCard(baseUser, teamOrg, activeSubscription as any);
} satisfies SubscriptionData;
renderCard(baseUser, teamOrg, activeSubscription);
expect(screen.getByText("Actif")).toBeInTheDocument();
expect(screen.getByText("Gérer l'abonnement")).toBeInTheDocument();
expect(screen.getByText("Annuler")).toBeInTheDocument();
@ -163,8 +165,8 @@ describe("SubscriptionCard", () => {
status: "trialing",
current_period_end: Math.floor(Date.now() / 1000) + 86400 * 14,
cancel_at_period_end: false,
};
renderCard(baseUser, teamOrg, trialingSubscription as any);
} satisfies SubscriptionData;
renderCard(baseUser, teamOrg, trialingSubscription);
expect(screen.getByText("Période d'essai")).toBeInTheDocument();
});
@ -178,8 +180,8 @@ describe("SubscriptionCard", () => {
status: "past_due",
current_period_end: Math.floor(Date.now() / 1000) - 86400,
cancel_at_period_end: false,
};
renderCard(baseUser, teamOrg, pastDueSubscription as any);
} satisfies SubscriptionData;
renderCard(baseUser, teamOrg, pastDueSubscription);
expect(screen.getByText("Paiement en retard")).toBeInTheDocument();
});
@ -194,8 +196,8 @@ describe("SubscriptionCard", () => {
status: "active",
current_period_end: Math.floor(Date.now() / 1000) + 86400 * 15,
cancel_at_period_end: true,
};
renderCard(baseUser, teamOrg, canceledSubscription as any);
} satisfies SubscriptionData;
renderCard(baseUser, teamOrg, canceledSubscription);
expect(screen.getByText(/Abonnement en cours d'annulation/)).toBeInTheDocument();
expect(screen.getByText("Réactiver l'abonnement")).toBeInTheDocument();
});

View file

@ -36,6 +36,7 @@ const baseUser: User = {
avatar_url: null,
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_signed_in: null,
plan: "none",
created_at: new Date().toISOString(),

View file

@ -23,6 +23,7 @@ const baseUser: User = {
avatar_url: null,
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_signed_in: null,
plan: "none",
created_at: new Date().toISOString(),

View file

@ -10,6 +10,11 @@ type PendingClientInvite = {
created_at: string;
};
type CreateClientInviteResponse = {
success: true;
inviteMode: "notification" | "setup";
};
export const usePendingClientInvites = (tabloId: string) => {
const api = useAuthedApi();
const { session } = useSession();
@ -32,17 +37,23 @@ export const useCreateClientInvite = () => {
return useMutation({
mutationFn: async ({ tabloId, email }: { tabloId: string; email: string }) => {
const { data } = await api.post<PendingClientInvite>(`/api/v1/client-invites/${tabloId}`, {
email,
});
const { data } = await api.post<CreateClientInviteResponse>(
`/api/v1/client-invites/${tabloId}`,
{
email,
}
);
return data;
},
onSuccess: (_data, { tabloId }) => {
onSuccess: (data, { tabloId }) => {
queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] });
toast.add(
{
title: "Lien magique envoyé",
description: "L'invitation client a été envoyée avec succès",
title: data.inviteMode === "setup" ? "Invitation client envoyée" : "Accès client accordé",
description:
data.inviteMode === "setup"
? "Un email de configuration du mot de passe a été envoyé au client."
: "Le client a été informé de son nouvel accès et pourra se connecter à son espace.",
type: "success",
},
{ timeout: 3000 }

View file

@ -0,0 +1,24 @@
const DEFAULT_CLIENTS_APP_URL = "https://clients.xtablo.com";
const trimTrailingSlash = (value: string) => value.replace(/\/+$/, "");
export function getClientPortalUrl(path = "/") {
const configuredUrl = import.meta.env.VITE_CLIENTS_APP_URL as string | undefined;
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
const baseUrl = configuredUrl
? trimTrailingSlash(configuredUrl)
: window.location.hostname === "app.xtablo.com"
? DEFAULT_CLIENTS_APP_URL
: window.location.hostname.startsWith("app.")
? `${window.location.protocol}//clients.${window.location.hostname.slice(4)}${
window.location.port ? `:${window.location.port}` : ""
}`
: DEFAULT_CLIENTS_APP_URL;
return `${baseUrl}${normalizedPath}`;
}
export function redirectClientUserToPortal(path = "/") {
window.location.replace(getClientPortalUrl(path));
}

View file

@ -34,6 +34,7 @@ describe("LoginPage", () => {
it("renders all form elements", () => {
renderWithProviders(<LoginPage />);
expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument();
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
expect(screen.getByRole("button", { name: /log in/i })).toBeInTheDocument();

View file

@ -1,10 +1,5 @@
import { LoginWithGoogle } from "@ui/components/BrandButtons/LoginWithGoogle";
import { useTheme } from "@xtablo/shared/contexts/ThemeContext";
import { Button } from "@xtablo/ui/components/button";
import { FieldError } from "@xtablo/ui/components/field";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { AuthCardShell, AuthEmailPasswordForm } from "@xtablo/auth-ui";
import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useSearchParams } from "react-router-dom";
@ -60,32 +55,6 @@ export function LoginPage() {
setIsHovered(false);
};
// Theme
const { theme, setTheme } = useTheme();
const toggleTheme = () => {
if (theme === "light") {
setTheme("dark");
} else if (theme === "dark") {
setTheme("system");
} else {
setTheme("light");
}
};
const getThemeIcon = () => {
switch (theme) {
case "light":
return <SunIcon className="w-5 h-5" />;
case "dark":
return <MoonIcon className="w-5 h-5" />;
case "system":
return <MonitorIcon className="w-5 h-5" />;
default:
return <SunIcon className="w-5 h-5" />;
}
};
const onSubmit = (e: React.FormEvent) => {
e.preventDefault();
login({
@ -95,168 +64,100 @@ export function LoginPage() {
};
return (
<div className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5 animate-gradient-x bg-size-[400%_400%] relative overflow-hidden px-4 py-8 sm:px-6">
<AnimatedBackground />
<div
ref={cardRef}
className={twMerge(
"w-full max-w-lg rounded-2xl relative",
"transition-transform duration-200 ease-out will-change-transform"
)}
style={{ transform }}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onClick={(e) => e.stopPropagation()}
>
{/* Glow effect behind the card */}
<div className="absolute inset-0 rounded-2xl bg-linear-to-br from-primary/10 via-primary/5 to-secondary/10 blur-xl -z-10"></div>
<div
className={twMerge(
"relative w-full h-full p-5 sm:p-8 bg-card/80 backdrop-blur-md rounded-2xl border border-border z-10 transition-shadow duration-200",
isHovered
? "shadow-[0_15px_35px_rgba(0,0,0,0.15)] dark:shadow-[0_15px_35px_rgba(0,0,0,0.3)]"
: "shadow-xl shadow-black/10 dark:shadow-black/25"
)}
<AuthCardShell
title={t("auth:login.title")}
background={<AnimatedBackground />}
topLeft={
<a
href="https://www.xtablo.com"
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<div className="mb-6 flex items-center justify-between">
<a
href="https://www.xtablo.com"
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
</svg>
{t("auth:common.backHome")}
</a>
{/* Theme Toggle */}
<Button
variant="ghost"
size="icon"
onClick={toggleTheme}
className="text-muted-foreground hover:text-foreground p-2"
aria-label={t("auth:common.themeToggle", { theme })}
>
{getThemeIcon()}
</Button>
</div>
{/* Xtablo Icon */}
<div className="flex justify-center mb-6">
<img
src="/logo_dark.png"
alt="Xtablo"
className="w-16 h-16 object-contain block dark:hidden"
<svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
<img
src="/logo_white.png"
alt="Xtablo"
className="w-16 h-16 object-contain hidden dark:block"
/>
</div>
</svg>
{t("auth:common.backHome")}
</a>
}
showThemeToggle
wrapperClassName="transition-transform duration-200 ease-out will-change-transform"
wrapperStyle={{ transform }}
onWrapperMouseMove={handleMouseMove}
onWrapperMouseLeave={handleMouseLeave}
isHovered={isHovered}
>
<div className="mb-6 text-center">
<Link
to="/login-v2"
className="inline-flex items-center text-sm text-[#804EEC] hover:text-[#6f3fd4] font-medium transition-colors"
>
{t("auth:login.newExperienceLink")}
</Link>
</div>
<h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-6 sm:mb-8 text-center">
{t("auth:login.title")}
</h1>
<div className="mb-6 text-center">
<Link
to="/login-v2"
className="inline-flex items-center text-sm text-[#804EEC] hover:text-[#6f3fd4] font-medium transition-colors"
>
{t("auth:login.newExperienceLink")}
</Link>
</div>
<div className="space-y-4 flex flex-col items-center">
<form className="space-y-4 w-full max-w-md mx-auto" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">
{t("common:labels.email")} <span className="text-red-500">*</span>
</Label>
<Input
id="email"
name="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
required
placeholder={t("auth:login.emailPlaceholder")}
/>
{errors?.email && <FieldError errors={[{ message: errors.email }]} />}
</div>
<div className="space-y-2">
<Label htmlFor="password">
{t("common:labels.password")} <span className="text-red-500">*</span>
</Label>
<Input
id="password"
name="password"
type="password"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
required
placeholder={t("auth:login.passwordPlaceholder")}
/>
{errors?.password && <FieldError errors={[{ message: errors.password }]} />}
</div>
<div className="flex items-center justify-end">
<Link
to="/reset-password"
className="text-sm text-purple-600 hover:text-purple-500 dark:text-purple-400 dark:hover:text-purple-300 transition-colors"
>
{t("auth:login.forgotPassword")}
</Link>
</div>
<Button className="w-full" type="submit">
{isPending ? t("auth:common.connecting") : t("auth:login.loginButton")}
</Button>
</form>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-border"></div>
</div>
<div className="relative flex justify-center text-sm">
<span
className={twMerge(
"px-4 py-1 bg-background",
"text-muted-foreground",
"text-sm font-medium",
"rounded-full",
"relative z-10",
"before:absolute before:w-[100px] before:h-px before:bg-border before:left-[-110px] before:top-1/2",
"after:absolute after:w-[100px] after:h-px after:bg-border after:right-[-110px] after:top-1/2"
)}
>
{t("auth:common.orContinue")}
</span>
</div>
</div>
<LoginWithGoogle />
<p className="text-center text-sm text-muted-foreground">
{t("auth:login.noAccount")}{" "}
<div className="space-y-4 flex flex-col items-center">
<AuthEmailPasswordForm
email={formData.email}
password={formData.password}
onEmailChange={(email: string) => setFormData({ ...formData, email })}
onPasswordChange={(password: string) => setFormData({ ...formData, password })}
onSubmit={onSubmit}
submitLabel={isPending ? t("auth:common.connecting") : t("auth:login.loginButton")}
emailLabel={`${t("common:labels.email")} *`}
passwordLabel={`${t("common:labels.password")} *`}
emailPlaceholder={t("auth:login.emailPlaceholder")}
passwordPlaceholder={t("auth:login.passwordPlaceholder")}
emailError={errors?.email}
passwordError={errors?.password}
extraContent={
<div className="flex items-center justify-end">
<Link
to="/signup"
className="text-foreground hover:text-foreground/80 font-medium text-sm px-2 py-1 rounded hover:bg-muted transition-colors"
to="/reset-password"
className="text-sm text-purple-600 hover:text-purple-500 dark:text-purple-400 dark:hover:text-purple-300 transition-colors"
>
{t("auth:login.signupLink")}
{t("auth:login.forgotPassword")}
</Link>
</p>
</div>
}
/>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-border"></div>
</div>
<div className="relative flex justify-center text-sm">
<span
className={twMerge(
"px-4 py-1 bg-background",
"text-muted-foreground",
"text-sm font-medium",
"rounded-full",
"relative z-10",
"before:absolute before:w-[100px] before:h-px before:bg-border before:left-[-110px] before:top-1/2",
"after:absolute after:w-[100px] after:h-px after:bg-border after:right-[-110px] after:top-1/2"
)}
>
{t("auth:common.orContinue")}
</span>
</div>
</div>
<LoginWithGoogle />
<p className="text-center text-sm text-muted-foreground">
{t("auth:login.noAccount")}{" "}
<Link
to="/signup"
className="text-foreground hover:text-foreground/80 font-medium text-sm px-2 py-1 rounded hover:bg-muted transition-colors"
>
{t("auth:login.signupLink")}
</Link>
</p>
</div>
</div>
</AuthCardShell>
);
}

View file

@ -61,6 +61,7 @@ const testUser: User = {
avatar_url: null,
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_signed_in: null,
plan: "none",
created_at: new Date("2026-01-01").toISOString(),

View file

@ -16,6 +16,7 @@ describe("ResetPasswordPage", () => {
it("renders form with email input", () => {
renderWithProviders(<ResetPasswordPage />);
expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument();
expect(screen.getByText(/forgot your password/i)).toBeInTheDocument();
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByRole("button", { name: /send reset link/i })).toBeInTheDocument();

View file

@ -1,13 +1,13 @@
import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui";
import { toast } from "@xtablo/shared";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { Text } from "@xtablo/ui/components/typography";
import { AlertCircle, CheckCircle2, Loader2Icon, MailIcon } from "lucide-react";
import { CheckCircle2, Loader2Icon, MailIcon } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import { twMerge } from "tailwind-merge";
import { supabase } from "../lib/supabase";
export function ResetPasswordPage() {
@ -49,113 +49,83 @@ export function ResetPasswordPage() {
if (isSubmitted) {
return (
<div
className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5"
onClick={() => navigate("/login")}
<AuthCardShell
title={t("resetPassword.emailSent")}
description={<Text>{t("resetPassword.checkInbox", { email })}</Text>}
onBackdropClick={() => navigate("/login")}
>
<div
className={twMerge(
"w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
"border border-border",
"shadow-xl"
)}
onClick={(e) => e.stopPropagation()}
>
<div className="text-center space-y-6">
<div className="flex justify-center">
<div className="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
<CheckCircle2 className="w-12 h-12 text-green-600 dark:text-green-400" />
</div>
<div className="space-y-6 text-center">
<div className="flex justify-center">
<div className="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
<CheckCircle2 className="w-12 h-12 text-green-600 dark:text-green-400" />
</div>
<div className="space-y-2">
<h1 className="text-3xl font-bold text-foreground">{t("resetPassword.emailSent")}</h1>
<Text className="text-muted-foreground">
{t("resetPassword.checkInbox", { email })}
</Text>
</div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="flex gap-3">
<MailIcon className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
<Text className="text-sm text-blue-800 dark:text-blue-200 text-left">
{t("resetPassword.emailInstructions")}
</Text>
</div>
</div>
<Link to="/login" className="block">
<Button className="mt-4">{t("resetPassword.backToLogin")}</Button>
</Link>
</div>
<AuthInfoBanner message={t("resetPassword.emailInstructions")} variant="info" />
<Link to="/login" className="block">
<Button className="mt-4">{t("resetPassword.backToLogin")}</Button>
</Link>
</div>
</div>
</AuthCardShell>
);
}
return (
<div
className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5"
onClick={() => navigate("/login")}
<AuthCardShell
title={t("resetPassword.title")}
description={<Text>{t("resetPassword.description")}</Text>}
onBackdropClick={() => navigate("/login")}
>
<div
className={twMerge(
"w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
"border border-border",
"shadow-xl"
)}
onClick={(e) => e.stopPropagation()}
>
<div className="space-y-6">
<div className="text-center">
<h1 className="text-3xl font-bold text-foreground mb-2">{t("resetPassword.title")}</h1>
<Text className="text-muted-foreground">{t("resetPassword.description")}</Text>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{t("resetPassword.emailLabel")}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t("resetPassword.emailPlaceholder")}
required
disabled={isPending}
className="transition-opacity disabled:opacity-50"
/>
</div>
{error && (
<div className="bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<div className="flex gap-3">
<AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0" />
<Text className="text-sm text-red-800 dark:text-red-200">{error}</Text>
</div>
</div>
)}
<Button className="w-full" type="submit" disabled={isPending}>
{isPending ? (
<>
<Loader2Icon className="w-4 h-4 mr-2 animate-spin" />
{t("resetPassword.sending")}
</>
) : (
t("resetPassword.submit")
)}
</Button>
</form>
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{t("resetPassword.emailLabel")}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t("resetPassword.emailPlaceholder")}
required
disabled={isPending}
className="transition-opacity disabled:opacity-50"
/>
</div>
<Button className="w-full" type="submit" disabled={isPending}>
{isPending ? (
<>
<Loader2Icon className="w-4 h-4 mr-2 animate-spin" />
{t("resetPassword.sending")}
</>
) : (
t("resetPassword.submit")
)}
</Button>
</form>
<p className="text-center text-sm text-muted-foreground">
<Link
to="/login"
className="text-foreground hover:text-foreground/80 font-medium transition-colors"
>
{t("resetPassword.backToLogin")}
</Link>
</p>
<div className="rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-800 dark:bg-blue-950/20">
<div className="flex gap-3">
<MailIcon className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
<Text className="text-sm text-blue-800 dark:text-blue-200">
{t("resetPassword.emailInstructions")}
</Text>
</div>
</div>
<p className="text-center text-sm text-muted-foreground">
<Link
to="/login"
className="text-foreground hover:text-foreground/80 font-medium transition-colors"
>
{t("resetPassword.backToLogin")}
</Link>
</p>
</div>
</div>
</AuthCardShell>
);
}

View file

@ -406,7 +406,7 @@ describe("TabloDetailsPage overview layout", () => {
expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toBeInTheDocument();
});
it("uses the standard email invite UI in the share dialog", async () => {
it("uses the client password invite UI in the share dialog", async () => {
const user = userEvent.setup();
renderWithProviders(<TabloDetailsPage />, {
@ -416,9 +416,10 @@ describe("TabloDetailsPage overview layout", () => {
await user.click(screen.getByRole("button", { name: "Inviter" }));
expect(screen.getByText("Inviter un utilisateur")).toBeInTheDocument();
expect(screen.getByPlaceholderText("Email de l'utilisateur à inviter")).toBeInTheDocument();
expect(screen.queryByText("Accès client")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Envoyer le lien" })).not.toBeInTheDocument();
expect(screen.getByText("Accès client")).toBeInTheDocument();
expect(screen.getByPlaceholderText("Email du client")).toBeInTheDocument();
expect(screen.getByText(/définir son mot de passe/i)).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Envoyer l'invitation" })).toBeInTheDocument();
expect(screen.queryByText("Inviter un utilisateur")).not.toBeInTheDocument();
});
});

View file

@ -5,20 +5,20 @@ import type { KanbanTask } from "@xtablo/shared-types";
import {
DEFAULT_OVERVIEW_LAYOUT,
EtapesSection,
getSingleTabloStatusConfig,
moveBetweenZones,
moveWithinZone,
type OverviewLayoutV1,
RoadmapSection,
SingleTabloOverview,
type SingleTabloTabId,
SingleTabloView,
sanitizeOverviewLayout,
TabloDiscussionSection,
TabloEventsSection,
TabloFilesSection,
TabloTasksSection,
TaskModal,
getSingleTabloStatusConfig,
moveBetweenZones,
moveWithinZone,
sanitizeOverviewLayout,
type SingleTabloTabId,
useChatUnread,
} from "@xtablo/tablo-views";
import { Avatar, AvatarFallback, AvatarImage } from "@xtablo/ui/components/avatar";
@ -86,8 +86,7 @@ const TAB_SECTIONS: TabSection[] = [
"roadmap",
];
// Temporary rollback until the client portal invite flow is ready to be used again.
const USE_CLIENT_MAGIC_LINK_INVITES = false;
const USE_CLIENT_PASSWORD_INVITES = true;
// ─── Page ─────────────────────────────────────────────────────────────────────
@ -337,166 +336,166 @@ export const TabloDetailsPage = () => {
return (
<>
<SingleTabloView
tablo={tablo}
roleLabel={isAdmin ? "Admin" : "Invité"}
statusLabel={statusLabel}
statusBadgeClass={badgeClass}
progress={progress}
activeTab={activeSection}
onTabChange={(tabId) => setSearchParams({ section: tabId })}
hasUnreadDiscussion={hasUnreadDiscussion}
discussionAction={{ kind: "link", to: `/chat/${tabloId}` }}
canInviteMembers={isAdmin}
onOpenInviteDialog={() => setIsShareDialogOpen(true)}
>
{activeSection === "overview" && (
<SingleTabloOverview
roleLabel={isAdmin ? "Admin" : "Invité"}
statusLabel={statusLabel}
statusBadgeClass={badgeClass}
description="Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les onglets ci-dessus pour naviguer entre les différentes sections."
tasks={visibleOverviewTasks}
projectTaskCount={tabloTasks.length}
personalTaskCount={myTabloTasks.length}
fileNames={fileNames}
showFileMenu={true}
onOpenTasks={() => setSearchParams({ section: "tasks" })}
onOpenFiles={() => setSearchParams({ section: "files" })}
onCreateTask={() => openTaskModal(undefined, currentUser.id)}
onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })}
showAllTasks={showAllOverviewTasks}
onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)}
layout={overviewLayout}
canEditLayout={isAdmin}
isLayoutEditMode={isLayoutEditMode}
draggedBlock={draggedOverviewBlock}
onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)}
onResetLayout={handleResetOverviewLayout}
onBlockDragStart={handleOverviewBlockDragStart}
onBlockDragOver={handleOverviewBlockDragOver}
onBlockDrop={handleOverviewBlockDrop}
onBlockDragEnd={() => setDraggedOverviewBlock(null)}
/>
)}
tablo={tablo}
roleLabel={isAdmin ? "Admin" : "Invité"}
statusLabel={statusLabel}
statusBadgeClass={badgeClass}
progress={progress}
activeTab={activeSection}
onTabChange={(tabId) => setSearchParams({ section: tabId })}
hasUnreadDiscussion={hasUnreadDiscussion}
discussionAction={{ kind: "link", to: `/chat/${tabloId}` }}
canInviteMembers={isAdmin}
onOpenInviteDialog={() => setIsShareDialogOpen(true)}
>
{activeSection === "overview" && (
<SingleTabloOverview
roleLabel={isAdmin ? "Admin" : "Invité"}
statusLabel={statusLabel}
statusBadgeClass={badgeClass}
description="Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les onglets ci-dessus pour naviguer entre les différentes sections."
tasks={visibleOverviewTasks}
projectTaskCount={tabloTasks.length}
personalTaskCount={myTabloTasks.length}
fileNames={fileNames}
showFileMenu={true}
onOpenTasks={() => setSearchParams({ section: "tasks" })}
onOpenFiles={() => setSearchParams({ section: "files" })}
onCreateTask={() => openTaskModal(undefined, currentUser.id)}
onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })}
showAllTasks={showAllOverviewTasks}
onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)}
layout={overviewLayout}
canEditLayout={isAdmin}
isLayoutEditMode={isLayoutEditMode}
draggedBlock={draggedOverviewBlock}
onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)}
onResetLayout={handleResetOverviewLayout}
onBlockDragStart={handleOverviewBlockDragStart}
onBlockDragOver={handleOverviewBlockDragOver}
onBlockDrop={handleOverviewBlockDrop}
onBlockDragEnd={() => setDraggedOverviewBlock(null)}
/>
)}
{activeSection === "tasks" && (
<TabloTasksSection
tablo={tablo}
isAdmin={isAdmin}
tasks={tabloTasks}
members={members}
etapes={etapes}
currentUser={currentUser}
pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))}
isInvitingUser={isInvitingUser}
isCancellingInvite={isCancellingInvite}
onCreateTask={(task) => createTask(task)}
onUpdateTask={(task) => updateTask(task)}
onDeleteTask={(taskId) => deleteTask(taskId)}
onUpdateTaskPositions={(updates) => updateTaskPositions(updates)}
onUpdateTablo={(data) =>
updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined)
}
onInviteUser={inviteUser}
onCancelInvite={(params) =>
cancelInvite({ ...params, inviteId: Number(params.inviteId) })
}
/>
)}
{activeSection === "files" && (
<TabloFilesSection
tablo={tablo}
isAdmin={isAdmin}
currentUserId={currentUser.id}
fileNames={fileNames}
filesLoading={false}
filesError={null}
folders={foldersData?.folders ?? []}
foldersLoading={foldersLoading}
foldersError={foldersError as Error | null}
currentUser={currentUser}
members={members}
pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))}
isInvitingUser={isInvitingUser}
isCancellingInvite={isCancellingInvite}
isCreatingFolder={isCreatingFolder}
isUpdatingFolder={isUpdatingFolder}
onCreateFile={(params) => uploadFile(params).then(() => undefined)}
onDeleteFile={(params) => deleteFile(params).then(() => undefined)}
onDownloadFile={(params) => downloadFile(params).then(() => undefined)}
onCreateFolder={(params) => createFolder(params).then(() => undefined)}
onUpdateFolder={(params) => updateFolder(params).then(() => undefined)}
onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)}
onUpdateTablo={(data) =>
updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined)
}
onInviteUser={inviteUser}
onCancelInvite={(params) =>
cancelInvite({ ...params, inviteId: Number(params.inviteId) })
}
/>
)}
{activeSection === "discussion" && (
<div className="flex-1 min-h-0">
<TabloDiscussionSection
{activeSection === "tasks" && (
<TabloTasksSection
tablo={tablo}
isAdmin={isAdmin}
tasks={tabloTasks}
members={members}
etapes={etapes}
currentUser={currentUser}
pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))}
isInvitingUser={isInvitingUser}
isCancellingInvite={isCancellingInvite}
onCreateTask={(task) => createTask(task)}
onUpdateTask={(task) => updateTask(task)}
onDeleteTask={(taskId) => deleteTask(taskId)}
onUpdateTaskPositions={(updates) => updateTaskPositions(updates)}
onUpdateTablo={(data) =>
updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined)
}
onInviteUser={inviteUser}
onCancelInvite={(params) =>
cancelInvite({ ...params, inviteId: Number(params.inviteId) })
}
/>
)}
{activeSection === "files" && (
<TabloFilesSection
tablo={tablo}
isAdmin={isAdmin}
currentUserId={currentUser.id}
fileNames={fileNames}
filesLoading={false}
filesError={null}
folders={foldersData?.folders ?? []}
foldersLoading={foldersLoading}
foldersError={foldersError as Error | null}
currentUser={currentUser}
members={members}
pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))}
isInvitingUser={isInvitingUser}
isCancellingInvite={isCancellingInvite}
isCreatingFolder={isCreatingFolder}
isUpdatingFolder={isUpdatingFolder}
onCreateFile={(params) => uploadFile(params).then(() => undefined)}
onDeleteFile={(params) => deleteFile(params).then(() => undefined)}
onDownloadFile={(params) => downloadFile(params).then(() => undefined)}
onCreateFolder={(params) => createFolder(params).then(() => undefined)}
onUpdateFolder={(params) => updateFolder(params).then(() => undefined)}
onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)}
onUpdateTablo={(data) =>
updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined)
}
onInviteUser={inviteUser}
onCancelInvite={(params) =>
cancelInvite({ ...params, inviteId: Number(params.inviteId) })
}
/>
</div>
)}
{activeSection === "events" && (
<TabloEventsSection
tablo={tablo}
isAdmin={isAdmin}
events={events ?? []}
isLoading={eventsLoading}
error={eventsError as Error | null}
currentUser={currentUser}
members={members}
pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))}
isInvitingUser={isInvitingUser}
isCancellingInvite={isCancellingInvite}
onCreateEvent={() => undefined}
onUpdateTablo={(data) =>
updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined)
}
onInviteUser={inviteUser}
onCancelInvite={(params) =>
cancelInvite({ ...params, inviteId: Number(params.inviteId) })
}
/>
)}
)}
{activeSection === "discussion" && (
<div className="flex-1 min-h-0">
<TabloDiscussionSection
tablo={tablo}
isAdmin={isAdmin}
currentUserId={currentUser.id}
members={members}
/>
</div>
)}
{activeSection === "events" && (
<TabloEventsSection
tablo={tablo}
isAdmin={isAdmin}
events={events ?? []}
isLoading={eventsLoading}
error={eventsError as Error | null}
currentUser={currentUser}
members={members}
pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))}
isInvitingUser={isInvitingUser}
isCancellingInvite={isCancellingInvite}
onCreateEvent={() => undefined}
onUpdateTablo={(data) =>
updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined)
}
onInviteUser={inviteUser}
onCancelInvite={(params) =>
cancelInvite({ ...params, inviteId: Number(params.inviteId) })
}
/>
)}
{activeSection === "etapes" && (
<EtapesSection
etapes={etapes}
tabloTasks={tabloTasks}
tabloId={tabloId ?? ""}
isAdmin={isAdmin}
onCreateTask={(task) =>
createTask({
...task,
status: task.status as "todo" | "in_progress" | "in_review" | "done",
})
}
onCreateEtape={(params) => createEtape(params).then(() => undefined)}
onUpdateEtape={(params) => updateEtape(params).then(() => undefined)}
onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)}
isCreatingEtape={isCreatingEtape}
isUpdatingEtape={isUpdatingEtape}
isDeletingEtape={isDeletingEtape}
/>
)}
{activeSection === "etapes" && (
<EtapesSection
etapes={etapes}
tabloTasks={tabloTasks}
tabloId={tabloId ?? ""}
isAdmin={isAdmin}
onCreateTask={(task) =>
createTask({
...task,
status: task.status as "todo" | "in_progress" | "in_review" | "done",
})
}
onCreateEtape={(params) => createEtape(params).then(() => undefined)}
onUpdateEtape={(params) => updateEtape(params).then(() => undefined)}
onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)}
isCreatingEtape={isCreatingEtape}
isUpdatingEtape={isUpdatingEtape}
isDeletingEtape={isDeletingEtape}
/>
)}
{activeSection === "roadmap" && (
<RoadmapSection
tabloTasks={tabloTasks}
onDateClick={openTaskModal}
onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })}
/>
)}
{activeSection === "roadmap" && (
<RoadmapSection
tabloTasks={tabloTasks}
onDateClick={openTaskModal}
onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })}
/>
)}
</SingleTabloView>
{/* Task Create Modal */}
@ -564,12 +563,13 @@ export const TabloDetailsPage = () => {
{/* Separator */}
<div className="border-t border-border pt-4">
{USE_CLIENT_MAGIC_LINK_INVITES ? (
{USE_CLIENT_PASSWORD_INVITES ? (
<>
<div className="mb-3">
<h4 className="text-sm font-semibold text-foreground">Accès client</h4>
<p className="text-xs text-muted-foreground">
Invitez des clients externes via un lien magique
Le client recevra un email pour définir son mot de passe ou, s'il a déjà un
compte, une notification d'accès directe à ce tablo.
</p>
</div>
@ -598,7 +598,7 @@ export const TabloDetailsPage = () => {
}}
disabled={!isEmailValid(clientInviteEmail)}
>
Envoyer le lien
Envoyer l'invitation
</Button>
)}
</div>
@ -681,7 +681,9 @@ export const TabloDetailsPage = () => {
) : (
<>
<div className="mb-3">
<h4 className="text-sm font-semibold text-foreground">Inviter un utilisateur</h4>
<h4 className="text-sm font-semibold text-foreground">
Inviter un utilisateur
</h4>
<p className="text-xs text-muted-foreground">
Utilisez le système d'invitation standard par email pour le moment
</p>

View file

@ -1,8 +1,8 @@
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TasksPage } from "./tasks";
import { renderWithProviders } from "../utils/testHelpers";
import { TasksPage } from "./tasks";
const mutateUpdateTask = vi.fn();
const mutateDeleteTask = vi.fn();

View file

@ -63,6 +63,7 @@ describe("TestUserStoreProvider", () => {
first_name: null,
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_name: null,
short_user_id: "short-id",
last_signed_in: null,

View file

@ -19,6 +19,7 @@ const defaultUser = {
avatar_url: "https://example.com/avatar.jpg",
is_temporary: false,
is_client: false,
client_onboarded_at: null,
last_signed_in: null,
plan: "none" as const,
created_at: new Date().toISOString(),

View file

@ -27,6 +27,8 @@
"paths": {
"*": ["./*"],
"@ui/*": ["./src/*"],
"@xtablo/auth-ui": ["../../packages/auth-ui/src"],
"@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"],
"@xtablo/ui/*": ["../../packages/ui/src/*"]
}
},

View file

@ -13,6 +13,12 @@
"apps/api/*.{ts,tsx,js,jsx,json}",
"packages/ui/src/**/*",
"packages/ui/*.{ts,tsx,js,jsx,json}",
"packages/tablo-views/src/**/*",
"packages/tablo-views/*.{ts,tsx,js,jsx,json}",
"packages/auth-ui/src/**/*",
"packages/auth-ui/*.{ts,tsx,js,jsx,json}",
"packages/chat-ui/src/**/*",
"packages/chat-ui/*.{ts,tsx,js,jsx,json}",
"packages/shared/src/**/*",
"packages/shared/*.{ts,tsx,js,jsx,json}",
"packages/shared-types/src/**/*",
@ -298,6 +304,12 @@
"apps/api/*.{ts,tsx}",
"packages/ui/src/**/*.{ts,tsx}",
"packages/ui/*.{ts,tsx}",
"packages/tablo-views/src/**/*.{ts,tsx}",
"packages/tablo-views/*.{ts,tsx}",
"packages/auth-ui/src/**/*.{ts,tsx}",
"packages/auth-ui/*.{ts,tsx}",
"packages/chat-ui/src/**/*.{ts,tsx}",
"packages/chat-ui/*.{ts,tsx}",
"packages/shared/src/**/*.{ts,tsx}",
"packages/shared/*.{ts,tsx}",
"packages/shared-types/src/**/*.{ts,tsx}",

View file

@ -0,0 +1,626 @@
# Client Password Invite Flow Implementation Plan
> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace the client magic-link callback flow with one-time password setup plus normal email/password login in `apps/clients`, while keeping client users restricted to the client portal.
**Architecture:** Keep Supabase Auth as the identity provider, but move invite lifecycle decisions into the API. The backend creates or reuses one client account per email, then branches between an onboarding email with a one-time setup token and an access-notification email for already-onboarded clients. On the frontend, extract the main login visual shell into a shared auth UI surface, add client login/set-password/reset routes, and redirect protected client routes through login with destination resume.
**Tech Stack:** Hono API, Supabase Auth, React 19, React Router, TanStack Query, Tailwind CSS v4, pnpm workspaces, Vitest.
**Spec:** `docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md`
---
## File Structure
### New files
**Database**
- `supabase/migrations/20260418110000_client_password_invites.sql` — replaces callback-oriented invite semantics with setup-token lifecycle fields and client-only auth metadata
**Shared auth UI**
- `packages/auth-ui/package.json` — shared auth UI package manifest if no existing package is a clean fit
- `packages/auth-ui/tsconfig.json` — package tsconfig
- `packages/auth-ui/src/index.ts` — barrel exports
- `packages/auth-ui/src/AuthCardShell.tsx` — shared auth page background, card shell, logo, theme toggle, and content slot
- `packages/auth-ui/src/AuthEmailPasswordForm.tsx` — shared email/password form layout with error and loading states
- `packages/auth-ui/src/AuthInfoBanner.tsx` — shared inline success/error/info banner component used by login/reset/setup screens
**Client auth pages**
- `apps/clients/src/pages/LoginPage.tsx` — client login screen using shared auth UI
- `apps/clients/src/pages/ResetPasswordPage.tsx` — client forgot-password page
- `apps/clients/src/pages/SetPasswordPage.tsx` — one-time invite setup screen
- `apps/clients/src/pages/LoginPage.test.tsx`
- `apps/clients/src/pages/ResetPasswordPage.test.tsx`
- `apps/clients/src/pages/SetPasswordPage.test.tsx`
- `apps/clients/src/components/ClientAuthGate.tsx` — preserves intended route and redirects unauthenticated users to login
**API tests**
- No brand-new top-level test files required if the current route tests remain focused; extend:
- `apps/api/src/__tests__/routes/clientInvites.test.ts`
- `apps/api/src/__tests__/middlewares/middlewares.test.ts`
### Modified files
**API**
- `apps/api/src/routers/clientInvites.ts` — replace callback accept flow with setup-token create/validate/complete flow plus access-notification branch
- `apps/api/src/helpers/helpers.ts` — split current `createClientUser()` into clearer helpers for create/reuse account, detect onboarding state, and grant tablo access
- `apps/api/src/routers/index.ts` or the file that mounts `clientInvites` — ensure new routes are exposed
- `apps/api/src/middlewares/middleware.ts` — keep client users blocked from regular main-app routes; tighten behavior if needed
- `apps/api/src/__tests__/routes/clientInvites.test.ts` — cover onboarding vs notification, token validation, single use, cancellation, and app-boundary expectations
- `apps/api/src/__tests__/middlewares/middlewares.test.ts` — keep client-only users rejected by main-app middleware
**Shared types**
- `packages/shared-types/src/database.types.ts` — add migration-driven type updates for `client_invites` and any new client auth columns
**Main app frontend**
- `apps/main/src/pages/tablo-details.tsx` — update invite dialog submit flow and text for password-setup onboarding / access notification messaging
- `apps/main/src/pages/tablo-details.layout.test.tsx` — cover active magic-link invite UI copy and success states after the backend contract change
- `apps/main/src/pages/login.tsx` — consume shared auth shell/form pieces after extraction
- `apps/main/src/pages/reset-password.tsx` — consume shared auth shell/form pieces after extraction
- `apps/main/src/hooks/client_invites.ts` — adapt to the updated invite response shape if needed
- `apps/main/src/hooks/auth.ts` — optionally extract reusable login/reset behavior or keep app-specific logic while sharing visuals
- `apps/main/src/pages/login.test.tsx`
- `apps/main/src/pages/reset-password.test.tsx`
**Client app frontend**
- `apps/clients/src/routes.tsx` — add `/login`, `/reset-password`, `/set-password`, and redirect handling; remove `/auth/callback` from primary flow
- `apps/clients/src/components/ClientLayout.tsx` — stop rendering dead-end unauthorized state and rely on auth gate redirect behavior
- `apps/clients/src/lib/supabase.ts` — no behavioral change expected, but verify redirect URLs and auth persistence assumptions
- `apps/clients/src/i18n.ts` — add auth namespaces reused from main or from shared locale files
- `apps/clients/src/main.tsx` — ensure new pages have needed providers
- `apps/clients/src/pages/AuthCallback.tsx` — remove or reduce to a temporary compatibility shim
- `apps/clients/src/pages/ClientTabloPage.tsx`
- `apps/clients/src/pages/ClientTabloListPage.tsx`
- `apps/clients/src/components/ClientLayout.test.tsx`
- `apps/clients/src/pages/ClientTabloPage.test.tsx`
---
## Chunk 1: Database And API Invite Lifecycle
### Task 1: Replace callback invite semantics with setup-token lifecycle
**Files:**
- Create: `supabase/migrations/20260418110000_client_password_invites.sql`
- Modify: `packages/shared-types/src/database.types.ts`
- Test: `apps/api/src/__tests__/routes/clientInvites.test.ts`
- [ ] **Step 1: Write the failing API test cases for the new lifecycle**
Add or replace route tests in `apps/api/src/__tests__/routes/clientInvites.test.ts` for:
```ts
it("creates a setup token for a first-time client invite", async () => {});
it("does not create a setup token for an already-onboarded client", async () => {});
it("rejects reused setup tokens", async () => {});
it("rejects expired setup tokens", async () => {});
it("marks cancelled pending setup tokens unusable", async () => {});
```
Model the first-time case so it asserts:
- `client_invites.is_pending === true`
- a setup token exists
- `sendMail` is called with a setup URL targeting `clients.xtablo.com`
Model the onboarded case so it asserts:
- no new setup token row is created
- `sendMail` is called with a direct `/tablo/:tabloId` URL
- [ ] **Step 2: Run the targeted API tests to verify failure**
Run:
```bash
pnpm --filter @xtablo/api test -- clientInvites.test.ts
```
Expected:
- FAIL because the current router still creates magic-link callback invites and still exposes `/accept/:token`
- [ ] **Step 3: Write the migration**
In `supabase/migrations/20260418110000_client_password_invites.sql`, evolve `client_invites` for setup-token lifecycle. Prefer modifying the existing table shape over creating a second invite table.
The migration should include the minimal schema required for:
```sql
ALTER TABLE public.client_invites
ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup',
ADD COLUMN IF NOT EXISTS used_at timestamptz,
ADD COLUMN IF NOT EXISTS cancelled_at timestamptz,
ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz;
-- If the old callback flow uses invite_token generically, keep the column
-- but redefine its meaning as the setup token for setup invites.
CREATE INDEX IF NOT EXISTS idx_client_invites_email_tablo_pending
ON public.client_invites (invited_email, tablo_id, is_pending);
```
Also add any client-account marker needed to distinguish:
- invited client users who have not completed password setup
- onboarded client users who already have password login
Keep the schema minimal. Avoid adding fields that can be derived from auth state unless tests require them.
- [ ] **Step 4: Update generated database types**
Update `packages/shared-types/src/database.types.ts` to reflect the migration:
- new `client_invites` columns
- any added client-profile/account lifecycle columns
Use the repos current type-generation practice if available; otherwise make the minimal manual edit and note it in the commit message.
- [ ] **Step 5: Refactor helper boundaries before touching the router**
In `apps/api/src/helpers/helpers.ts`, split the current client invite helper behavior into smaller pieces with one responsibility each:
```ts
export async function findOrCreateClientAccount(...) {}
export async function ensureClientTabloAccess(...) {}
export async function hasCompletedClientOnboarding(...) {}
export async function createClientSetupInvite(...) {}
```
Do not keep all onboarding, auth-user creation, and tablo-access behavior fused into one large helper.
- [ ] **Step 6: Replace callback endpoints with setup-token endpoints**
In `apps/api/src/routers/clientInvites.ts`, change the route surface to:
```ts
POST /client-invites/:tabloId
GET /client-invites/setup/:token
POST /client-invites/setup/:token
GET /client-invites/:tabloId/pending
DELETE /client-invites/:tabloId/:inviteId
```
Behavior:
- `POST /:tabloId`
- create/reuse client account
- ensure tablo access
- if account is not onboarded: create pending setup token + send setup email
- if account is onboarded: skip setup token + send access notification email to `/tablo/:tabloId`
- `GET /setup/:token`
- return token metadata for `SetPasswordPage`
- reject missing / expired / cancelled / already-used tokens
- `POST /setup/:token`
- validate token again
- set password for the client auth user
- mark invite consumed immediately
- return success payload for the frontend
Remove callback-style `accept/:token` logic from the primary flow.
- [ ] **Step 7: Keep `apps/main` protected from client-only users**
In `apps/api/src/middlewares/middleware.ts`, verify that `regularUserCheck` or equivalent main-app guard rejects `is_client` users cleanly. If the current behavior is already correct, only tighten the tests and leave code untouched.
Add or update targeted test coverage in `apps/api/src/__tests__/middlewares/middlewares.test.ts`:
```ts
it("returns 401 for client-only users on main-app protected routes", async () => {});
```
- [ ] **Step 8: Run API verification**
Run:
```bash
pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts
pnpm --filter @xtablo/api typecheck
```
Expected:
- PASS for invite lifecycle and middleware protection coverage
- [ ] **Step 9: Commit**
```bash
git add supabase/migrations/20260418110000_client_password_invites.sql \
packages/shared-types/src/database.types.ts \
apps/api/src/helpers/helpers.ts \
apps/api/src/routers/clientInvites.ts \
apps/api/src/__tests__/routes/clientInvites.test.ts \
apps/api/src/__tests__/middlewares/middlewares.test.ts \
apps/api/src/middlewares/middleware.ts
git commit -m "feat(api): add client password setup invite flow"
```
---
## Chunk 2: Shared Auth UI Extraction
### Task 2: Extract the main login visual shell into a shared package
**Files:**
- Create: `packages/auth-ui/package.json`
- Create: `packages/auth-ui/tsconfig.json`
- Create: `packages/auth-ui/src/index.ts`
- Create: `packages/auth-ui/src/AuthCardShell.tsx`
- Create: `packages/auth-ui/src/AuthEmailPasswordForm.tsx`
- Create: `packages/auth-ui/src/AuthInfoBanner.tsx`
- Modify: `apps/main/src/pages/login.tsx`
- Modify: `apps/main/src/pages/reset-password.tsx`
- Test: `apps/main/src/pages/login.test.tsx`
- Test: `apps/main/src/pages/reset-password.test.tsx`
- [ ] **Step 1: Write failing rendering tests around the shared auth shell contract**
Before extracting, add or update tests that pin the current main auth page structure at the right level:
```ts
it("renders the main login page through a reusable auth shell", async () => {});
it("renders the reset-password page through the shared auth shell", async () => {});
```
Assert only stable behavior:
- heading renders
- email/password fields render
- forgot-password link renders
- shared shell wrapper test id or landmark renders
Do not snapshot the entire page.
- [ ] **Step 2: Run the main auth tests to verify current coverage gap**
Run:
```bash
pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev
```
Expected:
- FAIL or insufficient coverage for the extraction seam
- [ ] **Step 3: Extract presentation-only auth UI**
Create `packages/auth-ui` and move only visual/auth-form composition into it.
Recommended split:
```tsx
// AuthCardShell.tsx
export function AuthCardShell(props: {
title: string;
children: React.ReactNode;
backHomeHref?: string;
footer?: React.ReactNode;
}) {}
// AuthEmailPasswordForm.tsx
export function AuthEmailPasswordForm(props: {
email: string;
password: string;
onEmailChange: (value: string) => void;
onPasswordChange: (value: string) => void;
onSubmit: (e: React.FormEvent) => void;
isPending?: boolean;
emailError?: string;
passwordError?: string;
submitLabel: string;
forgotPasswordHref?: string;
}) {}
```
Keep:
- theme toggle
- background
- card framing
- logo block
- stable form spacing and typography
Out of scope for the shared package:
- actual Supabase mutations
- route-specific navigation
- Google login wiring
- signup flow behavior
- [ ] **Step 4: Refactor main login and reset pages onto the shared auth UI**
Update:
- `apps/main/src/pages/login.tsx`
- `apps/main/src/pages/reset-password.tsx`
Keep existing behavior intact while removing duplicated layout markup.
- [ ] **Step 5: Run verification for main auth pages**
Run:
```bash
pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev
pnpm --filter @xtablo/main typecheck
pnpm --filter @xtablo/auth-ui typecheck
```
Expected:
- PASS with no behavior regression in main auth pages
- [ ] **Step 6: Commit**
```bash
git add packages/auth-ui \
apps/main/src/pages/login.tsx \
apps/main/src/pages/reset-password.tsx \
apps/main/src/pages/login.test.tsx \
apps/main/src/pages/reset-password.test.tsx
git commit -m "refactor(auth): extract shared auth ui"
```
---
## Chunk 3: Client Portal Auth Routes And Redirect Flow
### Task 3: Add client login, reset-password, set-password, and redirect memory
**Files:**
- Create: `apps/clients/src/components/ClientAuthGate.tsx`
- Create: `apps/clients/src/pages/LoginPage.tsx`
- Create: `apps/clients/src/pages/ResetPasswordPage.tsx`
- Create: `apps/clients/src/pages/SetPasswordPage.tsx`
- Modify: `apps/clients/src/routes.tsx`
- Modify: `apps/clients/src/components/ClientLayout.tsx`
- Modify: `apps/clients/src/pages/AuthCallback.tsx`
- Modify: `apps/clients/src/i18n.ts`
- Test: `apps/clients/src/pages/LoginPage.test.tsx`
- Test: `apps/clients/src/pages/ResetPasswordPage.test.tsx`
- Test: `apps/clients/src/pages/SetPasswordPage.test.tsx`
- Test: `apps/clients/src/components/ClientLayout.test.tsx`
- Test: `apps/clients/src/pages/ClientTabloPage.test.tsx`
- [ ] **Step 1: Write failing client auth route tests**
Add coverage for the new expected client behavior:
```ts
it("redirects unauthenticated /tablo/:tabloId requests to /login and resumes after login", async () => {});
it("renders the client login page with shared auth ui", async () => {});
it("submits forgot-password from the client login flow", async () => {});
it("renders an invalid-token state on the set-password page", async () => {});
it("submits password setup once and rejects token reuse", async () => {});
```
Prefer route-level tests with mocked Supabase/API behavior over isolated unit tests.
- [ ] **Step 2: Run the client auth tests to verify failure**
Run:
```bash
pnpm --filter @xtablo/clients exec vitest run \
src/components/ClientLayout.test.tsx \
src/pages/ClientTabloPage.test.tsx \
src/pages/LoginPage.test.tsx \
src/pages/ResetPasswordPage.test.tsx \
src/pages/SetPasswordPage.test.tsx \
--mode dev
```
Expected:
- FAIL because `/login`, `/reset-password`, and `/set-password` do not exist and protected client routes do not redirect correctly
- [ ] **Step 3: Add a client auth gate with redirect memory**
Create `apps/clients/src/components/ClientAuthGate.tsx` with behavior like:
```tsx
export function ClientAuthGate({ children }: { children: React.ReactNode }) {
// if no session:
// store current pathname + search in localStorage
// navigate("/login")
// else render children
}
```
Use a client-specific storage key such as:
```ts
const CLIENT_REDIRECT_KEY = "clients.redirectUrl";
```
Do not reuse the main apps generic redirect key unless the semantics are already isolated per app.
- [ ] **Step 4: Build the client login and reset pages on top of shared auth UI**
Implement:
- `apps/clients/src/pages/LoginPage.tsx`
- `apps/clients/src/pages/ResetPasswordPage.tsx`
Behavior:
- login via `supabase.auth.signInWithPassword`
- forgot-password via `supabase.auth.resetPasswordForEmail`
- no signup affordance
- successful login resumes `clients.redirectUrl` if present, otherwise `/`
- [ ] **Step 5: Build the one-time set-password page**
Implement `apps/clients/src/pages/SetPasswordPage.tsx`:
- read the token from the URL
- call `GET /api/v1/client-invites/setup/:token` on mount
- render clear invalid / expired / used states
- submit new password to `POST /api/v1/client-invites/setup/:token`
- after success, sign in the user and navigate to the granted destination
If the API returns enough information to sign the user in directly, use it. If not, perform a normal `signInWithPassword` after successful setup using the freshly set password.
- [ ] **Step 6: Update client routes and remove callback-first flow**
In `apps/clients/src/routes.tsx`, move to:
```tsx
<Route path="/login" element={<LoginPage />} />
<Route path="/reset-password" element={<ResetPasswordPage />} />
<Route path="/set-password" element={<SetPasswordPage />} />
<Route element={<ClientLayout />}>
<Route path="/tablo/:tabloId" element={<ClientAuthGate><ClientTabloPage /></ClientAuthGate>} />
<Route path="/" element={<ClientAuthGate><ClientTabloListPage /></ClientAuthGate>} />
</Route>
```
Reduce `AuthCallback.tsx` to:
- temporary compatibility notice, or
- redirect to `/login`
Do not leave it as the primary entry path.
- [ ] **Step 7: Update client translations and copy**
In `apps/clients/src/i18n.ts`, reuse the main auth namespace if practical. If not, add the minimal client auth keys needed without duplicating the entire namespace unnecessarily.
Required copy states:
- login
- forgot password
- set password
- invalid token
- expired token
- already-used token
- access granted / password set success
- [ ] **Step 8: Run client verification**
Run:
```bash
pnpm --filter @xtablo/clients exec vitest run \
src/components/ClientLayout.test.tsx \
src/pages/ClientTabloPage.test.tsx \
src/pages/LoginPage.test.tsx \
src/pages/ResetPasswordPage.test.tsx \
src/pages/SetPasswordPage.test.tsx \
--mode dev
pnpm --filter @xtablo/clients typecheck
```
Expected:
- PASS for login, reset-password, set-password, and redirect-resume flow
- [ ] **Step 9: Commit**
```bash
git add apps/clients/src/routes.tsx \
apps/clients/src/components/ClientAuthGate.tsx \
apps/clients/src/components/ClientLayout.tsx \
apps/clients/src/pages/LoginPage.tsx \
apps/clients/src/pages/ResetPasswordPage.tsx \
apps/clients/src/pages/SetPasswordPage.tsx \
apps/clients/src/pages/AuthCallback.tsx \
apps/clients/src/i18n.ts \
apps/clients/src/pages/LoginPage.test.tsx \
apps/clients/src/pages/ResetPasswordPage.test.tsx \
apps/clients/src/pages/SetPasswordPage.test.tsx \
apps/clients/src/components/ClientLayout.test.tsx \
apps/clients/src/pages/ClientTabloPage.test.tsx
git commit -m "feat(clients): add password auth onboarding flow"
```
---
## Chunk 4: Main Invite UI And Full Verification
### Task 4: Update main-app invite UX to match the new backend contract
**Files:**
- Modify: `apps/main/src/pages/tablo-details.tsx`
- Modify: `apps/main/src/hooks/client_invites.ts`
- Modify: `apps/main/src/pages/tablo-details.layout.test.tsx`
- [ ] **Step 1: Write failing main invite flow tests**
Extend `apps/main/src/pages/tablo-details.layout.test.tsx` with cases like:
```ts
it("shows password-setup onboarding messaging for first-time client invites", async () => {});
it("shows access-notification messaging for already-onboarded client invites", async () => {});
```
Assert only the user-facing contract:
- client invite UI is visible
- email field submits
- success state reflects either setup email sent or access notification sent
- [ ] **Step 2: Run the targeted main invite tests**
Run:
```bash
pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx --mode dev
```
Expected:
- FAIL because current UI still assumes the callback-style invite flow
- [ ] **Step 3: Update the main invite hook contract**
In `apps/main/src/hooks/client_invites.ts`, align the mutation response typing with the new API payload, for example:
```ts
type ClientInviteResponse = {
success: true;
inviteMode: "setup" | "notification";
};
```
Avoid frontend logic that infers email mode from copy alone.
- [ ] **Step 4: Update share-dialog copy and success handling**
In `apps/main/src/pages/tablo-details.tsx`, keep the client invite UI active, but change the submission/success states to match the new flow:
- first-time invite: explain that the client will receive a password-setup email
- existing client: explain that the client will receive a direct access notification
Do not reintroduce the old standard-email collaborator invite UI for this flow.
- [ ] **Step 5: Run focused frontend verification**
Run:
```bash
pnpm --filter @xtablo/main exec vitest run \
src/pages/tablo-details.layout.test.tsx \
src/pages/login.test.tsx \
src/pages/reset-password.test.tsx \
--mode dev
pnpm --filter @xtablo/main typecheck
```
Expected:
- PASS for share dialog copy, login page extraction, and reset page extraction
- [ ] **Step 6: Run cross-app final verification**
Run:
```bash
pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts
pnpm --filter @xtablo/api typecheck
pnpm --filter @xtablo/auth-ui typecheck
pnpm --filter @xtablo/main typecheck
pnpm --filter @xtablo/clients typecheck
pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev
pnpm --filter @xtablo/clients exec vitest run src/components/ClientLayout.test.tsx src/pages/ClientTabloPage.test.tsx src/pages/LoginPage.test.tsx src/pages/ResetPasswordPage.test.tsx src/pages/SetPasswordPage.test.tsx --mode dev
```
If the API tests require local Supabase migrations first, run the repo-standard migration command before rerunning tests and record that in the implementation notes.
- [ ] **Step 7: Commit**
```bash
git add apps/main/src/pages/tablo-details.tsx \
apps/main/src/hooks/client_invites.ts \
apps/main/src/pages/tablo-details.layout.test.tsx
git commit -m "feat(main): update client invite onboarding messaging"
```
---
## Completion Notes
- Keep commits small and aligned with the chunks above.
- Do not reintroduce permanent bearer links.
- Do not allow client-only users through `apps/main` guards, even if they authenticate successfully.
- Do not preserve `AuthCallback` as a hidden second primary flow; either remove it or make it an explicit compatibility dead-end.
- Prefer reusing the existing main auth translations where possible, but avoid coupling `apps/clients` directly to `apps/main` internals if extraction into a shared package is cleaner.

View file

@ -0,0 +1,318 @@
# Client Password Invite Flow
**Date**: 2026-04-18
**Status**: Draft
**Supersedes**: `docs/superpowers/specs/2026-04-15-client-magic-links-design.md`
## Overview
The current client invite flow is built around a magic-link callback path. That model is no longer the target.
`apps/clients` should become a normal password-based portal for invited client users. Invitations should bootstrap account access, not serve as the long-term authentication mechanism.
The revised flow is:
- a client is invited by email from `app.xtablo.com`
- if this email has not completed onboarding yet, the email contains a one-time password setup link
- the client sets a password once
- that setup link becomes invalid immediately after successful use
- all later access goes through a normal login form in `apps/clients`
- clients can reset their password themselves from the client login page
Client accounts are reused across multiple tablos by email. If a client who already has a password-based account is invited to another tablo, they should receive an access notification email instead of another password-setup link.
## Problem Statement
The current magic-link callback flow creates the wrong steady-state model for the client portal.
### Current issues
1. The invite email behaves as an authentication mechanism instead of a one-time onboarding step.
2. `apps/clients` does not provide a standard login form for later access.
3. The current callback-style flow is a poor fit for a client portal meant to feel like a stable authenticated product.
4. Reinviting the same email is awkward because the current model is centered around link acceptance rather than an account reused across multiple tablos.
5. The current flow does not express a strong boundary between `apps/main` users and `apps/clients` users.
## Goals
- Replace callback-style magic-link onboarding with one-time password setup
- Make `apps/clients` a normal email/password application after onboarding
- Reuse one client account per email across multiple tablos
- Allow self-service password reset from the client login page
- Support direct notification links to `clients.xtablo.com/tablo/:tabloId`
- Keep clients restricted to `apps/clients` only
- Reuse the main login page visual design through a shared auth UI surface
## Non-Goals
- Permanent bearer links that grant direct tablo access without authentication
- Self-service client signup without invitation
- Creating a separate custom auth system outside Supabase
- Granting client-portal users access to `apps/main`
- Preserving the current callback-based onboarding as the primary flow
## Hard Requirements
- Client users must not have access to `apps/main`
- The password-setup link must be one-time use
- The setup link must become invalid immediately after successful password creation
- The same email must map to one reusable client account across multiple tablos
- Existing onboarded clients invited to another tablo must receive an access notification email, not a new setup link
- The notification email must link directly to `clients.xtablo.com/tablo/:tabloId`
## Chosen Approach
Keep Supabase as the underlying authentication provider, but move invitation control into an invite lifecycle owned by the backend.
The backend creates or reuses a client auth user by email, grants access to the target tablo, and then chooses between two email modes:
- onboarding email with a one-time setup token
- access notification email for an already-onboarded client
`apps/clients` becomes a normal authenticated app with:
- a login page
- a one-time set-password page
- a forgot-password flow
- protected routes that redirect unauthenticated users to login and then resume their intended destination
## User Classes And App Boundary
The system should treat main-app users and client-portal users as distinct user classes.
### Main-app users
- collaborators
- internal users
- users who are allowed to access `app.xtablo.com`
### Client-portal users
- external client users invited to tablos
- users who are allowed to access `clients.xtablo.com`
- users who must not be able to use `apps/main`
### Boundary rule
Sharing auth UI does not mean sharing authorization.
Client accounts must be rejected by `apps/main` even if they hold a valid authenticated session. This boundary must be enforced in backend authorization as well as frontend routing.
## Auth Model
`apps/clients` becomes a normal password-based portal.
### Steady state
- one client account per email
- reused across multiple tablos
- normal email/password login after onboarding
- standard self-service password reset via "mot de passe oublié"
### Invite role
The invite email is no longer the long-term access credential. It is only the bootstrap mechanism for first-time password setup.
## Invite Lifecycle
Invite creation should branch based on whether the email already belongs to an onboarded client account.
### First invite for an email without a password-based client account
- create or reuse the client auth user for that email
- create or confirm the tablo access grant
- create a one-time setup token
- send a setup email to `clients.xtablo.com`
### Later invite for an existing onboarded client account
- create or confirm the tablo access grant
- do not create a setup token
- send a "you now have access" notification email
This keeps onboarding single-use while allowing account reuse across many tablos.
## End-To-End Flows
### First-time onboarding flow
1. Admin invites a client from `app.xtablo.com`.
2. Backend creates or reuses the client auth user.
3. Backend grants access to the target tablo.
4. Backend creates a one-time setup token.
5. Email sends a setup URL into `clients.xtablo.com`.
6. Client opens the link and validates the token.
7. Client sets a password.
8. Backend invalidates the token immediately.
9. Client is signed in and redirected into the client portal.
### Additional tablo access for an already-onboarded client
1. Admin invites the same email to another tablo.
2. Backend reuses the same client account.
3. Backend grants access to the target tablo.
4. Email sends a notification link to `clients.xtablo.com/tablo/:tabloId`.
5. If the client already has a session, the tablo opens directly.
6. If not authenticated, `apps/clients` redirects to login and returns to that tablo after successful login.
## Frontend Design
`apps/clients` should expose three auth surfaces:
- `LoginPage`
- `SetPasswordPage`
- existing authenticated portal routes
### LoginPage
Requirements:
- minimal standalone auth screen
- visually matches the main login page
- built from a shared auth UI package instead of importing directly from `apps/main`
- email and password fields
- forgot-password entry point
- no self-service signup
### SetPasswordPage
Requirements:
- dedicated route for one-time invite setup
- validates token before allowing password creation
- handles invalid, expired, and already-used tokens clearly
- on success, invalidates token and transitions into an authenticated client session
### Protected route behavior
- unauthenticated access to `clients.xtablo.com/tablo/:tabloId` redirects to login
- login preserves and resumes the intended destination
- fallback destination remains the client tablo list if no target route was captured
## Shared Auth UI
The login page in `apps/clients` should look like the main login page, but this should be done through extraction, not duplication.
Recommended ownership split:
- shared package owns auth shell, layout, form framing, banners, and visual treatment
- `apps/main` and `apps/clients` own submit handlers, route targets, and app-specific copy
This keeps visual parity durable without coupling `apps/clients` directly to `apps/main` internals.
## Backend Design
`client_invites` should remain the lifecycle/control record, but its meaning changes.
### Previous role
- pending invite accepted through callback-style magic-link flow
### New role
- one-time password-setup authorization record for first-time onboarding
### Backend responsibilities
`POST /client-invites/:tabloId`
- create or reuse client auth user by email
- create or confirm tablo access
- decide whether this email needs onboarding or only an access notification
- send the correct email type
Token validation endpoint:
- used by `SetPasswordPage`
- verifies token exists, is pending, and is still valid
Password setup completion endpoint:
- verifies token again
- sets password for the underlying auth user
- invalidates token immediately
- completes the onboarding transition cleanly
Admin visibility and cancellation endpoints:
- remain available for operational control
- cancelling a pending setup invite invalidates that setup path immediately
## Authorization Model
Authorization must reflect the split between apps.
### Required behavior
- client-portal users can access `apps/clients` resources they were granted
- client-portal users cannot use `apps/main` flows
- main-app authorization cannot assume that every authenticated user is a main-app user
This must be enforced on the backend, not only in the frontend shell.
## Error Handling
### Frontend
`SetPasswordPage` must handle:
- invalid token
- expired token
- already-used token
- password policy failure
`LoginPage` must handle:
- wrong credentials
- reset email sent state
- reset failure
Protected routes must:
- redirect unauthenticated users to login
- preserve intended destination
- resume navigation after login
### Backend
Invite creation must distinguish:
- first-time onboarding invite
- additional-access notification
Token completion must fail cleanly on:
- expired token
- reused token
- cancelled token
## Testing Strategy
### API tests
- first invite for a new client creates a setup token and sends setup email
- second invite for an already-onboarded client skips setup token creation and sends access notification
- setup token can be used exactly once
- expired or reused setup token is rejected
- client-only accounts are rejected by main-app authorization paths
### Frontend tests
- login page renders through shared auth UI and submits email/password flow
- forgot-password flow is reachable from the client login page
- set-password page handles success, invalid token, expired token, and reused token states
- protected `tablo/:tabloId` route redirects to login and resumes correctly after authentication
- access notification deep-link opens the intended tablo after login
### Manual verification
- first invite email for a new client leads to one-time setup, then normal login
- second invite for the same client leads to access notification only
- `clients.xtablo.com/tablo/:tabloId` works both with and without an existing session
- client user cannot enter `app.xtablo.com`
## Migration Notes
- the current `apps/clients/src/pages/AuthCallback.tsx` route should be removed or reduced to legacy compatibility once this flow is live
- existing frontend code that assumes invitation equals magic-link acceptance should be replaced with setup-token and login flows
- because the feature is not yet live, no legacy client-user migration path is required

View file

@ -0,0 +1,32 @@
{
"name": "@xtablo/auth-ui",
"version": "0.0.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "biome check .",
"lint:fix": "biome check --write .",
"format": "biome format --write ."
},
"dependencies": {
"@xtablo/shared": "workspace:*",
"@xtablo/ui": "workspace:*",
"lucide-react": "^0.460.0",
"react": "19.0.0",
"react-dom": "19.0.0",
"tailwind-merge": "^3.0.2"
},
"devDependencies": {
"@biomejs/biome": "2.2.5",
"@types/react": "19.0.10",
"@types/react-dom": "19.0.4",
"typescript": "^5.7.0",
"vite": "^6.2.2"
}
}

View file

@ -0,0 +1,127 @@
import { useTheme } from "@xtablo/shared/contexts/ThemeContext";
import { Button } from "@xtablo/ui/components/button";
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import type { CSSProperties, MouseEventHandler, ReactNode } from "react";
import { twMerge } from "tailwind-merge";
type AuthCardShellProps = {
title: string;
description?: ReactNode;
children: ReactNode;
background?: ReactNode;
topLeft?: ReactNode;
showThemeToggle?: boolean;
onBackdropClick?: () => void;
wrapperClassName?: string;
wrapperStyle?: CSSProperties;
onWrapperMouseMove?: MouseEventHandler<HTMLDivElement>;
onWrapperMouseLeave?: () => void;
isHovered?: boolean;
cardClassName?: string;
};
const XTABLO_ASSETS_BASE_URL = "https://assets.xtablo.com";
export function AuthCardShell({
title,
description,
children,
background,
topLeft,
showThemeToggle = false,
onBackdropClick,
wrapperClassName,
wrapperStyle,
onWrapperMouseMove,
onWrapperMouseLeave,
isHovered = false,
cardClassName,
}: AuthCardShellProps) {
const { theme, setTheme } = useTheme();
const toggleTheme = () => {
if (theme === "light") {
setTheme("dark");
} else if (theme === "dark") {
setTheme("system");
} else {
setTheme("light");
}
};
const themeIcon =
theme === "light" ? (
<SunIcon className="h-5 w-5" />
) : theme === "dark" ? (
<MoonIcon className="h-5 w-5" />
) : (
<MonitorIcon className="h-5 w-5" />
);
return (
<div
className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5 relative overflow-hidden px-4 py-8 sm:px-6"
onClick={onBackdropClick}
>
{background}
<div
className={twMerge("w-full max-w-lg rounded-2xl relative", wrapperClassName)}
style={wrapperStyle}
onMouseMove={onWrapperMouseMove}
onMouseLeave={onWrapperMouseLeave}
onClick={(event) => event.stopPropagation()}
>
<div className="absolute inset-0 rounded-2xl bg-linear-to-br from-primary/10 via-primary/5 to-secondary/10 blur-xl -z-10" />
<div
data-testid="auth-card-shell"
className={twMerge(
"relative w-full h-full p-5 sm:p-8 bg-card/80 backdrop-blur-md rounded-2xl border border-border z-10 transition-shadow duration-200",
isHovered
? "shadow-[0_15px_35px_rgba(0,0,0,0.15)] dark:shadow-[0_15px_35px_rgba(0,0,0,0.3)]"
: "shadow-xl shadow-black/10 dark:shadow-black/25",
cardClassName
)}
>
{topLeft || showThemeToggle ? (
<div className="mb-6 flex items-center justify-between">
<div>{topLeft}</div>
{showThemeToggle ? (
<Button
variant="ghost"
size="icon"
onClick={toggleTheme}
className="text-muted-foreground hover:text-foreground p-2"
aria-label={`change theme (${theme})`}
>
{themeIcon}
</Button>
) : null}
</div>
) : null}
<div className="mb-6 flex justify-center">
<img
src={`${XTABLO_ASSETS_BASE_URL}/logo_dark.png`}
alt="Xtablo"
className="w-16 h-16 object-contain block dark:hidden"
/>
<img
src={`${XTABLO_ASSETS_BASE_URL}/logo_white.png`}
alt="Xtablo"
className="w-16 h-16 object-contain hidden dark:block"
/>
</div>
<div className="space-y-2 text-center mb-6">
<h1 className="text-2xl sm:text-3xl font-bold text-foreground">{title}</h1>
{description ? <div className="text-muted-foreground">{description}</div> : null}
</div>
{children}
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,83 @@
import { Button } from "@xtablo/ui/components/button";
import { FieldError } from "@xtablo/ui/components/field";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import type { ReactNode } from "react";
type AuthEmailPasswordFormProps = {
email: string;
password: string;
onEmailChange: (value: string) => void;
onPasswordChange: (value: string) => void;
onSubmit: (event: React.FormEvent<HTMLFormElement>) => void;
submitLabel: string;
emailLabel: string;
passwordLabel: string;
emailPlaceholder: string;
passwordPlaceholder: string;
emailError?: string;
passwordError?: string;
isPending?: boolean;
footer?: ReactNode;
extraContent?: ReactNode;
};
export function AuthEmailPasswordForm({
email,
password,
onEmailChange,
onPasswordChange,
onSubmit,
submitLabel,
emailLabel,
passwordLabel,
emailPlaceholder,
passwordPlaceholder,
emailError,
passwordError,
isPending = false,
footer,
extraContent,
}: AuthEmailPasswordFormProps) {
return (
<form className="space-y-4 w-full max-w-md mx-auto" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{emailLabel}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(event) => onEmailChange(event.target.value)}
required
placeholder={emailPlaceholder}
disabled={isPending}
/>
{emailError ? <FieldError errors={[{ message: emailError }]} /> : null}
</div>
<div className="space-y-2">
<Label htmlFor="password">{passwordLabel}</Label>
<Input
id="password"
name="password"
type="password"
value={password}
onChange={(event) => onPasswordChange(event.target.value)}
required
placeholder={passwordPlaceholder}
disabled={isPending}
/>
{passwordError ? <FieldError errors={[{ message: passwordError }]} /> : null}
</div>
{extraContent}
<Button className="w-full" type="submit" disabled={isPending}>
{submitLabel}
</Button>
{footer}
</form>
);
}

View file

@ -0,0 +1,34 @@
import { AlertCircle, CheckCircle2, InfoIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
type AuthInfoBannerProps = {
message: string;
variant: "error" | "info" | "success";
};
const variantStyles: Record<AuthInfoBannerProps["variant"], string> = {
error:
"bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800",
info: "bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-950/20 dark:text-blue-200 dark:border-blue-800",
success:
"bg-green-50 text-green-800 border-green-200 dark:bg-green-950/20 dark:text-green-200 dark:border-green-800",
};
const variantIcon = {
error: AlertCircle,
info: InfoIcon,
success: CheckCircle2,
} satisfies Record<AuthInfoBannerProps["variant"], typeof AlertCircle>;
export function AuthInfoBanner({ message, variant }: AuthInfoBannerProps) {
const Icon = variantIcon[variant];
return (
<div className={twMerge("rounded-lg border p-4", variantStyles[variant])}>
<div className="flex gap-3">
<Icon className="mt-0.5 h-5 w-5 shrink-0" />
<p className="text-sm">{message}</p>
</div>
</div>
);
}

View file

@ -0,0 +1,3 @@
export { AuthCardShell } from "./AuthCardShell";
export { AuthEmailPasswordForm } from "./AuthEmailPasswordForm";
export { AuthInfoBanner } from "./AuthInfoBanner";

View file

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@xtablo/ui": ["../ui/src"],
"@xtablo/ui/*": ["../ui/src/*"],
"@xtablo/shared": ["../shared/src"],
"@xtablo/shared/*": ["../shared/src/*"]
}
},
"include": ["src", "src/vite-env.d.ts"]
}

View file

@ -2,45 +2,82 @@
/* ─── Message entry ─────────────────────────────────────────────── */
@keyframes chat-message-enter {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* ─── Toolbar entrance ──────────────────────────────────────────── */
@keyframes chat-toolbar-enter {
from { opacity: 0; transform: scale(0.95) translateY(4px); }
to { opacity: 1; transform: scale(1) translateY(0); }
from {
opacity: 0;
transform: scale(0.95) translateY(4px);
}
to {
opacity: 1;
transform: scale(1) translateY(0);
}
}
/* ─── Reaction pop ──────────────────────────────────────────────── */
@keyframes chat-reaction-pop {
0% { transform: scale(0); opacity: 0; }
70% { transform: scale(1.1); }
100% { transform: scale(1); opacity: 1; }
0% {
transform: scale(0);
opacity: 0;
}
70% {
transform: scale(1.1);
}
100% {
transform: scale(1);
opacity: 1;
}
}
/* ─── Typing indicator dots ─────────────────────────────────────── */
@keyframes chat-typing-pulse {
0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
30% { opacity: 1; transform: translateY(-4px); }
0%,
60%,
100% {
opacity: 0.3;
transform: translateY(0);
}
30% {
opacity: 1;
transform: translateY(-4px);
}
}
/* ─── Cursor blink (streaming) ──────────────────────────────────── */
@keyframes chat-cursor-blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
0%,
100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
/* ─── Read receipt status color transition ───────────────────────── */
@keyframes chat-status-read-in {
from { color: var(--color-muted-foreground); }
to { color: var(--color-primary); }
from {
color: var(--color-muted-foreground);
}
to {
color: var(--color-primary);
}
}
/* ─── Utility classes ───────────────────────────────────────────── */
@layer base {
.chat-message {
animation: chat-message-enter 250ms cubic-bezier(0.25, 0.1, 0.25, 1.0);
animation: chat-message-enter 250ms cubic-bezier(0.25, 0.1, 0.25, 1);
}
.chat-typing-dot {
@ -56,7 +93,7 @@
}
.chat-reaction-pop {
animation: chat-reaction-pop 200ms cubic-bezier(0.25, 0.1, 0.25, 1.0);
animation: chat-reaction-pop 200ms cubic-bezier(0.25, 0.1, 0.25, 1);
}
.chat-status-read {

File diff suppressed because it is too large Load diff

View file

@ -1,33 +1,33 @@
import * as React from "react"
import { cn } from "@xtablo/shared"
import { cn } from "@xtablo/shared";
import {
X,
Search,
Pin,
ArrowDown,
ArrowUp,
Check,
ChevronDown,
ChevronRight,
ArrowUp,
ArrowDown,
Pin,
Search,
Trash2,
Check,
} from "lucide-react"
import type { ChatMessageData } from "../types"
import { formatTimestamp } from "../hooks"
X,
} from "lucide-react";
import * as React from "react";
import { formatTimestamp } from "../hooks";
import type { ChatMessageData } from "../types";
// ─── ChatForwardDialog ────────────────────────────────────────────────────────
interface Conversation {
id: string
title: string
avatar?: string
id: string;
title: string;
avatar?: string;
}
interface ChatForwardDialogProps {
message: ChatMessageData
conversations: Conversation[]
onForward: (targetIds: string[]) => void
onCancel: () => void
className?: string
message: ChatMessageData;
conversations: Conversation[];
onForward: (targetIds: string[]) => void;
onCancel: () => void;
className?: string;
}
function ChatForwardDialog({
@ -37,24 +37,24 @@ function ChatForwardDialog({
onCancel,
className,
}: ChatForwardDialogProps) {
const [query, setQuery] = React.useState("")
const [selected, setSelected] = React.useState<Set<string>>(new Set())
const [query, setQuery] = React.useState("");
const [selected, setSelected] = React.useState<Set<string>>(new Set());
const filtered = conversations.filter((c) =>
c.title.toLowerCase().includes(query.toLowerCase())
)
const filtered = conversations.filter((c) => c.title.toLowerCase().includes(query.toLowerCase()));
const toggle = (id: string) => {
setSelected((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
return (
<div className={cn("fixed inset-0 z-50 flex items-center justify-center bg-black/50", className)}>
<div
className={cn("fixed inset-0 z-50 flex items-center justify-center bg-black/50", className)}
>
<div className="w-full max-w-sm overflow-hidden rounded-xl border border-border bg-card shadow-lg">
{/* Header */}
<div className="flex items-center justify-between border-b border-border px-4 py-3">
@ -66,7 +66,9 @@ function ChatForwardDialog({
{/* Preview */}
<div className="border-b border-border px-4 py-2">
<span className="text-[12px] font-semibold text-muted-foreground">{message.senderName}</span>
<span className="text-[12px] font-semibold text-muted-foreground">
{message.senderName}
</span>
<p className="truncate text-[13px] text-muted-foreground/60">{message.text}</p>
</div>
@ -106,7 +108,10 @@ function ChatForwardDialog({
{/* Actions */}
<div className="flex items-center justify-end gap-2 border-t border-border px-4 py-3">
<button onClick={onCancel} className="rounded-lg px-3 py-1.5 text-[13px] font-medium text-muted-foreground hover:bg-accent">
<button
onClick={onCancel}
className="rounded-lg px-3 py-1.5 text-[13px] font-medium text-muted-foreground hover:bg-accent"
>
Cancel
</button>
<button
@ -119,32 +124,30 @@ function ChatForwardDialog({
</div>
</div>
</div>
)
);
}
// ─── ChatEditComposer (inline edit mode) ──────────────────────────────────────
interface ChatEditComposerProps {
message: ChatMessageData
onSave: (messageId: string, newText: string) => void
onCancel: () => void
className?: string
message: ChatMessageData;
onSave: (messageId: string, newText: string) => void;
onCancel: () => void;
className?: string;
}
function ChatEditComposer({
message,
onSave,
onCancel,
className,
}: ChatEditComposerProps) {
const [value, setValue] = React.useState(message.text || "")
function ChatEditComposer({ message, onSave, onCancel, className }: ChatEditComposerProps) {
const [value, setValue] = React.useState(message.text || "");
return (
<div className={cn("border-t border-border", className)}>
{/* Edit bar */}
<div className="flex items-center gap-2 bg-amber-500/10 px-4 py-1.5">
<span className="text-[12px] font-semibold text-amber-500">Editing message</span>
<button onClick={onCancel} className="ml-auto text-[12px] text-muted-foreground hover:text-foreground">
<button
onClick={onCancel}
className="ml-auto text-[12px] text-muted-foreground hover:text-foreground"
>
Cancel
</button>
</div>
@ -153,8 +156,11 @@ function ChatEditComposer({
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); onSave(message.id, value.trim()) }
if (e.key === "Escape") onCancel()
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
onSave(message.id, value.trim());
}
if (e.key === "Escape") onCancel();
}}
rows={1}
autoFocus
@ -169,14 +175,14 @@ function ChatEditComposer({
</button>
</div>
</div>
)
);
}
// ─── ChatDeletedMessage (placeholder) ─────────────────────────────────────────
interface ChatDeletedMessageProps {
deletedBy?: string
className?: string
deletedBy?: string;
className?: string;
}
function ChatDeletedMessage({ deletedBy, className }: ChatDeletedMessageProps) {
@ -187,17 +193,17 @@ function ChatDeletedMessage({ deletedBy, className }: ChatDeletedMessageProps) {
{deletedBy ? `${deletedBy} deleted this message` : "This message was deleted"}
</span>
</div>
)
);
}
// ─── ChatPinnedPanel ──────────────────────────────────────────────────────────
interface ChatPinnedPanelProps {
pinnedMessages: ChatMessageData[]
onUnpin: (messageId: string) => void
onJumpTo: (messageId: string) => void
onClose: () => void
className?: string
pinnedMessages: ChatMessageData[];
onUnpin: (messageId: string) => void;
onJumpTo: (messageId: string) => void;
onClose: () => void;
className?: string;
}
function ChatPinnedPanel({
@ -227,17 +233,25 @@ function ChatPinnedPanel({
className="border-b border-border px-4 py-3 transition-colors hover:bg-accent"
>
<div className="flex items-center justify-between">
<span className="text-[12px] font-semibold text-muted-foreground">{msg.senderName}</span>
<span className="text-[12px] font-semibold text-muted-foreground">
{msg.senderName}
</span>
<span className="text-[10px] text-muted-foreground/60">
{formatTimestamp(new Date(msg.timestamp))}
</span>
</div>
<p className="mt-0.5 line-clamp-2 text-[13px] text-foreground">{msg.text}</p>
<div className="mt-1.5 flex items-center gap-2">
<button onClick={() => onJumpTo(msg.id)} className="text-[11px] text-primary hover:underline">
<button
onClick={() => onJumpTo(msg.id)}
className="text-[11px] text-primary hover:underline"
>
Jump to message
</button>
<button onClick={() => onUnpin(msg.id)} className="text-[11px] text-muted-foreground/60 hover:text-destructive">
<button
onClick={() => onUnpin(msg.id)}
className="text-[11px] text-muted-foreground/60 hover:text-destructive"
>
Unpin
</button>
</div>
@ -250,27 +264,27 @@ function ChatPinnedPanel({
)}
</div>
</div>
)
);
}
// ─── ChatNestedThread ─────────────────────────────────────────────────────────
interface ThreadedMessage extends ChatMessageData {
parentId: string | null
children: ThreadedMessage[]
depth: number
votes?: number
userVote?: "up" | "down" | null
isCollapsed?: boolean
parentId: string | null;
children: ThreadedMessage[];
depth: number;
votes?: number;
userVote?: "up" | "down" | null;
isCollapsed?: boolean;
}
interface ChatNestedThreadProps {
messages: ThreadedMessage[]
maxDepth?: number
onReply?: (parentId: string) => void
onVote?: (messageId: string, direction: "up" | "down") => void
showVotes?: boolean
className?: string
messages: ThreadedMessage[];
maxDepth?: number;
onReply?: (parentId: string) => void;
onVote?: (messageId: string, direction: "up" | "down") => void;
showVotes?: boolean;
className?: string;
}
function ChatNestedThread({
@ -294,7 +308,7 @@ function ChatNestedThread({
/>
))}
</div>
)
);
}
function ThreadMessage({
@ -304,29 +318,30 @@ function ThreadMessage({
onVote,
showVotes,
}: {
message: ThreadedMessage
maxDepth: number
onReply?: (parentId: string) => void
onVote?: (messageId: string, direction: "up" | "down") => void
showVotes: boolean
message: ThreadedMessage;
maxDepth: number;
onReply?: (parentId: string) => void;
onVote?: (messageId: string, direction: "up" | "down") => void;
showVotes: boolean;
}) {
const [collapsed, setCollapsed] = React.useState(message.isCollapsed ?? false)
const atMaxDepth = message.depth >= maxDepth
const [collapsed, setCollapsed] = React.useState(message.isCollapsed ?? false);
const atMaxDepth = message.depth >= maxDepth;
return (
<div style={{ paddingLeft: Math.min(message.depth, maxDepth) * 24 }}>
<div className="group flex items-start gap-2 rounded-lg px-2 py-1.5 transition-colors hover:bg-accent">
{/* Thread connector line */}
{message.depth > 0 && (
<div className="mt-1 h-full w-0.5 shrink-0 bg-border" />
)}
{message.depth > 0 && <div className="mt-1 h-full w-0.5 shrink-0 bg-border" />}
{/* Vote buttons */}
{showVotes && (
<div className="flex shrink-0 flex-col items-center gap-0.5">
<button
onClick={() => onVote?.(message.id, "up")}
className={cn("size-5 rounded text-muted-foreground/60 hover:text-primary", message.userVote === "up" && "text-primary")}
className={cn(
"size-5 rounded text-muted-foreground/60 hover:text-primary",
message.userVote === "up" && "text-primary"
)}
>
<ArrowUp className="size-3.5 mx-auto" />
</button>
@ -335,7 +350,10 @@ function ThreadMessage({
</span>
<button
onClick={() => onVote?.(message.id, "down")}
className={cn("size-5 rounded text-muted-foreground/60 hover:text-destructive", message.userVote === "down" && "text-destructive")}
className={cn(
"size-5 rounded text-muted-foreground/60 hover:text-destructive",
message.userVote === "down" && "text-destructive"
)}
>
<ArrowDown className="size-3.5 mx-auto" />
</button>
@ -353,7 +371,10 @@ function ThreadMessage({
<p className="text-[14px] leading-relaxed text-foreground">{message.text}</p>
<div className="mt-1 flex items-center gap-3">
{!atMaxDepth && (
<button onClick={() => onReply?.(message.id)} className="text-[11px] font-medium text-muted-foreground hover:text-primary">
<button
onClick={() => onReply?.(message.id)}
className="text-[11px] font-medium text-muted-foreground hover:text-primary"
>
Reply
</button>
)}
@ -362,7 +383,11 @@ function ThreadMessage({
onClick={() => setCollapsed(!collapsed)}
className="flex items-center gap-0.5 text-[11px] font-medium text-muted-foreground hover:text-foreground"
>
{collapsed ? <ChevronRight className="size-3" /> : <ChevronDown className="size-3" />}
{collapsed ? (
<ChevronRight className="size-3" />
) : (
<ChevronDown className="size-3" />
)}
{message.children.length} {message.children.length === 1 ? "reply" : "replies"}
</button>
)}
@ -392,53 +417,63 @@ function ThreadMessage({
</button>
)}
</div>
)
);
}
// ─── ChatSearch ───────────────────────────────────────────────────────────────
interface SearchResult {
messageId: string
conversationId?: string
conversationName?: string
senderName: string
snippet: string
timestamp: Date | number
messageId: string;
conversationId?: string;
conversationName?: string;
senderName: string;
snippet: string;
timestamp: Date | number;
}
interface ChatSearchProps {
onSearch: (query: string) => SearchResult[] | Promise<SearchResult[]>
onSelect: (result: SearchResult) => void
onClose: () => void
className?: string
onSearch: (query: string) => SearchResult[] | Promise<SearchResult[]>;
onSelect: (result: SearchResult) => void;
onClose: () => void;
className?: string;
}
function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps) {
const [query, setQuery] = React.useState("")
const [results, setResults] = React.useState<SearchResult[]>([])
const inputRef = React.useRef<HTMLInputElement>(null)
const [query, setQuery] = React.useState("");
const [results, setResults] = React.useState<SearchResult[]>([]);
const inputRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
inputRef.current?.focus()
}, [])
inputRef.current?.focus();
}, []);
React.useEffect(() => {
if (!query.trim()) { setResults([]); return }
if (!query.trim()) {
setResults([]);
return;
}
const timeout = setTimeout(async () => {
const r = await onSearch(query)
setResults(r)
}, 200)
return () => clearTimeout(timeout)
}, [query, onSearch])
const r = await onSearch(query);
setResults(r);
}, 200);
return () => clearTimeout(timeout);
}, [query, onSearch]);
React.useEffect(() => {
const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose() }
document.addEventListener("keydown", handler)
return () => document.removeEventListener("keydown", handler)
}, [onClose])
const handler = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [onClose]);
return (
<div className={cn("fixed inset-0 z-50 flex items-start justify-center pt-[15vh] bg-black/50", className)}>
<div
className={cn(
"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] bg-black/50",
className
)}
>
<div className="w-full max-w-lg overflow-hidden rounded-xl border border-border bg-card shadow-lg">
{/* Search input */}
<div className="flex items-center gap-3 border-b border-border px-4 py-3">
@ -451,7 +486,9 @@ function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps)
placeholder="Search messages..."
className="flex-1 bg-transparent text-[15px] text-foreground placeholder:text-muted-foreground/60 outline-none"
/>
<kbd className="rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground/60">ESC</kbd>
<kbd className="rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground/60">
ESC
</kbd>
</div>
{/* Results */}
@ -459,13 +496,18 @@ function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps)
{results.map((r) => (
<button
key={r.messageId}
onClick={() => { onSelect(r); onClose() }}
onClick={() => {
onSelect(r);
onClose();
}}
className="flex w-full flex-col gap-0.5 border-b border-border px-4 py-2.5 text-left transition-colors hover:bg-accent"
>
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-foreground">{r.senderName}</span>
{r.conversationName && (
<span className="text-[11px] text-muted-foreground/60">in {r.conversationName}</span>
<span className="text-[11px] text-muted-foreground/60">
in {r.conversationName}
</span>
)}
<span className="ml-auto text-[11px] text-muted-foreground/60">
{formatTimestamp(new Date(r.timestamp))}
@ -482,7 +524,7 @@ function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps)
</div>
</div>
</div>
)
);
}
// ─── Exports ──────────────────────────────────────────────────────────────────
@ -494,7 +536,7 @@ export {
ChatPinnedPanel,
ChatNestedThread,
ChatSearch,
}
};
export type {
Conversation,
ChatForwardDialogProps,
@ -505,4 +547,4 @@ export type {
ChatNestedThreadProps,
SearchResult,
ChatSearchProps,
}
};

View file

@ -1,38 +1,43 @@
import * as React from "react"
import { cn } from "@xtablo/shared"
import { cn } from "@xtablo/shared";
import {
MessageSquare,
Search,
Phone,
X,
ChevronLeft,
Plus,
Minimize2,
Pin,
Ticket,
Clock,
AlertCircle,
CheckCircle2,
ChevronLeft,
Circle,
Clock,
MessageSquare,
Minimize2,
Phone,
Pin,
Plus,
Search,
Ticket,
User,
} from "lucide-react"
import type { ChatMessageData, ChatUser, TypingUser } from "../types"
import { ChatProvider, ChatMessages, ChatComposer } from "./chat"
X,
} from "lucide-react";
import * as React from "react";
import type { ChatMessageData, ChatUser, TypingUser } from "../types";
import { ChatComposer, ChatMessages, ChatProvider } from "./chat";
// ─── Shared: ChatHeader ───────────────────────────────────────────────────────
interface ChatHeaderProps {
title: string
subtitle?: string
avatar?: React.ReactNode
actions?: React.ReactNode
onBack?: () => void
className?: string
title: string;
subtitle?: string;
avatar?: React.ReactNode;
actions?: React.ReactNode;
onBack?: () => void;
className?: string;
}
function ChatHeader({ title, subtitle, avatar, actions, onBack, className }: ChatHeaderProps) {
return (
<header className={cn("sticky top-0 z-10 flex items-center gap-3 border-b border-border bg-card px-4 py-3 backdrop-blur-[20px] backdrop-saturate-[180%]", className)}>
<header
className={cn(
"sticky top-0 z-10 flex items-center gap-3 border-b border-border bg-card px-4 py-3 backdrop-blur-[20px] backdrop-saturate-[180%]",
className
)}
>
{onBack && (
<button onClick={onBack} className="mr-1 text-muted-foreground hover:text-foreground">
<ChevronLeft className="size-5" />
@ -40,25 +45,27 @@ function ChatHeader({ title, subtitle, avatar, actions, onBack, className }: Cha
)}
{avatar}
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-[15px] font-semibold tracking-[-0.02em] text-foreground">{title}</span>
<span className="truncate text-[15px] font-semibold tracking-[-0.02em] text-foreground">
{title}
</span>
{subtitle && <span className="truncate text-[12px] text-muted-foreground">{subtitle}</span>}
</div>
{actions}
</header>
)
);
}
// ─── Shared: Sidebar conversation item ────────────────────────────────────────
interface SidebarConversation {
id: string
title: string
avatar?: string
lastMessage?: string
lastMessageTime?: string
unreadCount?: number
presence?: "online" | "away" | "offline"
isGroup?: boolean
id: string;
title: string;
avatar?: string;
lastMessage?: string;
lastMessageTime?: string;
unreadCount?: number;
presence?: "online" | "away" | "offline";
isGroup?: boolean;
}
function ConversationItem({
@ -66,9 +73,9 @@ function ConversationItem({
isActive,
onClick,
}: {
convo: SidebarConversation
isActive: boolean
onClick: () => void
convo: SidebarConversation;
isActive: boolean;
onClick: () => void;
}) {
return (
<button
@ -90,7 +97,9 @@ function ConversationItem({
<div className="flex items-center justify-between">
<span className="truncate text-[15px] font-semibold text-foreground">{convo.title}</span>
{convo.lastMessageTime && (
<span className="ml-2 shrink-0 text-[11px] text-muted-foreground/60">{convo.lastMessageTime}</span>
<span className="ml-2 shrink-0 text-[11px] text-muted-foreground/60">
{convo.lastMessageTime}
</span>
)}
</div>
<div className="flex items-center justify-between">
@ -103,7 +112,7 @@ function ConversationItem({
</div>
</div>
</button>
)
);
}
// ═══════════════════════════════════════════════════════════════════════════════
@ -111,16 +120,16 @@ function ConversationItem({
// ═══════════════════════════════════════════════════════════════════════════════
interface FullMessengerProps {
currentUser: ChatUser
conversations: SidebarConversation[]
activeConversationId?: string
onSelectConversation: (id: string) => void
messages: ChatMessageData[]
typingUsers?: TypingUser[]
onSend: (text: string) => void
title?: string
subtitle?: string
className?: string
currentUser: ChatUser;
conversations: SidebarConversation[];
activeConversationId?: string;
onSelectConversation: (id: string) => void;
messages: ChatMessageData[];
typingUsers?: TypingUser[];
onSend: (text: string) => void;
title?: string;
subtitle?: string;
className?: string;
}
function FullMessenger({
@ -135,8 +144,8 @@ function FullMessenger({
subtitle,
className,
}: FullMessengerProps) {
const activeConvo = conversations.find((c) => c.id === activeConversationId)
const showingConvo = !!activeConvo
const activeConvo = conversations.find((c) => c.id === activeConversationId);
const showingConvo = !!activeConvo;
return (
<ChatProvider
@ -214,9 +223,15 @@ function FullMessenger({
}
actions={
<div className="flex items-center gap-1">
<button className="flex size-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent"><Phone className="size-4" /></button>
<button className="flex size-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent"><Search className="size-4" /></button>
<button className="flex size-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent"><Pin className="size-4" /></button>
<button className="flex size-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent">
<Phone className="size-4" />
</button>
<button className="flex size-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent">
<Search className="size-4" />
</button>
<button className="flex size-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent">
<Pin className="size-4" />
</button>
</div>
}
/>
@ -227,14 +242,16 @@ function FullMessenger({
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
<MessageSquare className="mx-auto mb-3 size-12 text-muted-foreground/60" />
<p className="text-[15px] font-medium text-muted-foreground">Select a conversation</p>
<p className="text-[15px] font-medium text-muted-foreground">
Select a conversation
</p>
</div>
</div>
)}
</main>
</div>
</ChatProvider>
)
);
}
// ═══════════════════════════════════════════════════════════════════════════════
@ -242,14 +259,14 @@ function FullMessenger({
// ═══════════════════════════════════════════════════════════════════════════════
interface ChatWidgetProps {
currentUser: ChatUser
messages: ChatMessageData[]
onSend: (text: string) => void
title?: string
subtitle?: string
greeting?: string
position?: "bottom-right" | "bottom-left"
className?: string
currentUser: ChatUser;
messages: ChatMessageData[];
onSend: (text: string) => void;
title?: string;
subtitle?: string;
greeting?: string;
position?: "bottom-right" | "bottom-left";
className?: string;
}
function ChatWidget({
@ -261,11 +278,17 @@ function ChatWidget({
position = "bottom-right",
className,
}: ChatWidgetProps) {
const [isOpen, setIsOpen] = React.useState(false)
const [isOpen, setIsOpen] = React.useState(false);
return (
<ChatProvider currentUser={currentUser}>
<div className={cn("fixed z-50", position === "bottom-right" ? "bottom-5 right-5" : "bottom-5 left-5", className)}>
<div
className={cn(
"fixed z-50",
position === "bottom-right" ? "bottom-5 right-5" : "bottom-5 left-5",
className
)}
>
{/* Chat window */}
{isOpen && (
<div className="mb-3 flex h-[500px] w-[380px] flex-col overflow-hidden rounded-2xl border border-border bg-background shadow-lg">
@ -278,7 +301,10 @@ function ChatWidget({
</div>
}
actions={
<button onClick={() => setIsOpen(false)} className="text-muted-foreground hover:text-foreground">
<button
onClick={() => setIsOpen(false)}
className="text-muted-foreground hover:text-foreground"
>
<Minimize2 className="size-4" />
</button>
}
@ -298,7 +324,7 @@ function ChatWidget({
</button>
</div>
</ChatProvider>
)
);
}
// ═══════════════════════════════════════════════════════════════════════════════
@ -306,12 +332,12 @@ function ChatWidget({
// ═══════════════════════════════════════════════════════════════════════════════
interface InlineChatProps {
currentUser: ChatUser
messages: ChatMessageData[]
onSend: (text: string) => void
placeholder?: string
maxHeight?: number
className?: string
currentUser: ChatUser;
messages: ChatMessageData[];
onSend: (text: string) => void;
placeholder?: string;
maxHeight?: number;
className?: string;
}
function InlineChat({
@ -324,12 +350,18 @@ function InlineChat({
}: InlineChatProps) {
return (
<ChatProvider currentUser={currentUser}>
<div className={cn("flex flex-col overflow-hidden rounded-xl border border-border bg-background", className)} style={{ maxHeight }}>
<div
className={cn(
"flex flex-col overflow-hidden rounded-xl border border-border bg-background",
className
)}
style={{ maxHeight }}
>
<ChatMessages messages={messages} />
<ChatComposer onSend={onSend} placeholder={placeholder} />
</div>
</ChatProvider>
)
);
}
// ═══════════════════════════════════════════════════════════════════════════════
@ -337,23 +369,23 @@ function InlineChat({
// ═══════════════════════════════════════════════════════════════════════════════
interface Topic {
id: string
title: string
author: string
replyCount: number
lastActivity: string
isPinned?: boolean
tags?: string[]
id: string;
title: string;
author: string;
replyCount: number;
lastActivity: string;
isPinned?: boolean;
tags?: string[];
}
interface ChatBoardProps {
currentUser: ChatUser
topics: Topic[]
activeTopic?: Topic
onSelectTopic: (id: string) => void
onBack?: () => void
children?: React.ReactNode
className?: string
currentUser: ChatUser;
topics: Topic[];
activeTopic?: Topic;
onSelectTopic: (id: string) => void;
onBack?: () => void;
children?: React.ReactNode;
className?: string;
}
function ChatBoard({
@ -370,16 +402,25 @@ function ChatBoard({
<div className={cn("flex h-full flex-col bg-background", className)}>
{activeTopic ? (
<>
<ChatHeader title={activeTopic.title} subtitle={`${activeTopic.replyCount} replies`} onBack={onBack} />
<ChatHeader
title={activeTopic.title}
subtitle={`${activeTopic.replyCount} replies`}
onBack={onBack}
/>
<div className="flex-1 overflow-y-auto px-4 py-4">
<div className="mx-auto max-w-3xl">{children}</div>
</div>
</>
) : (
<>
<ChatHeader title="Discussions" actions={
<button className="flex size-8 items-center justify-center rounded-lg bg-primary text-white"><Plus className="size-4" /></button>
} />
<ChatHeader
title="Discussions"
actions={
<button className="flex size-8 items-center justify-center rounded-lg bg-primary text-white">
<Plus className="size-4" />
</button>
}
/>
<div className="flex-1 overflow-y-auto">
{topics.map((t) => (
<button
@ -400,7 +441,12 @@ function ChatBoard({
{t.tags && t.tags.length > 0 && (
<div className="mt-1 flex gap-1">
{t.tags.map((tag) => (
<span key={tag} className="rounded-full bg-accent px-2 py-0.5 text-[11px] font-medium text-primary">{tag}</span>
<span
key={tag}
className="rounded-full bg-accent px-2 py-0.5 text-[11px] font-medium text-primary"
>
{tag}
</span>
))}
</div>
)}
@ -412,7 +458,7 @@ function ChatBoard({
)}
</div>
</ChatProvider>
)
);
}
// ═══════════════════════════════════════════════════════════════════════════════
@ -420,12 +466,12 @@ function ChatBoard({
// ═══════════════════════════════════════════════════════════════════════════════
interface LiveChatProps {
currentUser: ChatUser
messages: ChatMessageData[]
onSend: (text: string) => void
title?: string
viewerCount?: number
className?: string
currentUser: ChatUser;
messages: ChatMessageData[];
onSend: (text: string) => void;
title?: string;
viewerCount?: number;
className?: string;
}
function LiveChat({
@ -452,64 +498,67 @@ function LiveChat({
<ChatComposer onSend={onSend} placeholder="Send a message..." />
</div>
</ChatProvider>
)
);
}
// ═══════════════════════════════════════════════════════════════════════════════
// LAYOUT 7: SupportTickets (Help desk / ticket queue)
// ═══════════════════════════════════════════════════════════════════════════════
type TicketStatus = "open" | "in-progress" | "resolved"
type TicketPriority = "low" | "medium" | "high" | "urgent"
type TicketStatus = "open" | "in-progress" | "resolved";
type TicketPriority = "low" | "medium" | "high" | "urgent";
interface SupportTicket {
id: string
subject: string
customerName: string
customerAvatar?: string
status: TicketStatus
priority: TicketPriority
category?: string
tags?: string[]
createdAt: string
updatedAt?: string
lastMessage?: string
unreadCount?: number
assignee?: string
id: string;
subject: string;
customerName: string;
customerAvatar?: string;
status: TicketStatus;
priority: TicketPriority;
category?: string;
tags?: string[];
createdAt: string;
updatedAt?: string;
lastMessage?: string;
unreadCount?: number;
assignee?: string;
}
interface SupportTicketsProps {
currentUser: ChatUser
tickets: SupportTicket[]
activeTicketId?: string
onSelectTicket: (id: string) => void
messages: ChatMessageData[]
typingUsers?: TypingUser[]
onSend: (text: string) => void
statusFilter?: TicketStatus | "all"
onStatusFilterChange?: (status: TicketStatus | "all") => void
title?: string
className?: string
currentUser: ChatUser;
tickets: SupportTicket[];
activeTicketId?: string;
onSelectTicket: (id: string) => void;
messages: ChatMessageData[];
typingUsers?: TypingUser[];
onSend: (text: string) => void;
statusFilter?: TicketStatus | "all";
onStatusFilterChange?: (status: TicketStatus | "all") => void;
title?: string;
className?: string;
}
// ─── Internal helpers ────────────────────────────────────────────────────────
const ticketStatusConfig: Record<TicketStatus, { icon: typeof Circle; label: string; color: string }> = {
const ticketStatusConfig: Record<
TicketStatus,
{ icon: typeof Circle; label: string; color: string }
> = {
open: { icon: Circle, label: "Open", color: "var(--color-chart-4)" },
"in-progress": { icon: Clock, label: "In Progress", color: "var(--color-primary)" },
resolved: { icon: CheckCircle2, label: "Resolved", color: "#22c55e" },
}
};
const ticketPriorityColors: Record<TicketPriority, string> = {
urgent: "var(--color-destructive)",
high: "var(--color-chart-4)",
medium: "var(--color-primary)",
low: "var(--color-muted-foreground)",
}
};
function TicketStatusBadge({ status }: { status: TicketStatus }) {
const cfg = ticketStatusConfig[status]
const Icon = cfg.icon
const cfg = ticketStatusConfig[status];
const Icon = cfg.icon;
return (
<span
className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium"
@ -521,11 +570,11 @@ function TicketStatusBadge({ status }: { status: TicketStatus }) {
<Icon className="size-3" />
{cfg.label}
</span>
)
);
}
function TicketPriorityBadge({ priority }: { priority: TicketPriority }) {
const color = ticketPriorityColors[priority]
const color = ticketPriorityColors[priority];
return (
<span
className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium capitalize"
@ -537,22 +586,22 @@ function TicketPriorityBadge({ priority }: { priority: TicketPriority }) {
<AlertCircle className="size-3" />
{priority}
</span>
)
);
}
function TicketFilterTabs({
value,
onChange,
}: {
value: TicketStatus | "all"
onChange: (v: TicketStatus | "all") => void
value: TicketStatus | "all";
onChange: (v: TicketStatus | "all") => void;
}) {
const tabs: { key: TicketStatus | "all"; label: string }[] = [
{ key: "all", label: "All" },
{ key: "open", label: "Open" },
{ key: "in-progress", label: "Active" },
{ key: "resolved", label: "Resolved" },
]
];
return (
<div className="flex gap-1">
{tabs.map((t) => (
@ -569,7 +618,7 @@ function TicketFilterTabs({
</button>
))}
</div>
)
);
}
function TicketItem({
@ -577,11 +626,11 @@ function TicketItem({
isActive,
onClick,
}: {
ticket: SupportTicket
isActive: boolean
onClick: () => void
ticket: SupportTicket;
isActive: boolean;
onClick: () => void;
}) {
const StatusIcon = ticketStatusConfig[ticket.status].icon
const StatusIcon = ticketStatusConfig[ticket.status].icon;
return (
<button
onClick={onClick}
@ -626,7 +675,7 @@ function TicketItem({
</span>
)}
</button>
)
);
}
// ─── Main component ──────────────────────────────────────────────────────────
@ -644,17 +693,17 @@ function SupportTickets({
title = "Support Tickets",
className,
}: SupportTicketsProps) {
const [internalFilter, setInternalFilter] = React.useState<TicketStatus | "all">("all")
const filter = controlledFilter ?? internalFilter
const setFilter = onStatusFilterChange ?? setInternalFilter
const [internalFilter, setInternalFilter] = React.useState<TicketStatus | "all">("all");
const filter = controlledFilter ?? internalFilter;
const setFilter = onStatusFilterChange ?? setInternalFilter;
const filteredTickets = filter === "all" ? tickets : tickets.filter((t) => t.status === filter)
const activeTicket = tickets.find((t) => t.id === activeTicketId)
const filteredTickets = filter === "all" ? tickets : tickets.filter((t) => t.status === filter);
const activeTicket = tickets.find((t) => t.id === activeTicketId);
const openCount = tickets.filter((t) => t.status === "open").length
const activeCount = tickets.filter((t) => t.status === "in-progress").length
const openCount = tickets.filter((t) => t.status === "open").length;
const activeCount = tickets.filter((t) => t.status === "in-progress").length;
const showingTicket = !!activeTicket
const showingTicket = !!activeTicket;
return (
<ChatProvider
@ -768,12 +817,12 @@ function SupportTickets({
</main>
</div>
</ChatProvider>
)
);
}
// ─── Exports ──────────────────────────────────────────────────────────────────
const ChatConversationItem = ConversationItem
const ChatConversationItem = ConversationItem;
export {
ChatHeader,
@ -787,7 +836,7 @@ export {
TicketStatusBadge,
TicketPriorityBadge,
TicketFilterTabs,
}
};
export type {
ChatHeaderProps,
SidebarConversation,
@ -801,4 +850,4 @@ export type {
TicketPriority,
SupportTicket,
SupportTicketsProps,
}
};

View file

@ -1,35 +1,21 @@
import {
useRef,
useEffect,
useCallback,
useState,
} from "react"
import {
isToday,
isYesterday,
format,
isSameDay,
differenceInSeconds,
} from "date-fns"
import type { ChatMessageData, MessageListItem, MessageGroup } from "./types"
import { differenceInSeconds, format, isSameDay, isToday, isYesterday } from "date-fns";
import { useCallback, useEffect, useRef, useState } from "react";
import type { ChatMessageData, MessageGroup, MessageListItem } from "./types";
// ─── Date formatting ──────────────────────────────────────────────────────────
export function formatDateLabel(date: Date): string {
if (isToday(date)) return "Today"
if (isYesterday(date)) return "Yesterday"
const now = new Date()
const diffDays = Math.floor(
(now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)
)
if (diffDays < 7) return format(date, "EEEE") // "Tuesday"
if (date.getFullYear() === now.getFullYear())
return format(date, "MMMM d") // "March 18"
return format(date, "MMMM d, yyyy") // "March 18, 2026"
if (isToday(date)) return "Today";
if (isYesterday(date)) return "Yesterday";
const now = new Date();
const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));
if (diffDays < 7) return format(date, "EEEE"); // "Tuesday"
if (date.getFullYear() === now.getFullYear()) return format(date, "MMMM d"); // "March 18"
return format(date, "MMMM d, yyyy"); // "March 18, 2026"
}
export function formatTimestamp(date: Date): string {
return format(date, "h:mm a") // "10:42 AM"
return format(date, "h:mm a"); // "10:42 AM"
}
// ─── Message grouping ─────────────────────────────────────────────────────────
@ -39,40 +25,40 @@ export function groupMessages(
currentUserId: string,
intervalSeconds: number = 120
): MessageListItem[] {
if (messages.length === 0) return []
if (messages.length === 0) return [];
const items: MessageListItem[] = []
let currentGroup: MessageGroup | null = null
let lastDate: Date | null = null
const items: MessageListItem[] = [];
let currentGroup: MessageGroup | null = null;
let lastDate: Date | null = null;
for (const msg of messages) {
const msgDate = new Date(msg.timestamp)
const msgDate = new Date(msg.timestamp);
// System messages break groups
if (msg.isSystem) {
if (currentGroup) {
items.push({ type: "group", group: currentGroup })
currentGroup = null
items.push({ type: "group", group: currentGroup });
currentGroup = null;
}
// Insert date separator if needed
if (!lastDate || !isSameDay(lastDate, msgDate)) {
items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) })
lastDate = msgDate
items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) });
lastDate = msgDate;
}
items.push({ type: "system", message: msg })
continue
items.push({ type: "system", message: msg });
continue;
}
// Insert date separator if needed
if (!lastDate || !isSameDay(lastDate, msgDate)) {
if (currentGroup) {
items.push({ type: "group", group: currentGroup })
currentGroup = null
items.push({ type: "group", group: currentGroup });
currentGroup = null;
}
items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) })
lastDate = msgDate
items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) });
lastDate = msgDate;
}
// Check if message should continue the current group
@ -82,16 +68,14 @@ export function groupMessages(
currentGroup.messages.length > 0 &&
differenceInSeconds(
msgDate,
new Date(
currentGroup.messages[currentGroup.messages.length - 1]!.timestamp
)
) <= intervalSeconds
new Date(currentGroup.messages[currentGroup.messages.length - 1]!.timestamp)
) <= intervalSeconds;
if (shouldGroup && currentGroup) {
currentGroup.messages.push(msg)
currentGroup.messages.push(msg);
} else {
if (currentGroup) {
items.push({ type: "group", group: currentGroup })
items.push({ type: "group", group: currentGroup });
}
currentGroup = {
senderId: msg.senderId,
@ -99,133 +83,126 @@ export function groupMessages(
senderAvatar: msg.senderAvatar,
messages: [msg],
isOutgoing: msg.senderId === currentUserId,
}
};
}
}
if (currentGroup) {
items.push({ type: "group", group: currentGroup })
items.push({ type: "group", group: currentGroup });
}
return items
return items;
}
// ─── Auto-scroll hook ─────────────────────────────────────────────────────────
export function useAutoScroll(
messages: ChatMessageData[],
opts?: { threshold?: number }
) {
const containerRef = useRef<HTMLDivElement>(null)
const [isAtBottom, setIsAtBottom] = useState(true)
const [unseenCount, setUnseenCount] = useState(0)
const prevLengthRef = useRef(messages.length)
const threshold = opts?.threshold ?? 100
export function useAutoScroll(messages: ChatMessageData[], opts?: { threshold?: number }) {
const containerRef = useRef<HTMLDivElement>(null);
const [isAtBottom, setIsAtBottom] = useState(true);
const [unseenCount, setUnseenCount] = useState(0);
const prevLengthRef = useRef(messages.length);
const threshold = opts?.threshold ?? 100;
const scrollToBottom = useCallback(
(behavior: ScrollBehavior = "smooth") => {
const el = containerRef.current
if (!el) return
el.scrollTo({ top: el.scrollHeight, behavior })
setUnseenCount(0)
},
[]
)
const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => {
const el = containerRef.current;
if (!el) return;
el.scrollTo({ top: el.scrollHeight, behavior });
setUnseenCount(0);
}, []);
// Track scroll position
useEffect(() => {
const el = containerRef.current
if (!el) return
const el = containerRef.current;
if (!el) return;
const handleScroll = () => {
const distanceFromBottom =
el.scrollHeight - el.scrollTop - el.clientHeight
const atBottom = distanceFromBottom <= threshold
setIsAtBottom(atBottom)
if (atBottom) setUnseenCount(0)
}
const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
const atBottom = distanceFromBottom <= threshold;
setIsAtBottom(atBottom);
if (atBottom) setUnseenCount(0);
};
el.addEventListener("scroll", handleScroll, { passive: true })
return () => el.removeEventListener("scroll", handleScroll)
}, [threshold])
el.addEventListener("scroll", handleScroll, { passive: true });
return () => el.removeEventListener("scroll", handleScroll);
}, [threshold]);
// Auto-scroll when new messages arrive and user is at bottom
useEffect(() => {
const newCount = messages.length - prevLengthRef.current
prevLengthRef.current = messages.length
const newCount = messages.length - prevLengthRef.current;
prevLengthRef.current = messages.length;
if (newCount <= 0) return
if (newCount <= 0) return;
if (isAtBottom) {
scrollToBottom("smooth")
scrollToBottom("smooth");
} else {
setUnseenCount((c) => c + newCount)
setUnseenCount((c) => c + newCount);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [messages.length])
}, [messages.length]);
// Scroll to bottom on mount
useEffect(() => {
scrollToBottom("instant")
scrollToBottom("instant");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
}, []);
return { containerRef, scrollToBottom, isAtBottom, unseenCount } as const
return { containerRef, scrollToBottom, isAtBottom, unseenCount } as const;
}
// ─── Auto-resize textarea hook ────────────────────────────────────────────────
export function useAutoResize(opts?: { maxRows?: number }) {
const textareaRef = useRef<HTMLTextAreaElement>(null)
const maxRows = opts?.maxRows ?? 6
const textareaRef = useRef<HTMLTextAreaElement>(null);
const maxRows = opts?.maxRows ?? 6;
const resize = useCallback(() => {
const el = textareaRef.current
if (!el) return
el.style.height = "auto"
const lineHeight = parseInt(getComputedStyle(el).lineHeight) || 22
const maxHeight = lineHeight * maxRows
el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`
el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden"
}, [maxRows])
const el = textareaRef.current;
if (!el) return;
el.style.height = "auto";
const lineHeight = parseInt(getComputedStyle(el).lineHeight) || 22;
const maxHeight = lineHeight * maxRows;
el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`;
el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden";
}, [maxRows]);
return { textareaRef, resize } as const
return { textareaRef, resize } as const;
}
// ─── Typing indicator hook ────────────────────────────────────────────────────
export function useTypingIndicator(opts?: {
onTypingChange?: (isTyping: boolean) => void
debounceMs?: number
onTypingChange?: (isTyping: boolean) => void;
debounceMs?: number;
}) {
const [isTyping, setIsTyping] = useState(false)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const debounceMs = opts?.debounceMs ?? 2000
const [isTyping, setIsTyping] = useState(false);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const debounceMs = opts?.debounceMs ?? 2000;
const handleKeyDown = useCallback(() => {
if (!isTyping) {
setIsTyping(true)
opts?.onTypingChange?.(true)
setIsTyping(true);
opts?.onTypingChange?.(true);
}
if (timeoutRef.current) clearTimeout(timeoutRef.current)
if (timeoutRef.current) clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
setIsTyping(false)
opts?.onTypingChange?.(false)
}, debounceMs)
}, [isTyping, debounceMs, opts])
setIsTyping(false);
opts?.onTypingChange?.(false);
}, debounceMs);
}, [isTyping, debounceMs, opts]);
const stopTyping = useCallback(() => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
setIsTyping(false)
opts?.onTypingChange?.(false)
}, [opts])
if (timeoutRef.current) clearTimeout(timeoutRef.current);
setIsTyping(false);
opts?.onTypingChange?.(false);
}, [opts]);
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
}
}, [])
if (timeoutRef.current) clearTimeout(timeoutRef.current);
};
}, []);
return { isTyping, handleKeyDown, stopTyping } as const
return { isTyping, handleKeyDown, stopTyping } as const;
}

View file

@ -1,114 +1,110 @@
// Core components
export {
ChatProvider,
ChatMessage,
ChatMessageGroup,
ChatDateSeparator,
ChatSystemMessage,
ChatMessages,
ChatComposer,
ChatMessageStatus,
ChatMessageReactions,
ChatMessageActions,
ChatMessageReply,
ChatTypingIndicator,
ChatReplyPreview,
ChatReadReceipts,
} from "./components/chat"
export type {
ChatProviderProps,
ChatMessageProps,
ChatMessageGroupProps,
ChatDateSeparatorProps,
ChatSystemMessageProps,
ChatMessagesProps,
ChatComposerProps,
ChatMessageActionsProps,
ChatTypingIndicatorProps,
ChatReplyPreviewProps,
} from "./components/chat"
export type {
ChatComposerProps,
ChatDateSeparatorProps,
ChatMessageActionsProps,
ChatMessageGroupProps,
ChatMessageProps,
ChatMessagesProps,
ChatProviderProps,
ChatReplyPreviewProps,
ChatSystemMessageProps,
ChatTypingIndicatorProps,
} from "./components/chat";
export {
ChatComposer,
ChatDateSeparator,
ChatMessage,
ChatMessageActions,
ChatMessageGroup,
ChatMessageReactions,
ChatMessageReply,
ChatMessageStatus,
ChatMessages,
ChatProvider,
ChatReadReceipts,
ChatReplyPreview,
ChatSystemMessage,
ChatTypingIndicator,
} from "./components/chat";
export type {
ChatDeletedMessageProps,
ChatEditComposerProps,
ChatForwardDialogProps,
ChatNestedThreadProps,
ChatPinnedPanelProps,
ChatSearchProps,
Conversation,
SearchResult,
ThreadedMessage,
} from "./components/features";
// Feature components
export {
ChatForwardDialog,
ChatEditComposer,
ChatDeletedMessage,
ChatPinnedPanel,
ChatEditComposer,
ChatForwardDialog,
ChatNestedThread,
ChatPinnedPanel,
ChatSearch,
} from "./components/features"
} from "./components/features";
export type {
Conversation,
ChatForwardDialogProps,
ChatEditComposerProps,
ChatDeletedMessageProps,
ChatPinnedPanelProps,
ThreadedMessage,
ChatNestedThreadProps,
SearchResult,
ChatSearchProps,
} from "./components/features"
// Pre-built layouts
export {
ChatHeader,
ChatConversationItem,
FullMessenger,
ChatWidget,
InlineChat,
ChatBoard,
LiveChat,
SupportTickets,
TicketStatusBadge,
TicketPriorityBadge,
TicketFilterTabs,
} from "./components/layouts"
export type {
ChatHeaderProps,
SidebarConversation,
FullMessengerProps,
ChatWidgetProps,
InlineChatProps,
Topic,
ChatBoardProps,
ChatHeaderProps,
ChatWidgetProps,
FullMessengerProps,
InlineChatProps,
LiveChatProps,
TicketStatus,
TicketPriority,
SidebarConversation,
SupportTicket,
SupportTicketsProps,
} from "./components/layouts"
TicketPriority,
TicketStatus,
Topic,
} from "./components/layouts";
// Pre-built layouts
export {
ChatBoard,
ChatConversationItem,
ChatHeader,
ChatWidget,
FullMessenger,
InlineChat,
LiveChat,
SupportTickets,
TicketFilterTabs,
TicketPriorityBadge,
TicketStatusBadge,
} from "./components/layouts";
// Hooks
export {
formatDateLabel,
formatTimestamp,
groupMessages,
useAutoResize,
useAutoScroll,
useTypingIndicator,
} from "./hooks";
export type { FileValidationResult } from "./security";
// Security utilities
export {
sanitizeUrl,
displayHostname,
formatReactionCount,
isValidEmoji,
sanitizeFileName,
sanitizeSenderName,
sanitizeUrl,
stripBidiOverrides,
truncateMessage,
sanitizeSenderName,
validateFile,
sanitizeFileName,
isValidEmoji,
formatReactionCount,
} from "./security"
export type { FileValidationResult } from "./security"
} from "./security";
// Types
export type {
ChatUser,
ChatConfig,
ChatLabels,
ChatMessageData,
ChatConfig,
ChatUser,
MessageGroup,
MessageListItem,
TypingUser,
} from "./types"
// Hooks
export {
groupMessages,
useAutoScroll,
useAutoResize,
useTypingIndicator,
formatTimestamp,
formatDateLabel,
} from "./hooks"
} from "./types";

View file

@ -5,22 +5,22 @@
// ─── URL Sanitization ─────────────────────────────────────────────────────────
const ALLOWED_URL_PROTOCOL = /^(https?:\/\/|mailto:)/i
const ALLOWED_URL_PROTOCOL = /^(https?:\/\/|mailto:)/i;
/** Sanitize a URL — only allow http, https, and mailto. Blocks javascript:, data:, etc. */
export function sanitizeUrl(url: string | undefined | null): string {
if (!url) return "#"
const trimmed = url.trim()
if (!ALLOWED_URL_PROTOCOL.test(trimmed)) return "#"
return trimmed
if (!url) return "#";
const trimmed = url.trim();
if (!ALLOWED_URL_PROTOCOL.test(trimmed)) return "#";
return trimmed;
}
/** Extract hostname from a URL for display (prevents misleading long URLs) */
export function displayHostname(url: string): string {
try {
return new URL(url).hostname
return new URL(url).hostname;
} catch {
return url
return url;
}
}
@ -29,7 +29,7 @@ export function displayHostname(url: string): string {
/** Strip bidi override characters that can disguise malicious content (RLO attacks) */
export function stripBidiOverrides(text: string): string {
// Remove LRO, RLO, LRE, RLE, PDF, LRI, RLI, FSI, PDI
return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, "")
return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, "");
}
/** Truncate message text to prevent rendering DoS */
@ -37,80 +37,97 @@ export function truncateMessage(
text: string,
maxLength: number = 10_000
): { text: string; truncated: boolean } {
if (text.length <= maxLength) return { text, truncated: false }
return { text: text.slice(0, maxLength) + "\u2026", truncated: true }
if (text.length <= maxLength) return { text, truncated: false };
return { text: `${text.slice(0, maxLength)}\u2026`, truncated: true };
}
/** Sanitize sender name — strip bidi, truncate */
export function sanitizeSenderName(name: string): string {
return stripBidiOverrides(name).slice(0, 100)
return stripBidiOverrides(name).slice(0, 100);
}
// ─── File Validation ──────────────────────────────────────────────────────────
const BLOCKED_EXTENSIONS = new Set([
".exe", ".bat", ".cmd", ".scr", ".pif", ".com",
".js", ".jsx", ".ts", ".tsx", ".mjs",
".html", ".htm", ".xhtml",
".exe",
".bat",
".cmd",
".scr",
".pif",
".com",
".js",
".jsx",
".ts",
".tsx",
".mjs",
".html",
".htm",
".xhtml",
".svg",
".xml", ".xsl", ".xslt",
".hta", ".vbs", ".vbe", ".wsf", ".wsh",
".ps1", ".psm1",
".sh", ".bash",
])
".xml",
".xsl",
".xslt",
".hta",
".vbs",
".vbe",
".wsf",
".wsh",
".ps1",
".psm1",
".sh",
".bash",
]);
const DEFAULT_MAX_FILE_SIZE = 25 * 1024 * 1024 // 25MB
const DEFAULT_MAX_FILE_SIZE = 25 * 1024 * 1024; // 25MB
export interface FileValidationResult {
valid: boolean
error?: string
valid: boolean;
error?: string;
}
export function validateFile(
file: File,
opts?: { maxSize?: number }
): FileValidationResult {
const maxSize = opts?.maxSize ?? DEFAULT_MAX_FILE_SIZE
export function validateFile(file: File, opts?: { maxSize?: number }): FileValidationResult {
const maxSize = opts?.maxSize ?? DEFAULT_MAX_FILE_SIZE;
// Check extension
const parts = file.name.split(".")
const ext = parts.length > 1 ? "." + parts[parts.length - 1]!.toLowerCase() : ""
const parts = file.name.split(".");
const ext = parts.length > 1 ? `.${parts[parts.length - 1]!.toLowerCase()}` : "";
if (BLOCKED_EXTENSIONS.has(ext)) {
return { valid: false, error: `File type ${ext} is not allowed` }
return { valid: false, error: `File type ${ext} is not allowed` };
}
// Check size
if (file.size > maxSize) {
const mbLimit = Math.round(maxSize / (1024 * 1024))
return { valid: false, error: `File exceeds maximum size of ${mbLimit}MB` }
const mbLimit = Math.round(maxSize / (1024 * 1024));
return { valid: false, error: `File exceeds maximum size of ${mbLimit}MB` };
}
return { valid: true }
return { valid: true };
}
/** Sanitize a file name for display */
export function sanitizeFileName(name: string): string {
let clean = name.replace(/[/\\]/g, "_") // Remove path traversal
clean = clean.replace(/\0/g, "") // Remove null bytes
clean = stripBidiOverrides(clean) // Remove bidi overrides
if (clean.length > 100) clean = clean.slice(0, 97) + "..."
return clean
let clean = name.replace(/[/\\]/g, "_"); // Remove path traversal
clean = clean.replace(/\0/g, ""); // Remove null bytes
clean = stripBidiOverrides(clean); // Remove bidi overrides
if (clean.length > 100) clean = `${clean.slice(0, 97)}...`;
return clean;
}
// ─── Emoji Validation ─────────────────────────────────────────────────────────
const EMOJI_REGEX = /^(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(\u200D(\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u
const EMOJI_REGEX =
/^(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(\u200D(\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u;
/** Validate that a string is a valid emoji (not arbitrary text) */
export function isValidEmoji(str: string): boolean {
return EMOJI_REGEX.test(str) && str.length <= 20
return EMOJI_REGEX.test(str) && str.length <= 20;
}
// ─── Reaction Count Safety ────────────────────────────────────────────────────
/** Format reaction count for display (cap at 999+, floor at 0) */
export function formatReactionCount(count: number): string {
if (count <= 0) return "0"
if (count > 999) return "999+"
return String(count)
if (count <= 0) return "0";
if (count > 999) return "999+";
return String(count);
}

View file

@ -1,84 +1,84 @@
export interface ChatUser {
id: string
name: string
avatar?: string
status?: "online" | "away" | "dnd" | "offline"
id: string;
name: string;
avatar?: string;
status?: "online" | "away" | "dnd" | "offline";
}
export interface ChatMessageData {
id: string
senderId: string
senderName: string
senderAvatar?: string
id: string;
senderId: string;
senderName: string;
senderAvatar?: string;
// Content
text?: string
images?: { url: string; width: number; height: number; alt?: string }[]
files?: { name: string; size: number; type: string; url: string }[]
voice?: { url: string; duration: number; waveform: number[] }
text?: string;
images?: { url: string; width: number; height: number; alt?: string }[];
files?: { name: string; size: number; type: string; url: string }[];
voice?: { url: string; duration: number; waveform: number[] };
linkPreview?: {
url: string
title: string
description: string
image?: string
}
code?: { language: string; code: string }
url: string;
title: string;
description: string;
image?: string;
};
code?: { language: string; code: string };
// Metadata
timestamp: Date | number
status?: "sending" | "sent" | "delivered" | "read" | "failed"
replyTo?: { id: string; senderName: string; text: string }
reactions?: { emoji: string; userIds: string[]; count: number }[]
isEdited?: boolean
isPinned?: boolean
isSystem?: boolean
systemEvent?: string
timestamp: Date | number;
status?: "sending" | "sent" | "delivered" | "read" | "failed";
replyTo?: { id: string; senderName: string; text: string };
reactions?: { emoji: string; userIds: string[]; count: number }[];
isEdited?: boolean;
isPinned?: boolean;
isSystem?: boolean;
systemEvent?: string;
// Read receipts (group chat) — list of users who have read up to this message
readBy?: { userId: string; name: string; avatar?: string }[]
readBy?: { userId: string; name: string; avatar?: string }[];
}
export interface ChatLabels {
composerPlaceholder?: string
typingOne?: string // e.g. "{{name}} is typing"
typingTwo?: string // e.g. "{{name1}} and {{name2}} are typing"
typingMany?: string // e.g. "Several people are typing"
scrollToBottom?: string
composerPlaceholder?: string;
typingOne?: string; // e.g. "{{name}} is typing"
typingTwo?: string; // e.g. "{{name1}} and {{name2}} are typing"
typingMany?: string; // e.g. "Several people are typing"
scrollToBottom?: string;
}
export interface ChatConfig {
currentUser: ChatUser
dateFormat?: "relative" | "absolute" | "time-only"
messageGroupingInterval?: number // seconds, default 120
labels?: ChatLabels
currentUser: ChatUser;
dateFormat?: "relative" | "absolute" | "time-only";
messageGroupingInterval?: number; // seconds, default 120
labels?: ChatLabels;
// Callbacks
onReactionAdd?: (messageId: string, emoji: string) => void
onReactionRemove?: (messageId: string, emoji: string) => void
onReply?: (message: ChatMessageData) => void
onEdit?: (message: ChatMessageData) => void
onDelete?: (messageId: string) => void
onPin?: (messageId: string) => void
onReactionAdd?: (messageId: string, emoji: string) => void;
onReactionRemove?: (messageId: string, emoji: string) => void;
onReply?: (message: ChatMessageData) => void;
onEdit?: (message: ChatMessageData) => void;
onDelete?: (messageId: string) => void;
onPin?: (messageId: string) => void;
}
/** A group of consecutive messages from the same sender within the grouping interval */
export interface MessageGroup {
senderId: string
senderName: string
senderAvatar?: string
messages: ChatMessageData[]
isOutgoing: boolean
senderId: string;
senderName: string;
senderAvatar?: string;
messages: ChatMessageData[];
isOutgoing: boolean;
}
/** Items that can appear in the message list */
export type MessageListItem =
| { type: "group"; group: MessageGroup }
| { type: "date"; date: Date; label: string }
| { type: "system"; message: ChatMessageData }
| { type: "system"; message: ChatMessageData };
/** Typing state for one or more users */
export interface TypingUser {
id: string
name: string
avatar?: string
id: string;
name: string;
avatar?: string;
}

View file

@ -83,31 +83,43 @@ export type Database = {
created_at: string;
expires_at: string;
id: number;
invite_type: string;
invited_by: string;
invited_email: string;
invite_token: string;
is_pending: boolean;
cancelled_at: string | null;
setup_completed_at: string | null;
tablo_id: string;
used_at: string | null;
};
Insert: {
created_at?: string;
expires_at?: string;
id?: number;
invite_type?: string;
invited_by: string;
invited_email: string;
invite_token: string;
is_pending?: boolean;
cancelled_at?: string | null;
setup_completed_at?: string | null;
tablo_id: string;
used_at?: string | null;
};
Update: {
created_at?: string;
expires_at?: string;
id?: number;
invite_type?: string;
invited_by?: string;
invited_email?: string;
invite_token?: string;
is_pending?: boolean;
cancelled_at?: string | null;
setup_completed_at?: string | null;
tablo_id?: string;
used_at?: string | null;
};
Relationships: [
{
@ -429,6 +441,7 @@ export type Database = {
profiles: {
Row: {
avatar_url: string | null;
client_onboarded_at: string | null;
created_at: string | null;
email: string | null;
first_name: string | null;
@ -443,6 +456,7 @@ export type Database = {
};
Insert: {
avatar_url?: string | null;
client_onboarded_at?: string | null;
created_at?: string | null;
email?: string | null;
first_name?: string | null;
@ -457,6 +471,7 @@ export type Database = {
};
Update: {
avatar_url?: string | null;
client_onboarded_at?: string | null;
created_at?: string | null;
email?: string | null;
first_name?: string | null;

View file

@ -35,7 +35,7 @@
"react-dom": "19.0.0",
"react-router-dom": "^7.9.4",
"sonner": "^2.0.7",
"tailwind-merge": "^3.0.2",
"tailwind-merge": "^3.0.2",
"ts-pattern": "^5.6.2",
"zustand": "^5.0.5"
},

View file

@ -1,11 +1,7 @@
import type { ChatLabels, ChatMessageData, ChatUser, TypingUser } from "@xtablo/chat-ui";
import { ChatComposer, ChatMessages as ChatMessageList, ChatProvider } from "@xtablo/chat-ui";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import {
ChatProvider,
ChatMessages as ChatMessageList,
ChatComposer,
} from "@xtablo/chat-ui";
import type { ChatLabels, ChatMessageData, ChatUser, TypingUser } from "@xtablo/chat-ui";
interface ChatMessage {
id: string;
@ -60,7 +56,7 @@ export function ChatMessages({
name: membersById.get(currentUserId)?.name ?? t("currentUserName"),
avatar: membersById.get(currentUserId)?.avatar_url ?? undefined,
}),
[currentUserId, membersById, t],
[currentUserId, membersById, t]
);
const chatMessages = useMemo<ChatMessageData[]>(
@ -77,7 +73,7 @@ export function ChatMessages({
status: msg.optimistic ? "sending" : undefined,
};
}),
[messages, membersById, t],
[messages, membersById, t]
);
const chatTypingUsers = useMemo<TypingUser[]>(
@ -87,7 +83,7 @@ export function ChatMessages({
name: membersById.get(userId)?.name ?? t("defaultUserName"),
avatar: membersById.get(userId)?.avatar_url ?? undefined,
})),
[typingUsers, membersById, t],
[typingUsers, membersById, t]
);
const chatLabels = useMemo<ChatLabels>(
@ -98,19 +94,12 @@ export function ChatMessages({
typingMany: t("typingMany"),
scrollToBottom: t("scrollToBottom"),
}),
[t],
[t]
);
return (
<ChatProvider
currentUser={currentUser}
labels={chatLabels}
className="flex h-full flex-col"
>
<ChatMessageList
messages={chatMessages}
typingUsers={chatTypingUsers}
/>
<ChatProvider currentUser={currentUser} labels={chatLabels} className="flex h-full flex-col">
<ChatMessageList messages={chatMessages} typingUsers={chatTypingUsers} />
<ChatComposer
onSend={onSend}
onTyping={(_isTyping) => {

View file

@ -1,5 +1,5 @@
import { cn } from "@xtablo/shared";
import type { Etape, KanbanTask } from "@xtablo/shared-types";
import type { Etape, KanbanTask, TaskStatus } from "@xtablo/shared-types";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import {
@ -8,8 +8,8 @@ import {
ChevronDownIcon,
ChevronRightIcon,
CircleCheckIcon,
PencilIcon,
ListChecksIcon,
PencilIcon,
PlusIcon,
Trash2Icon,
XIcon,
@ -30,6 +30,7 @@ interface EtapesSectionProps {
position: number;
}) => void;
onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise<void>;
onTaskStatusChange?: (taskId: string, status: TaskStatus) => void;
onUpdateEtape?: (params: { id: string; tabloId: string; title: string }) => Promise<void>;
onDeleteEtape?: (params: { id: string; tabloId: string }) => Promise<void>;
isCreatingEtape?: boolean;
@ -44,6 +45,7 @@ export function EtapesSection({
isAdmin,
onCreateTask,
onCreateEtape,
onTaskStatusChange,
onUpdateEtape,
onDeleteEtape,
isCreatingEtape = false,
@ -176,11 +178,7 @@ export function EtapesSection({
required
className="h-11 sm:h-9 sm:w-80"
/>
<Button
type="submit"
disabled={isCreatingEtape}
className="min-h-[44px] sm:min-h-0"
>
<Button type="submit" disabled={isCreatingEtape} className="min-h-[44px] sm:min-h-0">
<PlusIcon className="w-4 h-4" />
Ajouter une étape
</Button>
@ -381,7 +379,15 @@ export function EtapesSection({
{childTasks.map((task) => (
<div
key={task.id}
className="flex items-center gap-3 px-3 sm:px-5 py-3 pl-8 sm:pl-16 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
className={cn(
"flex items-center gap-3 px-3 sm:px-5 py-3 pl-8 sm:pl-16 transition-colors",
onTaskStatusChange
? "cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800"
: "hover:bg-gray-50 dark:hover:bg-gray-800"
)}
onClick={() =>
onTaskStatusChange?.(task.id, task.status === "done" ? "todo" : "done")
}
>
{task.status === "done" ? (
<CircleCheckIcon className="w-4 h-4 text-green-500 shrink-0" />

View file

@ -49,7 +49,9 @@ export function TabloDetailsShell({
<h1 className="text-xl md:text-3xl font-bold text-foreground">{tablo.name}</h1>
</div>
{headerActions && <div className="flex items-center gap-3 w-full sm:w-auto">{headerActions}</div>}
{headerActions && (
<div className="flex items-center gap-3 w-full sm:w-auto">{headerActions}</div>
)}
</div>
<div className="flex flex-wrap items-center gap-3 sm:gap-6 text-sm border-b border-[#F2F4F7] dark:border-gray-700 pb-4 mb-4">
@ -58,7 +60,8 @@ export function TabloDetailsShell({
key={item.key}
className={cn(
"flex items-center gap-2",
index < metadata.length - 1 && "sm:border-r border-[#D0D5DD] dark:border-gray-600 sm:pr-4"
index < metadata.length - 1 &&
"sm:border-r border-[#D0D5DD] dark:border-gray-600 sm:pr-4"
)}
>
<span className="text-muted-foreground">{item.label}</span>

View file

@ -1,7 +1,7 @@
import type { UserTablo } from "@xtablo/shared/types/tablos.types";
import { useEffect } from "react";
import { useChat } from "./hooks/useChat";
import { ChatMessages } from "./ChatMessages";
import { useChat } from "./hooks/useChat";
interface Member {
id: string;

View file

@ -46,7 +46,11 @@ interface TabloEventsSectionProps {
isInvitingUser?: boolean;
isCancellingInvite?: boolean;
onCreateEvent?: () => void;
onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise<void>;
onUpdateTablo?: (data: {
id: string;
name?: string | null;
color?: string | null;
}) => Promise<void>;
onInviteUser?: (params: { email: string; tablo_id: string }) => void;
onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void;
}

View file

@ -270,8 +270,9 @@ const FolderDialog = ({
const FolderSection = ({
folder,
files,
isAdmin,
isReadOnly,
canManageFolders,
canUploadFiles,
canDeleteFiles,
isOpen,
onToggle,
onEdit,
@ -285,8 +286,9 @@ const FolderSection = ({
}: {
folder: TabloFolder;
files: string[];
isAdmin: boolean;
isReadOnly: boolean;
canManageFolders: boolean;
canUploadFiles: boolean;
canDeleteFiles: boolean;
isOpen: boolean;
onToggle: () => void;
onEdit: () => void;
@ -341,7 +343,7 @@ const FolderSection = ({
</div>
</div>
<div className="flex items-center space-x-2">
{isAdmin && !isReadOnly && (
{canManageFolders && (
<>
<Button
size="sm"
@ -378,47 +380,49 @@ const FolderSection = ({
<CollapsibleContent>
<div className="border-t border-border p-4 space-y-4">
{/* File Upload Area */}
<div>
<input
ref={fileInputRef}
type="file"
onChange={handleFileSelect}
className="hidden"
accept="*/*"
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
className="w-full py-4 border-2 border-dashed border-gray-300 dark:border-gray-600 hover:border-amber-400 dark:hover:border-amber-500 bg-gray-50 dark:bg-gray-800/50 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-colors rounded-md cursor-pointer flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isUploading ? (
<>
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-amber-500"></div>
<span className="text-sm text-muted-foreground">Téléchargement...</span>
</>
) : (
<>
<svg
className="w-5 h-5 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 6v6m0 0v6m0-6h6m-6 0H6"
/>
</svg>
<span className="text-sm text-muted-foreground">
Ajouter un fichier à ce livrable
</span>
</>
)}
</button>
</div>
{canUploadFiles && (
<div>
<input
ref={fileInputRef}
type="file"
onChange={handleFileSelect}
className="hidden"
accept="*/*"
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
className="w-full py-4 border-2 border-dashed border-gray-300 dark:border-gray-600 hover:border-amber-400 dark:hover:border-amber-500 bg-gray-50 dark:bg-gray-800/50 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-colors rounded-md cursor-pointer flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isUploading ? (
<>
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-amber-500"></div>
<span className="text-sm text-muted-foreground">Téléchargement...</span>
</>
) : (
<>
<svg
className="w-5 h-5 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 6v6m0 0v6m0-6h6m-6 0H6"
/>
</svg>
<span className="text-sm text-muted-foreground">
Ajouter un fichier à ce livrable
</span>
</>
)}
</button>
</div>
)}
{/* Files List */}
{files.length > 0 ? (
@ -427,7 +431,7 @@ const FolderSection = ({
<FileItem
key={fileName}
displayName={getFileNameWithoutFolder(fileName)}
canDelete={true}
canDelete={canDeleteFiles}
onDownload={() => onDownloadFile(fileName)}
onDelete={() => onDeleteFile(fileName)}
isDownloading={downloadingFile === fileName}
@ -483,13 +487,38 @@ interface TabloFilesSectionProps {
isCancellingInvite?: boolean;
isCreatingFolder?: boolean;
isUpdatingFolder?: boolean;
onCreateFile?: (params: { tabloId: string; fileName: string; data: { content: string; contentType: string } }) => Promise<void>;
canUploadFiles?: boolean;
canManageFolders?: boolean;
canDeleteFiles?: boolean;
onCreateFile?: (params: {
tabloId: string;
fileName: string;
data: { content: string; contentType: string };
}) => Promise<void>;
onDeleteFile?: (params: { tabloId: string; fileName: string }) => Promise<void>;
onDownloadFile?: (params: { tabloId: string; fileName: string }) => Promise<void>;
onCreateFolder?: (params: { tabloId: string; name: string; description: string; createdBy: string }) => Promise<void>;
onUpdateFolder?: (params: { tabloId: string; folderId: string; name: string; description: string }) => Promise<void>;
onDeleteFolder?: (params: { tabloId: string; folderId: string; folderName: string }) => Promise<void>;
onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise<void>;
onCreateFolder?: (params: {
tabloId: string;
name: string;
description: string;
createdBy: string;
}) => Promise<void>;
onUpdateFolder?: (params: {
tabloId: string;
folderId: string;
name: string;
description: string;
}) => Promise<void>;
onDeleteFolder?: (params: {
tabloId: string;
folderId: string;
folderName: string;
}) => Promise<void>;
onUpdateTablo?: (data: {
id: string;
name?: string | null;
color?: string | null;
}) => Promise<void>;
onInviteUser?: (params: { email: string; tablo_id: string }) => void;
onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void;
}
@ -512,6 +541,9 @@ export const TabloFilesSection = ({
isCancellingInvite,
isCreatingFolder = false,
isUpdatingFolder = false,
canUploadFiles,
canManageFolders,
canDeleteFiles,
onCreateFile,
onDeleteFile,
onDownloadFile,
@ -534,6 +566,9 @@ export const TabloFilesSection = ({
const fileInputRef = useRef<HTMLInputElement>(null);
const folderIds = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
const allowUploadFiles = canUploadFiles ?? !isReadOnly;
const allowManageFolders = canManageFolders ?? (isAdmin && !isReadOnly);
const allowDeleteFiles = canDeleteFiles ?? true;
// Organize files by folder
const { filesInFolders, unorganizedFiles } = useMemo(() => {
@ -805,7 +840,7 @@ export const TabloFilesSection = ({
)}
{/* Create Folder Button - Admin Only */}
{isAdmin && !isReadOnly && (
{allowManageFolders && (
<div className="flex justify-end">
<Button onClick={handleCreateFolder} variant="outline" className="gap-2">
<FolderPlusIcon className="w-4 h-4" />
@ -836,8 +871,9 @@ export const TabloFilesSection = ({
key={folder.id}
folder={folder}
files={filesInFolders.get(folder.id) || []}
isAdmin={isAdmin}
isReadOnly={isReadOnly}
canManageFolders={allowManageFolders}
canUploadFiles={allowUploadFiles}
canDeleteFiles={allowDeleteFiles}
isOpen={openFolders.has(folder.id)}
onToggle={() => toggleFolder(folder.id)}
onEdit={() => handleEditFolder(folder)}
@ -879,7 +915,7 @@ export const TabloFilesSection = ({
</div>
{/* File Upload Area */}
{!selectedFile ? (
{allowUploadFiles && !selectedFile ? (
<div className="space-y-3">
<input
ref={fileInputRef}
@ -915,7 +951,7 @@ export const TabloFilesSection = ({
</div>
</button>
</div>
) : (
) : allowUploadFiles && selectedFile ? (
<div className="space-y-3">
<div className="flex items-center space-x-3 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-md">
<div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
@ -979,11 +1015,13 @@ export const TabloFilesSection = ({
</button>
</div>
</div>
)}
) : null}
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
Taille maximale par fichier: 20MB
</p>
{allowUploadFiles && (
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
Taille maximale par fichier: 20MB
</p>
)}
{/* Unorganized Files List */}
{unorganizedFiles.length > 0 && (
@ -992,7 +1030,7 @@ export const TabloFilesSection = ({
<FileItem
key={fileName}
displayName={getFileNameWithoutFolder(fileName)}
canDelete={true}
canDelete={allowDeleteFiles}
onDownload={() => handleDownloadFile(fileName)}
onDelete={() => handleDeleteFile(fileName)}
isDownloading={downloadingFile === fileName}

View file

@ -12,8 +12,8 @@ import { TypographyH3, TypographyMuted } from "@xtablo/ui/components/typography"
import { AlertTriangle, ListChecks } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { KanbanBoard } from "./components/kanban/KanbanBoard";
import type { TabloMember } from "./components/kanban/types";
import { TaskModal } from "./components/kanban/TaskModal";
import type { TabloMember } from "./components/kanban/types";
import { TabloHeaderActions } from "./TabloHeaderActions";
interface CurrentUser {
@ -39,8 +39,14 @@ interface TabloTasksSectionProps {
onCreateTask?: (task: KanbanTaskInsert) => void;
onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void;
onDeleteTask?: (taskId: string) => void;
onUpdateTaskPositions?: (updates: Array<{ id: string; position: number; status: TaskStatus }>) => void;
onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise<void>;
onUpdateTaskPositions?: (
updates: Array<{ id: string; position: number; status: TaskStatus }>
) => void;
onUpdateTablo?: (data: {
id: string;
name?: string | null;
color?: string | null;
}) => Promise<void>;
onInviteUser?: (params: { email: string; tablo_id: string }) => void;
onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void;
}
@ -245,7 +251,8 @@ export const TabloTasksSection = ({
{orphanedTasks.length} {pluralize("tâche", orphanedTasks.length)} sans Étape
</p>
<p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
Associez {orphanedTasks.length > 1 ? "ces" : "cette"} {pluralize("tâche", orphanedTasks.length)} à une étape.
Associez {orphanedTasks.length > 1 ? "ces" : "cette"}{" "}
{pluralize("tâche", orphanedTasks.length)} à une étape.
</p>
</div>
</div>

View file

@ -1,4 +1,10 @@
import type { Etape, KanbanTask, KanbanTaskInsert, KanbanTaskUpdate, TaskStatus } from "@xtablo/shared-types";
import type {
Etape,
KanbanTask,
KanbanTaskInsert,
KanbanTaskUpdate,
TaskStatus,
} from "@xtablo/shared-types";
import { Button } from "@xtablo/ui/components/button";
import { DatePicker } from "@xtablo/ui/components/date-picker";
import { Input } from "@xtablo/ui/components/input";
@ -74,11 +80,11 @@ export const TaskModal = ({
const selectedAssigneeLabel =
assigneeId === "unassigned"
? "Non assigné"
: providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné";
: (providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné");
const selectedEtapeLabel =
etapeId === "none"
? "Aucune Étape"
: providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape";
: (providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape");
useEffect(() => {
if (!isOpen) {
@ -104,7 +110,15 @@ export const TaskModal = ({
setSelectedTabloId(tablos[0].id);
}
}
}, [isOpen, task, initialTabloId, allowTabloSelection, tablos, initialDueDate, defaultAssigneeId]);
}, [
isOpen,
task,
initialTabloId,
allowTabloSelection,
tablos,
initialDueDate,
defaultAssigneeId,
]);
// Format Date to YYYY-MM-DD string for database storage
const formatDateForDb = (date: Date | undefined): string | null => {

View file

@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { useCallback, useEffect, useRef, useState } from "react";
interface ChatMessage {
id: string;
@ -31,7 +31,14 @@ function normalizeMessage(raw: RawApiMessage): ChatMessage {
}
type ServerMessage =
| { type: "message.new"; id: string; userId: string; text: string; createdAt: string; clientId: string }
| {
type: "message.new";
id: string;
userId: string;
text: string;
createdAt: string;
clientId: string;
}
| { type: "typing"; userId: string; isTyping: boolean }
| { type: "presence.update"; userId: string; status: "online" | "offline" }
| { type: "error"; code: string; message: string };
@ -56,30 +63,33 @@ export function useChat(channelId: string | undefined) {
const isTypingRef = useRef(false);
// Fetch message history from REST endpoint
const fetchHistory = useCallback(async (before?: string) => {
if (!channelId || !token) return;
const fetchHistory = useCallback(
async (before?: string) => {
if (!channelId || !token) return;
const params = new URLSearchParams({ limit: "50" });
if (before) params.set("before", before);
const params = new URLSearchParams({ limit: "50" });
if (before) params.set("before", before);
const res = await fetch(`${CHAT_API_BASE}/chat/channels/${channelId}/messages?${params}`, {
headers: { Authorization: `Bearer ${token}` },
});
const res = await fetch(`${CHAT_API_BASE}/chat/channels/${channelId}/messages?${params}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return;
if (!res.ok) return;
const data = await res.json() as { messages: RawApiMessage[]; hasMore: boolean };
const normalized = data.messages.map(normalizeMessage);
setHasMoreMessages(data.hasMore);
const data = (await res.json()) as { messages: RawApiMessage[]; hasMore: boolean };
const normalized = data.messages.map(normalizeMessage);
setHasMoreMessages(data.hasMore);
if (before) {
// Prepend older messages
setMessages((prev) => [...normalized, ...prev]);
} else {
// Initial load
setMessages(normalized);
}
}, [channelId, token]);
if (before) {
// Prepend older messages
setMessages((prev) => [...normalized, ...prev]);
} else {
// Initial load
setMessages(normalized);
}
},
[channelId, token]
);
// Load more (pagination)
const loadMoreMessages = useCallback(() => {
@ -116,13 +126,16 @@ export function useChat(channelId: string | undefined) {
if (withoutOptimistic.some((m) => m.id === msg.id)) {
return withoutOptimistic;
}
return [...withoutOptimistic, {
id: msg.id,
userId: msg.userId,
text: msg.text,
createdAt: msg.createdAt,
clientId: msg.clientId,
}];
return [
...withoutOptimistic,
{
id: msg.id,
userId: msg.userId,
text: msg.text,
createdAt: msg.createdAt,
clientId: msg.clientId,
},
];
});
break;
@ -130,7 +143,9 @@ export function useChat(channelId: string | undefined) {
if (msg.userId === session?.user?.id) break;
setTypingUsers((prev) =>
msg.isTyping
? prev.includes(msg.userId) ? prev : [...prev, msg.userId]
? prev.includes(msg.userId)
? prev
: [...prev, msg.userId]
: prev.filter((id) => id !== msg.userId)
);
break;
@ -138,7 +153,9 @@ export function useChat(channelId: string | undefined) {
case "presence.update":
setOnlineUsers((prev) =>
msg.status === "online"
? prev.includes(msg.userId) ? prev : [...prev, msg.userId]
? prev.includes(msg.userId)
? prev
: [...prev, msg.userId]
: prev.filter((id) => id !== msg.userId)
);
break;
@ -182,33 +199,36 @@ export function useChat(channelId: string | undefined) {
}, [channelId, token, fetchHistory]);
// Send message
const sendMessage = useCallback((text: string) => {
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
const sendMessage = useCallback(
(text: string) => {
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
const clientId = crypto.randomUUID();
const clientId = crypto.randomUUID();
// Optimistic update
setMessages((prev) => [
...prev,
{
id: `optimistic-${clientId}`,
userId: session?.user?.id ?? "",
text,
createdAt: new Date().toISOString(),
clientId,
optimistic: true,
},
]);
// Optimistic update
setMessages((prev) => [
...prev,
{
id: `optimistic-${clientId}`,
userId: session?.user?.id ?? "",
text,
createdAt: new Date().toISOString(),
clientId,
optimistic: true,
},
]);
wsRef.current.send(JSON.stringify({ type: "message.send", text, clientId }));
wsRef.current.send(JSON.stringify({ type: "message.send", text, clientId }));
// Stop typing when sending
if (isTypingRef.current) {
wsRef.current.send(JSON.stringify({ type: "typing.stop" }));
isTypingRef.current = false;
clearTimeout(typingTimerRef.current);
}
}, [session?.user?.id]);
// Stop typing when sending
if (isTypingRef.current) {
wsRef.current.send(JSON.stringify({ type: "typing.stop" }));
isTypingRef.current = false;
clearTimeout(typingTimerRef.current);
}
},
[session?.user?.id]
);
// Typing indicator
const sendTyping = useCallback(() => {

View file

@ -19,7 +19,7 @@ export function useChatUnread() {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return [];
const json = await res.json() as { unread: UnreadCount[] };
const json = (await res.json()) as { unread: UnreadCount[] };
return json.unread;
},
enabled: !!token,

View file

@ -1,32 +1,29 @@
export { TabloTasksSection } from "./TabloTasksSection";
export { TabloFilesSection } from "./TabloFilesSection";
export { TabloDiscussionSection } from "./TabloDiscussionSection";
export { TabloEventsSection } from "./TabloEventsSection";
export { EtapesSection } from "./EtapesSection";
export { RoadmapSection } from "./RoadmapSection";
export { TabloHeaderActions } from "./TabloHeaderActions";
export { ChatMessages } from "./ChatMessages";
export { TabloDetailsShell } from "./TabloDetailsShell";
export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview";
export { SingleTabloView } from "./single-tablo/SingleTabloView";
// Sub-components
export { GanttChart } from "./components/gantt/GanttChart";
export { KanbanBoard } from "./components/kanban/KanbanBoard";
export { TaskModal } from "./components/kanban/TaskModal";
// Types
export type { TabloMember } from "./components/kanban/types";
export { EtapesSection } from "./EtapesSection";
// Hooks
export { useChat } from "./hooks/useChat";
export { useChatUnread } from "./hooks/useChatUnread";
export { RoadmapSection } from "./RoadmapSection";
export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout";
export {
DEFAULT_OVERVIEW_LAYOUT,
sanitizeOverviewLayout,
} from "./single-tablo/overviewLayout";
export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout";
export { moveBetweenZones, moveWithinZone } from "./single-tablo/overviewReorder";
export { getSingleTabloStatusConfig } from "./single-tablo/shared";
export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview";
export { SingleTabloView } from "./single-tablo/SingleTabloView";
export type { SingleTabloTabId } from "./single-tablo/shared";
// Sub-components
export { GanttChart } from "./components/gantt/GanttChart";
export { TaskModal } from "./components/kanban/TaskModal";
export { KanbanBoard } from "./components/kanban/KanbanBoard";
// Hooks
export { useChat } from "./hooks/useChat";
export { useChatUnread } from "./hooks/useChatUnread";
// Types
export type { TabloMember } from "./components/kanban/types";
export { getSingleTabloStatusConfig } from "./single-tablo/shared";
export type { TabloDetailsShellMetadataItem, TabloDetailsShellTab } from "./TabloDetailsShell";
export { TabloDetailsShell } from "./TabloDetailsShell";
export { TabloDiscussionSection } from "./TabloDiscussionSection";
export { TabloEventsSection } from "./TabloEventsSection";
export { TabloFilesSection } from "./TabloFilesSection";
export { TabloHeaderActions } from "./TabloHeaderActions";
export { TabloTasksSection } from "./TabloTasksSection";

View file

@ -1,7 +1,13 @@
import { cn } from "@xtablo/shared";
import type { KanbanTask } from "@xtablo/shared-types";
import { Button } from "@xtablo/ui/components/button";
import { FileIcon, GripVerticalIcon, LayoutPanelTopIcon, ListChecksIcon, RotateCcwIcon } from "lucide-react";
import {
FileIcon,
GripVerticalIcon,
LayoutPanelTopIcon,
ListChecksIcon,
RotateCcwIcon,
} from "lucide-react";
import type { OverviewBlockId, OverviewLayoutV1 } from "./overviewLayout";
interface DraggedBlock {
@ -170,7 +176,12 @@ export function SingleTabloOverview({
))
)}
{personalTaskCount > 5 && (
<Button type="button" variant="link" className="px-0" onClick={onToggleShowAllTasks}>
<Button
type="button"
variant="link"
className="px-0"
onClick={onToggleShowAllTasks}
>
{showAllTasks ? "Afficher moins" : "Afficher plus"}
</Button>
)}
@ -231,11 +242,7 @@ export function SingleTabloOverview({
const block = renderBlockContent(blockId);
return (
<div
key={blockId}
onDragOver={onBlockDragOver}
onDrop={() => onBlockDrop(zone, index)}
>
<div key={blockId} onDragOver={onBlockDragOver} onDrop={() => onBlockDrop(zone, index)}>
<OverviewCard
title={block.title}
actions={block.actions}

View file

@ -148,6 +148,9 @@ importers:
'@tanstack/react-query':
specifier: ^5.69.0
version: 5.90.5(react@19.0.0)
'@xtablo/auth-ui':
specifier: workspace:*
version: link:../../packages/auth-ui
'@xtablo/chat-ui':
specifier: workspace:*
version: link:../../packages/chat-ui
@ -411,6 +414,9 @@ importers:
'@typescript/native-preview':
specifier: 7.0.0-dev.20251010.1
version: 7.0.0-dev.20251010.1
'@xtablo/auth-ui':
specifier: workspace:*
version: link:../../packages/auth-ui
'@xtablo/chat-ui':
specifier: workspace:*
version: link:../../packages/chat-ui
@ -635,6 +641,43 @@ importers:
specifier: ^4.24.3
version: 4.44.0(@cloudflare/workers-types@4.20260411.1)
packages/auth-ui:
dependencies:
'@xtablo/shared':
specifier: workspace:*
version: link:../shared
'@xtablo/ui':
specifier: workspace:*
version: link:../ui
lucide-react:
specifier: ^0.460.0
version: 0.460.0(react@19.0.0)
react:
specifier: 19.0.0
version: 19.0.0
react-dom:
specifier: 19.0.0
version: 19.0.0(react@19.0.0)
tailwind-merge:
specifier: ^3.0.2
version: 3.3.1
devDependencies:
'@biomejs/biome':
specifier: 2.2.5
version: 2.2.5
'@types/react':
specifier: 19.0.10
version: 19.0.10
'@types/react-dom':
specifier: 19.0.4
version: 19.0.4(@types/react@19.0.10)
typescript:
specifier: ^5.7.0
version: 5.9.3
vite:
specifier: ^6.2.2
version: 6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)
packages/chat-ui:
dependencies:
'@xtablo/shared':

View file

@ -0,0 +1,27 @@
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS client_onboarded_at timestamptz;
COMMENT ON COLUMN public.profiles.client_onboarded_at IS
'Timestamp when a client portal user completed their one-time password setup.';
ALTER TABLE public.client_invites
ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup',
ADD COLUMN IF NOT EXISTS used_at timestamptz,
ADD COLUMN IF NOT EXISTS cancelled_at timestamptz,
ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz;
COMMENT ON COLUMN public.client_invites.invite_type IS
'Invite lifecycle type. setup = first-time password onboarding token.';
COMMENT ON COLUMN public.client_invites.used_at IS
'Timestamp when the setup token was consumed.';
COMMENT ON COLUMN public.client_invites.cancelled_at IS
'Timestamp when a pending setup invite was cancelled.';
COMMENT ON COLUMN public.client_invites.setup_completed_at IS
'Timestamp when password setup completed successfully.';
CREATE UNIQUE INDEX IF NOT EXISTS idx_client_invites_pending_setup_email_tablo
ON public.client_invites (tablo_id, invited_email)
WHERE is_pending = true AND invite_type = 'setup';
CREATE INDEX IF NOT EXISTS idx_client_invites_token_pending
ON public.client_invites (invite_token, is_pending);