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
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Generated maps (scripts/postal-areas), kept small on one line
src/assets/postal-areas/
2 changes: 2 additions & 0 deletions backend/migrations/0038_broadcast_without_items.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Messages to sellers who have not announced any item yet (#304)
ALTER TYPE broadcast_audience ADD VALUE IF NOT EXISTS 'withoutItems';
3 changes: 3 additions & 0 deletions backend/migrations/0039_region_map_image.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Picture of a bazaar's region (#304): the app draws the chosen postal code areas when the
-- organizer saves, and sellers see it next to the postal codes
ALTER TABLE events ADD COLUMN region_map_image_id uuid REFERENCES files (id);
3 changes: 3 additions & 0 deletions backend/migrations/0040_admitted_by_region.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Sellers a bazaar's region let in by their postal code (#304): only theirs stays fixed
-- until the bazaar ends. The access code, an invitation or the team let others in too.
ALTER TABLE event_sellers ADD COLUMN admitted_by_region boolean NOT NULL DEFAULT false;
63 changes: 63 additions & 0 deletions backend/src/demo/extended.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use std::collections::HashMap;

use anyhow::{Context, anyhow};
use bytes::Bytes;
use chrono::{DateTime, Duration, DurationRound, NaiveTime, TimeZone, Utc};
use chrono_tz::Europe::Berlin;
use serde_json::{Value, json};
Expand All @@ -21,6 +22,7 @@ use super::{Seeder, UserSpec};
use crate::config::InstanceMode;
use crate::i18n::Locale;
use crate::rpc::Ctx;
use crate::storage;

pub const KIDS_TITLE: Text = t(
"Kinderbasar Kita Sonnenschein",
Expand Down Expand Up @@ -102,6 +104,11 @@ struct People {
emails: HashMap<Uuid, String>,
}

/// Pictures of the demo regions, drawn by the app (see `Demo::region`)
const REGION_KIDS: &[u8] = include_bytes!("regions/kids.webp");
const REGION_SKI: &[u8] = include_bytes!("regions/ski.webp");
const REGION_BOOKS: &[u8] = include_bytes!("regions/books.webp");

struct Demo<'a> {
seeder: &'a Seeder,
ctx: &'a mut Ctx,
Expand Down Expand Up @@ -141,6 +148,38 @@ impl Demo<'_> {
self.seeder.text(text)
}

/// Only sellers from the region join on their own (#304), switched on once the demo
/// sellers joined: in English they live in Oxford. The picture is the one the app draws
/// when the organizer saves the region (src/lib/regionImage.ts), made with the address
/// of the German demo.
async fn region(
&mut self,
event: Uuid,
postal_codes: Value,
picture: &'static [u8],
) -> anyhow::Result<()> {
let state = self.ctx.state.clone();
let image = storage::store(
&state,
self.ctx.conn(),
Bytes::from_static(picture),
"image/webp",
None,
)
.await?;
sqlx::query(
"UPDATE events SET region_map_image_id = $3,
features = features || jsonb_build_object('allowedPostalCodes', $2::jsonb)
WHERE id = $1",
)
.bind(event)
.bind(postal_codes)
.bind(image)
.execute(self.ctx.conn())
.await?;
Ok(())
}

async fn call(&mut self, user: Uuid, name: &str, args: Value) -> anyhow::Result<Value> {
self.ctx
.call(Some(user), name, args.clone())
Expand Down Expand Up @@ -1076,6 +1115,9 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()>
)
.await?;

// Only for families from around Ulm
demo.region(event, json!({ "DE": ["890", "891", "892"] }), REGION_KIDS)
.await?;
// On full hours, it looks better in screenshots
let start = now.duration_trunc(Duration::hours(1))? - Duration::hours(2);
demo.finish(event, start, start + Duration::hours(10), None)
Expand Down Expand Up @@ -1226,6 +1268,13 @@ async fn ski_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()>
)
.await?;

