Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
-30
@@ -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;
|
||||
}
|
||||
-151
@@ -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;
|
||||
}
|
||||
+91
@@ -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");
|
||||
});
|
||||
});
|
||||
+24
-132
@@ -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,
|
||||
};
|
||||
}
|
||||
-65
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
-104
@@ -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,
|
||||
};
|
||||
Reference in new issue
Block a user