u
This commit is contained in:
@@ -87,6 +87,11 @@ export default function getBySku(provider) {
|
||||
priceId: s.priceId ?? null,
|
||||
price: s.priceId != null && s.price?.net != null ? s.price : null,
|
||||
})),
|
||||
warehouses: parseJsonArray(a.warehousesJson).map((w) => ({
|
||||
id: w.id,
|
||||
name: w.name,
|
||||
stock: Number(w.stock ?? 0),
|
||||
})),
|
||||
optionsCount: a.optionsCount,
|
||||
articleListCount: a.articleListCount,
|
||||
childCount: a.childCount,
|
||||
|
||||
@@ -10,6 +10,7 @@ export function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
manifestarticle_id: row.manifestarticle_id,
|
||||
warehouse_id: row.warehouse_id ?? null,
|
||||
transaction_type: row.transaction_type,
|
||||
amount: row.amount,
|
||||
transaction_text: row.transaction_text,
|
||||
@@ -36,6 +37,7 @@ export function computePrevHash(row) {
|
||||
const payload = JSON.stringify({
|
||||
id: row.id,
|
||||
manifestarticle_id: row.manifestarticle_id,
|
||||
warehouse_id: row.warehouse_id ?? null,
|
||||
transaction_type: row.transaction_type,
|
||||
amount: row.amount,
|
||||
transaction_text: row.transaction_text,
|
||||
@@ -52,17 +54,19 @@ export function computePrevHash(row) {
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {object} input - Ledger entry payload.
|
||||
* @param {number} input.manifestarticle_id - ID of the referenced manifest line (can also pass manifestarticleId).
|
||||
* @param {number|null} [input.warehouse_id] - Optional warehouse ID (can also pass warehouseId).
|
||||
* @param {string} input.transaction_type - Transaction type (can also pass transactionType).
|
||||
* @param {number} input.amount - Movement amount.
|
||||
* @param {string} input.transaction_text - Transaction memo/details (can also pass transactionText).
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, manifestarticle_id: number, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>} The created ledger row.
|
||||
* @returns {Promise<{id: number, manifestarticle_id: number, warehouse_id: number|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>} The created ledger row.
|
||||
* @throws {Error} If user not authorized, company not selected, manifest article not found, or input invalid.
|
||||
*
|
||||
* @example
|
||||
* const entry = await store.ledger.add(googleAuthId, {
|
||||
* manifestarticle_id: 1,
|
||||
* transaction_type: 'PAYMENT',
|
||||
* warehouse_id: 1,
|
||||
* transaction_type: 'DELIVERY',
|
||||
* amount: 100.5,
|
||||
* transaction_text: 'Invoice paid',
|
||||
* });
|
||||
@@ -75,6 +79,8 @@ export default function add(provider) {
|
||||
return async (googleAuthId, input = {}, tx) => {
|
||||
const rawManifestarticleId =
|
||||
input.manifestarticle_id ?? input.manifestarticleId;
|
||||
const rawWarehouseId =
|
||||
input.warehouse_id ?? input.warehouseId;
|
||||
const rawTransactionType =
|
||||
input.transaction_type ?? input.transactionType;
|
||||
const rawAmount = input.amount;
|
||||
@@ -86,6 +92,14 @@ export default function add(provider) {
|
||||
throw new Error('Invalid ledger entry');
|
||||
}
|
||||
|
||||
let warehouseId = null;
|
||||
if (rawWarehouseId !== undefined && rawWarehouseId !== null) {
|
||||
warehouseId = Number(rawWarehouseId);
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('Invalid ledger entry');
|
||||
}
|
||||
}
|
||||
|
||||
const transactionType =
|
||||
typeof rawTransactionType === 'string'
|
||||
? rawTransactionType.trim()
|
||||
@@ -117,12 +131,25 @@ export default function add(provider) {
|
||||
throw new Error('Manifest article not found');
|
||||
}
|
||||
|
||||
let warehouseName = null;
|
||||
if (warehouseId != null) {
|
||||
const whCheck = await runner.query(queries.CHECK_WAREHOUSE_ACCESS, {
|
||||
warehouseId,
|
||||
companyId,
|
||||
});
|
||||
if (!whCheck.rows[0]) {
|
||||
throw new Error('Warehouse not found');
|
||||
}
|
||||
warehouseName = whCheck.rows[0].name;
|
||||
}
|
||||
|
||||
const latest = await runner.query(queries.GET_LATEST_ROW);
|
||||
const prevRow = latest.rows[0];
|
||||
const prevHash = computePrevHash(prevRow);
|
||||
|
||||
const inserted = await runner.query(queries.INSERT_ROW, {
|
||||
manifestarticleId,
|
||||
warehouseId,
|
||||
transactionType,
|
||||
amount,
|
||||
transactionText,
|
||||
@@ -157,6 +184,9 @@ export default function add(provider) {
|
||||
if (manifestArticle.supplierName) {
|
||||
details.push(`Lieferant: "${manifestArticle.supplierName}"`);
|
||||
}
|
||||
if (warehouseName) {
|
||||
details.push(`Lager: "${warehouseName}"`);
|
||||
}
|
||||
if (manifestArticle.net != null && Number.isFinite(Number(manifestArticle.net))) {
|
||||
const net = Number(manifestArticle.net);
|
||||
const rebate = Number(manifestArticle.rebate ?? 0);
|
||||
@@ -174,6 +204,8 @@ export default function add(provider) {
|
||||
transactionText?.trim() ||
|
||||
(manifestArticle.manifestNumber ? `Lieferung ${manifestArticle.manifestNumber}` : 'Lieferung');
|
||||
historyText = `${base}${suffix}`;
|
||||
} else if (warehouseName && !transactionText.includes(warehouseName)) {
|
||||
historyText = `${transactionText} (Lager: "${warehouseName}")`;
|
||||
}
|
||||
|
||||
for (const match of articleMatches.rows) {
|
||||
|
||||
@@ -7,6 +7,7 @@ function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
manifestarticle_id: row.manifestarticle_id,
|
||||
warehouse_id: row.warehouse_id ?? null,
|
||||
sku: row.sku ?? null,
|
||||
transaction_type: row.transaction_type,
|
||||
amount: row.amount,
|
||||
@@ -21,18 +22,18 @@ function shape(row) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists ledger entries for a specific manifest article line, optionally filtered by transaction type.
|
||||
* Lists ledger entries for a specific manifest article line, optionally filtered by transaction type and/or warehouse.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} manifestarticleId - The id of the manifest article line.
|
||||
* @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string }.
|
||||
* @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string, warehouse_id?: number, warehouseId?: number }.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>}
|
||||
* @returns {Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>}
|
||||
* @throws {Error} If user not authorized, company not selected, or manifest article not found.
|
||||
*
|
||||
* @example
|
||||
* const entries = await store.ledger.listByManifestarticleId(googleAuthId, 42, 'PAYMENT');
|
||||
* // => [{ id, manifestarticle_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
|
||||
* const entries = await store.ledger.listByManifestarticleId(googleAuthId, 42, 'DELIVERY');
|
||||
* // => [{ id, manifestarticle_id, warehouse_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
|
||||
*/
|
||||
export default function listByManifestarticleId(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
@@ -41,6 +42,7 @@ export default function listByManifestarticleId(provider) {
|
||||
|
||||
return async (googleAuthId, manifestarticleId, optionsOrType, tx) => {
|
||||
let transactionType = null;
|
||||
let warehouseId = null;
|
||||
let explicitTx = tx;
|
||||
|
||||
if (typeof optionsOrType === 'string') {
|
||||
@@ -54,6 +56,11 @@ export default function listByManifestarticleId(provider) {
|
||||
if (typeof rawType === 'string') {
|
||||
transactionType = rawType.trim() || null;
|
||||
}
|
||||
const rawWarehouse =
|
||||
optionsOrType.warehouse_id ?? optionsOrType.warehouseId;
|
||||
if (rawWarehouse != null) {
|
||||
warehouseId = Number(rawWarehouse) || null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +85,7 @@ export default function listByManifestarticleId(provider) {
|
||||
manifestarticleId: id,
|
||||
companyId,
|
||||
transactionType: transactionType || null,
|
||||
warehouseId: warehouseId || null,
|
||||
});
|
||||
|
||||
return res.rows.map(shape);
|
||||
|
||||
@@ -7,6 +7,7 @@ function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
manifestarticle_id: row.manifestarticle_id,
|
||||
warehouse_id: row.warehouse_id ?? null,
|
||||
sku: row.sku ?? null,
|
||||
transaction_type: row.transaction_type,
|
||||
amount: row.amount,
|
||||
@@ -21,18 +22,18 @@ function shape(row) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists ledger entries for a given article SKU, optionally filtered by transaction type.
|
||||
* Lists ledger entries for a given article SKU, optionally filtered by transaction type and/or warehouse.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {string} sku - The article SKU.
|
||||
* @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string }.
|
||||
* @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string, warehouse_id?: number, warehouseId?: number }.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>}
|
||||
* @returns {Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>}
|
||||
* @throws {Error} If user not authorized, company not selected, or SKU invalid.
|
||||
*
|
||||
* @example
|
||||
* const entries = await store.ledger.listBySku(googleAuthId, 'SKU-001', 'DELIVERY');
|
||||
* // => [{ id, manifestarticle_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
|
||||
* // => [{ id, manifestarticle_id, warehouse_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
|
||||
*/
|
||||
export default function listBySku(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
@@ -41,6 +42,7 @@ export default function listBySku(provider) {
|
||||
|
||||
return async (googleAuthId, sku, optionsOrType, tx) => {
|
||||
let transactionType = null;
|
||||
let warehouseId = null;
|
||||
let explicitTx = tx;
|
||||
|
||||
if (typeof optionsOrType === 'string') {
|
||||
@@ -54,6 +56,11 @@ export default function listBySku(provider) {
|
||||
if (typeof rawType === 'string') {
|
||||
transactionType = rawType.trim() || null;
|
||||
}
|
||||
const rawWarehouse =
|
||||
optionsOrType.warehouse_id ?? optionsOrType.warehouseId;
|
||||
if (rawWarehouse != null) {
|
||||
warehouseId = Number(rawWarehouse) || null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +76,7 @@ export default function listBySku(provider) {
|
||||
sku: trimmedSku,
|
||||
companyId,
|
||||
transactionType: transactionType || null,
|
||||
warehouseId: warehouseId || null,
|
||||
});
|
||||
|
||||
return res.rows.map(shape);
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
const DEFAULT_TYPES = ['sku', 'entity', 'delivery'];
|
||||
const DEFAULT_TYPES = ['sku', 'entity', 'delivery', 'adjustment'];
|
||||
|
||||
function shape(row) {
|
||||
return {
|
||||
|
||||
111
src/store/printer/create.js
Normal file
111
src/store/printer/create.js
Normal file
@@ -0,0 +1,111 @@
|
||||
import {
|
||||
CREATE as MSSQL_CREATE,
|
||||
GET_NEXT_SORT as MSSQL_GET_NEXT_SORT,
|
||||
} from '../../providers/mssql/queries/printer.js';
|
||||
import {
|
||||
CREATE as SQLITE_CREATE,
|
||||
GET_NEXT_SORT as SQLITE_GET_NEXT_SORT,
|
||||
} from '../../providers/sqlite3/queries/printer.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
const VALID_TYPES = new Set(['esc/pos', 'zpl']);
|
||||
|
||||
function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
company_id: row.company_id ?? row.companyId,
|
||||
address: row.address,
|
||||
type: row.type,
|
||||
model: row.model ?? null,
|
||||
serial: row.serial ?? null,
|
||||
sort: row.sort,
|
||||
desc: row.desc ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function optionalString(value) {
|
||||
if (value == null || value === '') return null;
|
||||
const s = String(value).trim();
|
||||
return s || null;
|
||||
}
|
||||
|
||||
export default function create(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const getSortSql = isSqlite ? SQLITE_GET_NEXT_SORT : MSSQL_GET_NEXT_SORT;
|
||||
const createSql = isSqlite ? SQLITE_CREATE : MSSQL_CREATE;
|
||||
|
||||
/**
|
||||
* Creates a new printer for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {object} input - Printer input.
|
||||
* @param {string} input.address - Printer address (network IP/host/path).
|
||||
* @param {string} input.type - Printer type ("esc/pos" or "zpl").
|
||||
* @param {string} [input.model] - Optional printer model name.
|
||||
* @param {string} [input.serial] - Optional printer serial number.
|
||||
* @param {number} [input.sort] - Optional sort order (auto-increments if omitted).
|
||||
* @param {string} [input.desc] - Optional description.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>}
|
||||
* @throws {Error} If address is missing, type is invalid, or sort is invalid.
|
||||
*
|
||||
* @example
|
||||
* const printer = await store.printer.create(googleAuthId, {
|
||||
* address: '192.168.1.200',
|
||||
* type: 'esc/pos',
|
||||
* model: 'TM-T88VI',
|
||||
* desc: 'Bar receipt printer',
|
||||
* });
|
||||
*/
|
||||
return async (googleAuthId, input = {}, tx) => {
|
||||
const address = typeof input.address === 'string' ? input.address.trim() : '';
|
||||
if (!address) {
|
||||
throw new Error('Address required');
|
||||
}
|
||||
|
||||
const type = typeof input.type === 'string' ? input.type.trim() : '';
|
||||
if (!type || !VALID_TYPES.has(type)) {
|
||||
throw new Error('Invalid printer type: must be "esc/pos" or "zpl"');
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
let sort = input.sort;
|
||||
if (sort === undefined || sort === null) {
|
||||
const next = await runner.query(getSortSql, { companyId });
|
||||
sort = next.rows[0].sort;
|
||||
} else if (!Number.isFinite(sort)) {
|
||||
throw new Error('Invalid sort');
|
||||
}
|
||||
|
||||
const model = optionalString(input.model);
|
||||
const serial = optionalString(input.serial);
|
||||
const desc = optionalString(input.desc);
|
||||
|
||||
const result = await runner.query(createSql, {
|
||||
companyId,
|
||||
address,
|
||||
type,
|
||||
model,
|
||||
serial,
|
||||
sort,
|
||||
desc,
|
||||
});
|
||||
|
||||
const row = result.rows[0] ?? {
|
||||
id: result.insertId,
|
||||
company_id: companyId,
|
||||
address,
|
||||
type,
|
||||
model,
|
||||
serial,
|
||||
sort,
|
||||
desc,
|
||||
};
|
||||
|
||||
return shape(row);
|
||||
};
|
||||
}
|
||||
38
src/store/printer/delete.js
Normal file
38
src/store/printer/delete.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import { DELETE_BY_COMPANY_AND_ID as MSSQL_DELETE } from '../../providers/mssql/queries/printer.js';
|
||||
import { DELETE_BY_COMPANY_AND_ID as SQLITE_DELETE } from '../../providers/sqlite3/queries/printer.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
export default function del(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const sql =
|
||||
provider?.dialect === 'sqlite3' ? SQLITE_DELETE : MSSQL_DELETE;
|
||||
|
||||
/**
|
||||
* Deletes a printer for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The printer ID to delete.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<void>}
|
||||
* @throws {Error} If printer is not found.
|
||||
*/
|
||||
return async (googleAuthId, id, tx) => {
|
||||
const numericId = Number(id);
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
throw new Error('Printer not found');
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const result = await runner.query(sql, {
|
||||
id: numericId,
|
||||
companyId,
|
||||
});
|
||||
|
||||
if (!result.rowsAffected) {
|
||||
throw new Error('Printer not found');
|
||||
}
|
||||
};
|
||||
}
|
||||
53
src/store/printer/getById.js
Normal file
53
src/store/printer/getById.js
Normal file
@@ -0,0 +1,53 @@
|
||||
import { GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID } from '../../providers/mssql/queries/printer.js';
|
||||
import { GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID } from '../../providers/sqlite3/queries/printer.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
company_id: row.company_id ?? row.companyId,
|
||||
address: row.address,
|
||||
type: row.type,
|
||||
model: row.model ?? null,
|
||||
serial: row.serial ?? null,
|
||||
sort: row.sort,
|
||||
desc: row.desc ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export default function getById(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const sql =
|
||||
provider?.dialect === 'sqlite3' ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
|
||||
|
||||
/**
|
||||
* Retrieves a printer by its ID for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The printer ID.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}|undefined>}
|
||||
*
|
||||
* @example
|
||||
* const printer = await store.printer.getById(googleAuthId, 1);
|
||||
* // => { id: 1, company_id: 1, address: '192.168.1.100', type: 'esc/pos', ... }
|
||||
*/
|
||||
return async (googleAuthId, id, tx) => {
|
||||
const numericId = Number(id);
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const result = await runner.query(sql, {
|
||||
id: numericId,
|
||||
companyId,
|
||||
});
|
||||
|
||||
const row = result.rows[0];
|
||||
return row ? shape(row) : undefined;
|
||||
};
|
||||
}
|
||||
44
src/store/printer/list.js
Normal file
44
src/store/printer/list.js
Normal file
@@ -0,0 +1,44 @@
|
||||
import { LIST_BY_COMPANY as MSSQL_LIST_BY_COMPANY } from '../../providers/mssql/queries/printer.js';
|
||||
import { LIST_BY_COMPANY as SQLITE_LIST_BY_COMPANY } from '../../providers/sqlite3/queries/printer.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
company_id: row.company_id ?? row.companyId,
|
||||
address: row.address,
|
||||
type: row.type,
|
||||
model: row.model ?? null,
|
||||
serial: row.serial ?? null,
|
||||
sort: row.sort,
|
||||
desc: row.desc ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export default function list(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const sql =
|
||||
provider?.dialect === 'sqlite3'
|
||||
? SQLITE_LIST_BY_COMPANY
|
||||
: MSSQL_LIST_BY_COMPANY;
|
||||
|
||||
/**
|
||||
* Lists all printers for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<Array<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>>}
|
||||
*
|
||||
* @example
|
||||
* const printers = await store.printer.list(42);
|
||||
* // => [{ id: 1, company_id: 1, address: '192.168.1.100', type: 'esc/pos', ... }]
|
||||
*/
|
||||
return async (googleAuthId, tx) => {
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const result = await runner.query(sql, { companyId });
|
||||
return result.rows.map(shape);
|
||||
};
|
||||
}
|
||||
76
src/store/printer/order.js
Normal file
76
src/store/printer/order.js
Normal file
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
LIST_IDS_BY_COMPANY as MSSQL_LIST_IDS_BY_COMPANY,
|
||||
UPDATE_SORT as MSSQL_UPDATE_SORT,
|
||||
} from '../../providers/mssql/queries/printer.js';
|
||||
import {
|
||||
LIST_IDS_BY_COMPANY as SQLITE_LIST_IDS_BY_COMPANY,
|
||||
UPDATE_SORT as SQLITE_UPDATE_SORT,
|
||||
} from '../../providers/sqlite3/queries/printer.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
export default function order(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const listIdsSql = isSqlite
|
||||
? SQLITE_LIST_IDS_BY_COMPANY
|
||||
: MSSQL_LIST_IDS_BY_COMPANY;
|
||||
const updateSortSql = isSqlite ? SQLITE_UPDATE_SORT : MSSQL_UPDATE_SORT;
|
||||
|
||||
/**
|
||||
* Reorders the printers of the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {object} input - The reorder input.
|
||||
* @param {Array<number>} input.printerIds - The printer ids in their new order.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{printerIds: Array<number>}>} The applied order.
|
||||
* @throws {Error} If the order is invalid.
|
||||
*/
|
||||
return async (googleAuthId, { printerIds } = {}, tx) => {
|
||||
if (!Array.isArray(printerIds)) {
|
||||
throw new Error('Invalid printer order');
|
||||
}
|
||||
|
||||
const runOrder = async (runner) => {
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const items = await runner.query(listIdsSql, { companyId });
|
||||
const existing = new Set(items.rows.map((r) => r.id));
|
||||
|
||||
if (printerIds.length !== existing.size) {
|
||||
throw new Error('Invalid printer order');
|
||||
}
|
||||
|
||||
const seen = new Set();
|
||||
for (const printerId of printerIds) {
|
||||
if (
|
||||
!Number.isFinite(printerId) ||
|
||||
!existing.has(printerId) ||
|
||||
seen.has(printerId)
|
||||
) {
|
||||
throw new Error('Invalid printer order');
|
||||
}
|
||||
seen.add(printerId);
|
||||
}
|
||||
|
||||
for (let sort = 0; sort < printerIds.length; sort++) {
|
||||
await runner.query(updateSortSql, {
|
||||
id: printerIds[sort],
|
||||
companyId,
|
||||
sort,
|
||||
});
|
||||
}
|
||||
|
||||
return { printerIds };
|
||||
};
|
||||
|
||||
if (tx) {
|
||||
return runOrder(makeRunner(provider, tx));
|
||||
}
|
||||
if (typeof provider?.transaction === 'function') {
|
||||
return provider.transaction(runOrder);
|
||||
}
|
||||
return runOrder(makeRunner(provider));
|
||||
};
|
||||
}
|
||||
124
src/store/printer/update.js
Normal file
124
src/store/printer/update.js
Normal file
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID,
|
||||
UPDATE as MSSQL_UPDATE,
|
||||
} from '../../providers/mssql/queries/printer.js';
|
||||
import {
|
||||
GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID,
|
||||
UPDATE as SQLITE_UPDATE,
|
||||
} from '../../providers/sqlite3/queries/printer.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
const VALID_TYPES = new Set(['esc/pos', 'zpl']);
|
||||
|
||||
function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
company_id: row.company_id ?? row.companyId,
|
||||
address: row.address,
|
||||
type: row.type,
|
||||
model: row.model ?? null,
|
||||
serial: row.serial ?? null,
|
||||
sort: row.sort,
|
||||
desc: row.desc ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function optionalString(value) {
|
||||
if (value == null || value === '') return null;
|
||||
const s = String(value).trim();
|
||||
return s || null;
|
||||
}
|
||||
|
||||
export default function update(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const getSql = isSqlite ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
|
||||
const updateSql = isSqlite ? SQLITE_UPDATE : MSSQL_UPDATE;
|
||||
|
||||
/**
|
||||
* Updates a printer for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The printer ID to update.
|
||||
* @param {object} input - Update payload.
|
||||
* @param {string} [input.address] - The printer address.
|
||||
* @param {string} [input.type] - The printer type ("esc/pos" or "zpl").
|
||||
* @param {string|null} [input.model] - The printer model.
|
||||
* @param {string|null} [input.serial] - The printer serial.
|
||||
* @param {number} [input.sort] - The sort order.
|
||||
* @param {string|null} [input.desc] - The description.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>}
|
||||
* @throws {Error} If printer not found, address is empty, type is invalid, or sort is invalid.
|
||||
*/
|
||||
return async (googleAuthId, id, input = {}, tx) => {
|
||||
const numericId = Number(id);
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
throw new Error('Printer not found');
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const existing = await runner.query(getSql, { id: numericId, companyId });
|
||||
const current = existing.rows[0];
|
||||
if (!current) {
|
||||
throw new Error('Printer not found');
|
||||
}
|
||||
|
||||
let address = current.address;
|
||||
if (input.address !== undefined) {
|
||||
const cleaned = typeof input.address === 'string' ? input.address.trim() : '';
|
||||
if (!cleaned) {
|
||||
throw new Error('Address required');
|
||||
}
|
||||
address = cleaned;
|
||||
}
|
||||
|
||||
let type = current.type;
|
||||
if (input.type !== undefined) {
|
||||
const cleaned = typeof input.type === 'string' ? input.type.trim() : '';
|
||||
if (!cleaned || !VALID_TYPES.has(cleaned)) {
|
||||
throw new Error('Invalid printer type: must be "esc/pos" or "zpl"');
|
||||
}
|
||||
type = cleaned;
|
||||
}
|
||||
|
||||
let sort = current.sort;
|
||||
if (input.sort !== undefined) {
|
||||
if (!Number.isFinite(input.sort)) {
|
||||
throw new Error('Invalid sort');
|
||||
}
|
||||
sort = input.sort;
|
||||
}
|
||||
|
||||
const model = input.model !== undefined ? optionalString(input.model) : (current.model ?? null);
|
||||
const serial = input.serial !== undefined ? optionalString(input.serial) : (current.serial ?? null);
|
||||
const desc = input.desc !== undefined ? optionalString(input.desc) : (current.desc ?? null);
|
||||
|
||||
const result = await runner.query(updateSql, {
|
||||
id: numericId,
|
||||
companyId,
|
||||
address,
|
||||
type,
|
||||
model,
|
||||
serial,
|
||||
sort,
|
||||
desc,
|
||||
});
|
||||
|
||||
const row = result.rows[0] ?? {
|
||||
id: numericId,
|
||||
company_id: companyId,
|
||||
address,
|
||||
type,
|
||||
model,
|
||||
serial,
|
||||
sort,
|
||||
desc,
|
||||
};
|
||||
|
||||
return shape(row);
|
||||
};
|
||||
}
|
||||
190
src/store/stock/adjust.js
Normal file
190
src/store/stock/adjust.js
Normal file
@@ -0,0 +1,190 @@
|
||||
import * as mssqlQueries from '../../providers/mssql/queries/manifestDoc.js';
|
||||
import * as sqliteQueries from '../../providers/sqlite3/queries/manifestDoc.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import resolveArticleBySku from '../article/resolveArticleBySku.js';
|
||||
import nextNumber from '../numbers/nextNumber.js';
|
||||
import ledgerAdd from '../ledger/add.js';
|
||||
import makeRunner from '../runner.js';
|
||||
import { parseDate } from '../manifestLines.js';
|
||||
|
||||
const ADJUSTMENT_TYPE = 'adjustment';
|
||||
|
||||
const GET_ARTICLE_NAME_SQL = `
|
||||
SELECT at.name
|
||||
FROM article a
|
||||
LEFT JOIN articletext at ON at.article_id = a.id AND at.language_id = @languageId
|
||||
WHERE a.id = @articleId;
|
||||
`;
|
||||
|
||||
export default function adjust(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const resolveArticle = resolveArticleBySku(provider);
|
||||
const allocateNumber = nextNumber(provider);
|
||||
const addLedger = ledgerAdd(provider);
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const queries = isSqlite ? sqliteQueries : mssqlQueries;
|
||||
|
||||
/**
|
||||
* Adjusts article stock manually by creating an implicit manifest of type "adjustment",
|
||||
* allocating a number from the "adjustment" number scheme, and appending to the ledger.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {object} input - Adjustment payload.
|
||||
* @param {string} [input.sku] - Article SKU (if single-item adjustment).
|
||||
* @param {number} [input.warehouseId] - Warehouse ID (can also pass warehouse_id).
|
||||
* @param {number} [input.amount] - Signed adjustment amount (+ to add, - to remove).
|
||||
* @param {string} [input.text] - Optional adjustment reason/memo.
|
||||
* @param {string} [input.externalNumber] - Optional external reference.
|
||||
* @param {string|Date} [input.date] - Optional date (defaults to now).
|
||||
* @param {Array<object>} [input.lines] - Optional array of items to adjust in one manifest.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{manifest: {id: number, number: string, type: string, date: string, createdAt: string}, lines: Array<object>, ledger: Array<object>}>}
|
||||
*/
|
||||
return async (googleAuthId, input = {}, tx) => {
|
||||
const rawLines = Array.isArray(input.lines)
|
||||
? input.lines
|
||||
: [
|
||||
{
|
||||
sku: input.sku,
|
||||
warehouseId: input.warehouseId ?? input.warehouse_id,
|
||||
amount: input.amount,
|
||||
text: input.text ?? input.transactionText ?? input.transaction_text,
|
||||
},
|
||||
];
|
||||
|
||||
if (rawLines.length === 0) {
|
||||
throw new Error('No items to adjust');
|
||||
}
|
||||
|
||||
const defaultWarehouseId = input.warehouseId ?? input.warehouse_id;
|
||||
const defaultText = input.text ?? input.transactionText ?? input.transaction_text;
|
||||
const externalNumber = input.externalNumber?.trim?.() ? input.externalNumber.trim() : null;
|
||||
const date = input.date ? parseDate(input.date) ?? new Date() : new Date();
|
||||
const createdAt = new Date();
|
||||
|
||||
const normalizedLines = rawLines.map((line, idx) => {
|
||||
const sku = typeof line.sku === 'string' ? line.sku.trim() : '';
|
||||
if (!sku) {
|
||||
throw new Error(`SKU required for item ${idx + 1}`);
|
||||
}
|
||||
|
||||
const rawWhId = line.warehouseId ?? line.warehouse_id ?? defaultWarehouseId;
|
||||
const warehouseId = Number(rawWhId);
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error(`Warehouse required for item ${idx + 1} (${sku})`);
|
||||
}
|
||||
|
||||
const amount = Number(line.amount);
|
||||
if (!Number.isFinite(amount) || amount === 0) {
|
||||
throw new Error(`Invalid amount for item ${idx + 1} (${sku}): must be non-zero number`);
|
||||
}
|
||||
|
||||
const text = (line.text ?? line.transactionText ?? line.transaction_text ?? defaultText)?.trim?.() ||
|
||||
(amount > 0 ? `Manual stock addition (+${amount})` : `Manual stock removal (${amount})`);
|
||||
|
||||
return {
|
||||
sku,
|
||||
warehouseId,
|
||||
amount,
|
||||
text,
|
||||
};
|
||||
});
|
||||
|
||||
const run = async (runner, activeTx) => {
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
// Validate all articles exist and belong to the user's company
|
||||
const resolvedArticles = [];
|
||||
for (const item of normalizedLines) {
|
||||
const resolved = await resolveArticle(googleAuthId, item.sku, activeTx);
|
||||
const nameRes = await runner.query(GET_ARTICLE_NAME_SQL, {
|
||||
articleId: resolved.articleId,
|
||||
languageId: resolved.languageId,
|
||||
});
|
||||
const articleName = nameRes.rows[0]?.name ?? item.sku;
|
||||
resolvedArticles.push({ ...item, ...resolved, articleName });
|
||||
}
|
||||
|
||||
// Allocate unique adjustment number using the dedicated adjustment number scheme
|
||||
const number = await allocateNumber(companyId, ADJUSTMENT_TYPE, activeTx);
|
||||
|
||||
// Create the implicit adjustment manifest
|
||||
const manifestRes = await runner.query(queries.CREATE_MANIFEST, {
|
||||
companyId,
|
||||
number,
|
||||
type: ADJUSTMENT_TYPE,
|
||||
entityId: null,
|
||||
externalNumber,
|
||||
date,
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const manifestId = manifestRes.rows[0]?.id ?? manifestRes.insertId;
|
||||
|
||||
const createdLines = [];
|
||||
const createdLedgerEntries = [];
|
||||
|
||||
for (const item of resolvedArticles) {
|
||||
// Create manifestarticle row
|
||||
const lineRes = await runner.query(queries.CREATE_LINE, {
|
||||
manifestId,
|
||||
sku: item.sku,
|
||||
name: item.articleName,
|
||||
pu: 1,
|
||||
amount: Math.abs(item.amount),
|
||||
net: 0,
|
||||
comment: item.text,
|
||||
rebate: 0,
|
||||
taxrate: 0,
|
||||
});
|
||||
|
||||
const manifestarticleId = lineRes.rows[0]?.id ?? lineRes.insertId;
|
||||
|
||||
// Append to ledger
|
||||
const ledgerRow = await addLedger(
|
||||
googleAuthId,
|
||||
{
|
||||
manifestarticle_id: manifestarticleId,
|
||||
warehouse_id: item.warehouseId,
|
||||
transaction_type: ADJUSTMENT_TYPE,
|
||||
amount: item.amount,
|
||||
transaction_text: item.text,
|
||||
},
|
||||
activeTx,
|
||||
);
|
||||
|
||||
createdLines.push({
|
||||
manifestarticle_id: manifestarticleId,
|
||||
sku: item.sku,
|
||||
name: item.articleName,
|
||||
warehouse_id: item.warehouseId,
|
||||
amount: item.amount,
|
||||
text: item.text,
|
||||
});
|
||||
|
||||
createdLedgerEntries.push(ledgerRow);
|
||||
}
|
||||
|
||||
return {
|
||||
manifest: {
|
||||
id: manifestId,
|
||||
number,
|
||||
type: ADJUSTMENT_TYPE,
|
||||
date: date.toISOString(),
|
||||
createdAt: createdAt.toISOString(),
|
||||
externalNumber,
|
||||
},
|
||||
lines: createdLines,
|
||||
ledger: createdLedgerEntries,
|
||||
};
|
||||
};
|
||||
|
||||
if (tx) {
|
||||
return run(makeRunner(provider, tx), tx);
|
||||
}
|
||||
if (typeof provider?.transaction === 'function') {
|
||||
return provider.transaction((runner, activeTx) => run(runner, activeTx));
|
||||
}
|
||||
return run(makeRunner(provider));
|
||||
};
|
||||
}
|
||||
59
src/store/warehouse/create.js
Normal file
59
src/store/warehouse/create.js
Normal file
@@ -0,0 +1,59 @@
|
||||
import { CREATE as MSSQL_CREATE } from '../../providers/mssql/queries/warehouse.js';
|
||||
import { CREATE as SQLITE_CREATE } from '../../providers/sqlite3/queries/warehouse.js';
|
||||
import { isUniqueConstraintError } from '../../providers/provider.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
function shape(row) {
|
||||
return { id: row.id, name: row.name };
|
||||
}
|
||||
|
||||
export default function create(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const sql =
|
||||
provider?.dialect === 'sqlite3' ? SQLITE_CREATE : MSSQL_CREATE;
|
||||
|
||||
/**
|
||||
* Creates a new warehouse for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {object} input - Warehouse input.
|
||||
* @param {string} input.name - The warehouse name.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, name: string}>} The created warehouse.
|
||||
* @throws {Error} If name is missing or already exists.
|
||||
*
|
||||
* @example
|
||||
* const wh = await store.warehouse.create(googleAuthId, { name: 'Hauptlager' });
|
||||
* // => { id: 1, name: 'Hauptlager' }
|
||||
*/
|
||||
return async (googleAuthId, { name } = {}, tx) => {
|
||||
const cleaned = typeof name === 'string' ? name.trim() : '';
|
||||
if (!cleaned) {
|
||||
throw new Error('Name required');
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
try {
|
||||
const result = await runner.query(sql, {
|
||||
companyId,
|
||||
name: cleaned,
|
||||
});
|
||||
|
||||
const row = result.rows[0] ?? { id: result.insertId, name: cleaned };
|
||||
return shape(row);
|
||||
} catch (err) {
|
||||
if (
|
||||
isUniqueConstraintError(err) ||
|
||||
err?.number === 2627 ||
|
||||
err?.number === 2601 ||
|
||||
err?.code === 'SQLITE_CONSTRAINT_UNIQUE'
|
||||
) {
|
||||
throw new Error('Warehouse already exists');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
62
src/store/warehouse/delete.js
Normal file
62
src/store/warehouse/delete.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
DELETE_BY_COMPANY_AND_ID as MSSQL_DELETE,
|
||||
CHECK_LEDGER_USAGE as MSSQL_CHECK_USAGE,
|
||||
} from '../../providers/mssql/queries/warehouse.js';
|
||||
import {
|
||||
DELETE_BY_COMPANY_AND_ID as SQLITE_DELETE,
|
||||
CHECK_LEDGER_USAGE as SQLITE_CHECK_USAGE,
|
||||
} from '../../providers/sqlite3/queries/warehouse.js';
|
||||
import { isForeignKeyConstraintError } from '../../providers/provider.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
export default function del(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const deleteSql = isSqlite ? SQLITE_DELETE : MSSQL_DELETE;
|
||||
const checkUsageSql = isSqlite ? SQLITE_CHECK_USAGE : MSSQL_CHECK_USAGE;
|
||||
|
||||
/**
|
||||
* Deletes a warehouse for the user's selected company, unless referenced in the ledger.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The warehouse ID to delete.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<void>}
|
||||
* @throws {Error} If warehouse not found or is in use in the ledger.
|
||||
*
|
||||
* @example
|
||||
* await store.warehouse.delete(googleAuthId, 1);
|
||||
*/
|
||||
return async (googleAuthId, id, tx) => {
|
||||
const numericId = Number(id);
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
throw new Error('Warehouse not found');
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
// Pre-check if warehouse is referenced in the ledger
|
||||
const usage = await runner.query(checkUsageSql, { warehouseId: numericId });
|
||||
if (usage.rows && usage.rows.length > 0) {
|
||||
throw new Error('Warehouse in use in ledger');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await runner.query(deleteSql, {
|
||||
id: numericId,
|
||||
companyId,
|
||||
});
|
||||
|
||||
if (!result.rowsAffected) {
|
||||
throw new Error('Warehouse not found');
|
||||
}
|
||||
} catch (err) {
|
||||
if (isForeignKeyConstraintError(err)) {
|
||||
throw new Error('Warehouse in use in ledger');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
44
src/store/warehouse/getById.js
Normal file
44
src/store/warehouse/getById.js
Normal file
@@ -0,0 +1,44 @@
|
||||
import { GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID } from '../../providers/mssql/queries/warehouse.js';
|
||||
import { GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID } from '../../providers/sqlite3/queries/warehouse.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
function shape(row) {
|
||||
return { id: row.id, name: row.name };
|
||||
}
|
||||
|
||||
export default function getById(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const sql =
|
||||
provider?.dialect === 'sqlite3' ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
|
||||
|
||||
/**
|
||||
* Retrieves a warehouse by its ID for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The warehouse ID.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, name: string}|undefined>} The warehouse or undefined.
|
||||
*
|
||||
* @example
|
||||
* const wh = await store.warehouse.getById(googleAuthId, 1);
|
||||
* // => { id: 1, name: 'Hauptlager' }
|
||||
*/
|
||||
return async (googleAuthId, id, tx) => {
|
||||
const numericId = Number(id);
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const result = await runner.query(sql, {
|
||||
id: numericId,
|
||||
companyId,
|
||||
});
|
||||
|
||||
const row = result.rows[0];
|
||||
return row ? shape(row) : undefined;
|
||||
};
|
||||
}
|
||||
33
src/store/warehouse/list.js
Normal file
33
src/store/warehouse/list.js
Normal file
@@ -0,0 +1,33 @@
|
||||
import { LIST_BY_COMPANY as MSSQL_LIST } from '../../providers/mssql/queries/warehouse.js';
|
||||
import { LIST_BY_COMPANY as SQLITE_LIST } from '../../providers/sqlite3/queries/warehouse.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
function shape(row) {
|
||||
return { id: row.id, name: row.name };
|
||||
}
|
||||
|
||||
export default function list(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const sql =
|
||||
provider?.dialect === 'sqlite3' ? SQLITE_LIST : MSSQL_LIST;
|
||||
|
||||
/**
|
||||
* Lists all warehouses for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<Array<{id: number, name: string}>>} List of warehouses.
|
||||
*
|
||||
* @example
|
||||
* const warehouses = await store.warehouse.list(googleAuthId);
|
||||
* // => [{ id: 1, name: 'Hauptlager' }]
|
||||
*/
|
||||
return async (googleAuthId, tx) => {
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const result = await runner.query(sql, { companyId });
|
||||
return result.rows.map(shape);
|
||||
};
|
||||
}
|
||||
77
src/store/warehouse/update.js
Normal file
77
src/store/warehouse/update.js
Normal file
@@ -0,0 +1,77 @@
|
||||
import {
|
||||
GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID,
|
||||
UPDATE_BY_ID as MSSQL_UPDATE,
|
||||
} from '../../providers/mssql/queries/warehouse.js';
|
||||
import {
|
||||
GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID,
|
||||
UPDATE_BY_ID as SQLITE_UPDATE,
|
||||
} from '../../providers/sqlite3/queries/warehouse.js';
|
||||
import { isUniqueConstraintError } from '../../providers/provider.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
function shape(row) {
|
||||
return { id: row.id, name: row.name };
|
||||
}
|
||||
|
||||
export default function update(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const getSql = isSqlite ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
|
||||
const updateSql = isSqlite ? SQLITE_UPDATE : MSSQL_UPDATE;
|
||||
|
||||
/**
|
||||
* Updates a warehouse name for the user's selected company.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The warehouse ID to update.
|
||||
* @param {object} input - Update payload.
|
||||
* @param {string} input.name - The new warehouse name.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, name: string}>} The updated warehouse.
|
||||
* @throws {Error} If warehouse not found, name is missing, or name already exists.
|
||||
*
|
||||
* @example
|
||||
* const updated = await store.warehouse.update(googleAuthId, 1, { name: 'Zentrallager' });
|
||||
* // => { id: 1, name: 'Zentrallager' }
|
||||
*/
|
||||
return async (googleAuthId, id, { name } = {}, tx) => {
|
||||
const numericId = Number(id);
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
throw new Error('Warehouse not found');
|
||||
}
|
||||
|
||||
const cleaned = typeof name === 'string' ? name.trim() : '';
|
||||
if (!cleaned) {
|
||||
throw new Error('Name required');
|
||||
}
|
||||
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const existing = await runner.query(getSql, { id: numericId, companyId });
|
||||
if (!existing.rows[0]) {
|
||||
throw new Error('Warehouse not found');
|
||||
}
|
||||
|
||||
try {
|
||||
await runner.query(updateSql, {
|
||||
id: numericId,
|
||||
companyId,
|
||||
name: cleaned,
|
||||
});
|
||||
|
||||
return shape({ id: numericId, name: cleaned });
|
||||
} catch (err) {
|
||||
if (
|
||||
isUniqueConstraintError(err) ||
|
||||
err?.number === 2627 ||
|
||||
err?.number === 2601 ||
|
||||
err?.code === 'SQLITE_CONSTRAINT_UNIQUE'
|
||||
) {
|
||||
throw new Error('Warehouse already exists');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user