Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
+424
@@ -0,0 +1,424 @@
|
||||
import { format } from "date-fns";
|
||||
import { db } from "../../db.server";
|
||||
import { adminGetAllUsersNamesInIds } from "../../db/users.db.server";
|
||||
import DateUtils from "../../shared/DateUtils";
|
||||
import PeriodHelper, { PeriodFilter } from "../PeriodHelper";
|
||||
import { AnalyticsInfoDto } from "~/application/dtos/marketing/AnalyticsInfoDto";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
import AnalyticsHelper from "../AnalyticsHelper";
|
||||
import { AppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { IpAddressDto } from "~/modules/ipAddress/dtos/IpAddressDto";
|
||||
import IpAddressServiceServer from "~/modules/ipAddress/services/IpAddressService.server";
|
||||
|
||||
async function getOrCreateUniqueVisitor({
|
||||
cookie,
|
||||
fromUrl,
|
||||
fromRoute,
|
||||
analytics,
|
||||
}: {
|
||||
cookie: string;
|
||||
fromUrl?: string;
|
||||
fromRoute?: string;
|
||||
analytics: AnalyticsInfoDto;
|
||||
}) {
|
||||
const visitor = await cachified({
|
||||
key: `analytics:uniqueVisitor:${cookie}`,
|
||||
ttl: 60 * 60,
|
||||
getFreshValue: async () => {
|
||||
return db.analyticsUniqueVisitor.findUnique({
|
||||
where: {
|
||||
cookie,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
if (visitor) {
|
||||
return visitor;
|
||||
}
|
||||
// console.log("Creating unique visitor", { referrer: analytics.referrer });
|
||||
return await db.analyticsUniqueVisitor
|
||||
.create({
|
||||
data: {
|
||||
cookie,
|
||||
httpReferrer: analytics.referrer?.http,
|
||||
via: analytics.referrer?.via,
|
||||
browser: analytics.userAgent?.browser.name,
|
||||
browserVersion: analytics.userAgent?.browser.version,
|
||||
os: analytics.userAgent?.os.family,
|
||||
osVersion: analytics.userAgent?.os.version,
|
||||
device: analytics.userAgent?.type,
|
||||
source: analytics.referrer?.source,
|
||||
medium: analytics.referrer?.utm_medium,
|
||||
campaign: analytics.referrer?.utm_campaign,
|
||||
content: analytics.referrer?.utm_content,
|
||||
term: analytics.referrer?.utm_term,
|
||||
country: analytics.region?.country,
|
||||
city: analytics.region?.city,
|
||||
fromUrl,
|
||||
fromRoute,
|
||||
userId: analytics.userId ?? null,
|
||||
portalId: analytics.portalId ?? null,
|
||||
portalUserId: analytics.portalUserId ?? null,
|
||||
},
|
||||
})
|
||||
.then((e) => {
|
||||
clearCacheKey(`analytics:uniqueVisitor:${cookie}`);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
export type AnalyticsOverviewDto = {
|
||||
uniqueVisitors: number;
|
||||
pageViews: number;
|
||||
events: number;
|
||||
liveVisitors: number;
|
||||
top: {
|
||||
sources: { name: string | null; count: number }[];
|
||||
httpReferrers: { name: string | null; count: number }[];
|
||||
urls: { name: string | null; count: number }[];
|
||||
routes: { name: string | null; count: number }[];
|
||||
os: { name: string | null; count: number }[];
|
||||
devices: { name: string | null; count: number }[];
|
||||
countries: { name: string | null; count: number }[];
|
||||
via: { name: string | null; count: number }[];
|
||||
medium: { name: string | null; count: number }[];
|
||||
campaign: { name: string | null; count: number }[];
|
||||
user: { name: string | null; count: number }[];
|
||||
};
|
||||
charts?: {
|
||||
pageViewsAndUniqueVisitors: {
|
||||
date: string;
|
||||
"Page views": number; // "Page Views"
|
||||
"Unique visitors": number; // "Unique Visitors"
|
||||
}[];
|
||||
};
|
||||
};
|
||||
type AnalyticsChart = "visitors" | "pages" | "events";
|
||||
async function getAnalyticsOverview({ withUsers, period, portalId }: { withUsers: boolean; period: PeriodFilter; portalId: string | null | undefined }) {
|
||||
const createdAt = PeriodHelper.getCreatedAt(period);
|
||||
if (period === "all-time") {
|
||||
const firstDate = await db.analyticsUniqueVisitor.findFirst({
|
||||
where: { portalId },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
if (firstDate) {
|
||||
createdAt.gte = firstDate.createdAt;
|
||||
}
|
||||
}
|
||||
const uniqueVisitors = await db.analyticsUniqueVisitor.count({
|
||||
where: { portalId, createdAt },
|
||||
});
|
||||
const pageViews = await db.analyticsPageView.count({
|
||||
where: {
|
||||
portalId,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
const events = await db.analyticsEvent.count({
|
||||
where: {
|
||||
portalId,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
const liveVisitors = await db.analyticsPageView.groupBy({
|
||||
by: ["uniqueVisitorId"],
|
||||
where: {
|
||||
portalId,
|
||||
createdAt: {
|
||||
gte: new Date(Date.now() - 1 * 60000),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const topHttpReferrers = (
|
||||
await db.analyticsUniqueVisitor.groupBy({
|
||||
by: ["httpReferrer"],
|
||||
_count: true,
|
||||
where: { portalId, createdAt },
|
||||
})
|
||||
).map((f) => {
|
||||
return { name: f.httpReferrer, count: f._count };
|
||||
});
|
||||
const topSources = (
|
||||
await db.analyticsUniqueVisitor.groupBy({
|
||||
by: ["source"],
|
||||
_count: true,
|
||||
where: { portalId, createdAt },
|
||||
})
|
||||
).map((f) => {
|
||||
return { name: f.source, count: f._count };
|
||||
});
|
||||
let topUrls = (
|
||||
await db.analyticsPageView.groupBy({
|
||||
by: ["url"],
|
||||
_count: true,
|
||||
where: { portalId, createdAt },
|
||||
})
|
||||
)
|
||||
.map((f) => {
|
||||
return { name: f.url, count: f._count };
|
||||
})
|
||||
.sort((a, b) => b.count - a.count);
|
||||
|
||||
if (!withUsers) {
|
||||
if (topUrls.length > 10) {
|
||||
topUrls = topUrls.slice(0, 10);
|
||||
}
|
||||
}
|
||||
const topRoutes = (
|
||||
await db.analyticsPageView.groupBy({
|
||||
by: ["route"],
|
||||
_count: true,
|
||||
where: { portalId, createdAt },
|
||||
})
|
||||
).map((f) => {
|
||||
return { name: f.route, count: f._count };
|
||||
});
|
||||
const topOs = (await db.analyticsUniqueVisitor.groupBy({ by: ["os"], _count: true, where: { portalId, createdAt } })).map((f) => {
|
||||
return { name: f.os, count: f._count };
|
||||
});
|
||||
const topDevices = (await db.analyticsUniqueVisitor.groupBy({ by: ["device"], _count: true, where: { portalId, createdAt } })).map((f) => {
|
||||
return { name: f.device, count: f._count };
|
||||
});
|
||||
const topCountries = (await db.analyticsUniqueVisitor.groupBy({ by: ["country"], _count: true, where: { portalId, createdAt } })).map((f) => {
|
||||
return { name: f.country, count: f._count };
|
||||
});
|
||||
const topVia = (await db.analyticsUniqueVisitor.groupBy({ by: ["via"], _count: true, where: { portalId, createdAt } })).map((f) => {
|
||||
return { name: f.via, count: f._count };
|
||||
});
|
||||
const topMedium = (await db.analyticsUniqueVisitor.groupBy({ by: ["medium"], _count: true, where: { portalId, createdAt } })).map((f) => {
|
||||
return { name: f.medium, count: f._count };
|
||||
});
|
||||
const topCampaign = (await db.analyticsUniqueVisitor.groupBy({ by: ["campaign"], _count: true, where: { portalId, createdAt } })).map((f) => {
|
||||
return { name: f.campaign, count: f._count };
|
||||
});
|
||||
let topUserIds: {
|
||||
id: string;
|
||||
count: number;
|
||||
}[] = [];
|
||||
if (withUsers) {
|
||||
topUserIds = (await db.analyticsUniqueVisitor.groupBy({ by: ["userId"], _count: true, where: { portalId, createdAt } })).map((f) => {
|
||||
return { id: f.userId ?? "", count: f._count };
|
||||
});
|
||||
}
|
||||
const users = await adminGetAllUsersNamesInIds(topUserIds.map((f) => f.id));
|
||||
const topUsers = topUserIds.map((f) => {
|
||||
const user = users.find((u) => u.id === f.id);
|
||||
return { name: user?.email ?? "", count: f.count };
|
||||
});
|
||||
|
||||
const charts = await getCharts({ period, portalId });
|
||||
|
||||
const data: AnalyticsOverviewDto = {
|
||||
uniqueVisitors,
|
||||
pageViews,
|
||||
events,
|
||||
liveVisitors: liveVisitors.length,
|
||||
top: {
|
||||
httpReferrers: topHttpReferrers.sort((a, b) => b.count - a.count),
|
||||
sources: topSources.sort((a, b) => b.count - a.count),
|
||||
urls: topUrls,
|
||||
routes: topRoutes.sort((a, b) => b.count - a.count),
|
||||
os: topOs.sort((a, b) => b.count - a.count),
|
||||
devices: topDevices.sort((a, b) => b.count - a.count),
|
||||
countries: topCountries.sort((a, b) => b.count - a.count),
|
||||
via: topVia.sort((a, b) => b.count - a.count),
|
||||
medium: topMedium.sort((a, b) => b.count - a.count),
|
||||
campaign: topCampaign.sort((a, b) => b.count - a.count),
|
||||
user: topUsers.sort((a, b) => b.count - a.count),
|
||||
},
|
||||
charts,
|
||||
};
|
||||
return data;
|
||||
}
|
||||
|
||||
async function getCharts({ period, portalId }: { period: PeriodFilter; portalId: string | null | undefined }) {
|
||||
const createdAt = PeriodHelper.getCreatedAt(period);
|
||||
if (period === "all-time") {
|
||||
const firstDate = await db.analyticsUniqueVisitor.findFirst({
|
||||
where: { portalId },
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
if (firstDate) {
|
||||
createdAt.gte = firstDate.createdAt;
|
||||
}
|
||||
}
|
||||
const pageViewsByDay = await db.analyticsPageView.groupBy({
|
||||
by: ["createdAt"],
|
||||
_count: true,
|
||||
where: { portalId, createdAt },
|
||||
});
|
||||
|
||||
const uniqueVisitorsByDay = await db.analyticsUniqueVisitor.groupBy({
|
||||
by: ["createdAt"],
|
||||
_count: true,
|
||||
where: { portalId, createdAt },
|
||||
});
|
||||
|
||||
const toDateString = (date: Date) => {
|
||||
if (period === "last-24-hours") {
|
||||
return format(date, "ha");
|
||||
} else if (period === "last-hour" || period === "last-10-minutes") {
|
||||
return format(date, "h:mm a");
|
||||
}
|
||||
return DateUtils.dateMonthDay(date);
|
||||
};
|
||||
|
||||
// Aggregate counts by date
|
||||
const aggregateCounts = (data: { createdAt: Date; _count: number }[]) => {
|
||||
const countMap = new Map();
|
||||
data.forEach((item) => {
|
||||
const dateKey = toDateString(item.createdAt);
|
||||
countMap.set(dateKey, (countMap.get(dateKey) || 0) + item._count);
|
||||
});
|
||||
return countMap;
|
||||
};
|
||||
|
||||
const pageViewsMap = aggregateCounts(pageViewsByDay);
|
||||
const uniqueVisitorsMap = aggregateCounts(uniqueVisitorsByDay);
|
||||
|
||||
const charts: AnalyticsOverviewDto["charts"] = {
|
||||
pageViewsAndUniqueVisitors: [],
|
||||
};
|
||||
|
||||
// from createdAt.gte to createdAt.lte (or today), each day
|
||||
const currentDate = new Date();
|
||||
let date = new Date(createdAt.gte ?? currentDate);
|
||||
|
||||
let i = 0;
|
||||
if (period === "last-24-hours") {
|
||||
date = new Date();
|
||||
date.setHours(date.getHours() - 23);
|
||||
for (let i = 1; i <= 24; i++) {
|
||||
const dateKey = toDateString(date);
|
||||
charts.pageViewsAndUniqueVisitors.push({
|
||||
date: dateKey,
|
||||
"Page views": pageViewsMap.get(dateKey) ?? 0,
|
||||
"Unique visitors": uniqueVisitorsMap.get(dateKey) ?? 0,
|
||||
});
|
||||
date.setHours(date.getHours() + 1);
|
||||
}
|
||||
return charts;
|
||||
} else if (period === "last-hour") {
|
||||
date = new Date();
|
||||
date.setMinutes(date.getMinutes() - 59);
|
||||
for (let i = 1; i <= 60; i++) {
|
||||
const dateKey = toDateString(date);
|
||||
charts.pageViewsAndUniqueVisitors.push({
|
||||
date: dateKey,
|
||||
"Page views": pageViewsMap.get(dateKey) ?? 0,
|
||||
"Unique visitors": uniqueVisitorsMap.get(dateKey) ?? 0,
|
||||
});
|
||||
date.setMinutes(date.getMinutes() + 1);
|
||||
}
|
||||
return charts;
|
||||
} else if (period === "last-10-minutes") {
|
||||
date = new Date();
|
||||
date.setMinutes(date.getMinutes() - 9);
|
||||
for (let i = 1; i <= 10; i++) {
|
||||
const dateKey = toDateString(date);
|
||||
charts.pageViewsAndUniqueVisitors.push({
|
||||
date: dateKey,
|
||||
"Page views": pageViewsMap.get(dateKey) ?? 0,
|
||||
"Unique visitors": uniqueVisitorsMap.get(dateKey) ?? 0,
|
||||
});
|
||||
date.setMinutes(date.getMinutes() + 1);
|
||||
}
|
||||
return charts;
|
||||
} else {
|
||||
while (date <= (createdAt.lte ?? currentDate) && i < 1000) {
|
||||
const dateKey = toDateString(date);
|
||||
charts.pageViewsAndUniqueVisitors.push({
|
||||
date: dateKey,
|
||||
"Page views": pageViewsMap.get(dateKey) ?? 0,
|
||||
"Unique visitors": uniqueVisitorsMap.get(dateKey) ?? 0,
|
||||
});
|
||||
date.setDate(date.getDate() + 1);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
return charts;
|
||||
}
|
||||
|
||||
async function getPageViews(filters: {
|
||||
url?: {
|
||||
startsWith?: string;
|
||||
contains?: string;
|
||||
};
|
||||
route?: {
|
||||
startsWith?: string;
|
||||
contains?: string;
|
||||
};
|
||||
}) {
|
||||
return await db.analyticsPageView.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ url: { startsWith: filters.url?.startsWith, contains: filters.url?.contains } },
|
||||
{ route: { startsWith: filters.route?.startsWith, contains: filters.route?.contains } },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function getFromRequest({ appConfiguration, request, userId }: { appConfiguration: AppConfiguration; request: Request; userId: string | null }) {
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
|
||||
// console.log({ headers: request.headers });
|
||||
let ip = getClientIPAddress(request)?.toString() || "";
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
ip = "134.201.250.155";
|
||||
}
|
||||
const userAgent = request.headers.get("user-agent") ?? navigator.userAgent;
|
||||
const httpReferrer = request.headers.get("referer")?.toString();
|
||||
const ref = searchParams.get("ref")?.toString();
|
||||
const via = searchParams.get("via")?.toString();
|
||||
const source = searchParams.get("source")?.toString();
|
||||
const utm_source = searchParams.get("utm_source")?.toString();
|
||||
const utm_medium = searchParams.get("utm_medium")?.toString();
|
||||
const utm_campaign = searchParams.get("utm_campaign")?.toString();
|
||||
const utm_content = searchParams.get("utm_content")?.toString();
|
||||
const utm_term = searchParams.get("utm_term")?.toString();
|
||||
let mergedSource = "";
|
||||
if (ref && ref?.length > 0) {
|
||||
mergedSource = ref;
|
||||
} else if (source && source?.length > 0) {
|
||||
mergedSource = source;
|
||||
} else if (utm_source && utm_source?.length > 0) {
|
||||
mergedSource = utm_source;
|
||||
}
|
||||
let ipAddress: IpAddressDto | null = null;
|
||||
if (ip && appConfiguration.analytics.ipLookup) {
|
||||
ipAddress = await IpAddressServiceServer.getOrCreateIpAddressLookup(ip);
|
||||
}
|
||||
|
||||
const analytics: AnalyticsInfoDto = {
|
||||
ip,
|
||||
userAgent: AnalyticsHelper.getUserAgentDetails(userAgent),
|
||||
referrer: {
|
||||
http: httpReferrer,
|
||||
via,
|
||||
source: mergedSource,
|
||||
utm_medium,
|
||||
utm_campaign,
|
||||
utm_content,
|
||||
utm_term,
|
||||
},
|
||||
userId: userId && userId.length > 0 ? userId : null,
|
||||
region: {
|
||||
country: ipAddress?.countryCode || undefined,
|
||||
city: ipAddress?.city || undefined,
|
||||
},
|
||||
};
|
||||
return analytics;
|
||||
}
|
||||
|
||||
export default {
|
||||
getOrCreateUniqueVisitor,
|
||||
getAnalyticsOverview,
|
||||
getPageViews,
|
||||
getFromRequest,
|
||||
};
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export type IpAddressDto = {
|
||||
ip: string;
|
||||
provider: string;
|
||||
type: string;
|
||||
countryCode: string;
|
||||
countryName: string;
|
||||
regionCode: string;
|
||||
regionName: string;
|
||||
city: string;
|
||||
zipCode: string;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
metadata: { [key: string]: any } | null;
|
||||
};
|
||||
export async function getOrCreateIpAddressLookup(ip: string): Promise<IpAddressDto | null> {
|
||||
let provider: string | null = null;
|
||||
if (process.env.IPSTACK_API_KEY) {
|
||||
provider = "ipstack";
|
||||
}
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
const item = await cachified({
|
||||
key: `ipAddress:${ip}`,
|
||||
getFreshValue: () =>
|
||||
db.ipAddress.findUnique({
|
||||
where: { ip },
|
||||
}),
|
||||
});
|
||||
if (item) {
|
||||
// eslint-disable-next-line no-console
|
||||
// console.log("[getOrCreateIpAddressLookup] Found in cache", ip);
|
||||
try {
|
||||
const dto: IpAddressDto = {
|
||||
ip,
|
||||
provider,
|
||||
type: item.type,
|
||||
countryCode: item.countryCode,
|
||||
countryName: item.countryName,
|
||||
regionCode: item.regionCode,
|
||||
regionName: item.regionName,
|
||||
city: item.city,
|
||||
zipCode: item.zipCode,
|
||||
latitude: item.latitude ? Number(item.latitude) : null,
|
||||
longitude: item.longitude ? Number(item.longitude) : null,
|
||||
metadata: JSON.parse(item.metadata),
|
||||
};
|
||||
return dto;
|
||||
} catch (error: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("[getOrCreateIpAddressLookup] Error parsing metadata", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
// console.log("[getOrCreateIpAddressLookup] Not found in cache, fetching", ip);
|
||||
try {
|
||||
const response = await fetch(`http://api.ipstack.com/${ip}?access_key=${process.env.IPSTACK_API_KEY}`);
|
||||
const data = await response.json();
|
||||
const dto: IpAddressDto = {
|
||||
ip,
|
||||
provider,
|
||||
type: data.type,
|
||||
countryCode: data.country_code,
|
||||
countryName: data.country_name,
|
||||
regionCode: data.region_code,
|
||||
regionName: data.region_name,
|
||||
city: data.city,
|
||||
zipCode: data.zip,
|
||||
latitude: data.latitude,
|
||||
longitude: data.longitude,
|
||||
metadata: data,
|
||||
};
|
||||
await db.ipAddress
|
||||
.create({
|
||||
data: {
|
||||
ip,
|
||||
provider,
|
||||
type: data.type,
|
||||
countryCode: data.country_code,
|
||||
countryName: data.country_name,
|
||||
regionCode: data.region_code,
|
||||
regionName: data.region_name,
|
||||
city: data.city,
|
||||
zipCode: data.zip,
|
||||
latitude: data.latitude,
|
||||
longitude: data.longitude,
|
||||
metadata: JSON.stringify(data),
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`ipAddress:${ip}`);
|
||||
return item;
|
||||
});
|
||||
return dto;
|
||||
} catch (error: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("[getOrCreateIpAddressLookup] Error fetching IP data", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
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;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildPermissionDeniedUrl } from "./PermissionsService";
|
||||
|
||||
describe("permission denied redirects", () => {
|
||||
it("keeps tenant scope when building tenant permission denial URLs", () => {
|
||||
expect(
|
||||
buildPermissionDeniedUrl({
|
||||
permissionName: "app.settings.members.view",
|
||||
tenantId: "tenant_1",
|
||||
requestUrl: "https://app.example.test/acme/settings/members?tab=active",
|
||||
})
|
||||
).toBe("/unauthorized/app.settings.members.view/tenant_1?redirect=%2Facme%2Fsettings%2Fmembers");
|
||||
});
|
||||
|
||||
it("keeps global denial URLs on the global unauthorized route", () => {
|
||||
expect(
|
||||
buildPermissionDeniedUrl({
|
||||
permissionName: "admin.accounts.view",
|
||||
tenantId: null,
|
||||
requestUrl: "https://admin.example.test/accounts/users",
|
||||
})
|
||||
).toBe("/unauthorized/admin.accounts.view?redirect=%2Faccounts%2Fusers");
|
||||
});
|
||||
});
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
findPermissionByUser: vi.fn(),
|
||||
findUserRolesByIds: vi.fn(),
|
||||
getUserRoleInAdmin: vi.fn(),
|
||||
getUserRoles: vi.fn(),
|
||||
userHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({
|
||||
getPermissionName: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/permissions/groups.db.server", () => ({
|
||||
getMyGroups: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
getTenantMember: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
getIsSuperAdminByUserId: vi.fn(),
|
||||
}));
|
||||
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import {
|
||||
buildPermissionDeniedUrl,
|
||||
shapePermissionCheckResult,
|
||||
verifyUserHasPermission,
|
||||
type PermissionCheckResult,
|
||||
} from "./PermissionsService";
|
||||
|
||||
const mocks = {
|
||||
getPermissionName: vi.mocked(getPermissionName),
|
||||
getTenantMember: vi.mocked(getTenantMember),
|
||||
getIsSuperAdminByUserId: vi.mocked(getIsSuperAdminByUserId),
|
||||
getUserInfo: vi.mocked(getUserInfo),
|
||||
userHasPermission: vi.mocked(userHasPermission),
|
||||
};
|
||||
|
||||
const permissionName = "app.dashboard.view";
|
||||
|
||||
async function expectRedirect(error: unknown) {
|
||||
expect(error).toBeInstanceOf(Response);
|
||||
const response = error as Response;
|
||||
expect(response.status).toBe(302);
|
||||
return response.headers.get("Location");
|
||||
}
|
||||
|
||||
describe("verifyUserHasPermission", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_123" });
|
||||
mocks.getPermissionName.mockResolvedValue({ id: "perm_123", name: permissionName, description: "Dashboard" });
|
||||
mocks.getTenantMember.mockResolvedValue({ id: "tenant_user_123", status: TenantUserStatus.ACTIVE } as Awaited<ReturnType<typeof getTenantMember>>);
|
||||
mocks.getIsSuperAdminByUserId.mockResolvedValue(false);
|
||||
mocks.userHasPermission.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it("allows users with a known granted permission", async () => {
|
||||
await expect(verifyUserHasPermission(new Request("https://app.example.com/dashboard"), permissionName, "tenant_123")).resolves.toBe(true);
|
||||
|
||||
expect(mocks.getUserInfo).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.getPermissionName).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.getPermissionName).toHaveBeenCalledWith(permissionName);
|
||||
expect(mocks.getTenantMember).toHaveBeenCalledWith("user_123", "tenant_123");
|
||||
expect(mocks.userHasPermission).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.userHasPermission).toHaveBeenCalledWith("user_123", "tenant_123", permissionName);
|
||||
});
|
||||
|
||||
it("fails closed for unknown permissions without counting user permissions", async () => {
|
||||
mocks.getPermissionName.mockResolvedValue(null);
|
||||
|
||||
await expect(verifyUserHasPermission(new Request("https://app.example.com/legacy"), permissionName, "tenant_123")).rejects.toThrow(
|
||||
`Unknown permission: ${permissionName}`
|
||||
);
|
||||
|
||||
expect(mocks.getUserInfo).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.getPermissionName).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.getTenantMember).not.toHaveBeenCalled();
|
||||
expect(mocks.userHasPermission).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("denies tenant permissions when the user no longer has active tenant membership", async () => {
|
||||
mocks.getTenantMember.mockResolvedValue(null);
|
||||
|
||||
let location: string | null = null;
|
||||
try {
|
||||
await verifyUserHasPermission(new Request("https://app.example.com/acme/settings?token=secret"), permissionName, "tenant_123");
|
||||
} catch (error) {
|
||||
location = await expectRedirect(error);
|
||||
}
|
||||
|
||||
expect(location).toBe(`/unauthorized/${permissionName}/tenant_123?redirect=%2Facme%2Fsettings`);
|
||||
expect(mocks.getTenantMember).toHaveBeenCalledWith("user_123", "tenant_123");
|
||||
expect(mocks.userHasPermission).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("throws Unauthorized for unauthenticated users before permission lookup", async () => {
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: null, cookies: [{ category: "analytics", allowed: true }] });
|
||||
|
||||
await expect(verifyUserHasPermission(new Request("https://app.example.com/dashboard?token=secret"), permissionName, "tenant_123")).rejects.toThrow(
|
||||
"Unauthorized"
|
||||
);
|
||||
|
||||
expect(mocks.getUserInfo).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.getPermissionName).not.toHaveBeenCalled();
|
||||
expect(mocks.userHasPermission).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("redirects denied tenant permissions with a redacted pathname-only redirect", async () => {
|
||||
mocks.userHasPermission.mockResolvedValue(false);
|
||||
|
||||
let location: string | null = null;
|
||||
try {
|
||||
await verifyUserHasPermission(new Request("https://app.example.com/settings?token=secret&apiKey=key_123"), permissionName, "tenant_123");
|
||||
} catch (error) {
|
||||
location = await expectRedirect(error);
|
||||
}
|
||||
|
||||
expect(location).toBe(`/unauthorized/${permissionName}/tenant_123?redirect=%2Fsettings`);
|
||||
expect(location).not.toContain("token=secret");
|
||||
expect(location).not.toContain("apiKey=key_123");
|
||||
expect(mocks.userHasPermission).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("redirects denied admin permissions without tenant scope", async () => {
|
||||
mocks.userHasPermission.mockResolvedValue(false);
|
||||
|
||||
let location: string | null = null;
|
||||
try {
|
||||
await verifyUserHasPermission(new Request("https://admin.example.com/users?jwt=secret"), "admin.users.view", null);
|
||||
} catch (error) {
|
||||
location = await expectRedirect(error);
|
||||
}
|
||||
|
||||
expect(location).toBe("/unauthorized/admin.users.view?redirect=%2Fusers");
|
||||
expect(location).not.toContain("jwt=secret");
|
||||
expect(mocks.userHasPermission).toHaveBeenCalledWith("user_123", null, "admin.users.view");
|
||||
});
|
||||
});
|
||||
|
||||
describe("permission decision helpers", () => {
|
||||
it("builds denied URLs from pathname only", () => {
|
||||
expect(
|
||||
buildPermissionDeniedUrl({ permissionName, tenantId: "tenant_123", requestUrl: "https://app.example.com/accounts?bearer=secret" })
|
||||
).toBe(`/unauthorized/${permissionName}/tenant_123?redirect=%2Faccounts`);
|
||||
});
|
||||
|
||||
it("shapes redacted permission check results", () => {
|
||||
const denied: PermissionCheckResult = shapePermissionCheckResult({
|
||||
allowed: false,
|
||||
permissionName,
|
||||
tenantId: "tenant_123",
|
||||
reason: "permission-denied",
|
||||
});
|
||||
|
||||
expect(denied).toEqual({ allowed: false, permissionName, tenantId: "tenant_123", reason: "permission-denied" });
|
||||
expect(JSON.stringify(denied)).not.toContain("cookie");
|
||||
expect(JSON.stringify(denied)).not.toContain("secret");
|
||||
});
|
||||
});
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
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 { 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";
|
||||
|
||||
const OPERATOR_ADMIN_BYPASS_DESCRIPTION = "Operator admin tenant permission bypass";
|
||||
|
||||
export async function getUserPermission({ userId, permissionName, tenantId }: { userId: string; permissionName: string; tenantId?: string | null }) {
|
||||
if (tenantId) {
|
||||
const user = await getUser(userId);
|
||||
const isOperatorAdmin = !!user?.admin || (await getIsSuperAdminByUserId(userId)) || !!(await getUserRoleInAdmin(userId, DefaultAdminRoles.SuperAdmin));
|
||||
if (isOperatorAdmin) {
|
||||
return {
|
||||
permission: { id: "operator-admin-bypass", name: permissionName, description: OPERATOR_ADMIN_BYPASS_DESCRIPTION },
|
||||
userPermission: permissionName,
|
||||
};
|
||||
}
|
||||
}
|
||||
const permission = await getPermissionName(permissionName);
|
||||
if (!permission) {
|
||||
return { permission, userPermission: undefined };
|
||||
}
|
||||
if (tenantId && (await getIsSuperAdminByUserId(userId))) {
|
||||
return { permission, userPermission: permission.name };
|
||||
}
|
||||
// const userRoles = await getUserRoles(userId ?? undefined, tenantId ?? null);
|
||||
// let userPermission: Permission | undefined = undefined;
|
||||
// userRoles.forEach((userRole) => {
|
||||
// userRole.role.permissions.forEach((rolePermission) => {
|
||||
// if (rolePermission.permission.name === permissionName) {
|
||||
// userPermission = rolePermission.permission;
|
||||
// }
|
||||
// });
|
||||
// });
|
||||
const userPermission = await findPermissionByUser(permissionName, userId, tenantId);
|
||||
return { permission, userPermission };
|
||||
}
|
||||
|
||||
export type PermissionCheckDeniedReason = "unauthenticated" | "permission-denied";
|
||||
|
||||
export type PermissionCheckResult =
|
||||
| { allowed: true; permissionName: DefaultPermission; tenantId: string | null; reason?: undefined }
|
||||
| { allowed: false; permissionName: DefaultPermission; tenantId: string | null; reason: PermissionCheckDeniedReason };
|
||||
|
||||
export function buildPermissionDeniedUrl({
|
||||
permissionName,
|
||||
tenantId,
|
||||
requestUrl,
|
||||
}: {
|
||||
permissionName: DefaultPermission;
|
||||
tenantId: string | null;
|
||||
requestUrl: string;
|
||||
}) {
|
||||
const requestPathname = new URL(requestUrl).pathname;
|
||||
const searchParams = new URLSearchParams([["redirect", requestPathname]]);
|
||||
const tenantSegment = tenantId ? `/${encodeURIComponent(tenantId)}` : "";
|
||||
return `/unauthorized/${permissionName}${tenantSegment}?${searchParams}`;
|
||||
}
|
||||
|
||||
export function shapePermissionCheckResult({
|
||||
allowed,
|
||||
permissionName,
|
||||
tenantId,
|
||||
reason,
|
||||
}: {
|
||||
allowed: boolean;
|
||||
permissionName: DefaultPermission;
|
||||
tenantId: string | null;
|
||||
reason?: PermissionCheckDeniedReason;
|
||||
}): PermissionCheckResult {
|
||||
if (allowed) {
|
||||
return { allowed: true, permissionName, tenantId };
|
||||
}
|
||||
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;
|
||||
// }
|
||||
// console.log("verifyUserHasPermission", permissionName);
|
||||
const userInfo = await getUserInfo(request);
|
||||
if (!userInfo.userId) {
|
||||
shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "unauthenticated" });
|
||||
throw Error("Unauthorized");
|
||||
}
|
||||
if (tenantId) {
|
||||
const user = await getUser(userInfo.userId);
|
||||
const isOperatorAdmin =
|
||||
!!user?.admin || (await getIsSuperAdminByUserId(userInfo.userId)) || !!(await getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin));
|
||||
if (isOperatorAdmin) {
|
||||
shapePermissionCheckResult({ allowed: true, permissionName, tenantId });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const permission = await getPermissionName(permissionName);
|
||||
if (!permission) {
|
||||
shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" });
|
||||
throw Error(`Unknown permission: ${permissionName}`);
|
||||
}
|
||||
|
||||
if (tenantId) {
|
||||
const tenantMember = await getTenantMember(userInfo.userId, tenantId);
|
||||
if (!tenantMember || tenantMember.status !== TenantUserStatus.ACTIVE) {
|
||||
const decision = shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" });
|
||||
throw redirect(buildPermissionDeniedUrl({ permissionName: decision.permissionName, tenantId: decision.tenantId, requestUrl: request.url }));
|
||||
}
|
||||
}
|
||||
|
||||
const userPermission = await userHasPermission(userInfo.userId, tenantId, permissionName);
|
||||
if (!userPermission) {
|
||||
const decision = shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" });
|
||||
throw redirect(buildPermissionDeniedUrl({ permissionName: decision.permissionName, tenantId: decision.tenantId, requestUrl: request.url }));
|
||||
}
|
||||
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
@@ -0,0 +1,65 @@
|
||||
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
@@ -0,0 +1,104 @@
|
||||
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,
|
||||
};
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { EntityWithDetails } from "../../db/entities/entities.db.server";
|
||||
import { RowWithDetails, getRowById } from "../../db/entities/rows.db.server";
|
||||
import ApiHelper, { ApiFormatOptions } from "../ApiHelper";
|
||||
import RowHelper from "../RowHelper";
|
||||
import { getTenant } from "../../db/tenants.db.server";
|
||||
import { RowAsJson } from "../TemplateApiHelper";
|
||||
|
||||
async function fetchRowWithRelationships({
|
||||
rowId,
|
||||
scope,
|
||||
entities,
|
||||
processedRows = new Set<string>(),
|
||||
backlog = [], // This will be used to store the deferred relationships to be fetched later.
|
||||
}: {
|
||||
rowId: string;
|
||||
scope: { entityId?: string; tenantId: string | null };
|
||||
entities: EntityWithDetails[];
|
||||
processedRows?: Set<string>;
|
||||
backlog?: { rowId: string; relation: "parent" | "child"; attachTo: RowWithDetails; scope: { entityId?: string; tenantId: string | null } }[];
|
||||
}): Promise<RowWithDetails | null> {
|
||||
if (processedRows.has(rowId)) {
|
||||
return null;
|
||||
}
|
||||
processedRows.add(rowId);
|
||||
|
||||
const row = await getRowById(rowId, scope);
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fetch parent relationships.
|
||||
for (const parentRow of row.parentRows) {
|
||||
backlog.push({ rowId: parentRow.parent.id, relation: "parent", attachTo: row, scope: { entityId: parentRow.parent.entityId, tenantId: parentRow.parent.tenantId } });
|
||||
}
|
||||
|
||||
// Fetch child relationships.
|
||||
for (const childRow of row.childRows) {
|
||||
backlog.push({ rowId: childRow.child.id, relation: "child", attachTo: row, scope: { entityId: childRow.child.entityId, tenantId: childRow.child.tenantId } });
|
||||
}
|
||||
|
||||
// Process the backlog.
|
||||
while (backlog.length > 0) {
|
||||
const { rowId: backlogRowId, relation, attachTo, scope: backlogScope } = backlog.shift()!;
|
||||
if (relation === "parent") {
|
||||
const parent = await fetchRowWithRelationships({ rowId: backlogRowId, scope: backlogScope, entities, processedRows, backlog });
|
||||
if (parent) {
|
||||
const parentRow = attachTo.parentRows.find((p) => p.parent.id === backlogRowId);
|
||||
if (parentRow) {
|
||||
parentRow.parent = parent;
|
||||
}
|
||||
}
|
||||
} else if (relation === "child") {
|
||||
const child = await fetchRowWithRelationships({ rowId: backlogRowId, scope: backlogScope, entities, processedRows, backlog });
|
||||
if (child) {
|
||||
const childRow = attachTo.childRows.find((c) => c.child.id === backlogRowId);
|
||||
if (childRow) {
|
||||
childRow.child = child;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
async function getRowInApiFormatWithRecursiveRelationships({
|
||||
entities,
|
||||
rowId,
|
||||
scope,
|
||||
t,
|
||||
options,
|
||||
}: {
|
||||
entities: EntityWithDetails[];
|
||||
rowId: string;
|
||||
scope: { entityId?: string; tenantId: string | null };
|
||||
t: TFunction;
|
||||
options: ApiFormatOptions;
|
||||
}): Promise<RowAsJson | null> {
|
||||
const row = await fetchRowWithRelationships({ rowId, scope, entities });
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
pruneDuplicateRows(row);
|
||||
const entity = entities.find((entity) => entity.id === row.entityId);
|
||||
if (!entity) {
|
||||
throw new Error(`Entity ${row.entityId} not found.`);
|
||||
}
|
||||
|
||||
const apiFormat = ApiHelper.getApiFormatWithRelationships({ entities, item: row, options });
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
name: RowHelper.getTextDescription({ entity, item: row, t }),
|
||||
entityId: entity.id,
|
||||
tenant: row.tenantId ? await getTenant(row.tenantId) : null,
|
||||
data: {
|
||||
[entity.name]: apiFormat,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function pruneDuplicateRows(mainRow: RowWithDetails): void {
|
||||
const seenRowIds: Set<string> = new Set();
|
||||
|
||||
let currentLevelRows: RowWithDetails[] = [mainRow];
|
||||
while (currentLevelRows.length > 0) {
|
||||
const nextLevelRows: RowWithDetails[] = [];
|
||||
|
||||
for (const row of currentLevelRows) {
|
||||
if (!row) continue;
|
||||
|
||||
// Process parent rows
|
||||
if (row.parentRows) {
|
||||
for (let i = row.parentRows.length - 1; i >= 0; i--) {
|
||||
const parent = row.parentRows[i].parent;
|
||||
if (seenRowIds.has(parent.id)) {
|
||||
row.parentRows.splice(i, 1); // Remove this parent
|
||||
} else {
|
||||
nextLevelRows.push(parent as RowWithDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process child rows
|
||||
if (row.childRows) {
|
||||
for (let i = row.childRows.length - 1; i >= 0; i--) {
|
||||
const child = row.childRows[i].child;
|
||||
if (seenRowIds.has(child.id)) {
|
||||
row.childRows.splice(i, 1); // Remove this child
|
||||
} else {
|
||||
nextLevelRows.push(child as RowWithDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mark the row as seen
|
||||
seenRowIds.add(row.id);
|
||||
}
|
||||
|
||||
// Move to the next level
|
||||
currentLevelRows = nextLevelRows;
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
getRowInApiFormatWithRecursiveRelationships,
|
||||
};
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import platform from "platform";
|
||||
import { CookieCategory } from "~/application/cookies/CookieCategory";
|
||||
import CookieHelper from "./CookieHelper";
|
||||
import { AppRootData } from "../data/useRootData";
|
||||
import { apiPath } from "../app/CanonicalUrlUtils";
|
||||
|
||||
// EU-Sterilisation (R-P1a): Google-Analytics-gtag-Aufrufe entfernt. Es bleibt nur die First-Party-
|
||||
// Analytics-Ingestion gegen den eigenen API-Endpunkt (gated über ANALYTICS-Cookie-Consent).
|
||||
|
||||
type AnalyticsProps = {
|
||||
url: string;
|
||||
rootData: Pick<AppRootData, "apiBaseUrl" | "userSession" | "analytics" | "analyticsToken">;
|
||||
route?: string;
|
||||
};
|
||||
|
||||
export async function addPageView({ url, rootData, route }: AnalyticsProps) {
|
||||
if (rootData.analytics && CookieHelper.hasConsent(rootData.userSession, CookieCategory.ANALYTICS)) {
|
||||
// console.log("[PAGE VIEW]", JSON.stringify({ url, analytics: rootData.analytics }));
|
||||
try {
|
||||
await fetch(new URL(apiPath("analytics/page-views", { mode: "host-aware" }), rootData.apiBaseUrl), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...(rootData.analyticsToken ? { "x-analytics-token": rootData.analyticsToken } : {}) },
|
||||
body: JSON.stringify({
|
||||
url,
|
||||
route,
|
||||
analytics: {
|
||||
...rootData.analytics,
|
||||
userAgent: getUserAgentDetails(),
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("[PAGE VIEW]", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type EventProps = AnalyticsProps & {
|
||||
url?: string;
|
||||
action: string;
|
||||
category: string;
|
||||
label: string;
|
||||
value: string;
|
||||
};
|
||||
export async function addEvent({ url, route, action, category, label, value, rootData }: EventProps) {
|
||||
if (rootData.analytics && CookieHelper.hasConsent(rootData.userSession, CookieCategory.ANALYTICS)) {
|
||||
// console.log("[EVENT]", JSON.stringify({ action, category, label, value, url, analytics: rootData.analytics }));
|
||||
try {
|
||||
await fetch(new URL(apiPath("analytics/events", { mode: "host-aware" }), rootData.apiBaseUrl), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...(rootData.analyticsToken ? { "x-analytics-token": rootData.analyticsToken } : {}) },
|
||||
body: JSON.stringify({
|
||||
action,
|
||||
category,
|
||||
label,
|
||||
value,
|
||||
url,
|
||||
route,
|
||||
analytics: {
|
||||
...rootData.analytics,
|
||||
userAgent: getUserAgentDetails(),
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("[PAGE VIEW]", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getUserAgentDetails(userAgent?: string) {
|
||||
const deviceType = () => {
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
}
|
||||
const ua = userAgent;
|
||||
if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
|
||||
return "tablet";
|
||||
} else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
|
||||
return "mobile";
|
||||
}
|
||||
return "desktop";
|
||||
};
|
||||
return {
|
||||
type: deviceType(),
|
||||
os: {
|
||||
family: platform.os?.family,
|
||||
version: platform.os?.version,
|
||||
},
|
||||
browser: {
|
||||
name: platform.name,
|
||||
version: platform.version,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// export async function createUniqueVisitorHash(domain: string, ipAddress: string, userAgent: string) {
|
||||
// const hash = sha256(domain + ipAddress + userAgent);
|
||||
// console.log({ hash });
|
||||
// return hash;
|
||||
// }
|
||||
|
||||
export default {
|
||||
addPageView,
|
||||
addEvent,
|
||||
getUserAgentDetails,
|
||||
};
|
||||
@@ -0,0 +1,420 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
export function getApiKeyCrudPermissions(c: boolean, r: boolean, u: boolean, d: boolean) {
|
||||
let permissions = "";
|
||||
if (c) {
|
||||
permissions += "C";
|
||||
}
|
||||
if (r) {
|
||||
permissions += "R";
|
||||
}
|
||||
if (u) {
|
||||
permissions += "U";
|
||||
}
|
||||
if (d) {
|
||||
permissions += "D";
|
||||
}
|
||||
return permissions;
|
||||
}
|
||||
|
||||
export function checkApiKeyCallIsCreditable(statusCode: number | null) {
|
||||
if (!statusCode) {
|
||||
return false;
|
||||
}
|
||||
if (apiKeyCreditableStatusCodes.includes(statusCode)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export const apiKeyCreditableStatusCodes = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226];
|
||||
export const apiKeyIgnoreEndpoints = ["/v1/usage"];
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Location } from "react-router";
|
||||
import { allCookieCategories } from "~/application/cookies/ApplicationCookies";
|
||||
import { CookieCategory } from "~/application/cookies/CookieCategory";
|
||||
import { UserSession } from "../session.server";
|
||||
|
||||
function hasConsent(userSession: UserSession, category: CookieCategory) {
|
||||
return category === CookieCategory.REQUIRED || userSession?.cookies?.find((f) => f.category === CookieCategory[category])?.allowed;
|
||||
}
|
||||
function requiresCookieConsent(userSession: UserSession, searchParams: URLSearchParams) {
|
||||
if (!userSession.cookies || userSession.cookies.length === 0 || searchParams.get("cookies")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const requiredCookieCategoryConsent = allCookieCategories.map((cookieCategory) => {
|
||||
if (userSession.cookies.find((f) => f.category === CookieCategory[cookieCategory]) === undefined) {
|
||||
return cookieCategory;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
if (requiredCookieCategoryConsent.filter((f) => f).length > 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function getUpdateCookieConsentForm({
|
||||
location,
|
||||
selectedCookies,
|
||||
searchParams,
|
||||
}: {
|
||||
location: Location;
|
||||
selectedCookies: CookieCategory[];
|
||||
searchParams: URLSearchParams;
|
||||
}) {
|
||||
const form = new FormData();
|
||||
form.set("action", "setCookieConsent");
|
||||
form.set("redirect", location.pathname);
|
||||
form.set("ref", searchParams.get("ref")?.toString() ?? "");
|
||||
form.set("source", searchParams.get("source")?.toString() ?? "");
|
||||
form.set("utm_source", searchParams.get("utm_source")?.toString() ?? "");
|
||||
form.set("utm_medium", searchParams.get("utm_medium")?.toString() ?? "");
|
||||
form.set("utm_campaign", searchParams.get("utm_campaign")?.toString() ?? "");
|
||||
form.set("utm_content", searchParams.get("utm_content")?.toString() ?? "");
|
||||
form.set("utm_term", searchParams.get("utm_term")?.toString() ?? "");
|
||||
selectedCookies.forEach((cookie) => {
|
||||
form.append("cookies[]", CookieCategory[cookie]);
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
export default {
|
||||
hasConsent,
|
||||
requiresCookieConsent,
|
||||
getUpdateCookieConsentForm,
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Return the company name based on the email domain:
|
||||
* person@company.com -> company, person@dev.company.com -> company
|
||||
*/
|
||||
export const companyFromEmail = (email: string) => {
|
||||
const domain = email.split("@")[1];
|
||||
const domainParts = domain.split(".");
|
||||
return domainParts[domainParts.length - 2];
|
||||
};
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
// @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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,351 @@
|
||||
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,
|
||||
};
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,129 @@
|
||||
import { MediaDto } from "~/application/dtos/entities/MediaDto";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import { JsonValue } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
|
||||
|
||||
const getText = (form: FormData, name: string): string | undefined => {
|
||||
const value = form.get(name);
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
return value.toString();
|
||||
};
|
||||
|
||||
const getNumber = (form: FormData, name: string): number | undefined => {
|
||||
const value = form.get(name);
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
return Number(value);
|
||||
};
|
||||
|
||||
const getBoolean = (form: FormData, name: string): boolean | undefined => {
|
||||
const value = form.get(name);
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === "false" || value === "0" || value === "off") {
|
||||
return false;
|
||||
}
|
||||
return value === "true" || value === "1" || value === "on" || Boolean(value);
|
||||
};
|
||||
|
||||
const getDate = (form: FormData, name: string): Date | undefined => {
|
||||
const value = form.get(name);
|
||||
if (value === undefined || value === null || !value) {
|
||||
return undefined;
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return value;
|
||||
} else if (typeof value === "string") {
|
||||
return new Date(value);
|
||||
} else if (typeof value === "number") {
|
||||
return new Date(value);
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const getDateString = (form: FormData, name: string): string | undefined => {
|
||||
const value = form.get(name);
|
||||
if (value === undefined || value === null || !value) {
|
||||
return undefined;
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString();
|
||||
} else if (typeof value === "string") {
|
||||
return value;
|
||||
} else if (typeof value === "number") {
|
||||
return new Date(value).toISOString();
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const getFormMedia = (form: FormData, name: string): MediaDto[] => {
|
||||
const items: MediaDto[] = form.getAll(name + "[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
return items;
|
||||
};
|
||||
|
||||
const getFormFirstMedia = (form: FormData, name: string): MediaDto | undefined => {
|
||||
const medias = getFormMedia(form, name);
|
||||
if (medias.length > 0) {
|
||||
return medias[0];
|
||||
}
|
||||
};
|
||||
|
||||
const getMultiple = (form: FormData, name: string): RowValueMultipleDto[] => {
|
||||
let multiple: RowValueMultipleDto[] = form.getAll(name + "[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
return multiple;
|
||||
};
|
||||
|
||||
const getJsonArray = (form: FormData, name: string): JsonValue[] => {
|
||||
let multiple: JsonValue[] = form.getAll(name + "[]").map((f: FormDataEntryValue) => {
|
||||
return f as JsonValue;
|
||||
});
|
||||
return multiple;
|
||||
};
|
||||
|
||||
const getNumberRange = (form: FormData, name: string): RowValueRangeDto => {
|
||||
const min = form.get(name + "-min");
|
||||
const max = form.get(name + "-max");
|
||||
let range: RowValueRangeDto = {
|
||||
numberMin: min ? Number(min ?? 0) : 0,
|
||||
numberMax: max ? Number(max ?? 0) : 0,
|
||||
dateMin: null,
|
||||
dateMax: null,
|
||||
};
|
||||
return range;
|
||||
};
|
||||
|
||||
const getDateRange = (form: FormData, name: string): RowValueRangeDto => {
|
||||
const min = form.get(name + "-min");
|
||||
const max = form.get(name + "-max");
|
||||
let range: RowValueRangeDto = {
|
||||
numberMin: null,
|
||||
numberMax: null,
|
||||
dateMin: min ? new Date(min?.toString()) : null,
|
||||
dateMax: max ? new Date(max?.toString()) : null,
|
||||
};
|
||||
return range;
|
||||
};
|
||||
|
||||
export default {
|
||||
getText,
|
||||
getNumber,
|
||||
getBoolean,
|
||||
getDate,
|
||||
getDateString,
|
||||
getFormMedia,
|
||||
getFormFirstMedia,
|
||||
getMultiple,
|
||||
getJsonArray,
|
||||
getNumberRange,
|
||||
getDateRange,
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
import { EmailAttachment } from "@toolctrl/db/prisma-browser";
|
||||
import { MediaDto } from "~/application/dtos/entities/MediaDto";
|
||||
|
||||
export function getAttachmentToMedia(attachment: EmailAttachment): MediaDto {
|
||||
return {
|
||||
title: attachment.name,
|
||||
name: attachment.name,
|
||||
file: attachment.publicUrl ?? attachment.content,
|
||||
type: attachment.type,
|
||||
};
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
interface OrderableItem {
|
||||
order: number;
|
||||
}
|
||||
|
||||
function getNextOrder(items: OrderableItem[]) {
|
||||
return (items.length > 0 ? Math.max(...items.map((o) => o.order)) : 0) + 1;
|
||||
}
|
||||
|
||||
export default {
|
||||
getNextOrder,
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
import DateUtils from "../shared/DateUtils";
|
||||
|
||||
export const PeriodFilters = [
|
||||
{ value: "all-time", name: "app.shared.periods.ALL_TIME" },
|
||||
{ value: "last-year", name: "app.shared.periods.LAST_YEAR" },
|
||||
{ value: "last-3-months", name: "app.shared.periods.LAST_3_MONTHS" },
|
||||
{ value: "last-30-days", name: "app.shared.periods.LAST_30_DAYS" },
|
||||
{ value: "last-7-days", name: "app.shared.periods.LAST_7_DAYS" },
|
||||
{ value: "last-24-hours", name: "app.shared.periods.LAST_24_HOURS" },
|
||||
{ value: "year-to-date", name: "app.shared.periods.YEAR_TO_DATE" },
|
||||
{ value: "month-to-date", name: "app.shared.periods.MONTH_TO_DATE" },
|
||||
{ value: "week-to-date", name: "app.shared.periods.WEEK_TO_DATE" },
|
||||
{ value: "last-hour", name: "app.shared.periods.LAST_HOUR" },
|
||||
{ value: "last-10-minutes", name: "app.shared.periods.LAST_10_MINUTES" },
|
||||
] as const;
|
||||
export type PeriodFilter = (typeof PeriodFilters)[number]["value"];
|
||||
export const defaultPeriodFilter = "last-30-days";
|
||||
|
||||
function getPeriodFromRequest({ request }: { request: Request }): PeriodFilter {
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const period = searchParams.get("period") || defaultPeriodFilter;
|
||||
const found = PeriodFilters.find((p) => p.value === period);
|
||||
if (found) {
|
||||
return found.value;
|
||||
}
|
||||
return defaultPeriodFilter;
|
||||
}
|
||||
|
||||
function getGreaterThanOrEqualsFromRequest({ request }: { request: Request }) {
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const countFilter = searchParams.get("period") ?? defaultPeriodFilter;
|
||||
if (countFilter === "all-time") {
|
||||
return undefined;
|
||||
} else if (countFilter === "last-year") {
|
||||
return DateUtils.daysFromDate(new Date(), 365 * -1);
|
||||
} else if (countFilter === "last-3-months") {
|
||||
return DateUtils.daysFromDate(new Date(), 90 * -1);
|
||||
} else if (countFilter === "last-30-days") {
|
||||
return DateUtils.daysFromDate(new Date(), 30 * -1);
|
||||
} else if (countFilter === "last-7-days") {
|
||||
return DateUtils.daysFromDate(new Date(), 7 * -1);
|
||||
} else if (countFilter === "last-24-hours") {
|
||||
return DateUtils.daysFromDate(new Date(), 1 * -1);
|
||||
} else if (countFilter === "last-hour") {
|
||||
return minutesFromDate(new Date(), 60 * -1);
|
||||
} else if (countFilter === "last-10-minutes") {
|
||||
return minutesFromDate(new Date(), 10 * -1);
|
||||
} else if (countFilter === "year-to-date") {
|
||||
return new Date(new Date().getFullYear(), 0, 1);
|
||||
} else if (countFilter === "month-to-date") {
|
||||
return new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
||||
} else if (countFilter === "week-to-date") {
|
||||
return weekStartDate(new Date());
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function minutesFromDate(date: Date, minutes: number) {
|
||||
return new Date(date.getTime() + minutes * 60000);
|
||||
}
|
||||
|
||||
function weekStartDate(date: Date) {
|
||||
const day = date.getDay();
|
||||
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
|
||||
return new Date(date.setDate(diff));
|
||||
}
|
||||
|
||||
function getCreatedAtFilter({ request }: { request: Request }) {
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
let period = searchParams.get("period");
|
||||
if (!period) {
|
||||
period = defaultPeriodFilter;
|
||||
}
|
||||
return getCreatedAt(period as PeriodFilter);
|
||||
}
|
||||
|
||||
function getCreatedAt(period: PeriodFilter) {
|
||||
let createdAt: { gte?: Date; lte?: Date } = {};
|
||||
switch (period) {
|
||||
case "all-time":
|
||||
break;
|
||||
case "last-year":
|
||||
createdAt.gte = DateUtils.daysFromDate(new Date(), 365 * -1);
|
||||
break;
|
||||
case "last-3-months":
|
||||
createdAt.gte = DateUtils.daysFromDate(new Date(), 90 * -1);
|
||||
break;
|
||||
case "last-30-days":
|
||||
createdAt.gte = DateUtils.daysFromDate(new Date(), 30 * -1);
|
||||
break;
|
||||
case "last-7-days":
|
||||
createdAt.gte = DateUtils.daysFromDate(new Date(), 7 * -1);
|
||||
break;
|
||||
case "last-24-hours":
|
||||
createdAt.gte = DateUtils.daysFromDate(new Date(), 1 * -1);
|
||||
break;
|
||||
case "year-to-date":
|
||||
const date = new Date();
|
||||
const year = date.getFullYear();
|
||||
createdAt.gte = new Date(year, 0, 1);
|
||||
break;
|
||||
case "month-to-date":
|
||||
createdAt.gte = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
||||
break;
|
||||
case "week-to-date":
|
||||
createdAt.gte = weekStartDate(new Date());
|
||||
break;
|
||||
case "last-hour":
|
||||
createdAt.gte = minutesFromDate(new Date(), 60 * -1);
|
||||
break;
|
||||
case "last-10-minutes":
|
||||
createdAt.gte = minutesFromDate(new Date(), 10 * -1);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
export default {
|
||||
getPeriodFromRequest,
|
||||
getGreaterThanOrEqualsFromRequest,
|
||||
getCreatedAtFilter,
|
||||
getCreatedAt,
|
||||
};
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { getUserHasPermission } from "./PermissionsHelper";
|
||||
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
import type { AppOrAdminData } from "../data/useAppOrAdminData";
|
||||
|
||||
function permissionsData(patch: Partial<AppOrAdminData> = {}): AppOrAdminData {
|
||||
return {
|
||||
user: {} as AppOrAdminData["user"],
|
||||
myTenants: [],
|
||||
currentTenant: null,
|
||||
allRoles: [],
|
||||
permissions: [],
|
||||
entities: [],
|
||||
entityGroups: [],
|
||||
isSuperUser: false,
|
||||
isSuperAdmin: false,
|
||||
myGroups: [],
|
||||
onboardingSession: null,
|
||||
tenantTypes: [],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe("getUserHasPermission", () => {
|
||||
test("defaults closed when permission data is missing", () => {
|
||||
expect(getUserHasPermission(permissionsData({ permissions: undefined as unknown as AppOrAdminData["permissions"] }), "app.settings.members.view")).toBe(false);
|
||||
});
|
||||
|
||||
test("allows super admins before checking permission payload availability", () => {
|
||||
expect(
|
||||
getUserHasPermission(
|
||||
permissionsData({ isSuperAdmin: true, permissions: undefined as unknown as AppOrAdminData["permissions"] }),
|
||||
"app.settings.members.view"
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("checks explicit app and entity permissions", () => {
|
||||
const entityPermission = "entity.contact.read" as DefaultPermission;
|
||||
const data = permissionsData({ permissions: ["app.settings.members.view", entityPermission] });
|
||||
|
||||
expect(getUserHasPermission(data, "app.settings.members.view")).toBe(true);
|
||||
expect(getUserHasPermission(data, entityPermission)).toBe(true);
|
||||
expect(getUserHasPermission(data, "app.settings.subscription.view")).toBe(false);
|
||||
});
|
||||
});
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
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) {
|
||||
return true;
|
||||
}
|
||||
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);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { createLocaleFormatters } from "~/locale/format";
|
||||
import { getYearlyDiscount } from "./PricingHelper";
|
||||
|
||||
describe("getYearlyDiscount", () => {
|
||||
const prices = [
|
||||
{ price: 100, currency: "usd", billingPeriod: SubscriptionBillingPeriod.MONTHLY },
|
||||
{ price: 1000, currency: "usd", billingPeriod: SubscriptionBillingPeriod.YEARLY },
|
||||
];
|
||||
|
||||
it("formats the discount through Intl by default", () => {
|
||||
expect(getYearlyDiscount(prices as never, "usd")).toBe("-17%");
|
||||
});
|
||||
|
||||
it("accepts the active locale percent formatter", () => {
|
||||
const formatters = createLocaleFormatters("de");
|
||||
|
||||
expect(getYearlyDiscount(prices as never, "usd", formatters.percent)).toMatch(/-17\s?%/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import billingPeriods from "~/application/pricing/billingPeriods";
|
||||
import currencies from "~/application/pricing/currencies";
|
||||
import { formatNumber, type LocaleFormatters } from "~/locale/format";
|
||||
|
||||
export function getUsageBasedUnitTitle(t: TFunction, name: string) {
|
||||
if (name === "api") {
|
||||
return t("models.apiCall.object");
|
||||
}
|
||||
return t(`models.${name}.object`);
|
||||
}
|
||||
|
||||
export function getUsageBasedUnitTitlePlural(t: TFunction, name: string) {
|
||||
if (name === "api") {
|
||||
return t("models.apiCall.plural");
|
||||
}
|
||||
return t(`models.${name}.plural`);
|
||||
}
|
||||
|
||||
function defaultFormatPercent(value: number, options?: Intl.NumberFormatOptions): string {
|
||||
return formatNumber(value, "en-US", { style: "percent", ...options });
|
||||
}
|
||||
|
||||
export function getYearlyDiscount(prices: SubscriptionPriceDto[], currency: string, formatPercent: LocaleFormatters["percent"] = defaultFormatPercent) {
|
||||
const priceYearly = prices.find((f) => f.billingPeriod === SubscriptionBillingPeriod.YEARLY && Number(f.price) > 0 && f.currency === currency);
|
||||
const priceMonthly = prices.find((f) => f.billingPeriod === SubscriptionBillingPeriod.MONTHLY && Number(f.price) > 0 && f.currency === currency);
|
||||
if (priceYearly?.price && priceMonthly?.price) {
|
||||
const discount = 100 - (Number(priceYearly.price) * 100) / (Number(priceMonthly.price) * 12);
|
||||
if (discount !== 0) {
|
||||
return formatPercent(-discount / 100, { maximumFractionDigits: 0 });
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getSortedBillingPeriods(items: SubscriptionBillingPeriod[]) {
|
||||
const sorted: SubscriptionBillingPeriod[] = [];
|
||||
billingPeriods.forEach((billingPeriod) => {
|
||||
if (items.includes(billingPeriod.value) && !sorted.includes(billingPeriod.value)) {
|
||||
sorted.push(billingPeriod.value);
|
||||
}
|
||||
});
|
||||
return sorted;
|
||||
}
|
||||
|
||||
export function getSortedCurrencies(items: string[]) {
|
||||
const sorted: string[] = [];
|
||||
currencies
|
||||
.filter((f) => !f.disabled)
|
||||
.forEach((currency) => {
|
||||
if (items.includes(currency.value) && !sorted.includes(currency.value)) {
|
||||
sorted.push(currency.value);
|
||||
}
|
||||
});
|
||||
return sorted;
|
||||
}
|
||||
|
||||
export function getPossibleBillingPeriods(prices: SubscriptionPriceDto[]) {
|
||||
let periods = prices.filter((f) => f.price).flatMap((f) => f.billingPeriod);
|
||||
// remove duplicates
|
||||
periods = periods.filter((v, i, a) => a.indexOf(v) === i);
|
||||
return getSortedBillingPeriods(periods);
|
||||
}
|
||||
|
||||
export function getPossibleCurrencies(prices: SubscriptionPriceDto[]) {
|
||||
let currencies = prices.filter((f) => f.price).flatMap((f) => f.currency);
|
||||
// remove duplicates
|
||||
currencies = currencies.filter((v, i, a) => a.indexOf(v) === i);
|
||||
return getSortedCurrencies(currencies);
|
||||
}
|
||||
|
||||
export function getCurrenciesAndPeriods(prices: SubscriptionPriceDto[], defaultCurrency?: string, defaultBillingPeriod?: SubscriptionBillingPeriod) {
|
||||
if (!defaultCurrency) {
|
||||
defaultCurrency = currencies.find((f) => f.default)?.value ?? "usd";
|
||||
}
|
||||
if (!defaultBillingPeriod) {
|
||||
defaultBillingPeriod = billingPeriods.find((f) => f.default)?.value ?? SubscriptionBillingPeriod.MONTHLY;
|
||||
}
|
||||
|
||||
const currencyState: { value: string; options: string[] } = { value: defaultCurrency, options: getPossibleCurrencies(prices) };
|
||||
if (!currencyState.options.includes(defaultCurrency) && currencyState.options.length > 0) {
|
||||
currencyState.value = currencyState.options[0];
|
||||
}
|
||||
const billingPeriodState: { value: SubscriptionBillingPeriod; options: SubscriptionBillingPeriod[] } = {
|
||||
value: defaultBillingPeriod,
|
||||
options: getPossibleBillingPeriods(prices).filter((f) => f !== SubscriptionBillingPeriod.ONCE),
|
||||
};
|
||||
if (!billingPeriodState.options.includes(defaultBillingPeriod) && billingPeriodState.options.length > 0) {
|
||||
billingPeriodState.value = billingPeriodState.options[0];
|
||||
}
|
||||
|
||||
return {
|
||||
currencies: currencyState,
|
||||
billingPeriods: billingPeriodState,
|
||||
};
|
||||
}
|
||||
|
||||
export function getBillingPeriodParams(billingPeriod: SubscriptionBillingPeriod) {
|
||||
switch (billingPeriod) {
|
||||
case SubscriptionBillingPeriod.ONCE:
|
||||
return "o";
|
||||
case SubscriptionBillingPeriod.DAILY:
|
||||
return "d";
|
||||
case SubscriptionBillingPeriod.WEEKLY:
|
||||
return "w";
|
||||
case SubscriptionBillingPeriod.MONTHLY:
|
||||
return "m";
|
||||
case SubscriptionBillingPeriod.YEARLY:
|
||||
return "y";
|
||||
case SubscriptionBillingPeriod.QUARTERLY:
|
||||
return "q";
|
||||
case SubscriptionBillingPeriod.SEMI_ANNUAL:
|
||||
return "s";
|
||||
default:
|
||||
return "m";
|
||||
}
|
||||
}
|
||||
|
||||
// export function findDiscounts({
|
||||
// currency,
|
||||
// billingPeriods,
|
||||
// products,
|
||||
// }: {
|
||||
// currency: string;
|
||||
// billingPeriods: SubscriptionBillingPeriod[];
|
||||
// products: SubscriptionProductDto[];
|
||||
// }) {
|
||||
// const discounts: { billingPeriod: SubscriptionBillingPeriod; discount: number }[] = [];
|
||||
// // iterate each product and find discounts against the highest price
|
||||
// products.forEach((product) => {
|
||||
// const prices = product.prices.filter((f) => f.currency === currency && billingPeriods.includes(f.billingPeriod));
|
||||
// if (prices.length > 0) {
|
||||
// const highestPrice = prices.reduce((prev, current) => (prev.price > current.price ? prev : current));
|
||||
// console.log("[highestPrice]", highestPrice.price);
|
||||
// prices.forEach((price) => {
|
||||
// if (price.price < highestPrice.price) {
|
||||
// const discount = 100 - (Number(price.price) * 100) / Number(highestPrice.price);
|
||||
// if (discount !== 0) {
|
||||
// discounts.push({ billingPeriod: price.billingPeriod, discount });
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
// return discounts;
|
||||
// }
|
||||
|
||||
export function getDefaultCurrency(request: Request) {
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
let defaultCurrency = currencies.find((f) => f.default)?.value ?? "";
|
||||
if (searchParams.get("c")) {
|
||||
defaultCurrency = searchParams.get("c")?.toString() ?? "";
|
||||
}
|
||||
return defaultCurrency;
|
||||
}
|
||||
|
||||
export function getDefaultBillingPeriod(request: Request) {
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
let defaultBillingPeriod = billingPeriods.find((f) => f.default)?.value ?? SubscriptionBillingPeriod.MONTHLY;
|
||||
if (searchParams.get("b")) {
|
||||
switch (searchParams.get("b")) {
|
||||
case "o":
|
||||
defaultBillingPeriod = SubscriptionBillingPeriod.ONCE;
|
||||
break;
|
||||
case "d":
|
||||
defaultBillingPeriod = SubscriptionBillingPeriod.DAILY;
|
||||
break;
|
||||
case "w":
|
||||
defaultBillingPeriod = SubscriptionBillingPeriod.WEEKLY;
|
||||
break;
|
||||
case "m":
|
||||
defaultBillingPeriod = SubscriptionBillingPeriod.MONTHLY;
|
||||
break;
|
||||
case "y":
|
||||
defaultBillingPeriod = SubscriptionBillingPeriod.YEARLY;
|
||||
break;
|
||||
case "q":
|
||||
defaultBillingPeriod = SubscriptionBillingPeriod.QUARTERLY;
|
||||
break;
|
||||
case "s":
|
||||
defaultBillingPeriod = SubscriptionBillingPeriod.SEMI_ANNUAL;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return defaultBillingPeriod;
|
||||
}
|
||||
|
||||
export function getFormattedPriceInCurrency({
|
||||
price,
|
||||
currency,
|
||||
decimals = 2,
|
||||
withSymbol = true,
|
||||
}: {
|
||||
price: number;
|
||||
currency: string | undefined;
|
||||
decimals?: number;
|
||||
withSymbol?: boolean;
|
||||
}) {
|
||||
let currencyDetails = currencies.find((c) => c.value.toLowerCase() === currency?.toLowerCase()) || currencies.find((c) => c.default);
|
||||
if (!currencyDetails) {
|
||||
// default
|
||||
currencyDetails = currencies.find((f) => f.default);
|
||||
}
|
||||
if (!currencyDetails) {
|
||||
return "Currency not supported: " + currency;
|
||||
}
|
||||
|
||||
const formattedPrice = formatPrice(price, currencyDetails.thousandSeparator, currencyDetails.decimalSeparator, decimals);
|
||||
if (!withSymbol) {
|
||||
return formattedPrice;
|
||||
}
|
||||
return currencyDetails.symbolRight ? `${formattedPrice}${currencyDetails.symbol}` : `${currencyDetails.symbol}${formattedPrice}`;
|
||||
}
|
||||
|
||||
function formatPrice(price: number, thousandSeparator: string = ",", decimalSeparator: string = ".", decimals: number = 2) {
|
||||
const normalized = formatNumber(price, "en-US", {
|
||||
minimumFractionDigits: decimals,
|
||||
maximumFractionDigits: decimals,
|
||||
});
|
||||
return normalized
|
||||
.replace(/,/g, "__GROUP__")
|
||||
.replace(/\./g, decimalSeparator)
|
||||
.replace(/__GROUP__/g, thousandSeparator);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
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" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
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,
|
||||
};
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
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;
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
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,
|
||||
};
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
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,
|
||||
};
|
||||
+387
@@ -0,0 +1,387 @@
|
||||
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,
|
||||
};
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import { Link } from "react-router";
|
||||
import { TFunction } from "i18next";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import { InputType } from "~/application/enums/shared/InputType";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { isKeyShapedLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
function safeTitle(t: TFunction, title: string) {
|
||||
const translated = String(t(title));
|
||||
return translated === title && isKeyShapedLabel(title) ? String(t("shared.invalid")) : translated;
|
||||
}
|
||||
|
||||
function displayRowValue<T>(t: TFunction, header: RowHeaderDisplayDto<T>, item: T, idxRow: number) {
|
||||
return (
|
||||
<>
|
||||
{!header.setValue ? (
|
||||
<>
|
||||
{header.href !== undefined && header.href(item) ? (
|
||||
<Link
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
to={header.href(item) ?? ""}
|
||||
className="focus:bg-secondary/90 hover:border-border rounded-md border-b border-dashed border-transparent"
|
||||
>
|
||||
<span>{header.formattedValue ? header.formattedValue(item, idxRow) : header.value(item, idxRow)}</span>
|
||||
</Link>
|
||||
) : (
|
||||
<span>{header.formattedValue ? header.formattedValue(item, idxRow) : header.value(item, idxRow)}</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{header.type === undefined || header.type === InputType.TEXT ? (
|
||||
<InputText
|
||||
borderless={header.inputBorderless}
|
||||
withLabel={false}
|
||||
name={header.name}
|
||||
title={safeTitle(t, header.title)}
|
||||
value={header.value(item, idxRow)}
|
||||
disabled={header.editable && !header.editable(item, idxRow)}
|
||||
setValue={(e) => {
|
||||
if (header.setValue) {
|
||||
header.setValue(e, idxRow);
|
||||
}
|
||||
}}
|
||||
required={!header.inputOptional}
|
||||
/>
|
||||
) : header.type === InputType.NUMBER ? (
|
||||
<InputNumber
|
||||
borderless={header.inputBorderless}
|
||||
withLabel={false}
|
||||
name={header.name}
|
||||
title={safeTitle(t, header.title)}
|
||||
value={header.value(item, idxRow)}
|
||||
disabled={header.editable && !header.editable(item)}
|
||||
setValue={(e) => {
|
||||
if (header.setValue) {
|
||||
header.setValue(e, idxRow);
|
||||
}
|
||||
}}
|
||||
required={!header.inputOptional}
|
||||
step={header.inputNumberStep}
|
||||
/>
|
||||
) : header.type === InputType.SELECT ? (
|
||||
<InputSelect
|
||||
borderless={header.inputBorderless}
|
||||
withLabel={false}
|
||||
name={header.name}
|
||||
title={safeTitle(t, header.title)}
|
||||
value={header.value(item, idxRow)}
|
||||
setValue={(e) => {
|
||||
if (header.setValue) {
|
||||
header.setValue(Number(e), idxRow);
|
||||
}
|
||||
}}
|
||||
options={header.options ?? []}
|
||||
required={!header.inputOptional}
|
||||
disabled={header.editable && !header.editable(item)}
|
||||
/>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default {
|
||||
displayRowValue,
|
||||
};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
const getFiltersCondition = (filters?: FiltersDto) => {
|
||||
let where = {};
|
||||
if (!filters) {
|
||||
return {};
|
||||
}
|
||||
const queryConditions: any[] = [];
|
||||
const AND_CONDITIONS: any[] = [];
|
||||
|
||||
filters.properties
|
||||
?.filter((f) => !f.manual)
|
||||
.forEach((field) => {
|
||||
if (filters.query && !field.isNumber) {
|
||||
queryConditions.push(getPropertyFilter(field.name, filters.query, field.condition, field.isNumber));
|
||||
}
|
||||
});
|
||||
|
||||
filters.properties
|
||||
?.filter((f) => !f.manual)
|
||||
.forEach((field) => {
|
||||
if (field.value) {
|
||||
AND_CONDITIONS.push(getPropertyFilter(field.name, field.value, field.condition, field.isNumber));
|
||||
}
|
||||
});
|
||||
|
||||
let whereQuery = {};
|
||||
let whereFilters = {};
|
||||
if (queryConditions.length > 0) {
|
||||
whereQuery = {
|
||||
OR: [...queryConditions],
|
||||
};
|
||||
}
|
||||
if (AND_CONDITIONS.length > 0) {
|
||||
whereFilters = {
|
||||
AND: [...AND_CONDITIONS],
|
||||
};
|
||||
}
|
||||
|
||||
const andConditions: any[] = [];
|
||||
if (queryConditions.length > 0) {
|
||||
andConditions.push(whereQuery);
|
||||
}
|
||||
if (AND_CONDITIONS.length > 0) {
|
||||
andConditions.push(whereFilters);
|
||||
}
|
||||
if (andConditions.length > 0) {
|
||||
where = {
|
||||
AND: andConditions,
|
||||
};
|
||||
}
|
||||
return where;
|
||||
};
|
||||
|
||||
function getPropertyFilter(name: string, value: string, condition: string | undefined, isNumber: boolean | undefined) {
|
||||
if (value === "{null}") {
|
||||
return { [name]: null };
|
||||
}
|
||||
if (isNumber) {
|
||||
return { [name]: { [condition ?? "contains"]: Number(value) } };
|
||||
}
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,818 @@
|
||||
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,
|
||||
};
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import Constants from "~/application/Constants";
|
||||
import { getPaginationFromCurrentUrl } from "./RowPaginationHelper";
|
||||
|
||||
function paginationFor(query: string) {
|
||||
return getPaginationFromCurrentUrl(new URLSearchParams(query));
|
||||
}
|
||||
|
||||
describe("RowPaginationHelper", () => {
|
||||
it("defaults invalid pagination params before they reach database queries", () => {
|
||||
expect(paginationFor("page=abc&pageSize=abc")).toMatchObject({
|
||||
page: 1,
|
||||
pageSize: Constants.DEFAULT_PAGE_SIZE,
|
||||
});
|
||||
expect(paginationFor("page=NaN&pageSize=Infinity")).toMatchObject({
|
||||
page: 1,
|
||||
pageSize: Constants.DEFAULT_PAGE_SIZE,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects decimal, zero, and negative pagination params", () => {
|
||||
expect(paginationFor("page=1.5&pageSize=25.5")).toMatchObject({
|
||||
page: 1,
|
||||
pageSize: Constants.DEFAULT_PAGE_SIZE,
|
||||
});
|
||||
expect(paginationFor("page=0&pageSize=0")).toMatchObject({
|
||||
page: 1,
|
||||
pageSize: Constants.DEFAULT_PAGE_SIZE,
|
||||
});
|
||||
expect(paginationFor("page=-3&pageSize=-20")).toMatchObject({
|
||||
page: 1,
|
||||
pageSize: Constants.DEFAULT_PAGE_SIZE,
|
||||
});
|
||||
});
|
||||
|
||||
it("caps oversized page sizes while preserving valid page numbers", () => {
|
||||
expect(paginationFor(`page=3&pageSize=${Constants.MAX_PAGE_SIZE + 1}`)).toMatchObject({
|
||||
page: 3,
|
||||
pageSize: Constants.MAX_PAGE_SIZE,
|
||||
});
|
||||
});
|
||||
});
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
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 } {
|
||||
return {
|
||||
page: getPageFromCurrentUrl(urlSearchParams),
|
||||
pageSize: getPageSizeFromCurrentUrl(urlSearchParams),
|
||||
sortedBy: getSortByFromCurrentUrl(urlSearchParams, entity, entityView),
|
||||
query: getSearchQueryFromCurrentUrl(urlSearchParams),
|
||||
};
|
||||
}
|
||||
|
||||
export function getFiltersFromCurrentUrl(request: Request, properties: FilterablePropertyDto[]): FiltersDto {
|
||||
const url = new URL(request.url);
|
||||
properties.forEach((property) => {
|
||||
const params = url.searchParams.get(property.name);
|
||||
property.value = params ?? null;
|
||||
if (property.isNumber && property.value) {
|
||||
if (isNaN(Number(property.value))) {
|
||||
property.value = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const query = url.searchParams.get("q") ?? undefined;
|
||||
|
||||
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;
|
||||
if (!Number.isSafeInteger(page) || page <= 0) {
|
||||
return 1;
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
function getPageSizeFromCurrentUrl(urlSearchParams: URLSearchParams): number {
|
||||
const paramsPageSize = urlSearchParams.get("pageSize");
|
||||
const pageSize = paramsPageSize ? Number(paramsPageSize) : Constants.DEFAULT_PAGE_SIZE;
|
||||
if (!Number.isSafeInteger(pageSize) || pageSize <= 0) {
|
||||
return Constants.DEFAULT_PAGE_SIZE;
|
||||
}
|
||||
if (pageSize > Constants.MAX_PAGE_SIZE) {
|
||||
return Constants.MAX_PAGE_SIZE;
|
||||
}
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
function getSearchQueryFromCurrentUrl(urlSearchParams: URLSearchParams): string {
|
||||
return urlSearchParams.get("q")?.toString() ?? "";
|
||||
}
|
||||
|
||||
function getSortByFromCurrentUrl(urlSearchParams: URLSearchParams, entity?: EntityWithDetails, entityView?: EntityViewWithDetails | null): SortedByDto[] {
|
||||
let sorts = urlSearchParams.get("sort")?.toString().split(",") ?? [];
|
||||
return sorts.map((sort) => {
|
||||
let direction: "asc" | "desc" = "asc";
|
||||
if (sort) {
|
||||
if (sort.startsWith("-")) {
|
||||
sort = sort.replace("-", "");
|
||||
direction = "desc";
|
||||
} else {
|
||||
direction = "asc";
|
||||
}
|
||||
}
|
||||
const sortName = sort.replace("-", "").replace("+", "");
|
||||
const property = entity?.properties.find((p) => p.name === sortName);
|
||||
return { entity, name: sortName, direction, property };
|
||||
});
|
||||
}
|
||||
|
||||
export function getNewPaginationUrl(request: Request, page: number, sortedBy?: { name: string; direction: "asc" | "desc" }): string {
|
||||
const url = new URL(request.url);
|
||||
const params = new URLSearchParams(url.search);
|
||||
|
||||
//Add a second foo parameter.
|
||||
if (params.get("page")) {
|
||||
params.set("page", page.toString());
|
||||
} else {
|
||||
params.append("page", page.toString());
|
||||
}
|
||||
|
||||
if (sortedBy?.name) {
|
||||
const withDirection = (sortedBy.direction === "desc" ? "-" : "") + sortedBy.name;
|
||||
if (params.get("sort")) {
|
||||
params.set("sort", withDirection);
|
||||
} else {
|
||||
params.append("sort", withDirection);
|
||||
}
|
||||
}
|
||||
|
||||
const newUrl = url + "?" + params;
|
||||
return newUrl;
|
||||
}
|
||||
|
||||
// export async function getPageFromCurrentUrl(request: Request): PaginationDto {
|
||||
// const params = new URL(request.url).searchParams;
|
||||
// const pageSize = Constants.DEFAULT_PAGE_SIZE;
|
||||
|
||||
// let page = 1;
|
||||
// const paramsPage = params.get("page");
|
||||
// if (paramsPage) {
|
||||
// page = Number(paramsPage);
|
||||
// }
|
||||
|
||||
// // const paramsSort = search.get("sort");
|
||||
// // if (!paramsPage) {
|
||||
// // throw redirect(request.url + "?page=1");
|
||||
// // }
|
||||
// // let orderBy: any = { createdAt: "desc" };
|
||||
// // if (paramsSort) {
|
||||
// // const column = paramsSort.replace("-", "").trim();
|
||||
// // if (column === "createdAt" || column === "folio") {
|
||||
// // orderBy = { [column]: paramsSort.startsWith("-") ? "desc" : "asc" };
|
||||
// // }
|
||||
// // }
|
||||
// const pagination: PaginationDto = {
|
||||
// page,
|
||||
// pageSize,
|
||||
// };
|
||||
// return pagination;
|
||||
// }
|
||||
@@ -0,0 +1,121 @@
|
||||
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,
|
||||
};
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,79 @@
|
||||
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;
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { getSubscriptionProduct } from "../db/subscriptionProducts.db.server";
|
||||
|
||||
async function getPlanFromForm(form: FormData) {
|
||||
const productId = form.get("product-id")?.toString() ?? "";
|
||||
const billingPeriod = Number(form.get("billing-period")) as SubscriptionBillingPeriod;
|
||||
const currency = form.get("currency")?.toString() ?? "";
|
||||
const quantity = Number(form.get("quantity"));
|
||||
const coupon = form.get("coupon")?.toString();
|
||||
const isUpgrade = form.get("is-upgrade")?.toString() === "true";
|
||||
const isDowngrade = form.get("is-downgrade")?.toString() === "true";
|
||||
const referral = form.get("referral")?.toString() || null;
|
||||
|
||||
const product = await getSubscriptionProduct(productId);
|
||||
if (!product) {
|
||||
throw Error("Invalid product");
|
||||
}
|
||||
|
||||
let flatPrice: SubscriptionPriceDto | undefined = undefined;
|
||||
let freeTrialDays: number | undefined = undefined;
|
||||
if (product.model === PricingModel.ONCE) {
|
||||
flatPrice = product.prices.find((f) => f.currency === currency && f.billingPeriod === SubscriptionBillingPeriod.ONCE);
|
||||
} else {
|
||||
flatPrice = product.prices.find((f) => f.currency === currency && f.billingPeriod === billingPeriod);
|
||||
}
|
||||
const usageBasedPrices = product?.usageBasedPrices?.filter((f) => f.currency === currency);
|
||||
|
||||
if (!flatPrice && usageBasedPrices?.length === 0) {
|
||||
throw Error("Invalid price");
|
||||
}
|
||||
let mode: "payment" | "setup" | "subscription" = "subscription";
|
||||
const line_items: { price: string; quantity?: number }[] = [];
|
||||
if (product.model === PricingModel.ONCE) {
|
||||
mode = "payment";
|
||||
}
|
||||
|
||||
if (flatPrice) {
|
||||
line_items.push({ price: flatPrice.stripeId, quantity });
|
||||
if (flatPrice.trialDays > 0) {
|
||||
freeTrialDays = flatPrice.trialDays;
|
||||
}
|
||||
}
|
||||
usageBasedPrices?.forEach((usageBasedPrice) => {
|
||||
line_items.push({ price: usageBasedPrice.stripeId });
|
||||
});
|
||||
|
||||
return {
|
||||
mode,
|
||||
line_items,
|
||||
product,
|
||||
flatPrice,
|
||||
usageBasedPrices,
|
||||
freeTrialDays,
|
||||
coupon,
|
||||
isUpgrade,
|
||||
isDowngrade,
|
||||
referral,
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
getPlanFromForm,
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
export function getSortedItems(items: any[]) {
|
||||
return items.slice().sort((x, y) => {
|
||||
return x.order > y.order ? 1 : -1;
|
||||
});
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
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,
|
||||
};
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
|
||||
|
||||
function getVisibilityTitle(t: TFunction, visibility: string) {
|
||||
switch (visibility) {
|
||||
case DefaultVisibility.Private:
|
||||
return t("shared.private");
|
||||
case DefaultVisibility.Tenant:
|
||||
return "Everyone on the account";
|
||||
case DefaultVisibility.Public:
|
||||
return t("shared.public");
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export default { getVisibilityTitle };
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
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,
|
||||
};
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
const includeDetails = {
|
||||
properties: true,
|
||||
filters: true,
|
||||
sort: true,
|
||||
groupByProperty: true,
|
||||
};
|
||||
|
||||
export default {
|
||||
includeDetails,
|
||||
};
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
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,
|
||||
};
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import RowModelHelper from "./RowModelHelper";
|
||||
import TenantSubscriptionProductModelHelper from "./TenantSubscriptionProductModelHelper";
|
||||
import UserModelHelper from "./UserModelHelper";
|
||||
|
||||
const selectSimpleTenantProperties = {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
icon: true,
|
||||
logo: true,
|
||||
deactivatedReason: true,
|
||||
types: true,
|
||||
active: true,
|
||||
theme: true,
|
||||
themeConfig: true,
|
||||
};
|
||||
|
||||
const includeTenantWithDetails = {
|
||||
inboundAddresses: true,
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
subscription: {
|
||||
include: {
|
||||
products: {
|
||||
include: { ...TenantSubscriptionProductModelHelper.includeTenantSubscriptionProductDetails },
|
||||
},
|
||||
},
|
||||
},
|
||||
tenantSettingsRow: { include: { row: { include: RowModelHelper.includeRowDetails } } },
|
||||
types: true,
|
||||
};
|
||||
|
||||
const includeTenantWithUsage = {
|
||||
inboundAddresses: true,
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
subscription: {
|
||||
include: {
|
||||
products: { include: { ...TenantSubscriptionProductModelHelper.includeTenantSubscriptionProductDetails } },
|
||||
},
|
||||
},
|
||||
tenantSettingsRow: { include: { row: { include: RowModelHelper.includeRowDetails } } },
|
||||
types: true,
|
||||
_count: true,
|
||||
};
|
||||
|
||||
export default {
|
||||
selectSimpleTenantProperties,
|
||||
includeTenantWithDetails,
|
||||
includeTenantWithUsage,
|
||||
};
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
const includeTenantSubscriptionProductDetails = {
|
||||
subscriptionProduct: { include: { features: true } },
|
||||
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
|
||||
};
|
||||
|
||||
export default {
|
||||
includeTenantSubscriptionProductDetails,
|
||||
};
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
export const selectSimpleUserProperties = {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
phone: true,
|
||||
locale: true,
|
||||
createdAt: true,
|
||||
};
|
||||
|
||||
const selectWithAvatar = {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
avatar: true,
|
||||
phone: true,
|
||||
admin: true,
|
||||
defaultTenantId: true,
|
||||
createdAt: true,
|
||||
locale: true,
|
||||
};
|
||||
|
||||
const includeSimpleCreatedByUser = {
|
||||
createdByUser: {
|
||||
select: selectSimpleUserProperties,
|
||||
},
|
||||
};
|
||||
|
||||
const includeSimpleUser = {
|
||||
user: {
|
||||
select: selectSimpleUserProperties,
|
||||
},
|
||||
};
|
||||
|
||||
export default {
|
||||
includeSimpleCreatedByUser,
|
||||
includeSimpleUser,
|
||||
selectSimpleUserProperties,
|
||||
selectWithAvatar,
|
||||
};
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
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")');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user