This commit is contained in:
seb
2026-09-27 21:01:30 +02:00
parent f9c570a036
commit 0cafa11a32
34 changed files with 2010 additions and 1534 deletions

View File

@@ -28,6 +28,7 @@ import articleSetPricesBySku from './store/article/setPricesBySku.js';
import articleSetEansBySku from './store/article/setEansBySku.js';
import articleSetBrandIdBySku from './store/article/setBrandIdBySku.js';
import articleSetWeightBySku from './store/article/setWeightBySku.js';
import articleSetTrackStockBySku from './store/article/setTrackStockBySku.js';
import articleSetCategoryIdsBySku from './store/article/setCategoryIdsBySku.js';
import articleSetFatherBySku from './store/article/setFatherBySku.js';
import articleImportRows from './store/article/importRows.js';
@@ -131,6 +132,7 @@ import warehouseGetById from './store/warehouse/getById.js';
import warehouseList from './store/warehouse/list.js';
import warehouseUpdate from './store/warehouse/update.js';
import warehouseDelete from './store/warehouse/delete.js';
import warehouseOrder from './store/warehouse/order.js';
import printerCreate from './store/printer/create.js';
import printerGetById from './store/printer/getById.js';
import printerList from './store/printer/list.js';
@@ -194,6 +196,7 @@ export default class LibDashStore {
setEansBySku: articleSetEansBySku(provider),
setBrandIdBySku: articleSetBrandIdBySku(provider),
setWeightBySku: articleSetWeightBySku(provider),
setTrackStockBySku: articleSetTrackStockBySku(provider),
setCategoryIdsBySku: articleSetCategoryIdsBySku(provider),
setFatherBySku: articleSetFatherBySku(provider),
importRows: articleImportRows(provider),
@@ -362,6 +365,7 @@ export default class LibDashStore {
list: warehouseList(provider),
update: warehouseUpdate(provider),
delete: warehouseDelete(provider),
order: warehouseOrder(provider),
};
this.printer = {

View File

@@ -31,6 +31,7 @@ export const ARTICLE_LIST_COLUMNS = `
at.slug,
pr.net,
t.rate AS taxRate,
a.track_stock,
CASE
WHEN a.optionslist_id IS NOT NULL THEN (
SELECT COUNT(*)
@@ -133,6 +134,12 @@ SET weight = @weight
WHERE id = @articleId
`;
export const UPDATE_TRACK_STOCK = `
UPDATE article
SET track_stock = @trackStock
WHERE id = @articleId
`;
export const UPDATE_BRAND = `
UPDATE article
SET brand_id = @brandId
@@ -158,9 +165,9 @@ WHERE id = @articleId
`;
export const CREATE = `
INSERT INTO article (company_id, sku, unit_id, unitamount, weight)
INSERT INTO article (company_id, sku, unit_id, unitamount, weight, track_stock)
OUTPUT INSERTED.id
VALUES (@companyId, @sku, @unitId, @unitamount, @weight)
VALUES (@companyId, @sku, @unitId, @unitamount, @weight, @trackStock)
`;
export const DELETE_EANS_BY_ARTICLE = `
@@ -287,6 +294,7 @@ SELECT
u.si AS unitSi,
ut.symbol AS unitSymbol,
a.unitamount,
a.track_stock,
b.name AS brandName,
b.name AS brandName,
pr.net AS net,
@@ -371,6 +379,7 @@ SELECT
at.slug,
a.unitamount,
a.weight,
a.track_stock,
u.si AS unitSi,
u.basesi AS unitBasesi,
u.basesifactor AS unitBasesifactor,
@@ -467,6 +476,7 @@ SELECT
SELECT
w.id,
w.name,
w.sort,
COALESCE(stock_calc.stock, 0) AS stock
FROM warehouse w
LEFT JOIN (
@@ -482,7 +492,7 @@ SELECT
GROUP BY l.warehouse_id
) stock_calc ON stock_calc.warehouse_id = w.id
WHERE w.company_id = a.company_id
ORDER BY w.name ASC
ORDER BY w.sort ASC, w.name ASC
FOR JSON PATH
) AS warehousesJson
FROM article a

View File

@@ -5,6 +5,7 @@ export const ARTICLE_DETAIL_COLUMNS = `
at.slug,
a.unitamount,
a.weight,
a.track_stock,
u.si AS unitSi,
u.basesi AS unitBasesi,
u.basesifactor AS unitBasesifactor,

View File

@@ -2,17 +2,19 @@ export const LIST_BY_COMPANY = `
SELECT
id,
company_id,
name
name,
sort
FROM warehouse
WHERE company_id = @companyId
ORDER BY name ASC;
ORDER BY sort ASC, name ASC;
`;
export const GET_BY_COMPANY_AND_ID = `
SELECT
id,
company_id,
name
name,
sort
FROM warehouse
WHERE id = @id AND company_id = @companyId;
`;
@@ -21,20 +23,39 @@ export const GET_BY_COMPANY_AND_NAME = `
SELECT
id,
company_id,
name
name,
sort
FROM warehouse
WHERE company_id = @companyId AND name = @name;
`;
export const GET_NEXT_SORT = `
SELECT ISNULL(MAX(sort), -1) + 1 AS sort
FROM warehouse
WHERE company_id = @companyId;
`;
export const CREATE = `
INSERT INTO warehouse (company_id, name)
OUTPUT INSERTED.id, INSERTED.company_id, INSERTED.name
VALUES (@companyId, @name);
INSERT INTO warehouse (company_id, name, sort)
OUTPUT INSERTED.id, INSERTED.company_id, INSERTED.name, INSERTED.sort
VALUES (@companyId, @name, @sort);
`;
export const UPDATE_BY_ID = `
UPDATE warehouse
SET name = @name
SET name = @name, sort = @sort
WHERE id = @id AND company_id = @companyId;
`;
export const LIST_IDS_BY_COMPANY = `
SELECT id
FROM warehouse
WHERE company_id = @companyId;
`;
export const UPDATE_SORT = `
UPDATE warehouse
SET sort = @sort
WHERE id = @id AND company_id = @companyId;
`;

View File

@@ -317,6 +317,7 @@ BEGIN
unit_id INT NOT NULL,
unitamount FLOAT NOT NULL,
weight FLOAT NOT NULL,
track_stock BIT NOT NULL CONSTRAINT DF_article_track_stock DEFAULT 1,
brand_id INT NULL,
articlelist_id INT NULL,
optionslist_id INT NULL,
@@ -340,6 +341,10 @@ BEGIN
ON article (fatherarticle_id, fathersort)
WHERE fatherarticle_id IS NOT NULL;
END
ELSE IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('article') AND name = 'track_stock')
BEGIN
ALTER TABLE article ADD track_stock BIT NOT NULL CONSTRAINT DF_article_track_stock DEFAULT 1;
END
`;
export const INIT_ARTICLEHISTORY = `
@@ -599,10 +604,15 @@ BEGIN
id INT IDENTITY(1,1) PRIMARY KEY,
company_id INT NOT NULL,
name NVARCHAR(255) NOT NULL,
sort INT NOT NULL CONSTRAINT DF_warehouse_sort DEFAULT 0,
CONSTRAINT FK_warehouse_company FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE,
CONSTRAINT UQ_warehouse_company_name UNIQUE (company_id, name)
);
END
ELSE IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('warehouse') AND name = 'sort')
BEGIN
ALTER TABLE warehouse ADD sort INT NOT NULL CONSTRAINT DF_warehouse_sort DEFAULT 0;
END
`;
export const INIT_LEDGER = `

View File

@@ -399,6 +399,20 @@ export class BetterSqlite3Provider extends BetterSqlite3Executor {
`ALTER TABLE ledger ADD COLUMN warehouse_id INTEGER REFERENCES warehouse(id) ON DELETE NO ACTION`,
);
}
const articleCols = this.db.pragma('table_info("article")').map((c) => c.name);
if (articleCols.length > 0 && !articleCols.includes('track_stock')) {
this.db.exec(
`ALTER TABLE article ADD COLUMN track_stock INTEGER NOT NULL DEFAULT 1`,
);
}
const warehouseCols = this.db.pragma('table_info("warehouse")').map((c) => c.name);
if (warehouseCols.length > 0 && !warehouseCols.includes('sort')) {
this.db.exec(
`ALTER TABLE warehouse ADD COLUMN sort INTEGER NOT NULL DEFAULT 0`,
);
}
} catch {
// ignore
}

View File

@@ -8,7 +8,7 @@ export const {
GET_BRAND_BY_COMPANY_AND_ID,
GET_CATEGORY_ID_BY_SKU, GET_CATEGORY_TREE_FLAT, GET_ID_BY_SKU,
SET_FATHER_SORT,
SET_IS_FATHER, UPDATE_BRAND, UPDATE_FATHER_BY_SKU, UPDATE_UNIT,
SET_IS_FATHER, UPDATE_BRAND, UPDATE_FATHER_BY_SKU, UPDATE_TRACK_STOCK, UPDATE_UNIT,
UPDATE_UNITAMOUNT, UPDATE_UNIT_AND_AMOUNT, UPDATE_WEIGHT,
} = queries;
@@ -83,7 +83,7 @@ WITH RECURSIVE category_tree AS (
INNER JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT DISTINCT a.id, a.sku, at.name, at.slug, u.si AS unitSi,
ut.symbol AS unitSymbol, a.unitamount, b.name AS brandName,
ut.symbol AS unitSymbol, a.unitamount, a.track_stock, b.name AS brandName,
pr.net, t.rate AS taxRate,
${JSON_EANS} AS eansJson,
${JSON_CATEGORIES} AS categoryIdsJson,
@@ -122,6 +122,7 @@ SELECT auth.*,
json_object(
'id', a.id, 'sku', a.sku, 'name', at.name, 'slug', at.slug,
'unitamount', a.unitamount, 'weight', a.weight,
'track_stock', a.track_stock,
'unitSi', u.si, 'unitBasesi', u.basesi,
'unitBasesifactor', u.basesifactor, 'unitSymbol', ut.symbol,
'unitName', ut.name,
@@ -169,7 +170,7 @@ SELECT auth.*,
WHERE s.article_id = a.id ORDER BY s.sort, s.id
))),
'warehousesJson', json((SELECT COALESCE(json_group_array(json_object(
'id', w.id, 'name', w.name, 'stock', COALESCE(stock_calc.stock, 0)
'id', w.id, 'name', w.name, 'sort', w.sort, 'stock', COALESCE(stock_calc.stock, 0)
)), '[]') FROM warehouse w
LEFT JOIN (
SELECT l.warehouse_id, SUM(l.amount) AS stock
@@ -184,7 +185,7 @@ SELECT auth.*,
GROUP BY l.warehouse_id
) stock_calc ON stock_calc.warehouse_id = w.id
WHERE w.company_id = a.company_id
ORDER BY w.name ASC))
ORDER BY w.sort ASC, w.name ASC))
) AS articleJson
FROM auth
INNER JOIN article a ON a.id = auth.articleId

View File

@@ -2,17 +2,19 @@ export const LIST_BY_COMPANY = `
SELECT
id,
company_id,
name
name,
sort
FROM warehouse
WHERE company_id = @companyId
ORDER BY name ASC;
ORDER BY sort ASC, name ASC;
`;
export const GET_BY_COMPANY_AND_ID = `
SELECT
id,
company_id,
name
name,
sort
FROM warehouse
WHERE id = @id AND company_id = @companyId;
`;
@@ -21,20 +23,39 @@ export const GET_BY_COMPANY_AND_NAME = `
SELECT
id,
company_id,
name
name,
sort
FROM warehouse
WHERE company_id = @companyId AND name = @name;
`;
export const GET_NEXT_SORT = `
SELECT IFNULL(MAX(sort), -1) + 1 AS sort
FROM warehouse
WHERE company_id = @companyId;
`;
export const CREATE = `
INSERT INTO warehouse (company_id, name)
VALUES (@companyId, @name)
RETURNING id, company_id, name;
INSERT INTO warehouse (company_id, name, sort)
VALUES (@companyId, @name, @sort)
RETURNING id, company_id, name, sort;
`;
export const UPDATE_BY_ID = `
UPDATE warehouse
SET name = @name
SET name = @name, sort = @sort
WHERE id = @id AND company_id = @companyId;
`;
export const LIST_IDS_BY_COMPANY = `
SELECT id
FROM warehouse
WHERE company_id = @companyId;
`;
export const UPDATE_SORT = `
UPDATE warehouse
SET sort = @sort
WHERE id = @id AND company_id = @companyId;
`;

