WP-03: employee records and contracts on real data

Replaces the demo module behind the team directory and the employee
record with scoped queries, and adds contracts, amendments, work
permits and the forfait-jours fields.

Writing the end-to-end test exposed a modelling error worth naming:
first and last names lived only on User, so an employee without an
application account had no name at all — the directory rendered
"— Salarié E0007". Most sales staff never sign in, and the personnel
register requires their name, so the name belongs to the record, not
to the login. Moved to EmployeeProfile with a data migration that
carries the existing names down from User.

Contract rules are pure functions tested at the boundaries. The case
that matters is an open-ended contract: a CDI with no end date overlaps
every later period, which a naive comparison of two date pairs misses,
and two overlapping active contracts would count one employee twice in
payroll. The check runs inside the transaction, not only in the form.

Forfait jours is refused without a written individual agreement and a
dated employee consent: without them the arrangement is unenforceable,
and enabling it would also switch off every weekly-duration control.

Salary and bank details are not merely hidden when the capability is
missing — they are never loaded. A field absent from the response
cannot leak through HTML, a log or an error message.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cr9dkEHwbDgkWPnyGj1Rjv
This commit is contained in:
Claude committed 2026-08-07 23:17:16 +00:00
1 parent f8050b06c7
commit 8a314991d3
18 files changed
+1667 -210

No files matched your search

