78 lines
2.7 KiB
JavaScript
78 lines
2.7 KiB
JavaScript
import { CREATE as MSSQL_CREATE } from '../../providers/mssql/queries/entity.js';
|
|
import { CREATE as SQLITE_CREATE } from '../../providers/sqlite3/queries/entity.js';
|
|
import { INSERT as MSSQL_INSERT_HISTORY } from '../../providers/mssql/queries/entityhistory.js';
|
|
import { INSERT as SQLITE_INSERT_HISTORY } from '../../providers/sqlite3/queries/entityhistory.js';
|
|
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
|
import ensureLieferantenGroup from './ensureLieferantenGroup.js';
|
|
import makeRunner from '../runner.js';
|
|
|
|
export default function create(provider) {
|
|
const access = resolveSelectedCompanyAccess(provider);
|
|
const isSqlite = provider?.dialect === 'sqlite3';
|
|
const createSql = isSqlite ? SQLITE_CREATE : MSSQL_CREATE;
|
|
const insertHistorySql = isSqlite
|
|
? SQLITE_INSERT_HISTORY
|
|
: MSSQL_INSERT_HISTORY;
|
|
|
|
/**
|
|
* 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.
|
|
* @param {object} [tx] - Optional transaction to run within.
|
|
* @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 } = {}, tx) => {
|
|
const cleaned = name?.trim();
|
|
if (!cleaned) {
|
|
throw new Error('Name required');
|
|
}
|
|
|
|
const runCreate = async (runner) => {
|
|
const { companyId, companyuserId } = await access(googleAuthId, runner);
|
|
const customergroupId = await ensureLieferantenGroup(provider, companyId, runner);
|
|
|
|
const created = await runner.query(createSql, {
|
|
customergroupId,
|
|
firstName: null,
|
|
name: cleaned,
|
|
number: null,
|
|
});
|
|
|
|
const row = created.rows[0] ?? {
|
|
id: created.insertId,
|
|
name: cleaned,
|
|
createdAt: new Date().toISOString(),
|
|
updatedAt: new Date().toISOString(),
|
|
};
|
|
|
|
await runner.query(insertHistorySql, {
|
|
entityId: row.id,
|
|
companyuserId,
|
|
text: 'Erstellt',
|
|
});
|
|
|
|
return {
|
|
id: row.id,
|
|
name: row.name,
|
|
createdAt: row.createdAt,
|
|
updatedAt: row.updatedAt,
|
|
};
|
|
};
|
|
|
|
if (tx) {
|
|
return runCreate(makeRunner(provider, tx));
|
|
}
|
|
if (typeof provider?.transaction === 'function') {
|
|
return provider.transaction(runCreate);
|
|
}
|
|
return runCreate(makeRunner(provider));
|
|
};
|
|
}
|