merge: resolve develop conflicts
This commit is contained in:
commit
11e6816a71
131 changed files with 9933 additions and 3204 deletions
|
|
@ -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
|
||||
|
|
@ -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
55
.github/workflows/ci.yml
vendored
Normal 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
|
||||
74
.github/workflows/frontend-sourcemaps.yml
vendored
Normal file
74
.github/workflows/frontend-sourcemaps.yml
vendored
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
name: Frontend Sourcemaps
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
|
||||
jobs:
|
||||
upload-sourcemaps:
|
||||
runs-on:
|
||||
- self-hosted
|
||||
- linux
|
||||
- x64
|
||||
env:
|
||||
DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }}
|
||||
DATADOG_SITE: datadoghq.com
|
||||
RELEASE_VERSION: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up pnpm
|
||||
uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 10.19.0
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
- name: Validate Datadog secrets
|
||||
run: |
|
||||
test -n "$DATADOG_API_KEY"
|
||||
test -n "$DATADOG_SITE"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile --child-concurrency=2
|
||||
|
||||
- name: Build main
|
||||
run: pnpm --filter @xtablo/main build:prod
|
||||
env:
|
||||
VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}
|
||||
|
||||
- name: Upload main sourcemaps
|
||||
run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets
|
||||
|
||||
- name: Remove main sourcemaps
|
||||
run: find apps/main/dist -name '*.map' -delete
|
||||
|
||||
- name: Build clients
|
||||
run: pnpm --filter @xtablo/clients build:prod
|
||||
env:
|
||||
VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}
|
||||
|
||||
- name: Upload clients sourcemaps
|
||||
run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets
|
||||
|
||||
- name: Remove clients sourcemaps
|
||||
run: find apps/clients/dist -name '*.map' -delete
|
||||
|
||||
- name: Build external
|
||||
run: pnpm --filter @xtablo/external build
|
||||
env:
|
||||
VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}
|
||||
|
||||
- name: Upload external sourcemaps
|
||||
run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets
|
||||
|
||||
- name: Remove external sourcemaps
|
||||
run: find apps/external/dist -name '*.map' -delete
|
||||
|
|
@ -88,3 +88,54 @@ See `.env.example` for required environment variables.
|
|||
## Deployment
|
||||
|
||||
The API is deployed to Google Cloud Run. See `cloudbuild.yaml` for deployment configuration.
|
||||
|
||||
## Dokploy Deployment
|
||||
|
||||
Prefer a Dokploy `Application` instead of a Compose service.
|
||||
|
||||
Dokploy supports Dockerfile-based applications directly, which fits this API better than maintaining a dedicated compose wrapper. Configure the application like this:
|
||||
|
||||
- Build Type: `Dockerfile`
|
||||
- Dockerfile Path: `apps/api/Dockerfile`
|
||||
- Docker Context Path: `.`
|
||||
- Docker Build Stage: `final`
|
||||
- Port: `8080`
|
||||
- Run Command: leave empty and use the image `CMD`
|
||||
|
||||
Set these Dokploy environment variables:
|
||||
|
||||
- `NODE_ENV`
|
||||
- `DD_SERVICE=xtablo-api`
|
||||
- `DD_ENV`
|
||||
- `DD_VERSION`
|
||||
- `DD_LOGS_INJECTION=true`
|
||||
- `SUPABASE_URL`
|
||||
- `SUPABASE_SERVICE_ROLE_KEY`
|
||||
- `SUPABASE_CONNECTION_STRING`
|
||||
- `SUPABASE_CA_CERT`
|
||||
- `STRIPE_SECRET_KEY`
|
||||
- `STRIPE_WEBHOOK_SECRET`
|
||||
- `STRIPE_SOLO_PRICE_ID`
|
||||
- `STRIPE_TEAM_PRICE_ID`
|
||||
- `STRIPE_FOUNDER_PRICE_ID`
|
||||
- `EMAIL_USER`
|
||||
- `EMAIL_CLIENT_ID`
|
||||
- `EMAIL_CLIENT_SECRET`
|
||||
- `EMAIL_REFRESH_TOKEN`
|
||||
- `R2_ACCOUNT_ID`
|
||||
- `R2_ACCESS_KEY_ID`
|
||||
- `R2_SECRET_ACCESS_KEY`
|
||||
- `TASKS_SECRET`
|
||||
|
||||
For Datadog logs, the Dokploy host should already run a Datadog Agent with Docker log collection enabled. Then add these Docker Swarm labels in Dokploy `Advanced Settings -> Swarm Settings -> Labels`:
|
||||
|
||||
- `com.datadoghq.tags.service=xtablo-api`
|
||||
- `com.datadoghq.tags.env=${DD_ENV}`
|
||||
- `com.datadoghq.tags.version=${DD_VERSION}`
|
||||
- `com.datadoghq.ad.logs=[{"source":"nodejs","service":"xtablo-api"}]`
|
||||
|
||||
This gives you:
|
||||
|
||||
- container logs in Datadog with `source: nodejs`
|
||||
- service tagging as `xtablo-api`
|
||||
- APM/log correlation via `dd-trace` plus `DD_LOGS_INJECTION=true`
|
||||
|
|
|
|||
|
|
@ -326,7 +326,7 @@ describe("Middleware Tests", () => {
|
|||
})
|
||||
);
|
||||
// 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);
|
||||
|
|
@ -353,7 +353,7 @@ describe("Middleware Tests", () => {
|
|||
})
|
||||
);
|
||||
// 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);
|
||||
|
|
@ -382,7 +382,7 @@ describe("Middleware Tests", () => {
|
|||
})
|
||||
);
|
||||
// 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);
|
||||
|
|
@ -410,7 +410,7 @@ describe("Middleware Tests", () => {
|
|||
})
|
||||
);
|
||||
// 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);
|
||||
|
|
@ -436,7 +436,7 @@ describe("Middleware Tests", () => {
|
|||
})
|
||||
);
|
||||
// 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);
|
||||
|
|
|
|||
|
|
@ -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 non-admin users with 403", 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(403);
|
||||
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 403 for a non-admin user", async () => {
|
||||
it("returns 401 for a temporary user before admin check", async () => {
|
||||
const res = await getPending(tempUser, adminTabloId);
|
||||
expect(res.status).toBe(403);
|
||||
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 403 for a non-admin user", 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,
|
||||
|
|
@ -352,22 +430,22 @@ describe("Client Invites Endpoints", () => {
|
|||
});
|
||||
|
||||
const res = await deleteInvite(tempUser, adminTabloId, inviteId);
|
||||
expect(res.status).toBe(403);
|
||||
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" },
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
import { testClient } from "hono/testing";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createConfig } from "../../config.js";
|
||||
import { MiddlewareManager } from "../../middlewares/middleware.js";
|
||||
import { getMainRouter } from "../../routers/index.js";
|
||||
import { TEST_USERS } from "../fixtures/testData.js";
|
||||
import type { TestUserData } from "../helpers/dbSetup.js";
|
||||
import { getTestUser } from "../helpers/dbSetup.js";
|
||||
|
||||
|
|
@ -34,6 +35,7 @@ describe("Tablo Endpoint", () => {
|
|||
const supabaseAdmin = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, {
|
||||
auth: { persistSession: false },
|
||||
});
|
||||
const createdTabloIds: string[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset all mocks before each test
|
||||
|
|
@ -41,6 +43,16 @@ describe("Tablo Endpoint", () => {
|
|||
mockSendMail.mockResolvedValue({ messageId: "test-message-id" });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (createdTabloIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const idsToDelete = createdTabloIds.splice(0, createdTabloIds.length);
|
||||
await supabaseAdmin.from("tablo_access").delete().in("tablo_id", idsToDelete);
|
||||
await supabaseAdmin.from("tablos").delete().in("id", idsToDelete);
|
||||
});
|
||||
|
||||
// Helper function to create tablo
|
||||
const createTabloRequest = async (
|
||||
user: TestUserData,
|
||||
|
|
@ -98,6 +110,23 @@ describe("Tablo Endpoint", () => {
|
|||
);
|
||||
};
|
||||
|
||||
const signInAsTestUser = async (email: string, password: string) => {
|
||||
const userClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, {
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
},
|
||||
});
|
||||
|
||||
const { data, error } = await userClient.auth.signInWithPassword({ email, password });
|
||||
|
||||
if (error || !data.session) {
|
||||
throw new Error(`Failed to sign in ${email}: ${error?.message ?? "missing session"}`);
|
||||
}
|
||||
|
||||
return userClient;
|
||||
};
|
||||
|
||||
// Helper function to get tablo members
|
||||
// biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
|
||||
const getTabloMembersRequest = async (user: TestUserData, client: any, tabloId: string) => {
|
||||
|
|
@ -171,6 +200,8 @@ describe("Tablo Endpoint", () => {
|
|||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.message).toBe("Tablo created successfully");
|
||||
expect(data.tablo?.id).toBeDefined();
|
||||
createdTabloIds.push(data.tablo.id);
|
||||
});
|
||||
|
||||
it("should deny temp user from creating a tablo (regularUserCheck blocks temporary users)", async () => {
|
||||
|
|
@ -271,7 +302,16 @@ describe("Tablo Endpoint", () => {
|
|||
}
|
||||
|
||||
if (fillerTablos.length > 0) {
|
||||
await supabaseAdmin.from("tablos").insert(fillerTablos);
|
||||
const { data: insertedTablos, error: insertError } = await supabaseAdmin
|
||||
.from("tablos")
|
||||
.insert(fillerTablos)
|
||||
.select("id");
|
||||
|
||||
if (insertError) {
|
||||
throw new Error(`Failed to insert filler tablos: ${insertError.message}`);
|
||||
}
|
||||
|
||||
createdTabloIds.push(...(insertedTablos ?? []).map((tablo) => tablo.id));
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -393,6 +433,35 @@ describe("Tablo Endpoint", () => {
|
|||
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("should allow owner to delete a tablo that contains etapes", async () => {
|
||||
const createRes = await createTabloRequest(ownerUser, client, {
|
||||
name: "Delete With Etape",
|
||||
status: "todo",
|
||||
color: "#804EEC",
|
||||
});
|
||||
|
||||
expect(createRes.status).toBe(200);
|
||||
const createData = await createRes.json();
|
||||
const createdTabloId = createData.tablo.id as string;
|
||||
createdTabloIds.push(createdTabloId);
|
||||
|
||||
const ownerClient = await signInAsTestUser(TEST_USERS.owner.email, TEST_USERS.owner.password);
|
||||
const { error: createEtapeError } = await ownerClient.from("tasks").insert({
|
||||
tablo_id: createdTabloId,
|
||||
title: "Delete me",
|
||||
is_parent: true,
|
||||
status: "todo",
|
||||
});
|
||||
|
||||
expect(createEtapeError).toBeNull();
|
||||
|
||||
const res = await deleteTabloRequest(ownerUser, client, createdTabloId);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.message).toBe("Tablo deleted successfully");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /tablos/members/:tablo_id - Get Tablo Members", () => {
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 été 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 été 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,109 +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 { 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
|
||||
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(middlewareManager.regularUserCheck, 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 });
|
||||
|
||||
|
|
@ -151,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"));
|
||||
|
|
@ -162,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();
|
||||
|
|
@ -179,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);
|
||||
|
||||
|
|
@ -190,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")
|
||||
|
|
@ -215,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;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { MiddlewareManager } from "../middlewares/middleware.js";
|
|||
import type { BaseEnv } from "../types/app.types.js";
|
||||
import { getAdminRouter } from "./admin.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";
|
||||
|
|
@ -35,6 +36,9 @@ export const getMainRouter = (config: AppConfig) => {
|
|||
// admin routes
|
||||
mainRouter.route("/admin", getAdminRouter(config));
|
||||
|
||||
// public client onboarding routes
|
||||
mainRouter.route("/client-invites", getPublicClientInvitesRouter());
|
||||
|
||||
// maybe authenticated routes (checked first to allow unauthenticated booking)
|
||||
mainRouter.route("/", getMaybeAuthenticatedRouter());
|
||||
|
||||
|
|
|
|||
|
|
@ -121,26 +121,10 @@ const deleteTablo = factory.createHandlers(async (c) => {
|
|||
|
||||
const deletedAt = new Date().toISOString();
|
||||
|
||||
const { error: tasksSoftDeleteError } = await supabase
|
||||
.from("tasks")
|
||||
.update({ deleted_at: deletedAt })
|
||||
.eq("tablo_id", id)
|
||||
.is("deleted_at", null);
|
||||
const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id);
|
||||
|
||||
if (tasksSoftDeleteError) {
|
||||
// Backward compatibility for environments where tasks.deleted_at is not migrated yet.
|
||||
const isMissingDeletedAtColumn =
|
||||
tasksSoftDeleteError.code === "42703" ||
|
||||
tasksSoftDeleteError.message?.toLowerCase().includes("deleted_at");
|
||||
|
||||
if (isMissingDeletedAtColumn) {
|
||||
const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id);
|
||||
if (tasksDeleteError) {
|
||||
return c.json({ error: tasksDeleteError.message }, 500);
|
||||
}
|
||||
} else {
|
||||
return c.json({ error: tasksSoftDeleteError.message }, 500);
|
||||
}
|
||||
if (tasksDeleteError) {
|
||||
return c.json({ error: tasksDeleteError.message }, 500);
|
||||
}
|
||||
|
||||
const { error } = await supabase.from("tablos").update({ deleted_at: deletedAt }).eq("id", id);
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ export default defineConfig({
|
|||
exclude: ["node_modules", "dist"],
|
||||
reporters: ["verbose"],
|
||||
pool: "forks",
|
||||
fileParallelism: false,
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
|
|
|
|||
|
|
@ -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"],
|
||||
|
|
|
|||
7
apps/clients/.env.production
Normal file
7
apps/clients/.env.production
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co
|
||||
VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM
|
||||
|
||||
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
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>XTablo -- Portail Clients</title>
|
||||
<title>Xtablo — Portail client</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="client-root"></div>
|
||||
|
|
|
|||
|
|
@ -8,8 +8,10 @@
|
|||
"build": "tsc -b && vite build --mode production",
|
||||
"build:staging": "tsc -b && vite build --mode staging",
|
||||
"build:prod": "tsc -b && vite build --mode production",
|
||||
"deploy": "wrangler deploy",
|
||||
"deploy:prod": "wrangler deploy --env=\"\"",
|
||||
"typecheck": "tsc -b",
|
||||
"test": "vitest run --mode test --passWithNoTests",
|
||||
"test:watch": "vitest watch --passWithNoTests",
|
||||
"lint": "biome check .",
|
||||
"lint:fix": "biome check --write .",
|
||||
"format": "biome format --write .",
|
||||
|
|
@ -20,18 +22,24 @@
|
|||
"@biomejs/biome": "2.2.5",
|
||||
"@cloudflare/vite-plugin": "^1.9.4",
|
||||
"@tailwindcss/vite": "^4.0.14",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/react": "19.0.10",
|
||||
"@types/react-dom": "19.0.4",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"jsdom": "^20.0.3",
|
||||
"tailwindcss": "^4.0.14",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5.7.0",
|
||||
"vite": "^6.2.2",
|
||||
"vite-tsconfig-paths": "^5.1.4",
|
||||
"vitest": "^3.2.4",
|
||||
"wrangler": "^4.24.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.69.0",
|
||||
"@xtablo/auth-ui": "workspace:*",
|
||||
"@xtablo/shared": "workspace:*",
|
||||
"@xtablo/shared-types": "workspace:*",
|
||||
"@xtablo/tablo-views": "workspace:*",
|
||||
|
|
|
|||
56
apps/clients/src/components/ClientAuthGate.tsx
Normal file
56
apps/clients/src/components/ClientAuthGate.tsx
Normal 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 />;
|
||||
}
|
||||
43
apps/clients/src/components/ClientLayout.test.tsx
Normal file
43
apps/clients/src/components/ClientLayout.test.tsx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
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 scrolling main viewport", () => {
|
||||
const { container } = renderWithProviders(<ClientLayout />);
|
||||
|
||||
const header = container.querySelector("header");
|
||||
expect(header).toHaveClass("h-[75px]");
|
||||
expect(header).toHaveClass("bg-navbar-background");
|
||||
|
||||
const headerInner = header?.firstElementChild;
|
||||
expect(headerInner).toHaveClass("w-full");
|
||||
expect(headerInner).toHaveClass("max-w-7xl");
|
||||
expect(headerInner).toHaveClass("mx-auto");
|
||||
|
||||
const main = container.querySelector("main");
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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,14 +24,10 @@ export function ClientLayout() {
|
|||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
{/* Top bar */}
|
||||
<header className="border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="flex h-14 items-center justify-between px-4 max-w-7xl mx-auto">
|
||||
{/* Brand */}
|
||||
<span className="text-lg font-bold text-foreground">Xtablo</span>
|
||||
|
||||
{/* User info + logout */}
|
||||
<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>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-8 w-8">
|
||||
|
|
@ -58,9 +42,10 @@ export function ClientLayout() {
|
|||
</div>
|
||||
</header>
|
||||
|
||||
{/* Page content */}
|
||||
<main className="max-w-7xl mx-auto px-4 py-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>
|
||||
);
|
||||
|
|
|
|||
15
apps/clients/src/envProduction.test.ts
Normal file
15
apps/clients/src/envProduction.test.ts
Normal 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");
|
||||
});
|
||||
});
|
||||
47
apps/clients/src/i18n.test.ts
Normal file
47
apps/clients/src/i18n.test.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import i18n from "i18next";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
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,
|
||||
components: componentsFr,
|
||||
pages: pagesFr,
|
||||
tablo: tabloFr,
|
||||
},
|
||||
en: {
|
||||
auth: authEn,
|
||||
booking: bookingEn,
|
||||
chat: chatEn,
|
||||
common: commonEn,
|
||||
components: componentsEn,
|
||||
pages: pagesEn,
|
||||
tablo: tabloEn,
|
||||
},
|
||||
},
|
||||
lng: "fr",
|
||||
fallbackLng: "fr",
|
||||
defaultNS: "booking",
|
||||
interpolation: {
|
||||
escapeValue: false,
|
||||
},
|
||||
});
|
||||
|
||||
export default i18n;
|
||||
|
|
@ -1,6 +1,18 @@
|
|||
import i18n from "i18next";
|
||||
import LanguageDetector from "i18next-browser-languagedetector";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
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";
|
||||
|
|
@ -11,10 +23,22 @@ i18n
|
|||
.init({
|
||||
resources: {
|
||||
fr: {
|
||||
auth: authFr,
|
||||
booking: bookingFr,
|
||||
chat: chatFr,
|
||||
common: commonFr,
|
||||
components: componentsFr,
|
||||
pages: pagesFr,
|
||||
tablo: tabloFr,
|
||||
},
|
||||
en: {
|
||||
auth: authEn,
|
||||
booking: bookingEn,
|
||||
chat: chatEn,
|
||||
common: commonEn,
|
||||
components: componentsEn,
|
||||
pages: pagesEn,
|
||||
tablo: tabloEn,
|
||||
},
|
||||
},
|
||||
fallbackLng: "fr",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
@import "tailwindcss";
|
||||
@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 *));
|
||||
|
||||
:root {
|
||||
|
|
@ -37,41 +41,45 @@
|
|||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
--navbar-background: rgb(249, 250, 251);
|
||||
--navbar-darker: #e5e7eb;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.145 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.145 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.985 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--background: oklch(0.17 0.012 290);
|
||||
--foreground: oklch(0.985 0.005 290);
|
||||
--card: oklch(0.16 0.014 290);
|
||||
--card-foreground: oklch(0.985 0.005 290);
|
||||
--popover: oklch(0.16 0.014 290);
|
||||
--popover-foreground: oklch(0.985 0.005 290);
|
||||
--primary: oklch(0.985 0.005 290);
|
||||
--primary-foreground: oklch(0.2 0.012 290);
|
||||
--secondary: oklch(0.22 0.018 290);
|
||||
--secondary-foreground: oklch(0.985 0.005 290);
|
||||
--muted: oklch(0.22 0.018 290);
|
||||
--muted-foreground: oklch(0.65 0.02 290);
|
||||
--accent: oklch(0.22 0.018 290);
|
||||
--accent-foreground: oklch(0.985 0.005 290);
|
||||
--destructive: oklch(0.396 0.141 25.723);
|
||||
--destructive-foreground: oklch(0.637 0.237 25.331);
|
||||
--border: oklch(0.269 0 0);
|
||||
--input: oklch(0.269 0 0);
|
||||
--ring: oklch(0.439 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--border: oklch(0.26 0.02 290);
|
||||
--input: oklch(0.26 0.02 290);
|
||||
--ring: oklch(0.45 0.03 290);
|
||||
--chart-1: oklch(0.55 0.2 290);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(0.269 0 0);
|
||||
--sidebar-ring: oklch(0.439 0 0);
|
||||
--sidebar: oklch(0.18 0.016 290);
|
||||
--sidebar-foreground: oklch(0.985 0.005 290);
|
||||
--sidebar-primary: oklch(0.55 0.2 290);
|
||||
--sidebar-primary-foreground: oklch(0.985 0.005 290);
|
||||
--sidebar-accent: oklch(0.24 0.02 290);
|
||||
--sidebar-accent-foreground: oklch(0.985 0.005 290);
|
||||
--sidebar-border: oklch(0.26 0.02 290);
|
||||
--sidebar-ring: oklch(0.45 0.03 290);
|
||||
--navbar-background: #1e1b2e;
|
||||
--navbar-darker: #141121;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
|
|
@ -111,8 +119,8 @@
|
|||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-navbar-background: #292e39;
|
||||
--color-navbar-darker: #171920;
|
||||
--color-navbar-background: var(--navbar-background);
|
||||
--color-navbar-darker: var(--navbar-darker);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
|
|
@ -122,31 +130,43 @@
|
|||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
@media (display-mode: standalone) {
|
||||
body {
|
||||
padding-top: env(safe-area-inset-top);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
padding-left: env(safe-area-inset-left);
|
||||
padding-right: env(safe-area-inset-right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.str-chat {
|
||||
--str-chat__primary-color: #8b7396;
|
||||
--str-chat__active-primary-color: #6e5c7d;
|
||||
--str-chat__primary-color: #804eec;
|
||||
--str-chat__active-primary-color: #6f3fd4;
|
||||
--str-chat__surface-color: #f5f3f7;
|
||||
--str-chat__secondary-surface-color: #e8e4ec;
|
||||
--str-chat__primary-surface-color: #ebe7f0;
|
||||
--str-chat__primary-surface-color-low-emphasis: #f2f0f5;
|
||||
--str-chat__primary-surface-color: #f4f3ff;
|
||||
--str-chat__primary-surface-color-low-emphasis: #f8f7ff;
|
||||
--str-chat__border-radius-circle: 6px;
|
||||
--str-chat__own-message-bubble-color: #804eec;
|
||||
--str-chat__own-message-text-color: #ffffff;
|
||||
}
|
||||
|
||||
.dark .str-chat {
|
||||
--str-chat__primary-color: #a68bb5;
|
||||
--str-chat__active-primary-color: #8b7396;
|
||||
--str-chat__surface-color: rgba(120, 107, 130, 0.25);
|
||||
--str-chat__secondary-surface-color: rgba(140, 130, 150, 0.18);
|
||||
--str-chat__primary-surface-color: rgba(166, 139, 181, 0.12);
|
||||
--str-chat__primary-surface-color-low-emphasis: rgba(166, 139, 181, 0.06);
|
||||
--str-chat__background-color: rgba(110, 100, 120, 0.2);
|
||||
--str-chat__secondary-background-color: rgba(80, 72, 88, 0.35);
|
||||
--str-chat__border-color: rgba(120, 107, 130, 0.28);
|
||||
--str-chat__text-color: #f5f3f7;
|
||||
--str-chat__text-low-emphasis-color: #b8b0c0;
|
||||
--str-chat__disabled-color: rgba(155, 143, 165, 0.35);
|
||||
--str-chat__primary-color: #9b6ff0;
|
||||
--str-chat__active-primary-color: #804eec;
|
||||
--str-chat__surface-color: rgba(128, 78, 236, 0.12);
|
||||
--str-chat__secondary-surface-color: rgba(128, 78, 236, 0.08);
|
||||
--str-chat__primary-surface-color: rgba(128, 78, 236, 0.1);
|
||||
--str-chat__primary-surface-color-low-emphasis: rgba(128, 78, 236, 0.05);
|
||||
--str-chat__background-color: rgba(30, 27, 46, 0.6);
|
||||
--str-chat__secondary-background-color: rgba(20, 17, 33, 0.5);
|
||||
--str-chat__border-color: rgba(128, 78, 236, 0.15);
|
||||
--str-chat__text-color: #eeeaf5;
|
||||
--str-chat__text-low-emphasis-color: #a8a0b8;
|
||||
--str-chat__disabled-color: rgba(128, 78, 236, 0.2);
|
||||
--str-chat__own-message-bubble-color: #804eec;
|
||||
--str-chat__own-message-text-color: #ffffff;
|
||||
}
|
||||
|
||||
@keyframes gradient-x {
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import App from "./App";
|
|||
import { supabase } from "./lib/supabase";
|
||||
|
||||
import "@xtablo/ui/styles/globals.css";
|
||||
import "@xtablo/tablo-views/styles/tablo-details-shell.css";
|
||||
import "./main.css";
|
||||
import "./i18n";
|
||||
|
||||
|
|
|
|||
17
apps/clients/src/mainCss.test.ts
Normal file
17
apps/clients/src/mainCss.test.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const mainCss = readFileSync(resolve(process.cwd(), "src/main.css"), "utf8");
|
||||
|
||||
describe("clients main.css", () => {
|
||||
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;");
|
||||
expect(mainCss).toContain("--str-chat__own-message-text-color: #ffffff;");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { useSession } from "@xtablo/shared/contexts/SessionContext";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { Navigate, useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { useSession } from "@xtablo/shared/contexts/SessionContext";
|
||||
|
||||
export function AuthCallback() {
|
||||
const [searchParams] = useSearchParams();
|
||||
|
|
@ -11,7 +11,11 @@ export function AuthCallback() {
|
|||
const hasAccepted = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!session || !token || hasAccepted.current) {
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session || hasAccepted.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -41,11 +45,15 @@ export function AuthCallback() {
|
|||
.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é."
|
||||
"Une erreur est survenue lors de l'acceptation de l'invitation. Veuillez contacter la personne qui vous a invite."
|
||||
);
|
||||
});
|
||||
}, [session, token, navigate]);
|
||||
|
||||
if (!token) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
|
|
|
|||
599
apps/clients/src/pages/ClientTabloPage.test.tsx
Normal file
599
apps/clients/src/pages/ClientTabloPage.test.tsx
Normal file
|
|
@ -0,0 +1,599 @@
|
|||
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, queryFn }: { queryKey: string[]; queryFn?: () => Promise<unknown> }) => {
|
||||
if (queryKey[0] === "client-tablo-folders" && queryFn) {
|
||||
void queryFn();
|
||||
}
|
||||
switch (queryKey[0]) {
|
||||
case "client-tablo":
|
||||
return {
|
||||
data: {
|
||||
id: "tablo-1",
|
||||
name: "Client Project",
|
||||
color: "bg-blue-500",
|
||||
image: null,
|
||||
created_at: "2026-01-01T00:00:00.000Z",
|
||||
deleted_at: null,
|
||||
position: 0,
|
||||
status: "todo",
|
||||
user_id: "user-1",
|
||||
is_admin: false,
|
||||
access_level: "guest",
|
||||
},
|
||||
isLoading: false,
|
||||
};
|
||||
case "client-tasks":
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
id: "task-1",
|
||||
title: "Prepare proposal",
|
||||
status: "todo",
|
||||
tablo_id: "tablo-1",
|
||||
assignee_id: "client-user-1",
|
||||
},
|
||||
],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
case "client-etapes":
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
id: "etape-1",
|
||||
title: "Kickoff",
|
||||
status: "in_progress",
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
case "client-events":
|
||||
case "client-members":
|
||||
case "client-tablo-folders":
|
||||
return {
|
||||
data: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
case "client-tablo-files":
|
||||
return {
|
||||
data: { fileNames: [] },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
default:
|
||||
return {
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@xtablo/tablo-views", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@xtablo/tablo-views")>();
|
||||
|
||||
return {
|
||||
...actual,
|
||||
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: (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",
|
||||
path: "/tablo/:tabloId",
|
||||
});
|
||||
|
||||
expect(screen.getByText("Client Project")).toBeInTheDocument();
|
||||
expect(screen.getAllByRole("button", { name: "Discussion" })).toHaveLength(2);
|
||||
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", () => {
|
||||
renderWithProviders(<ClientTabloPage />, {
|
||||
route: "/tablo/tablo-1",
|
||||
path: "/tablo/:tabloId",
|
||||
});
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Inviter" })).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", () => {
|
||||
renderWithProviders(<ClientTabloPage />, {
|
||||
route: "/tablo/tablo-1",
|
||||
path: "/tablo/:tabloId",
|
||||
});
|
||||
|
||||
expect(screen.getByText("Description du projet")).toBeInTheDocument();
|
||||
expect(screen.getByText("Mes tâches")).toBeInTheDocument();
|
||||
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");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,23 +1,25 @@
|
|||
import { useQuery } from "@tanstack/react-query";
|
||||
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 type {
|
||||
Etape,
|
||||
KanbanTask,
|
||||
KanbanTaskUpdate,
|
||||
TabloFolder,
|
||||
TaskStatus,
|
||||
UserTablo,
|
||||
} from "@xtablo/shared-types";
|
||||
import {
|
||||
EtapesSection,
|
||||
RoadmapSection,
|
||||
type SingleTabloTabId,
|
||||
SingleTabloView,
|
||||
TabloDiscussionSection,
|
||||
TabloEventsSection,
|
||||
TabloFilesSection,
|
||||
TabloTasksSection,
|
||||
} from "@xtablo/tablo-views";
|
||||
import {
|
||||
CalendarIcon,
|
||||
FolderIcon,
|
||||
KanbanIcon,
|
||||
ListChecksIcon,
|
||||
MapIcon,
|
||||
MessageCircleIcon,
|
||||
} from "lucide-react";
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { supabase } from "../lib/supabase";
|
||||
|
|
@ -138,7 +140,7 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined)
|
|||
queryKey: ["client-tablo-folders", tabloId],
|
||||
queryFn: async () => {
|
||||
const { data } = await api.get<{ folders: TabloFolder[] }>(
|
||||
`/api/v1/tablo-folders/${tabloId}`
|
||||
`/api/v1/tablo-data/${tabloId}/folders`
|
||||
);
|
||||
return data.folders ?? [];
|
||||
},
|
||||
|
|
@ -146,26 +148,308 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined)
|
|||
});
|
||||
}
|
||||
|
||||
// ─── Tabs ─────────────────────────────────────────────────────────────────────
|
||||
const invalidateClientFileQueries = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
tabloId: string
|
||||
) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["client-tablo-files", tabloId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["client-tablo-folders", tabloId] });
|
||||
};
|
||||
|
||||
type TabId = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap";
|
||||
function useClientCreateFile(tabloId: string, accessToken: string | undefined) {
|
||||
const api = useAuthedApi(accessToken);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [
|
||||
{ id: "overview", label: "Aperçu", icon: ListChecksIcon },
|
||||
{ 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 },
|
||||
];
|
||||
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 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) {
|
||||
switch (status) {
|
||||
case "in_progress":
|
||||
return {
|
||||
label: "En cours",
|
||||
badgeClass:
|
||||
"bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800",
|
||||
};
|
||||
case "done":
|
||||
return {
|
||||
label: "Terminé",
|
||||
badgeClass:
|
||||
"bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
label: "À faire",
|
||||
badgeClass:
|
||||
"bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function getEtapeProgressStats(etapes: Etape[]) {
|
||||
const total = etapes.length;
|
||||
const done = etapes.filter((etape) => etape.status === "done").length;
|
||||
const started = etapes.filter((etape) =>
|
||||
new Set(["in_progress", "in_review", "done"]).has(etape.status ?? "todo")
|
||||
).length;
|
||||
|
||||
if (total === 0) {
|
||||
return {
|
||||
startedPercentage: 0,
|
||||
donePercentage: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
startedPercentage: Math.round((started / total) * 100),
|
||||
donePercentage: Math.round((done / total) * 100),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function ClientTabloPage() {
|
||||
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 ?? "";
|
||||
|
|
@ -189,6 +473,15 @@ export function ClientTabloPage() {
|
|||
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("."));
|
||||
|
||||
|
|
@ -210,118 +503,214 @@ export function ClientTabloPage() {
|
|||
);
|
||||
}
|
||||
|
||||
const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status);
|
||||
const progress = getEtapeProgressStats(etapes);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Tablo header */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">{tablo.name}</h1>
|
||||
</div>
|
||||
<SingleTabloView
|
||||
tablo={tablo}
|
||||
roleLabel="Invité"
|
||||
statusLabel={statusLabel}
|
||||
statusBadgeClass={badgeClass}
|
||||
progress={progress}
|
||||
activeTab={activeTab}
|
||||
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>
|
||||
|
||||
{/* Tab bar */}
|
||||
<div className="border-b border-border">
|
||||
<nav className="flex gap-1 overflow-x-auto">
|
||||
{TABS.map((tab) => {
|
||||
const Icon = tab.icon;
|
||||
return (
|
||||
<button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 whitespace-nowrap transition-colors ${
|
||||
activeTab === tab.id
|
||||
? "border-primary text-primary"
|
||||
: "border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
{tab.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Tab content */}
|
||||
<div>
|
||||
{activeTab === "overview" && (
|
||||
<div className="space-y-6">
|
||||
{/* Simple overview: list etapes with progress */}
|
||||
<EtapesSection
|
||||
etapes={etapes}
|
||||
tabloTasks={tasks}
|
||||
tabloId={tablo.id}
|
||||
isAdmin={false}
|
||||
onCreateTask={() => {}}
|
||||
onCreateEtape={async () => {}}
|
||||
/>
|
||||
<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) => (
|
||||
<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={() => {}} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
66
apps/clients/src/pages/LoginPage.test.tsx
Normal file
66
apps/clients/src/pages/LoginPage.test.tsx
Normal 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");
|
||||
});
|
||||
});
|
||||
});
|
||||
102
apps/clients/src/pages/LoginPage.tsx
Normal file
102
apps/clients/src/pages/LoginPage.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
42
apps/clients/src/pages/ResetPasswordPage.test.tsx
Normal file
42
apps/clients/src/pages/ResetPasswordPage.test.tsx
Normal 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();
|
||||
});
|
||||
});
|
||||
});
|
||||
74
apps/clients/src/pages/ResetPasswordPage.tsx
Normal file
74
apps/clients/src/pages/ResetPasswordPage.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
94
apps/clients/src/pages/SetPasswordPage.test.tsx
Normal file
94
apps/clients/src/pages/SetPasswordPage.test.tsx
Normal 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");
|
||||
});
|
||||
});
|
||||
});
|
||||
205
apps/clients/src/pages/SetPasswordPage.tsx
Normal file
205
apps/clients/src/pages/SetPasswordPage.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
|
|
|
|||
41
apps/clients/src/setupTests.ts
Normal file
41
apps/clients/src/setupTests.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import "@testing-library/jest-dom";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach, vi } from "vitest";
|
||||
import "./i18n.test";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
global.ResizeObserver = class ResizeObserver {
|
||||
observe() {
|
||||
return undefined;
|
||||
}
|
||||
unobserve() {
|
||||
return undefined;
|
||||
}
|
||||
disconnect() {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof Element !== "undefined") {
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
Element.prototype.scrollTo = vi.fn();
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
11
apps/clients/src/test/testHelpers.test.tsx
Normal file
11
apps/clients/src/test/testHelpers.test.tsx
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderWithProviders } from "./testHelpers";
|
||||
|
||||
describe("client test harness", () => {
|
||||
it("renders a smoke test placeholder", () => {
|
||||
renderWithProviders(<div>client test harness</div>);
|
||||
|
||||
expect(screen.getByText("client test harness")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
69
apps/clients/src/test/testHelpers.tsx
Normal file
69
apps/clients/src/test/testHelpers.tsx
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
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";
|
||||
import React from "react";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import testI18n from "../i18n.test";
|
||||
|
||||
const defaultUser = {
|
||||
id: "client-user-1",
|
||||
app_metadata: {},
|
||||
aud: "test",
|
||||
created_at: "2021-01-01",
|
||||
email: "client@example.com",
|
||||
user_metadata: {
|
||||
full_name: "Client User",
|
||||
},
|
||||
};
|
||||
|
||||
interface RenderWithProvidersOptions {
|
||||
route?: string;
|
||||
path?: string;
|
||||
language?: string;
|
||||
testUser?: typeof defaultUser | undefined;
|
||||
}
|
||||
|
||||
export const renderWithProviders = (
|
||||
ui: React.ReactNode,
|
||||
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({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
staleTime: Infinity,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const content = path ? (
|
||||
<Routes>
|
||||
<Route path={path} element={ui} />
|
||||
</Routes>
|
||||
) : (
|
||||
ui
|
||||
);
|
||||
|
||||
return {
|
||||
user: userEvent.setup(),
|
||||
...render(
|
||||
<I18nextProvider i18n={testI18n}>
|
||||
<MemoryRouter initialEntries={[route]}>
|
||||
<ThemeProvider>
|
||||
<QueryClientProvider client={testQueryClient}>
|
||||
<SessionTestProvider testUser={testUser}>{content}</SessionTestProvider>
|
||||
</QueryClientProvider>
|
||||
</ThemeProvider>
|
||||
</MemoryRouter>
|
||||
</I18nextProvider>
|
||||
),
|
||||
};
|
||||
};
|
||||
9
apps/clients/src/vite-env.d.ts
vendored
Normal file
9
apps/clients/src/vite-env.d.ts
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_VERSION: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
18
apps/clients/src/viteConfig.test.ts
Normal file
18
apps/clients/src/viteConfig.test.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import configFactory from "../vite.config";
|
||||
|
||||
describe("clients vite config", () => {
|
||||
it("uses hidden sourcemaps for production builds", () => {
|
||||
const config = configFactory({
|
||||
mode: "production",
|
||||
command: "build",
|
||||
isSsrBuild: false,
|
||||
isPreview: false,
|
||||
});
|
||||
|
||||
expect(config.build?.sourcemap).toBe("hidden");
|
||||
});
|
||||
});
|
||||
|
|
@ -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"],
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"root":["./src/app.tsx","./src/i18n.ts","./src/main.tsx","./src/routes.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.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/vite-env.d.ts","./src/viteconfig.test.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"}
|
||||
|
|
@ -17,6 +17,20 @@ export default defineConfig(({ mode }) => {
|
|||
|
||||
return {
|
||||
plugins,
|
||||
build: {
|
||||
sourcemap: mode === "test" ? false : "hidden",
|
||||
},
|
||||
server: { cors: false },
|
||||
define: process.env.VITEST
|
||||
? {
|
||||
"import.meta.env.VITE_SUPABASE_URL": JSON.stringify("https://test.supabase.co"),
|
||||
"import.meta.env.VITE_SUPABASE_ANON_KEY": JSON.stringify("test-anon-key"),
|
||||
}
|
||||
: undefined,
|
||||
test: {
|
||||
globals: true,
|
||||
environment: "jsdom",
|
||||
setupFiles: "./src/setupTests.ts",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
name = "xtablo-clients"
|
||||
main = "worker/index.ts"
|
||||
compatibility_date = "2025-07-09"
|
||||
route = { pattern = "clients.xtablo.com", custom_domain = true }
|
||||
|
||||
[assets]
|
||||
directory = "./dist/"
|
||||
|
|
@ -8,10 +9,3 @@ not_found_handling = "single-page-application"
|
|||
|
||||
[observability]
|
||||
enabled = true
|
||||
|
||||
[[routes]]
|
||||
pattern = "clients.xtablo.com"
|
||||
custom_domain = true
|
||||
|
||||
[secrets]
|
||||
required = [ "ADMIN_APP_ACCESS_TOKEN" ]
|
||||
|
|
|
|||
1
apps/external/package.json
vendored
1
apps/external/package.json
vendored
|
|
@ -27,6 +27,7 @@
|
|||
"typescript": "^5.7.0",
|
||||
"vite": "^6.2.2",
|
||||
"vite-tsconfig-paths": "^5.1.4",
|
||||
"vitest": "^3.2.4",
|
||||
"wrangler": "^4.24.3"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
|
|||
1
apps/external/src/setupTests.ts
vendored
Normal file
1
apps/external/src/setupTests.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
// Intentionally minimal test setup so Vitest can honor the configured setupFiles path.
|
||||
8
apps/external/src/vite-env.d.ts
vendored
8
apps/external/src/vite-env.d.ts
vendored
|
|
@ -1 +1,9 @@
|
|||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_VERSION: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
|
|
|
|||
18
apps/external/src/viteConfig.test.ts
vendored
Normal file
18
apps/external/src/viteConfig.test.ts
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import configFactory from "../vite.config";
|
||||
|
||||
describe("external vite config", () => {
|
||||
it("uses hidden sourcemaps for production builds", () => {
|
||||
const config = configFactory({
|
||||
mode: "production",
|
||||
command: "build",
|
||||
isSsrBuild: false,
|
||||
isPreview: false,
|
||||
});
|
||||
|
||||
expect(config.build?.sourcemap).toBe("hidden");
|
||||
});
|
||||
});
|
||||
7
apps/external/vite.config.ts
vendored
7
apps/external/vite.config.ts
vendored
|
|
@ -3,13 +3,9 @@
|
|||
import { cloudflare } from "@cloudflare/vite-plugin";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { defineConfig, PluginOption } from "vite";
|
||||
import tsconfigPaths from "vite-tsconfig-paths";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig(({ mode }) => {
|
||||
const plugins: PluginOption[] = [
|
||||
|
|
@ -26,6 +22,9 @@ export default defineConfig(({ mode }) => {
|
|||
|
||||
return {
|
||||
plugins,
|
||||
build: {
|
||||
sourcemap: mode === "test" ? false : "hidden",
|
||||
},
|
||||
server: {
|
||||
cors: false,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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:*",
|
||||
|
|
|
|||
67
apps/main/src/components/AuthenticationGateway.test.tsx
Normal file
67
apps/main/src/components/AuthenticationGateway.test.tsx
Normal 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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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 />;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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}>
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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 />;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import i18n from "i18next";
|
|||
import { initReactI18next } from "react-i18next";
|
||||
import authEn from "./locales/en/auth.json";
|
||||
import availabilitiesEn from "./locales/en/availabilities.json";
|
||||
import chatEn from "./locales/en/chat.json";
|
||||
import commonEn from "./locales/en/common.json";
|
||||
import componentsEn from "./locales/en/components.json";
|
||||
import modalsEn from "./locales/en/modals.json";
|
||||
|
|
@ -13,6 +14,7 @@ import settingsEn from "./locales/en/settings.json";
|
|||
import tabloEn from "./locales/en/tablo.json";
|
||||
import authFr from "./locales/fr/auth.json";
|
||||
import availabilitiesFr from "./locales/fr/availabilities.json";
|
||||
import chatFr from "./locales/fr/chat.json";
|
||||
import commonFr from "./locales/fr/common.json";
|
||||
import componentsFr from "./locales/fr/components.json";
|
||||
import modalsFr from "./locales/fr/modals.json";
|
||||
|
|
@ -31,6 +33,7 @@ i18n.use(initReactI18next).init({
|
|||
pages: pagesFr,
|
||||
settings: settingsFr,
|
||||
availabilities: availabilitiesFr,
|
||||
chat: chatFr,
|
||||
auth: authFr,
|
||||
planning: planningFr,
|
||||
modals: modalsFr,
|
||||
|
|
@ -44,6 +47,7 @@ i18n.use(initReactI18next).init({
|
|||
pages: pagesEn,
|
||||
settings: settingsEn,
|
||||
availabilities: availabilitiesEn,
|
||||
chat: chatEn,
|
||||
auth: authEn,
|
||||
planning: planningEn,
|
||||
modals: modalsEn,
|
||||
|
|
|
|||
24
apps/main/src/lib/clientPortal.ts
Normal file
24
apps/main/src/lib/clientPortal.ts
Normal 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));
|
||||
}
|
||||
35
apps/main/src/lib/rum.test.ts
Normal file
35
apps/main/src/lib/rum.test.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const init = vi.fn();
|
||||
|
||||
vi.mock("@datadog/browser-rum", () => ({
|
||||
datadogRum: {
|
||||
init,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@datadog/browser-rum-react", () => ({
|
||||
reactPlugin: () => "react-plugin",
|
||||
}));
|
||||
|
||||
describe("rum config", () => {
|
||||
beforeEach(() => {
|
||||
init.mockReset();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("sets the Datadog release version from VITE_APP_VERSION", async () => {
|
||||
vi.stubEnv("VITE_APP_VERSION", "test-sha");
|
||||
vi.stubEnv("MODE", "production");
|
||||
|
||||
await import("./rum");
|
||||
|
||||
expect(init).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
service: "xtablo-ui",
|
||||
env: "production",
|
||||
version: "test-sha",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -13,9 +13,8 @@ datadogRum.init({
|
|||
site: "datadoghq.com",
|
||||
service: "xtablo-ui",
|
||||
env: import.meta.env.MODE,
|
||||
version: import.meta.env.VITE_APP_VERSION,
|
||||
|
||||
// Specify a version number to identify the deployed version of your application in Datadog
|
||||
// version: '1.0.0',
|
||||
sessionSampleRate: 100,
|
||||
sessionReplaySampleRate: 80,
|
||||
defaultPrivacyLevel: "mask-user-input",
|
||||
|
|
|
|||
|
|
@ -27,6 +27,12 @@
|
|||
"admin": "Admin",
|
||||
"guest": "Guest"
|
||||
},
|
||||
"details": {
|
||||
"roleLabel": "Role:",
|
||||
"createdAtLabel": "Created on:",
|
||||
"statusLabel": "Status:",
|
||||
"progressLabel": "Progress:"
|
||||
},
|
||||
"status": {
|
||||
"todo": "To Do",
|
||||
"inProgress": "In Progress",
|
||||
|
|
|
|||
|
|
@ -27,6 +27,12 @@
|
|||
"admin": "Admin",
|
||||
"guest": "Invité"
|
||||
},
|
||||
"details": {
|
||||
"roleLabel": "Rôle :",
|
||||
"createdAtLabel": "Créé le :",
|
||||
"statusLabel": "Statut :",
|
||||
"progressLabel": "Progression :"
|
||||
},
|
||||
"status": {
|
||||
"todo": "À faire",
|
||||
"inProgress": "En cours",
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
145
apps/main/src/pages/planning.test.tsx
Normal file
145
apps/main/src/pages/planning.test.tsx
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext";
|
||||
import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router-dom";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import testI18n from "../i18n.test";
|
||||
import { TestUserStoreProvider, type User } from "../providers/UserStoreProvider";
|
||||
import { PlanningPage } from "./planning";
|
||||
|
||||
vi.mock("../hooks/events", () => ({
|
||||
useDeleteEvent: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useEventsByTablo: () => ({
|
||||
data: [
|
||||
{
|
||||
event_id: "event-1",
|
||||
tablo_id: "tablo-1",
|
||||
tablo_name: "Tablo Alpha",
|
||||
tablo_color: "bg-blue-500",
|
||||
start_date: "2026-04-22",
|
||||
start_time: "09:00:00",
|
||||
end_time: "10:00:00",
|
||||
title: "Kickoff",
|
||||
description: "Planning event",
|
||||
},
|
||||
],
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/tablos", () => ({
|
||||
useGetAllTabloAccess: () => ({
|
||||
data: [{ tablo_id: "tablo-1", is_admin: true }],
|
||||
}),
|
||||
useTablosList: () => ({
|
||||
data: [{ id: "tablo-1", name: "Tablo Alpha" }],
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../providers/UserStoreProvider", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../providers/UserStoreProvider")>();
|
||||
return {
|
||||
...actual,
|
||||
useIsReadOnlyUser: () => false,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../components/EventModal", () => ({
|
||||
EventModal: () => <div data-testid="event-modal" />,
|
||||
}));
|
||||
|
||||
const testUser: User = {
|
||||
id: "user-1",
|
||||
short_user_id: "u1",
|
||||
name: "John Doe",
|
||||
first_name: "John",
|
||||
last_name: "Doe",
|
||||
email: "john@example.com",
|
||||
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(),
|
||||
};
|
||||
|
||||
const createTestRouter = (initialEntry: string) =>
|
||||
createMemoryRouter(
|
||||
[
|
||||
{
|
||||
path: "/planning",
|
||||
element: <PlanningPage />,
|
||||
},
|
||||
{
|
||||
path: "/tasks",
|
||||
element: <div>Tasks page</div>,
|
||||
},
|
||||
],
|
||||
{ initialEntries: [initialEntry] }
|
||||
);
|
||||
|
||||
const renderPlanningRouter = (initialEntry: string) => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
staleTime: Infinity,
|
||||
},
|
||||
},
|
||||
});
|
||||
const router = createTestRouter(initialEntry);
|
||||
|
||||
return {
|
||||
router,
|
||||
...render(
|
||||
<I18nextProvider i18n={testI18n}>
|
||||
<ThemeProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SessionTestProvider
|
||||
testUser={{
|
||||
id: testUser.id,
|
||||
app_metadata: {},
|
||||
aud: "test",
|
||||
created_at: "2021-01-01",
|
||||
user_metadata: {
|
||||
first_name: testUser.first_name,
|
||||
last_name: testUser.last_name,
|
||||
avatar_url: testUser.avatar_url,
|
||||
full_name: testUser.name,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<TestUserStoreProvider user={testUser}>
|
||||
<RouterProvider router={router} />
|
||||
</TestUserStoreProvider>
|
||||
</SessionTestProvider>
|
||||
</QueryClientProvider>
|
||||
</ThemeProvider>
|
||||
</I18nextProvider>
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
describe("PlanningPage", () => {
|
||||
beforeEach(() => {
|
||||
testI18n.changeLanguage("fr");
|
||||
});
|
||||
|
||||
it("does not throw when leaving the planning page from the events tab", async () => {
|
||||
const { router } = renderPlanningRouter("/planning?tab=events");
|
||||
|
||||
expect(screen.getByText("Événements")).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
await expect(router.navigate("/tasks")).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Tasks page")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1055,254 +1055,262 @@ export const PlanningPage = () => {
|
|||
);
|
||||
};
|
||||
|
||||
if (currentTab === "events") {
|
||||
return (
|
||||
<div className="min-h-screen bg-background px-4">
|
||||
{renderEventsView()}
|
||||
<EventModal
|
||||
mode="create"
|
||||
isOpen={isCreateEventOpen}
|
||||
onClose={() => setIsCreateEventOpen(false)}
|
||||
defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined}
|
||||
defaultDate={currentDate}
|
||||
/>
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="flex">
|
||||
{/* Sidebar */}
|
||||
<div className="w-64 bg-card border-r border-border min-h-screen">
|
||||
<div className="p-4">
|
||||
{/* Tablo Selector */}
|
||||
<div className="mb-4">
|
||||
<Select
|
||||
value={selectedTabloId}
|
||||
onValueChange={(value) => setSelectedTabloId(value)}
|
||||
disabled={tablosLoading}
|
||||
{currentTab === "events" ? (
|
||||
<div className="px-4">{renderEventsView()}</div>
|
||||
) : (
|
||||
<div className="flex">
|
||||
{/* Sidebar */}
|
||||
<div className="w-64 bg-card border-r border-border min-h-screen">
|
||||
<div className="p-4">
|
||||
{/* Tablo Selector */}
|
||||
<div className="mb-4">
|
||||
<Select
|
||||
value={selectedTabloId}
|
||||
onValueChange={(value) => setSelectedTabloId(value)}
|
||||
disabled={tablosLoading}
|
||||
>
|
||||
<SelectTrigger className="w-full" aria-label={t("planning:selectTablo")}>
|
||||
<SelectValue
|
||||
placeholder={
|
||||
tablosLoading ? t("common:actions.loading") : t("planning:selectTablo")
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("planning:allTablos")}</SelectItem>
|
||||
{tablos?.map((tablo) => (
|
||||
<SelectItem key={tablo.id} value={tablo.id}>
|
||||
{tablo.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (isReadOnly) {
|
||||
toast.add(
|
||||
{
|
||||
title: t("common:error"),
|
||||
description:
|
||||
"Vous êtes en mode lecture seule. Vous ne pouvez pas créer d'événement.",
|
||||
type: "error",
|
||||
},
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (selectedTabloId === "all") {
|
||||
navigate(`/planning/create?date=${currentDate.toISOString()}`);
|
||||
} else {
|
||||
navigate(
|
||||
`/planning/create?tablo_id=${selectedTabloId}&date=${currentDate.toISOString()}`
|
||||
);
|
||||
}
|
||||
}}
|
||||
className="w-full bg-[#804EEC] hover:bg-[#6f3fd4] text-white"
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<SelectTrigger className="w-full" aria-label={t("planning:selectTablo")}>
|
||||
<SelectValue
|
||||
placeholder={
|
||||
tablosLoading ? t("common:actions.loading") : t("planning:selectTablo")
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("planning:allTablos")}</SelectItem>
|
||||
{tablos?.map((tablo) => (
|
||||
<SelectItem key={tablo.id} value={tablo.id}>
|
||||
{tablo.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<PlusIcon className="w-5 h-5 mr-2" />
|
||||
{t("planning:createEvent")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (isReadOnly) {
|
||||
toast.add(
|
||||
{
|
||||
title: t("common:error"),
|
||||
description:
|
||||
"Vous êtes en mode lecture seule. Vous ne pouvez pas importer de calendrier.",
|
||||
type: "error",
|
||||
},
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
return;
|
||||
}
|
||||
setIsImportModalOpen(true);
|
||||
}}
|
||||
variant="secondary"
|
||||
className="w-full mt-2"
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<FolderInputIcon className="w-5 h-5 mr-2" />
|
||||
{t("planning:importPlanning")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handleExportICS}
|
||||
disabled={!tabloEvents || tabloEvents.length === 0}
|
||||
variant="outline"
|
||||
className="w-full mt-2"
|
||||
title={t("planning:exportICS")}
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
{t("planning:export")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (isReadOnly) {
|
||||
toast.add(
|
||||
{
|
||||
title: t("common:error"),
|
||||
description:
|
||||
"Vous êtes en mode lecture seule. Vous ne pouvez pas créer d'événement.",
|
||||
type: "error",
|
||||
},
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (selectedTabloId === "all") {
|
||||
navigate(`/planning/create?date=${currentDate.toISOString()}`);
|
||||
} else {
|
||||
navigate(
|
||||
`/planning/create?tablo_id=${selectedTabloId}&date=${currentDate.toISOString()}`
|
||||
);
|
||||
}
|
||||
}}
|
||||
className="w-full bg-[#804EEC] hover:bg-[#6f3fd4] text-white"
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<PlusIcon className="w-5 h-5 mr-2" />
|
||||
{t("planning:createEvent")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (isReadOnly) {
|
||||
toast.add(
|
||||
{
|
||||
title: t("common:error"),
|
||||
description:
|
||||
"Vous êtes en mode lecture seule. Vous ne pouvez pas importer de calendrier.",
|
||||
type: "error",
|
||||
},
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
return;
|
||||
}
|
||||
setIsImportModalOpen(true);
|
||||
}}
|
||||
variant="secondary"
|
||||
className="w-full mt-2"
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<FolderInputIcon className="w-5 h-5 mr-2" />
|
||||
{t("planning:importPlanning")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handleExportICS}
|
||||
disabled={!tabloEvents || tabloEvents.length === 0}
|
||||
variant="outline"
|
||||
className="w-full mt-2"
|
||||
title={t("planning:exportICS")}
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
{t("planning:export")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Mini Calendar */}
|
||||
<div className="p-4 border-t border-border">
|
||||
<div className="text-sm font-medium text-foreground mb-3">
|
||||
{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
|
||||
</div>
|
||||
<div className="grid grid-cols-7 gap-1 text-xs">
|
||||
{dayNamesShort.map((day) => (
|
||||
<div key={day} className="text-center text-muted-foreground p-1">
|
||||
{day.slice(0, 1)}
|
||||
</div>
|
||||
))}
|
||||
{getDaysInMonth(currentDate).map((day, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`text-center p-1 cursor-pointer rounded ${
|
||||
day ? "hover:bg-muted" : ""
|
||||
} ${
|
||||
day && formatDate(day) === formatDate(new Date())
|
||||
? "bg-[#804EEC] text-white"
|
||||
: day
|
||||
? "text-foreground"
|
||||
: ""
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (day) {
|
||||
navigateToCreateEvent(day, selectedTabloId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{day ? day.getDate() : ""}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="flex-1 flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="bg-card border-b border-border p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
<TypographyH3>{t("planning:title")}</TypographyH3>
|
||||
<Button
|
||||
onClick={goToToday}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="border-[#804EEC] text-[#804EEC] hover:bg-[#804EEC]/10"
|
||||
>
|
||||
{t("planning:today")}
|
||||
</Button>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button onClick={() => navigateDate(-1)} className="p-2 hover:bg-muted rounded">
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M15 19l-7-7 7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<button onClick={() => navigateDate(1)} className="p-2 hover:bg-muted rounded">
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M9 5l7 7-7 7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<TypographyH4>{getViewTitle()}</TypographyH4>
|
||||
{/* Mini Calendar */}
|
||||
<div className="p-4 border-t border-border">
|
||||
<div className="text-sm font-medium text-foreground mb-3">
|
||||
{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
|
||||
</div>
|
||||
<div className="grid grid-cols-7 gap-1 text-xs">
|
||||
{dayNamesShort.map((day) => (
|
||||
<div key={day} className="text-center text-muted-foreground p-1">
|
||||
{day.slice(0, 1)}
|
||||
</div>
|
||||
))}
|
||||
{getDaysInMonth(currentDate).map((day, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`text-center p-1 cursor-pointer rounded ${
|
||||
day ? "hover:bg-muted" : ""
|
||||
} ${
|
||||
day && formatDate(day) === formatDate(new Date())
|
||||
? "bg-[#804EEC] text-white"
|
||||
: day
|
||||
? "text-foreground"
|
||||
: ""
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (day) {
|
||||
navigateToCreateEvent(day, selectedTabloId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{day ? day.getDate() : ""}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
onClick={() => setIsWebcalModalOpen(true)}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
title={t("planning:syncCalendar")}
|
||||
>
|
||||
<RefreshCcw className="w-4 h-4 mr-1" />
|
||||
{t("planning:sync")}
|
||||
</Button>
|
||||
<div className="flex bg-muted rounded-lg p-1">
|
||||
{(["month", "week", "day"] as ViewType[]).map((view) => (
|
||||
<button
|
||||
key={view}
|
||||
onClick={() => changeView(view)}
|
||||
title={t(`planning:views.${view}Title`)}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors capitalize ${
|
||||
currentView === view
|
||||
? "bg-white dark:bg-gray-800 text-[#804EEC] shadow-sm font-semibold"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{t(`planning:views.${view}`)}
|
||||
<span className="ml-1 text-xs opacity-60">
|
||||
{t(`planning:views.${view}Short`)}
|
||||
</span>
|
||||
{/* Main Content */}
|
||||
<div className="flex-1 flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="bg-card border-b border-border p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
<TypographyH3>{t("planning:title")}</TypographyH3>
|
||||
<Button
|
||||
onClick={goToToday}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="border-[#804EEC] text-[#804EEC] hover:bg-[#804EEC]/10"
|
||||
>
|
||||
{t("planning:today")}
|
||||
</Button>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button onClick={() => navigateDate(-1)} className="p-2 hover:bg-muted rounded">
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M15 19l-7-7 7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
))}
|
||||
<button onClick={() => navigateDate(1)} className="p-2 hover:bg-muted rounded">
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M9 5l7 7-7 7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<TypographyH4>{getViewTitle()}</TypographyH4>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
onClick={() => setIsWebcalModalOpen(true)}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
title={t("planning:syncCalendar")}
|
||||
>
|
||||
<RefreshCcw className="w-4 h-4 mr-1" />
|
||||
{t("planning:sync")}
|
||||
</Button>
|
||||
<div className="flex bg-muted rounded-lg p-1">
|
||||
{(["month", "week", "day"] as ViewType[]).map((view) => (
|
||||
<button
|
||||
key={view}
|
||||
onClick={() => changeView(view)}
|
||||
title={t(`planning:views.${view}Title`)}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors capitalize ${
|
||||
currentView === view
|
||||
? "bg-white dark:bg-gray-800 text-[#804EEC] shadow-sm font-semibold"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{t(`planning:views.${view}`)}
|
||||
<span className="ml-1 text-xs opacity-60">
|
||||
{t(`planning:views.${view}Short`)}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Calendar Views */}
|
||||
<div className="flex-1 p-4">
|
||||
{tabloEventsLoading ? (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<img
|
||||
src="/icon.jpg"
|
||||
alt="Loading..."
|
||||
className="animate-spin rounded-full h-8 w-8 object-cover"
|
||||
/>
|
||||
<span className="ml-2 text-muted-foreground">{t("planning:loadingEvents")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{currentView === "month" && renderMonthView()}
|
||||
{currentView === "week" && renderWeekView()}
|
||||
{currentView === "day" && renderDayView()}
|
||||
</>
|
||||
)}
|
||||
{/* Calendar Views */}
|
||||
<div className="flex-1 p-4">
|
||||
{tabloEventsLoading ? (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<img
|
||||
src="/icon.jpg"
|
||||
alt="Loading..."
|
||||
className="animate-spin rounded-full h-8 w-8 object-cover"
|
||||
/>
|
||||
<span className="ml-2 text-muted-foreground">{t("planning:loadingEvents")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{currentView === "month" && renderMonthView()}
|
||||
{currentView === "week" && renderWeekView()}
|
||||
{currentView === "day" && renderDayView()}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<EventModal
|
||||
mode="create"
|
||||
isOpen={isCreateEventOpen}
|
||||
onClose={() => setIsCreateEventOpen(false)}
|
||||
defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined}
|
||||
defaultDate={currentDate}
|
||||
/>
|
||||
|
||||
<Outlet />
|
||||
|
||||
{isImportModalOpen && <ImportICSModal onClose={() => setIsImportModalOpen(false)} />}
|
||||
|
||||
<WebcalModal open={isWebcalModalOpen} onOpenChange={setIsWebcalModalOpen} />
|
||||
{isWebcalModalOpen && (
|
||||
<WebcalModal open={isWebcalModalOpen} onOpenChange={setIsWebcalModalOpen} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,28 @@
|
|||
import { screen } from "@testing-library/react";
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "../utils/testHelpers";
|
||||
import { TabloDetailsPage } from "./tablo-details";
|
||||
|
||||
if (!HTMLElement.prototype.hasPointerCapture) {
|
||||
HTMLElement.prototype.hasPointerCapture = () => false;
|
||||
}
|
||||
|
||||
if (!HTMLElement.prototype.setPointerCapture) {
|
||||
HTMLElement.prototype.setPointerCapture = () => undefined;
|
||||
}
|
||||
|
||||
if (!HTMLElement.prototype.releasePointerCapture) {
|
||||
HTMLElement.prototype.releasePointerCapture = () => undefined;
|
||||
}
|
||||
|
||||
const mutateUpdateTablo = vi.fn();
|
||||
const mutateUpdateTask = vi.fn();
|
||||
const mutateCreateTask = vi.fn();
|
||||
const mutateCreateEtape = vi.fn();
|
||||
const mutateUpdateEtape = vi.fn();
|
||||
const mutateDeleteEtape = vi.fn();
|
||||
const mutateDeleteTask = vi.fn();
|
||||
|
||||
const tablosData = [
|
||||
{
|
||||
|
|
@ -42,7 +60,15 @@ vi.mock("../hooks/tablos", () => ({
|
|||
isLoading: false,
|
||||
}),
|
||||
useTabloMembers: () => ({
|
||||
data: [],
|
||||
data: [
|
||||
{
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "john@example.com",
|
||||
avatar_url: null,
|
||||
is_admin: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
useTabloOverviewLayout: () => ({
|
||||
data: layoutData,
|
||||
|
|
@ -62,6 +88,20 @@ vi.mock("../hooks/tablo_invites", () => ({
|
|||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/client_invites", () => ({
|
||||
usePendingClientInvites: () => ({
|
||||
data: [],
|
||||
}),
|
||||
useCreateClientInvite: () => ({
|
||||
mutate: vi.fn(),
|
||||
isPending: false,
|
||||
}),
|
||||
useCancelClientInvite: () => ({
|
||||
mutate: vi.fn(),
|
||||
isPending: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/invite", () => ({
|
||||
useInviteUser: () => ({
|
||||
mutate: vi.fn(),
|
||||
|
|
@ -69,6 +109,14 @@ vi.mock("../hooks/invite", () => ({
|
|||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/events", () => ({
|
||||
useEventsByTablo: () => ({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/tasks", () => ({
|
||||
useAllTasks: () => ({
|
||||
data: [
|
||||
|
|
@ -78,23 +126,53 @@ vi.mock("../hooks/tasks", () => ({
|
|||
assignee_id: "user-1",
|
||||
title: "Task A",
|
||||
status: "todo",
|
||||
parent_task_id: "etape-1",
|
||||
},
|
||||
],
|
||||
}),
|
||||
useTabloEtapes: () => ({
|
||||
data: [],
|
||||
data: [
|
||||
{
|
||||
id: "etape-1",
|
||||
tablo_id: "tablo-1",
|
||||
title: "Kickoff",
|
||||
description: null,
|
||||
status: "todo",
|
||||
assignee_id: null,
|
||||
position: 0,
|
||||
created_at: "2026-01-01T00:00:00.000Z",
|
||||
updated_at: "2026-01-01T00:00:00.000Z",
|
||||
is_parent: true,
|
||||
parent_task_id: null,
|
||||
due_date: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
useUpdateTask: () => ({
|
||||
mutate: mutateUpdateTask,
|
||||
}),
|
||||
useDeleteTask: () => ({
|
||||
mutate: mutateDeleteTask,
|
||||
}),
|
||||
useTask: () => ({
|
||||
data: null,
|
||||
}),
|
||||
useCreateEtape: () => ({
|
||||
mutateAsync: vi.fn(),
|
||||
mutateAsync: mutateCreateEtape,
|
||||
isPending: false,
|
||||
}),
|
||||
useUpdateEtape: () => ({
|
||||
mutateAsync: mutateUpdateEtape,
|
||||
isPending: false,
|
||||
}),
|
||||
useDeleteEtape: () => ({
|
||||
mutateAsync: mutateDeleteEtape,
|
||||
isPending: false,
|
||||
}),
|
||||
useCreateTask: () => ({
|
||||
mutate: mutateCreateTask,
|
||||
}),
|
||||
useUpdateTaskPositions: () => ({
|
||||
mutate: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
|
@ -105,6 +183,34 @@ vi.mock("../hooks/tablo_data", () => ({
|
|||
fileNames: [],
|
||||
},
|
||||
}),
|
||||
useDownloadTabloFile: () => ({
|
||||
mutateAsync: vi.fn(),
|
||||
}),
|
||||
useUploadTabloFile: () => ({
|
||||
mutateAsync: vi.fn(),
|
||||
}),
|
||||
useDeleteTabloFile: () => ({
|
||||
mutateAsync: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/tablo_folders", () => ({
|
||||
useTabloFolders: () => ({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
useCreateTabloFolder: () => ({
|
||||
mutateAsync: vi.fn(),
|
||||
isPending: false,
|
||||
}),
|
||||
useUpdateTabloFolder: () => ({
|
||||
mutateAsync: vi.fn(),
|
||||
isPending: false,
|
||||
}),
|
||||
useDeleteTabloFolder: () => ({
|
||||
mutateAsync: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../providers/UserStoreProvider", async (importOriginal) => {
|
||||
|
|
@ -120,6 +226,141 @@ vi.mock("../providers/UserStoreProvider", async (importOriginal) => {
|
|||
});
|
||||
|
||||
describe("TabloDetailsPage overview layout", () => {
|
||||
it("keeps the add etape action enabled before typing", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Étapes" }));
|
||||
|
||||
expect(screen.getByRole("button", { name: "Ajouter une étape" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("creates an etape from the etapes tab", async () => {
|
||||
const user = userEvent.setup();
|
||||
mutateCreateEtape.mockResolvedValueOnce(undefined);
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Étapes" }));
|
||||
await user.type(screen.getByPlaceholderText("Nom de la nouvelle étape..."), "Kickoff");
|
||||
await user.click(screen.getByRole("button", { name: "Ajouter une étape" }));
|
||||
|
||||
expect(mutateCreateEtape).toHaveBeenCalledWith({
|
||||
tabloId: "tablo-1",
|
||||
title: "Kickoff",
|
||||
position: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("updates an etape from the etapes tab", async () => {
|
||||
const user = userEvent.setup();
|
||||
mutateUpdateEtape.mockResolvedValueOnce(undefined);
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Étapes" }));
|
||||
await user.click(screen.getByRole("button", { name: "Modifier l'étape Kickoff" }));
|
||||
await user.clear(screen.getByDisplayValue("Kickoff"));
|
||||
await user.type(screen.getByPlaceholderText("Nom de l'étape"), "Planification");
|
||||
await user.click(screen.getByRole("button", { name: "Enregistrer l'étape" }));
|
||||
|
||||
expect(mutateUpdateEtape).toHaveBeenCalledWith({
|
||||
id: "etape-1",
|
||||
tabloId: "tablo-1",
|
||||
title: "Planification",
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes an etape from the etapes tab", async () => {
|
||||
const user = userEvent.setup();
|
||||
mutateDeleteEtape.mockResolvedValueOnce(undefined);
|
||||
const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true);
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Étapes" }));
|
||||
await user.click(screen.getByRole("button", { name: "Supprimer l'étape Kickoff" }));
|
||||
|
||||
expect(confirmSpy).toHaveBeenCalled();
|
||||
expect(mutateDeleteEtape).toHaveBeenCalledWith({
|
||||
id: "etape-1",
|
||||
tabloId: "tablo-1",
|
||||
});
|
||||
|
||||
confirmSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("deletes a task from the inline kanban action", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Tâches" }));
|
||||
await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" }));
|
||||
|
||||
expect(mutateDeleteTask).toHaveBeenCalledWith("task-1");
|
||||
});
|
||||
|
||||
it("restores the task etape when reopening the same edit modal", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1?section=tasks",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByText("Task A"));
|
||||
await user.click(screen.getByRole("combobox", { name: "Étape" }));
|
||||
await user.click(screen.getByRole("option", { name: "Aucune" }));
|
||||
await user.click(screen.getByRole("button", { name: "Annuler" }));
|
||||
|
||||
await user.click(screen.getByText("Task A"));
|
||||
|
||||
expect(screen.getByRole("combobox", { name: "Étape" })).toHaveTextContent("Kickoff");
|
||||
});
|
||||
|
||||
it("assigns the current user when creating from mes tâches in overview", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Ajouter" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole("combobox", { name: "Assigné à" })).toHaveTextContent("Test User");
|
||||
});
|
||||
|
||||
await user.type(screen.getByLabelText("Titre *"), "Nouvelle tâche");
|
||||
await user.click(screen.getByRole("button", { name: "Créer" }));
|
||||
|
||||
expect(mutateCreateTask).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tablo_id: "tablo-1",
|
||||
title: "Nouvelle tâche",
|
||||
assignee_id: "user-1",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("renders overview cards in persisted left-zone order", () => {
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
|
|
@ -134,6 +375,28 @@ describe("TabloDetailsPage overview layout", () => {
|
|||
);
|
||||
});
|
||||
|
||||
it("uses a dominant overview first column and purple primary actions", () => {
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
expect(screen.getByTestId("single-tablo-overview-grid")).toHaveClass(
|
||||
"lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]"
|
||||
);
|
||||
expect(screen.getByRole("link", { name: "Discussion" })).toHaveClass("bg-[#804EEC]");
|
||||
expect(screen.getByRole("button", { name: "Inviter" })).toHaveClass(
|
||||
"border-[#804EEC]",
|
||||
"text-[#804EEC]"
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toHaveClass(
|
||||
"border-[#804EEC]",
|
||||
"text-[#804EEC]"
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Ajouter" })).toHaveClass("bg-[#804EEC]");
|
||||
expect(screen.getByRole("button", { name: "Ouvrir" })).toHaveClass("text-[#804EEC]");
|
||||
});
|
||||
|
||||
it("shows layout edit toggle for admin users", () => {
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
|
|
@ -142,4 +405,21 @@ describe("TabloDetailsPage overview layout", () => {
|
|||
|
||||
expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses the client password invite UI in the share dialog", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderWithProviders(<TabloDetailsPage />, {
|
||||
route: "/tablos/tablo-1",
|
||||
path: "/tablos/:tabloId",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Inviter" }));
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
92
apps/main/src/pages/tasks.test.tsx
Normal file
92
apps/main/src/pages/tasks.test.tsx
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "../utils/testHelpers";
|
||||
import { TasksPage } from "./tasks";
|
||||
|
||||
const mutateUpdateTask = vi.fn();
|
||||
const mutateDeleteTask = vi.fn();
|
||||
|
||||
vi.mock("../hooks/tablos", () => ({
|
||||
useTablosList: () => ({
|
||||
data: [
|
||||
{
|
||||
id: "tablo-1",
|
||||
name: "Projet Alpha",
|
||||
color: "bg-blue-500",
|
||||
},
|
||||
],
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/tasks", () => ({
|
||||
useAllTasks: () => ({
|
||||
data: [
|
||||
{
|
||||
id: "task-1",
|
||||
tablo_id: "tablo-1",
|
||||
title: "Task A",
|
||||
description: "Description",
|
||||
status: "todo",
|
||||
due_date: null,
|
||||
assignee_id: "123",
|
||||
assignee_name: "John Doe",
|
||||
assignee_avatar: null,
|
||||
tablos: {
|
||||
id: "tablo-1",
|
||||
name: "Projet Alpha",
|
||||
color: "bg-blue-500",
|
||||
},
|
||||
},
|
||||
],
|
||||
isLoading: false,
|
||||
}),
|
||||
useUpdateTask: () => ({
|
||||
mutate: mutateUpdateTask,
|
||||
}),
|
||||
useDeleteTask: () => ({
|
||||
mutate: mutateDeleteTask,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@xtablo/tablo-views", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@xtablo/tablo-views")>();
|
||||
return {
|
||||
...actual,
|
||||
GanttChart: () => <div data-testid="gantt-chart" />,
|
||||
TaskModal: () => null,
|
||||
};
|
||||
});
|
||||
|
||||
describe("TasksPage", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("deletes a task from the inline kanban action", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderWithProviders(<TasksPage />, {
|
||||
route: "/tasks?view=kanban",
|
||||
path: "/tasks",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" }));
|
||||
|
||||
expect(mutateDeleteTask).toHaveBeenCalledWith("task-1");
|
||||
});
|
||||
|
||||
it("deletes a task from the inline list action", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderWithProviders(<TasksPage />, {
|
||||
route: "/tasks?view=aggregated",
|
||||
path: "/tasks",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" }));
|
||||
|
||||
expect(mutateDeleteTask).toHaveBeenCalledWith("task-1");
|
||||
});
|
||||
});
|
||||
|
|
@ -33,6 +33,7 @@ import {
|
|||
Sparkles,
|
||||
Star,
|
||||
Sun,
|
||||
Trash2Icon,
|
||||
UserIcon,
|
||||
Waves,
|
||||
Zap,
|
||||
|
|
@ -42,7 +43,7 @@ import { useTranslation } from "react-i18next";
|
|||
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { useTablosList } from "../hooks/tablos";
|
||||
import { useAllTasks, useUpdateTask } from "../hooks/tasks";
|
||||
import { useAllTasks, useDeleteTask, useUpdateTask } from "../hooks/tasks";
|
||||
import { useUser } from "../providers/UserStoreProvider";
|
||||
|
||||
type TaskStatus = "all" | "todo" | "in_progress" | "in_review" | "done";
|
||||
|
|
@ -134,6 +135,7 @@ export function TasksPage() {
|
|||
|
||||
// Mutation for updating task status
|
||||
const updateTaskMutation = useUpdateTask();
|
||||
const deleteTaskMutation = useDeleteTask();
|
||||
|
||||
const openTaskModal = (dueDate?: Date) => {
|
||||
setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined);
|
||||
|
|
@ -556,6 +558,17 @@ export function TasksPage() {
|
|||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Supprimer la tâche ${task.title}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
deleteTaskMutation.mutate(task.id);
|
||||
}}
|
||||
className="text-gray-400 hover:text-red-500 shrink-0 p-2 -m-1 min-h-[44px] min-w-[44px] flex items-center justify-center"
|
||||
>
|
||||
<Trash2Icon className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{formattedDate && (
|
||||
|
|
@ -878,6 +891,17 @@ export function TasksPage() {
|
|||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Supprimer la tâche ${task.title}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
deleteTaskMutation.mutate(task.id);
|
||||
}}
|
||||
className="inline-flex items-center justify-center h-8 w-8 min-h-[44px] min-w-[44px] rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
<Trash2Icon className="w-4 h-4 text-gray-400 hover:text-red-500" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -21,19 +21,24 @@ global.ResizeObserver = class ResizeObserver {
|
|||
}
|
||||
};
|
||||
|
||||
// Mock scrollIntoView for Radix UI components
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
// Mock scroll APIs for DOM-oriented tests without breaking node-environment suites.
|
||||
if (typeof Element !== "undefined") {
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
Element.prototype.scrollTo = vi.fn();
|
||||
}
|
||||
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(), // deprecated
|
||||
removeListener: vi.fn(), // deprecated
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
if (typeof window !== "undefined") {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(), // deprecated
|
||||
removeListener: vi.fn(), // deprecated
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
8
apps/main/src/vite-env.d.ts
vendored
8
apps/main/src/vite-env.d.ts
vendored
|
|
@ -1 +1,9 @@
|
|||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_VERSION: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
|
|
|
|||
18
apps/main/src/viteConfig.test.ts
Normal file
18
apps/main/src/viteConfig.test.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import configFactory from "../vite.config";
|
||||
|
||||
describe("main vite config", () => {
|
||||
it("uses hidden sourcemaps for production builds", () => {
|
||||
const config = configFactory({
|
||||
mode: "production",
|
||||
command: "build",
|
||||
isSsrBuild: false,
|
||||
isPreview: false,
|
||||
});
|
||||
|
||||
expect(config.build?.sourcemap).toBe("hidden");
|
||||
});
|
||||
});
|
||||
|
|
@ -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/*"]
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -43,6 +43,9 @@ export default defineConfig(({ mode }) => {
|
|||
|
||||
return {
|
||||
plugins,
|
||||
build: {
|
||||
sourcemap: mode === "test" ? false : "hidden",
|
||||
},
|
||||
server: {
|
||||
cors: false,
|
||||
},
|
||||
|
|
|
|||
12
biome.json
12
biome.json
|
|
@ -16,6 +16,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/**/*",
|
||||
|
|
@ -304,6 +310,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}",
|
||||
|
|
|
|||
626
docs/superpowers/plans/2026-04-18-client-password-invite-flow.md
Normal file
626
docs/superpowers/plans/2026-04-18-client-password-invite-flow.md
Normal 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 repo’s 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 app’s 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.
|
||||
|
|
@ -0,0 +1,467 @@
|
|||
# Datadog RUM Sourcemaps Via CI 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:** Generate private frontend sourcemaps for Datadog RUM/Error Tracking, upload them from GitHub Actions, and keep `.map` files out of deployed frontend assets.
|
||||
|
||||
**Architecture:** Add an explicit release-version contract to the main app’s RUM init, enable hidden sourcemaps in all Vite frontends, and create a frontend CI workflow that builds each app, uploads sourcemaps with matching Datadog metadata, and removes `.map` files before any deploy step consumes the build output.
|
||||
|
||||
**Tech Stack:** React 19, Vite 6, Vitest, GitHub Actions, Datadog CI CLI, Cloudflare/Wrangler deploy targets, pnpm workspaces.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
### New files
|
||||
|
||||
- `.github/workflows/frontend-sourcemaps.yml` — GitHub Actions workflow that builds the frontend apps on a self-hosted runner and uploads sourcemaps to Datadog.
|
||||
- `apps/clients/src/vite-env.d.ts` — Vite env typings for client-specific build variables, including `VITE_APP_VERSION`.
|
||||
- `apps/main/src/lib/rum.test.ts` — regression test for Datadog RUM init config.
|
||||
- `apps/main/vite.config.test.ts` — production sourcemap config test for `apps/main`.
|
||||
- `apps/clients/vite.config.test.ts` — production sourcemap config test for `apps/clients`.
|
||||
- `apps/external/vite.config.test.ts` — production sourcemap config test for `apps/external`.
|
||||
|
||||
### Modified files
|
||||
|
||||
- `package.json` — add `@datadog/datadog-ci` to root dev dependencies.
|
||||
- `apps/main/src/lib/rum.ts` — add `version: import.meta.env.VITE_APP_VERSION`.
|
||||
- `apps/main/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing.
|
||||
- `apps/external/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing.
|
||||
- `apps/main/vite.config.ts` — enable hidden sourcemaps for non-test builds.
|
||||
- `apps/clients/vite.config.ts` — enable hidden sourcemaps for non-test builds.
|
||||
- `apps/external/vite.config.ts` — enable hidden sourcemaps for non-test builds.
|
||||
|
||||
---
|
||||
|
||||
## Chunk 1: Runtime Release Metadata
|
||||
|
||||
### Task 1: Wire Datadog RUM version in `apps/main`
|
||||
|
||||
**Files:**
|
||||
- Create: `apps/main/src/lib/rum.test.ts`
|
||||
- Modify: `apps/main/src/lib/rum.ts`
|
||||
- Modify: `apps/main/src/vite-env.d.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing RUM init test**
|
||||
|
||||
Create `apps/main/src/lib/rum.test.ts`:
|
||||
|
||||
```typescript
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const init = vi.fn();
|
||||
|
||||
vi.mock("@datadog/browser-rum", () => ({
|
||||
datadogRum: {
|
||||
init,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@datadog/browser-rum-react", () => ({
|
||||
reactPlugin: () => "react-plugin",
|
||||
}));
|
||||
|
||||
describe("rum config", () => {
|
||||
beforeEach(() => {
|
||||
init.mockReset();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("sets the Datadog release version from VITE_APP_VERSION", async () => {
|
||||
vi.stubEnv("VITE_APP_VERSION", "test-sha");
|
||||
vi.stubEnv("MODE", "production");
|
||||
|
||||
await import("./rum");
|
||||
|
||||
expect(init).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
service: "xtablo-ui",
|
||||
env: "production",
|
||||
version: "test-sha",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev
|
||||
```
|
||||
|
||||
Expected: FAIL because `version` is not set in `datadogRum.init`.
|
||||
|
||||
- [ ] **Step 3: Add the runtime version**
|
||||
|
||||
Update `apps/main/src/lib/rum.ts`:
|
||||
|
||||
```typescript
|
||||
service: "xtablo-ui",
|
||||
env: import.meta.env.MODE,
|
||||
version: import.meta.env.VITE_APP_VERSION,
|
||||
```
|
||||
|
||||
Update `apps/main/src/vite-env.d.ts`:
|
||||
|
||||
```typescript
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_VERSION: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev
|
||||
pnpm --filter @xtablo/main typecheck
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/main/src/lib/rum.ts apps/main/src/lib/rum.test.ts apps/main/src/vite-env.d.ts
|
||||
git commit -m "feat: add Datadog release version to main rum config"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Chunk 2: Hidden Sourcemaps In All Vite Frontends
|
||||
|
||||
### Task 2: Add production sourcemap config tests
|
||||
|
||||
**Files:**
|
||||
- Create: `apps/main/vite.config.test.ts`
|
||||
- Create: `apps/clients/vite.config.test.ts`
|
||||
- Create: `apps/external/vite.config.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing config test for `apps/main`**
|
||||
|
||||
Create `apps/main/vite.config.test.ts`:
|
||||
|
||||
```typescript
|
||||
import { describe, expect, it } from "vitest";
|
||||
import configFactory from "./vite.config";
|
||||
|
||||
describe("main vite config", () => {
|
||||
it("uses hidden sourcemaps for production builds", () => {
|
||||
const config = configFactory({ mode: "production" });
|
||||
expect(config.build?.sourcemap).toBe("hidden");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write the failing config test for `apps/clients`**
|
||||
|
||||
Create `apps/clients/vite.config.test.ts`:
|
||||
|
||||
```typescript
|
||||
import { describe, expect, it } from "vitest";
|
||||
import configFactory from "./vite.config";
|
||||
|
||||
describe("clients vite config", () => {
|
||||
it("uses hidden sourcemaps for production builds", () => {
|
||||
const config = configFactory({ mode: "production" });
|
||||
expect(config.build?.sourcemap).toBe("hidden");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Write the failing config test for `apps/external`**
|
||||
|
||||
Create `apps/external/vite.config.test.ts`:
|
||||
|
||||
```typescript
|
||||
import { describe, expect, it } from "vitest";
|
||||
import configFactory from "./vite.config";
|
||||
|
||||
describe("external vite config", () => {
|
||||
it("uses hidden sourcemaps for production builds", () => {
|
||||
const config = configFactory({ mode: "production" });
|
||||
expect(config.build?.sourcemap).toBe("hidden");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the tests to verify they fail**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev
|
||||
pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test
|
||||
pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test
|
||||
```
|
||||
|
||||
Expected: FAIL because `build.sourcemap` is not configured.
|
||||
|
||||
- [ ] **Step 5: Implement hidden sourcemaps in all three Vite configs**
|
||||
|
||||
Update:
|
||||
- `apps/main/vite.config.ts`
|
||||
- `apps/clients/vite.config.ts`
|
||||
- `apps/external/vite.config.ts`
|
||||
|
||||
Add the same build section in each returned config:
|
||||
|
||||
```typescript
|
||||
build: {
|
||||
sourcemap: mode === "test" ? false : "hidden",
|
||||
},
|
||||
```
|
||||
|
||||
Keep it alongside the existing `plugins`, `server`, `define`, and `test` sections.
|
||||
|
||||
- [ ] **Step 6: Add env typing for the remaining apps**
|
||||
|
||||
Create `apps/clients/src/vite-env.d.ts`:
|
||||
|
||||
```typescript
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_VERSION: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
```
|
||||
|
||||
Update `apps/external/src/vite-env.d.ts`:
|
||||
|
||||
```typescript
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_VERSION: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 7: Run the tests and typechecks**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev
|
||||
pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test
|
||||
pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test
|
||||
pnpm --filter @xtablo/main typecheck
|
||||
pnpm --filter @xtablo/clients typecheck
|
||||
pnpm --filter @xtablo/external typecheck
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 8: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/main/vite.config.ts apps/main/vite.config.test.ts apps/clients/vite.config.ts apps/clients/vite.config.test.ts apps/clients/src/vite-env.d.ts apps/external/vite.config.ts apps/external/vite.config.test.ts apps/external/src/vite-env.d.ts
|
||||
git commit -m "build: enable hidden sourcemaps for frontend apps"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Chunk 3: Datadog CI Upload Workflow
|
||||
|
||||
### Task 3: Add pinned Datadog CLI and frontend sourcemap workflow
|
||||
|
||||
**Files:**
|
||||
- Create: `.github/workflows/frontend-sourcemaps.yml`
|
||||
- Modify: `package.json`
|
||||
|
||||
- [ ] **Step 1: Add the Datadog CLI dependency**
|
||||
|
||||
Update root `package.json`:
|
||||
|
||||
```json
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.2.5",
|
||||
"@datadog/datadog-ci": "^3.21.0",
|
||||
"turbo": "^2.5.8",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Install dependencies and verify lockfile changes**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Expected: `pnpm-lock.yaml` updates with `@datadog/datadog-ci`.
|
||||
|
||||
- [ ] **Step 3: Create the workflow**
|
||||
|
||||
Create `.github/workflows/frontend-sourcemaps.yml`:
|
||||
|
||||
```yaml
|
||||
name: Frontend Sourcemaps
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
|
||||
jobs:
|
||||
upload-sourcemaps:
|
||||
runs-on:
|
||||
- self-hosted
|
||||
- linux
|
||||
- x64
|
||||
env:
|
||||
DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }}
|
||||
DATADOG_SITE: ${{ secrets.DATADOG_SITE }}
|
||||
RELEASE_VERSION: ${{ github.sha }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 10.19.0
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile --child-concurrency=2
|
||||
|
||||
- name: Build main
|
||||
run: pnpm --filter @xtablo/main build:prod
|
||||
env:
|
||||
VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}
|
||||
|
||||
- name: Upload main sourcemaps
|
||||
run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets
|
||||
|
||||
- name: Remove main sourcemaps
|
||||
run: find apps/main/dist -name '*.map' -delete
|
||||
|
||||
- name: Build clients
|
||||
run: pnpm --filter @xtablo/clients build:prod
|
||||
env:
|
||||
VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}
|
||||
|
||||
- name: Upload clients sourcemaps
|
||||
run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets
|
||||
|
||||
- name: Remove clients sourcemaps
|
||||
run: find apps/clients/dist -name '*.map' -delete
|
||||
|
||||
- name: Build external
|
||||
run: pnpm --filter @xtablo/external build
|
||||
env:
|
||||
VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}
|
||||
|
||||
- name: Upload external sourcemaps
|
||||
run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets
|
||||
|
||||
- name: Remove external sourcemaps
|
||||
run: find apps/external/dist -name '*.map' -delete
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Validate the workflow file structure**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
rg -n "datadog-ci sourcemaps upload|RELEASE_VERSION|find .*\\.map" .github/workflows/frontend-sourcemaps.yml
|
||||
```
|
||||
|
||||
Expected: one upload and one cleanup step for each frontend app.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json pnpm-lock.yaml .github/workflows/frontend-sourcemaps.yml
|
||||
git commit -m "ci: upload frontend sourcemaps to Datadog"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Chunk 4: End-To-End Verification
|
||||
|
||||
### Task 4: Prove builds emit hidden sourcemaps and cleanup works
|
||||
|
||||
**Files:**
|
||||
- No new source files
|
||||
|
||||
- [ ] **Step 1: Build each frontend locally with a release version**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
VITE_APP_VERSION=test-sha pnpm --filter @xtablo/main build:prod
|
||||
VITE_APP_VERSION=test-sha pnpm --filter @xtablo/clients build:prod
|
||||
VITE_APP_VERSION=test-sha pnpm --filter @xtablo/external build
|
||||
```
|
||||
|
||||
Expected: each `dist/` contains built assets and `.map` files, but the generated JS bundles do not include public `sourceMappingURL` comments.
|
||||
|
||||
- [ ] **Step 2: Verify `.map` files exist before cleanup**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort
|
||||
```
|
||||
|
||||
Expected: at least one sourcemap per app.
|
||||
|
||||
- [ ] **Step 3: Simulate CI cleanup locally**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' -delete
|
||||
find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort
|
||||
```
|
||||
|
||||
Expected: no output from the second command.
|
||||
|
||||
- [ ] **Step 4: Run the targeted regression suite**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts vite.config.test.ts --mode dev
|
||||
pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test
|
||||
pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test
|
||||
pnpm --filter @xtablo/main typecheck
|
||||
pnpm --filter @xtablo/clients typecheck
|
||||
pnpm --filter @xtablo/external typecheck
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
```
|
||||
|
||||
Expected: clean worktree before opening the implementation PR.
|
||||
|
|
@ -0,0 +1,216 @@
|
|||
# Client Portal Tablo Parity
|
||||
|
||||
**Date**: 2026-04-15
|
||||
**Status**: Approved
|
||||
|
||||
## Overview
|
||||
|
||||
Make the client portal route in `apps/clients` match the visual design of the main app route `apps/main` `/tablos/:tabloId` as closely as possible.
|
||||
|
||||
The target route in `apps/clients` remains `/tablo/:tabloId`, but it should present the same shell language as `TabloDetailsPage`:
|
||||
|
||||
- same header structure
|
||||
- same metadata bar
|
||||
- same sticky tab navigation
|
||||
- same overview card layout and styling
|
||||
- same Tailwind/CSS visual system
|
||||
- same translation strategy through i18n
|
||||
|
||||
The client portal keeps its simpler local tab state and stays read-only except for discussion.
|
||||
|
||||
## Goals
|
||||
|
||||
- Match the current `apps/main` `TabloDetailsPage` look as closely as possible
|
||||
- Prevent visual drift between `apps/main` and `apps/clients`
|
||||
- Reuse the existing shared `@xtablo/tablo-views` section components
|
||||
- Keep the client portal safe by removing admin and mutation affordances
|
||||
- Use shared i18n keys wherever possible instead of hardcoded copy
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Rebuilding the client portal as a separate visual concept
|
||||
- Copying the main app's `?section=` route model into `apps/clients`
|
||||
- Enabling client file uploads, task completion, task creation, or layout editing
|
||||
- Refactoring unrelated app-level layout or navigation outside the tablo detail view
|
||||
|
||||
## Chosen Approach
|
||||
|
||||
Use a shared presentational shell for the tablo detail page, backed by a shared stylesheet source.
|
||||
|
||||
This shell should live close to the existing shared tablo view layer, likely in `packages/tablo-views`, because that package already contains the shared section components used by both apps.
|
||||
|
||||
Each app remains responsible for its own routing, data hooks, and permissions:
|
||||
|
||||
- `apps/main` keeps full `TabloDetailsPage` behavior
|
||||
- `apps/clients` keeps local internal tab state and client-specific data loading
|
||||
|
||||
The shared shell owns the route-level presentation so visual changes land in one place and are inherited by both apps.
|
||||
|
||||
## Shared CSS Source
|
||||
|
||||
Exact visual parity requires shared CSS, not just shared JSX.
|
||||
|
||||
Today both apps import `@xtablo/ui/styles/globals.css`, but `apps/main/src/main.css` and `apps/clients/src/main.css` already diverge on important visual tokens such as:
|
||||
|
||||
- navbar colors
|
||||
- dark mode tokens
|
||||
- chat surface colors
|
||||
- other route-level color variables
|
||||
|
||||
Because of that, `apps/clients` must not keep an independent competing style source for this page.
|
||||
|
||||
### Requirement
|
||||
|
||||
Extract the route-relevant visual styles currently coming from `apps/main/src/main.css` into a shared stylesheet layer that both apps import.
|
||||
|
||||
This shared stylesheet should include whatever is required for the tablo detail route to render identically, including:
|
||||
|
||||
- theme tokens needed by the page shell
|
||||
- chat-related styling used in the discussion tab
|
||||
- any utility styles relied on by the shared shell
|
||||
|
||||
### Constraint
|
||||
|
||||
Do not import `apps/main/src/main.css` directly from `apps/clients`. That would create brittle cross-app coupling and make ownership unclear.
|
||||
|
||||
Instead:
|
||||
|
||||
- move route-relevant shared styles into a shared import
|
||||
- keep app-specific styles in each app-local `main.css`
|
||||
|
||||
## Shared Shell Responsibilities
|
||||
|
||||
The shared tablo detail shell should own:
|
||||
|
||||
- the project header layout
|
||||
- the icon/image block next to the project title
|
||||
- header action placement
|
||||
- the metadata bar layout and styling
|
||||
- sticky tab navigation styling and behavior hooks
|
||||
- the overview page card grid and visual treatment
|
||||
|
||||
The shell should accept data and slots through props rather than owning app-specific mutations or routing decisions.
|
||||
|
||||
Suggested inputs:
|
||||
|
||||
- `tablo`
|
||||
- status label and badge styling
|
||||
- progress values
|
||||
- role label
|
||||
- created-at label
|
||||
- tab definitions
|
||||
- active tab
|
||||
- tab change handler
|
||||
- header action slot
|
||||
- overview capability flags or overview card content
|
||||
- per-section capability flags such as read-only settings
|
||||
|
||||
## `apps/main` Responsibilities
|
||||
|
||||
`apps/main` remains the owner of:
|
||||
|
||||
- `?section=` URL state
|
||||
- invite and share flows
|
||||
- client invite management
|
||||
- overview layout editing
|
||||
- task creation and mutation
|
||||
- file mutations
|
||||
- admin-only controls
|
||||
|
||||
The main app should adopt the shared shell without losing any existing behavior.
|
||||
|
||||
## `apps/clients` Responsibilities
|
||||
|
||||
`apps/clients` adopts the same visual shell, but keeps a restricted capability profile.
|
||||
|
||||
### Navigation
|
||||
|
||||
- Keep the current local tab state in React
|
||||
- Do not add `?section=` routing
|
||||
- Keep the same visible tab order, icons, and active styling as `apps/main`
|
||||
|
||||
### Header
|
||||
|
||||
- Keep the same header structure and spacing as `apps/main`
|
||||
- Keep the discussion CTA styling and placement
|
||||
- Remove the `Inviter` action entirely
|
||||
|
||||
### Metadata Bar
|
||||
|
||||
- Keep the same metadata structure and styling
|
||||
- Use client-safe translated labels for role and status copy
|
||||
|
||||
### Overview
|
||||
|
||||
- Use the same card layout and card styling as the main app
|
||||
- Remove layout edit controls
|
||||
- Remove task creation controls
|
||||
- Make task completion non-interactive
|
||||
- Keep file previews informational only
|
||||
|
||||
### Read-only Scope
|
||||
|
||||
The client portal should be read-only except for discussion.
|
||||
|
||||
That means:
|
||||
|
||||
- `discussion`: interactive
|
||||
- `tasks`: readable, no mutations
|
||||
- `etapes`: readable, no mutations
|
||||
- `events`: readable, no mutations
|
||||
- `roadmap`: readable, no mutations
|
||||
- `files`: readable, no upload, rename, move, create-folder, delete, or overflow action UI
|
||||
|
||||
## i18n
|
||||
|
||||
The shared shell must not introduce new hardcoded French strings.
|
||||
|
||||
### Rules
|
||||
|
||||
- Reuse existing translation keys from `apps/main` when the copy already matches the desired wording
|
||||
- Add missing keys only where the shared shell needs copy that does not already exist
|
||||
- Ensure both `apps/main` and `apps/clients` can resolve the keys used by the shared shell
|
||||
- Prefer shared wording for labels like tab names, metadata labels, and overview headings
|
||||
|
||||
This keeps parity at the copy level and avoids one app silently diverging from the other.
|
||||
|
||||
## Testing And Verification
|
||||
|
||||
Implementation should prove both parity and restrictions.
|
||||
|
||||
### Automated
|
||||
|
||||
- Add tests that verify the client shell renders the same key structure as the main shell
|
||||
- Add tests that verify client mode hides admin and mutation controls
|
||||
- Add tests that discussion remains interactive while other sections are read-only
|
||||
|
||||
### Manual
|
||||
|
||||
Perform side-by-side checks between:
|
||||
|
||||
- `apps/main` `/tablos/:tabloId`
|
||||
- `apps/clients` `/tablo/:tabloId`
|
||||
|
||||
Compare at minimum:
|
||||
|
||||
- header layout
|
||||
- metadata bar
|
||||
- sticky tabs
|
||||
- overview cards
|
||||
- tab content framing
|
||||
- discussion styling
|
||||
|
||||
## Risks
|
||||
|
||||
- Shared CSS extraction may expose assumptions currently embedded in app-local stylesheets
|
||||
- Some `TabloDetailsPage` copy is currently hardcoded and will need i18n cleanup before sharing
|
||||
- If the shared shell grows to own business logic, parity will become harder to maintain
|
||||
|
||||
## Success Criteria
|
||||
|
||||
This work is successful when:
|
||||
|
||||
- the client portal visually matches the main app tablo detail route
|
||||
- the shared shell and shared style source make future parity maintainable
|
||||
- the client portal remains read-only except for discussion
|
||||
- the route continues to use simpler internal navigation rather than query-param section routing
|
||||
|
|
@ -0,0 +1,249 @@
|
|||
# Clients Exact Tablo Parity
|
||||
|
||||
**Date**: 2026-04-16
|
||||
**Status**: Draft
|
||||
**Supersedes**: `docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md`
|
||||
|
||||
## Overview
|
||||
|
||||
`clients.xtablo.com` is intended to be a portal for the clients of our clients. For the single-tablo experience, it must render the exact same UI surface as `app.xtablo.com` on `apps/main/src/pages/tablo-details.tsx`.
|
||||
|
||||
The current codebase does not guarantee that outcome because `apps/main` and `apps/clients` still compose the page separately. Shared sections and some shared CSS exist, but the full single-tablo route is not owned by one shared render surface.
|
||||
|
||||
The target is stricter than "close parity":
|
||||
|
||||
- same page shell
|
||||
- same header structure
|
||||
- same metadata row
|
||||
- same tab bar
|
||||
- same overview layout
|
||||
- same section framing
|
||||
- same responsive behavior
|
||||
- same route-level CSS source
|
||||
- same component tree for the single-tablo view
|
||||
|
||||
The only intended differences are:
|
||||
|
||||
- `apps/main` keeps URL-backed section state
|
||||
- `apps/clients` keeps in-memory section state
|
||||
- `apps/main` exposes full admin and mutation capabilities
|
||||
- `apps/clients` exposes a restricted client-safe capability set
|
||||
|
||||
## Problem Statement
|
||||
|
||||
`clients.xtablo.com` is not at feature parity today for structural reasons, not because of one isolated CSS bug.
|
||||
|
||||
### Current causes of drift
|
||||
|
||||
1. `apps/clients/src/pages/ClientTabloPage.tsx` reconstructs a client-specific page instead of rendering the same single-tablo surface as `apps/main`.
|
||||
2. `apps/clients/src/components/ClientLayout.tsx` owns a separate app shell, so spacing, header behavior, and responsive layout can drift from the main app.
|
||||
3. Shared CSS exists only partially. Route-level tokens and chat/page styling have been extracted in places, but the full single-tablo view is still not governed by one shared route stylesheet plus one shared render tree.
|
||||
4. Permissions are mixed into page composition instead of being expressed as a clean capability model. That forces `clients` to fork render logic instead of rendering the same surface with different behavior gates.
|
||||
|
||||
The result is predictable: any visual or structural change to the main tablo route risks being manually reimplemented in `clients`, and parity becomes a maintenance task instead of an invariant.
|
||||
|
||||
## Goals
|
||||
|
||||
- Make the single-tablo UI in `clients.xtablo.com` visually identical to `apps/main/src/pages/tablo-details.tsx`
|
||||
- Enforce parity through one shared single-tablo render surface
|
||||
- Share the route-level CSS and responsive behavior between both apps
|
||||
- Keep `apps/clients` on in-memory tab state
|
||||
- Keep `discussion` writable in client mode
|
||||
- Keep the rest of the client experience read-only or admin-hidden as approved
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Rebuilding the client portal as a separate visual concept
|
||||
- Introducing query-param section routing into `apps/clients`
|
||||
- Enabling client-side admin actions
|
||||
- Refactoring unrelated routes outside the single-tablo experience
|
||||
- Deleting the newer client-specific invite system from the codebase
|
||||
|
||||
## Hard Requirement
|
||||
|
||||
The UI must be the exact same.
|
||||
|
||||
That rules out maintaining two parallel page compositions for the single-tablo route. "Shared components plus duplicated page assembly" is not sufficient because parity will drift again. The single-tablo view must be rendered from one shared composition surface consumed by both apps.
|
||||
|
||||
## Chosen Approach
|
||||
|
||||
Create a shared single-tablo route surface in `packages/tablo-views` and make both apps consume it.
|
||||
|
||||
This shared surface owns the exact structure, responsive layout, CSS import, tab order, overview composition, and section framing for the route.
|
||||
|
||||
Each app becomes a thin adapter:
|
||||
|
||||
- `apps/main` passes full-capability handlers and URL-backed section state
|
||||
- `apps/clients` passes restricted capabilities and in-memory section state
|
||||
|
||||
This is a consolidation, not a styling pass.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Shared package ownership
|
||||
|
||||
`packages/tablo-views` should own the single-tablo route surface for both apps, including:
|
||||
|
||||
- header layout
|
||||
- title and icon/image block
|
||||
- metadata row
|
||||
- sticky tab navigation
|
||||
- overview block composition
|
||||
- section container layout
|
||||
- discussion full-height layout behavior
|
||||
- route-specific CSS for this surface
|
||||
|
||||
This shared surface should render the same DOM structure and use the same styling hooks regardless of app.
|
||||
|
||||
### App adapter ownership
|
||||
|
||||
`apps/main` should own:
|
||||
|
||||
- `?section=` query-param state
|
||||
- full mutation handlers
|
||||
- admin-only actions
|
||||
- share and invite workflows
|
||||
- main-only routing integrations
|
||||
|
||||
`apps/clients` should own:
|
||||
|
||||
- local in-memory tab state
|
||||
- client-safe data loading
|
||||
- capability restrictions
|
||||
- client-safe app shell concerns outside the single-tablo surface
|
||||
|
||||
### Key principle
|
||||
|
||||
The apps must differ by inputs, not by page composition.
|
||||
|
||||
## Capability Model
|
||||
|
||||
The shared single-tablo surface should branch on capabilities rather than on app identity.
|
||||
|
||||
Suggested capability contract:
|
||||
|
||||
- `canCreateTasks`
|
||||
- `canEditTasks`
|
||||
- `canEditEvents`
|
||||
- `canManageFiles`
|
||||
- `canManageMembers`
|
||||
- `canInviteMembers`
|
||||
- `canEditLayout`
|
||||
- `canWriteDiscussion`
|
||||
|
||||
### Approved client boundary
|
||||
|
||||
For `clients.xtablo.com`:
|
||||
|
||||
- `discussion`: writable
|
||||
- file read/download behavior: allowed where already supported
|
||||
- task edits: disabled
|
||||
- event edits: disabled
|
||||
- layout edits: hidden
|
||||
- member management: hidden or read-only
|
||||
- invite/share management: hidden
|
||||
|
||||
This preserves the same page structure while changing behavior safely.
|
||||
|
||||
## CSS And Responsiveness
|
||||
|
||||
Exact UI parity requires a single route-level CSS source for the single-tablo experience.
|
||||
|
||||
### Requirements
|
||||
|
||||
- the shared single-tablo surface imports one shared route stylesheet from `packages/tablo-views`
|
||||
- route-level tokens for navbar, metadata, sticky tabs, and discussion/chat visuals come from that shared stylesheet
|
||||
- responsive breakpoints and overflow behavior are not redefined independently in `apps/main` and `apps/clients`
|
||||
|
||||
### Constraint
|
||||
|
||||
`apps/clients` must not carry a competing route-specific single-tablo style layer that can override the shared surface in divergent ways.
|
||||
|
||||
App-local CSS can remain for app-wide concerns, but the single-tablo route must have one styling owner.
|
||||
|
||||
## State Model
|
||||
|
||||
The visual surface is shared, but tab state differs by app.
|
||||
|
||||
### Main app
|
||||
|
||||
- active section comes from `?section=...`
|
||||
- existing route behavior remains intact
|
||||
|
||||
### Clients app
|
||||
|
||||
- active section is stored in local React state
|
||||
- no query-param synchronization is required
|
||||
|
||||
This is acceptable because the user explicitly approved in-memory state for clients.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
### Phase 1: Consolidate the surface
|
||||
|
||||
- identify all remaining structure in `apps/main/src/pages/tablo-details.tsx` that is still page-owned instead of shared
|
||||
- move that structure into a shared single-tablo route surface in `packages/tablo-views`
|
||||
- make `apps/main` consume the shared surface first, preserving current behavior
|
||||
|
||||
### Phase 2: Convert the clients app into an adapter
|
||||
|
||||
- remove duplicated page composition from `apps/clients/src/pages/ClientTabloPage.tsx`
|
||||
- replace it with a thin adapter that passes client-safe data and capability flags into the shared surface
|
||||
- keep local in-memory tab state in the adapter only
|
||||
|
||||
### Phase 3: Normalize the shell
|
||||
|
||||
- ensure the surrounding shell and route-level CSS used by the single-tablo surface are shared consistently
|
||||
- keep `ClientLayout` responsible only for client-portal app concerns, not for redefining the single-tablo view
|
||||
|
||||
### Phase 4: Lock parity with tests
|
||||
|
||||
- add tests that assert `main` and `clients` render the same shared single-tablo structure
|
||||
- add client-mode tests for capability restrictions
|
||||
- add responsive regression coverage where practical
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
Verification must prove parity, not just correctness.
|
||||
|
||||
### Automated
|
||||
|
||||
- shared render tests for the single-tablo route surface in `packages/tablo-views`
|
||||
- adapter tests proving `apps/main` and `apps/clients` pass different state/capabilities into the same surface
|
||||
- regression tests that the client app hides or disables admin-only actions while keeping discussion writable
|
||||
- targeted CSS contract tests ensuring both apps import the same shared route stylesheet
|
||||
|
||||
### Manual
|
||||
|
||||
Side-by-side comparison between:
|
||||
|
||||
- `apps/main` `/tablos/:tabloId`
|
||||
- `apps/clients` `/tablo/:tabloId`
|
||||
|
||||
At minimum verify:
|
||||
|
||||
- desktop layout
|
||||
- mobile layout
|
||||
- sticky tabs
|
||||
- overview cards
|
||||
- discussion layout
|
||||
- header wrapping and spacing
|
||||
- empty states
|
||||
|
||||
## Risks
|
||||
|
||||
- `apps/main/src/pages/tablo-details.tsx` may still contain too much mixed business logic and render logic, making extraction noisy
|
||||
- some shared sections may still assume main-app permissions implicitly
|
||||
- partial CSS ownership may continue to cause drift if not fully normalized
|
||||
- client-safe data access may reveal places where the UI currently assumes admin or member-level data is always present
|
||||
|
||||
## Success Criteria
|
||||
|
||||
This work is successful when:
|
||||
|
||||
- `clients.xtablo.com` renders the same single-tablo UI as `app.xtablo.com`
|
||||
- future UI changes to the single-tablo route normally require edits in one shared place
|
||||
- `apps/clients` remains in-memory for tab state
|
||||
- client restrictions match the approved boundary
|
||||
- discussion remains writable in client mode
|
||||
- parity is enforced structurally, not maintained manually
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
# Datadog RUM Sourcemaps Via CI Design
|
||||
|
||||
**Goal:** Deobfuscate frontend RUM and Error Tracking stack traces in Datadog for the Xtablo frontends by generating sourcemaps during build, uploading them in CI, and keeping `.map` files off the public CDN.
|
||||
|
||||
## Current State
|
||||
|
||||
- `apps/main` initializes Datadog RUM in [apps/main/src/lib/rum.ts](/Users/arthur.belleville/Documents/perso/projects/xtablo-source/apps/main/src/lib/rum.ts) with `service: "xtablo-ui"` and `env: import.meta.env.MODE`, but no explicit release version.
|
||||
- `apps/main`, `apps/clients`, and `apps/external` are Vite frontends with production Cloudflare deployments.
|
||||
- None of the three Vite configs currently emit production sourcemaps.
|
||||
- On this branch there is no tracked GitHub Actions workflow yet, so CI wiring must be introduced as part of the implementation.
|
||||
|
||||
## Decision
|
||||
|
||||
Use Datadog’s recommended CI upload flow:
|
||||
|
||||
1. Build each frontend with Vite `build.sourcemap: "hidden"`.
|
||||
2. Upload generated sourcemaps from CI with `datadog-ci sourcemaps upload`.
|
||||
3. Use a release version derived from the CI commit SHA.
|
||||
4. Remove all `.map` files from `dist/` before deploy packaging so they are never publicly served.
|
||||
|
||||
This keeps sourcemaps private while still enabling unminified stack traces in Datadog.
|
||||
|
||||
Sources:
|
||||
- Datadog CI sourcemap upload guide: https://docs.datadoghq.com/real_user_monitoring/guide/upload-javascript-source-maps/?tab=vite
|
||||
- Vite `build.sourcemap` docs: https://vite.dev/config/build-options.html
|
||||
|
||||
## Runtime Contract
|
||||
|
||||
Datadog matches sourcemaps against browser events by `service` and `version`.
|
||||
|
||||
- `apps/main` must emit `version: import.meta.env.VITE_APP_VERSION` in its RUM initialization.
|
||||
- CI must upload sourcemaps for `apps/main` using:
|
||||
- `service=xtablo-ui`
|
||||
- `release-version=$GITHUB_SHA`
|
||||
- `apps/clients` and `apps/external` should use the same CI release version convention now, even though they do not currently emit RUM events. This keeps the deployment contract consistent and avoids another pipeline change when browser monitoring is enabled there.
|
||||
|
||||
## Public Asset Prefixes
|
||||
|
||||
The Datadog upload command must use the real production asset prefixes:
|
||||
|
||||
- `apps/main`: `https://app.xtablo.com/assets`
|
||||
- `apps/clients`: `https://clients.xtablo.com/assets`
|
||||
- `apps/external`: `https://embed.xtablo.com/assets`
|
||||
|
||||
These prefixes must match the actual URLs used by the deployed JS bundles.
|
||||
|
||||
## Implementation Shape
|
||||
|
||||
### Frontend code
|
||||
|
||||
- `apps/main/src/lib/rum.ts`
|
||||
- add `version: import.meta.env.VITE_APP_VERSION`
|
||||
- `apps/main/src/vite-env.d.ts`
|
||||
- declare `VITE_APP_VERSION`
|
||||
- `apps/clients/src/vite-env.d.ts`
|
||||
- create and declare `VITE_APP_VERSION`
|
||||
- `apps/external/src/vite-env.d.ts`
|
||||
- declare `VITE_APP_VERSION`
|
||||
|
||||
### Build config
|
||||
|
||||
- `apps/main/vite.config.ts`
|
||||
- `apps/clients/vite.config.ts`
|
||||
- `apps/external/vite.config.ts`
|
||||
|
||||
Each should emit hidden sourcemaps for non-test builds.
|
||||
|
||||
### CI
|
||||
|
||||
- Add GitHub Actions workflow for frontend builds on self-hosted runners.
|
||||
- Add `@datadog/datadog-ci` as a root dev dependency so the workflow can run a pinned CLI version from the repo.
|
||||
- After each frontend build:
|
||||
- upload sourcemaps to Datadog
|
||||
- delete `dist/**/*.map`
|
||||
|
||||
## Secrets And CI Inputs
|
||||
|
||||
The workflow needs:
|
||||
|
||||
- `DATADOG_API_KEY`
|
||||
- `DATADOG_SITE`
|
||||
- release version from `github.sha`
|
||||
|
||||
The workflow should fail fast if Datadog secrets are missing on the deployment path where sourcemap upload is required.
|
||||
|
||||
## Verification
|
||||
|
||||
- Unit test for `apps/main` RUM init to assert `version` is wired from env.
|
||||
- Vite config tests or config assertions for all three apps to verify production builds use `sourcemap: "hidden"`.
|
||||
- CI workflow smoke verification:
|
||||
- build the apps
|
||||
- run sourcemap upload
|
||||
- confirm `.map` files are removed from `dist`
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Enabling Datadog RUM in `apps/clients` or `apps/external` right now.
|
||||
- Serving sourcemaps publicly.
|
||||
- Changing app deployment hosts or CDN paths.
|
||||
|
|
@ -23,6 +23,7 @@
|
|||
"deploy:admin": "turbo deploy --filter=@xtablo/admin",
|
||||
"deploy:chat": "turbo deploy --filter=@xtablo/chat-worker",
|
||||
"deploy:external": "turbo deploy --filter=@xtablo/external",
|
||||
"deploy:clients": "turbo deploy:prod --filter=@xtablo/clients",
|
||||
"lint": "turbo lint",
|
||||
"lint:fix": "turbo lint:fix",
|
||||
"format": "turbo format",
|
||||
|
|
@ -34,6 +35,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.2.5",
|
||||
"@datadog/datadog-ci": "^4.3.0",
|
||||
"turbo": "^2.5.8",
|
||||
"typescript": "^5.7.0"
|
||||
},
|
||||
|
|
|
|||
32
packages/auth-ui/package.json
Normal file
32
packages/auth-ui/package.json
Normal 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"
|
||||
}
|
||||
}
|
||||
127
packages/auth-ui/src/AuthCardShell.tsx
Normal file
127
packages/auth-ui/src/AuthCardShell.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
83
packages/auth-ui/src/AuthEmailPasswordForm.tsx
Normal file
83
packages/auth-ui/src/AuthEmailPasswordForm.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
34
packages/auth-ui/src/AuthInfoBanner.tsx
Normal file
34
packages/auth-ui/src/AuthInfoBanner.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
3
packages/auth-ui/src/index.ts
Normal file
3
packages/auth-ui/src/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export { AuthCardShell } from "./AuthCardShell";
|
||||
export { AuthEmailPasswordForm } from "./AuthEmailPasswordForm";
|
||||
export { AuthInfoBanner } from "./AuthInfoBanner";
|
||||
27
packages/auth-ui/tsconfig.json
Normal file
27
packages/auth-ui/tsconfig.json
Normal 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"]
|
||||
}
|
||||
|
|
@ -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
|
|
@ -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,
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue