Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,800 @@
import { Entity, EntityRelationship, EntityTag, EntityTemplate, Prisma, Property, PropertyAttribute, PropertyOption } from "@toolctrl/db/prisma-browser";
import Constants from "~/application/Constants";
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
import { defaultProperties } from "~/utils/helpers/PropertyHelper";
import { db } from "../../db.server";
import { EntityRelationshipWithDetails } from "./entityRelationships.db.server";
import { EntityViewWithDetails } from "./entityViews.db.server";
import { createProperties, CreatePropertyDto } from "./properties.db.server";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
import EntitiesSingleton from "~/modules/rows/repositories/EntitiesSingleton";
export type EntitySimple = {
id: string;
order: number;
name: string;
title: string;
titlePlural: string;
active: boolean;
slug: string;
type: string;
hasApi: boolean;
showInSidebar: boolean;
icon: string;
onEdit: string | null;
};
export type RowsUsage = { entityId: string; _count: number };
export type EntityWithProperties = Entity & {
properties: PropertyWithDetails[];
};
export type EntityWithDetails = Entity & {
properties: PropertyWithDetails[];
views: EntityViewWithDetails[];
tags: EntityTag[];
parentEntities: EntityRelationshipWithDetails[];
childEntities: EntityRelationshipWithDetails[];
templates: EntityTemplate[];
};
export type EntityWithDetailsAndRelationships = EntityWithDetails & {
parentEntities: (EntityRelationship & { parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null } })[];
childEntities: (EntityRelationship & { parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null } })[];
};
export type EntityWithCount = EntityWithDetails & {
_count: { rows: number };
};
export type PropertyWithDetails = Property & {
// entity: EntityWithDetails;
attributes: PropertyAttribute[];
options: PropertyOption[];
parent?: PropertyWithDetails;
formula: { name: string; resultAs: string; calculationTrigger: string } | null;
};
// const includeEntityWithDetails = {
// properties: {
// include: {
// options: true,
// },
// },
// };
export async function getEntitiesInIds(ids: string[]) {
return await db.entity.findMany({
where: { id: { in: ids } },
});
}
export async function getAllEntities({
tenantId,
active,
types,
}: {
tenantId: string | null | undefined;
active?: boolean;
types?: string[];
}): Promise<EntityWithDetails[]> {
let where: Prisma.EntityWhereInput = {};
if (active) {
where = { active };
}
if (types) {
where = { ...where, type: { in: types } };
}
const allEntities = await db.entity.findMany({
where,
orderBy: [
{ type: "asc" },
{
order: "asc",
},
],
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
EntitiesSingleton.getInstance().setEntities(allEntities);
return allEntities;
}
export async function getAllEntitiesSimple({ active, types }: { active?: boolean; types?: string[] } = {}): Promise<EntitySimple[]> {
let where: Prisma.EntityWhereInput = {};
if (active) {
where = { active };
}
if (types) {
where = { ...where, type: { in: types } };
}
return await db.entity.findMany({
where,
orderBy: [
{ type: "asc" },
{
order: "asc",
},
],
select: EntityModelHelper.selectSimpleProperties,
});
}
export async function getEntitySimple({ id, name }: { id?: string; name?: string }): Promise<EntitySimple | null> {
if (!id && !name) {
return null;
} else if (id) {
return await db.entity.findUnique({
where: {
id,
},
select: EntityModelHelper.selectSimpleProperties,
});
} else {
return await db.entity.findUnique({
where: {
name,
},
select: EntityModelHelper.selectSimpleProperties,
});
}
}
export async function getEntitiesByName(name: string[]) {
return await db.entity.findMany({
where: {
name: {
in: name,
},
},
});
}
export async function getAllEntitiesWithRowCount({ tenantId }: { tenantId: string | null }): Promise<EntityWithCount[]> {
return await db.entity.findMany({
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
templates: {
where: { ...filterTenantId(tenantId) },
},
_count: {
select: {
rows: true,
},
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
},
orderBy: [
{ type: "asc" },
{
order: "asc",
},
],
});
}
export async function getAllRowsUsage(tenantId: string): Promise<RowsUsage[]> {
const countEntities = await db.row.groupBy({
by: ["entityId"],
_count: true,
where: {
OR: [
{
tenantId,
},
],
},
});
return countEntities;
}
export async function getEntityById({ id, tenantId }: { id: string; tenantId: string | null | undefined }): Promise<EntityWithDetailsAndRelationships | null> {
return await db.entity.findUnique({
where: {
id,
},
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
}
export async function getEntityBySlug({
tenantId,
slug,
activeOnly,
}: {
tenantId: string | null;
slug: string;
activeOnly?: boolean;
}): Promise<EntityWithDetails> {
const entity = await db.entity.findUnique({
where: {
slug,
},
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
if (!entity) {
throw new Error(`Entity '${slug}' not found`);
}
if (activeOnly && !entity.active) {
throw new Error(`Entity '${slug}' is not active`);
}
return entity;
}
export async function getSimpleEntityBySlug(slug: string): Promise<EntitySimple | null> {
return await db.entity.findUnique({
where: {
slug,
},
select: EntityModelHelper.selectSimpleProperties,
});
}
export async function findEntityBySlug(slug: string): Promise<Entity | null> {
return await db.entity.findUnique({
where: { slug },
});
}
export async function getEntityByName({ tenantId, name }: { tenantId: string | null | undefined; name: string }): Promise<EntityWithDetails> {
const entity = await db.entity.findUnique({
where: {
name,
},
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
if (!entity) {
throw new Error(`Entity with name ${name} not found`);
}
return entity;
}
export async function getEntityByIdOrName({
tenantId,
id,
name,
}: {
tenantId: string | null | undefined;
id?: string;
name?: string;
}): Promise<EntityWithDetails> {
let entity: EntityWithDetails | null = null;
if (id) {
entity = await getEntityById({ tenantId, id });
} else if (name) {
entity = await getEntityByName({ tenantId, name });
}
if (!entity) {
throw new Error(`Entity with id ${id} or name ${name} not found`);
}
return entity;
}
export async function getEntityByIdNameOrSlug({ tenantId, idNameOrSlug }: { tenantId: string | null; idNameOrSlug: string }): Promise<EntityWithDetails> {
return getEntityWithWhere({
tenantId,
where: {
OR: [{ id: idNameOrSlug }, { name: idNameOrSlug }, { slug: idNameOrSlug }],
},
});
}
async function getEntityWithWhere({ tenantId, where }: { tenantId: string | null; where: Prisma.EntityWhereInput }) {
const entity = await db.entity.findFirst({
where,
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
if (!entity) {
throw new Error(`Entity not found`);
}
return entity;
}
export async function findEntityByName({ tenantId, name }: { tenantId: string | null; name: string }): Promise<EntityWithDetails | null> {
return await db.entity.findUnique({
where: { name },
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
}
export async function findSimpleEntityByName(name: string): Promise<{ id: string; title: string; titlePlural: string; slug: string } | null> {
if (EntitiesSingleton.getInstance().isSet()) {
return (
EntitiesSingleton.getInstance()
.getEntities()
.find((f) => f.name === name) ?? null
);
}
return await db.entity.findUnique({
where: { name },
select: { id: true, title: true, titlePlural: true, slug: true },
});
}
export async function getEntityByPrefix(prefix: string): Promise<Entity | null> {
return await db.entity.findUnique({
where: {
prefix,
},
});
}
export async function createEntity(
data: {
name: string;
slug: string;
prefix: string;
title: string;
titlePlural: string;
isAutogenerated: boolean;
type: string;
hasApi: boolean;
icon: string;
active: boolean;
showInSidebar: boolean;
hasTags: boolean;
hasComments: boolean;
hasTasks: boolean;
hasActivity: boolean;
hasBulkDelete: boolean;
hasViews: boolean;
defaultVisibility: string;
onCreated: string | null;
onEdit: string | null;
},
order?: number | null
) {
if (!order) {
order = (await getMaxEntityOrder()) + 1;
}
const entity = await db.entity.create({
data: {
...data,
order,
},
});
const webhooks = [
{
action: DefaultLogActions.Created,
method: "POST",
endpoint: "",
},
{
action: DefaultLogActions.Updated,
method: "POST",
endpoint: "",
},
{
action: DefaultLogActions.Created,
method: "POST",
endpoint: "",
},
];
await Promise.all(
webhooks.map(async (webhook) => {
return await db.entityWebhook.create({
data: {
entityId: entity.id,
action: webhook.action,
method: webhook.method,
endpoint: webhook.endpoint,
},
});
})
);
await Promise.all(
defaultProperties.map(async (property) => {
return await db.property.create({
data: {
entityId: entity.id,
...property,
},
});
})
);
return entity;
}
export async function createCoreEntity(
data: {
name: string;
slug: string;
title: string;
titlePlural: string;
prefix: string;
type: string;
isAutogenerated?: boolean;
hasApi?: boolean;
icon?: string;
active?: boolean;
showInSidebar?: boolean;
hasTags?: boolean;
hasComments?: boolean;
hasTasks?: boolean;
hasActivity?: boolean;
hasBulkDelete?: boolean;
hasViews?: boolean;
defaultVisibility?: DefaultVisibility;
onCreated?: string | null;
onEdit?: string | null;
},
properties?: CreatePropertyDto[]
) {
const entity = await createEntity({
name: data.name,
slug: data.slug,
prefix: data.prefix,
title: data.title,
titlePlural: data.titlePlural,
type: data.type,
isAutogenerated: data.isAutogenerated !== undefined ? data.isAutogenerated : true,
hasApi: data.hasApi !== undefined ? data.hasApi : true,
icon: data.icon !== undefined ? data.icon : "",
active: data.active !== undefined ? data.active : true,
showInSidebar: data.showInSidebar !== undefined ? data.showInSidebar : true,
hasTags: data.hasTags !== undefined ? data.hasTags : true,
hasComments: data.hasComments !== undefined ? data.hasComments : true,
hasTasks: data.hasTasks !== undefined ? data.hasTasks : false,
hasActivity: data.hasActivity !== undefined ? data.hasActivity : true,
hasBulkDelete: data.hasBulkDelete !== undefined ? data.hasBulkDelete : false,
hasViews: data.hasViews !== undefined ? data.hasViews : true,
defaultVisibility: data.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY,
onCreated: data.onCreated ?? "redirectToOverview",
onEdit: data.onEdit ?? "editRoute",
});
if (properties) {
await createProperties(entity.id, properties);
}
return entity;
}
export async function updateEntity(
id: string,
data: {
name?: string;
slug?: string;
order?: number;
prefix?: string;
title?: string;
titlePlural?: string;
isAutogenerated?: boolean;
type?: string;
hasApi?: boolean;
icon?: string;
active?: boolean;
showInSidebar?: boolean;
hasTags?: boolean;
hasComments?: boolean;
hasTasks?: boolean;
hasActivity?: boolean;
hasBulkDelete?: boolean;
hasViews?: boolean;
defaultVisibility?: string;
onCreated?: string | null;
onEdit?: string | null;
}
) {
return await db.entity.update({
where: {
id,
},
data,
});
}
export async function deleteEntity(id: string) {
return await db.entity.delete({
where: {
id,
},
});
}
export default async function getMaxEntityOrder(): Promise<number> {
return (
(
await db.entity.aggregate({
_max: {
order: true,
},
})
)._max?.order ?? 0
);
}
export async function getDefaultEntityVisibility(id: string): Promise<DefaultVisibility> {
return ((
await db.entity.findUnique({
where: { id },
select: {
defaultVisibility: true,
},
})
)?.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY) as DefaultVisibility;
}
function filterTenantId(tenantId: string | null | undefined) {
const filter: { tenantId?: string | null; OR?: { tenantId?: string | null }[] } = {};
if (tenantId === undefined) {
return filter;
} else if (tenantId === null) {
filter.tenantId = null;
} else {
filter.OR = [{ tenantId: null }, { tenantId }];
}
return filter;
}
@@ -0,0 +1,137 @@
import { EntityGroup, EntityGroupEntity, Prisma } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { EntitySimple } from "./entities.db.server";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
import { EntityViewWithDetails } from "./entityViews.db.server";
export type EntityGroupWithDetails = EntityGroup & {
entities: EntityGroupEntityWithDetails[];
};
export type EntityGroupEntityWithDetails = EntityGroupEntity & {
entity: EntitySimple;
allView: EntityViewWithDetails | null;
};
export async function getAllEntityGroups(): Promise<EntityGroupWithDetails[]> {
return db.entityGroup.findMany({
include: {
entities: {
include: {
entity: { select: EntityModelHelper.selectSimpleProperties },
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
},
orderBy: { entity: { order: "asc" } },
},
},
orderBy: { order: "asc" },
});
}
export async function getEntityGroup(id: string): Promise<EntityGroupWithDetails | null> {
return db.entityGroup.findUnique({
where: { id },
include: {
entities: {
include: {
entity: { select: EntityModelHelper.selectSimpleProperties },
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
},
orderBy: { entity: { order: "asc" } },
},
},
});
}
export async function getEntityGroupBySlug(slug: string): Promise<EntityGroupWithDetails | null> {
return db.entityGroup.findUnique({
where: { slug },
include: {
entities: {
include: {
entity: { select: EntityModelHelper.selectSimpleProperties },
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
},
orderBy: { entity: { order: "asc" } },
},
},
});
}
export async function createEntityGroup(data: {
order: number;
slug: string;
title: string;
icon: string;
collapsible: boolean;
section: string | null;
entities: {
entityId: string;
allViewId: string | null;
}[];
}): Promise<EntityGroup> {
return db.entityGroup.create({
data: {
order: data.order,
slug: data.slug,
title: data.title,
icon: data.icon,
collapsible: data.collapsible,
section: data.section,
entities: {
create: data.entities.map((f) => {
return {
entityId: f.entityId,
allViewId: f.allViewId,
};
}),
},
},
});
}
export async function updateEntityGroup(
id: string,
data: {
order?: number;
slug?: string;
title?: string;
icon?: string;
collapsible?: boolean;
section?: string | null;
entities?: {
entityId: string;
allViewId: string | null;
}[];
}
): Promise<EntityGroup> {
let update: Prisma.EntityGroupUpdateInput = {
order: data.order,
slug: data.slug,
title: data.title,
icon: data.icon,
collapsible: data.collapsible,
section: data.section,
};
if (data.entities) {
update.entities = {
deleteMany: {},
create: data.entities.map((f) => {
return {
entityId: f.entityId,
allViewId: f.allViewId,
};
}),
};
}
return db.entityGroup.update({
where: { id },
data: update,
});
}
export async function deleteEntityGroup(id: string): Promise<EntityGroup> {
return db.entityGroup.delete({
where: { id },
});
}
@@ -0,0 +1,258 @@
import { EntityRelationship } from "@toolctrl/db/prisma-browser";
import { db } from "../../db.server";
import { EntityViewWithDetails } from "./entityViews.db.server";
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
export type EntityRelationshipWithDetails = EntityRelationship & {
parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
child: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
childEntityView: EntityViewWithDetails | null;
parentEntityView: EntityViewWithDetails | null;
};
export type EntityRelationshipWithCount = EntityRelationshipWithDetails & {
_count: { rows: number };
};
export async function getAllEntityRelationships(): Promise<EntityRelationshipWithDetails[]> {
return await db.entityRelationship.findMany({
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
},
});
}
export async function findEntityRelationship({
parentId,
childId,
title,
notIn,
}: {
parentId: string;
childId: string;
title: string | null;
notIn?: string[];
}): Promise<EntityRelationshipWithCount | null> {
return await db.entityRelationship.findFirst({
where: {
OR: [
{ parentId, childId },
{ parentId: childId, childId: parentId },
],
title,
id: {
notIn,
},
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
});
}
export async function getEntityRelationships(entityId: string): Promise<EntityRelationshipWithDetails[]> {
return await db.entityRelationship.findMany({
where: {
OR: [
{
parentId: entityId,
},
{
childId: entityId,
},
],
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
},
orderBy: [{ order: "asc" }],
});
}
export async function getEntityRelationshipsWithCount(entityId: string): Promise<EntityRelationshipWithCount[]> {
return await db.entityRelationship.findMany({
where: {
OR: [{ parentId: entityId }, { childId: entityId }],
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
orderBy: [{ order: "asc" }],
});
}
export async function getEntitiesRelationship({
parentEntityId,
childEntityId,
}: {
parentEntityId: string;
childEntityId: string;
}): Promise<EntityRelationshipWithDetails | null> {
return await db.entityRelationship.findFirst({
where: {
parentId: parentEntityId,
childId: childEntityId,
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
},
orderBy: [{ order: "asc" }],
});
}
export async function getEntityRelationship(id: string): Promise<EntityRelationshipWithCount | null> {
return await db.entityRelationship.findUnique({
where: {
id,
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
});
}
type EntityRelationshipScope = {
id: string;
entityId: string;
};
function relationshipScopeWhere(scope: EntityRelationshipScope) {
return {
id: scope.id,
OR: [{ parentId: scope.entityId }, { childId: scope.entityId }],
};
}
export async function getScopedEntityRelationship(scope: EntityRelationshipScope): Promise<EntityRelationshipWithCount | null> {
return await db.entityRelationship.findFirst({
where: relationshipScopeWhere(scope),
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
});
}
export async function createEntityRelationship({
parentId,
childId,
order,
title,
type,
required,
cascade,
readOnly,
hiddenIfEmpty,
childEntityViewId,
parentEntityViewId,
}: {
parentId: string;
childId: string;
order: number;
title: string | null;
type: string;
required: boolean;
cascade: boolean;
readOnly: boolean;
hiddenIfEmpty: boolean;
childEntityViewId: string | null;
parentEntityViewId: string | null;
}) {
return await db.entityRelationship.create({
data: {
parentId,
childId,
order,
title,
type,
required,
cascade,
readOnly,
hiddenIfEmpty,
childEntityViewId,
parentEntityViewId,
},
});
}
export async function updateEntityRelationship(
id: string,
data: {
parentId?: string;
childId?: string;
order?: number;
title?: string | null;
type?: string;
required?: boolean;
cascade?: boolean;
readOnly?: boolean;
hiddenIfEmpty?: boolean;
childEntityViewId?: string | null;
parentEntityViewId?: string | null;
}
) {
return await db.entityRelationship.update({
where: {
id,
},
data: {
...data,
},
});
}
type UpdateEntityRelationshipData = Parameters<typeof updateEntityRelationship>[1];
export async function updateScopedEntityRelationship(scope: EntityRelationshipScope, data: UpdateEntityRelationshipData) {
const result = await db.entityRelationship.updateMany({
where: relationshipScopeWhere(scope),
data: {
...data,
},
});
if (result.count !== 1) {
throw Error("Relationship not found");
}
return await getScopedEntityRelationship(scope);
}
export async function deleteEntityRelationship(id: string) {
return await db.entityRelationship.delete({
where: {
id,
},
});
}
export async function deleteScopedEntityRelationship(scope: EntityRelationshipScope) {
const result = await db.entityRelationship.deleteMany({
where: relationshipScopeWhere(scope),
});
if (result.count !== 1) {
throw Error("Relationship not found");
}
}
@@ -0,0 +1,47 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db.server", () => ({
db: {
entityTag: {
findFirst: vi.fn(),
findUnique: vi.fn(),
updateMany: vi.fn(),
deleteMany: vi.fn(),
},
},
}));
import { db } from "~/utils/db.server";
import { deleteEntityTag, getEntityTagById, updateEntityTag } from "./entityTags.db.server";
const entityTagMock = vi.mocked(db.entityTag, true);
describe("entity tag tenant boundary helpers", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("can resolve tags by id within an entity scope", async () => {
const tag = { id: "tag_1", entityId: "entity_1", value: "Warm", color: 3, createdAt: new Date("2026-01-01T00:00:00.000Z") };
entityTagMock.findFirst.mockResolvedValueOnce(tag);
await expect(getEntityTagById("tag_1", "entity_1")).resolves.toEqual(tag);
expect(entityTagMock.findFirst).toHaveBeenCalledWith({ where: { id: "tag_1", entityId: "entity_1" } });
expect(entityTagMock.findUnique).not.toHaveBeenCalled();
});
it("updates and deletes tags with id and entity scope", async () => {
entityTagMock.updateMany.mockResolvedValueOnce({ count: 1 });
entityTagMock.deleteMany.mockResolvedValueOnce({ count: 1 });
await updateEntityTag({ id: "tag_1", entityId: "entity_1" }, { value: "Warm", color: 3 });
await deleteEntityTag({ id: "tag_1", entityId: "entity_1" });
expect(entityTagMock.updateMany).toHaveBeenCalledWith({
where: { id: "tag_1", entityId: "entity_1" },
data: { value: "Warm", color: 3 },
});
expect(entityTagMock.deleteMany).toHaveBeenCalledWith({ where: { id: "tag_1", entityId: "entity_1" } });
});
});
@@ -0,0 +1,65 @@
import { EntityTag } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
export async function getEntityTags(entityId: string): Promise<EntityTag[]> {
return await db.entityTag.findMany({
where: {
entityId,
},
});
}
export async function getEntityTagById(id: string, entityId?: string): Promise<EntityTag | null> {
if (entityId) {
return await db.entityTag.findFirst({
where: {
id,
entityId,
},
});
}
return await db.entityTag.findUnique({ where: { id } });
}
export async function getEntityTag(entityId: string, value: string): Promise<EntityTag | null> {
return await db.entityTag.findFirst({
where: {
entityId,
value,
},
});
}
export async function getEntityTagByEntityName(entityName: string, value: string): Promise<EntityTag | null> {
return await db.entityTag.findFirst({
where: {
entity: { name: entityName },
value,
},
});
}
export async function createEntityTag(data: { entityId: string; color: number; value: string }) {
return await db.entityTag.create({
data,
});
}
export async function updateEntityTag({ id, entityId }: { id: string; entityId: string }, data: { color?: number; value?: string }) {
return await db.entityTag.updateMany({
where: {
id,
entityId,
},
data,
});
}
export async function deleteEntityTag({ id, entityId }: { id: string; entityId: string }) {
return await db.entityTag.deleteMany({
where: {
id,
entityId,
},
});
}
@@ -0,0 +1,70 @@
import { db } from "~/utils/db.server";
export async function getEntityTemplates(entityId: string, { tenantId }: { tenantId: string | null }) {
return await db.entityTemplate.findMany({
where: { entityId, tenantId },
orderBy: { entity: { order: "asc" } },
});
}
type EntityTemplateScope = {
id: string;
tenantId: string | null;
entityId: string;
};
export async function getEntityTemplate(id: string, { tenantId, entityId }: { tenantId: string | null; entityId?: string }) {
return await db.entityTemplate
.findFirstOrThrow({
where: { id, tenantId, ...(entityId ? { entityId } : {}) },
})
.catch(() => {
return null;
});
}
export async function createEntityTemplate(data: { tenantId: string | null; entityId: string; title: string; config: string }) {
return await db.entityTemplate.create({
data: {
tenantId: data.tenantId,
entityId: data.entityId,
title: data.title,
config: data.config,
},
});
}
export async function updateEntityTemplate(id: string, data: { title: string; config: string }) {
return await db.entityTemplate.update({
where: {
id,
},
data,
});
}
export async function updateScopedEntityTemplate(scope: EntityTemplateScope, data: { title: string; config: string }) {
const result = await db.entityTemplate.updateMany({
where: scope,
data,
});
if (result.count !== 1) {
throw Error("Entity template not found");
}
return await getEntityTemplate(scope.id, { tenantId: scope.tenantId, entityId: scope.entityId });
}
export async function deleteEntityTemplate(id: string) {
return await db.entityTemplate.delete({
where: { id },
});
}
export async function deleteScopedEntityTemplate(scope: EntityTemplateScope) {
const result = await db.entityTemplate.deleteMany({
where: scope,
});
if (result.count !== 1) {
throw Error("Entity template not found");
}
}
@@ -0,0 +1,19 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "entityViews.db.server.ts"), "utf8");
describe("entity views db wrapper", () => {
test("does not include tenant user-private views unless a user id is explicit", () => {
expect(source).toContain("const userId = options.userId ?? null");
expect(source).toContain("if (userId) {\n scope.unshift({ tenantId: options.tenantId, userId });\n }");
});
test("supports scoped entity-view lookup by id", () => {
expect(source).toContain("entityId: options?.entityId");
expect(source).toContain("...buildEntityViewScopeWhere({ tenantId: options?.tenantId, userId: options?.userId })");
});
});
@@ -0,0 +1,422 @@
import { EntityView, EntityViewFilter, EntityViewProperty, EntityViewSort, Prisma, Property } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
import TenantModelHelper from "~/utils/helpers/models/TenantModelHelper";
import { TenantSimple } from "../tenants.db.server";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
import { EntitySimple } from "./entities.db.server";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
export type EntityViewWithDetails = EntityView & {
properties: EntityViewProperty[];
filters: EntityViewFilter[];
sort: EntityViewSort[];
groupByProperty: Property | null;
};
export type EntityViewWithTenantAndUser = EntityViewWithDetails & {
entity: EntitySimple;
createdByUser: UserSimple | null;
tenant: TenantSimple | null;
user: UserSimple | null;
};
export async function getAllEntityViews({
type,
entityId,
pagination,
filters,
}: {
type?: string;
entityId?: string;
pagination?: { pageSize: number; page: number };
filters?: FiltersDto;
}): Promise<{ items: EntityViewWithTenantAndUser[]; total: number }> {
let where: Prisma.EntityViewWhereInput = {
entityId,
};
if (type === "default") {
where = { tenantId: null, userId: null, isSystem: false };
} else if (type === "tenant") {
where = { tenantId: { not: null }, userId: null, isSystem: false };
} else if (type === "user") {
where = { userId: { not: null }, isSystem: false };
} else if (type === "system") {
where = { isSystem: true };
}
const filterEntityId = filters?.properties.find((filter) => filter.name === "entityId")?.value;
const filterTenantId = filters?.properties.find((filter) => filter.name === "tenantId")?.value;
const filterUserId = filters?.properties.find((filter) => filter.name === "userId")?.value;
if (filterEntityId) {
where = { ...where, entityId: filterEntityId };
}
if (filterTenantId) {
where = { ...where, tenantId: filterTenantId };
}
if (filterUserId) {
where = { ...where, userId: filterUserId };
}
const items = await db.entityView.findMany({
take: pagination?.pageSize,
skip: pagination ? pagination.pageSize * (pagination.page - 1) : undefined,
where,
include: {
...EntityViewModelHelper.includeDetails,
entity: { select: EntityModelHelper.selectSimpleProperties },
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
user: { select: UserModelHelper.selectSimpleUserProperties },
},
orderBy: [{ tenantId: "asc" }, { userId: "asc" }, { order: "asc" }],
});
const total = await db.entityView.count({ where });
return {
items,
total,
};
}
export async function getEntityViews(
entityId: string,
options?: {
tenantId?: string | null;
userId?: string | null;
}
): Promise<EntityViewWithDetails[]> {
let where: Prisma.EntityViewWhereInput = {
entityId,
isSystem: false,
};
if (options?.tenantId !== undefined) {
const userId = options.userId ?? null;
const scope: Prisma.EntityViewWhereInput[] = [{ tenantId: options.tenantId, userId: null }, { tenantId: null, userId: null }];
if (userId) {
scope.unshift({ tenantId: options.tenantId, userId });
}
where = {
...where,
OR: scope,
};
}
return await db.entityView.findMany({
where,
include: EntityViewModelHelper.includeDetails,
orderBy: {
order: "asc",
},
});
}
function buildEntityViewScopeWhere({
tenantId,
userId,
}: {
tenantId?: string | null;
userId?: string | null;
}): Prisma.EntityViewWhereInput {
if (tenantId === undefined) {
return {};
}
return {
OR: [
{ tenantId, userId },
{ tenantId, userId: null },
{ tenantId: null, userId: null },
],
};
}
export async function getEntityView(
id: string,
options?: {
entityId?: string;
tenantId?: string | null;
userId?: string | null;
}
): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
id,
entityId: options?.entityId,
...buildEntityViewScopeWhere({ tenantId: options?.tenantId, userId: options?.userId }),
},
include: EntityViewModelHelper.includeDetails,
});
}
export async function getEntityViewWithTenantAndUser(id: string): Promise<EntityViewWithTenantAndUser | null> {
return await db.entityView.findUnique({
where: {
id,
},
include: {
...EntityViewModelHelper.includeDetails,
entity: { select: EntityModelHelper.selectSimpleProperties },
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
user: { select: UserModelHelper.selectSimpleUserProperties },
},
});
}
export async function getEntityViewByName({
entityId,
name,
isSystem,
tenantId,
userId,
}: {
entityId: string;
name: string;
isSystem?: boolean;
tenantId?: string | null;
userId?: string | null;
}): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
entityId,
name,
isSystem,
...buildEntityViewScopeWhere({ tenantId, userId }),
},
include: EntityViewModelHelper.includeDetails,
});
}
export async function getEntityViewDefault({
entityId,
isSystem,
tenantId,
userId,
}: {
entityId: string;
isSystem?: boolean;
tenantId?: string | null;
userId?: string | null;
}): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
entityId,
isSystem,
isDefault: true,
...buildEntityViewScopeWhere({ tenantId, userId }),
},
include: EntityViewModelHelper.includeDetails,
});
}
export async function getEntityViewByOrder(entityId: string, order: number): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
entityId,
order,
},
include: EntityViewModelHelper.includeDetails,
});
}
export default async function getMaxEntityViewOrder(entityId: string): Promise<number> {
return (
(
await db.entityView.aggregate({
where: { entityId },
_max: {
order: true,
},
})
)._max?.order ?? 0
);
}
export async function createEntityView(data: {
entityId: string;
tenantId: string | null;
userId: string | null;
createdByUserId: string;
layout: string;
name: string;
title: string;
isDefault: boolean;
isSystem: boolean;
pageSize: number;
groupByPropertyId?: string | null;
gridColumns?: number;
gridColumnsSm?: number;
gridColumnsMd?: number;
gridColumnsLg?: number;
gridColumnsXl?: number;
gridColumns2xl?: number;
gridGap?: string;
order?: number;
}) {
if (!data.order) {
data.order = (await getMaxEntityViewOrder(data.entityId)) + 1;
}
return await db.entityView.create({
data: {
entityId: data.entityId,
tenantId: data.tenantId,
userId: data.userId,
createdByUserId: data.createdByUserId,
layout: data.layout,
order: data.order,
name: data.name,
title: data.title,
isDefault: data.isDefault,
isSystem: data.isSystem,
pageSize: data.pageSize,
groupByPropertyId: data.groupByPropertyId,
gridColumns: data.gridColumns ?? 5,
gridColumnsSm: data.gridColumnsSm ?? 2,
gridColumnsMd: data.gridColumnsMd ?? 3,
gridColumnsLg: data.gridColumnsLg ?? 4,
gridColumnsXl: data.gridColumnsXl ?? 5,
gridColumns2xl: data.gridColumns2xl ?? 6,
gridGap: data.gridGap ?? "sm",
},
});
}
export async function updateEntityViewProperties(id: string, items: { propertyId: string | null; name: string; order: number }[]) {
await db.entityViewProperty.deleteMany({
where: { entityViewId: id },
});
return await Promise.all(
items.map(async (item) => {
return await db.entityViewProperty.create({
data: {
entityViewId: id,
propertyId: item.propertyId,
name: item.name,
order: item.order,
},
});
})
);
}
type EntityViewScope = {
id: string;
entityId: string;
tenantId: string | null;
userId: string | null;
};
async function assertScopedEntityView(scope: EntityViewScope) {
const view = await getEntityView(scope.id, { entityId: scope.entityId, tenantId: scope.tenantId, userId: scope.userId });
if (!view || view.tenantId !== scope.tenantId || view.userId !== scope.userId) {
throw Error("Entity view not found");
}
return view;
}
export async function updateScopedEntityViewProperties(scope: EntityViewScope, items: { propertyId: string | null; name: string; order: number }[]) {
await assertScopedEntityView(scope);
return await updateEntityViewProperties(scope.id, items);
}
export async function updateEntityViewFilters(id: string, items: { name: string; condition: string; value: string; match: string }[]) {
await db.entityViewFilter.deleteMany({
where: { entityViewId: id },
});
return await Promise.all(
items.map(async (item) => {
return await db.entityViewFilter.create({
data: {
entityViewId: id,
name: item.name,
condition: item.condition,
value: item.value,
match: item.match,
},
});
})
);
}
export async function updateScopedEntityViewFilters(scope: EntityViewScope, items: { name: string; condition: string; value: string; match: string }[]) {
await assertScopedEntityView(scope);
return await updateEntityViewFilters(scope.id, items);
}
export async function updateEntityViewSort(id: string, items: { name: string; asc: boolean; order: number }[]) {
await db.entityViewSort.deleteMany({
where: { entityViewId: id },
});
return await Promise.all(
items.map(async (item) => {
return await db.entityViewSort.create({
data: {
entityViewId: id,
name: item.name,
asc: item.asc,
order: item.order,
},
});
})
);
}
export async function updateScopedEntityViewSort(scope: EntityViewScope, items: { name: string; asc: boolean; order: number }[]) {
await assertScopedEntityView(scope);
return await updateEntityViewSort(scope.id, items);
}
export async function updateEntityView(
id: string,
data: {
layout?: string;
isDefault?: boolean;
isSystem?: boolean;
pageSize?: number;
name?: string;
title?: string;
order?: number;
groupByPropertyId?: string | null;
gridColumns?: number;
gridColumnsSm?: number;
gridColumnsMd?: number;
gridColumnsLg?: number;
gridColumnsXl?: number;
gridColumns2xl?: number;
gridGap?: string;
}
) {
return await db.entityView.update({
where: { id },
data,
});
}
type UpdateEntityViewData = Parameters<typeof updateEntityView>[1];
export async function updateScopedEntityView(scope: EntityViewScope, data: UpdateEntityViewData) {
const result = await db.entityView.updateMany({
where: scope,
data,
});
if (result.count !== 1) {
throw Error("Entity view not found");
}
return await assertScopedEntityView(scope);
}
export async function deleteEntityView(id: string) {
return await db.entityView.delete({
where: { id },
});
}
export async function deleteScopedEntityView(scope: EntityViewScope) {
const result = await db.entityView.deleteMany({
where: scope,
});
if (result.count !== 1) {
throw Error("Entity view not found");
}
}
@@ -0,0 +1,202 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db.server", () => ({
db: {
entityWebhook: {
deleteMany: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
updateMany: vi.fn(),
},
entityWebhookLog: {
create: vi.fn(async (args) => args.data),
},
},
}));
vi.mock("~/utils/url.server", () => ({
getBaseURL: vi.fn((request: Request) => new URL(request.url).origin),
}));
// The shared outbound client resolves DNS and rejects hosts that resolve to
// internal addresses. Stub the resolver so public test hosts resolve to a
// public IP, while a chosen host simulates DNS rebinding to a metadata address.
vi.mock("node:dns/promises", () => ({
lookup: vi.fn(async (hostname: string) => {
if (hostname === "rebind.attacker.test") {
return [{ address: "169.254.169.254", family: 4 }];
}
return [{ address: "93.184.216.34", family: 4 }];
}),
}));
import { db } from "~/utils/db.server";
import { callEntityWebhooks, deleteEntityWebhook, getEntityWebhook, updateEntityWebhook } from "./entityWebhooks.db.server";
const entityWebhookMock = vi.mocked(db.entityWebhook, true);
const entityWebhookLogMock = vi.mocked(db.entityWebhookLog, true);
describe("entity webhook delivery", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 204 })));
});
it("delivers allowed absolute webhook URLs", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_absolute", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenCalledWith("https://hooks.example.com/rows", expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal) }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_absolute", logId: "log_1", status: 204 } });
});
it("delivers webhooks at request-relative endpoints resolved against the base URL", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_relative", entityId: "entity_1", action: "created", method: "POST", endpoint: "/webhooks/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenCalledWith("https://tenant.example.com/webhooks/rows", expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal) }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_relative", logId: "log_1", status: 204 } });
});
it("follows safe redirects after validating the redirect target", async () => {
vi.stubGlobal(
"fetch",
vi
.fn()
.mockResolvedValueOnce(new Response(null, { status: 307, headers: { location: "https://hooks.example.com/rows-next" } }))
.mockResolvedValueOnce(new Response(null, { status: 204 }))
);
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_redirect", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenNthCalledWith(1, "https://hooks.example.com/rows", expect.objectContaining({ method: "POST", redirect: "manual" }));
expect(fetch).toHaveBeenNthCalledWith(2, "https://hooks.example.com/rows-next", expect.objectContaining({ method: "POST", redirect: "manual" }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_redirect", logId: "log_1", status: 204 } });
});
it("blocks unsafe redirect targets without following them", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 302, headers: { location: "http://127.0.0.1/webhook" } })));
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_redirect_blocked", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith("https://hooks.example.com/rows", expect.objectContaining({ redirect: "manual" }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_redirect_blocked", logId: "log_1", status: 0 } });
});
it("blocks unsafe webhook URLs and records failed delivery status without fetching", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_private", entityId: "entity_1", action: "created", method: "POST", endpoint: "http://10.0.0.1/webhook" },
{ id: "webhook_internal", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://worker.internal/webhook" },
{ id: "webhook_relative_localhost", entityId: "entity_1", action: "created", method: "POST", endpoint: "/webhooks/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://localhost/api/rows"),
});
expect(fetch).not.toHaveBeenCalled();
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_private", logId: "log_1", status: 0 } });
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_internal", logId: "log_1", status: 0 } });
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_relative_localhost", logId: "log_1", status: 0 } });
});
it("blocks public hostnames that resolve to internal addresses (DNS rebinding) without fetching", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_rebind", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://rebind.attacker.test/webhook" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).not.toHaveBeenCalled();
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_rebind", logId: "log_1", status: 0 } });
});
});
describe("entity webhook admin boundaries", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("reads a webhook only inside the current entity scope", async () => {
const webhook = { id: "webhook_1", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" };
entityWebhookMock.findFirst.mockResolvedValueOnce(webhook);
await expect(getEntityWebhook({ id: "webhook_1", entityId: "entity_1" })).resolves.toEqual(webhook);
expect(entityWebhookMock.findFirst).toHaveBeenCalledWith({ where: { id: "webhook_1", entityId: "entity_1" } });
});
it("updates and deletes only webhooks inside the current entity scope", async () => {
entityWebhookMock.updateMany.mockResolvedValueOnce({ count: 1 });
entityWebhookMock.deleteMany.mockResolvedValueOnce({ count: 1 });
await updateEntityWebhook(
{ id: "webhook_1", entityId: "entity_1" },
{ action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" }
);
await deleteEntityWebhook({ id: "webhook_1", entityId: "entity_1" });
expect(entityWebhookMock.updateMany).toHaveBeenCalledWith({
where: { id: "webhook_1", entityId: "entity_1" },
data: { action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
});
expect(entityWebhookMock.deleteMany).toHaveBeenCalledWith({ where: { id: "webhook_1", entityId: "entity_1" } });
});
it("rejects scoped update and delete misses", async () => {
entityWebhookMock.updateMany.mockResolvedValueOnce({ count: 0 });
entityWebhookMock.deleteMany.mockResolvedValueOnce({ count: 0 });
await expect(
updateEntityWebhook({ id: "webhook_foreign", entityId: "entity_1" }, { action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" })
).rejects.toThrow("Entity webhook not found.");
await expect(deleteEntityWebhook({ id: "webhook_foreign", entityId: "entity_1" })).rejects.toThrow("Entity webhook not found.");
});
});
@@ -0,0 +1,133 @@
import { EntityWebhook } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { getBaseURL } from "~/utils/url.server";
import { fetchOutboundHttpWithRedirects } from "~/utils/outboundHttp.server";
const BLOCKED_WEBHOOK_STATUS = 0;
export type EntityWebhookWithDetails = EntityWebhook & { _count: { logs: number } };
export async function getEntityWebhooks(entityId: string) {
return await db.entityWebhook.findMany({
where: {
entityId,
},
include: {
_count: {
select: {
logs: true,
},
},
},
});
}
export async function getEntityWebhook(input: { id: string; entityId: string }) {
return await db.entityWebhook.findFirst({
where: {
id: input.id,
entityId: input.entityId,
},
});
}
export async function getEntityWebhooksByAction(entityId: string, action: string) {
return await db.entityWebhook.findMany({
where: {
entityId,
action,
},
});
}
export async function createEntityWebhook(data: { entityId: string; action: string; method: string; endpoint: string }) {
return await db.entityWebhook.create({
data,
});
}
export async function updateEntityWebhook(
input: { id: string; entityId: string },
data: {
action: string;
method: string;
endpoint: string;
}
) {
const result = await db.entityWebhook.updateMany({
where: {
id: input.id,
entityId: input.entityId,
},
data,
});
if (result.count !== 1) {
throw new Error("Entity webhook not found.");
}
return result;
}
export async function deleteEntityWebhook(input: { id: string; entityId: string }) {
const result = await db.entityWebhook.deleteMany({
where: {
id: input.id,
entityId: input.entityId,
},
});
if (result.count !== 1) {
throw new Error("Entity webhook not found.");
}
return result;
}
export async function callEntityWebhooks({
logId,
entityId,
action,
body,
request,
}: {
logId: string;
entityId: string;
action: string;
body: string;
request?: Request;
}) {
const webhooks = await getEntityWebhooksByAction(entityId, action);
return await Promise.all(
webhooks.map(async (webhook) => {
if (webhook.endpoint) {
const status = await fetchLegacyWebhookStatus(webhook.endpoint, request, {
method: webhook.method,
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
});
return db.entityWebhookLog.create({
data: {
webhookId: webhook.id,
logId,
status,
},
});
}
})
);
}
function resolveWebhookEndpoint(endpoint: string, request?: Request): string {
return endpoint.startsWith("/") && request ? getBaseURL(request) + endpoint : endpoint;
}
// Delivery goes through the shared SSRF-safe outbound client, which validates
// the scheme, blocks literal private/loopback/link-local/metadata hosts, AND
// resolves DNS to reject public hostnames that resolve to internal addresses
// (DNS rebinding) — the gap in the previous forked, hostname-string-only guard.
// Redirect hops are re-validated and resolved the same way. Any rejection or
// transport error is recorded as a blocked-delivery status.
async function fetchLegacyWebhookStatus(endpoint: string, request: Request | undefined, init: RequestInit): Promise<number> {
try {
const response = await fetchOutboundHttpWithRedirects(resolveWebhookEndpoint(endpoint, request), init);
return response.status;
} catch {
return BLOCKED_WEBHOOK_STATUS;
}
}
@@ -0,0 +1,273 @@
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { Colors } from "~/application/enums/shared/Colors";
import { defaultProperties } from "~/utils/helpers/PropertyHelper";
import { db } from "../../db.server";
export async function getProperty(id: string) {
return await db.property.findUnique({
where: {
id,
},
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: true,
},
});
}
export async function getEntityPropertyByName(entityId: string, name: string) {
return await db.property.findFirst({
where: {
entityId,
name,
},
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
},
});
}
export async function createProperty(data: {
entityId: string;
name: string;
title: string;
type: PropertyType;
subtype: string | null;
order: number;
isDefault: boolean;
isRequired: boolean;
isHidden: boolean;
isDisplay: boolean;
isReadOnly: boolean;
canUpdate: boolean;
showInCreate: boolean;
formulaId: string | null;
tenantId: string | null;
}) {
if (data.name.includes(" ")) {
throw Error("Property names cannot contain spaces: " + data.name);
}
if (data.name.includes("-")) {
throw Error("Property names cannot contain '-': " + data.name);
}
return await db.property.create({
data,
});
}
export type CreatePropertyDto = {
name: string;
title: string;
type: PropertyType;
subtype: string | null;
isRequired?: boolean;
isDefault?: boolean;
isHidden?: boolean;
isDisplay?: boolean;
isReadOnly?: boolean;
canUpdate?: boolean;
showInCreate?: boolean;
formulaId?: string | null;
tenantId?: string | null;
options?: { order: number; value: string; name?: string; color?: Colors }[];
attributes?: {
name: string;
value: string;
}[];
};
export async function createProperties(entityId: string, fields: CreatePropertyDto[]) {
return await Promise.all(
fields.map(async (field, idx) => {
const property = await createProperty({
entityId,
order: defaultProperties.length + idx + 1,
name: field.name,
title: field.title,
type: field.type,
subtype: field.subtype ?? null,
isRequired: field.isRequired ?? true,
isDefault: field.isDefault ?? false,
isHidden: field.isHidden ?? false,
isDisplay: field.isDisplay ?? false,
isReadOnly: field.isReadOnly ?? false,
canUpdate: field.canUpdate ?? true,
showInCreate: field.showInCreate ?? true,
formulaId: field.formulaId ?? null,
tenantId: field.tenantId ?? null,
});
if (field.options) {
await updatePropertyOptions(
property.id,
field.options.map((option) => {
return {
order: option.order,
value: option.value,
name: option.name ?? null,
color: option.color,
};
})
);
}
if (field.attributes) {
await updatePropertyAttributes(property.id, field.attributes);
}
return property;
})
);
}
export async function updateProperty(
id: string,
data: {
name?: string;
title?: string;
type?: PropertyType;
subtype?: string | null;
order?: number;
isDefault?: boolean;
isRequired?: boolean;
isHidden?: boolean;
isDisplay?: boolean;
isReadOnly?: boolean;
canUpdate?: boolean;
showInCreate?: boolean;
formulaId?: string | null;
}
) {
const property = await db.property.update({
where: { id },
data,
});
return property;
}
type PropertyScope = {
id: string;
tenantId: string | null;
entityId: string;
};
type UpdatePropertyData = Parameters<typeof updateProperty>[1];
async function assertScopedProperty(scope: PropertyScope) {
const property = await getProperty(scope.id);
if (!property || property.tenantId !== scope.tenantId || property.entityId !== scope.entityId) {
throw Error("Property not found");
}
return property;
}
export async function getScopedProperty(scope: PropertyScope) {
const property = await getProperty(scope.id);
if (!property || property.tenantId !== scope.tenantId || property.entityId !== scope.entityId) {
return null;
}
return property;
}
export async function updateScopedProperty(scope: PropertyScope, data: UpdatePropertyData) {
const result = await db.property.updateMany({
where: scope,
data,
});
if (result.count !== 1) {
throw Error("Property not found");
}
return await assertScopedProperty(scope);
}
export async function updatePropertyOrder(id: string, order: number) {
return await db.property.update({
where: { id },
data: {
order,
},
});
}
export async function updateScopedPropertyOrder(scope: PropertyScope, order: number) {
const result = await db.property.updateMany({
where: scope,
data: {
order,
},
});
if (result.count !== 1) {
throw Error("Property not found");
}
}
export async function updatePropertyOptions(id: string, options: { order: number; value: string; name?: string | null; color?: Colors }[]) {
await db.propertyOption.deleteMany({
where: { propertyId: id },
});
await Promise.all(
options.map(async (option) => {
return await db.propertyOption.create({
data: {
propertyId: id,
order: option.order,
value: option.value,
name: option.name ?? null,
color: option.color,
},
});
})
);
}
export async function updateScopedPropertyOptions(scope: PropertyScope, options: { order: number; value: string; name?: string | null; color?: Colors }[]) {
await assertScopedProperty(scope);
await updatePropertyOptions(scope.id, options);
}
export async function updatePropertyAttributes(id: string, attributes: { name: string; value: string }[]) {
await db.propertyAttribute.deleteMany({
where: { propertyId: id },
});
await Promise.all(
attributes
.filter((f) => f.value !== undefined)
.map(async (attribute) => {
return await db.propertyAttribute.create({
data: {
propertyId: id,
name: attribute.name,
value: attribute.value,
},
});
})
);
}
export async function updateScopedPropertyAttributes(scope: PropertyScope, attributes: { name: string; value: string }[]) {
await assertScopedProperty(scope);
await updatePropertyAttributes(scope.id, attributes);
}
export async function deleteProperty(id: string) {
return await db.property.delete({
where: { id },
});
}
export async function deleteScopedProperty(scope: PropertyScope) {
const result = await db.property.deleteMany({
where: scope,
});
if (result.count !== 1) {
throw Error("Property not found");
}
}
@@ -0,0 +1,29 @@
import { RowCommentReaction } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
export type RowCommentReactionWithDetails = RowCommentReaction & {
createdByUser: UserSimple;
};
export async function setRowCommentReaction(data: { createdByUserId: string; rowCommentId: string; reaction: string }) {
const existing = await db.rowCommentReaction.findFirst({
where: {
createdByUserId: data.createdByUserId,
rowCommentId: data.rowCommentId,
reaction: data.reaction,
},
});
if (!existing) {
await db.rowCommentReaction.create({
data,
});
return true;
} else {
await db.rowCommentReaction.deleteMany({
where: {
...data,
},
});
return false;
}
}
@@ -0,0 +1,91 @@
import { RowComment } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
import { RowCommentReactionWithDetails } from "./rowCommentReaction.db.server";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
export type RowCommentWithDetails = RowComment & {
createdByUser: UserSimple;
reactions: RowCommentReactionWithDetails[];
// replies: (RowComment & { createdByUser: User })[];
};
export async function getRowComments(rowId: string): Promise<RowCommentWithDetails[]> {
return await db.rowComment.findMany({
where: {
rowId,
// parentCommentId: null,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
reactions: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
},
},
// replies: {
// include: {
// ...UserModelHelper.includeSimpleCreatedByUser,
// },
// },
},
});
}
export async function getRowComment(id: string): Promise<RowCommentWithDetails | null> {
return await db.rowComment.findUnique({
where: {
id,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
reactions: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
},
},
// replies: {
// include: {
// ...UserModelHelper.includeSimpleCreatedByUser,
// },
// },
},
});
}
export async function getRowCommentInRow({ id, rowId }: { id: string; rowId: string }): Promise<RowCommentWithDetails | null> {
return await db.rowComment.findFirst({
where: {
id,
rowId,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
reactions: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
},
},
},
});
}
export async function createRowComment(data: { createdByUserId: string; rowId: string; value: string }) {
return await db.rowComment.create({
data,
});
}
export async function updateRowCommentInRow({ id, rowId }: { id: string; rowId: string }, data: { value?: string; isDeleted?: boolean }) {
const updated = await db.rowComment.updateMany({
where: {
id,
rowId,
},
data,
});
if (updated.count !== 1) {
throw new Error("Row comment not found");
}
return updated;
}
@@ -0,0 +1,91 @@
import { db } from "~/utils/db.server";
import { createScopedLogger } from "~/utils/logger.server";
const rowRelationshipsLogger = createScopedLogger("db.entities.rowRelationships");
type RowRelationshipTenantScope = {
tenantId: string | null;
};
function scopedRowRelationshipWhere(scope: RowRelationshipTenantScope) {
return {
parent: { deletedAt: null, tenantId: scope.tenantId },
child: { deletedAt: null, tenantId: scope.tenantId },
};
}
export async function getRowRelationship(id: string, scope: RowRelationshipTenantScope) {
return await db.rowRelationship.findFirst({
where: { id, ...scopedRowRelationshipWhere(scope) },
include: {
relationship: true,
},
});
}
export async function getRowsRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
return await db.rowRelationship.findFirst({
where: { parentId, childId, ...scopedRowRelationshipWhere({ tenantId }) },
});
}
export async function createRowRelationship({
parentId,
childId,
relationshipId,
metadata,
tenantId,
}: {
parentId: string;
childId: string;
relationshipId: string;
metadata: string | null;
tenantId: string | null;
}) {
const [parent, child] = await Promise.all([
db.row.findFirst({ where: { id: parentId, deletedAt: null, tenantId }, select: { id: true } }),
db.row.findFirst({ where: { id: childId, deletedAt: null, tenantId }, select: { id: true } }),
]);
if (!parent || !child) {
return undefined;
}
return await db.rowRelationship
.create({
data: {
parentId,
childId,
relationshipId,
metadata,
},
})
.catch((e) => {
rowRelationshipsLogger.error({ err: e }, "Error creating row relationship");
});
}
export async function deleteRowRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
return await db.rowRelationship.deleteMany({
where: {
parentId,
childId,
...scopedRowRelationshipWhere({ tenantId }),
},
});
}
export async function deleteRowRelationshipById(id: string, scope: RowRelationshipTenantScope) {
const item = await db.rowRelationship.findFirst({
where: { id, ...scopedRowRelationshipWhere(scope) },
select: { id: true },
});
if (!item) {
return null;
}
return await db.rowRelationship.delete({
where: {
id: item.id,
},
});
}
@@ -0,0 +1,69 @@
import { EntityTag, RowTag } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
export type RowTagWithDetails = RowTag & {
tag: EntityTag;
};
export async function getRowTags(rowId: string): Promise<RowTagWithDetails[]> {
return await db.rowTag.findMany({
where: {
rowId,
},
include: {
tag: true,
},
});
}
export async function getRowTagById(id: string): Promise<RowTagWithDetails | null> {
return await db.rowTag.findUnique({
where: {
id,
},
include: {
tag: true,
},
});
}
export async function getRowTag(rowId: string, value: string): Promise<RowTagWithDetails | null> {
return await db.rowTag.findFirst({
where: {
rowId,
tag: {
value,
},
},
include: {
tag: true,
},
});
}
export async function getRowTagByIds(rowId: string, tagId: string): Promise<RowTagWithDetails | null> {
return await db.rowTag.findFirst({
where: {
rowId,
tagId,
},
include: {
tag: true,
},
});
}
export async function createRowTag(data: { rowId: string; tagId: string }) {
return await db.rowTag.create({
data,
});
}
export async function deleteRowTags(rowId: string, tagId: string) {
return await db.rowTag.deleteMany({
where: {
rowId,
tagId,
},
});
}
@@ -0,0 +1,46 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
type RowTaskDbMocks = {
findMany: ReturnType<typeof vi.fn>;
};
function getMocks(): RowTaskDbMocks {
const store = globalThis as typeof globalThis & { __rowTaskDbMocks__?: RowTaskDbMocks };
store.__rowTaskDbMocks__ ??= {
findMany: vi.fn(),
};
return store.__rowTaskDbMocks__;
}
vi.mock("~/utils/db.server", () => ({
db: {
rowTask: {
findMany: getMocks().findMany,
},
},
}));
import { getAllRowTasks } from "./rowTasks.db.server";
const mocks = getMocks();
describe("row task db helpers", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.findMany.mockResolvedValue([]);
});
it("filters task lists through row tenant scope when provided", async () => {
await getAllRowTasks({ tenantId: "tenant_1", assignedOrCreatedUserId: "user_1", completed: false });
expect(mocks.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
completed: false,
row: { tenantId: "tenant_1" },
OR: [{ createdByUserId: "user_1" }, { assignedToUserId: "user_1" }],
}),
})
);
});
});
@@ -0,0 +1,188 @@
import { Prisma, RowTask } from "@toolctrl/db/prisma-browser";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
import { RowWithValues } from "./rows.db.server";
export type RowTaskWithDetails = RowTask & {
createdByUser: UserSimple;
assignedToUser: UserSimple | null;
row: RowWithValues;
};
export async function getRowTasks(rowId: string): Promise<RowTaskWithDetails[]> {
return await db.rowTask.findMany({
where: {
rowId,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
orderBy: [
{
completed: "asc",
},
{
createdAt: "asc",
},
],
});
}
export async function getRowTask(id: string): Promise<RowTaskWithDetails | null> {
return await db.rowTask.findUnique({
where: {
id,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
});
}
export async function getRowTaskInRow({ id, rowId }: { id: string; rowId: string }): Promise<RowTaskWithDetails | null> {
return await db.rowTask.findFirst({
where: {
id,
rowId,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
});
}
export async function createRowTask(data: {
createdByUserId: string;
rowId: string;
title: string;
description?: string;
completed?: boolean;
completedAt?: Date | null;
completedByUserId?: string | null;
assignedToUserId?: string | null;
deadline?: Date | null;
}) {
return await db.rowTask.create({
data: {
createdByUserId: data.createdByUserId,
rowId: data.rowId,
title: data.title,
description: data.description ?? "",
completed: data.completed ?? false,
completedAt: data.completedAt ?? null,
completedByUserId: data.completedByUserId ?? null,
assignedToUserId: data.assignedToUserId ?? null,
deadline: data.deadline ?? null,
},
});
}
export async function updateRowTaskInRow(
scope: { id: string; rowId: string },
data: {
createdByUserId?: string;
rowId?: string;
title?: string;
description?: string;
completed?: boolean;
completedAt?: Date | null;
completedByUserId?: string | null;
assignedToUserId?: string | null;
deadline?: Date | null;
}
) {
const updated = await db.rowTask.updateMany({
where: {
id: scope.id,
rowId: scope.rowId,
},
data,
});
if (updated.count !== 1) {
throw new Error("Row task not found");
}
return updated;
}
export async function deleteRowTaskInRow(scope: { id: string; rowId: string }) {
const deleted = await db.rowTask.deleteMany({
where: {
id: scope.id,
rowId: scope.rowId,
},
});
if (deleted.count !== 1) {
throw new Error("Row task not found");
}
return deleted;
}
export async function getAllRowTasks({
completed,
assignedOrCreatedUserId,
tenantId,
}: {
completed?: boolean;
assignedOrCreatedUserId?: string;
tenantId?: string | null;
}): Promise<RowTaskWithDetails[]> {
const userWhere: Prisma.RowTaskWhereInput = {};
if (assignedOrCreatedUserId) {
userWhere.OR = [
{
createdByUserId: assignedOrCreatedUserId,
},
{
assignedToUserId: assignedOrCreatedUserId,
},
];
}
return await db.rowTask.findMany({
where: {
completed,
...(tenantId !== undefined ? { row: { tenantId } } : {}),
...userWhere,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
orderBy: [
{
createdAt: "desc",
},
],
});
}
@@ -0,0 +1,26 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const rootPath = (...segments: string[]) => resolve(process.cwd(), ...segments);
const readProjectFile = (path: string) => readFileSync(rootPath(path), "utf8");
describe("row tenant-scope guard", () => {
it("requires explicit tenant and entity scope for row reloads", () => {
const source = readProjectFile("apps/web/app/utils/db/entities/rows.db.server.ts");
expect(source).toContain("getRowById(id: string, scope: { entityId?: string; tenantId: string | null })");
expect(source).not.toContain("getRowById(id: string, scope?:");
expect(source).not.toContain("RowModelHelper.includeRowDetailsNested");
});
it("keeps legacy row relationship helpers tenant-scoped", () => {
const source = readProjectFile("apps/web/app/utils/db/entities/rowRelationships.db.server.ts");
expect(source).toContain("type RowRelationshipTenantScope");
expect(source).toContain("parent: { deletedAt: null, tenantId: scope.tenantId }");
expect(source).toContain("child: { deletedAt: null, tenantId: scope.tenantId }");
expect(source).not.toContain("findUnique({");
expect(source).not.toContain("where: { id },");
});
});
@@ -0,0 +1,505 @@
import {
hardDeleteRowById,
updateRowWithValues,
type LegacyRowWithDetails,
type RowMutationData,
type RowMutationValueInput,
type RowMutationRelationshipChildInput,
type RowMutationRelationshipParentInput,
} from "@toolctrl/db/rows.server";
import {
Prisma,
Row,
Tenant,
RowValue,
ApiKey,
RowMedia,
RowRelationship,
SampleCustomEntity,
RowPermission,
RowValueMultiple,
RowValueRange,
} from "@toolctrl/db/prisma-browser";
import { RowFiltersDto } from "~/application/dtos/data/RowFiltersDto";
import { MediaDto } from "~/application/dtos/entities/MediaDto";
import { deleteRowMediaFromStorageProvider, storeRowMediaInStorageProvider } from "~/utils/helpers/.server/MediaService";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import TenantHelper from "~/utils/helpers/TenantHelper";
import { db } from "../../db.server";
import { UserSimple } from "../users.db.server";
import { EntityWithDetails, getEntityById } from "./entities.db.server";
import { RowTagWithDetails } from "./rowTags.db.server";
import { getRowPermissionsCondition } from "~/utils/helpers/.server/PermissionsService";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
import RowModelHelper from "~/utils/helpers/models/RowModelHelper";
export type RowValueWithDetails = RowValue & {
media: RowMedia[];
multiple: RowValueMultiple[];
range: RowValueRange | null;
};
export type RowWithValues = Row & {
createdByUser: UserSimple | null;
createdByApiKey: ApiKey | null;
values: RowValueWithDetails[];
};
export type RowWithCreatedBy = Row & {
createdByUser: UserSimple | null;
createdByApiKey: ApiKey | null;
};
export type RowWithDetails = Row & {
createdByUser: UserSimple | null;
createdByApiKey: ApiKey | null;
tenant: Tenant | null;
values: RowValueWithDetails[];
tags: RowTagWithDetails[];
parentRows:
| (RowRelationship & { parent: RowWithValues })[]
| (RowRelationship & {
parent: RowWithValues & {
parentRows: (RowRelationship & {
parent: { values: RowValueWithDetails[] };
})[];
childRows: (RowRelationship & {
child: { values: RowValueWithDetails[] };
})[];
};
})[];
childRows: (RowRelationship & {
child: RowWithValues & {
parentRows: (RowRelationship & {
parent: { values: RowValueWithDetails[] };
})[];
childRows: (RowRelationship & {
child: { values: RowValueWithDetails[] };
})[];
};
})[];
permissions: RowPermission[];
sampleCustomEntity: SampleCustomEntity | null;
};
export type RowMutationScope = { id: string; entityId: string; tenantId: string | null };
export async function getAllRows(entityId: string): Promise<RowWithDetails[]> {
return await db.row.findMany({
where: {
deletedAt: null,
entityId,
},
include: RowModelHelper.includeRowDetails,
});
}
export async function getRows({
entityId,
entityName,
tenantId,
userId,
take,
skip,
orderBy,
filters,
ids,
rowWhere,
includePublic,
}: {
entityId?: string;
entityName?: string;
tenantId?: string | null;
userId?: string;
take?: number;
skip?: number;
orderBy?: Prisma.RowOrderByWithRelationInput[];
filters?: RowFiltersDto;
ids?: string[];
rowWhere?: Prisma.RowWhereInput;
includePublic?: boolean;
}): Promise<RowWithDetails[]> {
const whereFilters = RowFiltersHelper.getRowFiltersCondition(filters);
let filterEntity: Prisma.RowWhereInput | undefined = undefined;
if (entityId) {
filterEntity = { entityId };
} else if (entityName) {
filterEntity = { entity: { name: entityName } };
}
const accessFilters = await getAccessFilters({ tenantId });
const where: Prisma.RowWhereInput = {
AND: [
{ deletedAt: null },
{ ...rowWhere },
whereFilters,
{ id: { in: ids } },
{ ...filterEntity },
{ ...accessFilters },
// ...getSearchCondition(filters?.query),
],
};
return await db.row.findMany({
take,
skip,
where,
include: RowModelHelper.createScopedIncludeRowDetails(tenantId ?? null),
orderBy,
});
}
export async function getRowsBetween(name: string, tenantId: string | null, startDate: Date, endDate: Date): Promise<RowWithDetails[]> {
return await db.row.findMany({
where: {
AND: [
{ deletedAt: null },
{
entity: { name },
...TenantHelper.tenantCondition({ tenantId }),
},
{
createdAt: {
lte: endDate,
gte: startDate,
},
},
],
},
include: RowModelHelper.createScopedIncludeRowDetails(tenantId),
orderBy: { createdAt: "asc" },
});
}
export async function getRowsInIds(ids: string[], tenantId?: string | null): Promise<RowWithDetails[]> {
return await db.row.findMany({
where: {
deletedAt: null,
id: {
in: ids,
},
tenantId,
},
include: tenantId === undefined ? RowModelHelper.includeRowDetails : RowModelHelper.createScopedIncludeRowDetails(tenantId),
});
}
export async function countRows({
entityId,
entityName,
tenantId,
userId,
filters,
rowWhere,
includePublic,
}: {
entityId?: string;
entityName?: string;
tenantId?: string | null;
userId?: string | undefined;
filters?: RowFiltersDto;
rowWhere?: Prisma.RowWhereInput;
includePublic?: boolean;
}): Promise<number> {
const whereFilters = RowFiltersHelper.getRowFiltersCondition(filters);
let filterEntity: { entityId: string } | { entity: { name: string } } | undefined = undefined;
if (entityId) {
filterEntity = { entityId };
} else if (entityName) {
filterEntity = { entity: { name: entityName } };
}
const accessFilters = await getAccessFilters({ tenantId });
const where: Prisma.RowWhereInput = {
AND: [
{ deletedAt: null },
{ ...rowWhere },
whereFilters,
// { id: { in: ids } },
{ ...filterEntity },
{ ...accessFilters },
// ...getSearchCondition(filters?.query),
],
};
return await db.row.count({
where,
});
}
export async function getRow({ entityId, id, tenantId }: { entityId: string; id: string; tenantId?: string | null }): Promise<RowWithDetails | null> {
const accessFilters = await getAccessFilters({ tenantId });
return await db.row.findFirst({
where: {
deletedAt: null,
id,
entityId,
...accessFilters,
},
include: {
...RowModelHelper.createScopedIncludeRowDetails(tenantId ?? null),
},
});
}
export async function getRowById(id: string, scope: { entityId?: string; tenantId: string | null }): Promise<RowWithDetails | null> {
return await db.row.findFirst({
where: {
deletedAt: null,
id,
...(scope.entityId ? { entityId: scope.entityId } : {}),
tenantId: scope.tenantId,
},
include: {
...RowModelHelper.createScopedIncludeRowDetails(scope.tenantId),
},
});
}
export async function getMaxRowFolio({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
let where: any = { tenantId, entityId };
return await db.row.aggregate({
where,
_max: {
folio: true,
},
});
}
export async function getNextRowFolio({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
const maxFolio = await getMaxRowFolio({ tenantId, entityId });
let next = 1;
if (maxFolio && maxFolio._max.folio !== null) {
next = maxFolio._max.folio + 1;
}
return next;
}
export async function getMaxRowOrder({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
let where: any = { tenantId, entityId };
return await db.row.aggregate({
where,
_max: {
order: true,
},
});
}
export async function getNextRowOrder({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
const maxOrder = await getMaxRowOrder({ tenantId, entityId });
let next = 1;
if (maxOrder && maxOrder._max.order !== null) {
next = maxOrder._max.order + 1;
}
return next;
}
export async function createRow({
entity,
data,
nextFolio,
nextOrder,
}: {
entity: EntityWithDetails;
data: {
tenantId: string | null;
createdByUserId?: string | null;
createdByApiKeyId?: string | null;
properties: any;
dynamicProperties?: {
propertyId: string;
id?: string | null;
textValue?: string | null;
numberValue?: number | string | null;
dateValue?: Date | string | null;
booleanValue?: boolean | null;
media?: MediaDto[];
multiple?: RowValueMultipleDto[];
range?: RowValueRangeDto;
}[];
parentRows?: { relationshipId: string; parentId: string }[];
childRows?: { relationshipId: string; childId: string }[];
rowCreateInput?: Partial<Prisma.RowCreateInput>;
};
nextFolio?: number | undefined;
nextOrder?: number | undefined;
}) {
let folio = nextFolio ?? 1;
if (!nextFolio) {
const maxFolio = await getMaxRowFolio({ tenantId: data.tenantId, entityId: entity.id });
if (maxFolio && maxFolio._max.folio !== null) {
folio = maxFolio._max.folio + 1;
}
}
let order = nextOrder ?? 1;
if (!nextOrder) {
const maxOrder = await getMaxRowOrder({ tenantId: data.tenantId, entityId: entity.id });
if (maxOrder && maxOrder._max.order !== null) {
order = maxOrder._max.order + 1;
}
}
const createInput: Prisma.XOR<Prisma.RowCreateInput, Prisma.RowUncheckedCreateInput> = {
folio,
order,
entityId: entity.id,
tenantId: data.tenantId,
createdByUserId: data.createdByUserId ?? null,
createdByApiKeyId: data.createdByApiKeyId ?? null,
...data.properties,
values: {
create: data.dynamicProperties
// .filter((f) => !f.id)
?.map((value) => {
return {
propertyId: value.propertyId,
textValue: value.textValue,
numberValue: value.numberValue,
dateValue: value.dateValue,
booleanValue: value.booleanValue,
media: {
create: value.media?.map((m) => {
return {
name: m.name,
title: m.title,
type: m.type,
file: m.file,
publicUrl: m.publicUrl,
};
}),
},
multiple: {
create: value.multiple?.map((m) => {
return {
order: m.order,
value: m.value,
};
}),
},
range: {
create: {
numberMin: value.range?.numberMin,
numberMax: value.range?.numberMax,
dateMin: value.range?.dateMin,
dateMax: value.range?.dateMax,
},
},
};
}),
},
parentRows: {
create: data.parentRows?.map(({ relationshipId, parentId }) => {
return {
relationshipId,
parentId,
};
}),
},
childRows: {
create: data.childRows?.map(({ relationshipId, childId }) => {
return {
relationshipId,
childId,
};
}),
},
...data.rowCreateInput,
};
const row = await db.row.create({
data: createInput,
});
return row;
}
export async function updateRow(
scope: RowMutationScope,
data: {
properties: any;
dynamicProperties: {
propertyId: string;
id?: string | null;
textValue?: string | null;
numberValue?: number | string | null;
dateValue?: Date | string | null;
booleanValue?: boolean | null;
media?: MediaDto[];
multiple?: RowValueMultipleDto[];
range?: RowValueRangeDto | undefined;
}[];
parentRows?: { relationshipId: string; parentId: string }[];
childRows?: { relationshipId: string; childId: string }[];
rowUpdateInput?: Prisma.RowUpdateInput;
}
) {
const row = await updateRowWithValues(scope, {
properties: data.properties,
dynamicProperties: data.dynamicProperties as RowMutationValueInput[],
parentRows: data.parentRows as RowMutationRelationshipParentInput[] | undefined,
childRows: data.childRows as RowMutationRelationshipChildInput[] | undefined,
rowUpdateInput: data.rowUpdateInput,
} satisfies Omit<RowMutationData, "tenantId" | "createdByUserId" | "createdByApiKeyId" | "rowCreateInput">) as LegacyRowWithDetails as RowWithDetails;
const entity = await getEntityById({ tenantId: row.tenantId, id: row.entityId });
if (entity) {
await storeRowMediaInStorageProvider(entity, row);
}
return row;
}
export async function deleteRow(scope: RowMutationScope) {
const row = await getRowById(scope.id, { entityId: scope.entityId, tenantId: scope.tenantId });
await deleteRowMediaFromStorageProvider(row);
return await hardDeleteRowById(scope);
}
export async function deleteRows({ entityId, tenantId }: { entityId: string; tenantId: string | null }) {
return await db.row.deleteMany({
where: { entityId, tenantId },
});
}
export async function deleteRowsInIds({ ids, entityId, tenantId }: { ids: string[]; entityId: string; tenantId: string | null }) {
return await db.row.deleteMany({
where: { id: { in: ids }, entityId, tenantId },
});
}
export async function updateRowMedia(
scope: { id: string; rowId: string; entityId: string; tenantId: string | null },
data: {
file?: string;
publicUrl?: string | null;
storageBucket?: string | null;
storageProvider?: string | null;
}
) {
const result = await db.rowMedia.updateMany({
where: {
id: scope.id,
rowValue: {
rowId: scope.rowId,
row: { entityId: scope.entityId, tenantId: scope.tenantId, deletedAt: null },
},
},
data,
});
if (result.count !== 1) {
throw new Error(`Row media ${scope.id} not found`);
}
}
async function getAccessFilters({ tenantId, userId }: { tenantId?: string | null; userId?: string }) {
let tenantFilters: Prisma.RowWhereInput | undefined = undefined;
let userPermissionFilters: Prisma.RowWhereInput | undefined = undefined;
if (tenantId !== undefined) {
tenantFilters = TenantHelper.tenantCondition({ tenantId });
}
if (userId) {
userPermissionFilters = await getRowPermissionsCondition({ tenantId, userId });
}
const filters: Prisma.RowWhereInput = {
AND: [{ ...tenantFilters }, { ...userPermissionFilters }],
};
return filters;
}