// The Blautal and its neighbours; club members from elsewhere use the access code
demo.region(
event,
json!({ "DE": ["733", "890", "891", "896"] }),
REGION_SKI,
)
.await?;
let start = berlin(now, 9, 9, 0);
let end = berlin(now, 9, 14, 0);
demo.finish(
Expand Down Expand Up @@ -1525,6 +1574,20 @@ async fn book_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()>
)
.await?;
}
// Around the lake, across three borders
demo.region(
event,
json!({
"AT": [
"672", "684", "685", "686", "687", "688", "689", "690", "691", "692", "693",
"694", "695", "696", "697"
],
"CH": ["903", "904", "940", "941", "942", "943", "944", "945"],
"DE": ["880", "881"],
}),
REGION_BOOKS,
)
.await?;
demo.finish(
event,
berlin(now, -240, 10, 0),
Expand Down
Binary file added backend/src/demo/regions/books.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/src/demo/regions/kids.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/src/demo/regions/ski.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
28 changes: 28 additions & 0 deletions backend/src/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,34 @@ pub async fn enqueue(
.await
}

/// Schedules several jobs of one kind in a single insert, each at its own time.
pub async fn enqueue_many<P: Serialize>(
conn: &mut PgConnection,
kind: &str,
jobs: &[(P, DateTime<Utc>)],
) -> sqlx::Result<()> {
if jobs.is_empty() {
return Ok(());
}
let mut payloads = Vec::with_capacity(jobs.len());
let mut run_ats = Vec::with_capacity(jobs.len());
for (payload, run_at) in jobs {
payloads
.push(serde_json::to_value(payload).map_err(|err| sqlx::Error::Encode(err.into()))?);
run_ats.push(*run_at);
}
sqlx::query(
"INSERT INTO jobs (kind, payload, run_at)
SELECT $1, payload, run_at FROM UNNEST($2::jsonb[], $3::timestamptz[]) AS t(payload, run_at)",
)
.bind(kind)
.bind(payloads)
.bind(run_ats)
.execute(conn)
.await?;
Ok(())
}

/// Removes a job that has not started yet, like `ctx.scheduler.cancel`.
pub async fn cancel(conn: &mut PgConnection, id: Uuid) -> sqlx::Result<bool> {
let result = sqlx::query("DELETE FROM jobs WHERE id = $1 AND locked_until IS NULL")
Expand Down
4 changes: 4 additions & 0 deletions backend/src/modules/broadcasts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ enum Audience {
Accepted,
/// Sellers with unsold items still to pick up
Pickup,
/// Sellers who have not announced any item yet (#304), e.g. "Bitte bis Freitag anmelden"
WithoutItems,
}

impl Audience {
Expand All @@ -51,6 +53,7 @@ impl Audience {
Self::All => "all",
Self::Accepted => "accepted",
Self::Pickup => "pickup",
Self::WithoutItems => "withoutItems",
}
}
}
Expand All @@ -67,6 +70,7 @@ async fn recipients(ctx: &mut Ctx, event: Uuid, audience: Audience) -> sqlx::Res
"EXISTS (SELECT 1 FROM event_products ep JOIN products p ON p.id = ep.product_id
WHERE ep.event_id = r.event_id AND p.vendor_id = r.user_id AND ep.status = 'available')"
}
Audience::WithoutItems => super::event_seller::WITHOUT_ITEMS,
};
sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
"SELECT r.user_id FROM event_roles r WHERE r.event_id = $1 AND r.role = 'seller' AND {items}
Expand Down
6 changes: 5 additions & 1 deletion backend/src/modules/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ pub struct Event {
pub description: String,
pub cover_image: Option<Uuid>,
pub event_map_image: Option<Uuid>,
/// Picture of the region of a bazaar for its region (#304)
pub region_map_image: Option<Uuid>,
pub location: String,
/// Address of the venue; `location` is its name or, in older events, all of it
pub street: Option<String>,
Expand Down Expand Up @@ -188,6 +190,7 @@ struct EventRow {
description: String,
cover_image_id: Option<Uuid>,
map_image_id: Option<Uuid>,
region_map_image_id: Option<Uuid>,
location: String,
street: Option<String>,
postal_code: Option<String>,
Expand Down Expand Up @@ -254,6 +257,7 @@ impl From<EventRow> for Event {
description: row.description,
cover_image: row.cover_image_id,
event_map_image: row.map_image_id,
region_map_image: row.region_map_image_id,
location: row.location,
street: row.street,
postal_code: row.postal_code,
Expand Down Expand Up @@ -317,7 +321,7 @@ pub const SELLER_PLACES_SQL: &str = concat!(
/// SELECT list of the events table aliased `e`.
pub const EVENT_COLUMNS: &str = concat!(
"e.id, e.created_at, e.title, e.description, e.cover_image_id,
e.map_image_id, e.location, e.street, e.postal_code, e.city, e.country,
e.map_image_id, e.region_map_image_id, e.location, e.street, e.postal_code, e.city, e.country,
e.start_date, e.end_date, e.contact_info,
ARRAY(SELECT c.category_id FROM event_categories c WHERE c.event_id = e.id ORDER BY c.position)
AS categories,
Expand Down
45 changes: 34 additions & 11 deletions backend/src/modules/event_roles.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Roles in an event: organizer, co-organizer (helper), seller.
//! Platform administrators count as organizer of every event.

use std::collections::{HashMap, HashSet};

use chrono::Utc;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -441,6 +443,8 @@ pub struct VendorWithCalculations {
/// The seller's commission in percent: their group's or the bazaar's; once paid out the
/// one settled with
pub commission_percent: Decimal,
/// Has not announced any item yet (#304, `event_seller::WITHOUT_ITEMS`)
pub without_items: Option<bool>,
}

/// A seller's fee group as the team sees it.
Expand Down Expand Up @@ -501,20 +505,29 @@ pub async fn load_vendors_with_calculations(

let mut exclusions = exclusions_of_event(ctx.conn(), event_id).await?;
let all_purchases = docs::purchases_where(ctx.conn(), "event_id = $1", event_id).await?;
let mut vendors = Vec::new();
let users = docs::users(ctx.conn(), &vendor_ids).await?;
let mut purchases_by_seller: HashMap<Uuid, Vec<&docs::Purchase>> = HashMap::new();
for purchase in &all_purchases {
purchases_by_seller
.entry(purchase.seller_id)
.or_default()
.push(purchase);
}
let helpers: HashMap<Uuid, Option<Vec<String>>> = helpers.into_iter().collect();
let mut vendors = Vec::with_capacity(vendor_ids.len());
let mut users: HashMap<Uuid, docs::User> = docs::users(ctx.conn(), &vendor_ids)
.await?
.into_iter()
.map(|user| (user.id, user))
.collect();
let over = event.end_date < Utc::now();
let keeps_record = keeps_seller_record(&event);
let universal = label_mark(&event) == "universal";
for vendor in vendor_ids {
let Some(mut user) = users.iter().find(|user| user.id == vendor).cloned() else {
let Some(mut user) = users.remove(&vendor) else {
continue;
};
ctx.read(Topic::User(vendor));
let purchases: Vec<_> = all_purchases
.iter()
.filter(|purchase| purchase.seller_id == vendor)
.collect();
let purchases = purchases_by_seller.remove(&vendor).unwrap_or_default();
let total_revenue: Decimal = purchases.iter().map(|p| p.total_amount).sum();
let commission: Decimal = purchases.iter().map(|p| p.commission_amount).sum();
let sales_payout: Decimal = purchases.iter().map(|p| p.payout_amount).sum();
Expand All @@ -527,9 +540,8 @@ pub async fn load_vendors_with_calculations(
user = with_snapshot(user, snapshot);
}
let helper_permissions = helpers
.iter()
.find(|(user, _)| *user == vendor)
.map(|(_, stored)| permissions_of(stored.clone()));
.get(&vendor)
.map(|stored| permissions_of(stored.clone()));
let member = if groups {
Membership {
stored: seller.as_ref().and_then(|s| s.fee_group_id.clone()),
Expand Down Expand Up @@ -606,6 +618,8 @@ pub async fn load_vendors_with_calculations(
excluded: exclusions.remove(&vendor),
fee_group,
commission_percent,
// Only the seller list needs it: `get_vendors_for_event`
without_items: None,
});
}
Ok(vendors)
Expand All @@ -622,7 +636,16 @@ async fn get_vendors_for_event(
args: EventArgs,
) -> AppResult<Vec<VendorWithCalculations>> {
require_team(ctx, args.event_id.0).await?;
load_vendors_with_calculations(ctx, args.event_id.0).await
let mut vendors = load_vendors_with_calculations(ctx, args.event_id.0).await?;
let without_items: HashSet<Uuid> =
super::event_seller::sellers_without_items(ctx.conn(), args.event_id.0)
.await?
.into_iter()
.collect();
for vendor in &mut vendors {
vendor.without_items = without_items.contains(&vendor.user.id).then_some(true);
}
Ok(vendors)
}

#[derive(Deserialize)]
Expand Down
Loading
Loading