import { CREATE, GET_NEXT_SORT } from '../../sql/entitycontact.js'; import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js'; import resolveEntityAccess from '../entity/resolveEntityAccess.js'; function shape(row) { return { id: row.id, entityId: row.entityId, contactType: row.contactType, contact: row.contact, sort: row.sort, }; } export default function create(pool) { const access = resolveSelectedCompanyAccess(pool); const entityAccess = resolveEntityAccess(pool); /** * Creates a new contact for an entity. * * @param {number} googleAuthId - The id of the Google auth user. * @param {number} entityId - The id of the entity. * @param {object} input - The contact input. * @param {string} input.contactType - The contact type (e.g. `'email'`). * @param {string} input.contact - The contact value. * @param {number} [input.sort] - Optional sort order. * @returns {Promise<{id: number, entityId: number, contactType: string, contact: string, sort: number}>} The created contact. * @throws {Error} If the contact type or value is missing. * * @example * const contact = await store.entitycontact.create(42, 5, { contactType: 'email', contact: 'a@b.c' }); * // => { id, entityId, contactType, contact, sort } */ return async (googleAuthId, entityId, input = {}) => { const contactType = input.contactType?.trim?.() ? input.contactType.trim() : null; const contact = input.contact?.trim?.() ? input.contact.trim() : null; if (!contactType || !contact) { throw new Error('Contact required'); } const { companyId } = await access(googleAuthId); await entityAccess(companyId, entityId); let sort = input.sort; if (sort === undefined || sort === null) { const next = await pool .request() .input('entityId', entityId) .query(GET_NEXT_SORT); sort = next.recordset[0].sort; } else if (!Number.isFinite(sort)) { throw new Error('Invalid sort'); } const result = await pool .request() .input('entityId', entityId) .input('contactType', contactType) .input('contact', contact) .input('sort', sort) .query(CREATE); return shape(result.recordset[0]); }; }