feat(worker): refund AI scan quota on definitive job failure + sanitize DLQ jobId
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { schema } from "@app/database";
|
||||
import type { WorkerContext } from "../context.js";
|
||||
|
||||
/**
|
||||
* Återbetalar AI-skanningskvot när ett skann-jobb dör definitivt.
|
||||
* Speglar consumeAiScan (api): kvot debiteras på household-ägaren (billingUser).
|
||||
* Barcode-skanningar drar ingen kvot och hoppas över. Golvat på 0.
|
||||
*/
|
||||
export async function refundAiScanForFailedJob(ctx: WorkerContext, scanJobId: string): Promise<void> {
|
||||
const [job] = await ctx.db
|
||||
.select({ userId: schema.scanJobs.userId, scanType: schema.scanJobs.scanType })
|
||||
.from(schema.scanJobs)
|
||||
.where(eq(schema.scanJobs.id, scanJobId))
|
||||
.limit(1);
|
||||
if (!job || job.scanType === "barcode") return;
|
||||
|
||||
let billingUserId = job.userId;
|
||||
const [member] = await ctx.db
|
||||
.select({ householdId: schema.householdMembers.householdId })
|
||||
.from(schema.householdMembers)
|
||||
.where(eq(schema.householdMembers.userId, job.userId))
|
||||
.orderBy(schema.householdMembers.joinedAt)
|
||||
.limit(1);
|
||||
if (member?.householdId) {
|
||||
const [owner] = await ctx.db
|
||||
.select({ userId: schema.householdMembers.userId })
|
||||
.from(schema.householdMembers)
|
||||
.where(and(eq(schema.householdMembers.householdId, member.householdId), eq(schema.householdMembers.role, "owner")))
|
||||
.limit(1);
|
||||
if (owner?.userId) billingUserId = owner.userId;
|
||||
}
|
||||
|
||||
const month = new Date().toISOString().slice(0, 7);
|
||||
await ctx.db
|
||||
.update(schema.aiUsageCounters)
|
||||
.set({ aiScans: sql`GREATEST(${schema.aiUsageCounters.aiScans} - 1, 0)` })
|
||||
.where(and(eq(schema.aiUsageCounters.userId, billingUserId), eq(schema.aiUsageCounters.month, month)));
|
||||
}
|
||||
Reference in New Issue
Block a user