diff --git a/README.md b/README.md index e6ed854..ce6a37d 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ ID fields in the JS API use camelCase `…Id` (DB columns stay snake_case). `goo | 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 }` | | `delete` | `(companyId)` | `void` | | `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) 3. Ensures tax rows for `taxrate`, `reducedtaxrate`, and `0` → `taxfreerateId` 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`) -`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` diff --git a/src/schema.js b/src/schema.js index 2fea415..ca67659 100644 --- a/src/schema.js +++ b/src/schema.js @@ -109,7 +109,7 @@ BEGIN taxrate INT NULL, reducedtaxrate INT NULL, taxfreerate INT NULL, - poscustomergroup_id INT NULL, + poscustomergroup_id INT NOT NULL, 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_default_language FOREIGN KEY (default_language_id) REFERENCES language(id) ON DELETE SET NULL, @@ -126,7 +126,9 @@ BEGIN CREATE TABLE customergroup ( id INT IDENTITY(1,1) PRIMARY KEY, 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 ); END @@ -270,6 +272,9 @@ BEGIN CONSTRAINT FK_articleean_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE, 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 `; @@ -351,6 +356,9 @@ BEGIN CONSTRAINT FK_categoryarticle_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE, 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 `; @@ -420,6 +428,10 @@ BEGIN 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 ); + -- 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 `; diff --git a/src/sql/article.js b/src/sql/article.js index 49f8951..0292418 100644 --- a/src/sql/article.js +++ b/src/sql/article.js @@ -59,6 +59,45 @@ INNER JOIN categoryarticle ca ON ca.article_id = a.id 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 = ` INSERT INTO article (sku, unit_id, unitamount, weight) OUTPUT INSERTED.id diff --git a/src/sql/articleDetail.js b/src/sql/articleDetail.js index 81695dc..982a4e9 100644 --- a/src/sql/articleDetail.js +++ b/src/sql/articleDetail.js @@ -54,6 +54,25 @@ LEFT JOIN article father ON father.id = a.fatherarticle_id 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 = ` SELECT ca.category_id AS categoryId FROM categoryarticle ca diff --git a/src/sql/company.js b/src/sql/company.js index 32fcdbb..597aa52 100644 --- a/src/sql/company.js +++ b/src/sql/company.js @@ -17,7 +17,8 @@ INSERT INTO company ( default_language_id, taxrate, reducedtaxrate, - taxfreerate + taxfreerate, + poscustomergroup_id ) OUTPUT INSERTED.id VALUES ( @@ -26,7 +27,8 @@ VALUES ( @languageId, @taxrate, @reducedtaxrate, - @taxfreerate + @taxfreerate, + @posCustomerGroupId ) `; diff --git a/src/sql/customergroup.js b/src/sql/customergroup.js new file mode 100644 index 0000000..a0ffd5a --- /dev/null +++ b/src/sql/customergroup.js @@ -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 +`; diff --git a/src/store/article/addImage.js b/src/store/article/addImage.js index 90054fa..7a01e11 100644 --- a/src/store/article/addImage.js +++ b/src/store/article/addImage.js @@ -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 { CREATE as CREATE_PIC } from '../../sql/pic.js'; import processAvifImage from '../../util/processAvifImage.js'; import newFullHash from '../../util/newFullHash.js'; -import resolveCategoryAccess from '../category/resolveCategoryAccess.js'; import request from '../request.js'; +import resolveArticleBySku from './resolveArticleBySku.js'; export default function addImage(pool) { - const access = resolveCategoryAccess(pool); + const resolve = resolveArticleBySku(pool); return async (googleAuthId, sku, image) => { - const categoryLookup = await pool - .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 { articleId } = await resolve(googleAuthId, sku); const processed = await processAvifImage(image); @@ -29,7 +18,7 @@ export default function addImage(pool) { try { const sortResult = await request(pool, tx) - .input('articleId', row.articleId) + .input('articleId', articleId) .query(GET_NEXT_SORT); const sort = sortResult.recordset[0].sort; @@ -51,7 +40,7 @@ export default function addImage(pool) { const picId = picResult.recordset[0].id; await request(pool, tx) - .input('articleId', row.articleId) + .input('articleId', articleId) .input('picId', picId) .input('sort', sort) .query(ADD_ARTICLEPIC); diff --git a/src/store/article/getBySku.js b/src/store/article/getBySku.js index e32b888..bd6a8b7 100644 --- a/src/store/article/getBySku.js +++ b/src/store/article/getBySku.js @@ -1,25 +1,18 @@ -import { GET_CATEGORY_ID_BY_SKU } from '../../sql/article.js'; -import resolveCategoryAccess from '../category/resolveCategoryAccess.js'; +import resolveArticleBySku from './resolveArticleBySku.js'; import queryBySku from './queryBySku.js'; export default function getBySku(pool) { - const access = resolveCategoryAccess(pool); + const resolve = resolveArticleBySku(pool); const load = queryBySku(pool); return async (googleAuthId, sku) => { - const categoryLookup = await pool - .request() - .input('sku', sku) - .query(GET_CATEGORY_ID_BY_SKU); + let t0 = performance.now(); + const { articleId, languageId } = await resolve(googleAuthId, sku); + console.log(`[getBySku] resolveArticleBySku ${(performance.now() - t0).toFixed(1)}ms`); - const categoryId = categoryLookup.recordset[0]?.categoryId; - if (!categoryId) { - throw new Error('Article not found'); - } - - const { languageId } = await access(googleAuthId, categoryId); - - const article = await load(sku, languageId); + t0 = performance.now(); + const article = await load(articleId, languageId); + console.log(`[getBySku] queryBySku (parallel) ${(performance.now() - t0).toFixed(1)}ms`); if (!article) { throw new Error('Article not found'); } diff --git a/src/store/article/queryBySku.js b/src/store/article/queryBySku.js index f11080c..3bc29fe 100644 --- a/src/store/article/queryBySku.js +++ b/src/store/article/queryBySku.js @@ -1,6 +1,6 @@ import { GET_CATEGORY_IDS_BY_ARTICLE_ID, - GET_DETAIL_BY_SKU, + GET_DETAIL_BY_ARTICLE_ID, GET_EANS_BY_ARTICLE_ID, GET_PHOTOS_BY_ARTICLE_ID, GET_PRICES_BY_ARTICLE_ID, @@ -36,25 +36,24 @@ function shapeArticleDetail(row, categoryIds, photos, eans, prices) { } export default function queryBySku(pool) { - return async (sku, languageId) => { - const detail = await pool - .request() - .input('sku', sku) - .input('languageId', languageId) - .query(GET_DETAIL_BY_SKU); + return async (articleId, languageId) => { + const [detail, categories, photos, eans, prices] = await Promise.all([ + pool + .request() + .input('articleId', articleId) + .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]; if (!row) { 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( row, categories.recordset, diff --git a/src/store/article/resolveArticleBySku.js b/src/store/article/resolveArticleBySku.js index 48393d9..3c8effc 100644 --- a/src/store/article/resolveArticleBySku.js +++ b/src/store/article/resolveArticleBySku.js @@ -1,26 +1,31 @@ -import { GET_CATEGORY_ID_BY_SKU } from '../../sql/article.js'; -import resolveCategoryAccess from '../category/resolveCategoryAccess.js'; +import { RESOLVE_ARTICLE_ACCESS_BY_SKU } from '../../sql/article.js'; export default function resolveArticleBySku(pool) { - const access = resolveCategoryAccess(pool); - return async (googleAuthId, sku) => { - const lookup = await pool + const result = await pool .request() .input('sku', sku) - .query(GET_CATEGORY_ID_BY_SKU); + .input('googleAuthId', googleAuthId) + .query(RESOLVE_ARTICLE_ACCESS_BY_SKU); - const row = lookup.recordset[0]; - if (!row?.categoryId || !row?.articleId) { + const row = result.recordset[0]; + if (!row?.articleId || !row?.categoryId) { throw new Error('Article not found'); } - - const { languageId } = await access(googleAuthId, row.categoryId); + if (!row.companyId || !row.rootCategoryId || !row.languageId) { + throw new Error('Parent not found'); + } + if (!row.companyuserId) { + throw new Error('Not authorized'); + } return { articleId: row.articleId, categoryId: row.categoryId, - languageId, + languageId: row.languageId, + companyId: row.companyId, + rootCategoryId: row.rootCategoryId, + posCustomerGroupId: row.posCustomerGroupId ?? null, }; }; } diff --git a/src/store/article/updateBySku.js b/src/store/article/updateBySku.js index 410dced..94f0bcf 100644 --- a/src/store/article/updateBySku.js +++ b/src/store/article/updateBySku.js @@ -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 resolveCategoryAccess from '../category/resolveCategoryAccess.js'; import request from '../request.js'; import queryBySku from './queryBySku.js'; +import resolveArticleBySku from './resolveArticleBySku.js'; function slugify(name) { return name @@ -15,7 +14,7 @@ function slugify(name) { } export default function updateBySku(pool) { - const access = resolveCategoryAccess(pool); + const resolve = resolveArticleBySku(pool); const load = queryBySku(pool); return async (googleAuthId, sku, { name }) => { @@ -23,17 +22,7 @@ export default function updateBySku(pool) { throw new Error('Name required'); } - const categoryLookup = await pool - .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 { articleId, languageId } = await resolve(googleAuthId, sku); const slug = slugify(name); const tx = pool.transaction(); @@ -41,7 +30,7 @@ export default function updateBySku(pool) { try { const update = await request(pool, tx) - .input('articleId', row.articleId) + .input('articleId', articleId) .input('languageId', languageId) .input('name', name.trim()) .input('slug', slug) @@ -53,7 +42,7 @@ export default function updateBySku(pool) { await tx.commit(); - const article = await load(sku, languageId); + const article = await load(articleId, languageId); if (!article) { throw new Error('Article not found'); } diff --git a/src/store/company/create.js b/src/store/company/create.js index 4e1eee0..977fbbb 100644 --- a/src/store/company/create.js +++ b/src/store/company/create.js @@ -1,11 +1,17 @@ import { CREATE } from '../../sql/company.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 getByName from './getByName.js'; import langEnsure from '../lang/ensure.js'; import taxEnsure from '../tax/ensure.js'; import request from '../request.js'; +const POS_CUSTOMERGROUP_NAME = 'POS'; + export default function create(pool) { const nameTaken = getByName(pool); const ensureLang = langEnsure(pool); @@ -33,6 +39,14 @@ export default function create(pool) { 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) .input('name', name) .input('rootCategoryId', rootCategoryId) @@ -40,10 +54,16 @@ export default function create(pool) { .input('taxrate', taxrateId) .input('reducedtaxrate', reducedtaxrateId) .input('taxfreerate', taxfreerateId) + .input('posCustomerGroupId', posCustomerGroupId) .query(CREATE); const companyId = result.recordset[0].id; + await request(pool, tx) + .input('id', posCustomerGroupId) + .input('companyId', companyId) + .query(SET_CUSTOMERGROUP_COMPANY); + await request(pool, tx) .input('companyId', companyId) .input('googleAuthId', googleAuthId) @@ -58,6 +78,7 @@ export default function create(pool) { taxrateId, reducedtaxrateId, taxfreerateId, + posCustomerGroupId, }; } catch (err) { try {