u
This commit is contained in:
55
src/store/agentprinter/findOrCreate.js
Normal file
55
src/store/agentprinter/findOrCreate.js
Normal file
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
FIND_BY_COMBO as MSSQL_FIND,
|
||||
CREATE as MSSQL_CREATE,
|
||||
} from '../../providers/mssql/queries/agentprinter.js';
|
||||
import {
|
||||
FIND_BY_COMBO as SQLITE_FIND,
|
||||
CREATE as SQLITE_CREATE,
|
||||
} from '../../providers/sqlite3/queries/agentprinter.js';
|
||||
import makeRunner from '../runner.js';
|
||||
import { shape } from './_shared.js';
|
||||
|
||||
export default function findOrCreate(provider) {
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const findSql = isSqlite ? SQLITE_FIND : MSSQL_FIND;
|
||||
const createSql = isSqlite ? SQLITE_CREATE : MSSQL_CREATE;
|
||||
|
||||
/**
|
||||
* Finds or creates an agentprinter by (printeragentId, type, model, serial) combo.
|
||||
*
|
||||
* @param {number} printeragentId - The parent printer agent id.
|
||||
* @param {object} input
|
||||
* @param {string} input.type - Printer type ("zpl", "esc/pos", etc.).
|
||||
* @param {string|null} [input.model] - Discovered model name.
|
||||
* @param {string|null} [input.serial] - Discovered serial number.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{created: boolean, agentprinter: {id: number, printeragentId: number, type: string, model: string|null, serial: string|null, enabled: boolean, sort: number}}>}
|
||||
*/
|
||||
return async (printeragentId, input = {}, tx) => {
|
||||
const pId = Number(printeragentId);
|
||||
if (!Number.isInteger(pId) || pId <= 0) {
|
||||
throw new Error('Printeragent not found');
|
||||
}
|
||||
|
||||
const type = typeof input.type === 'string' && input.type.trim() ? input.type.trim().toLowerCase() : 'zpl';
|
||||
const model = input.model != null && String(input.model).trim() ? String(input.model).trim() : null;
|
||||
const serial = input.serial != null && String(input.serial).trim() ? String(input.serial).trim() : null;
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const existing = await runner.query(findSql, { printeragentId: pId, type, model, serial });
|
||||
if (existing.rows.length > 0) {
|
||||
return { created: false, agentprinter: shape(existing.rows[0]) };
|
||||
}
|
||||
|
||||
const created = await runner.query(createSql, {
|
||||
printeragentId: pId,
|
||||
type,
|
||||
model,
|
||||
serial,
|
||||
enabled: 1,
|
||||
sort: 0,
|
||||
});
|
||||
return { created: true, agentprinter: shape(created.rows[0]) };
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user