38 lines
970 B
TypeScript
38 lines
970 B
TypeScript
import type { Db } from '../db';
|
|
import type { User } from './users';
|
|
|
|
export interface Shop {
|
|
id: number;
|
|
name: string;
|
|
code: string;
|
|
}
|
|
|
|
interface ShopRow {
|
|
id: number;
|
|
name: string;
|
|
code: string;
|
|
}
|
|
|
|
const toShop = (r: ShopRow): Shop => ({ id: r.id, name: r.name, code: r.code });
|
|
export function shopsForUser(db: Db, user: User): Shop[] {
|
|
if (!user.active) return [];
|
|
|
|
const rows = user.isAdmin
|
|
? (db.prepare('SELECT id, name, code FROM shops WHERE active = 1 ORDER BY name, id').all() as ShopRow[])
|
|
: (db
|
|
.prepare(
|
|
`SELECT s.id, s.name, s.code
|
|
FROM shops s
|
|
JOIN user_shops us ON us.shop_id = s.id
|
|
WHERE us.user_id = ? AND s.active = 1
|
|
ORDER BY s.name, s.id`,
|
|
)
|
|
.all(user.id) as ShopRow[]);
|
|
|
|
return rows.map(toShop);
|
|
}
|
|
|
|
export function canUseShop(db: Db, user: User, shopId: number): boolean {
|
|
return shopsForUser(db, user).some((s) => s.id === shopId);
|
|
}
|