This commit is contained in:
seb
2026-08-01 05:10:03 +02:00
parent ee895fab5f
commit 9be9f7f74c
12 changed files with 164 additions and 79 deletions

View File

@@ -33,7 +33,7 @@ ID fields in the JS API use camelCase `…Id` (DB columns stay snake_case). `goo
| Method | Signature | Returns | | Method | Signature | Returns |
| --- | --- | --- | | --- | --- | --- |
| `create` | `({ iso639, name, taxrate, reducedtaxrate, googleAuthId })` | `{ id, rootCategoryId, languageId, taxrateId, reducedtaxrateId, taxfreerateId }` | | `create` | `({ iso639, name, taxrate, reducedtaxrate, googleAuthId })` | `{ id, rootCategoryId, languageId, taxrateId, reducedtaxrateId, taxfreerateId, posCustomerGroupId }` |
| `update` | `(id, { iso639, name, taxrate, reducedtaxrate })` | `{ id, rootCategoryId, languageId, taxrateId, reducedtaxrateId, taxfreerateId }` | | `update` | `(id, { iso639, name, taxrate, reducedtaxrate })` | `{ id, rootCategoryId, languageId, taxrateId, reducedtaxrateId, taxfreerateId }` |
| `delete` | `(companyId)` | `void` | | `delete` | `(companyId)` | `void` |
| `list` | `(googleAuthId)` | `{ id, name, rootCategoryId, languageId, taxrate, reducedtaxrate, taxfreerate }[]` | | `list` | `(googleAuthId)` | `{ id, name, rootCategoryId, languageId, taxrate, reducedtaxrate, taxfreerate }[]` |
@@ -46,10 +46,10 @@ For `POST /api/company`:
2. Ensures language by `iso639` (get or create) 2. Ensures language by `iso639` (get or create)
3. Ensures tax rows for `taxrate`, `reducedtaxrate`, and `0` → `taxfreerateId` 3. Ensures tax rows for `taxrate`, `reducedtaxrate`, and `0` → `taxfreerateId`
4. Creates root category (`parentId = null`) 4. Creates root category (`parentId = null`)
5. Inserts company with all FKs set 5. Creates POS `customergroup` (name `POS`), then inserts company with `poscustomergroup_id` (**NOT NULL**), then links the group via `customergroup.company_id`
6. Links creator as `companyuser` (`googleAuthId` → `company_id`) 6. Links creator as `companyuser` (`googleAuthId` → `company_id`)
`company.poscustomergroup_id` (optional) points at the `customergroup` used for POS pricing in `getTreeForCompany` articles. `company.poscustomergroup_id` is required (POS pricing in `getTreeForCompany` / category articles). Circular FK with `customergroup.company_id`: the group is inserted first with `company_id` null, then linked after the company row exists.
### `list` ### `list`

View File

@@ -109,7 +109,7 @@ BEGIN
taxrate INT NULL, taxrate INT NULL,
reducedtaxrate INT NULL, reducedtaxrate INT NULL,
taxfreerate INT NULL, taxfreerate INT NULL,
poscustomergroup_id INT NULL, poscustomergroup_id INT NOT NULL,
CONSTRAINT UQ_company_name UNIQUE (name), CONSTRAINT UQ_company_name UNIQUE (name),
CONSTRAINT FK_company_root_category FOREIGN KEY (root_category_id) REFERENCES category(id) ON DELETE SET NULL, CONSTRAINT FK_company_root_category FOREIGN KEY (root_category_id) REFERENCES category(id) ON DELETE SET NULL,
CONSTRAINT FK_company_default_language FOREIGN KEY (default_language_id) REFERENCES language(id) ON DELETE SET NULL, CONSTRAINT FK_company_default_language FOREIGN KEY (default_language_id) REFERENCES language(id) ON DELETE SET NULL,
@@ -126,7 +126,9 @@ BEGIN
CREATE TABLE customergroup ( CREATE TABLE customergroup (
id INT IDENTITY(1,1) PRIMARY KEY, id INT IDENTITY(1,1) PRIMARY KEY,
name NVARCHAR(255) NOT NULL, name NVARCHAR(255) NOT NULL,
company_id INT NOT NULL, -- Nullable only for company-create chicken-egg (POS group first, then company, then SET).
-- Always set before commit; never left null for live rows.
company_id INT NULL,
CONSTRAINT FK_customergroup_company FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE CONSTRAINT FK_customergroup_company FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE
); );
END END
@@ -270,6 +272,9 @@ BEGIN
CONSTRAINT FK_articleean_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE, CONSTRAINT FK_articleean_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE,
CONSTRAINT UQ_articleean_ean UNIQUE (ean) CONSTRAINT UQ_articleean_ean UNIQUE (ean)
); );
-- Hot path: getBySku EANs by article (UQ is ean-leading only)
CREATE INDEX IX_articleean_article_ean
ON articleean (article_id, ean);
END END
`; `;
@@ -351,6 +356,9 @@ BEGIN
CONSTRAINT FK_categoryarticle_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE, CONSTRAINT FK_categoryarticle_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE,
CONSTRAINT UQ_categoryarticle_category_article UNIQUE (category_id, article_id) CONSTRAINT UQ_categoryarticle_category_article UNIQUE (category_id, article_id)
); );
-- Hot path: getBySku / resolve by article (UQ is category-leading)
CREATE INDEX IX_categoryarticle_article_category
ON categoryarticle (article_id, category_id);
END END
`; `;
@@ -420,6 +428,10 @@ BEGIN
CONSTRAINT FK_price_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE, CONSTRAINT FK_price_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE,
CONSTRAINT FK_price_customergroup FOREIGN KEY (customergroup_id) REFERENCES customergroup(id) ON DELETE CASCADE CONSTRAINT FK_price_customergroup FOREIGN KEY (customergroup_id) REFERENCES customergroup(id) ON DELETE CASCADE
); );
-- Hot path: getBySku prices by article (covers ORDER BY + SELECT cols)
CREATE INDEX IX_price_article_cg_mult
ON price (article_id, customergroup_id, minmultiplier)
INCLUDE (net, tax_id);
END END
`; `;

View File

@@ -59,6 +59,45 @@ INNER JOIN categoryarticle ca ON ca.article_id = a.id
WHERE a.sku = @sku WHERE a.sku = @sku
`; `;
/** SKU → article/category + company auth in one round-trip. */
export const RESOLVE_ARTICLE_ACCESS_BY_SKU = `
WITH article_cat AS (
SELECT TOP 1 a.id AS articleId, ca.category_id AS categoryId
FROM article a
INNER JOIN categoryarticle ca ON ca.article_id = a.id
WHERE a.sku = @sku
),
ancestors AS (
SELECT c.id, c.parent_id
FROM category c
INNER JOIN article_cat ac ON c.id = ac.categoryId
UNION ALL
SELECT c.id, c.parent_id
FROM category c
INNER JOIN ancestors a ON c.id = a.parent_id
),
root AS (
SELECT TOP 1 id AS rootCategoryId
FROM ancestors
WHERE parent_id IS NULL
)
SELECT
ac.articleId,
ac.categoryId,
r.rootCategoryId,
co.id AS companyId,
co.default_language_id AS languageId,
co.poscustomergroup_id AS posCustomerGroupId,
cu.id AS companyuserId
FROM article_cat ac
LEFT JOIN root r ON 1 = 1
LEFT JOIN company co ON co.root_category_id = r.rootCategoryId
LEFT JOIN companyuser cu
ON cu.company_id = co.id AND cu.google_auth_id = @googleAuthId
`;
export const CREATE = ` export const CREATE = `
INSERT INTO article (sku, unit_id, unitamount, weight) INSERT INTO article (sku, unit_id, unitamount, weight)
OUTPUT INSERTED.id OUTPUT INSERTED.id

View File

@@ -54,6 +54,25 @@ LEFT JOIN article father ON father.id = a.fatherarticle_id
WHERE a.sku = @sku WHERE a.sku = @sku
`; `;
export const GET_DETAIL_BY_ARTICLE_ID = `
SELECT
${ARTICLE_DETAIL_COLUMNS}
FROM article a
LEFT JOIN articletext at
ON at.article_id = a.id AND at.language_id = @languageId
LEFT JOIN unit u ON u.id = a.unit_id
LEFT JOIN brand b ON b.id = a.brand_id
OUTER APPLY (
SELECT TOP 1 bp.pic_id
FROM brandpic bp
WHERE bp.brand_id = b.id
ORDER BY bp.sort ASC, bp.id ASC
) first_brand_pic
LEFT JOIN pic brand_pic ON brand_pic.id = first_brand_pic.pic_id
LEFT JOIN article father ON father.id = a.fatherarticle_id
WHERE a.id = @articleId
`;
export const GET_CATEGORY_IDS_BY_ARTICLE_ID = ` export const GET_CATEGORY_IDS_BY_ARTICLE_ID = `
SELECT ca.category_id AS categoryId SELECT ca.category_id AS categoryId
FROM categoryarticle ca FROM categoryarticle ca

View File

@@ -17,7 +17,8 @@ INSERT INTO company (
default_language_id, default_language_id,
taxrate, taxrate,
reducedtaxrate, reducedtaxrate,
taxfreerate taxfreerate,
poscustomergroup_id
) )
OUTPUT INSERTED.id OUTPUT INSERTED.id
VALUES ( VALUES (
@@ -26,7 +27,8 @@ VALUES (
@languageId, @languageId,
@taxrate, @taxrate,
@reducedtaxrate, @reducedtaxrate,
@taxfreerate @taxfreerate,
@posCustomerGroupId
) )
`; `;

17
src/sql/customergroup.js Normal file
View File

@@ -0,0 +1,17 @@
export const CREATE = `
INSERT INTO customergroup (name, company_id)
OUTPUT INSERTED.id
VALUES (@name, @companyId)
`;
export const CREATE_WITHOUT_COMPANY = `
INSERT INTO customergroup (name)
OUTPUT INSERTED.id
VALUES (@name)
`;
export const SET_COMPANY = `
UPDATE customergroup
SET company_id = @companyId
WHERE id = @id
`;

View File

@@ -1,26 +1,15 @@
import { GET_CATEGORY_ID_BY_SKU } from '../../sql/article.js';
import { ADD as ADD_ARTICLEPIC, GET_NEXT_SORT } from '../../sql/articlepic.js'; import { ADD as ADD_ARTICLEPIC, GET_NEXT_SORT } from '../../sql/articlepic.js';
import { CREATE as CREATE_PIC } from '../../sql/pic.js'; import { CREATE as CREATE_PIC } from '../../sql/pic.js';
import processAvifImage from '../../util/processAvifImage.js'; import processAvifImage from '../../util/processAvifImage.js';
import newFullHash from '../../util/newFullHash.js'; import newFullHash from '../../util/newFullHash.js';
import resolveCategoryAccess from '../category/resolveCategoryAccess.js';
import request from '../request.js'; import request from '../request.js';
import resolveArticleBySku from './resolveArticleBySku.js';
export default function addImage(pool) { export default function addImage(pool) {
const access = resolveCategoryAccess(pool); const resolve = resolveArticleBySku(pool);
return async (googleAuthId, sku, image) => { return async (googleAuthId, sku, image) => {
const categoryLookup = await pool const { articleId } = await resolve(googleAuthId, sku);
.request()
.input('sku', sku)
.query(GET_CATEGORY_ID_BY_SKU);
const row = categoryLookup.recordset[0];
if (!row?.categoryId || !row?.articleId) {
throw new Error('Article not found');
}
await access(googleAuthId, row.categoryId);
const processed = await processAvifImage(image); const processed = await processAvifImage(image);
@@ -29,7 +18,7 @@ export default function addImage(pool) {
try { try {
const sortResult = await request(pool, tx) const sortResult = await request(pool, tx)
.input('articleId', row.articleId) .input('articleId', articleId)
.query(GET_NEXT_SORT); .query(GET_NEXT_SORT);
const sort = sortResult.recordset[0].sort; const sort = sortResult.recordset[0].sort;
@@ -51,7 +40,7 @@ export default function addImage(pool) {
const picId = picResult.recordset[0].id; const picId = picResult.recordset[0].id;
await request(pool, tx) await request(pool, tx)
.input('articleId', row.articleId) .input('articleId', articleId)
.input('picId', picId) .input('picId', picId)
.input('sort', sort) .input('sort', sort)
.query(ADD_ARTICLEPIC); .query(ADD_ARTICLEPIC);

View File

@@ -1,25 +1,18 @@
import { GET_CATEGORY_ID_BY_SKU } from '../../sql/article.js'; import resolveArticleBySku from './resolveArticleBySku.js';
import resolveCategoryAccess from '../category/resolveCategoryAccess.js';
import queryBySku from './queryBySku.js'; import queryBySku from './queryBySku.js';
export default function getBySku(pool) { export default function getBySku(pool) {
const access = resolveCategoryAccess(pool); const resolve = resolveArticleBySku(pool);
const load = queryBySku(pool); const load = queryBySku(pool);
return async (googleAuthId, sku) => { return async (googleAuthId, sku) => {
const categoryLookup = await pool let t0 = performance.now();
.request() const { articleId, languageId } = await resolve(googleAuthId, sku);
.input('sku', sku) console.log(`[getBySku] resolveArticleBySku ${(performance.now() - t0).toFixed(1)}ms`);
.query(GET_CATEGORY_ID_BY_SKU);
const categoryId = categoryLookup.recordset[0]?.categoryId; t0 = performance.now();
if (!categoryId) { const article = await load(articleId, languageId);
throw new Error('Article not found'); console.log(`[getBySku] queryBySku (parallel) ${(performance.now() - t0).toFixed(1)}ms`);
}
const { languageId } = await access(googleAuthId, categoryId);
const article = await load(sku, languageId);
if (!article) { if (!article) {
throw new Error('Article not found'); throw new Error('Article not found');
} }

View File

@@ -1,6 +1,6 @@
import { import {
GET_CATEGORY_IDS_BY_ARTICLE_ID, GET_CATEGORY_IDS_BY_ARTICLE_ID,
GET_DETAIL_BY_SKU, GET_DETAIL_BY_ARTICLE_ID,
GET_EANS_BY_ARTICLE_ID, GET_EANS_BY_ARTICLE_ID,
GET_PHOTOS_BY_ARTICLE_ID, GET_PHOTOS_BY_ARTICLE_ID,
GET_PRICES_BY_ARTICLE_ID, GET_PRICES_BY_ARTICLE_ID,
@@ -36,25 +36,24 @@ function shapeArticleDetail(row, categoryIds, photos, eans, prices) {
} }
export default function queryBySku(pool) { export default function queryBySku(pool) {
return async (sku, languageId) => { return async (articleId, languageId) => {
const detail = await pool const [detail, categories, photos, eans, prices] = await Promise.all([
.request() pool
.input('sku', sku) .request()
.input('languageId', languageId) .input('articleId', articleId)
.query(GET_DETAIL_BY_SKU); .input('languageId', languageId)
.query(GET_DETAIL_BY_ARTICLE_ID),
pool.request().input('articleId', articleId).query(GET_CATEGORY_IDS_BY_ARTICLE_ID),
pool.request().input('articleId', articleId).query(GET_PHOTOS_BY_ARTICLE_ID),
pool.request().input('articleId', articleId).query(GET_EANS_BY_ARTICLE_ID),
pool.request().input('articleId', articleId).query(GET_PRICES_BY_ARTICLE_ID),
]);
const row = detail.recordset[0]; const row = detail.recordset[0];
if (!row) { if (!row) {
return null; return null;
} }
const [categories, photos, eans, prices] = await Promise.all([
pool.request().input('articleId', row.id).query(GET_CATEGORY_IDS_BY_ARTICLE_ID),
pool.request().input('articleId', row.id).query(GET_PHOTOS_BY_ARTICLE_ID),
pool.request().input('articleId', row.id).query(GET_EANS_BY_ARTICLE_ID),
pool.request().input('articleId', row.id).query(GET_PRICES_BY_ARTICLE_ID),
]);
return shapeArticleDetail( return shapeArticleDetail(
row, row,
categories.recordset, categories.recordset,

View File

@@ -1,26 +1,31 @@
import { GET_CATEGORY_ID_BY_SKU } from '../../sql/article.js'; import { RESOLVE_ARTICLE_ACCESS_BY_SKU } from '../../sql/article.js';
import resolveCategoryAccess from '../category/resolveCategoryAccess.js';
export default function resolveArticleBySku(pool) { export default function resolveArticleBySku(pool) {
const access = resolveCategoryAccess(pool);
return async (googleAuthId, sku) => { return async (googleAuthId, sku) => {
const lookup = await pool const result = await pool
.request() .request()
.input('sku', sku) .input('sku', sku)
.query(GET_CATEGORY_ID_BY_SKU); .input('googleAuthId', googleAuthId)
.query(RESOLVE_ARTICLE_ACCESS_BY_SKU);
const row = lookup.recordset[0]; const row = result.recordset[0];
if (!row?.categoryId || !row?.articleId) { if (!row?.articleId || !row?.categoryId) {
throw new Error('Article not found'); throw new Error('Article not found');
} }
if (!row.companyId || !row.rootCategoryId || !row.languageId) {
const { languageId } = await access(googleAuthId, row.categoryId); throw new Error('Parent not found');
}
if (!row.companyuserId) {
throw new Error('Not authorized');
}
return { return {
articleId: row.articleId, articleId: row.articleId,
categoryId: row.categoryId, categoryId: row.categoryId,
languageId, languageId: row.languageId,
companyId: row.companyId,
rootCategoryId: row.rootCategoryId,
posCustomerGroupId: row.posCustomerGroupId ?? null,
}; };
}; };
} }

View File

@@ -1,8 +1,7 @@
import { GET_CATEGORY_ID_BY_SKU } from '../../sql/article.js';
import { UPDATE_BY_ARTICLE_AND_LANGUAGE } from '../../sql/articletext.js'; import { UPDATE_BY_ARTICLE_AND_LANGUAGE } from '../../sql/articletext.js';
import resolveCategoryAccess from '../category/resolveCategoryAccess.js';
import request from '../request.js'; import request from '../request.js';
import queryBySku from './queryBySku.js'; import queryBySku from './queryBySku.js';
import resolveArticleBySku from './resolveArticleBySku.js';
function slugify(name) { function slugify(name) {
return name return name
@@ -15,7 +14,7 @@ function slugify(name) {
} }
export default function updateBySku(pool) { export default function updateBySku(pool) {
const access = resolveCategoryAccess(pool); const resolve = resolveArticleBySku(pool);
const load = queryBySku(pool); const load = queryBySku(pool);
return async (googleAuthId, sku, { name }) => { return async (googleAuthId, sku, { name }) => {
@@ -23,17 +22,7 @@ export default function updateBySku(pool) {
throw new Error('Name required'); throw new Error('Name required');
} }
const categoryLookup = await pool const { articleId, languageId } = await resolve(googleAuthId, sku);
.request()
.input('sku', sku)
.query(GET_CATEGORY_ID_BY_SKU);
const row = categoryLookup.recordset[0];
if (!row?.categoryId || !row?.articleId) {
throw new Error('Article not found');
}
const { languageId } = await access(googleAuthId, row.categoryId);
const slug = slugify(name); const slug = slugify(name);
const tx = pool.transaction(); const tx = pool.transaction();
@@ -41,7 +30,7 @@ export default function updateBySku(pool) {
try { try {
const update = await request(pool, tx) const update = await request(pool, tx)
.input('articleId', row.articleId) .input('articleId', articleId)
.input('languageId', languageId) .input('languageId', languageId)
.input('name', name.trim()) .input('name', name.trim())
.input('slug', slug) .input('slug', slug)
@@ -53,7 +42,7 @@ export default function updateBySku(pool) {
await tx.commit(); await tx.commit();
const article = await load(sku, languageId); const article = await load(articleId, languageId);
if (!article) { if (!article) {
throw new Error('Article not found'); throw new Error('Article not found');
} }

View File

@@ -1,11 +1,17 @@
import { CREATE } from '../../sql/company.js'; import { CREATE } from '../../sql/company.js';
import { CREATE as CREATE_CATEGORY } from '../../sql/category.js'; import { CREATE as CREATE_CATEGORY } from '../../sql/category.js';
import {
CREATE_WITHOUT_COMPANY as CREATE_CUSTOMERGROUP,
SET_COMPANY as SET_CUSTOMERGROUP_COMPANY,
} from '../../sql/customergroup.js';
import { ADD as ADD_COMPANYUSER } from '../../sql/companyuser.js'; import { ADD as ADD_COMPANYUSER } from '../../sql/companyuser.js';
import getByName from './getByName.js'; import getByName from './getByName.js';
import langEnsure from '../lang/ensure.js'; import langEnsure from '../lang/ensure.js';
import taxEnsure from '../tax/ensure.js'; import taxEnsure from '../tax/ensure.js';
import request from '../request.js'; import request from '../request.js';
const POS_CUSTOMERGROUP_NAME = 'POS';
export default function create(pool) { export default function create(pool) {
const nameTaken = getByName(pool); const nameTaken = getByName(pool);
const ensureLang = langEnsure(pool); const ensureLang = langEnsure(pool);
@@ -33,6 +39,14 @@ export default function create(pool) {
const rootCategoryId = category.recordset[0].id; const rootCategoryId = category.recordset[0].id;
// Circular FK: create POS group first (company_id null), company with
// poscustomergroup_id NOT NULL, then link the group back to the company.
const posGroup = await request(pool, tx)
.input('name', POS_CUSTOMERGROUP_NAME)
.query(CREATE_CUSTOMERGROUP);
const posCustomerGroupId = posGroup.recordset[0].id;
const result = await request(pool, tx) const result = await request(pool, tx)
.input('name', name) .input('name', name)
.input('rootCategoryId', rootCategoryId) .input('rootCategoryId', rootCategoryId)
@@ -40,10 +54,16 @@ export default function create(pool) {
.input('taxrate', taxrateId) .input('taxrate', taxrateId)
.input('reducedtaxrate', reducedtaxrateId) .input('reducedtaxrate', reducedtaxrateId)
.input('taxfreerate', taxfreerateId) .input('taxfreerate', taxfreerateId)
.input('posCustomerGroupId', posCustomerGroupId)
.query(CREATE); .query(CREATE);
const companyId = result.recordset[0].id; const companyId = result.recordset[0].id;
await request(pool, tx)
.input('id', posCustomerGroupId)
.input('companyId', companyId)
.query(SET_CUSTOMERGROUP_COMPANY);
await request(pool, tx) await request(pool, tx)
.input('companyId', companyId) .input('companyId', companyId)
.input('googleAuthId', googleAuthId) .input('googleAuthId', googleAuthId)
@@ -58,6 +78,7 @@ export default function create(pool) {
taxrateId, taxrateId,
reducedtaxrateId, reducedtaxrateId,
taxfreerateId, taxfreerateId,
posCustomerGroupId,
}; };
} catch (err) { } catch (err) {
try { try {