import { storage } from "../storage"; import { sql } from "drizzle-orm"; import { db } from "../db"; const CUSTOMER_FORM_ID = 8; export async function findCustomerByInn( inn: string, organizationId: number ): Promise { const formFields = await storage.getFormFields(CUSTOMER_FORM_ID, organizationId); const companyField = formFields.find((f) => f.type === "company"); if (!companyField || !companyField.companyAutofill) { return null; } const autofill = companyField.companyAutofill as Record; const innFieldCode = autofill["inn"]; if (!innFieldCode) return null; const innField = formFields.find((f) => f.code === innFieldCode); if (!innField) return null; const result = await db.execute(sql` SELECT t.id FROM tasks t JOIN task_field_values v ON t.id = v.task_id AND t.form_id = v.form_id WHERE t.form_id = ${CUSTOMER_FORM_ID} AND t.organization_id = ${organizationId} AND v.field_id = ${innField.id} AND LOWER(TRIM(v.value #>> '{}')) = LOWER(TRIM(${inn})) LIMIT 1 `); const rows = result.rows as Array<{ id: number }>; return rows[0]?.id ?? null; }