mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix: retain import actor attribution
Persist record and actor identities through job completion.\nWrite one bounded transactional completion audit per job.
This commit is contained in:
1 parent
adb932052c
commit
620817b10b
19 files changed
+211
-63
No files matched your search
+10
-2
@@ -49,16 +49,24 @@ export async function auditLog(
|
||||
action: string,
|
||||
opts: {
|
||||
userId?: string | null;
|
||||
/** Explicit worker attribution when no request context remains. */
|
||||
actorUserId?: string | null;
|
||||
/** Use the active transaction when the audit must commit atomically. */
|
||||
client?: Pick<typeof prisma, "auditLog">;
|
||||
details?: Record<string, unknown>;
|
||||
ipAddress?: string | null;
|
||||
} = {},
|
||||
) {
|
||||
const userId = opts.userId ?? null;
|
||||
const entry = await prisma.auditLog.create({
|
||||
const client = opts.client ?? prisma;
|
||||
const entry = await client.auditLog.create({
|
||||
data: {
|
||||
action,
|
||||
userId,
|
||||
actorUserId: actingActorFor(userId),
|
||||
actorUserId:
|
||||
opts.actorUserId === undefined
|
||||
? actingActorFor(userId)
|
||||
: opts.actorUserId,
|
||||
details: opts.details ? JSON.stringify(opts.details) : null,
|
||||
ipAddress: opts.ipAddress ?? null,
|
||||
},
|
||||
|
||||
@@ -125,13 +125,14 @@ describe("medication intake import worker bounds", () => {
|
||||
medicationIntakeImportJob: {
|
||||
findUnique: async () => ({
|
||||
id: "job-many-days",
|
||||
userId: "user-1",
|
||||
recordUserId: "user-1",
|
||||
actorUserId: "user-1",
|
||||
medicationId: "medication-1",
|
||||
status,
|
||||
payload: { entries: [] },
|
||||
progress: persistedProgress,
|
||||
startedAt: new Date(),
|
||||
user: { timezone: "UTC" },
|
||||
recordUser: { timezone: "UTC" },
|
||||
}),
|
||||
update: async (args: {
|
||||
data: { progress?: unknown; status?: string };
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Job, JobWithMetadata } from "pg-boss";
|
||||
import { Prisma, type PrismaClient } from "@/generated/prisma/client";
|
||||
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma, toJson } from "@/lib/db";
|
||||
import { jobDone, type JobOutcome } from "@/lib/jobs/job-outcome";
|
||||
import { consumeImportedIntakesBatch } from "@/lib/medications/inventory/consumption";
|
||||
@@ -584,14 +585,14 @@ async function processNextChunk(
|
||||
|
||||
const row = await tx.medicationIntakeImportJob.findUnique({
|
||||
where: { id: jobId },
|
||||
include: { user: { select: { timezone: true } } },
|
||||
include: { recordUser: { select: { timezone: true } } },
|
||||
});
|
||||
if (!row || row.status === "done" || row.status === "failed") {
|
||||
return {
|
||||
terminal: true,
|
||||
finalized: false,
|
||||
result: null,
|
||||
userId: row?.userId ?? null,
|
||||
userId: row?.recordUserId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -604,9 +605,9 @@ async function processNextChunk(
|
||||
);
|
||||
await recomputeTouchedDays(
|
||||
tx,
|
||||
row.userId,
|
||||
row.recordUserId,
|
||||
row.medicationId,
|
||||
row.user.timezone,
|
||||
row.recordUser.timezone,
|
||||
rollupDays,
|
||||
);
|
||||
const finalizedProgress: MedicationImportProgress = {
|
||||
@@ -629,7 +630,7 @@ async function processNextChunk(
|
||||
terminal: false,
|
||||
finalized: false,
|
||||
result: null,
|
||||
userId: row.userId,
|
||||
userId: row.recordUserId,
|
||||
};
|
||||
}
|
||||
const result: MedicationImportResult = {
|
||||
@@ -644,18 +645,17 @@ async function processNextChunk(
|
||||
: { skippedDetailsOmitted: progress.skippedDetailsOmitted }),
|
||||
};
|
||||
const completedAt = new Date();
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
userId: row.userId,
|
||||
action: "medication.intake.import",
|
||||
details: JSON.stringify({
|
||||
jobId: row.id,
|
||||
medicationId: row.medicationId,
|
||||
imported: result.imported,
|
||||
skipped: result.skipped,
|
||||
skipReasons: result.skipReasons,
|
||||
total: progress.total,
|
||||
}),
|
||||
await auditLog("medication.intake.import", {
|
||||
client: tx,
|
||||
userId: row.recordUserId,
|
||||
actorUserId: row.actorUserId,
|
||||
details: {
|
||||
jobId: row.id,
|
||||
recordUserId: row.recordUserId,
|
||||
actorUserId: row.actorUserId,
|
||||
imported: result.imported,
|
||||
skipped: result.skipped,
|
||||
total: progress.total,
|
||||
},
|
||||
});
|
||||
await tx.medicationIntakeImportJob.update({
|
||||
@@ -673,7 +673,7 @@ async function processNextChunk(
|
||||
terminal: true,
|
||||
finalized: true,
|
||||
result,
|
||||
userId: row.userId,
|
||||
userId: row.recordUserId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -714,7 +714,7 @@ async function processNextChunk(
|
||||
const takenAt =
|
||||
entry.takenAt === null ? null : new Date(entry.takenAt);
|
||||
return {
|
||||
userId: row.userId,
|
||||
userId: row.recordUserId,
|
||||
medicationId: resolveMedicationId(entry),
|
||||
// The scheduled slot and the time taken are two separate facts, and
|
||||
// the export states both. Writing the take into both columns — which
|
||||
@@ -774,7 +774,7 @@ async function processNextChunk(
|
||||
for (const [medicationId, events] of consumedByMedication) {
|
||||
await consumeImportedIntakesBatch({
|
||||
client: tx,
|
||||
userId: row.userId,
|
||||
userId: row.recordUserId,
|
||||
medicationId,
|
||||
events,
|
||||
});
|
||||
@@ -783,7 +783,7 @@ async function processNextChunk(
|
||||
const touchedDays = created.map((event) =>
|
||||
encodeTouchedDay(
|
||||
event.medicationId,
|
||||
dayKeyForScheduledFor(event.scheduledFor, row.user.timezone),
|
||||
dayKeyForScheduledFor(event.scheduledFor, row.recordUser.timezone),
|
||||
),
|
||||
);
|
||||
// Two different facts, counted apart. The Map collapse above is entries
|
||||
@@ -818,7 +818,7 @@ async function processNextChunk(
|
||||
terminal: false,
|
||||
finalized: false,
|
||||
result: null,
|
||||
userId: row.userId,
|
||||
userId: row.recordUserId,
|
||||
};
|
||||
},
|
||||
{ timeout: 60_000 },
|
||||
|
||||
@@ -33,7 +33,8 @@ import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma, toJson } from "@/lib/db";
|
||||
|
||||
export interface IntakeImportAdmissionInput {
|
||||
userId: string;
|
||||
recordUserId: string;
|
||||
actorUserId: string;
|
||||
/** `null` = the account-wide dose-history import. */
|
||||
medicationId: string | null;
|
||||
payload: MedicationImportPayload;
|
||||
@@ -60,7 +61,8 @@ export type IntakeImportAdmission =
|
||||
* submissions serialise against each other without blocking an unrelated one.
|
||||
*/
|
||||
export async function admitIntakeImportJob({
|
||||
userId,
|
||||
recordUserId,
|
||||
actorUserId,
|
||||
medicationId,
|
||||
payload,
|
||||
progress,
|
||||
@@ -71,7 +73,7 @@ export async function admitIntakeImportJob({
|
||||
await tx.$queryRaw`
|
||||
SELECT "id"
|
||||
FROM "users"
|
||||
WHERE "id" = ${userId}
|
||||
WHERE "id" = ${recordUserId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
} else {
|
||||
@@ -79,7 +81,7 @@ export async function admitIntakeImportJob({
|
||||
SELECT "id"
|
||||
FROM "medications"
|
||||
WHERE "id" = ${medicationId}
|
||||
AND "user_id" = ${userId}
|
||||
AND "user_id" = ${recordUserId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
}
|
||||
@@ -94,7 +96,7 @@ export async function admitIntakeImportJob({
|
||||
// heartbeat, after the start, and before either.
|
||||
await tx.medicationIntakeImportJob.updateMany({
|
||||
where: {
|
||||
userId,
|
||||
recordUserId,
|
||||
medicationId,
|
||||
status: { in: ["queued", "running"] },
|
||||
OR: [
|
||||
@@ -117,7 +119,7 @@ export async function admitIntakeImportJob({
|
||||
|
||||
const activeJob = await tx.medicationIntakeImportJob.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
recordUserId,
|
||||
medicationId,
|
||||
status: { in: ["queued", "running"] },
|
||||
},
|
||||
@@ -127,7 +129,8 @@ export async function admitIntakeImportJob({
|
||||
|
||||
const importJob = await tx.medicationIntakeImportJob.create({
|
||||
data: {
|
||||
userId,
|
||||
recordUserId,
|
||||
actorUserId,
|
||||
medicationId,
|
||||
status: "queued",
|
||||
payload: toJson(payload),
|
||||
@@ -169,7 +172,8 @@ export async function admitIntakeImportJob({
|
||||
},
|
||||
});
|
||||
await auditLog("medication.intake.import.kickoff.denied", {
|
||||
userId,
|
||||
userId: recordUserId,
|
||||
actorUserId,
|
||||
ipAddress,
|
||||
details: {
|
||||
jobId,
|
||||
|
||||
@@ -109,18 +109,18 @@ export function projectMedicationImportResult(
|
||||
* Read one job the caller owns, or `null`.
|
||||
*
|
||||
* `medicationId` narrows to a job scoped to that medication; omit it for the
|
||||
* account-wide import. `userId` is always in the `where`, so a job id belonging
|
||||
* account-wide import. `recordUserId` is always in the `where`, so a job id belonging
|
||||
* to somebody else is a 404 and not a leak.
|
||||
*/
|
||||
export async function readMedicationIntakeImportJob(
|
||||
userId: string,
|
||||
recordUserId: string,
|
||||
jobId: string,
|
||||
medicationId?: string,
|
||||
): Promise<MedicationIntakeImportJobStatus | null> {
|
||||
const row = await prisma.medicationIntakeImportJob.findFirst({
|
||||
where: {
|
||||
id: jobId,
|
||||
userId,
|
||||
recordUserId,
|
||||
// An account-wide job carries no medication, and asking for one by id must
|
||||
// not resolve to the other kind. `null` is the explicit narrowing.
|
||||
medicationId: medicationId ?? null,
|
||||
|
||||
Reference in new issue
Block a user