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,11 @@
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
import EntitiesSingleton from "../EntitiesSingleton";
export async function loadEntities() {
const instace = EntitiesSingleton.getInstance();
if (!instace.isSet()) {
const entities = await getAllEntities({ tenantId: null });
instace.setEntities(entities);
}
return instace.getEntities();
}
@@ -0,0 +1,53 @@
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
export default class EntitiesSingleton {
private static instance: EntitiesSingleton;
private entities: EntityWithDetails[] | undefined;
private constructor(entities?: EntityWithDetails[]) {
this.entities = entities;
}
public static getInstance(entities?: EntityWithDetails[]): EntitiesSingleton {
if (!EntitiesSingleton.instance) {
EntitiesSingleton.instance = new EntitiesSingleton(entities);
}
return EntitiesSingleton.instance;
}
public isSet() {
return this.entities !== undefined;
}
public getEntities(): EntityWithDetails[] {
if (!this.entities) {
throw new Error("Entities not set: Call await EntitiesSingleton.load() before using RowRepository or EntityRepository");
}
return this.entities;
}
public setEntities(entities: EntityWithDetails[]): void {
const instance = EntitiesSingleton.getInstance();
instance.entities = entities;
}
public static getEntity(data: { name: string } | { id: string }): EntityWithDetails {
const entities = EntitiesSingleton.getInstance().getEntities();
if ("name" in data) {
const entity = entities.find((f) => f.name === data.name);
if (!entity) {
throw new Error("Entity not found: " + data.name);
}
return entity;
} else {
const entity = entities.find((f) => f.id === data.id);
if (!entity) {
throw new Error("Entity not found: " + data.id);
}
return entity;
}
}
public static getEntityByIdNameOrSlug(idNameOrSlug: string) {
const entity = EntitiesSingleton.getInstance()
.getEntities()
.find((f) => f.id === idNameOrSlug || f.name === idNameOrSlug || f.slug === idNameOrSlug);
if (!entity) {
throw new Error(`Entity not found`);
}
return entity;
}
}
@@ -0,0 +1,60 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("~/utils/api/.server/RowsApi", () => ({
RowsApi: {
getAll: vi.fn(),
get: vi.fn(),
create: vi.fn(),
},
}));
vi.mock("~/utils/helpers/RowHelper", () => ({
default: {
getRowPropertiesFromForm: vi.fn(() => ({})),
getTextDescription: vi.fn(() => ""),
},
}));
vi.mock("~/utils/api/.server/RowRelationshipsApi", () => ({
RowRelationshipsApi: {
createRelationship: vi.fn(),
deleteRelationship: vi.fn(),
},
}));
vi.mock("~/utils/helpers/.server/RowValueService", () => ({
default: {
update: vi.fn(),
},
}));
import EntityRepository from "./EntityRepository.server";
import EntitiesSingleton from "./EntitiesSingleton";
import { RowsApi } from "~/utils/api/.server/RowsApi";
const rowsApi = vi.mocked(RowsApi);
const session = { tenantId: "tenant-1", userId: "user-1" };
const entity = { id: "entity-1", name: "contacts", slug: "contacts", properties: [], parentEntities: [], childEntities: [] };
const row = { id: "row-1", entityId: "entity-1", tenantId: "tenant-1", values: [], parentRows: [], childRows: [] };
describe("EntityRepository tenant session propagation", () => {
it("keeps the session on repositories returned from list, read, and create calls", async () => {
EntitiesSingleton.getInstance().setEntities([entity as any]);
rowsApi.getAll.mockResolvedValue({ items: [row as any] } as any);
rowsApi.get.mockResolvedValue({ item: row as any } as any);
rowsApi.create.mockResolvedValue(row as any);
const repository = new EntityRepository({ session });
const rows = await repository.getRows("contacts");
const fetched = await repository.getRow("contacts", "row-1");
const created = await repository.createRow("contacts", []);
expect(rows[0].session).toEqual(session);
expect(fetched.session).toEqual(session);
expect(created.session).toEqual(session);
expect(rowsApi.getAll).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant-1", userId: "user-1" }));
expect(rowsApi.get).toHaveBeenCalledWith("row-1", expect.objectContaining({ tenantId: "tenant-1", userId: "user-1" }));
expect(rowsApi.create).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant-1", userId: "user-1" }));
});
});
@@ -0,0 +1,62 @@
import { RowsApi } from "~/utils/api/.server/RowsApi";
import RowHelper, { RowValueCreateDto } from "~/utils/helpers/RowHelper";
import EntitiesSingleton from "./EntitiesSingleton";
import RowRepository from "./RowRepository.server";
export default class EntityRepository {
session: { tenantId: string | null; userId?: string };
constructor(options: { session: { tenantId: string | null; userId?: string } }) {
this.session = options?.session;
}
async getRows(entityName: string) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
const entity = allEntities.find((entity) => entity.name === entityName);
if (!entity) {
throw new Error("Entity not found: " + entityName);
}
const { items } = await RowsApi.getAll({
entity,
tenantId: this.session.tenantId,
userId: this.session?.userId,
});
return items.map((row) => new RowRepository(row, { session: this.session }));
}
async getRow(entityName: string, rowId: string) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
const entity = allEntities.find((entity) => entity.name === entityName);
if (!entity) {
throw new Error("Entity not found: " + entityName);
}
const existing = await RowsApi.get(rowId, {
entity,
tenantId: this.session.tenantId,
userId: this.session?.userId,
});
return new RowRepository(existing.item, { session: this.session });
}
async createRow(entityName: string, values: RowValueCreateDto[]) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
const entity = allEntities.find((entity) => entity.name === entityName);
if (!entity) {
throw new Error("Entity not found: " + entityName);
}
const row = await RowsApi.create({
entity,
tenantId: this.session.tenantId,
userId: this.session?.userId,
rowValues: RowHelper.getRowPropertiesFromForm({
entity,
values,
}),
});
return new RowRepository(row, { session: this.session });
}
async deleteRow(entityName: string, rowId: string, options = { checkPermissions: true }) {
return RowsApi.del(rowId, {
entity: { name: entityName },
tenantId: this.session.tenantId,
userId: this.session?.userId,
checkPermissions: options.checkPermissions,
});
}
}
@@ -0,0 +1,11 @@
import { Row } from "@toolctrl/db/prisma-browser";
import { RowValueWithDetails, RowWithDetails } from "~/utils/db/entities/rows.db.server";
export type RowDto = (
| (Row & {
values: RowValueWithDetails[];
})
| RowWithDetails
) & {
metadata?: { [key: string]: any } | null;
};
@@ -0,0 +1,133 @@
import RowHelper from "~/utils/helpers/RowHelper";
import RowValueHelper from "~/utils/helpers/RowValueHelper";
import EntitiesSingleton from "./EntitiesSingleton";
import { RowDto } from "./RowDto";
export default class RowModel {
row: RowDto;
constructor(
row: RowDto,
options?: {
metadata?: string | null;
}
) {
this.row = row;
try {
if (options?.metadata) {
this.row.metadata = options?.metadata ? JSON.parse(options.metadata) : null;
}
} catch {}
}
public getEntity() {
const entities = EntitiesSingleton.getInstance().getEntities();
const entity = entities.find((entity) => entity.id === this.row.entityId);
if (!entity) {
throw new Error("Entity not found with ID: " + this.row.entityId);
}
return entity;
}
public getParents(entityName: string) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
const entity = allEntities.find((e) => e.name === entityName);
const relationship = this.getEntity().parentEntities.find((e) => e.parentId === entity?.id);
if (!relationship) {
return [];
}
if (!("parentRows" in this.row)) {
return [];
}
const rows = this.row.parentRows
.filter((r) => r.relationshipId === relationship.id)
.sort((a, b) => {
return a.createdAt > b.createdAt ? -1 : 1;
});
return rows.map(({ parent, metadata }) => new RowModel(parent, { metadata }));
}
public getFirstParent(entityName: string) {
const parents = this.getParents(entityName);
if (parents.length === 0) {
return null;
}
return parents[0];
}
public getChildren(entityName: string) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
const entity = allEntities.find((e) => e.name === entityName);
const relationship = this.getEntity().childEntities.find((e) => e.childId === entity?.id);
if (!relationship) {
return [];
}
if (!("childRows" in this.row)) {
return [];
}
const rows = this.row.childRows
.filter((r) => r.relationshipId === relationship.id)
.sort((a, b) => {
return a.createdAt > b.createdAt ? -1 : 1;
});
return rows.map(({ child, metadata }) => new RowModel(child, { metadata }));
}
public getFirstChild(entityName: string) {
const children = this.getChildren(entityName);
if (children.length === 0) {
return null;
}
return children[0];
}
public getRelated(entityName: string) {
const children = this.getChildren(entityName);
const parents = this.getParents(entityName);
return [...children, ...parents];
}
public getText(name: string) {
return RowValueHelper.getText({ row: this.row, entity: this.getEntity(), name });
}
public getBoolean(name: string) {
return RowValueHelper.getBoolean({ row: this.row, entity: this.getEntity(), name });
}
public getNumber(name: string) {
return RowValueHelper.getNumber({ row: this.row, entity: this.getEntity(), name });
}
public getDate(name: string) {
return RowValueHelper.getDate({ row: this.row, entity: this.getEntity(), name });
}
public getMedia(name: string) {
return RowValueHelper.getMedia({ row: this.row, entity: this.getEntity(), name });
}
public getFirstMedia(name: string) {
return RowValueHelper.getFirstMedia({ row: this.row, entity: this.getEntity(), name });
}
public getFirstMediaFile(name: string) {
return RowValueHelper.getFirstMediaFile({ row: this.row, entity: this.getEntity(), name });
}
public getMediaPublicUrl(name: string) {
return RowValueHelper.getFirstMedia({ row: this.row, entity: this.getEntity(), name })?.publicUrl;
}
public getMediaPublicUrlOrFile(name: string) {
const value = RowValueHelper.getFirstMedia({ row: this.row, entity: this.getEntity(), name });
return value?.publicUrl || value?.file;
}
public getSelected(name: string) {
return RowValueHelper.getSelected({ row: this.row, entity: this.getEntity(), name });
}
public getMultiple(name: string) {
return RowValueHelper.getMultiple({ row: this.row, entity: this.getEntity(), name });
}
public getNumberRange(name: string) {
return RowValueHelper.getNumberRange({ row: this.row, entity: this.getEntity(), name });
}
public getDateRange(name: string) {
return RowValueHelper.getDateRange({ row: this.row, entity: this.getEntity(), name });
}
public getValue(name: string) {
const property = this.getEntity().properties.find((p) => p.name === name);
const value = this.row.values.find((v) => v.propertyId === property?.id);
return {
property,
value,
};
}
public toString() {
return RowHelper.getTextDescription({ item: this.row, entity: this.getEntity() });
}
}
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import { vi } from "vitest";
vi.mock("~/utils/api/.server/RowRelationshipsApi", () => ({
RowRelationshipsApi: {
createRelationship: vi.fn(),
deleteRelationship: vi.fn(),
},
}));
vi.mock("~/utils/helpers/.server/RowValueService", () => ({
default: {
update: vi.fn(),
},
}));
vi.mock("~/utils/helpers/RowHelper", () => ({
default: {
getTextDescription: vi.fn(() => ""),
},
}));
import EntitiesSingleton from "./EntitiesSingleton";
import RowRepository from "./RowRepository.server";
const relationship = { id: "relationship-1", parentId: "parent-entity", childId: "child-entity" };
const parentEntity = { id: "parent-entity", name: "parents", slug: "parents", properties: [], parentEntities: [], childEntities: [relationship] };
const childEntity = { id: "child-entity", name: "children", slug: "children", properties: [], parentEntities: [relationship], childEntities: [] };
const parentRow = { id: "parent-row", entityId: "parent-entity", tenantId: "tenant-1", values: [], parentRows: [], childRows: [] };
const childRow = { id: "child-row", entityId: "child-entity", tenantId: "tenant-1", values: [], parentRows: [], childRows: [] };
describe("RowRepository tenant session propagation", () => {
it("keeps the session on related parent and child repositories", () => {
const session = { tenantId: "tenant-1", userId: "user-1" };
EntitiesSingleton.getInstance().setEntities([parentEntity as any, childEntity as any]);
const childRepository = new RowRepository(
{
...childRow,
parentRows: [{ relationshipId: "relationship-1", parent: parentRow }],
} as any,
{ session },
);
const parentRepository = new RowRepository(
{
...parentRow,
childRows: [{ relationshipId: "relationship-1", child: childRow }],
} as any,
{ session },
);
expect(childRepository.getParents("parents")[0].session).toEqual(session);
expect(parentRepository.getChildren("children")[0].session).toEqual(session);
});
});
@@ -0,0 +1,158 @@
import { RowMedia } from "@toolctrl/db/prisma-browser";
import { MediaDto } from "~/application/dtos/entities/MediaDto";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
import { RowRelationshipsApi } from "~/utils/api/.server/RowRelationshipsApi";
import RowValueService, { RowValueUpdateDto } from "~/utils/helpers/.server/RowValueService";
import EntitiesSingleton from "./EntitiesSingleton";
import RowModel from "./RowModel";
import { RowDto } from "./RowDto";
export default class RowRepository extends RowModel {
session: { tenantId: string | null; userId?: string } | undefined;
constructor(
row: RowDto,
options?: {
session?: { tenantId: string | null; userId?: string } | undefined;
}
) {
super(row);
this.session = options?.session;
}
private async update(value: RowValueUpdateDto, options?: { checkPermissions?: boolean; createLog?: boolean }) {
await RowValueService.update({
entity: this.getEntity(),
row: this.row,
session: this.session,
values: [value],
checkPermissions: options?.checkPermissions,
options: { createLog: options?.createLog },
});
}
public async updateMany(values: RowValueUpdateDto[], options?: { checkPermissions?: boolean; createLog?: boolean }) {
await RowValueService.update({
entity: this.getEntity(),
row: this.row,
session: this.session,
values,
checkPermissions: options?.checkPermissions,
options: { createLog: options?.createLog },
});
}
public async updateText(name: string, textValue: string | undefined, options?: { checkPermissions?: boolean; createLog?: boolean }) {
const value: RowValueUpdateDto = { name, textValue };
await this.update(value, options);
}
public async updateNumber(name: string, numberValue: number | undefined, options?: { checkPermissions?: boolean; createLog?: boolean }) {
const value: RowValueUpdateDto = { name, numberValue };
await this.update(value, options);
}
public async updateBoolean(name: string, booleanValue: boolean | undefined, options?: { checkPermissions?: boolean; createLog?: boolean }) {
const value: RowValueUpdateDto = { name, booleanValue };
await this.update(value, options);
}
public async updateDate(name: string, dateValue: Date | undefined, options?: { checkPermissions?: boolean; createLog?: boolean }) {
const value: RowValueUpdateDto = { name, dateValue };
await this.update(value, options);
}
public async updateMedia(name: string, media: MediaDto[] | undefined, options?: { checkPermissions?: boolean; createLog?: boolean }) {
const value: RowValueUpdateDto = { name, media: media as RowMedia[] };
await this.update(value, options);
}
public async updateMultiple(name: string, multiple: RowValueMultipleDto[] | undefined, options?: { checkPermissions?: boolean; createLog?: boolean }) {
const value: RowValueUpdateDto = { name, multiple };
await this.update(value, options);
}
public async updateRange(name: string, range: RowValueRangeDto | undefined, options?: { checkPermissions?: boolean; createLog?: boolean }) {
const value: RowValueUpdateDto = { name, range };
await this.update(value, options);
}
public async addChild(
relatedRow:
| { id: string; entityId: string }
| {
id: string;
entityName: string;
},
options?: { metadata?: { [key: string]: any } | null }
) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
let metadataString: string | null = null;
if (options?.metadata) {
try {
metadataString = JSON.stringify(options?.metadata);
} catch {}
}
return await RowRelationshipsApi.createRelationship({ parent: this.row, child: relatedRow, tenantId: this.session?.tenantId ?? null, metadata: metadataString, allEntities });
}
public async removeChild(relatedRow: { id: string; entityId: string } | { id: string; entityName: string }) {
const deleted = await RowRelationshipsApi.deleteRelationship({ parent: this.row, child: relatedRow, tenantId: this.session?.tenantId ?? null });
if (deleted.count) {
return;
}
// remove child
if (!("childRows" in this.row)) {
return [];
}
const childRowIndex = this.row.childRows.findIndex((r) => r.childId === relatedRow.id);
if (childRowIndex !== -1) {
this.row.childRows.splice(childRowIndex, 1);
}
}
public async addParent(
relatedRow: { id: string; entityId: string } | { id: string; entityName: string },
options?: { metadata?: { [key: string]: any } | null }
) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
let metadataString: string | null = null;
if (options?.metadata) {
try {
metadataString = JSON.stringify(options.metadata);
} catch {}
}
return await RowRelationshipsApi.createRelationship({ parent: relatedRow, child: this.row, tenantId: this.session?.tenantId ?? null, metadata: metadataString, allEntities });
}
public async removeParent(relatedRow: { id: string; entityId: string } | { id: string; entityName: string }) {
return await RowRelationshipsApi.deleteRelationship({ parent: relatedRow, child: this.row, tenantId: this.session?.tenantId ?? null });
}
public getParents(entityName: string) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
const entity = allEntities.find((e) => e.name === entityName);
const relationship = this.getEntity().parentEntities.find((e) => e.parentId === entity?.id);
if (!relationship) {
return [];
}
if (!("parentRows" in this.row)) {
return [];
}
const rows = this.row.parentRows.filter((r) => r.relationshipId === relationship.id).map((r) => r.parent);
return rows.map((row) => new RowRepository(row, { session: this.session }));
}
public getFirstParent(entityName: string) {
const parents = this.getParents(entityName);
if (parents.length === 0) {
return null;
}
return parents[0];
}
public getChildren(entityName: string) {
const allEntities = EntitiesSingleton.getInstance().getEntities();
const entity = allEntities.find((e) => e.name === entityName);
const relationship = this.getEntity().childEntities.find((e) => e.childId === entity?.id);
if (!relationship) {
return [];
}
if (!("childRows" in this.row)) {
return [];
}
const rows = this.row.childRows.filter((r) => r.relationshipId === relationship.id).map((r) => r.child);
return rows.map((row) => new RowRepository(row, { session: this.session }));
}
public getFirstChild(entityName: string) {
const children = this.getChildren(entityName);
if (children.length === 0) {
return null;
}
return children[0];
}
}