import { GET_BY_ENTITY_AND_ID, UPDATE } from '../../providers/mssql/queries/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 update(pool) { const access = resolveSelectedCompanyAccess(pool); const entityAccess = resolveEntityAccess(pool); /** * Updates a contact of an entity. * * @param {number} googleAuthId - The id of the Google auth user. * @param {number} entityId - The id of the entity. * @param {number} id - The id of the contact to update. * @param {object} patch - The update patch (any subset of contact fields). * @returns {Promise<{id: number, entityId: number, contactType: string, contact: string, sort: number}>} The updated contact. * @throws {Error} If the contact is not found. * * @example * const contact = await store.entitycontact.update(42, 5, 9, { contact: 'b@c.d' }); * // => { id, entityId, contactType, contact, sort } */ return async (googleAuthId, entityId, id, patch = {}) => { if (!Number.isFinite(id)) { throw new Error('Contact not found'); } const { companyId } = await access(googleAuthId); await entityAccess(companyId, entityId); const existing = await pool .request() .input('id', id) .input('entityId', entityId) .query(GET_BY_ENTITY_AND_ID); const current = existing.recordset[0]; if (!current) { throw new Error('Contact not found'); } let contactType = current.contactType; if (Object.prototype.hasOwnProperty.call(patch, 'contactType')) { contactType = patch.contactType?.trim?.() ? patch.contactType.trim() : null; } let contact = current.contact; if (Object.prototype.hasOwnProperty.call(patch, 'contact')) { contact = patch.contact?.trim?.() ? patch.contact.trim() : null; } if (!contactType || !contact) { throw new Error('Contact required'); } let sort = current.sort; if (Object.prototype.hasOwnProperty.call(patch, 'sort')) { if (!Number.isFinite(patch.sort)) { throw new Error('Invalid sort'); } sort = patch.sort; } const result = await pool .request() .input('id', id) .input('entityId', entityId) .input('contactType', contactType) .input('contact', contact) .input('sort', sort) .query(UPDATE); const row = result.recordset[0]; if (!row) { throw new Error('Contact not found'); } return shape(row); }; }