add organization access to clients

This commit is contained in:
2025-05-06 17:25:13 +05:30
parent 67c637d6da
commit d6d25004b9
6 changed files with 65 additions and 14 deletions

View File

@@ -1,3 +1,5 @@
import mongoose from "mongoose";
import { AuthenticatedUser } from "../auth";
import { getFilterObject, getSortObject, PageQueryParams } from "../pagination";
import { ChangeEvent, dbEvents } from "../realtime";
import { generateId } from "../utils/id";
@@ -35,14 +37,26 @@ export async function getOrg(orgId: string, tenantId: string) {
});
}
export async function listOrgs(params: PageQueryParams, tenantId: string) {
export async function listOrgs(
params: PageQueryParams,
user: AuthenticatedUser
) {
const page = params.page || 1;
const pageSize = params.pageSize || 10;
const sortObj = getSortObject(params, orgFields);
const filterObj = getFilterObject(params) || [];
if (user.role === "client") {
filterObj.push({
$or: [
{ type: "county" },
{ _id: new mongoose.Types.ObjectId(user.orgId) },
],
});
}
const orgs = await orgModel.aggregate([
{ $match: { $and: [{ tenantId: tenantId }, ...filterObj] } },
{ $match: { $and: [{ tenantId: user.tenantId }, ...filterObj] } },
{
$facet: {
metadata: [{ $count: "count" }],
@@ -118,19 +132,31 @@ export async function deleteOrg(orgId: string, tenantId: string) {
return res;
}
export async function searchOrgs(params: PageQueryParams, tenantId: string) {
export async function searchOrgs(
params: PageQueryParams,
user: AuthenticatedUser
) {
const page = params.page || 1;
const pageSize = params.pageSize || 10;
const sortObj = getSortObject(params, orgFields);
const filterObj = getFilterObject(params) || [];
if (user.role === "client") {
filterObj.push({
$or: [
{ type: "county" },
{ _id: new mongoose.Types.ObjectId(user.orgId) },
],
});
}
if (!params.searchToken)
return { orgs: [], metadata: { count: 0, page, pageSize } };
const regex = new RegExp(params.searchToken, "i");
const orgs = await orgModel.aggregate([
{ $match: { $and: [{ tenantId: tenantId }, ...filterObj] } },
{ $match: { $and: [{ tenantId: user.tenantId }, ...filterObj] } },
{
$match: {
$or: [{ name: { $regex: regex } }, { domain: { $regex: regex } }],