@@ -0,0 +1,157 @@
-- CreateEnum
CREATE TYPE "ContractType" AS ENUM ('APPRENTISSAGE', 'CDD', 'CDI', 'DIRIGEANT_ASSIMILE_SALARIE', 'DIRIGEANT_NON_SALARIE', 'EXTRA', 'INTERIM', 'STAGIAIRE', 'SAISONNIER');
-- CreateEnum
CREATE TYPE "ContractStatus" AS ENUM ('DRAFT', 'ACTIVE', 'ENDED');
-- CreateEnum
CREATE TYPE "WorkTimeArrangement" AS ENUM ('HOURLY', 'FORFAIT_JOURS');
-- CreateTable
CREATE TABLE "EmployeeProfile" (
"membershipId" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"birthDate" DATE,
"birthPlace" TEXT,
"nationality" TEXT,
"addressLine1" TEXT,
"postalCode" TEXT,
"city" TEXT,
"country" TEXT,
"phone" TEXT,
"personalEmail" TEXT,
"socialSecurityNumberEnc" BYTEA,
"ibanEnc" BYTEA,
"bicEnc" BYTEA,
"emergencyContactName" TEXT,
"emergencyContactPhone" TEXT,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "EmployeeProfile_pkey" PRIMARY KEY ("membershipId")
);
-- CreateTable
CREATE TABLE "WorkPermit" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"membershipId" TEXT NOT NULL,
"permitType" TEXT NOT NULL,
"reference" TEXT NOT NULL,
"issuedAt" DATE,
"expiresAt" DATE NOT NULL,
CONSTRAINT "WorkPermit_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "UserContract" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"membershipId" TEXT NOT NULL,
"locationId" TEXT NOT NULL,
"contractType" "ContractType" NOT NULL,
"startDate" DATE NOT NULL,
"endDate" DATE,
"trialEndDate" DATE,
"workTimeArrangement" "WorkTimeArrangement" NOT NULL DEFAULT 'HOURLY',
"weeklyHours" DECIMAL(5,2) NOT NULL DEFAULT 35,
"forfaitDaysPerYear" DECIMAL(5,1),
"forfaitAgreementRef" TEXT,
"forfaitAgreedAt" TIMESTAMP(3),
"isModulated" BOOLEAN NOT NULL DEFAULT false,
"hourlyRate" DECIMAL(10,4),
"monthlySalary" DECIMAL(10,2),
"jobTitleId" TEXT,
"classification" TEXT,
"coefficient" TEXT,
"status" "ContractStatus" NOT NULL DEFAULT 'ACTIVE',
"endReason" TEXT,
"version" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "UserContract_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Amendment" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"userContractId" TEXT NOT NULL,
"effectiveDate" DATE NOT NULL,
"changes" JSONB NOT NULL,
"reason" TEXT,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Amendment_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ForfaitDayEntry" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"userContractId" TEXT NOT NULL,
"localDate" DATE NOT NULL,
"quantity" DECIMAL(2,1) NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ForfaitDayEntry_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "WorkloadReview" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"userContractId" TEXT NOT NULL,
"heldAt" DATE NOT NULL,
"summary" TEXT NOT NULL,
"actions" TEXT,
CONSTRAINT "WorkloadReview_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EmployeeProfile_accountId_idx" ON "EmployeeProfile"("accountId");
-- CreateIndex
CREATE INDEX "WorkPermit_accountId_idx" ON "WorkPermit"("accountId");
-- CreateIndex
CREATE INDEX "WorkPermit_membershipId_idx" ON "WorkPermit"("membershipId");
-- CreateIndex
CREATE INDEX "UserContract_accountId_idx" ON "UserContract"("accountId");
-- CreateIndex
CREATE INDEX "UserContract_membershipId_idx" ON "UserContract"("membershipId");
-- CreateIndex
CREATE INDEX "Amendment_accountId_idx" ON "Amendment"("accountId");
-- CreateIndex
CREATE INDEX "Amendment_userContractId_idx" ON "Amendment"("userContractId");
-- CreateIndex
CREATE INDEX "ForfaitDayEntry_accountId_idx" ON "ForfaitDayEntry"("accountId");
-- CreateIndex
CREATE UNIQUE INDEX "ForfaitDayEntry_userContractId_localDate_key" ON "ForfaitDayEntry"("userContractId", "localDate");
-- CreateIndex
CREATE INDEX "WorkloadReview_accountId_idx" ON "WorkloadReview"("accountId");
-- CreateIndex
CREATE INDEX "WorkloadReview_userContractId_idx" ON "WorkloadReview"("userContractId");
-- AddForeignKey
ALTER TABLE "EmployeeProfile" ADD CONSTRAINT "EmployeeProfile_membershipId_fkey" FOREIGN KEY ("membershipId") REFERENCES "Membership"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WorkPermit" ADD CONSTRAINT "WorkPermit_membershipId_fkey" FOREIGN KEY ("membershipId") REFERENCES "Membership"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "UserContract" ADD CONSTRAINT "UserContract_membershipId_fkey" FOREIGN KEY ("membershipId") REFERENCES "Membership"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Amendment" ADD CONSTRAINT "Amendment_userContractId_fkey" FOREIGN KEY ("userContractId") REFERENCES "UserContract"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,27 @@
-- Étend l'isolation aux tables du dossier salarié.
--
-- Le test « toute table portant accountId est protégée » échoue sans ceci :
-- c'est lui qui transforme cet oubli en échec de CI plutôt qu'en fuite.
DO $$
DECLARE
t text;
BEGIN
FOREACH t IN ARRAY ARRAY[
'EmployeeProfile', 'WorkPermit', 'UserContract', 'Amendment',
'ForfaitDayEntry', 'WorkloadReview'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', t);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY', t);
EXECUTE format(
'CREATE POLICY tenant_isolation ON %I USING ("accountId" = planflow_current_account())',
t
);
EXECUTE format(
'CREATE POLICY tenant_insert ON %I FOR INSERT WITH CHECK ("accountId" = planflow_current_account())',
t
);
END LOOP;
END;
$$;
@@ -0,0 +1,24 @@
/*
Warnings:
- Added the required column `firstName` to the `EmployeeProfile` table without a default value. This is not possible if the table is not empty.
- Added the required column `lastName` to the `EmployeeProfile` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "EmployeeProfile" ADD COLUMN "firstName" TEXT,
ADD COLUMN "lastName" TEXT;
-- Reprise : le nom existait sur le compte utilisateur, il descend au dossier.
UPDATE "EmployeeProfile" p
SET "firstName" = COALESCE(u."firstName", 'Prénom'),
"lastName" = COALESCE(u."lastName", 'À compléter')
FROM "Membership" m
LEFT JOIN "User" u ON u.id = m."userId"
WHERE m.id = p."membershipId";
UPDATE "EmployeeProfile" SET "firstName" = 'Prénom' WHERE "firstName" IS NULL;
UPDATE "EmployeeProfile" SET "lastName" = 'À compléter' WHERE "lastName" IS NULL;
ALTER TABLE "EmployeeProfile" ALTER COLUMN "firstName" SET NOT NULL;
ALTER TABLE "EmployeeProfile" ALTER COLUMN "lastName" SET NOT NULL;
+168
View File
@@ -119,6 +119,9 @@ model Membership {
scopes MembershipScope[]
invitations Invitation[]
auditLogs AuditLog[]
profile EmployeeProfile?
contracts UserContract[]
workPermits WorkPermit[]
@@unique([accountId, employeeNumber])
@@index([accountId])
@@ -377,3 +380,168 @@ model LegalConfigEntry {
@@unique([accountId, domain, key, effectiveFrom])
@@index([accountId])
}
// ============================================================================
// Dossier salarié et contrats — PLAN.md §4.3, WP-03
// ============================================================================
/// Dossier personnel. NIR, IBAN et BIC sont chiffrés au repos (PLAN.md §3.6) :
/// une sauvegarde volée ne doit pas suffire à les lire.
model EmployeeProfile {
membershipId String @id
accountId String
/// Nom d'état civil, porté par le dossier et non par le compte utilisateur :
/// la plupart des salariés n'ont pas de compte, et le registre unique du
/// personnel exige leur nom.
firstName String
lastName String
birthDate DateTime? @db.Date
birthPlace String?
nationality String?
addressLine1 String?
postalCode String?
city String?
country String?
phone String?
personalEmail String?
socialSecurityNumberEnc Bytes?
ibanEnc Bytes?
bicEnc Bytes?
emergencyContactName String?
emergencyContactPhone String?
updatedAt DateTime @updatedAt
membership Membership @relation(fields: [membershipId], references: [id], onDelete: Cascade)
@@index([accountId])
}
/// Titre de séjour et son échéance. Le tableau de bord RH surveille les
/// expirations : un titre périmé interdit l'emploi.
model WorkPermit {
id String @id @default(cuid())
accountId String
membershipId String
permitType String
reference String
issuedAt DateTime? @db.Date
expiresAt DateTime @db.Date
membership Membership @relation(fields: [membershipId], references: [id], onDelete: Cascade)
@@index([accountId])
@@index([membershipId])
}
model UserContract {
id String @id @default(cuid())
accountId String
membershipId String
locationId String
contractType ContractType
startDate DateTime @db.Date
endDate DateTime? @db.Date
trialEndDate DateTime? @db.Date
/// Organisation du temps. Le forfait jours exclut le décompte horaire (§6.4).
workTimeArrangement WorkTimeArrangement @default(HOURLY)
weeklyHours Decimal @default(35) @db.Decimal(5, 2)
forfaitDaysPerYear Decimal? @db.Decimal(5, 1)
/// Convention individuelle écrite. Sans elle le forfait est inopposable :
/// l'activation est refusée.
forfaitAgreementRef String?
forfaitAgreedAt DateTime?
isModulated Boolean @default(false)
hourlyRate Decimal? @db.Decimal(10, 4)
monthlySalary Decimal? @db.Decimal(10, 2)
jobTitleId String?
classification String?
coefficient String?
status ContractStatus @default(ACTIVE)
endReason String?
version Int @default(0)
createdAt DateTime @default(now())
membership Membership @relation(fields: [membershipId], references: [id], onDelete: Cascade)
amendments Amendment[]
@@index([accountId])
@@index([membershipId])
}
/// Liste exhaustive relevée dans le filtre « Tous les types de contrats ».
enum ContractType {
APPRENTISSAGE
CDD
CDI
DIRIGEANT_ASSIMILE_SALARIE
DIRIGEANT_NON_SALARIE
EXTRA
INTERIM
STAGIAIRE
SAISONNIER
}
enum ContractStatus {
DRAFT
ACTIVE
ENDED
}
enum WorkTimeArrangement {
HOURLY
FORFAIT_JOURS
}
/// Avenant. Conserve l'historique plutôt que d'écraser le contrat : un contrôle
/// demande l'état du contrat au moment des faits, pas son état actuel.
model Amendment {
id String @id @default(cuid())
accountId String
userContractId String
effectiveDate DateTime @db.Date
changes Json
reason String?
createdBy String
createdAt DateTime @default(now())
contract UserContract @relation(fields: [userContractId], references: [id], onDelete: Cascade)
@@index([accountId])
@@index([userContractId])
}
/// Décompte des jours d'un salarié au forfait. Conservation 3 ans (§12.5).
model ForfaitDayEntry {
id String @id @default(cuid())
accountId String
userContractId String
localDate DateTime @db.Date
quantity Decimal @db.Decimal(2, 1)
createdBy String
createdAt DateTime @default(now())
@@unique([userContractId, localDate])
@@index([accountId])
}
/// Entretien annuel de charge, obligatoire au forfait jours (matrice n° 7).
model WorkloadReview {
id String @id @default(cuid())
accountId String
userContractId String
heldAt DateTime @db.Date
summary String
actions String?
@@index([accountId])
@@index([userContractId])
}
+59
View File
@@ -181,6 +181,65 @@ async function main() {
console.log(` ${person.email} — ${person.role}`);
}
console.log('→ Contrats et dossiers');
const contractSpecs = [
{ number: 'E0001', type: 'CDI', hours: 39, forfait: false, location: 'loc-nantes' },
{ number: 'E0002', type: 'CDI', hours: 0, forfait: true, location: 'loc-nantes' },
{ number: 'E0003', type: 'CDI', hours: 35, forfait: false, location: 'loc-rennes' },
{ number: 'E0004', type: 'CDD', hours: 24, forfait: false, location: 'loc-nantes' },
] as const;
for (const spec of contractSpecs) {
const membership = await prisma.membership.findUnique({
where: {
accountId_employeeNumber: {
accountId: account.id,
employeeNumber: spec.number,
},
},
});
if (!membership) continue;
const holder = membership.userId
? await prisma.user.findUnique({ where: { id: membership.userId } })
: null;
await prisma.employeeProfile.upsert({
where: { membershipId: membership.id },
update: {},
create: {
membershipId: membership.id,
accountId: account.id,
firstName: holder?.firstName ?? 'Prénom',
lastName: holder?.lastName ?? 'À compléter',
city: 'Nantes',
phone: '00 00 00 00 00',
},
});
const existing = await prisma.userContract.findFirst({
where: { membershipId: membership.id },
});
if (existing) continue;
await prisma.userContract.create({
data: {
accountId: account.id,
membershipId: membership.id,
locationId: spec.location,
contractType: spec.type,
startDate: new Date('2024-01-08'),
workTimeArrangement: spec.forfait ? 'FORFAIT_JOURS' : 'HOURLY',
weeklyHours: spec.forfait ? 0 : spec.hours,
forfaitDaysPerYear: spec.forfait ? 218 : null,
forfaitAgreementRef: spec.forfait ? 'CONV-2024-002' : null,
forfaitAgreedAt: spec.forfait ? new Date('2024-01-05') : null,
monthlySalary: 2100,
},
});
}
console.log(` ${contractSpecs.length} contrats`);
console.log('→ Durées de conservation');
const retention = [
['Shift', 12, 'creation', 'Décompte des horaires : 1 an minimum (matrice n° 21).'],