Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,30 +0,0 @@
import { ApiKeyEntity, Entity } from "@toolctrl/db/prisma-browser";
import { ApiKeyEntityPermissionDto } from "~/application/dtos/apiKeys/ApiKeyEntityPermissionDto";
import { getEntitiesInIds } from "~/utils/db/entities/entities.db.server";
export async function getApiKeyEntityPermissions(
entities:
| {
entityId: string;
create: boolean;
read: boolean;
update: boolean;
delete: boolean;
}[]
| (ApiKeyEntity & { entity: Entity })[]
): Promise<ApiKeyEntityPermissionDto[]> {
const apiKeyEntities = await getEntitiesInIds(entities.map((f) => f.entityId));
const entityPermissions: ApiKeyEntityPermissionDto[] = [];
entities.forEach((apiKeyEntity) => {
const entity = apiKeyEntities.find((f) => f.id === apiKeyEntity.entityId);
entityPermissions.push({
id: apiKeyEntity.entityId,
name: entity?.name ?? "",
create: apiKeyEntity.create,
read: apiKeyEntity.read,
update: apiKeyEntity.update,
delete: apiKeyEntity.delete,
});
});
return entityPermissions;
}
@@ -1,151 +0,0 @@
import { Entity } from "@toolctrl/db/prisma-browser";
import { RowWithDetails, updateRowMedia } from "~/utils/db/entities/rows.db.server";
import { deleteFile, hasStorageCredentials, putBufferAsFile } from "~/utils/integrations/storageService";
import { fetchOutboundHttpWithRedirects } from "~/utils/outboundHttp.server";
// Media sources come from client-supplied row JSON. A bare fetch() of a
// caller-controlled URL is an SSRF vector (cloud metadata, internal services),
// so only inline data: URIs are fetched directly; any remote URL is routed
// through the SSRF-safe helper that validates the scheme and rejects
// private/loopback/link-local/metadata addresses (incl. across redirects).
async function fetchMediaSource(source: string): Promise<Blob> {
const trimmed = (source ?? "").trim();
if (trimmed.toLowerCase().startsWith("data:")) {
return await (await fetch(trimmed)).blob();
}
const response = await fetchOutboundHttpWithRedirects(trimmed, {});
return await response.blob();
}
export async function storeRowMediaInStorageProvider(entity: Entity, row: RowWithDetails | null) {
if (!row) {
return;
}
const mediaRowValues = row.values.filter((f) => f.media && f.media.length > 0);
return await Promise.all(
mediaRowValues.map(async (mediaRowValue) => {
if (mediaRowValue.media) {
return await Promise.all(
mediaRowValue.media
.filter((f) => !f.publicUrl)
.map(async (media) => {
if (hasStorageCredentials()) {
try {
media.name = sanitizeFileName(media.name);
const blob = await fetchMediaSource(media.publicUrl || media.file);
const body = new Uint8Array(await blob.arrayBuffer());
const key = media.id + "-" + media.name;
const stored = await putBufferAsFile({ bucket: entity.name, key, body, contentType: blob.type || undefined });
if (stored.publicUrl) {
media.file = "";
media.publicUrl = stored.publicUrl;
media.storageBucket = entity.name;
media.storageProvider = "s3";
return await updateRowMedia({
id: media.id,
rowId: mediaRowValue.rowId,
entityId: row.entityId,
tenantId: row.tenantId,
}, {
file: "",
publicUrl: stored.publicUrl,
storageBucket: entity.name,
storageProvider: "s3",
});
}
} catch (e) {
// eslint-disable-next-line no-console
console.log("Could not store row media: " + e);
}
}
})
);
}
})
);
}
export async function deleteRowMediaFromStorageProvider(row: RowWithDetails | null) {
if (!row) {
return;
}
const mediaRowValues = row.values.filter((f) => f.media && f.media.length > 0);
return await Promise.all(
mediaRowValues.map(async (mediaRowValue) => {
if (mediaRowValue.media) {
return await Promise.all(
mediaRowValue.media.map(async (media) => {
if (media.publicUrl && media.storageBucket && hasStorageCredentials()) {
try {
await deleteFile({ bucket: media.storageBucket, key: media.id + "-" + media.name });
return await updateRowMedia({
id: media.id,
rowId: mediaRowValue.rowId,
entityId: row.entityId,
tenantId: row.tenantId,
}, {
file: "",
publicUrl: "",
storageBucket: "",
storageProvider: "",
});
} catch (e) {
// eslint-disable-next-line no-console
console.log("Could not delete stored media: " + e);
}
}
})
);
}
})
);
}
// export async function getMediaFromZipFiles(zipFiles: MediaDto[]) {
// let createdFiles: MediaDto[] = [];
// await Promise.all(
// zipFiles.map(async (item) => {
// const filePath = "zip-uploads/" + item.name.replace(" ", "");
// deleteFile(filePath);
// const path = await saveZip(filePath, { type: item.type, content: item.file.split(",")[1] });
// if (path) {
// const folderPath = path + "-unzip";
// deleteFolder(folderPath, { recursive: true, force: true });
// const entries = await extractZip(path);
// entries.forEach((entry) => {
// if (entry.name.startsWith("._")) {
// return;
// }
// var file = entry.getData().toString("base64");
// let type = "";
// if (entry.name.toLowerCase().endsWith("xml")) {
// type = "text/xml";
// } else if (entry.name.toLowerCase().endsWith("pdf")) {
// type = "application/pdf";
// }
// createdFiles.push({
// title: entry.name,
// name: entry.name,
// file: `data:${type};base64,${file}`,
// type,
// });
// });
// deleteFile(path);
// }
// deleteFile(filePath);
// })
// );
// return createdFiles;
// }
function sanitizeFileName(fileName: string): string {
// Replace spaces with underscores
const sanitized = fileName
.replace(/\s+/g, "_")
// Remove or replace other invalid characters as needed, e.g., commas, semicolons, etc.
.replace(/[^a-zA-Z0-9._-]/g, "");
// Optionally, you could add more specific replacements for known bad characters
// .replace(/specific-bad-character/g, 'replacement')
return sanitized;
}
@@ -0,0 +1,91 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(),
}));
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({
getPermissionName: vi.fn(),
}));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
findPermissionByUser: vi.fn(),
getUserRoleInAdmin: vi.fn(),
userHasPermission: vi.fn(),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
getTenantMember: vi.fn(),
}));
vi.mock("~/utils/loaders.middleware", () => ({
getIsSuperAdminByUserId: vi.fn(),
}));
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
getAuthUserWithoutPasswordById: vi.fn(),
}));
vi.mock("~/utils/services/.server/billingStatusService", () => ({
getTenantBillingReadOnlyState: vi.fn(),
}));
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
import { getTenantMember } from "~/utils/db/tenants.db.server";
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
import { getUserInfo } from "~/utils/session.server";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
import { getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { verifyUserHasPermission } from "./PermissionsService";
const userInfo = { userId: "user-1", lightOrDarkMode: "light", lng: "en", cookies: [] };
function request(method: string, path: string) {
return new Request(`https://app.example.test${path}`, { method });
}
async function expectStatus(promise: Promise<unknown>, status: number) {
try {
await promise;
throw new Error(`Expected response status ${status}`);
} catch (error) {
expect(error).toBeInstanceOf(Response);
expect((error as Response).status).toBe(status);
}
}
describe("verifyUserHasPermission billing read-only guard", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getUserInfo).mockResolvedValue(userInfo);
vi.mocked(getUser).mockResolvedValue(null);
vi.mocked(getIsSuperAdminByUserId).mockResolvedValue(false);
vi.mocked(getUserRoleInAdmin).mockResolvedValue(null);
vi.mocked(getPermissionName).mockResolvedValue({ id: "perm-1", name: "tasks.create" } as never);
vi.mocked(getTenantMember).mockResolvedValue({ status: TenantUserStatus.ACTIVE } as never);
vi.mocked(userHasPermission).mockResolvedValue(true);
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValue({ readOnly: false, status: null });
});
it("blocks mutating tenant requests when billing is read-only", async () => {
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValueOnce({ readOnly: true, status: "frozen" });
await expectStatus(verifyUserHasPermission(request("POST", "/acme/tasks/new"), "tasks.create", "tenant-1"), 423);
expect(getTenantBillingReadOnlyState).toHaveBeenCalledWith("tenant-1");
expect(userHasPermission).not.toHaveBeenCalled();
});
it("allows read-only GET requests without checking the billing write guard", async () => {
await expect(verifyUserHasPermission(request("GET", "/acme/tasks"), "tasks.create", "tenant-1")).resolves.toBe(true);
expect(getTenantBillingReadOnlyState).not.toHaveBeenCalled();
expect(userHasPermission).toHaveBeenCalledWith("user-1", "tenant-1", "tasks.create");
});
it("allows subscription actions so tenants can recover billing", async () => {
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValueOnce({ readOnly: true, status: "frozen" });
await expect(verifyUserHasPermission(request("POST", "/acme/settings/subscription"), "app.settings.subscription.update", "tenant-1")).resolves.toBe(true);
expect(getTenantBillingReadOnlyState).not.toHaveBeenCalled();
expect(userHasPermission).toHaveBeenCalledWith("user-1", "tenant-1", "app.settings.subscription.update");
});
});
@@ -1,21 +1,36 @@
import { Prisma } from "@toolctrl/db/prisma-browser";
import { redirect } from "react-router";
import { RowPermissionsDto } from "~/application/dtos/entities/RowPermissionsDto";
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { RowAccess, RowAccessTypes } from "~/application/enums/entities/RowAccess";
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
import { getMyGroups } from "~/utils/db/permissions/groups.db.server";
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
import { findPermissionByUser, findUserRolesByIds, getUserRoles, getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { findPermissionByUser, getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { getTenantMember } from "~/utils/db/tenants.db.server";
import { getEntityPermission } from "~/utils/helpers/PermissionsHelper";
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
import { getUserInfo } from "~/utils/session.server";
import { getAuthUserWithoutPasswordById as getUser } from "@toolctrl/db/auth-boundary.server";
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
const OPERATOR_ADMIN_BYPASS_DESCRIPTION = "Operator admin tenant permission bypass";
const BILLING_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "billing:status.readOnly" } };
function isMutatingRequest(request: Request): boolean {
return !["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase());
}
export function isBillingReadOnlyBypassPath(requestUrl: string): boolean {
const pathname = new URL(requestUrl).pathname;
return /\/settings\/subscription\/?$/.test(pathname);
}
export async function assertTenantWritableForRequest(request: Request, tenantId: string | null) {
if (!tenantId || !isMutatingRequest(request) || isBillingReadOnlyBypassPath(request.url)) {
return;
}
const billingState = await getTenantBillingReadOnlyState(tenantId);
if (billingState.readOnly) {
throw Response.json(BILLING_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
}
}
export async function getUserPermission({ userId, permissionName, tenantId }: { userId: string; permissionName: string; tenantId?: string | null }) {
if (tenantId) {
@@ -86,17 +101,6 @@ export function shapePermissionCheckResult({
return { allowed: false, permissionName, tenantId, reason: reason ?? "permission-denied" };
}
export type EntityPermissionOperation = "view" | "read" | "create" | "update" | "delete";
export async function verifyUserHasEntityPermission(
request: Request,
entity: { name: string },
operation: EntityPermissionOperation,
tenantId: string | null = null
) {
return verifyUserHasPermission(request, getEntityPermission(entity, operation), tenantId);
}
export async function verifyUserHasPermission(request: Request, permissionName: DefaultPermission, tenantId: string | null = null) {
// if (permissionName.startsWith("entity.")) {
// return true;
@@ -107,6 +111,7 @@ export async function verifyUserHasPermission(request: Request, permissionName:
shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "unauthenticated" });
throw Error("Unauthorized");
}
await assertTenantWritableForRequest(request, tenantId);
if (tenantId) {
const user = await getUser(userInfo.userId);
const isOperatorAdmin =
@@ -138,116 +143,3 @@ export async function verifyUserHasPermission(request: Request, permissionName:
shapePermissionCheckResult({ allowed: true, permissionName, tenantId });
return true;
}
export async function getUserRowPermission(row: RowWithDetails, tenantId?: string | null, userId?: string): Promise<RowPermissionsDto> {
const accessLevels: RowAccess[] = ["none"];
let isOwner = false;
if (tenantId && userId && (await getIsSuperAdminByUserId(userId))) {
isOwner = true;
} else if (tenantId === null && userId) {
const isSuperAdmin = await getUserRoleInAdmin(userId, DefaultAdminRoles.SuperAdmin);
if (isSuperAdmin) {
isOwner = true;
}
} else if (tenantId === undefined && userId === undefined) {
accessLevels.push("view");
} else {
isOwner = !!userId && userId === row.createdByUserId;
if (tenantId) {
const existing = row.permissions.find((f) => f.tenantId === tenantId);
if (existing) {
accessLevels.push(existing.access as RowAccess);
}
} else if (userId) {
if (row.createdByUserId === userId || row.createdByUserId === null) {
accessLevels.push("delete");
}
const existing = row.permissions.find((f) => f.userId === userId);
if (existing) {
accessLevels.push(existing.access as RowAccess);
}
}
if (tenantId !== undefined && userId) {
const inRoles = row.permissions
.filter((f) => f.roleId)
.map((f) => f.roleId)
.map((f) => f as string);
if (inRoles.length > 0) {
const userRoles = await findUserRolesByIds(userId, tenantId, inRoles);
userRoles.forEach((userRole) => {
const existing = row.permissions.find((f) => f.roleId === userRole.roleId);
if (existing) {
accessLevels.push(existing.access as RowAccess);
}
});
}
const inGroups = row.permissions
.filter((f) => f.groupId)
.map((f) => f.groupId)
.map((f) => f as string);
if (inGroups.length > 0) {
const userGroups = await getMyGroups(userId, tenantId);
userGroups.forEach((userGroup) => {
const existing = row.permissions.find((f) => f.groupId === userGroup.id);
if (existing) {
accessLevels.push(existing.access as RowAccess);
}
});
}
}
}
let access: RowAccess | undefined = undefined;
for (let idx = RowAccessTypes.length - 1; idx >= 0; idx--) {
const accessType = RowAccessTypes[idx];
if (accessLevels.includes(accessType)) {
access = accessType;
break;
}
}
const rowPermissions: RowPermissionsDto = {
canRead: isOwner || (access && access !== "none"),
canComment: isOwner || access === "comment" || access === "edit" || access === "delete",
canUpdate: isOwner || access === "edit" || access === "delete",
canDelete: isOwner || access === "delete",
isOwner,
};
return rowPermissions;
}
export type RowPermissionsFilter = Prisma.RowWhereInput | {};
export async function getRowPermissionsCondition({ tenantId, userId }: { tenantId?: string | null; userId?: string }) {
if (tenantId && userId && (await getIsSuperAdminByUserId(userId))) {
return {};
}
const OR_CONDITIONS: Prisma.RowWhereInput[] = [];
const readableAccess = { not: "none" };
if (tenantId) {
OR_CONDITIONS.push(...[{ permissions: { some: { tenantId, access: readableAccess } } }]);
if (userId) {
OR_CONDITIONS.push(...[{ createdByUserId: userId }, { permissions: { some: { userId, access: readableAccess } } }]);
}
} else {
if (userId) {
OR_CONDITIONS.push(...[{ createdByUserId: null }, { createdByUserId: userId }, { permissions: { some: { userId, access: readableAccess } } }]);
}
}
if (tenantId !== undefined && userId) {
const userRoles = await getUserRoles(userId, tenantId);
userRoles.forEach((userRole) => {
OR_CONDITIONS.push(...[{ permissions: { some: { roleId: userRole.roleId, access: readableAccess } } }]);
});
const userGroups = await getMyGroups(userId, tenantId);
userGroups.forEach((userGroup) => {
OR_CONDITIONS.push(...[{ permissions: { some: { groupId: userGroup.id, access: readableAccess } } }]);
});
}
return {
OR: OR_CONDITIONS,
};
}
@@ -1,65 +0,0 @@
import { Prisma } from "@toolctrl/db/prisma-browser";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { RowFiltersDto } from "~/application/dtos/data/RowFiltersDto";
import { SortedByDto } from "~/application/dtos/data/SortedByDto";
import { RowWithDetails, getRows, countRows } from "~/utils/db/entities/rows.db.server";
export async function getRowsWithPagination({
pageSize,
page,
entityId,
entityName,
tenantId,
portalId,
userId,
sortedBy,
filters,
rowWhere,
includePublic,
orderBy,
}: {
pageSize: number;
page: number;
entityId?: string;
entityName?: string;
tenantId?: string | null;
portalId?: string | null;
userId?: string | undefined;
sortedBy?: SortedByDto[];
filters?: RowFiltersDto;
rowWhere?: Prisma.RowWhereInput;
includePublic?: boolean;
orderBy?: Prisma.RowOrderByWithRelationInput[];
}): Promise<{
items: RowWithDetails[];
pagination: PaginationDto;
}> {
if (!orderBy) {
orderBy = [{ order: "desc" }, { createdAt: "desc" }];
}
let skip: number | undefined = pageSize * (page - 1);
let take: number | undefined = pageSize;
if (pageSize === -1) {
skip = undefined;
take = undefined;
}
const items = await getRows({ entityId, entityName, tenantId, userId, take, skip, orderBy, filters, rowWhere, includePublic });
const totalItems = await countRows({ entityId, entityName, tenantId, userId, filters, rowWhere, includePublic });
let totalPages = Math.ceil(totalItems / pageSize);
if (pageSize === -1) {
totalPages = 1;
}
return {
items,
pagination: {
totalItems,
totalPages,
page,
pageSize,
sortedBy,
query: undefined,
},
};
}
@@ -1,104 +0,0 @@
import { RowMedia, Entity, Prisma, RowValue, RowValueMultiple, RowValueRange } from "@toolctrl/db/prisma-browser";
import { RowsApi } from "../../api/.server/RowsApi";
import { db } from "../../db.server";
import { PropertyWithDetails } from "../../db/entities/entities.db.server";
import { RowValueWithDetails } from "../../db/entities/rows.db.server";
import { RowValueDto } from "~/application/dtos/entities/RowValueDto";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
export type RowValueUpdateDto = {
name: string;
textValue?: string | undefined;
numberValue?: number | undefined;
dateValue?: Date | undefined;
booleanValue?: boolean | undefined;
media?: RowMedia[];
multiple?: RowValueMultipleDto[];
range?: RowValueRangeDto | undefined;
};
async function update({
entity,
row,
values,
rowUpdateInput,
session,
checkPermissions = true,
options,
}: {
entity: Entity & { properties: PropertyWithDetails[] };
row: { id: string; entityId: string; tenantId: string | null; values: RowValueWithDetails[] };
values?: RowValueUpdateDto[];
rowUpdateInput?: Prisma.RowUpdateInput;
session: { tenantId: string | null; userId?: string } | undefined;
checkPermissions?: boolean;
options?: {
createLog?: boolean;
createEvent?: boolean;
};
}) {
const dynamicProperties: RowValueDto[] = [];
await Promise.all(
(values ?? []).map(async (value) => {
const property = entity.properties.find((i) => i.name === value.name);
if (property) {
let existingProperty: RowValue | null = row.values.find((f) => f.propertyId === property?.id) ?? null;
if (!existingProperty) {
existingProperty = await db.rowValue.findFirstOrThrow({ where: { propertyId: property.id, rowId: row.id } }).catch(() => {
return null;
});
}
if (!existingProperty) {
existingProperty = await db.rowValue.create({
data: {
propertyId: property.id,
rowId: row.id,
textValue: value.textValue,
numberValue: value.numberValue,
dateValue: value.dateValue,
},
});
}
dynamicProperties.push({
id: existingProperty.id,
property,
propertyId: property.id,
textValue: value.textValue,
numberValue: value.numberValue,
dateValue: value.dateValue,
booleanValue: value.booleanValue,
media: value.media,
multiple: value.multiple as RowValueMultiple[],
range: value.range as RowValueRange,
});
if (value.textValue !== undefined) {
existingProperty.textValue = value.textValue;
}
if (value.numberValue !== undefined) {
existingProperty.numberValue = value.numberValue ? new Prisma.Decimal(value.numberValue) : null;
}
if (value.dateValue !== undefined) {
existingProperty.dateValue = value.dateValue;
}
if (value.booleanValue !== undefined) {
existingProperty.booleanValue = value.booleanValue;
}
}
})
);
return await RowsApi.update(row.id, {
entity,
tenantId: row.tenantId,
rowValues: {
dynamicProperties,
},
rowUpdateInput,
userId: session?.userId,
checkPermissions,
options,
});
}
export default {
update,
};
@@ -1,420 +0,0 @@
import { MediaDto } from "~/application/dtos/entities/MediaDto";
import { RowValueDto } from "~/application/dtos/entities/RowValueDto";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { EntityWithDetails, EntityWithProperties, PropertyWithDetails } from "../db/entities/entities.db.server";
import { RowWithDetails, RowWithValues } from "../db/entities/rows.db.server";
import RowHelper from "./RowHelper";
import bcrypt from "bcryptjs";
import { TFunction } from "i18next";
import { validatePropertyValue, validatePropertyValue_Media, validatePropertyValue_Multiple } from "./PropertyHelper";
import PropertyAttributeHelper from "./PropertyAttributeHelper";
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
import { EntityRelationshipWithDetails } from "../db/entities/entityRelationships.db.server";
import RelationshipHelper from "./RelationshipHelper";
import { RowMedia, RowValueMultiple, RowValueRange } from "@toolctrl/db/prisma-browser";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
const generateKey = () => {
const id: string = crypto.randomUUID();
return id;
};
const hashKey = async (key: string) => {
return await bcrypt.hash(key, 10);
};
const validateKey = async (key: string, hashedKey: string) => {
return await bcrypt.compare(key, hashedKey);
};
const getRowPropertiesFromJson = (t: TFunction | undefined, entity: EntityWithDetails, jsonObject: any, existing?: RowWithDetails) => {
const dynamicProperties: RowValueDto[] = [];
const properties: any = {};
entity.properties
.filter((f) => !f.isHidden)
.forEach((property) => {
const propertyValue = getPropertyValueFromJson(t, property, jsonObject, existing);
if (propertyValue?.rowValue) {
dynamicProperties.push(propertyValue?.rowValue);
}
});
return {
dynamicProperties,
properties,
};
};
function getPropertyValueFromJson(t: TFunction | undefined, property: PropertyWithDetails, object: any, existing?: RowWithDetails) {
let jsonValue: any | null = null;
let media: MediaDto[] = [];
let multiple: RowValueMultipleDto[] = [];
let range: RowValueRangeDto | null = null;
let name = property.name;
if (property.type === PropertyType.RANGE_NUMBER) {
try {
range = {
numberMin: object[name]?.min ?? null,
numberMax: object[name]?.min ?? null,
dateMin: null,
dateMax: null,
};
} catch (e: any) {
throw Error(`Invalid number range (${property.name}): ${e.message}`);
}
} else if (property.type === PropertyType.RANGE_DATE) {
try {
const min = object[name]?.min;
const max = object[name]?.max;
range = {
numberMin: null,
numberMax: null,
dateMin: min ? new Date(min?.toString()) : null,
dateMax: max ? new Date(max?.toString()) : null,
};
} catch (e: any) {
throw Error(`Invalid date range (${property.name}): ${e.message}`);
}
} else if ([PropertyType.MULTI_SELECT, PropertyType.MULTI_TEXT].includes(property.type)) {
multiple =
object[name]?.map((f: string, idx: number) => {
const value: RowValueMultipleDto = {
order: idx + 1,
value: f,
};
return value;
}) ?? [];
validatePropertyValue_Multiple({ t, property, multiple });
} else if (property.type === PropertyType.MEDIA) {
media =
object[name]?.map((f: MediaDto) => {
return f;
}) ?? [];
validatePropertyValue_Media({ t, property, media });
} else {
jsonValue = object[name];
if (property.isRequired && !property.isRequired && (jsonValue === null || jsonValue === undefined || jsonValue === "")) {
const defaultValue = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.DefaultValue);
if (defaultValue) {
jsonValue = defaultValue;
} else {
if (existing && !object.hasOwnProperty(name)) {
return null;
}
if (t) {
throw Error(`${t(property.title)}: required`);
} else {
throw Error(`${property.name}: required`);
}
}
}
validatePropertyValue({ t, property, value: jsonValue });
}
const value = RowHelper.getValueFromType(property.type, jsonValue);
value.media = media;
value.multiple = multiple;
value.range = range;
const existingValue = existing?.values.find((f) => f.propertyId === property.id);
const rowValue: RowValueDto = {
id: existingValue?.id ?? null,
propertyId: property.id,
property: property,
...value,
};
return { rowValue };
}
const getApiFormat = (entity: EntityWithProperties, item: RowWithValues | null, options: ApiFormatOptions = {}) => {
if (item === null) {
return null;
}
let properties: any = {};
entity.properties
.filter((f) => !f.isDefault)
.forEach((property) => {
const value = getPropertyApiFormat({ entity, property, item });
properties[property.name] = value;
});
const object: any = {
id: item.id,
folio: RowHelper.getRowFolio(entity, item),
...properties,
createdAt: item.createdAt,
createdByUser: item.createdByUser
? {
id: item.createdByUserId,
email: item.createdByUser.email,
firstName: item.createdByUser.firstName,
lastName: item.createdByUser.lastName,
}
: null,
createdByApiKey: item.createdByApiKey
? {
alias: item.createdByApiKey.alias,
}
: null,
};
options?.exclude?.forEach((toExclude) => {
delete object[toExclude];
});
return object;
};
export type ApiFormatOptions = {
exclude?: string[];
};
function getApiFormatWithRelationships({
entities,
item,
options,
originalParentId,
}: {
entities: EntityWithDetails[];
item: RowWithDetails | null;
options?: ApiFormatOptions;
originalParentId?: string;
}) {
if (!item) {
return null;
}
const entity = entities.find((f) => f.id === item.entityId);
if (entity === undefined) {
return null;
}
const apiFormat = getApiFormat(entity, item, options);
Object.assign(
apiFormat,
getRelationship({ entity, entities, relationships: entity.parentEntities, type: "parent", item, options, originalParentId: originalParentId ?? item.id })
);
Object.assign(
apiFormat,
getRelationship({ entity, entities, relationships: entity.childEntities, type: "child", item, options, originalParentId: originalParentId ?? item.id })
);
return apiFormat;
}
function getRelationship({
entity,
entities,
relationships,
type,
item,
options,
originalParentId,
}: {
entity: EntityWithDetails;
entities: EntityWithDetails[];
relationships: EntityRelationshipWithDetails[];
type: "parent" | "child";
item: RowWithDetails;
options?: ApiFormatOptions;
originalParentId: string;
}) {
const fromEntityId = entity.id;
const apiFormat: any = {};
relationships.forEach((relationship) => {
const { id, parent, child } = relationship;
const multiple = RelationshipHelper.getInputType({ fromEntityId, relationship }) === "multi-select";
const entity = entities.find((e) => e.id === (type === "parent" ? parent.id : child.id));
if (!entity) {
return;
}
const rows =
type === "parent"
? (item.parentRows
?.filter((f) => f.parentId !== originalParentId)
?.map((f) => {
return { id: f.id, relationshipId: f.relationshipId, row: f.parent };
}) ?? [])
: (item.childRows
?.filter((f) => f.childId !== originalParentId)
?.map((f) => {
return { id: f.id, relationshipId: f.relationshipId, row: f.child };
}) ?? []);
if (multiple && entity.id === child.id) {
apiFormat[entity.name] = [];
rows
.filter((f) => f.relationshipId === id)
.forEach((r) => {
if (!r.row) {
return;
}
const rowApiFormat = getApiFormat(entity!, r.row, options);
apiFormat[entity.name].push({
// relationshipId: r.id,
...rowApiFormat,
...getApiFormatWithRelationships({ entities, item: r.row as RowWithDetails, options, originalParentId }),
});
});
} else {
const row = rows?.find((f) => f.relationshipId === id);
if (row) {
const rowApiFormat = getApiFormat(entity!, row.row, options);
apiFormat[entity.name] = {
// relationshipId: row.id,
...rowApiFormat,
...getApiFormatWithRelationships({ entities, item: row.row as RowWithDetails, options, originalParentId }),
};
} else {
apiFormat[entity.name] = null;
}
}
});
return apiFormat;
}
const getPropertyApiFormat = ({ entity, item, property }: { entity: EntityWithProperties; item: RowWithValues; property: PropertyWithDetails }) => {
const value = RowHelper.getPropertyValue({ entity, item, property });
if (property.type === PropertyType.TEXT) {
return value?.toString();
} else if (property.type === PropertyType.NUMBER) {
return value as number;
} else if (property.type === PropertyType.BOOLEAN) {
return value as boolean;
} else if (property.type === PropertyType.DATE) {
let date = value as Date;
return date?.toISOString();
} else if (property.type === PropertyType.SELECT) {
return value?.toString();
} else if (property.type === PropertyType.MEDIA) {
const media = value as RowMedia[];
return (
media?.map((f) => {
return {
id: f.id,
name: f.name,
file: f.publicUrl ?? f.file,
type: f.type,
};
}) ?? []
);
} else if (property.type === PropertyType.MULTI_SELECT) {
const multiple = value as RowValueMultiple[];
return (
multiple?.map((f) => {
return f.value;
}) ?? []
);
} else if (property.type === PropertyType.MULTI_TEXT) {
const multiple = value as RowValueMultiple[];
return (
multiple?.map((f) => {
return f.value;
}) ?? []
);
} else if (property.type === PropertyType.RANGE_NUMBER) {
const range = value as RowValueRange;
return {
min: range?.numberMin ?? null,
max: range?.numberMax ?? null,
};
} else if (property.type === PropertyType.RANGE_DATE) {
const range = value as RowValueRange;
return {
min: range?.dateMin?.toISOString() ?? null,
max: range?.dateMax?.toISOString() ?? null,
};
} else {
return RowHelper.getPropertyValue({ entity, item, property });
}
};
function getSchemaType({ property }: { property: PropertyWithDetails }) {
switch (property.type) {
case PropertyType.TEXT:
case PropertyType.SELECT:
return { type: "string" };
case PropertyType.NUMBER:
return { type: "integer" };
case PropertyType.BOOLEAN:
return { type: "boolean" };
case PropertyType.DATE:
return { type: "string", format: "date" }; // or "date-time" if ISO 8601 format
case PropertyType.MULTI_SELECT:
case PropertyType.MULTI_TEXT:
return { type: "array", items: { type: "string" } };
case PropertyType.MEDIA:
return {
type: "array",
items: {
type: "object",
properties: {
title: { type: "string" },
name: { type: "string" },
file: { type: "string" },
type: { type: "string" },
},
},
};
case PropertyType.RANGE_NUMBER:
return {
type: "object",
properties: {
min: { type: "integer" },
max: { type: "integer" },
},
};
case PropertyType.RANGE_DATE:
return {
type: "object",
properties: {
min: { type: "string", format: "date" },
max: { type: "string", format: "date" },
},
};
default:
return { type: "string" };
}
}
function getSampleValue({ property }: { property: PropertyWithDetails }) {
switch (property.type) {
case PropertyType.TEXT:
return "Sample text";
case PropertyType.NUMBER:
return 123;
case PropertyType.BOOLEAN:
return true;
case PropertyType.DATE:
return new Date();
case PropertyType.SELECT:
return property.options.length > 0 ? property.options[0].value : "Sample select";
case PropertyType.MEDIA:
return [{ name: "My image.png", type: "image/png", title: "My image", file: "https://placehold.co/1000x500.png?text=My%20image" }];
case PropertyType.MULTI_SELECT:
case PropertyType.MULTI_TEXT:
return property.options.map((f) => f.value);
case PropertyType.RANGE_DATE:
return { min: new Date(), max: new Date() };
case PropertyType.RANGE_NUMBER:
return { min: 1, max: 100 };
default:
return "{NOT SUPPORTED}";
}
}
export default {
generateKey,
hashKey,
validateKey,
getRowPropertiesFromJson,
getApiFormat,
getApiFormatWithRelationships,
getSchemaType,
getSampleValue,
};
@@ -1,19 +0,0 @@
// @vitest-environment node
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "EntityHelper.ts"), "utf8");
describe("EntityHelper admin routes", () => {
it("does not emit tenant-only grouped entity routes on the admin host", () => {
expect(source).toContain("appPath({ tenantSlug: params.tenant, path: `g/${entityInGroup.slug}/${entity.slug}`");
expect(source).not.toContain("adminPath(`g/${entityInGroup.slug}/${entity.slug}`");
expect(source).toContain("adminPath(`entities/${entity.slug}/no-code/${entity.slug}`");
});
it("does not emit nonexistent portal entity row routes", () => {
expect(source).not.toContain("portals/${params.portal}/${entity.slug}/rows");
});
});
@@ -1,351 +0,0 @@
import { Property, Row } from "@toolctrl/db/prisma-browser";
import { TFunction } from "i18next";
import { Params } from "react-router";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { FilterDto } from "~/components/ui/input/InputFilters";
import { EntitiesApi } from "../api/.server/EntitiesApi";
import { EntityWithDetails } from "../db/entities/entities.db.server";
import RowFiltersHelper from "./RowFiltersHelper";
import RowHelper from "./RowHelper";
import { AppOrAdminData } from "../data/useAppOrAdminData";
import { EntitiesTemplateDto, TemplateEntityDto, TemplateEntityViewDto } from "~/modules/templates/EntityTemplateDto";
import { EntityRelationshipWithDetails } from "../db/entities/entityRelationships.db.server";
import EntityViewHelper from "./EntityViewHelper";
import { mapToEntityTemplateType } from "./PropertyHelper";
import Constants from "~/application/Constants";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
// const getEntityFromParams = async (params: Params) => {
// return await getEntityBySlug(params.entity ?? "");
// };
const getFieldTitle = (field: Property, _ = false): string => {
switch (field.type) {
// case PropertyType.USER:
// case PropertyType.ROLE:
// case PropertyType.ID:
// if (isDefault) {
// return "entities.defaultFields." + PropertyType[field.type];
// } else {
// return "entities.fields." + PropertyType[field.type];
// }
default:
return field.title;
}
};
function getFilters({ t, entity, pagination }: { t: TFunction; entity: EntityWithDetails; pagination?: PaginationDto }) {
const filters: FilterDto[] = [
...entity.properties
.filter((f) => RowFiltersHelper.isPropertyFilterable(f))
.map((item) => {
const filter: FilterDto = {
name: item.name,
title: t(item.title),
options: item.options?.map((option) => {
return {
color: option.color,
name: option.name ?? option.value,
value: option.value,
};
}),
isBoolean: item.type === PropertyType.BOOLEAN,
hideSearch: item.type === PropertyType.BOOLEAN,
};
return filter;
}),
];
if (entity.tags.length > 0) {
filters.push({
name: "tag",
title: t("models.tag.plural"),
options: entity.tags.map((tag) => {
return {
color: tag.color,
name: tag.value,
value: tag.value,
};
}),
});
}
// if (pagination) {
// filters.push({
// hideSearch: true,
// name: "pageSize",
// title: t("shared.pageSize"),
// options: [
// { name: "5", value: "5" },
// { name: "10", value: "10" },
// { name: "25", value: "25" },
// { name: "50", value: "50" },
// { name: "100", value: "100" },
// ],
// });
// }
return filters;
}
function getRoutes({
routes,
entity,
item,
}: {
routes?: EntitiesApi.Routes;
entity: { slug: string; onEdit: string | null };
item?: Row;
}): EntitiesApi.Routes | undefined {
if (!routes) {
return undefined;
}
const entityRoutes: EntitiesApi.Routes = {
list: routes.list?.split(":entity").join(entity.slug),
new: routes.new?.split(":entity").join(entity.slug),
overview: routes.overview
?.split(":entity")
.join(entity.slug)
.replace(":id", item?.id ?? ""),
edit: routes.edit
?.split(":entity")
.join(entity.slug)
.replace(":id", item?.id ?? ""),
import: routes.import?.split(":entity").join(entity.slug),
export: routes.export?.split(":entity").join(entity.slug),
publicUrl: routes.publicUrl
?.split(":entity")
.join(entity.slug)
.replace(":id", item?.id ?? ""),
group: routes.group?.split(":entity").join(entity.slug),
};
if (entity.onEdit === "overviewRoute") {
entityRoutes.edit = entityRoutes.overview + "?editing";
} else if (entity.onEdit === "overviewAlwaysEditable") {
entityRoutes.edit = entityRoutes.overview + "?editing";
}
return entityRoutes;
}
function getLayoutBreadcrumbsMenu({
type,
t,
entity,
routes,
item,
params,
appOrAdminData,
}: {
type: "edit" | "new" | "overview";
t: TFunction;
entity: EntityWithDetails;
routes: EntitiesApi.Routes;
item: Row | undefined;
params: Params;
appOrAdminData: AppOrAdminData;
}) {
let menu: { title: string; routePath?: string }[] = [];
if (params.group) {
const group = appOrAdminData.entityGroups.find((f) => f.slug === params.group);
if (group) {
menu.push({
title: group.title,
routePath: params.tenant
? appPath({ tenantSlug: params.tenant, path: `g/${params.group}`, mode: "host-aware" })
: adminPath(`g/${params.group}`, { mode: "host-aware" }),
});
}
}
if (type === "edit") {
menu = [
...menu,
{ title: t(entity.titlePlural), routePath: getRoutes({ routes, entity: entity })?.list },
{
title: RowHelper.getRowFolio(entity, item!),
routePath: getRoutes({ routes, entity: entity, item: item })?.overview,
},
{
title: t("shared.edit"),
routePath: getRoutes({ routes, entity: entity, item: item })?.edit,
},
];
} else if (type === "new") {
menu = [
...menu,
{
title: t(entity.titlePlural),
routePath: getRoutes({ routes, entity })?.list,
},
{
title: t("shared.new"),
routePath: getRoutes({ routes, entity })?.new,
},
];
} else if (type === "overview") {
menu = [
...menu,
{
title: t(entity.titlePlural),
routePath: getRoutes({ routes, entity: entity, item: item })?.list,
},
{
title: RowHelper.getRowFolio(entity, item!),
routePath: getRoutes({ routes, entity: entity, item: item })?.overview,
},
{ title: t("shared.overview") },
];
}
return menu;
}
function getEntityRoute({ entity, params, appOrAdminData }: { entity: EntityWithDetails; params: Params; appOrAdminData: AppOrAdminData }) {
const entityInGroup = appOrAdminData.entityGroups.find((f) => f.entities.find((e) => e.entityId === entity.id));
if (entityInGroup) {
if (params.tenant) {
return appPath({ tenantSlug: params.tenant, path: `g/${entityInGroup.slug}/${entity.slug}`, mode: "host-aware" });
} else {
return adminPath(`entities/${entity.slug}/no-code/${entity.slug}`, { mode: "host-aware" });
}
}
if (params.tenant) {
return appPath({ tenantSlug: params.tenant, path: entity.slug, mode: "host-aware" });
} else {
return adminPath(`entities/${entity.slug}/no-code/${entity.slug}`, { mode: "host-aware" });
}
}
function exportEntitiesToTemplate(entities: EntityWithDetails[], relationships: EntityRelationshipWithDetails[]) {
const templateEntities: EntitiesTemplateDto = {
entities: [],
relationships: [],
};
entities.forEach((entity) => {
const exportedEntity: TemplateEntityDto = {
type: entity.type,
name: entity.name,
slug: entity.slug,
title: entity.title,
titlePlural: entity.titlePlural,
prefix: entity.prefix,
properties: entity.properties
.filter((f) => !f.isDefault)
.map((property) => {
return {
name: property.name,
title: property.title,
type: mapToEntityTemplateType(property.type),
subtype: property.subtype,
isRequired: property.isRequired ?? undefined,
isDisplay: property.isDisplay ?? undefined,
isReadOnly: property.isReadOnly ?? undefined,
showInCreate: property.showInCreate ?? undefined,
attributes:
property.attributes.filter((f) => f.value).length === 0
? undefined
: property.attributes
.filter((f) => f.value)
.map((attr) => {
return {
name: attr.name,
value: attr.value,
};
}),
options:
property.options.length === 0
? undefined
: property.options?.map((option) => {
return {
value: option.value,
name: option.name ?? undefined,
color: option.color ?? undefined,
};
}),
tenantId: property.tenantId ?? undefined,
};
}),
isAutogenerated: entity.isAutogenerated ? true : false,
hasApi: entity.hasApi ? true : false,
icon: entity.icon.length > 0 ? entity.icon : undefined,
active: entity.active ? true : false,
hasTags: entity.hasTags ? true : false,
hasComments: entity.hasComments ? true : false,
hasTasks: entity.hasTasks ? true : false,
defaultVisibility: entity.defaultVisibility === "private" ? undefined : entity.defaultVisibility,
onCreated: entity.onCreated ?? "redirectToOverview",
onEdit: entity.onEdit ?? "editRoute",
};
if (entity.views.length > 0) {
exportedEntity.views = entity.views
.sort((a, b) => a.order - b.order)
.map((view) => {
const exportedView: TemplateEntityViewDto = {
layout: view.layout === "table" ? "table" : "board",
name: view.name,
title: view.title,
properties:
view.properties
.sort((a, b) => a.order - b.order)
.map((prop) => {
// const property = entity.properties.find((f) => f.name === prop.name);
return prop.name ?? "";
}) ?? undefined,
filters: view.filters.map((filter) => {
return {
match: filter.match === "and" ? "and" : "or",
name: filter.name,
condition: EntityViewHelper.getCondition(filter.condition),
value: filter.value,
};
}),
sort: view.sort.map((sort) => {
return {
name: sort.name,
asc: sort.asc,
};
}),
isDefault: view.isDefault ?? undefined,
isSystem: view.isSystem ?? undefined,
tenantId: view.tenantId ?? undefined,
userId: view.userId ?? undefined,
pageSize: view.pageSize !== Constants.DEFAULT_PAGE_SIZE ? view.pageSize : undefined,
order: view.order ?? undefined,
groupByProperty: view.groupByProperty?.name ?? undefined,
};
return exportedView;
});
}
templateEntities.entities.push(exportedEntity);
});
relationships.forEach((relationship) => {
const parentExists = entities.find((f) => f.name === relationship.parent.name);
const childExists = entities.find((f) => f.name === relationship.child.name);
if (!parentExists || !childExists) {
return;
}
templateEntities.relationships.push({
parent: relationship.parent.name,
child: relationship.child.name,
order: relationship.order ?? 0,
title: relationship.title ?? null,
type: relationship.type ?? "one-to-many",
required: relationship.required ?? false,
cascade: relationship.cascade ?? false,
readOnly: relationship.readOnly ?? false,
hiddenIfEmpty: relationship.hiddenIfEmpty ?? false,
});
});
return templateEntities;
}
export default {
// getEntityFromParams,
getFieldTitle,
getFilters,
getRoutes,
getLayoutBreadcrumbsMenu,
getEntityRoute,
// getAdminNoCodeRoutes,
// getTenantNoCodeRoutes,
exportEntitiesToTemplate,
};
@@ -1,62 +0,0 @@
import { EntityView } from "@toolctrl/db/prisma-browser";
import { ViewFilterCondition } from "~/application/enums/entities/ViewFilterCondition";
import { GridLayoutDto } from "~/application/dtos/layout/GridLayoutDto";
function getCondition(condition: string) {
switch (condition) {
case "equals":
return ViewFilterCondition.equals;
case "contains":
return ViewFilterCondition.contains;
case "lt":
return ViewFilterCondition.lt;
case "lte":
return ViewFilterCondition.lte;
case "gt":
return ViewFilterCondition.gt;
case "gte":
return ViewFilterCondition.gte;
case "startsWith":
return ViewFilterCondition.startsWith;
case "endsWith":
return ViewFilterCondition.endsWith;
case "in":
return ViewFilterCondition.in;
case "notIn":
return ViewFilterCondition.notIn;
default:
return ViewFilterCondition.equals;
}
}
function getGridLayout(view: EntityView | null): GridLayoutDto {
const layout: GridLayoutDto = {
columns: view?.gridColumns ?? 5,
sm: view?.gridColumnsSm ?? 2,
md: view?.gridColumnsMd ?? 3,
lg: view?.gridColumnsLg ?? 4,
xl: view?.gridColumnsXl ?? 5,
xl2: view?.gridColumns2xl ?? 6,
gap: (view?.gridGap ?? "sm") as "xs" | "sm" | "md" | "lg" | "xl",
};
return layout;
}
function getType(view: EntityView): "default" | "tenant" | "user" | "system" {
if (view.isSystem) {
return "system";
} else if (view.tenantId && !view.userId) {
return "tenant";
} else if (view.tenantId && view.userId) {
return "user";
} else if (!view.tenantId && !view.userId) {
return "default";
}
return "default";
}
export default {
getCondition,
getGridLayout,
getType,
};
@@ -1,4 +1,4 @@
import { EmailAttachment } from "@toolctrl/db/prisma-browser";
import { EmailAttachment } from "@hivegrid/db/prisma-browser";
import { MediaDto } from "~/application/dtos/entities/MediaDto";
export function getAttachmentToMedia(attachment: EmailAttachment): MediaDto {
@@ -1,160 +0,0 @@
import { TFunction } from "i18next";
import EditIcon from "~/components/ui/icons/crud/EditIcon";
import PrototypeIcon from "~/components/ui/icons/crud/PrototypeIcon";
import TagsIcon from "~/components/ui/icons/crud/TagsIcon";
import UploadIcon from "~/components/ui/icons/crud/UploadIcon";
import DownloadIcon from "~/components/ui/icons/DownloadIcon";
import ListIcon from "~/components/ui/icons/entities/ListIcon";
import PlusIcon from "~/components/ui/icons/PlusIcon";
import ShareIcon from "~/components/ui/icons/ShareIcon";
import { EntityWithDetails } from "../db/entities/entities.db.server";
import { RowWithDetails } from "../db/entities/rows.db.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
export type NoCodeEntityViewsDto = {
title: string;
description: string;
views: {
name: string;
description: string;
href?: string;
error?: string;
reloadDocument?: boolean;
icon?: React.ReactNode;
underConstruction?: boolean;
enterprise?: boolean;
}[];
};
function getBlockPreviews({ t, entities }: { t: TFunction; entities: EntityWithDetails[] }) {
const cruds: NoCodeEntityViewsDto = {
title: t("models.entity.noCode.previews.blocks.crud.title"),
description: t("models.entity.noCode.previews.blocks.crud.description"),
views: [],
};
entities.forEach((entity) => {
cruds.views.push({
name: t(entity.title),
description: t("models.entity.noCode.previews.blocks.crud.entityDescription"),
href: adminPath(`entities/${entity.slug}/no-code`, { mode: "host-aware" }),
// icon: <PlusIcon className="mx-auto h-4 w-4 text-foreground" />,
});
});
const previews: NoCodeEntityViewsDto[] = [
cruds,
{
title: t("models.entity.noCode.previews.blocks.stats.title"),
description: t("models.entity.noCode.previews.blocks.stats.description"),
views: [
{
name: t("models.entity.noCode.previews.blocks.stats.count.name"),
description: t("models.entity.noCode.previews.blocks.stats.count.description"),
href: "stats/count",
},
],
},
{
title: t("models.entity.noCode.previews.blocks.lists.title"),
description: t("models.entity.noCode.previews.blocks.lists.description"),
views: [
{
name: t("models.entity.noCode.previews.blocks.lists.tasks.name"),
description: t("models.entity.noCode.previews.blocks.lists.tasks.description"),
href: "lists/tasks",
},
{
name: t("models.entity.noCode.previews.blocks.lists.myRequests.name"),
description: t("models.entity.noCode.previews.blocks.lists.myRequests.description"),
underConstruction: true,
},
],
},
];
return previews;
}
function getEntityPreviews({ t, entity, rows }: { t: TFunction; entity: EntityWithDetails; rows: RowWithDetails[] }) {
const previews: NoCodeEntityViewsDto[] = [
{
title: t("models.entity.noCode.previews.entityRoutes.title"),
description: t("models.entity.noCode.previews.entityRoutes.description"),
views: [
{
name: t("models.entity.noCode.previews.entityRoutes.views.allInOne.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.allInOne.description"),
href: `${entity.slug}/all-in-one`,
icon: <ListIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.listDefault.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.listDefault.description"),
href: `${entity.slug}`,
icon: <ListIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.new.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.new.description"),
href: `${entity.slug}/new`,
icon: <PlusIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.overview.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.overview.description"),
href: rows.length > 0 ? `${entity.slug}/${rows[0].id}` : undefined,
error: rows.length === 0 ? t("models.entity.noCode.previews.errors.noRows") : undefined,
icon: <PrototypeIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.edit.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.edit.description"),
href: rows.length > 0 ? `${entity.slug}/${rows[0].id}/edit` : undefined,
error: rows.length === 0 ? t("models.entity.noCode.previews.errors.noRows") : undefined,
icon: <EditIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.import.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.import.description"),
href: `${entity.slug}/import`,
icon: <UploadIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.export.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.export.description"),
href: `${entity.slug}/export`,
reloadDocument: true,
icon: <DownloadIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.tags.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.tags.description"),
href: rows.length > 0 ? `${entity.slug}/${rows[0].id}/tags` : undefined,
error: rows.length === 0 ? t("models.entity.noCode.previews.errors.noRows") : undefined,
reloadDocument: true,
icon: <TagsIcon className="text-foreground mx-auto h-4 w-4" />,
},
{
name: t("models.entity.noCode.previews.entityRoutes.views.share.name"),
description: t("models.entity.noCode.previews.entityRoutes.views.share.description"),
href: rows.length > 0 ? `${entity.slug}/${rows[0].id}/share` : undefined,
error: rows.length === 0 ? t("models.entity.noCode.previews.errors.noRows") : undefined,
reloadDocument: true,
icon: <ShareIcon className="text-foreground mx-auto h-4 w-4" />,
},
],
},
];
if (!entity.isAutogenerated || entity.type === "system") {
previews.forEach((preview) => {
preview.views.forEach((view) => {
view.error = t("models.entity.noCode.previews.errors.notAutogenerated");
});
});
}
return previews;
}
export default {
getBlockPreviews,
getEntityPreviews,
};
@@ -1,22 +1,5 @@
import { Entity } from "@toolctrl/db/prisma-browser";
import { AppOrAdminData } from "../data/useAppOrAdminData";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { RowPermissionsWithDetails } from "../db/permissions/rowPermissions.db.server";
import { t as i18nT } from "i18next";
export function getEntityPermissions(entity: Entity): { name: string; description: string }[] {
return [
{ name: getEntityPermission(entity, "view"), description: i18nT("admin.permissions.entities.viewPage", { entity: entity.name }) },
{ name: getEntityPermission(entity, "read"), description: i18nT("admin.permissions.entities.readRecords", { entity: entity.name }) },
{ name: getEntityPermission(entity, "create"), description: i18nT("admin.permissions.entities.createRecord", { entity: entity.name }) },
{ name: getEntityPermission(entity, "update"), description: i18nT("admin.permissions.entities.updateRecord", { entity: entity.name }) },
{ name: getEntityPermission(entity, "delete"), description: i18nT("admin.permissions.entities.deleteRecord", { entity: entity.name }) },
];
}
export function getEntityPermission(entity: { name: string }, permission: "view" | "read" | "create" | "update" | "delete"): DefaultPermission {
return `entity.${entity.name}.${permission}` as DefaultPermission;
}
export function getUserHasPermission(appOrAdminData: AppOrAdminData, permission: DefaultPermission) {
if (appOrAdminData.isSuperAdmin) {
@@ -25,47 +8,5 @@ export function getUserHasPermission(appOrAdminData: AppOrAdminData, permission:
if (appOrAdminData?.permissions === undefined) {
return false;
}
if (permission.startsWith("entity.")) {
return appOrAdminData.permissions.includes(permission);
}
return appOrAdminData.permissions.includes(permission);
}
export function getRowPermissionsObjects(permissions: RowPermissionsWithDetails[]) {
return permissions
.filter((f) => f !== null)
.map((item) => {
return {
tenant: item.tenant ? { id: item.tenant.id, name: item.tenant.name } : null,
role: item.role ? { id: item.role.id, name: item.role.name } : null,
group: item.group ? { id: item.group.id, name: item.group.name } : null,
user: item.user ? { id: item.user.id, email: item.user.email } : null,
};
})
.filter((f) => f !== null);
}
export function getRowPermissionsDescription(
permissions: {
tenant: { id: string; name: string } | null;
role: { id: string; name: string } | null;
group: { id: string; name: string } | null;
user: { id: string; email: string } | null;
}[]
) {
return permissions
.filter((f) => f !== null)
.map((item) => {
if (item.tenant) {
return `Account '${item.tenant.name}'`;
} else if (item.role) {
return `Role '${item.role.name}'`;
} else if (item.group) {
return `Group '${item.group.name}'`;
} else if (item.user) {
return `User '${item.user.email}'`;
}
return "";
})
.filter((f) => f !== null);
}
@@ -1,25 +0,0 @@
import { describe, expect, it } from "vitest";
import type { TFunction } from "i18next";
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
import PropertyAttributeHelper from "./PropertyAttributeHelper";
describe("PropertyAttributeHelper", () => {
it("localizes visible property attribute option labels when a translator is provided", () => {
const t = (key: string) =>
({
"formats.boolean.yesNo": "Ja/Nein",
"formats.boolean.trueFalse": "Wahr/Falsch",
"formats.boolean.enabledDisabled": "Aktiviert/Deaktiviert",
"formats.boolean.onOff": "An/Aus",
"formats.boolean.activeInactive": "Aktiv/Inaktiv",
})[key] ?? key;
expect(PropertyAttributeHelper.getPropertyAttributeOptions(PropertyAttributeName.FormatBoolean, t as unknown as TFunction)).toEqual([
{ name: "Ja/Nein", value: "yesNo", labelKey: "formats.boolean.yesNo" },
{ name: "Wahr/Falsch", value: "trueFalse", labelKey: "formats.boolean.trueFalse" },
{ name: "Aktiviert/Deaktiviert", value: "enabledDisabled", labelKey: "formats.boolean.enabledDisabled" },
{ name: "An/Aus", value: "onOff", labelKey: "formats.boolean.onOff" },
{ name: "Aktiv/Inaktiv", value: "activeInactive", labelKey: "formats.boolean.activeInactive" },
]);
});
});
@@ -1,215 +0,0 @@
import { TFunction } from "i18next";
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { PropertyWithDetails } from "../db/entities/entities.db.server";
import { BooleanFormats } from "../shared/BooleanUtils";
import { DateFormats } from "../shared/DateUtils";
import { NumberFormats } from "../shared/NumberUtils";
import { SeparatorFormats } from "../shared/SeparatorUtils";
import { SelectOptionsFormats } from "../shared/SelectOptionsUtils";
type AttributeOption = { name: string; value: string | number | undefined; labelKey?: string };
function localizeOptions<T extends AttributeOption>(options: T[], t?: TFunction) {
if (!t) return options;
return options.map((option) => ({
...option,
name: option.labelKey ? t(option.labelKey) : option.name,
}));
}
function getAttributesByType(type: PropertyType, attributes?: { name: string; value: string | undefined }[]): PropertyAttributeName[] {
const commonAttributes = [
PropertyAttributeName.HintText,
PropertyAttributeName.HelpText,
PropertyAttributeName.Icon,
PropertyAttributeName.Columns,
PropertyAttributeName.Group,
];
switch (type) {
case PropertyType.TEXT:
const editor = attributes?.find((f) => f.name === PropertyAttributeName.Editor);
if (editor?.value === "monaco") {
return [PropertyAttributeName.Editor, PropertyAttributeName.EditorLanguage];
} else if (editor?.value === "wysiwyg") {
return [PropertyAttributeName.Editor, PropertyAttributeName.EditorSize];
}
return [
PropertyAttributeName.DefaultValue,
PropertyAttributeName.Placeholder,
PropertyAttributeName.Min,
PropertyAttributeName.Max,
PropertyAttributeName.Rows,
PropertyAttributeName.Pattern,
PropertyAttributeName.Uppercase,
PropertyAttributeName.Lowercase,
PropertyAttributeName.Password,
PropertyAttributeName.Editor,
...commonAttributes,
];
case PropertyType.NUMBER:
return [
PropertyAttributeName.DefaultValue,
PropertyAttributeName.Placeholder,
PropertyAttributeName.Min,
PropertyAttributeName.Max,
PropertyAttributeName.Step,
PropertyAttributeName.FormatNumber,
...commonAttributes,
];
case PropertyType.DATE:
return [PropertyAttributeName.FormatDate, ...commonAttributes];
case PropertyType.SELECT:
return [PropertyAttributeName.SelectOptions, PropertyAttributeName.DefaultValue, PropertyAttributeName.Placeholder, ...commonAttributes];
case PropertyType.BOOLEAN:
return [PropertyAttributeName.DefaultValue, PropertyAttributeName.FormatBoolean, ...commonAttributes];
case PropertyType.MEDIA:
return [PropertyAttributeName.Min, PropertyAttributeName.Max, PropertyAttributeName.AcceptFileTypes, PropertyAttributeName.MaxSize, ...commonAttributes];
case PropertyType.MULTI_TEXT:
return [PropertyAttributeName.Separator, ...commonAttributes];
case PropertyType.RANGE_NUMBER:
return [PropertyAttributeName.FormatNumber];
case PropertyType.RANGE_DATE:
return [PropertyAttributeName.FormatDate];
default:
return [];
}
}
function getAttributeTitle(t: TFunction, name: PropertyAttributeName) {
switch (name) {
case PropertyAttributeName.HintText:
return t("models.propertyAttribute.hintText");
case PropertyAttributeName.HelpText:
return t("models.propertyAttribute.helpText");
case PropertyAttributeName.Icon:
return t("models.propertyAttribute.icon");
case PropertyAttributeName.Pattern:
return t("models.propertyAttribute.pattern");
case PropertyAttributeName.Min:
return t("models.propertyAttribute.min");
case PropertyAttributeName.Max:
return t("models.propertyAttribute.max");
case PropertyAttributeName.Step:
return t("models.propertyAttribute.step");
case PropertyAttributeName.Rows:
return t("models.propertyAttribute.rows");
case PropertyAttributeName.DefaultValue:
return t("models.propertyAttribute.defaultValue");
case PropertyAttributeName.Uppercase:
return t("models.propertyAttribute.uppercase");
case PropertyAttributeName.Lowercase:
return t("models.propertyAttribute.lowercase");
case PropertyAttributeName.Placeholder:
return t("models.propertyAttribute.placeholder");
case PropertyAttributeName.AcceptFileTypes:
return t("models.propertyAttribute.acceptFileTypes");
case PropertyAttributeName.MaxSize:
return t("models.propertyAttribute.maxSize");
case PropertyAttributeName.Editor:
return t("models.propertyAttribute.editor");
case PropertyAttributeName.EditorLanguage:
return t("models.propertyAttribute.editorLanguage");
case PropertyAttributeName.EditorSize:
return t("models.propertyAttribute.editorSize");
case PropertyAttributeName.Columns:
return t("models.propertyAttribute.columns");
case PropertyAttributeName.Group:
return t("models.propertyAttribute.group");
case PropertyAttributeName.FormatNumber:
case PropertyAttributeName.FormatDate:
case PropertyAttributeName.FormatBoolean:
return t("models.propertyAttribute.format");
case PropertyAttributeName.Separator:
return t("models.propertyAttribute.separator");
case PropertyAttributeName.SelectOptions:
return t("models.propertyAttribute.selectOptions");
case PropertyAttributeName.Password:
return t("models.propertyAttribute.password");
default:
return t("models.propertyAttribute.unknown");
}
}
function getPropertyAttributeValue(property: PropertyWithDetails, name: PropertyAttributeName) {
const attribute = property.attributes.find((a) => a.name === name);
if (attribute) {
return attribute.value;
}
return undefined;
}
function getPropertyAttributeValue_String(property: PropertyWithDetails, name: PropertyAttributeName) {
return getPropertyAttributeValue(property, name);
}
function getPropertyAttributeValue_Number(property: PropertyWithDetails, name: PropertyAttributeName) {
const value = getPropertyAttributeValue(property, name);
if (value) {
return Number(value);
}
return undefined;
}
function getPropertyAttributeValue_Boolean(property: PropertyWithDetails, name: PropertyAttributeName) {
const value = getPropertyAttributeValue(property, name);
if (value) {
return value === "true";
}
return undefined;
}
function getPropertyAttributeOptions(name: PropertyAttributeName, t?: TFunction) {
if (name === PropertyAttributeName.Editor) {
return localizeOptions(
[
{ name: "Monaco", value: "monaco", labelKey: "formats.editor.monaco" },
{ name: "WYSIWYG", value: "wysiwyg", labelKey: "formats.editor.wysiwyg" },
{ name: "iframe", value: "iframe", labelKey: "formats.editor.iframe" },
],
t
);
} else if (name === PropertyAttributeName.EditorLanguage) {
return localizeOptions(
[
{ name: "Markdown", value: "markdown", labelKey: "formats.editorLanguage.markdown" },
{ name: "TypeScript", value: "typescript", labelKey: "formats.editorLanguage.typescript" },
{ name: "JavaScript", value: "javascript", labelKey: "formats.editorLanguage.javascript" },
{ name: "HTML", value: "html", labelKey: "formats.editorLanguage.html" },
{ name: "CSS", value: "css", labelKey: "formats.editorLanguage.css" },
],
t
);
} else if (name === PropertyAttributeName.EditorSize) {
return localizeOptions(
[
{ name: "Small", value: "sm", labelKey: "formats.editorSize.small" },
{ name: "Medium", value: "md", labelKey: "formats.editorSize.medium" },
{ name: "Large", value: "lg", labelKey: "formats.editorSize.large" },
{ name: "Auto", value: "auto", labelKey: "formats.editorSize.auto" },
{ name: "Screen", value: "screen", labelKey: "formats.editorSize.screen" },
],
t
);
} else if (name === PropertyAttributeName.FormatNumber) {
return localizeOptions(NumberFormats, t);
} else if (name === PropertyAttributeName.FormatDate) {
return localizeOptions(DateFormats, t);
} else if (name === PropertyAttributeName.FormatBoolean) {
return localizeOptions(BooleanFormats, t);
} else if (name === PropertyAttributeName.Separator) {
return localizeOptions(SeparatorFormats, t);
} else if (name === PropertyAttributeName.SelectOptions) {
return localizeOptions(SelectOptionsFormats, t);
}
return [];
}
export default {
getAttributesByType,
getAttributeTitle,
getPropertyAttributeValue_String,
getPropertyAttributeValue_Number,
getPropertyAttributeValue_Boolean,
getPropertyAttributeOptions,
};
@@ -1,232 +0,0 @@
import { Property } from "@toolctrl/db/prisma-browser";
import { TFunction } from "i18next";
import { MediaDto } from "~/application/dtos/entities/MediaDto";
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { TemplateEntityPropertyTypeDto } from "~/modules/templates/EntityTemplateDto";
import { EntityWithProperties, PropertyWithDetails } from "../db/entities/entities.db.server";
import PropertyAttributeHelper from "./PropertyAttributeHelper";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
export const validateProperty = async (name: string, title: string, properties: Property[], property?: Property | null, t?: TFunction) => {
const errors: string[] = [];
if (!property || property?.name !== name) {
const existingName = properties.find((f) => f.name === name);
if (existingName) {
errors.push(
t
? t("models.property.errors.existingName", { name, title: existingName.title })
: `Existing property with name '${name}': ${existingName.title}`
);
}
}
if (!property || property?.title !== title) {
const existingTitle = properties.find((f) => f.title === title);
if (existingTitle) {
errors.push(
t
? t("models.property.errors.existingTitle", { title, existingTitle: existingTitle.title })
: `Existing entity with title '${title}': ${existingTitle.title}`
);
}
}
return errors;
};
export const defaultProperties: {
order: number;
name: string;
title: string;
type: number;
// formula?: string | null;
parentId?: string | null;
isDefault: boolean;
isRequired: boolean;
isHidden: boolean;
isDisplay: boolean;
}[] = [
{
name: "id",
title: "ID",
order: 1,
type: PropertyType.NUMBER,
// options: [],
isDefault: true,
isRequired: false,
isHidden: true,
// formula: undefined,
isDisplay: false,
},
{
name: "folio",
title: "models.row.folio",
order: 2,
type: PropertyType.NUMBER,
// options: [],
isDefault: true,
isRequired: false,
isHidden: true,
// formula: undefined,
isDisplay: false,
},
{
name: "createdAt",
title: "shared.createdAt",
order: 3,
type: PropertyType.DATE,
// options: [],
isDefault: true,
isRequired: false,
isHidden: true,
// formula: undefined,
isDisplay: false,
},
];
export function validatePropertyValue({ t, property, value }: { t?: TFunction; property: PropertyWithDetails; value: any }) {
const max = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max);
const min = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Min);
if (max) {
if (property.type === PropertyType.TEXT) {
if (value.length > max) {
throwError({ t, property, error: `must have less than ${max} characters (${value})` });
}
} else if (property.type === PropertyType.NUMBER) {
if (!!value && Number(value) > max) {
throwError({ t, property, error: `must be less than ${max} (${value})` });
}
}
}
if (min) {
if (property.type === PropertyType.TEXT) {
if (value.length < min) {
throwError({ t, property, error: `must have less than ${min} characters (${value})` });
}
} else if (property.type === PropertyType.NUMBER) {
if (!!value && Number(value) < min) {
throwError({ t, property, error: `must be greater than ${min} (${value})` });
}
}
}
return true;
}
function throwError({ t, property, error }: { t?: TFunction; property: Property; error: string }) {
if (t) {
throw Error(`${t(property.title)}: ${error}`);
}
throw Error(`${property.name}: ${error}`);
}
export function validatePropertyValue_Media({ t, property, media }: { t?: TFunction; property: PropertyWithDetails; media: MediaDto[] }) {
const max = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max);
const min = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Min);
if (property.isRequired && media.length === 0) {
throwError({ t, property, error: `required` });
} else if (max && media.length > max) {
if (max === 1) {
throwError({ t, property, error: `can only have one file` });
} else {
throwError({ t, property, error: `cannot have more than ${max} files` });
}
} else if (min && media.length < min) {
if (min === 1) {
throwError({ t, property, error: `must have at least one file` });
} else {
throwError({ t, property, error: `must have at least ${min} files` });
}
}
return true;
}
export function validatePropertyValue_Multiple({ t, property, multiple }: { t?: TFunction; property: PropertyWithDetails; multiple: RowValueMultipleDto[] }) {
const max = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max);
const min = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Min);
if (property.isRequired && multiple.length === 0) {
throwError({ t, property, error: `required` });
} else if (max && multiple.length > max) {
if (max === 1) {
throwError({ t, property, error: `can only have one` });
} else {
throwError({ t, property, error: `cannot have more than ${max}` });
}
} else if (min && multiple.length < min) {
if (min === 1) {
throwError({ t, property, error: `must have at least one` });
} else {
throwError({ t, property, error: `must have at least ${min}` });
}
}
return true;
}
export function mapToEntityTemplateType(type: PropertyType): TemplateEntityPropertyTypeDto {
switch (type) {
case PropertyType.NUMBER:
return "number";
case PropertyType.TEXT:
return "string";
case PropertyType.DATE:
return "date";
case PropertyType.MEDIA:
return "media";
case PropertyType.SELECT:
return "select";
case PropertyType.BOOLEAN:
return "boolean";
case PropertyType.MULTI_SELECT:
return "multiSelect";
case PropertyType.MULTI_TEXT:
return "multiText";
case PropertyType.RANGE_NUMBER:
return "rangeNumber";
case PropertyType.RANGE_DATE:
return "rangeDate";
case PropertyType.FORMULA:
return "formula";
default:
return "string";
}
}
export enum RowDisplayDefaultProperty {
ID = "default.id",
ENTITY = "default.entity",
TENANT = "default.tenant",
ORDER = "default.order",
FOLIO = "default.folio",
CREATED_AT = "default.createdAt",
CREATED_BY = "default.createdBy",
PERMISSIONS = "default.permissions",
TAGS = "default.tags",
TASKS = "default.tasks",
COMMENTS = "default.comments",
HIDDEN_PARENTS = "default.hiddenParents",
HIDDEN_CHILDREN = "default.hiddenChildren",
}
export const defaultDisplayProperties: { name: string; title: string; position: "before" | "after"; displayedByDefault: boolean }[] = [
{ name: RowDisplayDefaultProperty.ID, title: "ID", position: "before", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.ENTITY, title: "models.row.entity", position: "before", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.TENANT, title: "models.row.tenant", position: "before", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.ORDER, title: "models.row.order", position: "before", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.FOLIO, title: "models.row.folio", position: "before", displayedByDefault: true },
{ name: RowDisplayDefaultProperty.CREATED_AT, title: "models.row.createdAt", position: "after", displayedByDefault: true },
{ name: RowDisplayDefaultProperty.CREATED_BY, title: "models.row.createdBy", position: "after", displayedByDefault: true },
{ name: RowDisplayDefaultProperty.PERMISSIONS, title: "models.row.permissions", position: "after", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.TAGS, title: "models.row.tags", position: "after", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.TASKS, title: "models.row.tasks", position: "after", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.COMMENTS, title: "models.row.comments", position: "after", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.HIDDEN_PARENTS, title: "", position: "after", displayedByDefault: false },
{ name: RowDisplayDefaultProperty.HIDDEN_CHILDREN, title: "", position: "after", displayedByDefault: false },
];
export function getFormProperties({ mode, entity, properties }: { mode: "create" | "edit"; entity: EntityWithProperties; properties?: string[] }) {
let items = entity.properties.filter((f) => !f.isDefault && !f.isHidden && (properties === undefined || properties.includes(f.name)));
if (mode === "create") {
items = items.filter((f) => f.showInCreate);
}
return items;
}
@@ -1,71 +0,0 @@
import { EntityRelationshipWithDetails } from "../db/entities/entityRelationships.db.server";
// function getTopEntities({ entity }: { entity: EntityWithDetails }) {
// return [...entity.parentEntities.filter((f) => f.type !== "one-to-one")];
// }
// function getBottomEntities({ entity }: { entity: EntityWithDetails }) {
// return [...entity.childEntities, ...entity.parentEntities.filter((f) => f.type === "one-to-one")];
// }
function getTitle({ fromEntityId, relationship }: { fromEntityId: string; relationship: EntityRelationshipWithDetails }) {
if (relationship.title) {
return relationship.title;
}
const isParent = relationship.parentId === fromEntityId;
switch (relationship.type) {
case "one-to-one":
return isParent ? relationship.child.title : relationship.parent.title;
case "one-to-many":
return isParent ? relationship.child.titlePlural : relationship.parent.title;
case "many-to-one":
return isParent ? relationship.child.title : relationship.parent.titlePlural;
case "many-to-many":
return isParent ? relationship.child.titlePlural : relationship.parent.titlePlural;
default:
return isParent ? relationship.child.titlePlural : relationship.parent.title;
}
}
function getTitleWithName({ fromEntityId, relationship }: { fromEntityId: string; relationship: EntityRelationshipWithDetails }) {
if (relationship.title) {
return relationship.title;
}
const isParent = relationship.parentId === fromEntityId;
switch (relationship.type) {
case "one-to-one":
return isParent ? `${relationship.child.title} (1)` : `${relationship.parent.title} (1)${relationship.required ? "*" : ""}`;
case "one-to-many":
return isParent ? `${relationship.child.titlePlural} (N)` : `${relationship.parent.title} (1)${relationship.required ? "*" : ""}`;
case "many-to-one":
return isParent ? `${relationship.child.title} (1)${relationship.required ? "*" : ""}` : `${relationship.parent.titlePlural} (N)`;
case "many-to-many":
return isParent ? `${relationship.child.titlePlural} (N)` : `${relationship.parent.titlePlural} (N)${relationship.required ? "*" : ""}`;
default:
return isParent ? `${relationship.child.titlePlural} (N)` : `${relationship.parent.title} (1)${relationship.required ? "*" : ""}`;
}
}
function getInputType({ fromEntityId, relationship }: { fromEntityId: string; relationship: EntityRelationshipWithDetails }): "single-select" | "multi-select" {
const isParent = relationship.parentId === fromEntityId;
switch (relationship.type) {
case "one-to-one":
return "single-select";
case "one-to-many":
return isParent ? "multi-select" : "single-select";
case "many-to-one":
return isParent ? "single-select" : "multi-select";
case "many-to-many":
return "multi-select";
default:
return isParent ? "multi-select" : "single-select";
}
}
export default {
// getTopEntities,
// getBottomEntities,
getTitle,
getTitleWithName,
getInputType,
};
@@ -1,78 +0,0 @@
import { Property } from "@toolctrl/db/prisma-browser";
import { EntityWithDetails } from "../db/entities/entities.db.server";
import { defaultDisplayProperties } from "./PropertyHelper";
function isPropertyVisible(property: Property) {
return !["id"].includes(property.name);
}
function getDefaultEntityColumns(entity: EntityWithDetails) {
let properties: { name: string; title: string; visible: boolean }[] = [];
// first default properties
properties = [
...properties,
...defaultDisplayProperties
.filter((f) => f.position === "before")
.map((p) => {
return { name: p.name, title: p.title, visible: p.displayedByDefault };
}),
];
// properties
const entityProperties = entity.properties
.filter((f) => !f.isDefault)
.map((i) => {
return { name: i.name, title: i.title, visible: true };
});
if (entityProperties.length > 0) {
properties = [...properties, ...entityProperties];
}
// parents
const parents = entity.parentEntities
.filter((f) => !f.hiddenIfEmpty)
.map((i) => {
return { name: "parent." + i.parent.name, title: i.parent.titlePlural, visible: true };
});
if (parents.length > 0) {
properties = [...properties, ...parents];
}
// children
const children = entity.childEntities
.filter((f) => !f.hiddenIfEmpty)
.map((i) => {
return { name: "child." + i.child.name, title: i.child.titlePlural, visible: true };
});
if (children.length > 0) {
properties = [...properties, ...children];
}
const hiddenParents = entity.parentEntities.filter((f) => f.hiddenIfEmpty);
if (hiddenParents.length > 0) {
properties = [...properties, { name: "default.hiddenParents", title: "", visible: true }];
}
const hiddenChildren = entity.childEntities.filter((f) => f.hiddenIfEmpty);
if (hiddenChildren.length > 0) {
properties = [...properties, { name: "default.hiddenChildren", title: "", visible: true }];
}
// last default properties
properties = [
...properties,
...defaultDisplayProperties
.filter((f) => f.position === "after")
.map((p) => {
return { name: p.name, title: p.title, visible: p.displayedByDefault };
}),
];
return properties;
}
export default {
isPropertyVisible,
getDefaultEntityColumns,
};
@@ -1,387 +0,0 @@
import { Fragment } from "react";
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
import { EntityWithDetails, PropertyWithDetails } from "../db/entities/entities.db.server";
import { RowWithDetails } from "../db/entities/rows.db.server";
import DateUtils from "../shared/DateUtils";
import RowHelper from "./RowHelper";
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
import { EntitiesApi } from "../api/.server/EntitiesApi";
import EntityHelper from "./EntityHelper";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import { Colors } from "~/application/enums/shared/Colors";
import { TFunction, i18n as I18nextInstance } from "i18next";
import { RowDisplayDefaultProperty } from "./PropertyHelper";
import DateCell from "~/components/ui/dates/DateCell";
import RowCreatedByCell from "~/components/entities/rows/cells/RowCreatedByCell";
import RowFolioCell from "~/components/entities/rows/cells/RowFolioCell";
import RowTagsCell from "~/components/entities/rows/cells/RowTagsCell";
import RowOrderButtons from "~/components/entities/rows/RowOrderButtons";
import RowRelationshipRow from "~/components/entities/rows/cells/RowRelationshipRow";
import RowRelationshipRowsByEntity from "~/components/entities/rows/cells/RowRelationshipRowsByEntity";
import { translateEntityTitle, translateEntityTitlePlural, translatePropertyTitle } from "~/utils/i18n/translateLabel";
function isColumnVisible(columns?: ColumnDto[], name?: string) {
if (!columns) {
return true;
}
const column = columns?.find((f) => f.name === name);
if (!columns || !column) {
return false;
}
return column.visible;
}
function displayTenant(t: TFunction): RowHeaderDisplayDto<RowWithDetails> {
return {
name: RowDisplayDefaultProperty.TENANT,
title: "models.tenant.object",
value: (item) => <div>{item.tenant === null ? <div className="italic">{t("shared.admin")}</div> : <div>{item.tenant.name}</div>}</div>,
// href: (item) => item.tenant?.id ?? "",
breakpoint: "sm",
};
}
function displayFolio(entity: EntityWithDetails, routes?: EntitiesApi.Routes, onClick?: (item: RowWithDetails) => void): RowHeaderDisplayDto<RowWithDetails> {
return {
name: RowDisplayDefaultProperty.FOLIO,
title: "models.row.folio",
value: (item) => (
<RowFolioCell
prefix={entity.prefix}
folio={item.folio}
href={routes && onClick === undefined ? EntityHelper.getRoutes({ routes, entity, item })?.overview : undefined}
onClick={onClick !== undefined ? () => onClick(item) : undefined}
/>
),
// breakpoint: "sm",
sortable: true,
};
}
function displayOrder(): RowHeaderDisplayDto<RowWithDetails> {
return {
name: RowDisplayDefaultProperty.ORDER,
title: "",
className: "w-12",
value: (item) => <RowOrderButtons id={item.id} order={item.order} />,
};
}
function displayTags(): RowHeaderDisplayDto<RowWithDetails> {
return {
name: RowDisplayDefaultProperty.TAGS,
title: "models.tag.plural",
value: (item) => <RowTagsCell items={item.tags} />,
breakpoint: "sm",
sortable: true,
};
}
function translatedEntityTitleKey(
t: TFunction,
i18n: Pick<I18nextInstance, "exists"> | null | undefined,
entity: { name: string; title?: string | null }
): string {
const key = `models.${entity.name}.object`;
return i18n?.exists(key) ? key : translateEntityTitle(t, i18n, entity);
}
function translatedEntityTitlePluralKey(
t: TFunction,
i18n: Pick<I18nextInstance, "exists"> | null | undefined,
entity: { name: string; titlePlural?: string | null }
): string {
const key = `models.${entity.name}.plural`;
return i18n?.exists(key) ? key : translateEntityTitlePlural(t, i18n, entity);
}
function translatedPropertyTitleKey(
t: TFunction,
i18n: Pick<I18nextInstance, "exists"> | null | undefined,
entityName: string,
property: { name: string; title?: string | null }
): string {
const key = `models.${entityName}.${property.name}`;
return i18n?.exists(key) ? key : translatePropertyTitle(t, i18n, entityName, property);
}
function displayProperty(
entity: EntityWithDetails,
property: PropertyWithDetails,
i18n: Pick<I18nextInstance, "exists"> | null | undefined,
t: TFunction,
layout?: string
): RowHeaderDisplayDto<RowWithDetails> {
return {
name: property.name,
title: translatedPropertyTitleKey(t, i18n, entity.name, property),
value: (item) => RowHelper.getPropertyValue({ entity, item, property }),
formattedValue: (item) => <div className="max-w-sm truncate">{RowHelper.getCellValue({ entity, property, item })}</div>,
};
}
function displayCreatedAt(): RowHeaderDisplayDto<RowWithDetails> {
return {
name: RowDisplayDefaultProperty.CREATED_AT,
title: "shared.createdAt",
value: (item) => DateUtils.dateAgo(item.createdAt),
formattedValue: (item) => <DateCell date={item.createdAt} />,
className: "text-muted-foreground text-xs",
breakpoint: "sm",
};
}
function displayCreatedBy(): RowHeaderDisplayDto<RowWithDetails> {
return {
name: RowDisplayDefaultProperty.CREATED_BY,
title: "shared.createdBy",
value: (item) => <RowCreatedByCell user={item.createdByUser} apiKey={item.createdByApiKey} />,
className: "text-muted-foreground text-xs",
breakpoint: "sm",
};
}
function getDisplayedHeaders({
entity,
columns,
layout,
allEntities,
routes,
onFolioClick,
onEditClick,
onRelatedRowClick,
t,
i18n,
}: {
entity: EntityWithDetails;
columns?: ColumnDto[];
layout?: string;
allEntities: EntityWithDetails[];
routes?: EntitiesApi.Routes;
onFolioClick?: (item: RowWithDetails) => void;
onEditClick?: (item: RowWithDetails) => void;
onRelatedRowClick?: (item: RowWithDetails) => void;
t: TFunction;
i18n?: Pick<I18nextInstance, "exists"> | null;
}): RowHeaderDisplayDto<RowWithDetails>[] {
let headers: RowHeaderDisplayDto<RowWithDetails>[] = [];
if (columns && isColumnVisible(columns, RowDisplayDefaultProperty.ID)) {
headers.push({
name: RowDisplayDefaultProperty.ID,
title: "ID",
value: (item) => (
<div>
{onEditClick !== undefined ? (
<button
type="button"
onClick={() => onEditClick(item)}
className="focus:bg-secondary/90 hover:border-border rounded-md border-b border-dashed border-transparent"
>
{item.id}
</button>
) : (
<div>{item.id}</div>
)}
</div>
),
href: (item) => (onEditClick === undefined ? item.id : undefined),
breakpoint: "sm",
});
}
if (columns && isColumnVisible(columns, RowDisplayDefaultProperty.ENTITY)) {
headers.push({
name: RowDisplayDefaultProperty.ENTITY,
title: "models.row.entity",
value: () => translateEntityTitle(t, i18n, entity),
});
}
if (columns && isColumnVisible(columns, RowDisplayDefaultProperty.TENANT)) {
headers.push(displayTenant(t));
}
if (columns && isColumnVisible(columns, RowDisplayDefaultProperty.ORDER) && layout === "table") {
headers.push(displayOrder());
}
if (isColumnVisible(columns, RowDisplayDefaultProperty.FOLIO)) {
headers.push(displayFolio(entity, routes, onFolioClick));
}
entity.properties
.filter((f) => !f.isHidden && isColumnVisible(columns, f.name))
.forEach((property) => {
headers.push(displayProperty(entity, property, i18n, t, layout));
});
entity.parentEntities
.filter((f) => !f.hiddenIfEmpty)
.forEach((relationship) => {
const parentEntity = allEntities.find((f) => f.id === relationship.parentId);
if (parentEntity && isColumnVisible(columns, `parent.${parentEntity.name}`)) {
headers.push({
name: `parent.${parentEntity.name}`,
title: translatedEntityTitleKey(t, i18n, parentEntity),
value: (item) => (
<div className="flex max-w-xs items-center space-x-2 overflow-x-auto">
{!item.parentRows?.length || item.parentRows.length === 0 ? (
<div className="text-muted-foreground px-1 pt-1 pb-0.5 text-center text-sm italic">{t("shared.none")}</div>
) : (
<Fragment>
{item.parentRows
?.filter((f) => f.relationshipId === relationship.id)
.map(({ parent }) => {
return (
<Fragment key={parent.id}>
<RowRelationshipRow
entity={parentEntity}
item={parent}
onRelatedRowClick={onRelatedRowClick ? () => onRelatedRowClick(item) : undefined}
routes={routes}
t={t}
/>
</Fragment>
);
})}
</Fragment>
)}
</div>
),
});
}
});
entity.childEntities
.filter((f) => !f.hiddenIfEmpty)
.forEach((relationship) => {
const childEntity = allEntities.find((f) => f.id === relationship.childId);
if (childEntity && isColumnVisible(columns, `child.${childEntity.name}`)) {
headers.push({
name: `child.${childEntity.name}`,
title: translatedEntityTitlePluralKey(t, i18n, childEntity),
value: (item) => (
<ul className="flex max-h-20 max-w-lg flex-col space-y-1 overflow-auto">
{!item.childRows?.length || item.childRows.length === 0 ? (
<div className="text-muted-foreground px-1 pt-1 pb-0.5 text-sm italic">{t("shared.none")}</div>
) : (
<Fragment>
{childEntity.properties.filter((f) => !f.isDefault && f.isDisplay).length === 0 ? (
<div>
<SimpleBadge title={item.childRows?.length.toString()} color={Colors.INDIGO} />
</div>
) : (
<Fragment>
{item.childRows
?.filter((f) => f.relationshipId === relationship.id)
.map(({ child }) => {
return (
<li key={child.id}>
<RowRelationshipRow
entity={childEntity}
item={child}
onRelatedRowClick={onRelatedRowClick ? () => onRelatedRowClick(item) : undefined}
routes={routes}
t={t}
/>
</li>
);
})}
</Fragment>
)}
</Fragment>
)}
</ul>
),
});
}
});
if (isColumnVisible(columns, RowDisplayDefaultProperty.HIDDEN_PARENTS)) {
headers.push({
name: RowDisplayDefaultProperty.HIDDEN_PARENTS,
title: "",
value: (item) => (
<RowRelationshipRowsByEntity
entity={entity}
item={item}
onRelatedRowClick={onRelatedRowClick ? () => onRelatedRowClick(item) : undefined}
routes={routes}
allEntities={allEntities}
type="parents"
/>
),
});
}
if (isColumnVisible(columns, RowDisplayDefaultProperty.HIDDEN_CHILDREN)) {
headers.push({
name: RowDisplayDefaultProperty.HIDDEN_CHILDREN,
title: "",
value: (item) => (
<RowRelationshipRowsByEntity
entity={entity}
item={item}
onRelatedRowClick={onRelatedRowClick ? () => onRelatedRowClick(item) : undefined}
routes={routes}
allEntities={allEntities}
type="children"
/>
),
});
}
if (isColumnVisible(columns, RowDisplayDefaultProperty.CREATED_AT)) {
headers.push(displayCreatedAt());
}
if (isColumnVisible(columns, RowDisplayDefaultProperty.CREATED_BY)) {
headers.push(displayCreatedBy());
}
if (columns && isColumnVisible(columns, RowDisplayDefaultProperty.PERMISSIONS)) {
headers.push({
name: RowDisplayDefaultProperty.PERMISSIONS,
title: "models.row.permissions",
value: () => <div className="text-muted-foreground italic">{t("shared.notAvailable")}</div>,
});
}
if (columns && entity.hasTags && isColumnVisible(columns, RowDisplayDefaultProperty.TAGS)) {
headers.push(displayTags());
}
if (columns && entity.hasTasks && isColumnVisible(columns, RowDisplayDefaultProperty.TASKS)) {
headers.push({
name: RowDisplayDefaultProperty.TASKS,
title: "models.row.tasks",
value: () => <div className="text-muted-foreground italic">{t("shared.notAvailable")}</div>,
});
}
if (columns && entity.hasComments && isColumnVisible(columns, RowDisplayDefaultProperty.COMMENTS)) {
headers.push({
name: RowDisplayDefaultProperty.COMMENTS,
title: "models.row.comments",
value: () => <div className="text-muted-foreground italic">{t("shared.notAvailable")}</div>,
});
}
if (columns && columns.length > 0) {
const newOrder: RowHeaderDisplayDto<RowWithDetails>[] = [];
columns.forEach((column) => {
const header = headers.find((f) => f.name === column.name);
if (header && !newOrder.includes(header)) {
newOrder.push(header);
}
});
headers = newOrder;
}
let nonDefaultHeaders = headers.filter((f) => !f.name?.startsWith("default."));
if (nonDefaultHeaders.length === 1) {
nonDefaultHeaders[0].className = "w-full";
}
return headers;
}
export default {
isColumnVisible,
displayTenant,
displayFolio,
displayProperty,
displayCreatedAt,
displayCreatedBy,
getDisplayedHeaders,
};
@@ -1,23 +0,0 @@
import { adminGetApiKeyById } from "../db/apiKeys.db.server";
import { getUser, UserWithoutPassword } from "../db/users.db.server";
export async function getRowUserOrApiKey(data: { userId?: string | null; apiKeyId?: string | null }) {
// Event: RowCreated
let createdByUser: UserWithoutPassword | null = null;
let createdByApiKey: Awaited<ReturnType<typeof adminGetApiKeyById>> = null;
let user: any = undefined;
let apiKey: any = undefined;
if (data.userId) {
createdByUser = await getUser(data.userId);
user = { id: createdByUser?.id, email: createdByUser?.email ?? "" };
}
if (data.apiKeyId) {
createdByApiKey = await adminGetApiKeyById(data.apiKeyId);
apiKey = { id: createdByApiKey?.id, email: createdByApiKey?.alias ?? "" };
}
return {
user,
apiKey,
};
}
@@ -1,178 +1,9 @@
import { Prisma, Property } from "@toolctrl/db/prisma-browser";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { RowFiltersDto } from "~/application/dtos/data/RowFiltersDto";
import { PropertyType } from "~/application/enums/entities/PropertyType";
const getRowFiltersCondition = (filters?: RowFiltersDto): Prisma.RowWhereInput => {
let where: Prisma.RowWhereInput = {};
if (!filters) {
return {};
}
const OR_CONDITIONS: Prisma.RowWhereInput[] = [];
const AND_CONDITIONS: Prisma.RowWhereInput[] = [];
const parentEntityFilters = filters.properties.filter((f) => f.parentEntity);
parentEntityFilters
.filter((f) => f.value !== undefined)
.forEach((filter) => {
if (filter.value === "null") {
AND_CONDITIONS.push({
parentRows: {
none: {},
},
});
} else {
AND_CONDITIONS.push({
parentRows: {
some: {
parentId: filter.value?.toString(),
},
},
});
}
});
if (filters.query) {
filters.properties
.filter((f) => isPropertyFilterable(f.property))
?.forEach((field) => {
if (field.property) {
OR_CONDITIONS.push(getFilterByDynamicProperty(field.property, filters.query, field.condition));
}
});
}
filters.properties
.filter((f) => f.value && isPropertyFilterable(f.property))
?.forEach((field) => {
if (field.property) {
if (field.match && field.match === "or") {
OR_CONDITIONS.push(getFilterByDynamicProperty(field.property, field.value, field.condition));
} else {
AND_CONDITIONS.push(getFilterByDynamicProperty(field.property, field.value, field.condition));
}
}
});
let whereQuery = {};
let whereFilters = {};
let whereTags = {};
if (OR_CONDITIONS.length > 0) {
whereQuery = {
OR: [...OR_CONDITIONS],
};
}
if (AND_CONDITIONS.length > 0) {
whereFilters = {
AND: [...AND_CONDITIONS],
};
}
if (filters.tags.length > 0) {
whereTags = {
tags: {
some: {
tag: {
value: {
in: filters.tags,
},
},
},
},
};
}
const andConditions: any[] = [];
if (OR_CONDITIONS.length > 0) {
andConditions.push(whereQuery);
}
if (AND_CONDITIONS.length > 0) {
andConditions.push(whereFilters);
}
if (filters.tags.length > 0) {
andConditions.push(whereTags);
}
if (andConditions.length > 0) {
where = {
AND: andConditions,
};
}
return where;
};
function getFilterByDynamicProperty(property: Property, value: string | string[] | null, condition: string | undefined) {
let where: Prisma.RowWhereInput = {};
if (value === null) {
return where;
}
if (property.type === PropertyType.TEXT || property.type === PropertyType.SELECT) {
if (typeof value === "string") {
where = {
values: {
some: {
propertyId: property.id,
textValue: {
[condition ?? "contains"]: value,
mode: "insensitive",
},
},
},
};
} else if (Array.isArray(value)) {
where = {
values: {
some: {
propertyId: property.id,
textValue: {
[condition ?? "in"]: value,
mode: "insensitive",
},
},
},
};
}
} else if (property.type === PropertyType.BOOLEAN) {
if (value !== "false" && value !== "true") {
return {};
}
if (value === "false") {
where = {
values: {
none: {
propertyId: property.id,
booleanValue: {
[condition ?? "equals"]: true,
},
},
},
};
} else {
where = {
values: {
some: {
propertyId: property.id,
booleanValue: {
[condition ?? "equals"]: value === "true",
},
},
},
};
}
}
return where;
}
function isPropertyFilterable(property?: Property) {
if (!property) {
return true;
}
return (
property.type === PropertyType.TEXT ||
property.type === PropertyType.SELECT ||
property.type === PropertyType.BOOLEAN ||
property.type === PropertyType.NUMBER
);
}
// Generic URL-filter → Prisma where-condition builder. The entity-builder-specific
// `getRowFiltersCondition` (Prisma.RowWhereInput) was removed with the row engine
// (R-P6B-β, AD-2); only the generic `FiltersDto`-based condition remains, used by
// the typed DB layers (users/logs/permissions/tenants/apiKeys/events/analytics).
const getFiltersCondition = (filters?: FiltersDto) => {
let where = {};
if (!filters) {
@@ -235,34 +66,6 @@ function getPropertyFilter(name: string, value: string, condition: string | unde
return { [name]: { [condition ?? "contains"]: value } };
}
function getParam_String(urlSearchParams: URLSearchParams | undefined, names: string[]) {
for (let idx = 0; idx < names.length; idx++) {
const text = urlSearchParams?.get(names[idx])?.toString();
if (text) {
return urlSearchParams?.get(names[idx])?.toString();
}
}
}
function getParam_Number(urlSearchParams: URLSearchParams | undefined, names: string[]) {
for (let idx = 0; idx < names.length; idx++) {
const number = getNumber(urlSearchParams?.get(names[idx])?.toString());
if (number) {
return number;
}
}
}
function getNumber(value?: string) {
if (value && !isNaN(Number(value)) && Number(value) < 2147483647) {
return Number(value);
}
}
export default {
getRowFiltersCondition,
getFiltersCondition,
isPropertyFilterable,
getParam_String,
getParam_Number,
};
@@ -1,818 +0,0 @@
import { Entity, Property, RowMedia, RowValue, RowValueMultiple, RowValueRange } from "@toolctrl/db/prisma-browser";
import { Decimal } from "decimal.js";
import { RowValueDto } from "~/application/dtos/entities/RowValueDto";
import { MediaDto } from "~/application/dtos/entities/MediaDto";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { EntityWithDetails, EntityWithProperties, PropertyWithDetails } from "../db/entities/entities.db.server";
import NumberUtils, { NumberFormatType } from "../shared/NumberUtils";
import { validatePropertyValue, validatePropertyValue_Media, validatePropertyValue_Multiple } from "./PropertyHelper";
import i18next, { TFunction, t as i18nT } from "i18next";
import { RowValueWithDetails, RowWithValues } from "../db/entities/rows.db.server";
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
import PropertyOptionValueBadge from "~/components/entities/properties/PropertyOptionValueBadge";
import RowMediaCell from "~/components/entities/rows/cells/RowMediaCell";
import RowBooleanCell, { getBooleanAsStringValue } from "~/components/entities/rows/cells/RowBooleanCell";
import { BooleanFormatType } from "../shared/BooleanUtils";
import RowNumberCell, { getNumberAsStringValue } from "~/components/entities/rows/cells/RowNumberCell";
import RowDateCell, { getDateAsString } from "~/components/entities/rows/cells/RowDateCell";
import { DateFormatType } from "../shared/DateUtils";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import PropertyMultipleValueBadge from "~/components/entities/properties/PropertyMultipleValueBadge";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
import PropertyFormulaValueBadge from "~/components/entities/properties/PropertyFormulaValueBadge";
import FormulaHelpers from "~/modules/formulas/utils/FormulaHelpers";
import { SelectOptionsDisplay } from "../shared/SelectOptionsUtils";
import RowRangeNumberCell from "~/components/entities/rows/cells/RowRangeNumberCell";
import RowRangeDateCell from "~/components/entities/rows/cells/RowRangeDateCell";
import PropertyAttributeHelper from "./PropertyAttributeHelper";
import { translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
import { renderSanitizedMarkdown } from "~/utils/html-sanitizer";
// import RelationshipHelper from "./RelationshipHelper";
const getCellValue = ({ entity, item, property }: { entity: EntityWithDetails; item: RowWithValues; property: PropertyWithDetails }) => {
const value = getPropertyValue({ entity, item, property });
if (property.type === PropertyType.BOOLEAN) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatBoolean)?.value;
return <RowBooleanCell value={value as boolean} format={format as BooleanFormatType} />;
} else if (property.type === PropertyType.SELECT) {
const display = property.attributes.find((f) => f.name === PropertyAttributeName.SelectOptions)?.value as SelectOptionsDisplay;
return <PropertyOptionValueBadge entity={entity} property={property.name} value={value as string} display={display} />;
} else if ([PropertyType.MULTI_SELECT, PropertyType.MULTI_TEXT].includes(property.type)) {
return <PropertyMultipleValueBadge values={value as RowValueMultiple[]} options={property.options} entityName={entity.name} propertyName={property.name} />;
} else if ([PropertyType.RANGE_NUMBER].includes(property.type)) {
const range = value as RowValueRangeDto;
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value as NumberFormatType;
return <RowRangeNumberCell value={range} format={format} currencySymbol={undefined} />;
} else if ([PropertyType.RANGE_DATE].includes(property.type)) {
const range = value as RowValueRangeDto;
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value as DateFormatType;
return <RowRangeDateCell value={range} format={format} />;
} else if ([PropertyType.FORMULA].includes(property.type)) {
return <PropertyFormulaValueBadge property={property} value={value} />;
} else if (property.type === PropertyType.NUMBER) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value;
return <RowNumberCell value={value as number} format={format as NumberFormatType} />;
} else if (property.type === PropertyType.DATE) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value;
return <RowDateCell value={value as Date} format={format as DateFormatType} />;
} else if (property.type === PropertyType.MEDIA) {
const media = value as MediaDto[];
return <RowMediaCell media={media} />;
} else if (property.type === PropertyType.SELECT && value) {
const display = property.attributes.find((f) => f.name === PropertyAttributeName.SelectOptions)?.value as SelectOptionsDisplay;
return <PropertyOptionValueBadge entity={entity} property={property.name} value={value as string} display={display} />;
}
let formattedValue = getFormattedValue(value, property.type);
if (PropertyAttributeHelper.getPropertyAttributeValue_Boolean(property, PropertyAttributeName.Password)) {
formattedValue = "************************";
} else if (PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor) === "wysiwyg") {
return <div className="truncate" dangerouslySetInnerHTML={{ __html: renderSanitizedMarkdown(formattedValue) }} />;
}
return formattedValue;
};
const getValueAsString = ({
entity,
item,
property,
t,
}: {
entity: EntityWithProperties;
item: { id: string; values: RowValueWithDetails[] };
property: PropertyWithDetails;
t?: TFunction;
}) => {
const value = getPropertyValue({ entity, item, property });
if (value === null) {
return null;
}
if (property.type === PropertyType.TEXT) {
if (property.attributes.find((f) => f.name === PropertyAttributeName.Editor)?.value) {
return null;
}
return value as string;
} else if (property.type === PropertyType.BOOLEAN) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatBoolean)?.value;
return getBooleanAsStringValue({ value: value as boolean, format: format as BooleanFormatType, t });
} else if (property.type === PropertyType.SELECT) {
const option = property.options.find((f) => f.value === value);
if (option) {
return t ? translateSelectOptionLabel(t, i18next, entity.name, property.name, option) : (option.name ?? option.value);
}
return value?.toString();
} else if ([PropertyType.MULTI_SELECT, PropertyType.MULTI_TEXT].includes(property.type)) {
return (value as RowValueMultiple[])
.map((v) => {
const option = property.options.find((f) => f.value === v.value);
if (option && t) {
return translateSelectOptionLabel(t, i18next, entity.name, property.name, option);
}
return option?.name ?? v.value;
})
.join(", ");
} else if ([PropertyType.RANGE_NUMBER, PropertyType.RANGE_DATE].includes(property.type)) {
const range = value as RowValueRangeDto;
if (property.type === PropertyType.RANGE_NUMBER) {
const numberFormat = property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value as NumberFormatType;
const numberMin = range?.numberMin ? Number(range?.numberMin) : undefined;
const numberMax = range?.numberMax ? Number(range?.numberMax) : undefined;
const min = getNumberAsStringValue({ value: numberMin, format: numberFormat });
const max = getNumberAsStringValue({ value: numberMax, format: numberFormat });
return `${min} - ${max}`;
} else {
const dateFormat = property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value as DateFormatType;
const min = getDateAsString({ value: range?.dateMin, format: dateFormat });
const max = getDateAsString({ value: range?.dateMax, format: dateFormat });
return `${min} - ${max}`;
}
} else if ([PropertyType.FORMULA].includes(property.type)) {
if (property.formula?.resultAs === "number") {
const numberFormat = property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value as NumberFormatType;
return getNumberAsStringValue({ value: value as number, format: numberFormat });
} else if (property.formula?.resultAs === "boolean") {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatBoolean)?.value;
return getBooleanAsStringValue({ value: value as boolean, format: format as BooleanFormatType, t });
} else if (property.formula?.resultAs === "date") {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value;
return getDateAsString({ value: value as Date, format: format as DateFormatType });
} else {
return value?.toString();
}
} else if (property.type === PropertyType.NUMBER) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value;
return getNumberAsStringValue({ value: value as number, format: format as NumberFormatType });
} else if (property.type === PropertyType.DATE) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value;
return getDateAsString({ value: value as Date, format: format as DateFormatType });
} else if (property.type === PropertyType.MEDIA) {
const media = value as MediaDto[];
function getFileName(name: string) {
let fileName = name;
if (name.includes("/")) {
fileName = name.split("/").pop() ?? name;
}
if (name.includes("\\")) {
fileName = name.split("\\").pop() ?? name;
}
return fileName;
}
return media.map((f) => getFileName(f.title)).join(", ");
}
return "";
};
const getPropertyValue = ({
entity,
item,
property,
propertyName,
}: {
entity: Entity & {
properties: (Property & { formula?: null | { name: string; resultAs: string; calculationTrigger: string } })[];
};
item: { values: RowValueWithDetails[] } | null;
property?: Property & { formula?: null | { name: string; resultAs: string; calculationTrigger: string } };
propertyName?: string;
}): string | number | boolean | RowMedia[] | RowValueMultiple[] | RowValueRange | Date | null => {
if (!property) {
property = entity.properties.find((f) => f.name === propertyName);
}
if (!property) {
return null;
}
const value = item?.values?.find((f) => f?.propertyId === property?.id);
if (value) {
if (property.type === PropertyType.FORMULA) {
const resultAs = FormulaHelpers.getResultAs(property.formula?.resultAs ?? "");
switch (resultAs) {
case "number":
return getDynamicPropertyValue(value, PropertyType.NUMBER);
case "string":
return getDynamicPropertyValue(value, PropertyType.TEXT);
case "date":
return getDynamicPropertyValue(value, PropertyType.DATE);
case "boolean":
return getDynamicPropertyValue(value, PropertyType.BOOLEAN);
default:
return null;
}
} else {
return getDynamicPropertyValue(value, property.type);
}
}
try {
if (!item) {
return null;
}
const object = item[entity?.name as keyof typeof item];
if (object) {
// DEPRECATED
// return object[property.name as keyof typeof object];
}
return null;
} catch {
// eslint-disable-next-line no-console
console.error(`Error getting row value.`, { entity: entity?.name, property: property.name });
return null;
}
};
const getProperties = (entity: EntityWithProperties, item: RowWithValues | null) => {
const customProperties: any = {};
entity.properties
.filter((f) => !f.isHidden)
.forEach((property) => {
if (property.type === PropertyType.MEDIA) {
const media = (getPropertyValue({ entity, item, property }) ?? []) as RowMedia[];
const max = property.attributes.find((f) => f.name === PropertyAttributeName.Max);
if (max?.value && Number(max.value) === 1) {
if (media?.length > 0) {
customProperties[property.name] = media[0].publicUrl ?? media[0].file;
} else {
customProperties[property.name] = "";
}
} else {
customProperties[property.name] = media.map((item) => item.publicUrl ?? item.file);
}
} else {
const value = getPropertyValue({ entity, item, property });
customProperties[property.name] = value;
}
});
return customProperties;
};
function getDynamicPropertyValue(item: RowValue & { media: RowMedia[]; multiple: RowValueMultiple[]; range: RowValueRange | null }, type: PropertyType) {
switch (type) {
case PropertyType.NUMBER:
if (item.numberValue === null || isNaN(Number(item.numberValue))) {
return null;
}
return Number(item.numberValue);
case PropertyType.TEXT:
case PropertyType.SELECT:
// case PropertyType.FORMULA:
return item.textValue;
case PropertyType.DATE:
return item.dateValue;
case PropertyType.BOOLEAN:
return item.booleanValue;
// case PropertyType.ROLE:
// case PropertyType.USER:
case PropertyType.MEDIA:
return item.media;
case PropertyType.MULTI_SELECT:
case PropertyType.MULTI_TEXT:
return item.multiple;
case PropertyType.RANGE_NUMBER:
case PropertyType.RANGE_DATE:
return item.range;
default:
return getRowValueNotSupported();
}
}
function getDetailFormattedValue(entity: EntityWithDetails, item: RowWithValues, property: PropertyWithDetails) {
const value = getPropertyValue({ entity, item, property });
if (value) {
return getFormattedValue(value, property.type);
}
return "";
}
function getFormattedValue(value: any, type: PropertyType, t?: TFunction): string {
switch (type) {
case PropertyType.NUMBER:
if (value === null || isNaN(value)) {
return "";
}
return NumberUtils.decimalFormat(Number(value));
case PropertyType.TEXT:
case PropertyType.SELECT:
// case PropertyType.FORMULA:
return value;
case PropertyType.BOOLEAN:
return getBooleanAsStringValue({ value: Boolean(value), t });
case PropertyType.DATE:
if (!value) {
return "";
}
try {
const date = new Date(value);
return date.toISOString().split("T")[0];
} catch {
return value.toISOString().split("T")[0];
}
// case PropertyType.ROLE:
// case PropertyType.USER:
// case PropertyType.ID:
// return value;
case PropertyType.MEDIA:
return value?.length ?? "0";
default:
return getRowValueNotSupported(t);
}
}
function getRowValueNotSupported(t?: TFunction): string {
return (t ?? i18nT)("models.row.values.notSupported");
}
const getRowFolio = (entity: Entity, item: { folio: number }) => {
return `${entity?.prefix}-${NumberUtils.pad(item?.folio ?? 0, 4)}`.toUpperCase();
};
const getTextDescription = ({
entity,
item,
t,
defaultsToFolio = true,
includeFolio,
}: {
entity: EntityWithDetails;
item: { id: string; folio: number; values: RowValueWithDetails[] };
t?: TFunction;
defaultsToFolio?: boolean;
includeFolio?: boolean;
}): string => {
const descriptions: string[] = [];
entity.properties
.filter((f) => !f.isDefault && f.isDisplay)
.forEach((property) => {
const value = getValueAsString({ entity, item, property, t });
if (value) {
descriptions.push(value);
}
});
if (descriptions.length > 0) {
if (includeFolio) {
descriptions.push(getRowFolio(entity, item));
}
return descriptions.join(" • ");
}
return defaultsToFolio || includeFolio ? getRowFolio(entity, item) : "";
};
const getFirstProperty = ({ entity, item }: { entity: EntityWithDetails; item: RowWithValues }) => {
let displayProperties = entity.properties.sort((a, b) => a.order - b.order).filter((f) => f.isDisplay);
if (displayProperties.length > 0) {
const property = displayProperties[0];
const value = getCellValue({ entity, item, property });
return value;
} else {
return getRowFolio(entity, item);
}
};
const search = (entity: EntityWithDetails, item: RowWithValues, searchInput: string) => {
if (!searchInput || searchInput.trim() === "") {
return true;
}
const properties = entity.properties.filter((f) => !f.isHidden);
for (let idx = 0; idx < properties.length; idx++) {
const property = properties[idx];
const rowValue = getPropertyValue({ entity, item, property });
if (rowValue?.toString()?.toUpperCase().trim().includes(searchInput.toUpperCase().trim())) {
return true;
}
}
if (
getRowFolio(entity, item)?.toUpperCase().includes(searchInput.toUpperCase()) ||
item.createdByUser?.email?.toUpperCase().includes(searchInput.toUpperCase()) ||
(item.createdByUser?.firstName + " " + item.createdByUser?.lastName)?.toUpperCase().includes(searchInput.toUpperCase())
) {
return true;
}
return false;
};
const updateFieldValueTypeArray = (item: RowValueDto, value: any) => {
return getValueFromType(item.property.type, value);
};
const getValueFromType = (type: PropertyType, value: any) => {
switch (type) {
case PropertyType.NUMBER:
if (typeof value === "string") {
return { numberValue: !value ? null : Number(value) };
}
return { numberValue: value ?? null };
case PropertyType.TEXT:
case PropertyType.SELECT:
// case PropertyType.FORMULA:
return { textValue: value };
case PropertyType.DATE:
if (value === null || value === undefined || value === "") {
return { dateValue: undefined };
} else {
return { dateValue: new Date(value) };
}
case PropertyType.BOOLEAN:
return { booleanValue: value === "true" || value === true };
case PropertyType.MEDIA:
return { media: value };
// case PropertyType.USER:
// case PropertyType.ROLE:
// return { idValue: value };
case PropertyType.MULTI_SELECT:
case PropertyType.MULTI_TEXT:
return { multiple: value };
case PropertyType.RANGE_NUMBER:
case PropertyType.RANGE_DATE:
return { range: value };
case PropertyType.FORMULA:
return { textValue: value };
default:
return {};
}
};
export type RowValueCreateDto = {
name: string;
value?: string;
media?: MediaDto[];
multiple?: RowValueMultipleDto[];
range?: RowValueRangeDto;
};
const getRowPropertiesFromForm = ({
t,
entity,
form,
values,
existing,
options,
}: {
t?: TFunction;
entity: EntityWithDetails;
form?: FormData;
values?: RowValueCreateDto[];
existing?: RowWithValues;
options?: {
skipValidation?: boolean;
};
}): {
dynamicProperties: RowValueDto[];
properties: any;
parentRows?: { relationshipId: string; parentId: string }[];
childRows?: { relationshipId: string; childId: string }[];
} => {
const dynamicProperties: RowValueDto[] = [];
entity.properties
.filter((f) => !f.isHidden && !f.isDefault)
.forEach((property) => {
let formValue: FormDataEntryValue | null = null;
let media: MediaDto[] = [];
let multiple: RowValueMultipleDto[] = [];
let range: RowValueRangeDto | null = null;
let name = property.name;
const propertyValue = values?.find((f) => f.name === name);
if ([PropertyType.MEDIA, PropertyType.MULTI_SELECT, PropertyType.MULTI_TEXT].includes(property.type)) {
name += "[]";
}
if ([PropertyType.RANGE_NUMBER, PropertyType.RANGE_DATE].includes(property.type)) {
if (propertyValue?.range) {
range = propertyValue.range;
} else {
const min = getFormDataEntryValue({ name: name + "-min", form, values });
const max = getFormDataEntryValue({ name: name + "-max", form, values });
if (PropertyType.RANGE_NUMBER === property.type) {
range = {
numberMin: Number(min ?? 0),
numberMax: Number(max ?? 0),
dateMin: null,
dateMax: null,
};
} else if (PropertyType.RANGE_DATE === property.type) {
range = {
numberMin: null,
numberMax: null,
dateMin: min ? new Date(min?.toString()) : null,
dateMax: max ? new Date(max?.toString()) : null,
};
}
}
} else if (property.type === PropertyType.MEDIA) {
if (propertyValue?.media) {
media = propertyValue.media;
} else {
media = getFormDataEntryValues({ name, form, values }).map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
}
if (!options?.skipValidation) {
validatePropertyValue_Media({ t, property, media });
}
} else if ([PropertyType.MULTI_SELECT, PropertyType.MULTI_TEXT].includes(property.type)) {
if (propertyValue?.multiple) {
multiple = propertyValue.multiple;
} else {
multiple = getFormDataEntryValues({ name, form, values }).map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
}
if (!options?.skipValidation) {
validatePropertyValue_Multiple({ t, property, multiple });
}
} else {
formValue = getFormDataEntryValue({ name, form, values });
if (!options?.skipValidation) {
if (property.isRequired && !property.isReadOnly && (formValue === null || formValue === undefined || !formValue)) {
if (t) {
throw Error(`${t(property.title)}: required`);
} else {
throw Error(`${property.name}: required`);
}
}
validatePropertyValue({ t, property, value: formValue });
}
}
const value = getValueFromType(property.type, formValue);
value.media = media;
value.multiple = multiple;
value.range = range;
let hasFormValue = formValue !== null && formValue !== undefined;
if (property.type === PropertyType.MEDIA) {
hasFormValue = media.length > 0;
} else if ([PropertyType.MULTI_SELECT, PropertyType.MULTI_TEXT].includes(property.type)) {
hasFormValue = multiple.length > 0;
} else if ([PropertyType.RANGE_NUMBER, PropertyType.RANGE_DATE].includes(property.type)) {
hasFormValue = range !== null;
}
if (!hasFormValue) {
if (!property.isRequired) {
return;
} else if (property.isReadOnly) {
return;
} else if (!property.canUpdate && existing) {
return;
}
}
const existingValue = existing?.values?.find((f) => f.propertyId === property.id);
const rowValue = {
id: existingValue?.id ?? null,
propertyId: property.id,
property: property,
...value,
};
dynamicProperties.push(rowValue);
});
let parentRows: { relationshipId: string; parentId: string }[] | undefined = undefined;
let childRows: { relationshipId: string; childId: string }[] | undefined = undefined;
entity.parentEntities.forEach((relationship) => {
let name = "parents[" + relationship.parent.name + "]";
if (form?.has(name)) {
parentRows = parentRows ?? [];
}
const rowIds = getFormDataEntryValues({ name, form, values }).map((f) => f.toString());
const parentRowIds = rowIds.map((parentId) => {
return { relationshipId: relationship.id, parentId };
});
if (relationship.required && parentRowIds.length === 0) {
throw Error(`${t ? t(relationship.parent.title) : relationship.parent.name}: required`);
}
parentRows = parentRows?.concat(parentRowIds);
// if (relationship.required && parentRowIds.length === 0) {
// throw Error(`${t ? t(RelationshipHelper.getTitle({ fromEntityId: entity.id, relationship })) : relationship.parent.name}: required`);
// }
});
entity.childEntities.forEach((relationship) => {
let name = "children[" + relationship.child.name + "]";
if (form?.has(name)) {
childRows = childRows ?? [];
}
const rowIds = getFormDataEntryValues({ name, form, values }).map((f) => f.toString());
const childRowIds = rowIds.map((childId) => {
return { relationshipId: relationship.id, childId };
});
childRows = childRows?.concat(childRowIds);
});
return {
dynamicProperties,
properties: {},
parentRows,
childRows,
};
};
function getFormDataEntryValue({
name,
form,
values,
}: {
name: string;
form?: FormData;
values?: { name: string; value?: string }[];
}): FormDataEntryValue | null {
if (form) {
return form.get(name);
} else {
return values?.find((f) => f.name === name)?.value ?? null;
}
}
function getFormDataEntryValues({ name, form, values }: { name: string; form?: FormData; values?: { name: string; value?: string }[] }): FormDataEntryValue[] {
let entries: FormDataEntryValue[] = [];
if (form) {
entries = form.getAll(name);
} else {
entries = values?.filter((f) => f.name === name).map((f) => f.value ?? "") ?? [];
}
return entries;
}
const getPropertyDefaultValue = (property: Property): string | number | boolean | RowMedia[] | RowValueMultiple[] | RowValueRange | Date | null => {
switch (property.type) {
case PropertyType.NUMBER:
return 0;
case PropertyType.TEXT:
case PropertyType.SELECT:
return "";
case PropertyType.DATE:
return null;
case PropertyType.BOOLEAN:
return false;
case PropertyType.MEDIA:
return [];
case PropertyType.MULTI_SELECT:
case PropertyType.MULTI_TEXT:
return [];
case PropertyType.RANGE_NUMBER:
case PropertyType.RANGE_DATE:
return {
rowValueId: "",
numberMin: null,
numberMax: null,
dateMin: null,
dateMax: null,
};
case PropertyType.FORMULA:
return null;
default:
return getRowValueNotSupported();
}
};
const getFakePropertyValue = ({ property, idx, t }: { property: PropertyWithDetails; idx: number; t: TFunction }): RowValueWithDetails => {
let sampleText = `${t(property.title)} ${idx}`;
const rowValue: RowValueWithDetails = {
id: "1",
createdAt: new Date(),
updatedAt: null,
rowId: "1",
propertyId: property.id,
textValue: null,
numberValue: null,
dateValue: null,
booleanValue: null,
media: [],
multiple: [],
range: null,
};
switch (property.type) {
case PropertyType.FORMULA: {
const resultAs = FormulaHelpers.getResultAs(property.formula?.resultAs ?? "");
switch (resultAs) {
case "number":
rowValue.numberValue = new Decimal(123);
break;
case "string":
rowValue.textValue = sampleText;
break;
case "date":
rowValue.dateValue = new Date();
break;
case "boolean":
rowValue.booleanValue = true;
break;
default:
break;
}
}
case PropertyType.NUMBER:
rowValue.numberValue = new Decimal(123 * idx);
break;
case PropertyType.TEXT:
if (property.subtype === "email") {
rowValue.textValue = `john.doe.${idx}@company.com`;
} else if (property.subtype === "url") {
rowValue.textValue = "https://www.example.com";
} else if (property.subtype === "phone") {
rowValue.textValue = "+1 123 456 7890";
} else {
rowValue.textValue = sampleText;
}
break;
case PropertyType.SELECT:
if (property.options.length > 0) {
rowValue.textValue = property.options[0].value;
} else {
rowValue.textValue = sampleText;
}
break;
case PropertyType.DATE:
rowValue.dateValue = new Date();
break;
case PropertyType.BOOLEAN:
rowValue.booleanValue = true;
break;
case PropertyType.MEDIA:
const media: RowMedia[] = [
{
id: "1",
rowValueId: "",
file: "",
type: "image/png",
name: "Image 1.png",
title: "Image 1",
publicUrl: "https://placehold.co/150",
storageBucket: null,
storageProvider: null,
},
];
rowValue.media = media;
break;
case PropertyType.MULTI_TEXT: {
let multiple: RowValueMultiple[] = [
{ id: "1", rowValueId: "", order: 1, value: sampleText },
{ id: "2", rowValueId: "", order: 2, value: sampleText },
];
rowValue.multiple = multiple;
break;
}
case PropertyType.MULTI_SELECT: {
let multiple: RowValueMultiple[] = [
{ id: "1", rowValueId: "", order: 1, value: sampleText },
{ id: "2", rowValueId: "", order: 2, value: sampleText },
];
if (property.options.length > 0) {
multiple = property.options.map((option, index) => {
return { id: `${index}`, rowValueId: "", order: index, value: option.value };
});
}
rowValue.multiple = multiple;
break;
}
case PropertyType.RANGE_NUMBER:
const rangeNumber = {
rowValueId: "",
numberMin: new Decimal(100),
numberMax: new Decimal(200),
dateMin: null,
dateMax: null,
};
rowValue.range = rangeNumber;
break;
case PropertyType.RANGE_DATE:
const rangeDate = {
rowValueId: "",
numberMin: null,
numberMax: null,
dateMin: new Date(),
dateMax: new Date(),
};
rowValue.range = rangeDate;
break;
}
return rowValue;
};
const getDiff = ({ entity, before, after }: { entity: EntityWithProperties; before: RowWithValues; after: RowWithValues }) => {
const propertiesToCheck = entity.properties.filter((f) => !f.isDefault);
const diff: { [key: string]: { before: any; after: any } } = {};
propertiesToCheck.forEach((property) => {
const beforeValue = getFormattedValue(getPropertyValue({ entity, item: before, property }), property.type);
const afterValue = getFormattedValue(getPropertyValue({ entity, item: after, property }), property.type);
if (beforeValue !== afterValue) {
diff[property.name] = { before: beforeValue, after: afterValue };
}
});
return diff;
};
export default {
getCellValue,
getPropertyValue,
getDetailFormattedValue,
getFormattedValue,
getRowFolio,
search,
updateFieldValueTypeArray,
getValueFromType,
getProperties,
getDynamicPropertyValue,
getRowPropertiesFromForm,
getFirstProperty,
getTextDescription,
getPropertyDefaultValue,
getFakePropertyValue,
getValueAsString,
getDiff,
};
@@ -1,22 +1,13 @@
import { Property } from "@toolctrl/db/prisma-browser";
import { RowFiltersDto } from "~/application/dtos/data/RowFiltersDto";
import { SortedByDto } from "~/application/dtos/data/SortedByDto";
import { EntityWithDetails } from "../db/entities/entities.db.server";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import Constants from "~/application/Constants";
import { EntityViewWithDetails } from "../db/entities/entityViews.db.server";
import { EntityRelationshipWithDetails } from "../db/entities/entityRelationships.db.server";
export function getPaginationFromCurrentUrl(
urlSearchParams: URLSearchParams,
entity?: EntityWithDetails,
entityView?: EntityViewWithDetails | null
): { page: number; pageSize: number; sortedBy: SortedByDto[]; query: string } {
export function getPaginationFromCurrentUrl(urlSearchParams: URLSearchParams): { page: number; pageSize: number; sortedBy: SortedByDto[]; query: string } {
return {
page: getPageFromCurrentUrl(urlSearchParams),
pageSize: getPageSizeFromCurrentUrl(urlSearchParams),
sortedBy: getSortByFromCurrentUrl(urlSearchParams, entity, entityView),
sortedBy: getSortByFromCurrentUrl(urlSearchParams),
query: getSearchQueryFromCurrentUrl(urlSearchParams),
};
}
@@ -38,61 +29,6 @@ export function getFiltersFromCurrentUrl(request: Request, properties: Filterabl
return { query, properties };
}
export function getEntityFiltersFromCurrentUrl(
customRow: boolean,
entity: EntityWithDetails,
urlSearchParams: URLSearchParams,
entityView?: EntityViewWithDetails | null | null
): RowFiltersDto {
const tags: string[] = [];
const properties: {
property?: Property;
name?: string;
value: string | string[] | null;
condition?: string;
match?: "and" | "or";
parentEntity?: EntityRelationshipWithDetails;
}[] = [];
entity.properties.forEach((property) => {
if (urlSearchParams.getAll(property.name).length > 1) {
properties.push({ property, value: urlSearchParams.getAll(property.name) });
} else {
const param = urlSearchParams.get(property.name);
properties.push({ property, value: param ?? null });
}
});
entityView?.filters.forEach((filter) => {
const property = entity.properties.find((f) => f.name === filter.name);
const match = filter.match === "or" ? "or" : "and";
if (property) {
properties.push({ property, value: filter.value ?? null, condition: filter.condition, match });
} else {
properties.push({ name: filter.name, value: filter.value ?? null, condition: filter.condition, match });
}
});
urlSearchParams.getAll("tag").forEach((tag) => {
tags.push(tag);
});
entity.parentEntities.forEach((parentRel) => {
const id = urlSearchParams.get(`${parentRel.parent.name}_id`);
if (id) {
properties.push({
name: `${parentRel.parent.name}_id`,
value: id,
parentEntity: parentRel,
});
}
});
const query = urlSearchParams.get("q");
// console.log({ tags });
return { customRow, entity, properties, query, tags };
}
function getPageFromCurrentUrl(urlSearchParams: URLSearchParams): number {
const paramsPage = urlSearchParams.get("page");
const page = paramsPage ? Number(paramsPage) : 1;
@@ -118,7 +54,7 @@ function getSearchQueryFromCurrentUrl(urlSearchParams: URLSearchParams): string
return urlSearchParams.get("q")?.toString() ?? "";
}
function getSortByFromCurrentUrl(urlSearchParams: URLSearchParams, entity?: EntityWithDetails, entityView?: EntityViewWithDetails | null): SortedByDto[] {
function getSortByFromCurrentUrl(urlSearchParams: URLSearchParams): SortedByDto[] {
let sorts = urlSearchParams.get("sort")?.toString().split(",") ?? [];
return sorts.map((sort) => {
let direction: "asc" | "desc" = "asc";
@@ -131,8 +67,7 @@ function getSortByFromCurrentUrl(urlSearchParams: URLSearchParams, entity?: Enti
}
}
const sortName = sort.replace("-", "").replace("+", "");
const property = entity?.properties.find((p) => p.name === sortName);
return { entity, name: sortName, direction, property };
return { name: sortName, direction };
});
}
@@ -1,121 +0,0 @@
import { RowValueMultiple, RowValueRange } from "@toolctrl/db/prisma-browser";
import { Decimal } from "decimal.js";
import { PropertyWithDetails } from "../db/entities/entities.db.server";
import { PropertyType } from "~/application/enums/entities/PropertyType";
function getString({ urlSearchParams, property }: { urlSearchParams: URLSearchParams; property: PropertyWithDetails }): string | undefined {
const value = urlSearchParams.get(property.name);
if (value === null) {
return undefined;
}
return value;
}
function getNumber({ urlSearchParams, property }: { urlSearchParams: URLSearchParams; property: PropertyWithDetails }): number | undefined {
const value = urlSearchParams.get(property.name);
if (value === null) {
return undefined;
}
// see if it's a number
const numberValue = Number(value);
if (isNaN(numberValue)) {
return undefined;
}
return numberValue;
}
function getBoolean({ urlSearchParams, property }: { urlSearchParams: URLSearchParams; property: PropertyWithDetails }): boolean | undefined {
const value = urlSearchParams.get(property.name);
if (value === null) {
return undefined;
}
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return undefined;
}
function getDate({ urlSearchParams, property }: { urlSearchParams: URLSearchParams; property: PropertyWithDetails }): Date | undefined {
const value = urlSearchParams.get(property.name);
if (value === null) {
return undefined;
}
try {
const dateValue = new Date(value);
if (isNaN(dateValue.getTime())) {
return undefined;
}
return dateValue;
} catch (error) {
return undefined;
}
}
function getMultiple({ urlSearchParams, property }: { urlSearchParams: URLSearchParams; property: PropertyWithDetails }): RowValueMultiple[] | undefined {
const values = urlSearchParams.getAll(property.name);
if (values.length === 0) {
return undefined;
}
return values.map((value, idx) => {
return {
id: "",
rowValueId: "",
order: idx,
value,
};
});
}
function getRange({ urlSearchParams, property }: { urlSearchParams: URLSearchParams; property: PropertyWithDetails }): RowValueRange | undefined {
if (property.type === PropertyType.RANGE_NUMBER) {
const min = urlSearchParams.get(`${property.name}_min`);
const max = urlSearchParams.get(`${property.name}_max`);
if (min === null || max === null) {
return undefined;
}
let numberMin: Decimal = new Decimal(0);
let numberMax: Decimal = new Decimal(0);
try {
numberMin = new Decimal(min);
} catch (error) {}
try {
numberMax = new Decimal(max);
} catch (error) {}
return {
rowValueId: "",
numberMin,
numberMax,
dateMin: null,
dateMax: null,
};
} else if (property.type === PropertyType.RANGE_DATE) {
const min = urlSearchParams.get(`${property.name}_min`);
const max = urlSearchParams.get(`${property.name}_max`);
if (min === null || max === null) {
return undefined;
}
const dateMin = new Date(min);
const dateMax = new Date(max);
return {
rowValueId: "",
numberMin: null,
numberMax: null,
dateMin,
dateMax,
};
} else {
return undefined;
}
}
export default {
getString,
getNumber,
getBoolean,
getDate,
getMultiple,
getRange,
};
@@ -1,174 +0,0 @@
import { Entity, Property, RowMedia, RowValueMultiple } from "@toolctrl/db/prisma-browser";
import { RowValueWithDetails } from "../db/entities/rows.db.server";
import RowHelper from "./RowHelper";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
import { PropertyWithDetails } from "../db/entities/entities.db.server";
function getText({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): string | undefined {
const value = RowHelper.getPropertyValue({ entity, item: row, propertyName: name });
return value?.toString();
}
function getBoolean({ entity, row, name }: { entity: Entity & { properties: Property[] }; row: { values: RowValueWithDetails[] }; name: string }): boolean {
return Boolean(RowHelper.getPropertyValue({ entity, item: row, propertyName: name }));
}
function getNumber({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): number | undefined {
const value = RowHelper.getPropertyValue({ entity, item: row, propertyName: name });
return value !== undefined && value !== null ? Number(value) : undefined;
}
function getDate({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): Date | undefined {
const value = RowHelper.getPropertyValue({ entity, item: row, propertyName: name });
if (!value) {
return undefined;
}
return value as Date;
}
function getMedia({ entity, row, name }: { entity: Entity & { properties: Property[] }; row: { values: RowValueWithDetails[] }; name: string }): RowMedia[] {
const value = (RowHelper.getPropertyValue({ entity, item: row, propertyName: name }) ?? []) as RowMedia[];
return value;
}
function getFirstMedia({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): RowMedia | undefined {
const media = getMedia({ entity, row, name });
const value = media?.length > 0 ? media[0] : undefined;
return value;
}
function getFirstMediaFile({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): string | undefined {
const media = getFirstMedia({ entity, row, name });
if (!media) {
return undefined;
}
const value = media?.publicUrl ?? media?.file;
return value;
}
function getSelected({
entity,
row,
name,
}: {
entity: Entity & { properties: PropertyWithDetails[] };
row: { values: RowValueWithDetails[] };
name: string;
}): { value: string; name: string | null; color: number } | undefined {
const value = RowHelper.getPropertyValue({ entity, item: row, propertyName: name });
if (!value) {
return undefined;
}
const option = entity.properties.find((i) => i.name === name)?.options.find((i) => i.value === value);
if (option) {
return { name: option.name, value: option.value, color: option.color };
} else {
return { name: null, value: value.toString(), color: 0 };
}
}
function getMultiple({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): RowValueMultipleDto[] {
const value = RowHelper.getPropertyValue({ entity, item: row, propertyName: name });
if (!value) {
return [];
}
let multiple = value as RowValueMultiple[];
return multiple ?? [];
}
function getNumberRange({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): RowValueRangeDto {
const value = RowHelper.getPropertyValue({ entity, item: row, propertyName: name });
let range = value as RowValueRangeDto;
if (!range) {
range = {
numberMin: null,
numberMax: null,
dateMin: null,
dateMax: null,
};
}
return range;
}
function getDateRange({
entity,
row,
name,
}: {
entity: Entity & { properties: Property[] };
row: { values: RowValueWithDetails[] };
name: string;
}): RowValueRangeDto {
const value = RowHelper.getPropertyValue({ entity, item: row, propertyName: name });
let range = value as RowValueRangeDto;
if (!range) {
range = {
numberMin: null,
numberMax: null,
dateMin: null,
dateMax: null,
};
}
return range;
}
export default {
getText,
getBoolean,
getNumber,
getDate,
getMedia,
getFirstMedia,
getFirstMediaFile,
getSelected,
getMultiple,
getNumberRange,
getDateRange,
};
@@ -1,79 +0,0 @@
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { PropertyWithDetails } from "../db/entities/entities.db.server";
import { RowValueWithDetails } from "../db/entities/rows.db.server";
import RowHelper from "./RowHelper";
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
import { MediaDto } from "~/application/dtos/entities/MediaDto";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
import PropertyFormulaValueBadge from "~/components/entities/properties/PropertyFormulaValueBadge";
import PropertyMultipleValueBadge from "~/components/entities/properties/PropertyMultipleValueBadge";
import RowBooleanCell from "~/components/entities/rows/cells/RowBooleanCell";
import RowDateCell from "~/components/entities/rows/cells/RowDateCell";
import RowMediaCell from "~/components/entities/rows/cells/RowMediaCell";
import RowNumberCell from "~/components/entities/rows/cells/RowNumberCell";
import RowRangeDateCell from "~/components/entities/rows/cells/RowRangeDateCell";
import RowRangeNumberCell from "~/components/entities/rows/cells/RowRangeNumberCell";
import { BooleanFormatType } from "../shared/BooleanUtils";
import { DateFormatType } from "../shared/DateUtils";
import { NumberFormatType } from "../shared/NumberUtils";
import { SelectOptionsDisplay } from "../shared/SelectOptionsUtils";
import PropertyAttributeHelper from "./PropertyAttributeHelper";
import { renderSanitizedMarkdown } from "~/utils/html-sanitizer";
import RowSelectedOptionCell from "~/components/entities/rows/cells/RowSelectedOptionCell";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
interface Props {
property: PropertyWithDetails;
value: RowValueWithDetails | null | undefined;
withTitle?: boolean;
}
export default function RowValueUI({ property, value, withTitle }: Props) {
const rowValue = value ? RowHelper.getDynamicPropertyValue(value, property.type) : undefined;
const entityName = (property as PropertyWithDetails & { entity?: { name: string } }).entity?.name;
if (rowValue === null || rowValue === undefined) {
return null;
}
if (property.type === PropertyType.BOOLEAN) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatBoolean)?.value;
return (
<div className="flex items-center space-x-1">
<RowBooleanCell value={rowValue as boolean} format={format as BooleanFormatType} />
{withTitle && <div className="text-xs font-medium">{property.title}</div>}
</div>
);
} else if (property.type === PropertyType.SELECT) {
const display = property.attributes.find((f) => f.name === PropertyAttributeName.SelectOptions)?.value as SelectOptionsDisplay;
return <RowSelectedOptionCell value={rowValue as string} options={property.options ?? []} display={display} entityName={entityName} propertyName={property.name} />;
} else if ([PropertyType.MULTI_SELECT, PropertyType.MULTI_TEXT].includes(property.type)) {
return <PropertyMultipleValueBadge values={rowValue as RowValueMultipleDto[]} options={property.options ?? []} entityName={entityName} propertyName={property.name} />;
} else if ([PropertyType.RANGE_NUMBER].includes(property.type)) {
const range = rowValue as RowValueRangeDto;
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value as NumberFormatType;
return <RowRangeNumberCell value={range} format={format} currencySymbol={undefined} />;
} else if ([PropertyType.RANGE_DATE].includes(property.type)) {
const range = rowValue as RowValueRangeDto;
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value as DateFormatType;
return <RowRangeDateCell value={range} format={format} />;
} else if ([PropertyType.FORMULA].includes(property.type)) {
return <PropertyFormulaValueBadge property={property} value={rowValue} />;
} else if (property.type === PropertyType.NUMBER) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value;
return <RowNumberCell value={rowValue as number} format={format as NumberFormatType} />;
} else if (property.type === PropertyType.DATE) {
const format = property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value;
return <RowDateCell value={rowValue as Date} format={format as DateFormatType} />;
} else if (property.type === PropertyType.MEDIA) {
const media = rowValue as MediaDto[];
return <RowMediaCell media={media} />;
} else if (property.type === PropertyType.SELECT && rowValue) {
const display = property.attributes.find((f) => f.name === PropertyAttributeName.SelectOptions)?.value as SelectOptionsDisplay;
return <RowSelectedOptionCell value={rowValue as string} options={property.options ?? []} display={display} entityName={entityName} propertyName={property.name} />;
}
let formattedValue = RowHelper.getFormattedValue(rowValue, property.type);
if (PropertyAttributeHelper.getPropertyAttributeValue_Boolean(property, PropertyAttributeName.Password)) {
formattedValue = "************************";
} else if (PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor) === "wysiwyg") {
return <div className="truncate" dangerouslySetInnerHTML={{ __html: renderSanitizedMarkdown(formattedValue) }} />;
}
return formattedValue;
}
@@ -37,13 +37,13 @@ async function getPlanFromForm(form: FormData) {
}
if (flatPrice) {
line_items.push({ price: flatPrice.stripeId, quantity });
line_items.push({ price: flatPrice.billingProviderId, quantity });
if (flatPrice.trialDays > 0) {
freeTrialDays = flatPrice.trialDays;
}
}
usageBasedPrices?.forEach((usageBasedPrice) => {
line_items.push({ price: usageBasedPrice.stripeId });
line_items.push({ price: usageBasedPrice.billingProviderId });
});
return {
@@ -1,79 +0,0 @@
import { TFunction } from "i18next";
import type { EntityWithDetails } from "../db/entities/entities.db.server";
import type { UserSimple } from "../db/users.db.server";
import type { TenantWithDetails } from "../db/tenants.db.server";
import TenantHelper from "./TenantHelper";
export type RowAsJson = {
id: string;
entityId: string;
name: string;
data: any;
tenant: TenantWithDetails | null;
};
export interface TemplateValueResultDto {
variable: { [key: string]: string | number };
row?: any;
session: {
user: { firstName: string; lastName: string; email: string; createdAt: Date } | null;
tenant: { [key: string]: any } | null;
};
promptFlow?: {
results: {
[key: number]: string;
};
};
}
function getTemplateValue({
allEntities,
t,
session,
variables,
row,
}: {
allEntities: EntityWithDetails[];
t: TFunction;
session: {
user: UserSimple | null;
tenant: TenantWithDetails | null;
};
variables: {
[key: string]: string | number;
};
row: RowAsJson | undefined;
}): TemplateValueResultDto {
const tenantSettingsEntity = allEntities.find((f) => f.name === "tenantSettings") ?? null;
let object: TemplateValueResultDto = {
variable: {},
row: row ? {} : undefined,
session: {
user: !session.user
? null
: {
firstName: session.user!.firstName,
lastName: session.user!.lastName,
email: session.user!.email,
createdAt: session.user!.createdAt,
},
tenant: !session.tenant ? null : TenantHelper.apiFormat({ tenant: session.tenant, subscriptions: null, tenantSettingsEntity, t }),
},
promptFlow: {
results: [],
},
};
if (Object.keys(variables).length > 0) {
object.variable = variables;
}
if (row) {
object.row = row.data;
}
return object;
}
export default {
getTemplateValue,
};
@@ -1,103 +0,0 @@
import { Prisma } from "@toolctrl/db/prisma-browser";
import type { TenantWithDetails } from "../db/tenants.db.server";
import type { TenantSubscriptionWithDetails } from "../db/tenantSubscriptions.db.server";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import type { EntityWithDetails } from "../db/entities/entities.db.server";
import RowHelper from "./RowHelper";
import { TFunction } from "i18next";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
const tenantCondition = ({ tenantId, includePublic }: { tenantId: string | null; includePublic?: boolean }): Prisma.RowWhereInput => {
if (includePublic) {
return { OR: [{ tenantId }, { permissions: { some: { tenantId } } }, { permissions: { some: { public: true } } }] };
} else {
return { OR: [{ tenantId }, { permissions: { some: { tenantId } } }] };
}
};
function apiFormat({
tenant,
subscriptions,
tenantSettingsEntity,
t,
}: {
tenant: TenantWithDetails;
subscriptions: TenantSubscriptionWithDetails | null;
tenantSettingsEntity: EntityWithDetails | null;
t: TFunction;
}) {
let customRow = undefined;
if (tenantSettingsEntity) {
customRow = RowHelper.getProperties(tenantSettingsEntity, tenant.tenantSettingsRow?.row ?? null);
}
return {
id: tenant.id,
createdAt: tenant.createdAt,
updatedAt: tenant.updatedAt,
slug: tenant.slug,
name: tenant.name,
icon: tenant.icon,
...customRow,
subscription: !subscriptions
? null
: {
id: subscriptions.id,
stripeCustomerId: subscriptions.stripeCustomerId,
products: subscriptions.products.map((f) => {
return {
id: f.id,
product: t(f.subscriptionProduct.title),
quantity: f.quantity,
currentPeriodStart: f.currentPeriodStart,
currentPeriodEnd: f.currentPeriodEnd,
model: PricingModel[f.subscriptionProduct.model],
cancelledAt: f.cancelledAt ?? undefined,
endsAt: f.endsAt ?? undefined,
stripeId: f.stripeSubscriptionId,
prices: f.prices.map((p) => {
return {
id: p.id,
...(p.subscriptionPrice
? {
stripeId: p.subscriptionPrice.stripeId,
type: SubscriptionPriceType[p.subscriptionPrice.type],
billingPeriod: SubscriptionBillingPeriod[p.subscriptionPrice.billingPeriod],
price: Number(p.subscriptionPrice.price),
currency: p.subscriptionPrice.currency,
}
: p.subscriptionUsageBasedPrice
? {
stripeId: p.subscriptionUsageBasedPrice.stripeId,
billingPeriod: SubscriptionBillingPeriod[p.subscriptionUsageBasedPrice.billingPeriod],
currency: p.subscriptionUsageBasedPrice.currency,
unit: p.subscriptionUsageBasedPrice.unit,
unitTitle: t(p.subscriptionUsageBasedPrice.unitTitle),
unitTitlePlural: t(p.subscriptionUsageBasedPrice.unitTitlePlural),
usageType: p.subscriptionUsageBasedPrice.usageType,
aggregateUsage: p.subscriptionUsageBasedPrice.aggregateUsage,
tiersMode: p.subscriptionUsageBasedPrice.tiersMode,
billingScheme: p.subscriptionUsageBasedPrice.billingScheme,
tiers: p.subscriptionUsageBasedPrice.tiers.map((t) => {
return {
id: t.id,
from: Number(t.from),
to: t.to ? Number(t.to) : null,
perUnitPrice: t.perUnitPrice ? Number(t.perUnitPrice) : undefined,
flatFeePrice: t.flatFeePrice ? Number(t.flatFeePrice) : undefined,
};
}),
}
: undefined),
};
}),
};
}),
},
};
}
export default {
tenantCondition,
apiFormat,
};
@@ -1,21 +0,0 @@
const selectSimpleProperties = {
id: true,
order: true,
name: true,
title: true,
titlePlural: true,
active: true,
slug: true,
type: true,
hasApi: true,
showInSidebar: true,
icon: true,
onEdit: true,
};
const selectEntityWithoutIcon = { id: true, name: true, title: true, titlePlural: true, slug: true, onEdit: true };
export default {
selectSimpleProperties,
selectEntityWithoutIcon,
};
@@ -1,10 +0,0 @@
const includeDetails = {
properties: true,
filters: true,
sort: true,
groupByProperty: true,
};
export default {
includeDetails,
};
@@ -1,171 +0,0 @@
import UserModelHelper from "./UserModelHelper";
const includeParentRows = {
parent: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
};
const includeChildRowsNested = {
child: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
parentRows: {
include: {
parent: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
childRows: {
include: {
child: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
},
},
};
const includeRowDetails = {
...UserModelHelper.includeSimpleCreatedByUser,
createdByApiKey: true,
tenant: true,
values: { include: { media: true, multiple: true, range: true } },
tags: { include: { tag: true } },
parentRows: {
include: includeParentRows,
},
childRows: {
include: includeChildRowsNested,
},
permissions: true,
sampleCustomEntity: true,
};
const includeParentRowsNested = {
parent: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
parentRows: {
include: {
parent: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
childRows: {
include: {
child: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
},
},
};
const includeRowDetailsNested = {
...UserModelHelper.includeSimpleCreatedByUser,
createdByApiKey: true,
tenant: true,
values: { include: { media: true, multiple: true, range: true } },
tags: { include: { tag: true } },
parentRows: {
include: includeParentRowsNested,
},
childRows: {
include: includeChildRowsNested,
},
permissions: true,
sampleCustomEntity: true,
};
function createScopedNestedParentRowsInclude(tenantId: string | null) {
return {
where: { parent: { tenantId, deletedAt: null } },
include: {
parent: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
} as const;
}
function createScopedNestedChildRowsInclude(tenantId: string | null) {
return {
where: { child: { tenantId, deletedAt: null } },
include: {
child: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
} as const;
}
function createScopedIncludeRowDetails(tenantId: string | null) {
const scopedNestedParentRows = createScopedNestedParentRowsInclude(tenantId);
const scopedNestedChildRows = createScopedNestedChildRowsInclude(tenantId);
return {
...UserModelHelper.includeSimpleCreatedByUser,
createdByApiKey: true,
tenant: true,
values: { include: { media: true, multiple: true, range: true } },
tags: { include: { tag: true } },
parentRows: {
where: { parent: { tenantId, deletedAt: null } },
include: {
parent: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
parentRows: scopedNestedParentRows,
childRows: scopedNestedChildRows,
},
},
},
},
childRows: {
where: { child: { tenantId, deletedAt: null } },
include: {
child: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
parentRows: scopedNestedParentRows,
childRows: scopedNestedChildRows,
},
},
},
},
permissions: true,
sampleCustomEntity: true,
} as const;
}
export default {
includeRowDetails,
includeRowDetailsNested,
createScopedIncludeRowDetails,
};
@@ -1,4 +1,3 @@
import RowModelHelper from "./RowModelHelper";
import TenantSubscriptionProductModelHelper from "./TenantSubscriptionProductModelHelper";
import UserModelHelper from "./UserModelHelper";
@@ -29,7 +28,6 @@ const includeTenantWithDetails = {
},
},
},
tenantSettingsRow: { include: { row: { include: RowModelHelper.includeRowDetails } } },
types: true,
};
@@ -45,7 +43,6 @@ const includeTenantWithUsage = {
products: { include: { ...TenantSubscriptionProductModelHelper.includeTenantSubscriptionProductDetails } },
},
},
tenantSettingsRow: { include: { row: { include: RowModelHelper.includeRowDetails } } },
types: true,
_count: true,
};
@@ -1,32 +0,0 @@
import { describe, expect, it } from "vitest";
import { readRepoFile } from "~/utils/testing/repoPaths";
describe("row display header i18n guards", () => {
it("keeps row, relationship, and formula labels behind model translation helpers", () => {
const source = [
"apps/web/app/utils/helpers/RowDisplayHeaderHelper.tsx",
"apps/web/app/components/entities/rows/RowsListAndTable.tsx",
"apps/web/app/components/entities/rows/RowCard.tsx",
"apps/web/app/components/entities/rows/RowsRelationships.tsx",
"apps/web/app/components/entities/rows/cells/RowRelationshipRowsByEntity.tsx",
"apps/web/app/components/entities/rows/RowForm.tsx",
"apps/web/app/components/entities/rows/RowValueInput.tsx",
]
.map((file) => readRepoFile(file))
.join("\n");
expect(source).toContain("translatePropertyTitle");
expect(source).toContain("translateEntityTitle");
expect(source).toContain("translateEntityTitlePlural");
expect(source).toContain("translateLabel(t, i18n, header.title)");
expect(source).not.toContain("title: property.title");
expect(source).not.toContain("title: parentEntity.title");
expect(source).not.toContain("title: childEntity.titlePlural");
expect(source).not.toContain("t(entity.title)");
expect(source).not.toContain("t(relationship.parent.title)");
expect(source).not.toContain("t(relationship.child.title)");
expect(source).not.toContain("title={props.property.title}");
expect(source).not.toContain(">Admin<");
expect(source).toContain('t("shared.admin")');
});
});