34 lines
1.5 KiB
TypeScript
34 lines
1.5 KiB
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
|
|
// Einen Laden aus der Gangfolge einer Kette anlegen (Onboarding, Schritt 3:
|
|
// „Hauptladen wählen: Kette aus der Liste mit Standard-Gangfolge“). Der Laden
|
|
// gehört dem Haushalt, die Gänge sind seine Kopie; später lernt er aus der
|
|
// Reihenfolge des Abhakens. Der erste Laden wird Hauptladen.
|
|
//
|
|
// Aufruf in withHousehold(householdId, …).
|
|
export async function createStoreFromChain(
|
|
client: PoolClient,
|
|
householdId: string,
|
|
chainKey: string,
|
|
options: { name?: string; locale?: string } = {},
|
|
): Promise<string> {
|
|
const chain = (await client.query<{ name: string }>("select name from store_chains where key = $1", [chainKey])).rows[0];
|
|
if (!chain) throw new Error(`unknown chain: ${chainKey}`);
|
|
const name = options.name?.trim() || chain.name;
|
|
if (!name) throw new Error("a store needs a name");
|
|
const hasDefault = (await client.query("select 1 from stores where is_default")).rowCount! > 0;
|
|
const { rows } = await client.query<{ id: string }>(
|
|
"insert into stores (household_id, name, chain, is_default) values ($1, $2, $3, $4) returning id",
|
|
[householdId, name, chainKey, !hasDefault],
|
|
);
|
|
const storeId = rows[0]!.id;
|
|
await client.query(
|
|
`insert into store_aisles (household_id, store_id, position, name, ingredient_categories)
|
|
select $1, $2, a.position, coalesce(a.names ->> $4, a.names ->> 'de'), a.ingredient_categories
|
|
from chain_aisles a where a.chain_key = $3`,
|
|
[householdId, storeId, chainKey, options.locale ?? "de"],
|
|
);
|
|
return storeId;
|
|
}
|