Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 7x 4x 4x 4x 4x 4x 2x 2x 2x 2x | // Data Access Layer for CRM Settings
import { eq, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { CrmSettings } from "../db/schema";
export class CrmSettingsDal {
constructor(private db: DrizzleD1Database<typeof schema>) {}
async findByProId(proId: string): Promise<CrmSettings | undefined> {
const result = await this.db
.select()
.from(schema.crmSettings)
.where(eq(schema.crmSettings.proId, proId))
.limit(1);
return result[0];
}
/**
* Race-safe upsert: INSERT OR IGNORE ensures concurrent calls don't crash,
* then UPDATE applies any provided data.
*/
async upsert(
proId: string,
data: Partial<Omit<CrmSettings, "id" | "proId">>,
): Promise<CrmSettings> {
// Atomic insert — ignores UNIQUE constraint violations from concurrent calls
await this.db.run(
sql`INSERT OR IGNORE INTO crm_settings (pro_id, kanban_header_display, auto_archive_enabled, auto_archive_won_days, auto_archive_lost_days, date_updated)
VALUES (${proId}, 'count', 0, 90, 30, unixepoch())`,
);
// If caller provided data, apply it
const hasData = Object.keys(data).length > 0;
if (hasData) {
const result = await this.db
.update(schema.crmSettings)
.set({ ...data, dateUpdated: new Date() })
.where(eq(schema.crmSettings.proId, proId))
.returning();
return result[0];
}
// Return the (possibly just-created) record
const result = await this.findByProId(proId);
// biome-ignore lint/style/noNonNullAssertion: record was just upserted above
return result!;
}
}
|