Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions backend/migrations/0019_category_translations.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- Names of a category in other languages. `label` stays the name that counts: it decides
-- the extra fields of its items and is shown wherever a language has no translation.
ALTER TABLE categories ADD COLUMN translations jsonb NOT NULL DEFAULT '{}';

UPDATE categories c
SET translations = jsonb_build_object('en', d.en)
FROM (VALUES
('Kleidung', 'Clothing'),
('Schuhe', 'Shoes'),
('Sport', 'Sports'),
('Fahrräder', 'Bikes'),
('Elektronik', 'Electronics'),
('Bücher', 'Books'),
('Spielzeug', 'Toys'),
('Möbel', 'Furniture'),
('Haushalt', 'Household'),
('Accessoires', 'Accessories'),
('Sonstiges', 'Other')
) AS d (de, en)
WHERE c.label = d.de;
25 changes: 19 additions & 6 deletions backend/src/demo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ impl Seeder {
product_images: Option<Vec<Uuid>>,
) -> AppResult<Self> {
let mut categories = HashMap::new();
for (cat, label) in CATEGORIES {
let label = label.get(locale);
for (cat, names) in CATEGORIES {
let label = names.get(locale);
let existing: Option<Uuid> = sqlx::query_scalar(
"SELECT id FROM categories WHERE label = $1 ORDER BY created_at LIMIT 1",
)
Expand All @@ -118,10 +118,18 @@ impl Seeder {
let id = match existing {
Some(id) => id,
None => {
sqlx::query_scalar("INSERT INTO categories (label) VALUES ($1) RETURNING id")
.bind(label)
.fetch_one(ctx.conn())
.await?
// A German demo carries the English name too; an English one needs none
let translations = match locale {
Locale::De => json!({ "en": names.en }),
Locale::En => json!({}),
};
sqlx::query_scalar(
"INSERT INTO categories (label, translations) VALUES ($1, $2) RETURNING id",
)
.bind(label)
.bind(translations)
.fetch_one(ctx.conn())
.await?
}
};
categories.insert(*cat, id);
Expand Down Expand Up @@ -348,6 +356,11 @@ pub async fn run(state: &AppState, options: Options) -> anyhow::Result<String> {
let failed = |err: crate::error::AppError| anyhow::anyhow!("{err}");

let mut ctx = Ctx::begin(state).await?;
// The backend created the German default categories on its first start. Without users
// nothing uses them yet, and `--locale en` would show them next to the English ones.
sqlx::query("DELETE FROM categories WHERE NOT EXISTS (SELECT 1 FROM users)")
.execute(ctx.conn())
.await?;
ctx.call(None, "seed.seedFeatureFlags", json!({}))
.await
.map_err(failed)?;
Expand Down
7 changes: 7 additions & 0 deletions backend/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,13 @@ async fn categories(
known: &mut Known,
report: &mut Report,
) -> anyhow::Result<()> {
// The backend ran before the import and created the default categories. Nothing uses them
// yet, the database has no users; the export would add its own next to them.
if export.docs("categories").next().is_some() {
sqlx::query("DELETE FROM categories")
.execute(&mut *tx)
.await?;
}
for doc in export.docs("categories") {
sqlx::query(
"INSERT INTO categories (id, legacy_id, label, updated_at, created_at)
Expand Down
10 changes: 10 additions & 0 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ async fn main() -> anyhow::Result<()> {
{
tracing::warn!(error = %err, "ADMIN_EMAIL not promoted");
}
if let Err(err) = rpc::call(
&state,
None,
"categories.seedIfEmpty",
serde_json::json!({}),
)
.await
{
tracing::warn!(error = %err, "default categories not created");
}
let hub = state.hub.clone();

tokio::spawn(async move {
Expand Down
196 changes: 175 additions & 21 deletions backend/src/modules/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ use futures::FutureExt;
use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use sqlx::types::Json;
use uuid::Uuid;

use super::access::require_admin;
use crate::error::AppResult;
use crate::error::{AppError, AppResult};
use crate::realtime::Topic;
use crate::register;
use crate::rpc::{Audience, Ctx, Registry};
Expand All @@ -18,11 +19,35 @@ const TOPIC: Topic = Topic::Table("categories");

pub fn register(registry: &mut Registry) {
register!(registry, Mutation "categories.createCategory" => create_category);
register!(registry, Mutation "categories.updateCategory" => update_category);
register!(registry, Mutation "categories.deleteCategory" => delete_category);
register!(registry, Query "categories.listForAdmin" => list_for_admin);
register!(registry, Query "categories.getAllCategories" => get_all_categories);
registry.share("categories.getAllCategories", same_for_everybody);
register!(registry, Query "categories.getCategoryLabel" => get_category_label);
register!(registry, Query "categories.getCategoryId" => get_category_id);
register!(registry, InternalMutation "categories.seedCategories" => seed_categories);
register!(registry, InternalMutation "categories.seedIfEmpty" => seed_if_empty);
}

/// Names in other languages. `label` remains the name that decides the extra fields
/// (category_fields) and the one shown when a language has no translation.
#[skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Translations {
pub en: Option<String>,
}

impl Translations {
fn trimmed(self) -> Self {
Self {
en: self
.en
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty()),
}
}
}

#[skip_serializing_none]
Expand All @@ -38,13 +63,23 @@ pub struct Category {
pub parent_id: Option<Uuid>,
#[serde(with = "ms")]
pub updated_at: DateTime<Utc>,
pub translations: Json<Translations>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CreateArgs {
label: String,
parent_category: Option<Id>,
translations: Option<Translations>,
}

fn clean_label(label: &str) -> AppResult<String> {
let label = label.trim();
if label.is_empty() {
return Err(AppError::bad_request("category.labelEmpty"));
}
Ok(label.to_owned())
}

async fn find_by_label(ctx: &mut Ctx, label: &str) -> sqlx::Result<Option<Uuid>> {
Expand All @@ -57,7 +92,8 @@ async fn find_by_label(ctx: &mut Ctx, label: &str) -> sqlx::Result<Option<Uuid>>
/// Admins only. Returns the existing category if the label exists already.
async fn create_category(ctx: &mut Ctx, args: CreateArgs) -> AppResult<Uuid> {
require_admin(ctx).await?;
if let Some(existing) = find_by_label(ctx, &args.label).await? {
let label = clean_label(&args.label)?;
if let Some(existing) = find_by_label(ctx, &label).await? {
return Ok(existing);
}
// A parent that does not exist is left out
Expand All @@ -71,16 +107,118 @@ async fn create_category(ctx: &mut Ctx, args: CreateArgs) -> AppResult<Uuid> {
None => None,
};
let id = sqlx::query_scalar(
"INSERT INTO categories (label, parent_id) VALUES ($1, $2) RETURNING id",
"INSERT INTO categories (label, parent_id, translations) VALUES ($1, $2, $3) RETURNING id",
)
.bind(&args.label)
.bind(&label)
.bind(parent)
.bind(Json(args.translations.unwrap_or_default().trimmed()))
.fetch_one(ctx.conn())
.await?;
ctx.touch(TOPIC);
Ok(id)
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct UpdateArgs {
category_id: Id,
label: String,
translations: Translations,
}

/// Admins only. Items and bazaars point to the id and follow; sales keep the name they had.
async fn update_category(ctx: &mut Ctx, args: UpdateArgs) -> AppResult<()> {
require_admin(ctx).await?;
let label = clean_label(&args.label)?;
let taken: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM categories WHERE lower(label) = lower($1) AND id <> $2)",
)
.bind(&label)
.bind(args.category_id.0)
.fetch_one(ctx.conn())
.await?;
if taken {
return Err(AppError::bad_request("category.labelTaken"));
}
let updated = sqlx::query(
"UPDATE categories SET label = $2, translations = $3, updated_at = now() WHERE id = $1",
)
.bind(args.category_id.0)
.bind(&label)
.bind(Json(args.translations.trimmed()))
.execute(ctx.conn())
.await?;
if updated.rows_affected() == 0 {
return Err(AppError::not_found("notFound.category"));
}
ctx.touch(TOPIC);
Ok(())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct DeleteArgs {
category_id: Id,
}

/// Admins only, and only what nothing uses: items and bazaars need their category, and a
/// sub-category would lose the fields it inherits. Sales keep the name they recorded.
async fn delete_category(ctx: &mut Ctx, args: DeleteArgs) -> AppResult<()> {
require_admin(ctx).await?;
let id = args.category_id.0;
let (exists, in_use, others): (bool, bool, bool) = sqlx::query_as(
"SELECT EXISTS (SELECT 1 FROM categories WHERE id = $1),
EXISTS (SELECT 1 FROM products WHERE category_id = $1)
OR EXISTS (SELECT 1 FROM event_categories WHERE category_id = $1)
OR EXISTS (SELECT 1 FROM categories WHERE parent_id = $1),
EXISTS (SELECT 1 FROM categories WHERE id <> $1)",
)
.bind(id)
.fetch_one(ctx.conn())
.await?;
if !exists {
return Err(AppError::not_found("notFound.category"));
}
if in_use {
return Err(AppError::bad_request("category.inUse"));
}
// No bazaar could be created without one, and the next start would bring the defaults back
if !others {
return Err(AppError::bad_request("category.lastOne"));
}
sqlx::query("DELETE FROM categories WHERE id = $1")
.bind(id)
.execute(ctx.conn())
.await?;
ctx.touch(TOPIC);
Ok(())
}

#[derive(Serialize, sqlx::FromRow)]
#[serde(rename_all = "camelCase")]
struct AdminCategory {
#[sqlx(flatten)]
#[serde(flatten)]
category: Category,
product_count: i64,
event_count: i64,
child_count: i64,
}

async fn list_for_admin(ctx: &mut Ctx, _: NoArgs) -> AppResult<Vec<AdminCategory>> {
require_admin(ctx).await?;
ctx.read(TOPIC);
Ok(sqlx::query_as(
"SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations,
(SELECT count(*) FROM products p WHERE p.category_id = c.id) AS product_count,
(SELECT count(*) FROM event_categories e WHERE e.category_id = c.id) AS event_count,
(SELECT count(*) FROM categories s WHERE s.parent_id = c.id) AS child_count
FROM categories c ORDER BY c.created_at, c.id",
)
.fetch_all(ctx.conn())
.await?)
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NoArgs {}
Expand All @@ -96,7 +234,8 @@ fn same_for_everybody<'a>(
async fn get_all_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult<Vec<Category>> {
ctx.read(TOPIC);
Ok(sqlx::query_as(
"SELECT id, created_at, label, parent_id, updated_at FROM categories ORDER BY created_at",
"SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations
FROM categories c ORDER BY c.created_at",
)
.fetch_all(ctx.conn())
.await?)
Expand Down Expand Up @@ -129,31 +268,46 @@ async fn get_category_id(ctx: &mut Ctx, args: IdArgs) -> AppResult<Option<Uuid>>
Ok(find_by_label(ctx, &args.category_label).await?)
}

/// The default categories (German labels); adds the missing ones, safe to run repeatedly:
/// `bazarpro-backend run categories.seedCategories`
pub const DEFAULT_CATEGORIES: [&str; 11] = [
"Kleidung",
"Schuhe",
"Sport",
"Fahrräder",
"Elektronik",
"Bücher",
"Spielzeug",
"Möbel",
"Haushalt",
"Accessoires",
"Sonstiges",
/// The default categories (German label, English name); adds the missing ones, safe to run
/// repeatedly: `bazarpro-backend run categories.seedCategories`
pub const DEFAULT_CATEGORIES: [(&str, &str); 11] = [
("Kleidung", "Clothing"),
("Schuhe", "Shoes"),
("Sport", "Sports"),
("Fahrräder", "Bikes"),
("Elektronik", "Electronics"),
("Bücher", "Books"),
("Spielzeug", "Toys"),
("Möbel", "Furniture"),
("Haushalt", "Household"),
("Accessoires", "Accessories"),
("Sonstiges", "Other"),
];

async fn seed_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult<&'static str> {
for label in DEFAULT_CATEGORIES {
for (label, en) in DEFAULT_CATEGORIES {
if find_by_label(ctx, label).await?.is_none() {
sqlx::query("INSERT INTO categories (label) VALUES ($1)")
sqlx::query("INSERT INTO categories (label, translations) VALUES ($1, $2)")
.bind(label)
.bind(Json(Translations {
en: Some(en.to_owned()),
}))
.execute(ctx.conn())
.await?;
}
}
ctx.touch(TOPIC);
Ok("Categories seeded successfully")
}

/// On every start of the server: without categories no bazaar can be created, and the app
/// has no page to add them. An instance that already has categories keeps exactly those.
async fn seed_if_empty(ctx: &mut Ctx, args: NoArgs) -> AppResult<&'static str> {
let any: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM categories)")
.fetch_one(ctx.conn())
.await?;
if any {
return Ok("Categories already exist");
}
seed_categories(ctx, args).await
}
Loading
Loading