Add entity address/contact tables and CRUD for entity resources
This commit is contained in:
67
src/store/entitycontact/update.js
Normal file
67
src/store/entitycontact/update.js
Normal file
@@ -0,0 +1,67 @@
|
||||
import { GET_BY_ENTITY_AND_ID, UPDATE } from '../../sql/entitycontact.js';
|
||||
import resolveCompanyAccess from '../companyuser/resolveCompanyAccess.js';
|
||||
import resolveEntityAccess from '../entity/resolveEntityAccess.js';
|
||||
|
||||
function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
entityId: row.entityId,
|
||||
contactType: row.contactType,
|
||||
contact: row.contact,
|
||||
};
|
||||
}
|
||||
|
||||
export default function update(pool) {
|
||||
const access = resolveCompanyAccess(pool);
|
||||
const entityAccess = resolveEntityAccess(pool);
|
||||
|
||||
return async (googleAuthId, companyId, entityId, id, patch = {}) => {
|
||||
if (!Number.isFinite(id)) {
|
||||
throw new Error('Contact not found');
|
||||
}
|
||||
|
||||
await access(googleAuthId, companyId);
|
||||
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');
|
||||
}
|
||||
|
||||
const result = await pool
|
||||
.request()
|
||||
.input('id', id)
|
||||
.input('entityId', entityId)
|
||||
.input('contactType', contactType)
|
||||
.input('contact', contact)
|
||||
.query(UPDATE);
|
||||
|
||||
const row = result.recordset[0];
|
||||
if (!row) {
|
||||
throw new Error('Contact not found');
|
||||
}
|
||||
return shape(row);
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user