import { CREATE } from '../../providers/mssql/queries/entity.js'; import { INSERT as INSERT_HISTORY } from '../../providers/mssql/queries/entityhistory.js'; import request from '../request.js'; import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js'; import ensureLieferantenGroup from './ensureLieferantenGroup.js'; export default function create(pool) { const access = resolveSelectedCompanyAccess(pool); /** * Creates a new supplier for the user's selected company, recording history. * * @param {number} googleAuthId - The id of the Google auth user. * @param {object} input - The supplier input. * @param {string} input.name - The supplier name. * @returns {Promise<{id: number, name: string, createdAt: string, updatedAt: string}>} The created supplier. * @throws {Error} If the name is empty. * * @example * const supplier = await store.supplier.create(42, { name: 'Acme Supplies' }); * // => { id, name, createdAt, updatedAt } */ return async (googleAuthId, { name } = {}) => { const cleaned = name?.trim(); if (!cleaned) { throw new Error('Name required'); } const { companyId, companyuserId } = await access(googleAuthId); const tx = pool.transaction(); await tx.begin(); try { const customergroupId = await ensureLieferantenGroup(pool, companyId, tx); const created = await request(pool, tx) .input('customergroupId', customergroupId) .input('firstName', null) .input('name', cleaned) .input('number', null) .query(CREATE); const row = created.recordset[0]; await request(pool, tx) .input('entityId', row.id) .input('companyuserId', companyuserId) .input('text', 'Erstellt') .query(INSERT_HISTORY); await tx.commit(); return { id: row.id, name: row.name, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } catch (err) { try { await tx.rollback(); } catch { // ignore } throw err; } }; }