View File

@@ -216,6 +216,7 @@ CREATE TABLE IF NOT EXISTS article (
unit_id INTEGER NOT NULL,
unitamount REAL NOT NULL,
weight REAL NOT NULL,
track_stock INTEGER NOT NULL DEFAULT 1,
brand_id INTEGER,
articlelist_id INTEGER,
optionslist_id INTEGER,
@@ -431,6 +432,7 @@ CREATE TABLE IF NOT EXISTS warehouse (
id INTEGER PRIMARY KEY,
company_id INTEGER NOT NULL,
name TEXT NOT NULL COLLATE NOCASE,
sort INTEGER NOT NULL DEFAULT 0,
UNIQUE (company_id, name),
FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE
);

View File

@@ -32,14 +32,18 @@ export default function createUnderParent(provider) {
* @param {number} input.googleAuthId - The id of the Google auth user.
* @param {number} input.parentId - The id of the parent category.
* @param {string} input.name - The article name.
* @param {boolean|number} [input.track_stock=true] - Whether inventory stock is tracked.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, parentId: number, name: string, sku: string}>} The created article.
* @returns {Promise<{id: number, parentId: number, name: string, sku: string, track_stock: boolean}>} The created article.
*
* @example
* const article = await store.article.createUnderParent({ googleAuthId: 42, parentId: 5, name: 'Cola' });
* // => { id, parentId, name, sku }
* // => { id, parentId, name, sku, track_stock }
*/
return async ({ googleAuthId, parentId, name }, tx) => {
return async ({ googleAuthId, parentId, name, track_stock, trackStock }, tx) => {
const rawTrack = track_stock ?? trackStock;
const finalTrackStock = rawTrack == null ? 1 : (rawTrack ? 1 : 0);
const runCreate = async (runner) => {
const { companyId, languageId, companyuserId } = await access(
googleAuthId,
@@ -59,6 +63,7 @@ export default function createUnderParent(provider) {
unitId,
unitamount: 1,
weight: 0,
trackStock: finalTrackStock,
});
} catch (err) {
if (isUniqueConstraintError(err)) {
@@ -92,6 +97,7 @@ export default function createUnderParent(provider) {
parentId,
name,
sku,
track_stock: Boolean(finalTrackStock),
};
};

View File

@@ -18,7 +18,7 @@ export default function getBySku(provider) {
* @param {number} googleAuthId - The id of the Google auth user.
* @param {string} sku - The article SKU.
* @param {object} [tx] - Optional transaction.
* @returns {Promise<{article: {id: number, sku: string, name: string, slug: string, unitamount: number|null, weight: number|null, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>, optionsCount: number, articleListCount: number, childCount: number, fatherArticleId: number|null, fatherSku: string|null}}>} The full article detail.
* @returns {Promise<{article: {id: number, sku: string, name: string, slug: string, unitamount: number|null, weight: number|null, track_stock: boolean, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>, optionsCount: number, articleListCount: number, childCount: number, fatherArticleId: number|null, fatherSku: string|null}}>} The full article detail.
* @throws {Error} If the article is not found or the user is not authorized.
*
* @example
@@ -56,6 +56,7 @@ export default function getBySku(provider) {
slug: a.slug,
unitamount: a.unitamount,
weight: a.weight,
track_stock: Boolean(a.track_stock ?? 1),
unit: {
si: a.unitSi,
basesi: a.unitBasesi,
@@ -92,6 +93,7 @@ export default function getBySku(provider) {
warehouses: parseJsonArray(a.warehousesJson).map((w) => ({
id: w.id,
name: w.name,
sort: Number(w.sort ?? 0),
stock: Number(w.stock ?? 0),
})),
optionsCount: a.optionsCount,

View File

@@ -103,6 +103,7 @@ export default function importRows(provider) {
* @param {number|string} [input.rows[].net] - The POS net price (accepts German decimals).
* @param {number|string} [input.rows[].tax] - The tax rate in percent (e.g. `19`).
* @param {Array<string>|string} [input.rows[].eans] - The EANs to set.
* @param {boolean|number} [input.rows[].track_stock=true] - Whether inventory stock is tracked.
* @param {string} [input.rows[].fatherSku] - The father article SKU for a V/K compound link.
* @param {number|string} [input.rows[].deposit] - The deposit (Pfand) value; currently ignored.
* @param {object} [tx] - Optional transaction.
@@ -168,12 +169,16 @@ export default function importRows(provider) {
const unitId = await ensureUnit(runner, companyId, languageId);
const slug = slugify(name);
const rawTrack = row.track_stock ?? row.trackStock;
const trackStock = rawTrack == null ? 1 : (rawTrack ? 1 : 0);
const article = await runner.query(articleQueries.CREATE, {
companyId,
sku,
unitId,
unitamount: 1,
weight: 0,
trackStock,
});
const articleId = article.rows[0]?.id ?? article.insertId;

View File

@@ -94,6 +94,7 @@ export default function listExport(provider) {
unitSi: row.unitSi,
unitSymbol: row.unitSymbol,
unitamount: row.unitamount,
track_stock: Boolean(row.track_stock ?? 1),
brandName: row.brandName,
net: row.net,
taxRate: row.taxRate,

View File

@@ -10,6 +10,7 @@ function shapeArticleDetail(row, categoryIds, photos, eans, prices) {
slug: row.slug,
unitamount: row.unitamount,
weight: row.weight,
track_stock: Boolean(row.track_stock ?? 1),
unit: {
si: row.unitSi,
basesi: row.unitBasesi,

View File

@@ -0,0 +1,53 @@
import { UPDATE_TRACK_STOCK as MSSQL_UPDATE_TRACK_STOCK } from '../../providers/mssql/queries/article.js';
import { UPDATE_TRACK_STOCK as SQLITE_UPDATE_TRACK_STOCK } from '../../providers/sqlite3/queries/article.js';
import queryBySku from './queryBySku.js';
import resolveArticleBySku from './resolveArticleBySku.js';
import makeRunner from '../runner.js';
export default function setTrackStockBySku(provider) {
const resolve = resolveArticleBySku(provider);
const load = queryBySku(provider);
const sql =
provider?.dialect === 'sqlite3'
? SQLITE_UPDATE_TRACK_STOCK
: MSSQL_UPDATE_TRACK_STOCK;
/**
* Sets the track_stock flag of an article by its SKU.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {string} sku - The article SKU.
* @param {boolean|number} trackStock - Whether stock tracking is enabled.
* @param {object} [tx] - Optional transaction.
* @returns {Promise<object>} The updated article.
* @throws {Error} If trackStock is invalid or the article is not found.
*
* @example
* const article = await store.article.setTrackStockBySku(42, 'SKU-1', true);
* // => { id, sku, name, track_stock, ... }
*/
return async (googleAuthId, sku, trackStock, tx) => {
if (typeof trackStock !== 'boolean' && trackStock !== 0 && trackStock !== 1) {
throw new Error('Invalid track_stock');
}
const runner = makeRunner(provider, tx);
const { articleId, languageId } = await resolve(googleAuthId, sku, runner);
const result = await runner.query(sql, {
articleId,
trackStock: trackStock ? 1 : 0,
});
if (!result.rowsAffected) {
throw new Error('Article not found');
}
const article = await load(articleId, languageId, runner);
if (!article) {
throw new Error('Article not found');
}
return article;
};
}

View File

@@ -41,20 +41,24 @@ export default function updateBySku(provider) {
* @param {string} [patch.name] - The new article name.
* @param {string} [patch.unitSi] - The new unit SI code.
* @param {number} [patch.unitamount] - The new unit amount (must be > 0).
* @param {boolean|number} [patch.track_stock] - Whether inventory stock is tracked.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<object>} The updated article.
* @throws {Error} If no valid field is provided or the article is not found.
*
* @example
* const article = await store.article.updateBySku(42, 'SKU-1', { name: 'Cola 1L', unitSi: 'l', unitamount: 1 });
* const article = await store.article.updateBySku(42, 'SKU-1', { name: 'Cola 1L', unitSi: 'l', unitamount: 1, track_stock: true });
* // => { id, sku, name, ... }
*/
return async (googleAuthId, sku, patch = {}, tx) => {
const hasName = Object.prototype.hasOwnProperty.call(patch, 'name');
const hasUnitamount = Object.prototype.hasOwnProperty.call(patch, 'unitamount');
const hasUnitSi = Object.prototype.hasOwnProperty.call(patch, 'unitSi');
const hasTrackStock =
Object.prototype.hasOwnProperty.call(patch, 'track_stock') ||
Object.prototype.hasOwnProperty.call(patch, 'trackStock');
if (!hasName && !hasUnitamount && !hasUnitSi) {
if (!hasName && !hasUnitamount && !hasUnitSi && !hasTrackStock) {
throw new Error('Name required');
}
@@ -66,6 +70,13 @@ export default function updateBySku(provider) {
throw new Error('Invalid unitamount');
}
const rawTrackStock = Object.prototype.hasOwnProperty.call(patch, 'track_stock')
? patch.track_stock
: patch.trackStock;
if (hasTrackStock && typeof rawTrackStock !== 'boolean' && rawTrackStock !== 0 && rawTrackStock !== 1) {
throw new Error('Invalid track_stock');
}
const runUpdate = async (runner) => {
const { articleId, languageId, companyId, companyuserId } = await resolve(
googleAuthId,
@@ -122,6 +133,15 @@ export default function updateBySku(provider) {
historyLines.push(`Einheit geändert von "${oldLabel}" auf "${newLabel}"`);
}
}
if (hasTrackStock) {
const oldTrack = Boolean(current.track_stock ?? 1);
const newTrack = Boolean(rawTrackStock);
if (oldTrack !== newTrack) {
historyLines.push(
`Bestandsführung geändert von "${oldTrack ? 'Ja' : 'Nein'}" auf "${newTrack ? 'Ja' : 'Nein'}"`,
);
}
}
if (hasName) {
const slug = slugify(patch.name);
@@ -155,6 +175,13 @@ export default function updateBySku(provider) {
});
}
if (hasTrackStock) {
await runner.query(articleQueries.UPDATE_TRACK_STOCK, {
articleId,
trackStock: Boolean(rawTrackStock) ? 1 : 0,
});
}
if (historyLines.length) {
await runner.query(insertHistorySql, {
articleId,

View File

@@ -24,6 +24,7 @@ export default function queryCategoryArticles(provider) {
} = row;
return {
...rest,
track_stock: Boolean(rest.track_stock ?? 1),
brand: brandName
? {
id: brandId ?? null,

View File

@@ -1,17 +1,24 @@
import { CREATE as MSSQL_CREATE } from '../../providers/mssql/queries/warehouse.js';
import { CREATE as SQLITE_CREATE } from '../../providers/sqlite3/queries/warehouse.js';
import {
CREATE as MSSQL_CREATE,
GET_NEXT_SORT as MSSQL_GET_NEXT_SORT,
} from '../../providers/mssql/queries/warehouse.js';
import {
CREATE as SQLITE_CREATE,
GET_NEXT_SORT as SQLITE_GET_NEXT_SORT,
} 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 };
return { id: row.id, name: row.name, sort: row.sort };
}
export default function create(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql =
provider?.dialect === 'sqlite3' ? SQLITE_CREATE : MSSQL_CREATE;
const isSqlite = provider?.dialect === 'sqlite3';
const getSortSql = isSqlite ? SQLITE_GET_NEXT_SORT : MSSQL_GET_NEXT_SORT;
const sql = isSqlite ? SQLITE_CREATE : MSSQL_CREATE;
/**
* Creates a new warehouse for the user's selected company.
@@ -19,15 +26,16 @@ export default function create(provider) {
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Warehouse input.
* @param {string} input.name - The warehouse name.
* @param {number} [input.sort] - Optional sort order (auto-increments if omitted).
* @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.
* @returns {Promise<{id: number, name: string, sort: number}>} The created warehouse.
* @throws {Error} If name is missing, sort is invalid, or name already exists.
*
* @example
* const wh = await store.warehouse.create(googleAuthId, { name: 'Hauptlager' });
* // => { id: 1, name: 'Hauptlager' }
* // => { id: 1, name: 'Hauptlager', sort: 0 }
*/
return async (googleAuthId, { name } = {}, tx) => {
return async (googleAuthId, { name, sort: explicitSort } = {}, tx) => {
const cleaned = typeof name === 'string' ? name.trim() : '';
if (!cleaned) {
throw new Error('Name required');
@@ -36,13 +44,27 @@ export default function create(provider) {
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
let sort = explicitSort;
if (sort === undefined || sort === null) {
const next = await runner.query(getSortSql, { companyId });
sort = next.rows[0]?.sort ?? 0;
} else if (!Number.isFinite(sort)) {
throw new Error('Invalid sort');
}
try {
const result = await runner.query(sql, {
companyId,
name: cleaned,
sort,
});
const row = result.rows[0] ?? { id: result.insertId, name: cleaned };
const row = result.rows[0] ?? {
id: result.insertId,
company_id: companyId,
name: cleaned,
sort,
};
return shape(row);
} catch (err) {
if (

View File

@@ -4,7 +4,7 @@ import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyA
import makeRunner from '../runner.js';
function shape(row) {
return { id: row.id, name: row.name };
return { id: row.id, name: row.name, sort: row.sort };
}
export default function getById(provider) {
@@ -18,11 +18,11 @@ export default function getById(provider) {
* @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.
* @returns {Promise<{id: number, name: string, sort: number}|undefined>} The warehouse or undefined.
*
* @example
* const wh = await store.warehouse.getById(googleAuthId, 1);
* // => { id: 1, name: 'Hauptlager' }
* // => { id: 1, name: 'Hauptlager', sort: 0 }
*/
return async (googleAuthId, id, tx) => {
const numericId = Number(id);

View File

@@ -4,7 +4,7 @@ import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyA
import makeRunner from '../runner.js';
function shape(row) {
return { id: row.id, name: row.name };
return { id: row.id, name: row.name, sort: row.sort };
}
export default function list(provider) {
@@ -17,11 +17,11 @@ export default function list(provider) {
*
* @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.
* @returns {Promise<Array<{id: number, name: string, sort: number}>>} List of warehouses.
*
* @example
* const warehouses = await store.warehouse.list(googleAuthId);
* // => [{ id: 1, name: 'Hauptlager' }]
* // => [{ id: 1, name: 'Hauptlager', sort: 0 }]
*/
return async (googleAuthId, tx) => {
const runner = makeRunner(provider, tx);

View 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/warehouse.js';
import {
LIST_IDS_BY_COMPANY as SQLITE_LIST_IDS_BY_COMPANY,
UPDATE_SORT as SQLITE_UPDATE_SORT,
} from '../../providers/sqlite3/queries/warehouse.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 warehouses 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.warehouseIds - The warehouse ids in their new order.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{warehouseIds: Array<number>}>} The applied order.
* @throws {Error} If the order is invalid.
*/
return async (googleAuthId, { warehouseIds } = {}, tx) => {
if (!Array.isArray(warehouseIds)) {
throw new Error('Invalid warehouse 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 (warehouseIds.length !== existing.size) {
throw new Error('Invalid warehouse order');
}
const seen = new Set();
for (const warehouseId of warehouseIds) {
if (
!Number.isFinite(warehouseId) ||
!existing.has(warehouseId) ||
seen.has(warehouseId)
) {
throw new Error('Invalid warehouse order');
}
seen.add(warehouseId);
}
for (let sort = 0; sort < warehouseIds.length; sort++) {
await runner.query(updateSortSql, {
id: warehouseIds[sort],
companyId,
sort,
});
}
return { warehouseIds };
};
if (tx) {
return runOrder(makeRunner(provider, tx));
}
if (typeof provider?.transaction === 'function') {
return provider.transaction(runOrder);
}
return runOrder(makeRunner(provider));
};
}

View File

@@ -11,7 +11,7 @@ import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyA
import makeRunner from '../runner.js';
function shape(row) {
return { id: row.id, name: row.name };
return { id: row.id, name: row.name, sort: row.sort };
}
export default function update(provider) {
@@ -21,47 +21,66 @@ export default function update(provider) {
const updateSql = isSqlite ? SQLITE_UPDATE : MSSQL_UPDATE;
/**
* Updates a warehouse name for the user's selected company.
* Updates a warehouse name and/or sort order 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 {string} [input.name] - The new warehouse name.
* @param {number} [input.sort] - The new sort order.
* @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.
* @returns {Promise<{id: number, name: string, sort: number}>} The updated warehouse.
* @throws {Error} If warehouse not found, name is empty, sort is invalid, or name already exists.
*
* @example
* const updated = await store.warehouse.update(googleAuthId, 1, { name: 'Zentrallager' });
* // => { id: 1, name: 'Zentrallager' }
* const updated = await store.warehouse.update(googleAuthId, 1, { name: 'Zentrallager', sort: 1 });
* // => { id: 1, name: 'Zentrallager', sort: 1 }
*/
return async (googleAuthId, id, { name } = {}, tx) => {
return async (googleAuthId, id, input = {}, 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]) {
const current = existing.rows[0];
if (!current) {
throw new Error('Warehouse not found');
}
let name = current.name;
if (input.name !== undefined) {
const cleaned = typeof input.name === 'string' ? input.name.trim() : '';
if (!cleaned) {
throw new Error('Name required');
}
name = cleaned;
}
let sort = current.sort;
if (input.sort !== undefined) {
if (!Number.isFinite(input.sort)) {
throw new Error('Invalid sort');
}
sort = input.sort;
}
if (input.name === undefined && input.sort === undefined) {
throw new Error('Name required');
}
try {
await runner.query(updateSql, {
id: numericId,
companyId,
name: cleaned,
name,
sort,
});
return shape({ id: numericId, name: cleaned });
return shape({ id: numericId, name, sort });
} catch (err) {
if (
isUniqueConstraintError(err) ||