Add role-based visibility and management features for products
- Introduced a role-based visibility system for products, ensuring that only users with approved roles can view specific products. - Added new database tables for roles, user roles, and product role visibility to manage access control. - Implemented utility functions for role management, including fetching approved roles, checking product visibility, and assigning roles to users and products. - Updated API endpoints to filter products based on user roles, enhancing security and user experience. - Prepared the database schema for future role request and approval workflows in upcoming phases.
This commit is contained in:
43
server/database/migrations/0001_clammy_bulldozer.sql
Normal file
43
server/database/migrations/0001_clammy_bulldozer.sql
Normal file
@@ -0,0 +1,43 @@
|
||||
CREATE TYPE "public"."role_code" AS ENUM('private', 'educator', 'company');--> statement-breakpoint
|
||||
CREATE TYPE "public"."role_request_status" AS ENUM('pending', 'approved', 'rejected');--> statement-breakpoint
|
||||
CREATE TABLE "product_role_visibility" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"product_id" uuid NOT NULL,
|
||||
"role_id" uuid NOT NULL,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "roles" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"code" "role_code" NOT NULL,
|
||||
"display_name" text NOT NULL,
|
||||
"description" text NOT NULL,
|
||||
"requires_approval" boolean DEFAULT false NOT NULL,
|
||||
"sort_order" integer DEFAULT 0 NOT NULL,
|
||||
"active" boolean DEFAULT true NOT NULL,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "roles_code_unique" UNIQUE("code")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user_roles" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"role_id" uuid NOT NULL,
|
||||
"status" "role_request_status" DEFAULT 'pending' NOT NULL,
|
||||
"organization_name" text,
|
||||
"admin_notes" text,
|
||||
"status_history" jsonb DEFAULT '[]' NOT NULL,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "product_role_visibility" ADD CONSTRAINT "product_role_visibility_product_id_products_id_fk" FOREIGN KEY ("product_id") REFERENCES "public"."products"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "product_role_visibility" ADD CONSTRAINT "product_role_visibility_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "product_role_visibility_product_id_role_id_unique" ON "product_role_visibility" USING btree ("product_id","role_id");--> statement-breakpoint
|
||||
CREATE INDEX "product_role_visibility_product_id_idx" ON "product_role_visibility" USING btree ("product_id");--> statement-breakpoint
|
||||
CREATE INDEX "user_roles_user_id_role_id_unique" ON "user_roles" USING btree ("user_id","role_id");--> statement-breakpoint
|
||||
CREATE INDEX "user_roles_user_id_idx" ON "user_roles" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE INDEX "user_roles_status_idx" ON "user_roles" USING btree ("status");
|
||||
1000
server/database/migrations/meta/0001_snapshot.json
Normal file
1000
server/database/migrations/meta/0001_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,13 @@
|
||||
"when": 1761820599588,
|
||||
"tag": "0000_tiresome_malcolm_colcord",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1762074397305,
|
||||
"tag": "0001_clammy_bulldozer",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -95,6 +95,16 @@ export const orderStatusEnum = pgEnum('order_status', [
|
||||
'failed',
|
||||
])
|
||||
|
||||
// Role codes for user roles
|
||||
export const roleCodeEnum = pgEnum('role_code', ['private', 'educator', 'company'])
|
||||
|
||||
// Role request status (for approval workflow in Phase 2/3)
|
||||
export const roleRequestStatusEnum = pgEnum('role_request_status', [
|
||||
'pending',
|
||||
'approved',
|
||||
'rejected',
|
||||
])
|
||||
|
||||
/**
|
||||
* Users Table
|
||||
* Stores local user profiles linked to Cidaas authentication
|
||||
@@ -146,6 +156,93 @@ export const products = pgTable(
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Roles Table
|
||||
* Defines available user roles (private, educator, company)
|
||||
* Phase 2/3: Educator and Company roles require approval workflow
|
||||
*/
|
||||
export const roles = pgTable('roles', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
code: roleCodeEnum('code').unique().notNull(), // 'private', 'educator', 'company'
|
||||
displayName: text('display_name').notNull(), // "Privatperson", "Pädagoge", "Unternehmen"
|
||||
description: text('description').notNull(), // Role description
|
||||
requiresApproval: boolean('requires_approval').notNull().default(false), // false for 'private', true for 'educator'/'company'
|
||||
sortOrder: integer('sort_order').notNull().default(0), // Display order
|
||||
active: boolean('active').notNull().default(true), // Can be deactivated
|
||||
createdAt: timestamp('created_at').defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at').defaultNow().notNull(),
|
||||
})
|
||||
|
||||
/**
|
||||
* User Roles Table (Junction Table)
|
||||
* Many-to-Many relationship between users and roles
|
||||
* MVP: Roles assigned manually via DB, always status='approved'
|
||||
* Phase 2/3: Users can request roles, admin approves/rejects
|
||||
*/
|
||||
export const userRoles = pgTable(
|
||||
'user_roles',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
roleId: uuid('role_id')
|
||||
.notNull()
|
||||
.references(() => roles.id, { onDelete: 'cascade' }),
|
||||
|
||||
// Role request status (Phase 2/3 feature - prepared in MVP)
|
||||
status: roleRequestStatusEnum('status').notNull().default('pending'),
|
||||
|
||||
// Role request data (Phase 2/3 feature - prepared in MVP)
|
||||
organizationName: text('organization_name'), // School/Company name (freetext in MVP, FK to organizations in Phase 2/3)
|
||||
adminNotes: text('admin_notes'), // Admin comments on approval/rejection
|
||||
|
||||
// JSONB history of status changes (Phase 2/3 feature - prepared in MVP)
|
||||
// Format: [{ status, organizationName, adminNotes, changedAt, changedBy }, ...]
|
||||
statusHistory: jsonb('status_history').notNull().default('[]'),
|
||||
|
||||
createdAt: timestamp('created_at').defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at').defaultNow().notNull(),
|
||||
},
|
||||
(table) => ({
|
||||
// Unique constraint: User can only have one entry per role
|
||||
userIdRoleIdUnique: index('user_roles_user_id_role_id_unique').on(
|
||||
table.userId,
|
||||
table.roleId
|
||||
),
|
||||
userIdIdx: index('user_roles_user_id_idx').on(table.userId),
|
||||
statusIdx: index('user_roles_status_idx').on(table.status),
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Product Role Visibility Table (Junction Table)
|
||||
* Many-to-Many relationship between products and roles
|
||||
* Defines which roles can see which products
|
||||
* Products WITHOUT role assignments are INVISIBLE (opt-in visibility)
|
||||
*/
|
||||
export const productRoleVisibility = pgTable(
|
||||
'product_role_visibility',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
productId: uuid('product_id')
|
||||
.notNull()
|
||||
.references(() => products.id, { onDelete: 'cascade' }),
|
||||
roleId: uuid('role_id')
|
||||
.notNull()
|
||||
.references(() => roles.id, { onDelete: 'cascade' }),
|
||||
createdAt: timestamp('created_at').defaultNow().notNull(),
|
||||
},
|
||||
(table) => ({
|
||||
// Unique constraint: Product-Role pair can only exist once
|
||||
productIdRoleIdUnique: index('product_role_visibility_product_id_role_id_unique').on(
|
||||
table.productId,
|
||||
table.roleId
|
||||
),
|
||||
productIdIdx: index('product_role_visibility_product_id_idx').on(table.productId),
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Carts Table
|
||||
* Shopping carts for both authenticated and guest users
|
||||
@@ -232,6 +329,7 @@ export const orderItems = pgTable('order_items', {
|
||||
export const usersRelations = relations(users, ({ many }) => ({
|
||||
carts: many(carts),
|
||||
orders: many(orders),
|
||||
userRoles: many(userRoles),
|
||||
}))
|
||||
|
||||
export const cartsRelations = relations(carts, ({ one, many }) => ({
|
||||
@@ -275,4 +373,32 @@ export const orderItemsRelations = relations(orderItems, ({ one }) => ({
|
||||
export const productsRelations = relations(products, ({ many }) => ({
|
||||
cartItems: many(cartItems),
|
||||
orderItems: many(orderItems),
|
||||
roleVisibility: many(productRoleVisibility),
|
||||
}))
|
||||
|
||||
export const rolesRelations = relations(roles, ({ many }) => ({
|
||||
userRoles: many(userRoles),
|
||||
productVisibility: many(productRoleVisibility),
|
||||
}))
|
||||
|
||||
export const userRolesRelations = relations(userRoles, ({ one }) => ({
|
||||
user: one(users, {
|
||||
fields: [userRoles.userId],
|
||||
references: [users.id],
|
||||
}),
|
||||
role: one(roles, {
|
||||
fields: [userRoles.roleId],
|
||||
references: [roles.id],
|
||||
}),
|
||||
}))
|
||||
|
||||
export const productRoleVisibilityRelations = relations(productRoleVisibility, ({ one }) => ({
|
||||
product: one(products, {
|
||||
fields: [productRoleVisibility.productId],
|
||||
references: [products.id],
|
||||
}),
|
||||
role: one(roles, {
|
||||
fields: [productRoleVisibility.roleId],
|
||||
references: [roles.id],
|
||||
}),
|
||||
}))
|
||||
|
||||
@@ -7,8 +7,42 @@
|
||||
|
||||
import 'dotenv/config'
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import postgres from 'postgres'
|
||||
import { products } from './schema'
|
||||
import * as schema from './schema'
|
||||
import { products, roles, productRoleVisibility } from './schema'
|
||||
|
||||
/**
|
||||
* Standard roles for the system
|
||||
* MVP: All roles are created, but assignment is manual
|
||||
* Phase 2/3: educator and company roles require approval workflow
|
||||
*/
|
||||
const standardRoles = [
|
||||
{
|
||||
code: 'private' as const,
|
||||
displayName: 'Privatperson',
|
||||
description: 'Für private Besucher und Einzelpersonen',
|
||||
requiresApproval: false,
|
||||
sortOrder: 1,
|
||||
active: true,
|
||||
},
|
||||
{
|
||||
code: 'educator' as const,
|
||||
displayName: 'Pädagoge',
|
||||
description: 'Für Lehrer, Erzieher und pädagogische Fachkräfte',
|
||||
requiresApproval: true,
|
||||
sortOrder: 2,
|
||||
active: true,
|
||||
},
|
||||
{
|
||||
code: 'company' as const,
|
||||
displayName: 'Unternehmen',
|
||||
description: 'Für Firmenkunden und B2B-Partner',
|
||||
requiresApproval: true,
|
||||
sortOrder: 3,
|
||||
active: true,
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* Sample annual pass products for experimenta
|
||||
@@ -55,33 +89,108 @@ async function seed() {
|
||||
|
||||
console.log('🌱 Starting database seed...')
|
||||
|
||||
// Create database connection
|
||||
// Create database connection with schema
|
||||
const client = postgres(connectionString)
|
||||
const db = drizzle(client)
|
||||
const db = drizzle(client, { schema })
|
||||
|
||||
try {
|
||||
// Insert products
|
||||
console.log(`📦 Inserting ${mockProducts.length} products...`)
|
||||
const insertedProducts = await db
|
||||
.insert(products)
|
||||
.values(mockProducts)
|
||||
.onConflictDoUpdate({
|
||||
target: products.navProductId,
|
||||
set: {
|
||||
name: mockProducts[0].name, // Drizzle requires a set object, using sql.excluded in real impl
|
||||
description: mockProducts[0].description,
|
||||
price: mockProducts[0].price,
|
||||
stockQuantity: mockProducts[0].stockQuantity,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
.returning()
|
||||
// 1. Insert/Update Roles
|
||||
console.log(`👥 Inserting ${standardRoles.length} roles...`)
|
||||
const insertedRoles = []
|
||||
for (const roleData of standardRoles) {
|
||||
const [role] = await db
|
||||
.insert(roles)
|
||||
.values(roleData)
|
||||
.onConflictDoUpdate({
|
||||
target: roles.code,
|
||||
set: {
|
||||
displayName: roleData.displayName,
|
||||
description: roleData.description,
|
||||
requiresApproval: roleData.requiresApproval,
|
||||
sortOrder: roleData.sortOrder,
|
||||
active: roleData.active,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
.returning()
|
||||
insertedRoles.push(role)
|
||||
}
|
||||
|
||||
console.log(`✅ Successfully inserted/updated ${insertedRoles.length} roles:`)
|
||||
insertedRoles.forEach((role) => {
|
||||
console.log(
|
||||
` - ${role.displayName} (${role.code}) ${role.requiresApproval ? '[requires approval]' : '[auto-approved]'}`
|
||||
)
|
||||
})
|
||||
|
||||
// 2. Insert/Update Products
|
||||
console.log(`\n📦 Inserting ${mockProducts.length} products...`)
|
||||
const insertedProducts = []
|
||||
for (const productData of mockProducts) {
|
||||
const [product] = await db
|
||||
.insert(products)
|
||||
.values(productData)
|
||||
.onConflictDoUpdate({
|
||||
target: products.navProductId,
|
||||
set: {
|
||||
name: productData.name,
|
||||
description: productData.description,
|
||||
price: productData.price,
|
||||
stockQuantity: productData.stockQuantity,
|
||||
category: productData.category,
|
||||
active: productData.active,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
.returning()
|
||||
insertedProducts.push(product)
|
||||
}
|
||||
|
||||
console.log(`✅ Successfully inserted/updated ${insertedProducts.length} products:`)
|
||||
insertedProducts.forEach((product) => {
|
||||
console.log(` - ${product.name} (${product.navProductId}) - €${product.price}`)
|
||||
})
|
||||
|
||||
// 3. Assign Roles to Products (Category-based mapping)
|
||||
console.log(`\n🔗 Assigning roles to products based on category...`)
|
||||
|
||||
// Category to role mapping
|
||||
const categoryRoleMapping: Record<string, string[]> = {
|
||||
'makerspace-annual-pass': ['private', 'educator'],
|
||||
'annual-pass': ['private'],
|
||||
'educator-annual-pass': ['educator'],
|
||||
}
|
||||
|
||||
let assignmentCount = 0
|
||||
for (const product of insertedProducts) {
|
||||
const roleCodes = categoryRoleMapping[product.category] || []
|
||||
|
||||
for (const roleCode of roleCodes) {
|
||||
// Find role by code
|
||||
const role = insertedRoles.find((r) => r.code === roleCode)
|
||||
if (!role) continue
|
||||
|
||||
// Check if assignment already exists
|
||||
const existing = await db.query.productRoleVisibility.findFirst({
|
||||
where: and(
|
||||
eq(productRoleVisibility.productId, product.id),
|
||||
eq(productRoleVisibility.roleId, role.id)
|
||||
),
|
||||
})
|
||||
|
||||
if (!existing) {
|
||||
await db.insert(productRoleVisibility).values({
|
||||
productId: product.id,
|
||||
roleId: role.id,
|
||||
})
|
||||
assignmentCount++
|
||||
console.log(` - ${product.name} → ${role.displayName}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ Created ${assignmentCount} product-role assignments`)
|
||||
|
||||
console.log('\n✨ Database seed completed successfully!')
|
||||
} catch (error) {
|
||||
console.error('❌ Error seeding database:', error)
|
||||
|
||||
Reference in New Issue
Block a user