From e5a286f92e87612c13f856196b77e5581b1c9d04 Mon Sep 17 00:00:00 2001
From: Ingrihka
Date: Mon, 26 Oct 2026 12:24:30 +0100
Subject: [PATCH 01/15] feat: butikknavn i databasen og storeName i GraphQL
(#129)
---
backend/db/migrations/002_stores.sql | 28 +++++++++++++++++++
backend/src/resolvers/filters.ts | 8 ++++--
backend/src/resolvers/products.ts | 19 ++++++++-----
backend/src/resolvers/resolvers.ts | 2 ++
backend/src/resolvers/stores.ts | 13 +++++++++
backend/src/schema.ts | 8 +++++-
.../pages/SearchResults/SearchResultsPage.tsx | 5 ++++
.../src/pages/SearchResults/searchQueries.ts | 1 +
.../pages/productDetails/productQueries.ts | 4 +--
frontend/src/types/product.ts | 3 +-
10 files changed, 76 insertions(+), 15 deletions(-)
create mode 100644 backend/db/migrations/002_stores.sql
create mode 100644 backend/src/resolvers/stores.ts
diff --git a/backend/db/migrations/002_stores.sql b/backend/db/migrations/002_stores.sql
new file mode 100644
index 0000000..997b57b
--- /dev/null
+++ b/backend/db/migrations/002_stores.sql
@@ -0,0 +1,28 @@
+-- 002_stores.sql
+-- Butikknavn for kjedene i Kassalapp-dataene.
+-- Dumpen har bare storeCode, ikke navnet, så kjedene legges inn som startdata.
+-- import.ts oppdaterer navnene senere når det kjøres en ny import.
+-- Fila tåler å kjøres flere ganger (IF NOT EXISTS og ON CONFLICT).
+
+CREATE TABLE IF NOT EXISTS stores (
+ code TEXT PRIMARY KEY, -- samme kode som prices.store_code, f.eks. KIWI
+ name TEXT NOT NULL -- navnet som vises i appen, f.eks. Kiwi
+);
+
+INSERT INTO stores (code, name) VALUES
+ -- Dagligvarekjeder
+ ('BUNNPRIS', 'Bunnpris'),
+ ('COOP_NO', 'Coop'),
+ ('JOKER_NO', 'Joker'),
+ ('KIWI', 'Kiwi'),
+ ('MENY_NO', 'Meny'),
+ ('SPAR_NO', 'Spar'),
+ -- Nettbutikker og andre
+ ('ENGROSSNETT_NO', 'Engrossnett'),
+ ('EUROPRIS_NO', 'Europris'),
+ ('FUDI', 'Fudi'),
+ ('HAVARISTEN', 'Havaristen'),
+ ('HOLDBART', 'Holdbart'),
+ ('ODA_NO', 'Oda'),
+ ('PERREROBERT', 'Pierre Robert') -- koden er stavet slik hos Kassalapp
+ON CONFLICT (code) DO NOTHING;
\ No newline at end of file
diff --git a/backend/src/resolvers/filters.ts b/backend/src/resolvers/filters.ts
index f6b69a3..c43174b 100644
--- a/backend/src/resolvers/filters.ts
+++ b/backend/src/resolvers/filters.ts
@@ -1,4 +1,4 @@
-import { pool } from '../db.js';
+import { pool } from "../db.js";
export const categoryFilterCounts = async (
_parent: unknown,
@@ -91,11 +91,13 @@ export const storeFilterCounts = async (
)
SELECT
pr.store_code AS value,
- pr.store_code AS label,
+ COALESCE(s.name, pr.store_code) AS label,
COUNT(DISTINCT p.ean)::integer AS count
FROM prices pr
INNER JOIN products p
ON p.ean = pr.ean
+ LEFT JOIN stores s
+ ON s.code = pr.store_code
WHERE
(
$1::text IS NULL
@@ -107,7 +109,7 @@ export const storeFilterCounts = async (
SELECT id FROM selected_categories
)
)
- GROUP BY pr.store_code
+ GROUP BY pr.store_code, s.name
HAVING COUNT(DISTINCT p.ean) > 0
ORDER BY count DESC, value
`,
diff --git a/backend/src/resolvers/products.ts b/backend/src/resolvers/products.ts
index 681b1ee..4023bfc 100644
--- a/backend/src/resolvers/products.ts
+++ b/backend/src/resolvers/products.ts
@@ -238,17 +238,22 @@ export const productCategory = async (product: { categoryId?: number | null }) =
return result.rows[0] ?? null;
};
+// Prisene for én vare, billigst først.
+// Butikknavnet hentes fra stores. Mangler butikken der, vises koden i stedet.
export const productPrices = async (product: { ean: string }) => {
const result = await pool.query(
`
SELECT
- store_code AS "storeCode",
- price,
- unit_price AS "unitPrice",
- url
- FROM prices
- WHERE ean = $1
- ORDER BY price
+ pr.store_code AS "storeCode",
+ COALESCE(s.name, pr.store_code) AS "storeName",
+ pr.price,
+ pr.unit_price AS "unitPrice",
+ pr.url
+ FROM prices pr
+ LEFT JOIN stores s
+ ON s.code = pr.store_code
+ WHERE pr.ean = $1
+ ORDER BY pr.price
`,
[product.ean],
);
diff --git a/backend/src/resolvers/resolvers.ts b/backend/src/resolvers/resolvers.ts
index 0af48a3..8bdd063 100644
--- a/backend/src/resolvers/resolvers.ts
+++ b/backend/src/resolvers/resolvers.ts
@@ -18,6 +18,7 @@ import {
shoppingList,
shoppingListItems,
} from './shoppingLists.js';
+import { stores } from './stores.js';
// Samler resolverne fra hvert område, så alle spørringer og mutasjoner står på ett sted
export const resolvers = {
@@ -26,6 +27,7 @@ export const resolvers = {
productsCount,
product,
categories,
+ stores,
shoppingList,
categoryFilterCounts,
storeFilterCounts,
diff --git a/backend/src/resolvers/stores.ts b/backend/src/resolvers/stores.ts
new file mode 100644
index 0000000..f05bf29
--- /dev/null
+++ b/backend/src/resolvers/stores.ts
@@ -0,0 +1,13 @@
+import { pool } from "../db.js";
+
+// Alle butikkjedene med navn, sortert alfabetisk.
+// Brukes av frontend til å vise navn der den bare har butikkoden.
+export const stores = async () => {
+ const result = await pool.query(`
+ SELECT code, name
+ FROM stores
+ ORDER BY name
+ `);
+
+ return result.rows;
+};
diff --git a/backend/src/schema.ts b/backend/src/schema.ts
index 019956d..74cf0db 100644
--- a/backend/src/schema.ts
+++ b/backend/src/schema.ts
@@ -10,9 +10,15 @@ export const typeDefs = `#graphql
label: String!
count: Int!
}
+
+ type Store {
+ code: String!
+ name: String!
+ }
type Price {
storeCode: String!
+ storeName: String!
price: Float!
unitPrice: Float
url: String
@@ -26,7 +32,6 @@ export const typeDefs = `#graphql
categoryId: ID
category: Category
prices: [Price!]!
-
ingredients: String
nutrition: [Nutrition!]!
allergens: [Allergen!]!
@@ -80,6 +85,7 @@ export const typeDefs = `#graphql
product(ean: String!): Product
categories: [Category!]!
+ stores: [Store!]!
shoppingList(id: ID!): ShoppingList
categoryFilterCounts(
diff --git a/frontend/src/pages/SearchResults/SearchResultsPage.tsx b/frontend/src/pages/SearchResults/SearchResultsPage.tsx
index bf6a522..6a7ee06 100644
--- a/frontend/src/pages/SearchResults/SearchResultsPage.tsx
+++ b/frontend/src/pages/SearchResults/SearchResultsPage.tsx
@@ -110,6 +110,7 @@ function normalizeProducts(
categoryId?: string | null;
prices?: ReadonlyArray<{
storeCode?: string;
+ storeName?: string;
price?: number;
unitPrice?: number | null;
} | null>;
@@ -136,6 +137,10 @@ function normalizeProducts(
return [{
storeCode: price.storeCode,
+ storeName:
+ typeof price.storeName === "string"
+ ? price.storeName
+ : price.storeCode,
price: price.price,
unitPrice:
typeof price.unitPrice === "number"
diff --git a/frontend/src/pages/SearchResults/searchQueries.ts b/frontend/src/pages/SearchResults/searchQueries.ts
index e16b259..14c53ea 100644
--- a/frontend/src/pages/SearchResults/searchQueries.ts
+++ b/frontend/src/pages/SearchResults/searchQueries.ts
@@ -57,6 +57,7 @@ export const SEARCH_PRODUCTS_QUERY: TypedDocumentNode<
categoryId
prices {
storeCode
+ storeName
price
unitPrice
}
diff --git a/frontend/src/pages/productDetails/productQueries.ts b/frontend/src/pages/productDetails/productQueries.ts
index c127f3d..4ef331b 100644
--- a/frontend/src/pages/productDetails/productQueries.ts
+++ b/frontend/src/pages/productDetails/productQueries.ts
@@ -1,4 +1,3 @@
-
import { gql } from "@apollo/client";
import type { TypedDocumentNode } from "@apollo/client";
import type { Product } from "../../types/product";
@@ -27,6 +26,7 @@ export const PRODUCT_QUERY: TypedDocumentNode<
}
prices {
storeCode
+ storeName
price
unitPrice
url
@@ -43,4 +43,4 @@ export const PRODUCT_QUERY: TypedDocumentNode<
}
}
}
-`;
\ No newline at end of file
+`;
diff --git a/frontend/src/types/product.ts b/frontend/src/types/product.ts
index 2385f4e..dd71a65 100644
--- a/frontend/src/types/product.ts
+++ b/frontend/src/types/product.ts
@@ -1,6 +1,7 @@
// Pris i én butikk
export type ProductPrice = {
storeCode: string;
+ storeName: string; //navn fra backend
price: number;
unitPrice: number | null;
};
@@ -38,5 +39,3 @@ export type Product = Omit & {
unit: string;
}[];
};
-
-
From ba888715b19f9918c63cf58b22a6e4c95a17aab1 Mon Sep 17 00:00:00 2001
From: Ingrihka
Date: Mon, 26 Oct 2026 12:52:36 +0100
Subject: [PATCH 02/15] refactor: butikknavn fra GraphQL i stedet for
hardkodede lister (#129)
---
frontend/src/hooks/useStoreNames.ts | 44 +++++++++++++++++++
.../pages/SearchResults/SearchEmptyState.tsx | 23 +++-------
.../src/pages/SearchResults/SearchFilters.tsx | 18 ++------
.../pages/SearchResults/SearchProductList.tsx | 15 +------
.../pages/SearchResults/SearchResultsPage.tsx | 30 ++++---------
.../productDetails/ProductDetailsPage.tsx | 19 +-------
6 files changed, 63 insertions(+), 86 deletions(-)
create mode 100644 frontend/src/hooks/useStoreNames.ts
diff --git a/frontend/src/hooks/useStoreNames.ts b/frontend/src/hooks/useStoreNames.ts
new file mode 100644
index 0000000..9bbbecc
--- /dev/null
+++ b/frontend/src/hooks/useStoreNames.ts
@@ -0,0 +1,44 @@
+import { useMemo } from "react";
+import { gql } from "@apollo/client";
+import type { TypedDocumentNode } from "@apollo/client";
+import { useQuery } from "@apollo/client/react";
+
+// ---------- Spørring ----------
+
+type Store = {
+ code: string;
+ name: string;
+};
+
+type StoresData = {
+ stores: Store[];
+};
+
+const STORES_QUERY: TypedDocumentNode = gql`
+ query Stores {
+ stores {
+ code
+ name
+ }
+ }
+`;
+
+// ---------- Hook ----------
+
+// Gir navnet på en butikk ut fra koden, f.eks. "MENY_NO" → "Meny".
+// Navnene hentes fra databasen (tabellen stores). Apollo husker svaret,
+// så spørringen kjøres bare én gang selv om hooken brukes mange steder.
+// Mangler navnet (mens den laster, eller ukjent butikk), vises koden.
+export function useStoreNames() {
+ const { data } = useQuery(STORES_QUERY);
+
+ // Oppslag fra kode til navn. Bygges bare på nytt når dataene endres.
+ const storeNames = useMemo(
+ () => new Map((data?.stores ?? []).map((store) => [store.code, store.name])),
+ [data],
+ );
+
+ const getStoreName = (code: string) => storeNames.get(code) ?? code;
+
+ return { getStoreName };
+}
\ No newline at end of file
diff --git a/frontend/src/pages/SearchResults/SearchEmptyState.tsx b/frontend/src/pages/SearchResults/SearchEmptyState.tsx
index 9264e0f..1bcbda5 100644
--- a/frontend/src/pages/SearchResults/SearchEmptyState.tsx
+++ b/frontend/src/pages/SearchResults/SearchEmptyState.tsx
@@ -1,5 +1,6 @@
import type { FilterCount } from "../../types/filters";
+import { useStoreNames } from "../../hooks/useStoreNames";
type SearchEmptyStateProps = {
searchTerm: string;
@@ -10,19 +11,6 @@ type SearchEmptyStateProps = {
onResetFilters: () => void;
};
-const storeNames: Record = {
- KIWI: "Kiwi",
- MENY_NO: "Meny",
- SPAR_NO: "Spar",
- BUNNPRIS: "Bunnpris",
- COOP_NO: "Coop",
- JOKER_NO: "Joker",
- ODA_NO: "Oda",
- EUROPRIS_NO: "Europris",
- ENGROSSNETT_NO: "Engrosnett",
- HAVARISTEN: "Havaristen",
-};
-
export default function SearchEmptyState({
searchTerm,
hasActiveFilters,
@@ -31,9 +19,9 @@ export default function SearchEmptyState({
onSelectStore,
onResetFilters,
}: SearchEmptyStateProps) {
- const selectedStoreNames = selectedStores.map(
- (code) => storeNames[code] ?? code,
- );
+ const { getStoreName } = useStoreNames();
+
+ const selectedStoreNames = selectedStores.map(getStoreName);
const storeDescription =
selectedStoreNames.length === 1
@@ -108,8 +96,7 @@ export default function SearchEmptyState({
}
>
- {storeNames[store.value] ??
- store.label}
+ {store.label}
diff --git a/frontend/src/pages/SearchResults/SearchFilters.tsx b/frontend/src/pages/SearchResults/SearchFilters.tsx
index e5b00c2..9abc61c 100644
--- a/frontend/src/pages/SearchResults/SearchFilters.tsx
+++ b/frontend/src/pages/SearchResults/SearchFilters.tsx
@@ -11,18 +11,6 @@ type SearchFiltersProps = {
onStoresChange: (values: string[]) => void;
};
-const storeNames: Record = {
- KIWI: "Kiwi",
- MENY_NO: "Meny",
- SPAR_NO: "Spar",
- BUNNPRIS: "Bunnpris",
- COOP_NO: "Coop",
- JOKER_NO: "Joker",
- ODA_NO: "Oda",
- EUROPRIS_NO: "Europris",
- ENGROSSNETT_NO: "Engrosnett",
-};
-
const collator = new Intl.Collator("nb-NO", {
sensitivity: "base",
});
@@ -43,8 +31,8 @@ export default function SearchFilters({
const sortedStores = [...stores].sort((a, b) =>
collator.compare(
- storeNames[a.value] ?? a.label,
- storeNames[b.value] ?? b.label,
+ a.label,
+ b.label,
),
);
@@ -94,7 +82,7 @@ export default function SearchFilters({
{sortedStores.map((store) => (
diff --git a/frontend/src/pages/SearchResults/SearchProductList.tsx b/frontend/src/pages/SearchResults/SearchProductList.tsx
index 49cd793..cb9dfee 100644
--- a/frontend/src/pages/SearchResults/SearchProductList.tsx
+++ b/frontend/src/pages/SearchResults/SearchProductList.tsx
@@ -16,18 +16,6 @@ const formatter = new Intl.NumberFormat("nb-NO", {
maximumFractionDigits: 2,
});
-const storeNames: Record = {
- KIWI: "Kiwi",
- MENY_NO: "Meny",
- SPAR_NO: "Spar",
- BUNNPRIS: "Bunnpris",
- COOP_NO: "Coop",
- JOKER_NO: "Joker",
- ODA_NO: "Oda",
- EUROPRIS_NO: "Europris",
- ENGROSSNETT_NO: "Engrosnett",
-};
-
function getDisplayPrice(
prices: ProductPrice[],
selectedStores: string[],
@@ -90,8 +78,7 @@ export default function SearchProductList({
}
chain={
displayPrice
- ? (storeNames[displayPrice.storeCode] ??
- displayPrice.storeCode)
+ ? displayPrice.storeName
: undefined
}
onAdd={onAddProduct ? () => onAddProduct(product) : undefined
diff --git a/frontend/src/pages/SearchResults/SearchResultsPage.tsx b/frontend/src/pages/SearchResults/SearchResultsPage.tsx
index 6a7ee06..ca427e0 100644
--- a/frontend/src/pages/SearchResults/SearchResultsPage.tsx
+++ b/frontend/src/pages/SearchResults/SearchResultsPage.tsx
@@ -32,6 +32,7 @@ import type { SearchSort, FilterCount } from "../../types/filters";
import "./SearchResultsPage.css";
import SearchEmptyState from "./SearchEmptyState";
+import { useStoreNames } from "../../hooks/useStoreNames";
import { useSearchParams } from "react-router";
@@ -53,22 +54,6 @@ const CATEGORY_NAMES_QUERY: TypedDocumentNode = gql`
}
`;
-const storeNames: Record = {
- KIWI: "Kiwi",
- MENY_NO: "Meny",
- SPAR_NO: "Spar",
- BUNNPRIS: "Bunnpris",
- COOP_NO: "Coop",
- JOKER_NO: "Joker",
- ODA_NO: "Oda",
- EUROPRIS_NO: "Europris",
- ENGROSSNETT_NO: "Engrosnett",
- HOLDBART: "Holdbart",
- HAVARISTEN: "Havaristen",
- FUDI: "Fudi",
- PERREROBERT: "Perrerobert",
-};
-
const collator = new Intl.Collator("nb-NO", {
sensitivity: "base",
});
@@ -163,6 +148,8 @@ function normalizeProducts(
export default function SearchResultsPage() {
const [searchParams] = useSearchParams();
+ // Butikknavn fra databasen, f.eks. "MENY_NO" → "Meny"
+ const { getStoreName } = useStoreNames();
const urlSearchTerm = searchParams.get("q");
// Hent lagrede innstillinger kun ved første rendering.
@@ -422,16 +409,15 @@ export default function SearchResultsPage() {
...selectedStores,
].sort((a, b) =>
collator.compare(
- storeNames[a] ?? a,
- storeNames[b] ?? b,
+ getStoreName(a),
+ getStoreName(b),
),
);
const storeHeading =
selectedStores.length === 1
? ` hos ${
- storeNames[selectedStores[0]] ??
- selectedStores[0]
+ getStoreName(selectedStores[0])
}`
: selectedStores.length > 1
? ` hos ${selectedStores.length} butikker`
@@ -552,8 +538,8 @@ export default function SearchResultsPage() {
{sortedSelectedStores.map((value) => (
{
preservePosition();
handleStoresChange(
diff --git a/frontend/src/pages/productDetails/ProductDetailsPage.tsx b/frontend/src/pages/productDetails/ProductDetailsPage.tsx
index 5528189..9eaa420 100644
--- a/frontend/src/pages/productDetails/ProductDetailsPage.tsx
+++ b/frontend/src/pages/productDetails/ProductDetailsPage.tsx
@@ -8,21 +8,6 @@ type ProductDetailsPageProps = {
ean: string;
};
-const storeNames: Record = {
- KIWI: "Kiwi",
- MENY_NO: "Meny",
- SPAR_NO: "Spar",
- BUNNPRIS: "Bunnpris",
- COOP_NO: "Coop",
- JOKER_NO: "Joker",
- ODA_NO: "Oda",
- EUROPRIS_NO: "Europris",
- ENGROSSNETT_NO: "Engrosnett",
-};
-
-const getStoreName = (storeCode: string) =>
- storeNames[storeCode] ?? storeCode;
-
export default function ProductDetailsPage({
ean,
}: ProductDetailsPageProps) {
@@ -166,7 +151,7 @@ export default function ProductDetailsPage({
- BILLIGST HOS {getStoreName(cheapest.storeCode).toUpperCase()}
+ BILLIGST HOS {cheapest.storeName.toUpperCase()}
>
) : (
@@ -187,7 +172,7 @@ export default function ProductDetailsPage({
Date: Mon, 26 Oct 2026 13:01:59 +0100
Subject: [PATCH 03/15] fix(#135): move navigation menu to right side
---
frontend/src/components/navigationMenu/NavigationMenu.css | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/frontend/src/components/navigationMenu/NavigationMenu.css b/frontend/src/components/navigationMenu/NavigationMenu.css
index 4a4017f..7e81c30 100644
--- a/frontend/src/components/navigationMenu/NavigationMenu.css
+++ b/frontend/src/components/navigationMenu/NavigationMenu.css
@@ -19,7 +19,7 @@
.navigation-menu {
position: absolute;
- inset: 0 auto 0 0;
+ inset: 0 0 0 auto;
display: flex;
flex-direction: column;
width: min(320px, 90vw);
@@ -27,7 +27,7 @@
box-sizing: border-box;
padding: 24px 20px;
background: var(--bg-page);
- border-right: 1px solid var(--border-hairline);
+ border-left: 1px solid var(--border-hairline);
color: var(--text-primary);
overflow-y: auto;
}
From 0273c90817baeb62fc30ff5236cfb28bb057ff56 Mon Sep 17 00:00:00 2001
From: Linde Vrenne
Date: Mon, 26 Oct 2026 13:35:10 +0100
Subject: [PATCH 04/15] Legg til Prettier-oppsett for frontend og backend
---
.prettierrc.json | 8 ++++++++
.vscode/extensions.json | 3 +++
.vscode/settings.json | 5 +++++
backend/.prettierignore | 3 +++
backend/package-lock.json | 17 +++++++++++++++++
backend/package.json | 5 ++++-
frontend/.prettierignore | 2 ++
frontend/package-lock.json | 17 +++++++++++++++++
frontend/package.json | 5 ++++-
9 files changed, 63 insertions(+), 2 deletions(-)
create mode 100644 .prettierrc.json
create mode 100644 .vscode/extensions.json
create mode 100644 .vscode/settings.json
create mode 100644 backend/.prettierignore
create mode 100644 frontend/.prettierignore
diff --git a/.prettierrc.json b/.prettierrc.json
new file mode 100644
index 0000000..b8ea967
--- /dev/null
+++ b/.prettierrc.json
@@ -0,0 +1,8 @@
+{
+ "semi": true,
+ "singleQuote": false,
+ "trailingComma": "all",
+ "tabWidth": 2,
+ "printWidth": 80,
+ "endOfLine": "lf"
+}
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 0000000..d7df89c
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,3 @@
+{
+ "recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
+}
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..5be1482
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,5 @@
+{
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
+ "editor.formatOnSave": true,
+ "prettier.requireConfig": true
+}
diff --git a/backend/.prettierignore b/backend/.prettierignore
new file mode 100644
index 0000000..7748f9e
--- /dev/null
+++ b/backend/.prettierignore
@@ -0,0 +1,3 @@
+dist
+data
+package-lock.json
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 6af8421..2cb56b9 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -17,6 +17,7 @@
"devDependencies": {
"@types/node": "^24.19.0",
"@types/pg": "^8.23.1",
+ "prettier": "3.9.10",
"tsx": "^4.23.15",
"typescript": "~6.0.2"
}
@@ -1722,6 +1723,22 @@
"node": ">=0.10.0"
}
},
+ "node_modules/prettier": {
+ "version": "3.9.10",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz",
+ "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "prettier": "bin/prettier.cjs"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/prettier/prettier?sponsor=1"
+ }
+ },
"node_modules/qs": {
"version": "6.16.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
diff --git a/backend/package.json b/backend/package.json
index cbe29fc..000d7a5 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -7,7 +7,9 @@
"build": "tsc",
"start": "node dist/index.js",
"import": "tsx src/scripts/import.ts",
- "seed": "tsx src/scripts/seed.ts"
+ "seed": "tsx src/scripts/seed.ts",
+ "format": "prettier --write .",
+ "format:check": "prettier --check ."
},
"keywords": [],
"author": "",
@@ -22,6 +24,7 @@
"devDependencies": {
"@types/node": "^24.19.0",
"@types/pg": "^8.23.1",
+ "prettier": "3.9.10",
"tsx": "^4.23.15",
"typescript": "~6.0.2"
}
diff --git a/frontend/.prettierignore b/frontend/.prettierignore
new file mode 100644
index 0000000..67af583
--- /dev/null
+++ b/frontend/.prettierignore
@@ -0,0 +1,2 @@
+dist
+package-lock.json
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index b4aa3b8..68c6492 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -28,6 +28,7 @@
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.6",
"globals": "^17.12.0",
+ "prettier": "3.9.10",
"typescript": "~6.0.2",
"typescript-eslint": "^8.69.0",
"vite": "^8.3.0"
@@ -2612,6 +2613,22 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/prettier": {
+ "version": "3.9.10",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz",
+ "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "prettier": "bin/prettier.cjs"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/prettier/prettier?sponsor=1"
+ }
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index d63f188..161fc75 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -7,7 +7,9 @@
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "format": "prettier --write .",
+ "format:check": "prettier --check ."
},
"dependencies": {
"@apollo/client": "^4.3.2",
@@ -30,6 +32,7 @@
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.6",
"globals": "^17.12.0",
+ "prettier": "3.9.10",
"typescript": "~6.0.2",
"typescript-eslint": "^8.69.0",
"vite": "^8.3.0"
From 96d2c1f6533cd122616a153bd0c3992e0fe8b1f5 Mon Sep 17 00:00:00 2001
From: Linde Vrenne
Date: Mon, 26 Oct 2026 13:37:33 +0100
Subject: [PATCH 05/15] Formater all kode med Prettier
---
backend/src/context.ts | 9 +-
backend/src/db.ts | 6 +-
backend/src/index.ts | 18 +-
backend/src/resolvers/filters.ts | 2 +-
backend/src/resolvers/products.ts | 107 +++---
backend/src/resolvers/resolvers.ts | 11 +-
backend/src/resolvers/shoppingLists.ts | 64 ++--
backend/src/scripts/explore-kassalapp.ts | 104 +++--
backend/src/scripts/import.ts | 33 +-
backend/src/scripts/seed.ts | 54 +--
frontend/README.md | 24 +-
frontend/eslint.config.js | 18 +-
frontend/index.html | 11 +-
frontend/src/App.tsx | 10 +-
frontend/src/apolloClient.ts | 2 +-
frontend/src/components/badge/Badge.css | 30 +-
frontend/src/components/button/Button.css | 62 +--
frontend/src/components/card/Card.css | 22 +-
.../components/categoryCard/CategoryCard.css | 102 ++---
frontend/src/components/checkbox/Checkbox.css | 46 +--
frontend/src/components/checkbox/Checkbox.tsx | 5 +-
.../src/components/filterChip/FilterChip.css | 44 +--
.../src/components/filterRow/FilterRow.css | 50 +--
frontend/src/components/header/Header.css | 2 -
frontend/src/components/header/Header.tsx | 23 +-
frontend/src/components/logo/Logo.css | 2 +-
.../src/components/menuButton/MenuButton.css | 1 -
.../src/components/menuButton/MenuButton.tsx | 8 +-
.../navigationMenu/NavigationMenu.tsx | 14 +-
frontend/src/components/noteItem/NoteItem.css | 28 +-
frontend/src/components/noteItem/NoteItem.tsx | 6 +-
.../src/components/resultRow/ResultRow.css | 183 +++++----
.../src/components/resultRow/ResultRow.tsx | 5 +-
.../components/searchfield/Searchfield.css | 106 +++---
frontend/src/index.css | 5 +-
frontend/src/main.tsx | 13 +-
.../pages/SearchResults/SearchEmptyState.tsx | 44 +--
.../src/pages/SearchResults/SearchFilters.tsx | 9 +-
.../pages/SearchResults/SearchPagination.tsx | 23 +-
.../pages/SearchResults/SearchProductList.tsx | 17 +-
.../pages/SearchResults/SearchResultsPage.css | 56 +--
.../pages/SearchResults/SearchResultsPage.tsx | 299 ++++++---------
.../pages/SearchResults/SearchSortSelect.tsx | 37 +-
.../pages/SearchResults/searchPreferences.ts | 34 +-
.../src/pages/SearchResults/searchQueries.ts | 11 +-
frontend/src/pages/home/HomePage.css | 4 +-
frontend/src/pages/home/HomePage.tsx | 96 ++---
frontend/src/pages/home/categoryNavigation.ts | 4 +-
frontend/src/pages/home/homeCategories.ts | 1 -
.../productDetails/ProductDetailsPage.css | 10 +-
.../productDetails/ProductDetailsPage.tsx | 358 ++++++++----------
.../pages/productDetails/productQueries.ts | 3 +-
.../pages/shoppingLists/PreviousListRow.tsx | 21 +-
.../pages/shoppingLists/PreviousListsPage.css | 5 +-
.../pages/shoppingLists/PreviousListsPage.tsx | 152 ++++----
.../pages/shoppingLists/ShoppingListCard.css | 7 +-
.../pages/shoppingLists/ShoppingListCard.tsx | 48 +--
.../pages/shoppingLists/ShoppingListsPage.css | 5 +-
.../pages/shoppingLists/ShoppingListsPage.tsx | 201 +++++-----
.../pages/shoppingLists/shoppingListTabs.ts | 2 +-
frontend/src/theme.css | 21 +-
frontend/src/types/product.ts | 2 -
frontend/vite.config.ts | 15 +-
63 files changed, 1215 insertions(+), 1500 deletions(-)
diff --git a/backend/src/context.ts b/backend/src/context.ts
index 6d60622..2b28ae0 100644
--- a/backend/src/context.ts
+++ b/backend/src/context.ts
@@ -1,23 +1,24 @@
-import type { IncomingMessage } from 'node:http';
+import type { IncomingMessage } from "node:http";
export interface Context {
ownerId: string;
}
// Godtar bare id-er som ser ut som en uuid fra crypto.randomUUID()
-const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const UUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export const createContext = async ({
req,
}: {
req: IncomingMessage;
}): Promise => {
- const header = req.headers['x-user-id'];
+ const header = req.headers["x-user-id"];
const userId = Array.isArray(header) ? header[0] : header;
// Uten gyldig header (f.eks. i Apollo Sandbox) brukes 'anonymous', som i dag.
// Senere kan innlogget bruker hentes her i stedet.
return {
- ownerId: userId && UUID_PATTERN.test(userId) ? userId : 'anonymous',
+ ownerId: userId && UUID_PATTERN.test(userId) ? userId : "anonymous",
};
};
diff --git a/backend/src/db.ts b/backend/src/db.ts
index f8034d6..59e969c 100644
--- a/backend/src/db.ts
+++ b/backend/src/db.ts
@@ -1,9 +1,9 @@
-import 'dotenv/config';
-import pg from 'pg';
+import "dotenv/config";
+import pg from "pg";
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
- throw new Error('DATABASE_URL mangler i backend/.env (se .env.example)');
+ throw new Error("DATABASE_URL mangler i backend/.env (se .env.example)");
}
// Én felles tilkoblingspool for hele backenden.
diff --git a/backend/src/index.ts b/backend/src/index.ts
index 3cff853..1bb3ddf 100644
--- a/backend/src/index.ts
+++ b/backend/src/index.ts
@@ -1,11 +1,15 @@
-import 'dotenv/config';
-import { ApolloServer } from '@apollo/server';
-import { startStandaloneServer } from '@apollo/server/standalone';
-import { typeDefs } from './schema.js';
-import { resolvers } from './resolvers/resolvers.js';
-import { createContext, type Context } from './context.js';
+import "dotenv/config";
+import { ApolloServer } from "@apollo/server";
+import { startStandaloneServer } from "@apollo/server/standalone";
+import { typeDefs } from "./schema.js";
+import { resolvers } from "./resolvers/resolvers.js";
+import { createContext, type Context } from "./context.js";
-const server = new ApolloServer({ typeDefs, resolvers, introspection: true });
+const server = new ApolloServer({
+ typeDefs,
+ resolvers,
+ introspection: true,
+});
// Port 3001 er kravet i oppgaven, men kan overstyres i .env
const port = Number(process.env.PORT ?? 3001);
diff --git a/backend/src/resolvers/filters.ts b/backend/src/resolvers/filters.ts
index f6b69a3..b34d0d3 100644
--- a/backend/src/resolvers/filters.ts
+++ b/backend/src/resolvers/filters.ts
@@ -1,4 +1,4 @@
-import { pool } from '../db.js';
+import { pool } from "../db.js";
export const categoryFilterCounts = async (
_parent: unknown,
diff --git a/backend/src/resolvers/products.ts b/backend/src/resolvers/products.ts
index 681b1ee..e762415 100644
--- a/backend/src/resolvers/products.ts
+++ b/backend/src/resolvers/products.ts
@@ -1,4 +1,4 @@
-import { pool } from '../db.js';
+import { pool } from "../db.js";
export const categories = async () => {
const result = await pool.query(`
@@ -14,8 +14,8 @@ export const categories = async () => {
};
export const product = async (_parent: unknown, args: { ean: string }) => {
- const result = await pool.query(
- `
+ const result = await pool.query(
+ `
SELECT
ean,
name,
@@ -28,10 +28,10 @@ export const product = async (_parent: unknown, args: { ean: string }) => {
FROM products
WHERE ean = $1
`,
- [args.ean],
- );
+ [args.ean],
+ );
- return result.rows[0] ?? null;
+ return result.rows[0] ?? null;
};
export const products = async (
@@ -49,20 +49,11 @@ export const products = async (
const categories = args.categories ?? [];
const storeCodes = args.storeCodes ?? [];
- const allowedSorts = [
- "relevance",
- "price_asc",
- "price_desc",
- ];
+ const allowedSorts = ["relevance", "price_asc", "price_desc"];
- const sort = allowedSorts.includes(args.sort ?? "")
- ? args.sort
- : "relevance";
+ const sort = allowedSorts.includes(args.sort ?? "") ? args.sort : "relevance";
- const limit = Math.min(
- Math.max(args.limit ?? 20, 1),
- 100,
- );
+ const limit = Math.min(Math.max(args.limit ?? 20, 1), 100);
const offset = Math.max(args.offset ?? 0, 0);
@@ -150,14 +141,7 @@ export const products = async (
LIMIT $4
OFFSET $5
`,
- [
- search,
- categories,
- storeCodes,
- limit,
- offset,
- sort,
- ],
+ [search, categories, storeCodes, limit, offset, sort],
);
return result.rows;
@@ -218,7 +202,9 @@ export const productsCount = async (
return result.rows[0].count;
};
-export const productCategory = async (product: { categoryId?: number | null }) => {
+export const productCategory = async (product: {
+ categoryId?: number | null;
+}) => {
if (!product.categoryId) {
return null;
}
@@ -256,37 +242,38 @@ export const productPrices = async (product: { ean: string }) => {
return result.rows;
};
-export const nutrition = (
- product: {
- nutrition?: {
- code: string;
- display_name: string;
- amount: number;
- unit: string;
- }[] | null;
- }) => {
- return (product.nutrition ?? []).map((item) => ({
- code: item.code,
- displayName: item.display_name,
- amount: item.amount,
- unit: item.unit,
- }));
- };
+export const nutrition = (product: {
+ nutrition?:
+ | {
+ code: string;
+ display_name: string;
+ amount: number;
+ unit: string;
+ }[]
+ | null;
+}) => {
+ return (product.nutrition ?? []).map((item) => ({
+ code: item.code,
+ displayName: item.display_name,
+ amount: item.amount,
+ unit: item.unit,
+ }));
+};
-
-export const allergens =(
- product: {
- allergens?: {
- code: string;
- display_name: string;
- contains: string;
- }[] | null;
- }) => {
- return (product.allergens ?? [])
- .filter((item) => item.contains !== "NO")
- .map((item) => ({
- code: item.code,
- displayName: item.display_name,
- contains: item.contains,
- }));
- };
+export const allergens = (product: {
+ allergens?:
+ | {
+ code: string;
+ display_name: string;
+ contains: string;
+ }[]
+ | null;
+}) => {
+ return (product.allergens ?? [])
+ .filter((item) => item.contains !== "NO")
+ .map((item) => ({
+ code: item.code,
+ displayName: item.display_name,
+ contains: item.contains,
+ }));
+};
diff --git a/backend/src/resolvers/resolvers.ts b/backend/src/resolvers/resolvers.ts
index e78abd6..cf6e24c 100644
--- a/backend/src/resolvers/resolvers.ts
+++ b/backend/src/resolvers/resolvers.ts
@@ -1,7 +1,4 @@
-import {
- categoryFilterCounts,
- storeFilterCounts,
-} from './filters.js';
+import { categoryFilterCounts, storeFilterCounts } from "./filters.js";
import {
allergens,
categories,
@@ -11,7 +8,7 @@ import {
productPrices,
products,
productsCount,
-} from './products.js';
+} from "./products.js";
import {
addItemToList,
completeShoppingList,
@@ -28,7 +25,7 @@ import {
shoppingListItems,
updateItemNote,
updateItemQuantity,
-} from './shoppingLists.js';
+} from "./shoppingLists.js";
// Samler resolverne fra hvert område, så alle spørringer og mutasjoner står på ett sted
export const resolvers = {
@@ -60,7 +57,7 @@ export const resolvers = {
category: productCategory,
prices: productPrices,
nutrition,
- allergens
+ allergens,
},
ShoppingList: {
diff --git a/backend/src/resolvers/shoppingLists.ts b/backend/src/resolvers/shoppingLists.ts
index 53e7dc8..b7af007 100644
--- a/backend/src/resolvers/shoppingLists.ts
+++ b/backend/src/resolvers/shoppingLists.ts
@@ -1,7 +1,7 @@
-import { pool } from '../db.js';
-import type { Context } from '../context.js';
+import { pool } from "../db.js";
+import type { Context } from "../context.js";
-type ListStatus = 'ACTIVE' | 'DONE';
+type ListStatus = "ACTIVE" | "DONE";
// Grenser for det brukeren kan skrive inn. Hindrer veldig lange tekster,
// og at antallet blir større enn INTEGER-kolonnen i databasen tåler.
@@ -27,7 +27,7 @@ const LIST_COLUMNS = `
// rett til frontend.
const parseId = (id: string) => {
if (!/^\d+$/.test(id)) {
- throw new Error('Ugyldig id');
+ throw new Error("Ugyldig id");
}
return id;
@@ -36,8 +36,8 @@ const parseId = (id: string) => {
const validateName = (name: string) => {
const trimmed = name.trim();
- if (trimmed === '') {
- throw new Error('Navnet kan ikke være tomt');
+ if (trimmed === "") {
+ throw new Error("Navnet kan ikke være tomt");
}
if (trimmed.length > MAX_NAME_LENGTH) {
@@ -73,11 +73,11 @@ const getOwnedList = async (
const list = result.rows[0];
if (!list) {
- throw new Error('Handlelisten finnes ikke');
+ throw new Error("Handlelisten finnes ikke");
}
- if (mustBeActive && list.status === 'DONE') {
- throw new Error('Handlelisten er fullført og kan ikke endres');
+ if (mustBeActive && list.status === "DONE") {
+ throw new Error("Handlelisten er fullført og kan ikke endres");
}
return list;
@@ -99,11 +99,11 @@ const getActiveListIdForItem = async (itemId: string, ownerId: string) => {
const row = result.rows[0];
if (!row) {
- throw new Error('Varen finnes ikke');
+ throw new Error("Varen finnes ikke");
}
- if (row.status === 'DONE') {
- throw new Error('Handlelisten er fullført og kan ikke endres');
+ if (row.status === "DONE") {
+ throw new Error("Handlelisten er fullført og kan ikke endres");
}
return row.list_id as string;
@@ -227,7 +227,10 @@ export const renameShoppingList = async (
// Nytt navn er lov også på fullførte lister, det endrer ikke historikken
const name = validateName(args.name);
await getOwnedList(args.id, context.ownerId);
- await pool.query(`UPDATE shopping_lists SET name = $1 WHERE id = $2`, [name, args.id]);
+ await pool.query(`UPDATE shopping_lists SET name = $1 WHERE id = $2`, [
+ name,
+ args.id,
+ ]);
return touchList(args.id);
};
@@ -268,7 +271,7 @@ export const reuseShoppingList = async (
let newListId: string;
try {
- await client.query('BEGIN');
+ await client.query("BEGIN");
const created = await client.query(
`INSERT INTO shopping_lists (owner_id, name) VALUES ($1, $2) RETURNING id`,
@@ -287,9 +290,9 @@ export const reuseShoppingList = async (
[newListId, args.id],
);
- await client.query('COMMIT');
+ await client.query("COMMIT");
} catch (error) {
- await client.query('ROLLBACK');
+ await client.query("ROLLBACK");
throw error;
} finally {
client.release();
@@ -304,7 +307,10 @@ export const setShoppingListInUse = async (
context: Context,
) => {
await getOwnedList(args.id, context.ownerId, { mustBeActive: true });
- await pool.query(`UPDATE shopping_lists SET in_use = $1 WHERE id = $2`, [args.inUse, args.id]);
+ await pool.query(`UPDATE shopping_lists SET in_use = $1 WHERE id = $2`, [
+ args.inUse,
+ args.id,
+ ]);
return touchList(args.id);
};
@@ -322,7 +328,7 @@ export const deleteShoppingList = async (
// Samme feil som de andre mutasjonene når lista ikke finnes
if (result.rowCount === 0) {
- throw new Error('Handlelisten finnes ikke');
+ throw new Error("Handlelisten finnes ikke");
}
return true;
@@ -341,10 +347,13 @@ export const addItemToList = async (
// Sjekker også at lista tilhører brukeren og ikke er fullført
await getOwnedList(args.listId, context.ownerId, { mustBeActive: true });
- const productResult = await pool.query(`SELECT ean FROM products WHERE ean = $1`, [args.ean]);
+ const productResult = await pool.query(
+ `SELECT ean FROM products WHERE ean = $1`,
+ [args.ean],
+ );
if (productResult.rows.length === 0) {
- throw new Error('Produktet finnes ikke');
+ throw new Error("Produktet finnes ikke");
}
// Finnes varen allerede i lista, økes antallet. LEAST hindrer at summen
@@ -368,7 +377,10 @@ export const setItemChecked = async (
context: Context,
) => {
const listId = await getActiveListIdForItem(args.itemId, context.ownerId);
- await pool.query(`UPDATE list_items SET checked = $1 WHERE id = $2`, [args.checked, args.itemId]);
+ await pool.query(`UPDATE list_items SET checked = $1 WHERE id = $2`, [
+ args.checked,
+ args.itemId,
+ ]);
return touchList(listId);
};
@@ -381,7 +393,10 @@ export const updateItemQuantity = async (
validateQuantity(args.quantity);
const listId = await getActiveListIdForItem(args.itemId, context.ownerId);
- await pool.query(`UPDATE list_items SET quantity = $1 WHERE id = $2`, [args.quantity, args.itemId]);
+ await pool.query(`UPDATE list_items SET quantity = $1 WHERE id = $2`, [
+ args.quantity,
+ args.itemId,
+ ]);
return touchList(listId);
};
@@ -399,7 +414,10 @@ export const updateItemNote = async (
}
const listId = await getActiveListIdForItem(args.itemId, context.ownerId);
- await pool.query(`UPDATE list_items SET note = $1 WHERE id = $2`, [note, args.itemId]);
+ await pool.query(`UPDATE list_items SET note = $1 WHERE id = $2`, [
+ note,
+ args.itemId,
+ ]);
return touchList(listId);
};
diff --git a/backend/src/scripts/explore-kassalapp.ts b/backend/src/scripts/explore-kassalapp.ts
index 9301ecb..124b015 100644
--- a/backend/src/scripts/explore-kassalapp.ts
+++ b/backend/src/scripts/explore-kassalapp.ts
@@ -1,22 +1,26 @@
// Utforsker Kassalapp-dataene for issue #6.
// Kjør fra backend-mappen: npx tsx src/scripts/explore-kassalapp.ts
-import 'dotenv/config';
+import "dotenv/config";
const KEY = process.env.KASSALAPP_API_KEY;
-if (!KEY) throw new Error('KASSALAPP_API_KEY mangler i backend/.env');
+if (!KEY) throw new Error("KASSALAPP_API_KEY mangler i backend/.env");
-const BASE = 'https://kassal.app/api/v1/';
+const BASE = "https://kassal.app/api/v1/";
const PAGES = 5; // 5 sider à 100 varer
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function get(path: string): Promise<{ status: number; body: any }> {
const res = await fetch(BASE + path, {
- headers: { Authorization: `Bearer ${KEY}`, Accept: 'application/json' },
+ headers: { Authorization: `Bearer ${KEY}`, Accept: "application/json" },
});
const text = await res.text();
let body: unknown = text;
- try { body = JSON.parse(text); } catch { /* ikke JSON */ }
+ try {
+ body = JSON.parse(text);
+ } catch {
+ /* ikke JSON */
+ }
await sleep(1100); // holder oss under 60 kall i minuttet
return { status: res.status, body };
}
@@ -24,20 +28,31 @@ async function get(path: string): Promise<{ status: number; body: any }> {
const count = (items: T[], key: (x: T) => string | undefined) => {
const m = new Map();
for (const x of items) {
- const k = key(x) ?? '(mangler)';
+ const k = key(x) ?? "(mangler)";
m.set(k, (m.get(k) ?? 0) + 1);
}
return Object.fromEntries([...m].sort((a, b) => b[1] - a[1]));
};
// 1. /categories og /labels
-for (const path of ['categories', 'labels']) {
+for (const path of ["categories", "labels"]) {
const { status, body } = await get(path);
const data = body?.data ?? body;
- console.log(`\n== /${path}: status ${status}, ${Array.isArray(data) ? data.length + ' elementer' : ''}`);
- console.log(JSON.stringify(Array.isArray(data) ? data.slice(0, 5) : data, null, 1).slice(0, 1500));
- if (path === 'labels' && Array.isArray(data)) {
- console.log('Alle label-navn:', data.map((l: { name: string }) => l.name).join(', '));
+ console.log(
+ `\n== /${path}: status ${status}, ${Array.isArray(data) ? data.length + " elementer" : ""}`,
+ );
+ console.log(
+ JSON.stringify(
+ Array.isArray(data) ? data.slice(0, 5) : data,
+ null,
+ 1,
+ ).slice(0, 1500),
+ );
+ if (path === "labels" && Array.isArray(data)) {
+ console.log(
+ "Alle label-navn:",
+ data.map((l: { name: string }) => l.name).join(", "),
+ );
}
}
@@ -46,33 +61,72 @@ for (const path of ['categories', 'labels']) {
const products: any[] = [];
for (let page = 1; page <= PAGES; page++) {
const { status, body } = await get(`products?size=100&page=${page}`);
- if (status !== 200) { console.log('products side', page, 'status', status); break; }
+ if (status !== 200) {
+ console.log("products side", page, "status", status);
+ break;
+ }
products.push(...body.data);
}
const n = products.length;
const pct = (k: number) => `${k} av ${n} (${((100 * k) / n).toFixed(1)} %)`;
console.log(`\n== Produkter hentet: ${n}`);
-console.log('Mangler EAN: ', pct(products.filter((p) => !p.ean).length));
-console.log('Mangler kategori: ', pct(products.filter((p) => !p.category?.length).length));
-console.log('Mangler bilde: ', pct(products.filter((p) => !p.image).length));
-console.log('Mangler pris: ', pct(products.filter((p) => p.current_price == null).length));
-console.log('Butikker:', count(products, (p) => p.store?.code));
-console.log('Labels:', count(products.flatMap((p) => p.labels ?? []), (l) => l.name));
-console.log('Toppkategorier:', count(products.filter((p) => p.category?.length), (p) =>
- [...p.category].sort((a, b) => a.depth - b.depth)[0].name));
+console.log("Mangler EAN: ", pct(products.filter((p) => !p.ean).length));
+console.log(
+ "Mangler kategori: ",
+ pct(products.filter((p) => !p.category?.length).length),
+);
+console.log("Mangler bilde: ", pct(products.filter((p) => !p.image).length));
+console.log(
+ "Mangler pris: ",
+ pct(products.filter((p) => p.current_price == null).length),
+);
+console.log(
+ "Butikker:",
+ count(products, (p) => p.store?.code),
+);
+console.log(
+ "Labels:",
+ count(
+ products.flatMap((p) => p.labels ?? []),
+ (l) => l.name,
+ ),
+);
+console.log(
+ "Toppkategorier:",
+ count(
+ products.filter((p) => p.category?.length),
+ (p) => [...p.category].sort((a, b) => a.depth - b.depth)[0].name,
+ ),
+);
// 3. Samme EAN i flere kjeder?
-const eans = count(products.filter((p) => p.ean), (p) => p.ean);
+const eans = count(
+ products.filter((p) => p.ean),
+ (p) => p.ean,
+);
const repeated = Object.entries(eans).filter(([, c]) => c > 1).length;
-console.log(`\nEAN som går igjen i utvalget: ${repeated} av ${Object.keys(eans).length}`);
+console.log(
+ `\nEAN som går igjen i utvalget: ${repeated} av ${Object.keys(eans).length}`,
+);
-const ean = '7038010014604'; // Norvegia 500 g
+const ean = "7038010014604"; // Norvegia 500 g
const { status, body } = await get(`products/ean/${ean}`);
const hits = body?.data?.products ?? body?.data ?? [];
console.log(`\n== /products/ean/${ean}: status ${status}`);
if (Array.isArray(hits)) {
- console.log('Butikker med denne EAN-en:', hits.filter((p: { store?: unknown }) => p.store).map((p: { store?: { code: string }; current_price?: number | { price: number } }) =>
- `${p.store?.code} ${typeof p.current_price === "object" ? p.current_price?.price : p.current_price ?? "-"} kr`).join(', '));
+ console.log(
+ "Butikker med denne EAN-en:",
+ hits
+ .filter((p: { store?: unknown }) => p.store)
+ .map(
+ (p: {
+ store?: { code: string };
+ current_price?: number | { price: number };
+ }) =>
+ `${p.store?.code} ${typeof p.current_price === "object" ? p.current_price?.price : (p.current_price ?? "-")} kr`,
+ )
+ .join(", "),
+ );
} else {
console.log(JSON.stringify(body).slice(0, 500));
}
diff --git a/backend/src/scripts/import.ts b/backend/src/scripts/import.ts
index 646325e..90935e5 100644
--- a/backend/src/scripts/import.ts
+++ b/backend/src/scripts/import.ts
@@ -19,7 +19,6 @@ const since: Date | null = await readFile(LAST_IMPORT_PATH, "utf-8")
})
.catch(() => null);
-
type KassalappCategory = {
id: number;
parent_id?: number | null;
@@ -132,7 +131,7 @@ async function getProducts(since: Date | null): Promise {
if (since && oldest && new Date(oldest) < since) {
console.log("Nådde produkter fra før forrige import. Stopper.");
- break;
+ break;
}
}
@@ -223,8 +222,7 @@ function normalizeCategories(
const categoryPath = product.category ?? [];
categoryPath.forEach((category, index) => {
- const parent =
- index > 0 ? categoryPath[index - 1] : null;
+ const parent = index > 0 ? categoryPath[index - 1] : null;
if (!categoriesById.has(category.id)) {
categoriesById.set(category.id, {
@@ -246,8 +244,7 @@ function normalizeCategories(
return Array.from(categoriesById.values());
}
-const sleep = (ms: number) =>
- new Promise((resolve) => setTimeout(resolve, ms));
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function get(path: string): Promise {
while (true) {
@@ -259,7 +256,9 @@ async function get(path: string): Promise {
});
if (response.status === 429) {
- console.log("Rate limit nådd (429). Venter 5 sekunder før nytt forsøk...");
+ console.log(
+ "Rate limit nådd (429). Venter 5 sekunder før nytt forsøk...",
+ );
await sleep(5000);
continue;
}
@@ -281,7 +280,6 @@ async function get(path: string): Promise {
const startedAt = new Date().toISOString();
-
console.log(
since
? `Henter endringer siden ${since.toISOString()}`
@@ -308,18 +306,13 @@ const products = await getProducts(since);
console.log(`Totalt antall produkter hentet: ${products.length}`);
-const productsWithoutEan = products.filter(
- (product) => !product.ean,
-).length;
+const productsWithoutEan = products.filter((product) => !product.ean).length;
console.log(`Produkter uten EAN hoppet over: ${productsWithoutEan}`);
const normalizedProducts = normalizeProducts(products);
-const normalizedCategories = normalizeCategories(
- topLevelCategories,
- products,
-);
+const normalizedCategories = normalizeCategories(topLevelCategories, products);
console.log(`Kategorier i dumpen: ${normalizedCategories.length}`);
@@ -340,15 +333,11 @@ const withoutCategory = normalizedProducts.filter(
console.log(`Produkter uten kategori: ${withoutCategory}`);
const dump = {
- importedAt: startedAt,
+ importedAt: startedAt,
categories: normalizedCategories,
products: normalizedProducts,
};
-await writeFile(
- OUTPUT_PATH,
- JSON.stringify(dump, null, 2),
- "utf-8",
-);
+await writeFile(OUTPUT_PATH, JSON.stringify(dump, null, 2), "utf-8");
-console.log(`JSON-dump lagret til ${OUTPUT_PATH}`);
\ No newline at end of file
+console.log(`JSON-dump lagret til ${OUTPUT_PATH}`);
diff --git a/backend/src/scripts/seed.ts b/backend/src/scripts/seed.ts
index 0251fcf..43cd2d8 100644
--- a/backend/src/scripts/seed.ts
+++ b/backend/src/scripts/seed.ts
@@ -129,32 +129,32 @@ try {
labels = EXCLUDED.labels,
category_id = COALESCE(NULLIF(EXCLUDED.category_id, -1), products.category_id)
`,
- [
- product.ean,
- product.name,
- product.brand,
- product.vendor,
- product.imageUrl,
- product.description,
- product.ingredients,
- product.weight,
- product.weightUnit,
- JSON.stringify(product.nutrition),
- JSON.stringify(product.allergens),
- product.labels.map((label) => {
- if (
- typeof label === "object" &&
- label !== null &&
- "name" in label &&
- typeof label.name === "string"
- ) {
- return label.name;
- }
-
- return String(label);
- }),
- product.categoryId,
- ],
+ [
+ product.ean,
+ product.name,
+ product.brand,
+ product.vendor,
+ product.imageUrl,
+ product.description,
+ product.ingredients,
+ product.weight,
+ product.weightUnit,
+ JSON.stringify(product.nutrition),
+ JSON.stringify(product.allergens),
+ product.labels.map((label) => {
+ if (
+ typeof label === "object" &&
+ label !== null &&
+ "name" in label &&
+ typeof label.name === "string"
+ ) {
+ return label.name;
+ }
+
+ return String(label);
+ }),
+ product.categoryId,
+ ],
);
}
@@ -211,4 +211,4 @@ try {
} finally {
client.release();
await pool.end();
-}
\ No newline at end of file
+}
diff --git a/frontend/README.md b/frontend/README.md
index 653fa86..a6b4d60 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -20,9 +20,9 @@ If you are developing a production application, we recommend updating the config
```js
export default defineConfig([
- globalIgnores(['dist']),
+ globalIgnores(["dist"]),
{
- files: ['**/*.{ts,tsx}'],
+ files: ["**/*.{ts,tsx}"],
extends: [
// Other configs...
@@ -37,42 +37,40 @@ export default defineConfig([
],
languageOptions: {
parserOptions: {
- project: ['./tsconfig.node.json', './tsconfig.app.json'],
+ project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
-])
-
+]);
```
You can also install [eslint-plugin-react-x](https://npmx.dev/package/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://npmx.dev/package/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
-import reactX from 'eslint-plugin-react-x'
-import reactDom from 'eslint-plugin-react-dom'
+import reactX from "eslint-plugin-react-x";
+import reactDom from "eslint-plugin-react-dom";
export default defineConfig([
- globalIgnores(['dist']),
+ globalIgnores(["dist"]),
{
- files: ['**/*.{ts,tsx}'],
+ files: ["**/*.{ts,tsx}"],
extends: [
// Other configs...
// Enable lint rules for React
- reactX.configs['recommended-typescript'],
+ reactX.configs["recommended-typescript"],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
- project: ['./tsconfig.node.json', './tsconfig.app.json'],
+ project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
-])
-
+]);
```
diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js
index ef614d2..da6f026 100644
--- a/frontend/eslint.config.js
+++ b/frontend/eslint.config.js
@@ -1,14 +1,14 @@
-import js from '@eslint/js'
-import globals from 'globals'
-import reactHooks from 'eslint-plugin-react-hooks'
-import reactRefresh from 'eslint-plugin-react-refresh'
-import tseslint from 'typescript-eslint'
-import { defineConfig, globalIgnores } from 'eslint/config'
+import js from "@eslint/js";
+import globals from "globals";
+import reactHooks from "eslint-plugin-react-hooks";
+import reactRefresh from "eslint-plugin-react-refresh";
+import tseslint from "typescript-eslint";
+import { defineConfig, globalIgnores } from "eslint/config";
export default defineConfig([
- globalIgnores(['dist']),
+ globalIgnores(["dist"]),
{
- files: ['**/*.{ts,tsx}'],
+ files: ["**/*.{ts,tsx}"],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
@@ -19,4 +19,4 @@ export default defineConfig([
globals: globals.browser,
},
},
-])
+]);
diff --git a/frontend/index.html b/frontend/index.html
index 9db57f1..ca847eb 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -2,15 +2,8 @@
-
-
+
+
Handlelappen
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 45dbefe..e024c25 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -147,10 +147,7 @@ function AppLayout() {
}
/>
- }
- />
+ } />
} />
- }
- />
+ } />
:first-child {
- color: var(--text-accent);
+.category-card__top > :first-child {
+ color: var(--text-accent);
}
.category-card__bottom {
- display: flex;
- justify-content: space-between;
- align-items: flex-end;
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-end;
}
.category-card__name {
- display: block;
- font-size: 1.25rem;
- font-weight: 500;
- letter-spacing: -0.02em;
- color: var(--text-primary);
+ display: block;
+ font-size: 1.25rem;
+ font-weight: 500;
+ letter-spacing: -0.02em;
+ color: var(--text-primary);
}
.category-card__description {
- display: block;
- margin-top: 4px;
- font-size: 0.8125rem;
- color: var(--text-secondary);
+ display: block;
+ margin-top: 4px;
+ font-size: 0.8125rem;
+ color: var(--text-secondary);
}
.category-card__arrow {
- display: grid;
- place-items: center;
- width: 30px;
- height: 30px;
- border-radius: 50%;
- background: var(--bg-muted);
- color: var(--text-primary);
- transition: background 0.15s, color 0.15s;
+ display: grid;
+ place-items: center;
+ width: 30px;
+ height: 30px;
+ border-radius: 50%;
+ background: var(--bg-muted);
+ color: var(--text-primary);
+ transition:
+ background 0.15s,
+ color 0.15s;
}
.category-card:hover .category-card__arrow {
- background: var(--bg-primary);
- color: var(--text-on-dark);
-}
\ No newline at end of file
+ background: var(--bg-primary);
+ color: var(--text-on-dark);
+}
diff --git a/frontend/src/components/checkbox/Checkbox.css b/frontend/src/components/checkbox/Checkbox.css
index cb5b06d..a215416 100644
--- a/frontend/src/components/checkbox/Checkbox.css
+++ b/frontend/src/components/checkbox/Checkbox.css
@@ -1,40 +1,40 @@
/* Checkbox – fra Figma (Components → Checkbox)
Bruker en ekte , så den virker med tastatur og skjermleser. */
.checkbox {
- appearance: none;
- display: inline-grid;
- place-items: center;
- flex-shrink: 0;
- width: 16px;
- height: 16px;
- margin: 0;
- background: var(--bg-surface);
- border: 1.25px solid var(--border-brand);
- border-radius: 3px;
- cursor: pointer;
+ appearance: none;
+ display: inline-grid;
+ place-items: center;
+ flex-shrink: 0;
+ width: 16px;
+ height: 16px;
+ margin: 0;
+ background: var(--bg-surface);
+ border: 1.25px solid var(--border-brand);
+ border-radius: 3px;
+ cursor: pointer;
}
.checkbox--large {
- width: 18px;
- height: 18px;
+ width: 18px;
+ height: 18px;
}
/* Avkrysset: fylt burgunder med hvit hake */
.checkbox:checked {
- background: var(--bg-brand);
- border-color: var(--bg-brand);
+ background: var(--bg-brand);
+ border-color: var(--bg-brand);
}
.checkbox:checked::after {
- content: "";
- width: 8px;
- height: 4px;
- border-left: 1.8px solid var(--text-on-dark);
- border-bottom: 1.8px solid var(--text-on-dark);
- transform: translateY(-1px) rotate(-45deg);
+ content: "";
+ width: 8px;
+ height: 4px;
+ border-left: 1.8px solid var(--text-on-dark);
+ border-bottom: 1.8px solid var(--text-on-dark);
+ transform: translateY(-1px) rotate(-45deg);
}
.checkbox:focus-visible {
- outline: 2px solid var(--text-accent);
- outline-offset: 2px;
+ outline: 2px solid var(--text-accent);
+ outline-offset: 2px;
}
diff --git a/frontend/src/components/checkbox/Checkbox.tsx b/frontend/src/components/checkbox/Checkbox.tsx
index f39d9e2..13aa48f 100644
--- a/frontend/src/components/checkbox/Checkbox.tsx
+++ b/frontend/src/components/checkbox/Checkbox.tsx
@@ -3,7 +3,10 @@ import "./Checkbox.css";
// En ekte , så den virker med tastatur og skjermleser.
// Alle vanlige input-props (checked, onChange, id, aria-label ...) sendes rett videre.
-type CheckboxProps = Omit, "type" | "size"> & {
+type CheckboxProps = Omit<
+ InputHTMLAttributes,
+ "type" | "size"
+> & {
size?: "normal" | "large";
};
diff --git a/frontend/src/components/filterChip/FilterChip.css b/frontend/src/components/filterChip/FilterChip.css
index d24373f..a15e8b7 100644
--- a/frontend/src/components/filterChip/FilterChip.css
+++ b/frontend/src/components/filterChip/FilterChip.css
@@ -1,35 +1,35 @@
/* FilterChip – fra Figma (Components → FilterChip)
Viser et aktivt filter, med × for å fjerne det. */
.filter-chip {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- height: 28px;
- padding: 0 10px;
- border: 1px solid transparent;
- border-radius: 4px;
- background: var(--bg-tint);
- color: var(--text-brand);
- font: 500 0.625rem var(--font-mono);
- letter-spacing: 0.06em;
- text-transform: uppercase;
- cursor: pointer;
- /* Lange filternavn får bryte i stedet for å sprenge bredden */
- max-width: 100%;
- white-space: normal;
- text-align: left;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ height: 28px;
+ padding: 0 10px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ background: var(--bg-tint);
+ color: var(--text-brand);
+ font: 500 0.625rem var(--font-mono);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ cursor: pointer;
+ /* Lange filternavn får bryte i stedet for å sprenge bredden */
+ max-width: 100%;
+ white-space: normal;
+ text-align: left;
}
.filter-chip__close {
- font: 400 0.875rem var(--font-ui);
- line-height: 1;
+ font: 400 0.875rem var(--font-ui);
+ line-height: 1;
}
.filter-chip:hover {
- border-color: var(--border-brand);
+ border-color: var(--border-brand);
}
.filter-chip:focus-visible {
- outline: 2px solid var(--text-accent);
- outline-offset: 2px;
+ outline: 2px solid var(--text-accent);
+ outline-offset: 2px;
}
diff --git a/frontend/src/components/filterRow/FilterRow.css b/frontend/src/components/filterRow/FilterRow.css
index 68536f3..2439b91 100644
--- a/frontend/src/components/filterRow/FilterRow.css
+++ b/frontend/src/components/filterRow/FilterRow.css
@@ -1,48 +1,48 @@
/* FilterRow – én rad i filterlisten (Components → FilterRow) */
.filter-row {
- display: flex;
- align-items: center;
- gap: 10px;
- min-width: 160px;
- padding: 7px 0;
- cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 160px;
+ padding: 7px 0;
+ cursor: pointer;
}
.filter-row__name {
- flex: 1;
- font: 400 0.875rem var(--font-ui);
- color: var(--text-primary);
+ flex: 1;
+ font: 400 0.875rem var(--font-ui);
+ color: var(--text-primary);
}
.filter-row__count {
- font: 500 0.625rem var(--font-mono);
- letter-spacing: 0.06em;
- color: var(--text-muted);
+ font: 500 0.625rem var(--font-mono);
+ letter-spacing: 0.06em;
+ color: var(--text-muted);
}
/* Valgt: navnet blir litt tykkere */
.filter-row:has(.checkbox:checked) .filter-row__name {
- font-weight: 500;
+ font-weight: 500;
}
/* Hover: navnet får aksentfarge */
.filter-row:hover .filter-row__name {
- color: var(--text-accent);
+ color: var(--text-accent);
}
/* Mobil: høyere rader og større boks, lettere å treffe med tommelen */
@media (max-width: 700px) {
- .filter-row {
- padding: 12px 0;
- }
+ .filter-row {
+ padding: 12px 0;
+ }
- .filter-row .checkbox {
- width: 20px;
- height: 20px;
- }
+ .filter-row .checkbox {
+ width: 20px;
+ height: 20px;
+ }
- .filter-row .checkbox:checked::after {
- width: 10px;
- height: 5px;
- }
+ .filter-row .checkbox:checked::after {
+ width: 10px;
+ height: 5px;
+ }
}
diff --git a/frontend/src/components/header/Header.css b/frontend/src/components/header/Header.css
index 79e1d13..3eeeccf 100644
--- a/frontend/src/components/header/Header.css
+++ b/frontend/src/components/header/Header.css
@@ -1,4 +1,3 @@
-
/* =========================================
HEADER – ISSUE #50
Felles header for Handlelappen
@@ -159,4 +158,3 @@
padding-right: 7px;
}
}
-
diff --git a/frontend/src/components/header/Header.tsx b/frontend/src/components/header/Header.tsx
index 8a1048f..137bf01 100644
--- a/frontend/src/components/header/Header.tsx
+++ b/frontend/src/components/header/Header.tsx
@@ -36,21 +36,13 @@ export default function Header({
{variant === "home" ? (
) : (
-
+
);
diff --git a/frontend/src/components/logo/Logo.css b/frontend/src/components/logo/Logo.css
index ee45b7f..fddde6b 100644
--- a/frontend/src/components/logo/Logo.css
+++ b/frontend/src/components/logo/Logo.css
@@ -93,4 +93,4 @@
outline: 2px solid var(--text-accent);
outline-offset: 4px;
border-radius: 4px;
-}
\ No newline at end of file
+}
diff --git a/frontend/src/components/menuButton/MenuButton.css b/frontend/src/components/menuButton/MenuButton.css
index 97222e2..35c7d2c 100644
--- a/frontend/src/components/menuButton/MenuButton.css
+++ b/frontend/src/components/menuButton/MenuButton.css
@@ -1,4 +1,3 @@
-
/* =========================================
MENU BUTTON – ISSUE #50
Gjenbrukbar menyknapp
diff --git a/frontend/src/components/menuButton/MenuButton.tsx b/frontend/src/components/menuButton/MenuButton.tsx
index ab07e55..3588be5 100644
--- a/frontend/src/components/menuButton/MenuButton.tsx
+++ b/frontend/src/components/menuButton/MenuButton.tsx
@@ -1,4 +1,3 @@
-
import "./MenuButton.css";
type MenuButtonProps = {
@@ -23,11 +22,7 @@ export default function MenuButton({
aria-label={isOpen ? "Lukk meny" : "Åpne meny"}
aria-expanded={onClick ? isOpen : undefined}
title={
- isDisabled
- ? "Meny kommer snart"
- : isOpen
- ? "Lukk meny"
- : "Åpne meny"
+ isDisabled ? "Meny kommer snart" : isOpen ? "Lukk meny" : "Åpne meny"
}
>
@@ -38,4 +33,3 @@ export default function MenuButton({
);
}
-
diff --git a/frontend/src/components/navigationMenu/NavigationMenu.tsx b/frontend/src/components/navigationMenu/NavigationMenu.tsx
index 14b4158..caded6b 100644
--- a/frontend/src/components/navigationMenu/NavigationMenu.tsx
+++ b/frontend/src/components/navigationMenu/NavigationMenu.tsx
@@ -1,4 +1,3 @@
-
import { useEffect, useRef } from "react";
import { Link } from "react-router";
@@ -41,9 +40,7 @@ export default function NavigationMenu({
};
// Lukk når brukeren klikker utenfor selve menyen.
- const handleBackdropClick = (
- event: React.MouseEvent,
- ) => {
+ const handleBackdropClick = (event: React.MouseEvent) => {
if (event.target === event.currentTarget) {
onClose();
}
@@ -73,14 +70,9 @@ export default function NavigationMenu({
-
- NAVIGASJON
-
+ NAVIGASJON
-