Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
No files matched your search
@@ -5,7 +5,7 @@ import { CookieCategory } from "./CookieCategory";
|
||||
const allApplicationCookies: ApplicationCookie[] = [
|
||||
{
|
||||
category: CookieCategory.REQUIRED,
|
||||
name: "RJ_session",
|
||||
name: "hivegrid_session",
|
||||
expiry: "1 month",
|
||||
expiryKey: "cookies.expiry.oneMonth",
|
||||
descriptionKey: "cookies.items.session.description",
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
export type ApiKeyEntityPermissionDto = {
|
||||
id: string;
|
||||
name: string;
|
||||
create: boolean;
|
||||
read: boolean;
|
||||
update: boolean;
|
||||
delete: boolean;
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
export type BillingProviderCouponDto = {
|
||||
amount_off?: number | null;
|
||||
percent_off?: number | null;
|
||||
currency?: string | null;
|
||||
applies_to?: {
|
||||
products: string[];
|
||||
} | null;
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { BillingGatewayInvoice } from "@hivegrid/billing";
|
||||
|
||||
export type CustomerBillingInvoiceDto = {
|
||||
id: string;
|
||||
number: string | null;
|
||||
issuingDate: string | null;
|
||||
amountCents: number | null;
|
||||
currency: string | null;
|
||||
status: BillingGatewayInvoice["status"];
|
||||
paymentStatus: BillingGatewayInvoice["paymentStatus"];
|
||||
invoiceType: string | null;
|
||||
downloadHref: string | null;
|
||||
};
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Entity, Property } from "@toolctrl/db/prisma-browser";
|
||||
import { EntityRelationshipWithDetails } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
|
||||
export interface RowFiltersDto {
|
||||
customRow: boolean;
|
||||
entity: Entity;
|
||||
query: string | null;
|
||||
properties: {
|
||||
property?: Property;
|
||||
name?: string;
|
||||
value: string | string[] | null;
|
||||
condition?: string;
|
||||
match?: "and" | "or";
|
||||
parentEntity?: EntityRelationshipWithDetails;
|
||||
}[];
|
||||
tags: string[];
|
||||
}
|
||||
@@ -1,8 +1,4 @@
|
||||
import { Entity, Property } from "@toolctrl/db/prisma-browser";
|
||||
|
||||
export interface SortedByDto {
|
||||
name: string;
|
||||
direction: "asc" | "desc";
|
||||
property?: Property;
|
||||
entity?: Entity;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { Entity, Property, RowValue } from "@toolctrl/db/prisma-browser";
|
||||
|
||||
export interface RowDynamicValuesDto {
|
||||
form: Entity | undefined;
|
||||
name: string;
|
||||
total: number;
|
||||
headers: (RowValue & { property: Property })[];
|
||||
// details: RequestDetailDto[];
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { RowMedia, RowValueMultiple, RowValueRange } from "@toolctrl/db/prisma-browser";
|
||||
import { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
|
||||
export type RowValueDto = {
|
||||
id?: string | null;
|
||||
property: PropertyWithDetails;
|
||||
propertyId: string;
|
||||
textValue?: string | undefined;
|
||||
numberValue?: number | undefined;
|
||||
dateValue?: Date | undefined;
|
||||
booleanValue?: boolean | undefined;
|
||||
selectedOption?: string | undefined;
|
||||
media?: RowMedia[];
|
||||
multiple?: RowValueMultiple[];
|
||||
range?: RowValueRange | undefined;
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
export type SetupItem = {
|
||||
title: string;
|
||||
description: string;
|
||||
completed: boolean;
|
||||
path: string | undefined;
|
||||
};
|
||||
@@ -27,12 +27,6 @@ export const DefaultPermissions = [
|
||||
"admin.roles.update",
|
||||
"admin.roles.delete",
|
||||
"admin.roles.set",
|
||||
"admin.analytics.view",
|
||||
"admin.analytics.delete",
|
||||
"admin.entities.view",
|
||||
"admin.entities.create",
|
||||
"admin.entities.update",
|
||||
"admin.entities.delete",
|
||||
// "admin.workflows.view",
|
||||
// "admin.workflows.create",
|
||||
// "admin.workflows.update",
|
||||
@@ -51,10 +45,6 @@ export const DefaultPermissions = [
|
||||
"admin.emails.create",
|
||||
"admin.emails.update",
|
||||
"admin.emails.delete",
|
||||
"admin.onboarding.view",
|
||||
"admin.onboarding.create",
|
||||
"admin.onboarding.update",
|
||||
"admin.onboarding.delete",
|
||||
"admin.notifications.view",
|
||||
"admin.notifications.manage",
|
||||
"admin.featureFlags.view",
|
||||
@@ -68,10 +58,6 @@ export const DefaultPermissions = [
|
||||
"admin.prompts.create",
|
||||
"admin.prompts.update",
|
||||
"admin.prompts.delete",
|
||||
"admin.formulas.view",
|
||||
"admin.formulas.create",
|
||||
"admin.formulas.update",
|
||||
"admin.formulas.delete",
|
||||
"admin.metrics.view",
|
||||
"admin.metrics.update",
|
||||
"admin.metrics.delete",
|
||||
@@ -86,13 +72,19 @@ export const DefaultPermissions = [
|
||||
"admin.settings.general.update",
|
||||
"admin.settings.authentication.view",
|
||||
"admin.settings.authentication.update",
|
||||
"admin.settings.analytics.view",
|
||||
"admin.settings.analytics.update",
|
||||
"admin.settings.seo.update",
|
||||
"admin.settings.internationalization.view",
|
||||
"admin.settings.internationalization.update",
|
||||
"admin.settings.danger.reset",
|
||||
"app.dashboard.view",
|
||||
// P11 Dashboard (R-P11b) — see packages/db permissions-seed.
|
||||
"dashboard.read",
|
||||
"dashboard.customize",
|
||||
// P12 Automation (R-P12a) — see packages/db permissions-seed.
|
||||
"automation.read",
|
||||
"automation.manage",
|
||||
"automation.run",
|
||||
"automation.admin",
|
||||
"app.settings.members.view",
|
||||
"app.settings.members.create",
|
||||
"app.settings.members.update",
|
||||
@@ -105,6 +97,8 @@ export const DefaultPermissions = [
|
||||
"app.settings.subscription.update",
|
||||
"app.settings.subscription.delete",
|
||||
"app.settings.subscription.invoices.view",
|
||||
"app.onboarding.demoData.manage",
|
||||
"app.onboarding.checklist.update",
|
||||
"app.settings.account.view",
|
||||
"app.settings.account.update",
|
||||
"app.settings.account.delete",
|
||||
@@ -131,6 +125,105 @@ export const DefaultPermissions = [
|
||||
"tasks.write",
|
||||
"tasks.delete",
|
||||
"tasks.admin",
|
||||
// P6 CRM core (R-P6) — see packages/db permissions-seed (same list).
|
||||
"crm.read_own",
|
||||
"crm.read_all",
|
||||
"crm.write",
|
||||
"crm.delete",
|
||||
"crm.admin",
|
||||
// P7 Lead-Inbox (R-P7) — see packages/db permissions-seed (same list).
|
||||
"leads.read_own",
|
||||
"leads.read_all",
|
||||
"leads.write",
|
||||
"leads.delete",
|
||||
"leads.admin",
|
||||
// P8 Projekt/Pipelines (R-P8a) — see packages/db permissions-seed.
|
||||
"projects.read_own",
|
||||
"projects.read_own_member",
|
||||
"projects.read_own_pl",
|
||||
"projects.read_all",
|
||||
"projects.write",
|
||||
"projects.change_stage",
|
||||
"projects.manage_members",
|
||||
"projects.delete",
|
||||
"projects.admin",
|
||||
// P9 Plantafel + Abnahme (R-P9b) — see packages/db permissions-seed.
|
||||
"plantafel.read_own",
|
||||
"plantafel.read_all",
|
||||
"plantafel.write",
|
||||
"plantafel.bulk_reassign",
|
||||
"acceptance.read",
|
||||
"acceptance.write",
|
||||
"acceptance.admin",
|
||||
"deals.read_volume_own",
|
||||
"deals.read_volume_all",
|
||||
"deals.read_aggregates",
|
||||
// P17 HR-Hub core (AK-P17a) — see packages/db permissions-seed (same list).
|
||||
"hr.read_own",
|
||||
"hr.read_all",
|
||||
"hr.write",
|
||||
"hr.admin",
|
||||
"hr.passwordsafe.use",
|
||||
"hr.passwordsafe.admin",
|
||||
// P17 HR-Hub workflows (AK-P17b) — see packages/db permissions-seed (same list).
|
||||
"hr.leave.approve",
|
||||
"hr.surveys.results",
|
||||
// P14 Email (AK-P14a) — tenant-side sending-domain management (see packages/db
|
||||
// permissions-seed, same list). The module itself is feature-gated
|
||||
// (email-marketing); these gate viewing/managing the sending domain + suppression.
|
||||
"email.domain.view",
|
||||
"email.domain.manage",
|
||||
// P14 Email-Marketing (AK-P14b) — see packages/db permissions-seed (same list).
|
||||
"emailMarketing.view",
|
||||
"emailMarketing.manage",
|
||||
// P23 Postfach-Sync (VA-P23) — see packages/db permissions-seed (same list).
|
||||
// read_own: mails of the user's OWN connected mailboxes; read_all: every
|
||||
// tenant mailbox; write: compose/send over the own mailbox (M09 Block I).
|
||||
"email.read_own",
|
||||
"email.read_all",
|
||||
"email.write",
|
||||
// P5 Apps-Engine (R-P5) — see packages/db permissions-seed (same list).
|
||||
"integrations.read",
|
||||
"integrations.connect",
|
||||
"integrations.disconnect",
|
||||
"integrations.manual_sync",
|
||||
"integrations.view_logs",
|
||||
"integrations.admin",
|
||||
// P16 Calendar-Sync (AK-P16a) — see packages/db permissions-seed (same list).
|
||||
// connect_own: connect/manage your OWN calendar; admin: tenant-wide oversight
|
||||
// + force-disconnect on user offboarding (M25 Block I).
|
||||
"calendar.connect_own",
|
||||
"calendar.admin",
|
||||
// P16 Booking (AK-P16b) — see packages/db permissions-seed (same list). Cumulative
|
||||
// bundle (M06 Block K): read_own < read_all < write < admin. read_own/write are
|
||||
// owner-filtered server-side (provider_user_id = self).
|
||||
"bookings.read_own",
|
||||
"bookings.read_all",
|
||||
"bookings.write",
|
||||
"bookings.admin",
|
||||
// P16 Forms (AK-P16c) — see packages/db permissions-seed (same list).
|
||||
"forms.basic",
|
||||
"forms.builder",
|
||||
"forms.publisher",
|
||||
"forms.admin",
|
||||
// P16 Signature (AK-P16d) — see packages/db permissions-seed (same list).
|
||||
// Cumulative bundle: read < send < revoke < admin. read/send are owner-filtered
|
||||
// server-side through the linked Projekt; admin can manage every tenant document.
|
||||
"signature.read",
|
||||
"signature.send",
|
||||
"signature.revoke",
|
||||
"signature.admin",
|
||||
// P11 Global Search (R-P11a) — search.use opens Cmd+K and full search;
|
||||
// search.admin is reserved for reindex/admin controls.
|
||||
"search.use",
|
||||
"search.admin",
|
||||
// P21 Privacy/GDPR (AK-P21) — see packages/db permissions-seed (same list).
|
||||
"privacy.user_export.self",
|
||||
"privacy.tenant_export",
|
||||
"privacy.tenant_deletion",
|
||||
"privacy.avv.read",
|
||||
"privacy.avv.accept",
|
||||
"privacy.subprocessors.read",
|
||||
// "entity.{name}.view",
|
||||
// "entity.{name}.read",
|
||||
// "entity.{name}.create",
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { SubscriptionProductDto } from "./SubscriptionProductDto";
|
||||
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { SubscriptionUsageBasedTier } from "@toolctrl/db/prisma-browser";
|
||||
import { SubscriptionUsageBasedTier } from "@hivegrid/db/prisma-browser";
|
||||
import { Decimal } from "decimal.js";
|
||||
|
||||
export interface SubscriptionPriceDto {
|
||||
id?: string;
|
||||
stripeId: string;
|
||||
billingProviderId: string;
|
||||
type: SubscriptionPriceType;
|
||||
billingPeriod: SubscriptionBillingPeriod;
|
||||
price: number | Decimal;
|
||||
|
||||
@@ -2,11 +2,11 @@ import { SubscriptionPriceDto } from "./SubscriptionPriceDto";
|
||||
import { SubscriptionFeatureDto } from "./SubscriptionFeatureDto";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { SubscriptionUsageBasedPriceDto } from "./SubscriptionUsageBasedPriceDto";
|
||||
import { TenantSubscriptionProduct, TenantType } from "@toolctrl/db/prisma-browser";
|
||||
import { TenantSubscriptionProduct, TenantType } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
export interface SubscriptionProductDto {
|
||||
id?: string;
|
||||
stripeId: string;
|
||||
billingProviderId: string;
|
||||
order: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { SubscriptionUsageBasedTierDto } from "./SubscriptionUsageBasedTierDto";
|
||||
export interface SubscriptionUsageBasedPriceDto {
|
||||
id: string;
|
||||
subscriptionProductId: string;
|
||||
stripeId: string;
|
||||
billingProviderId: string;
|
||||
billingPeriod: SubscriptionBillingPeriod;
|
||||
currency: string;
|
||||
unit: string;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getEnvVariableDefinition } from "@toolctrl/config";
|
||||
import { loadFeatureManifests } from "@toolctrl/plugins";
|
||||
import { queueNames } from "@toolctrl/queue";
|
||||
import { getEnvVariableDefinition } from "@hivegrid/config";
|
||||
import { loadFeatureManifests } from "@hivegrid/plugins";
|
||||
import { queueNames } from "@hivegrid/queue";
|
||||
|
||||
const manifestLoad = await loadFeatureManifests();
|
||||
const manifests = manifestLoad.manifests;
|
||||
@@ -125,34 +125,7 @@ describe("feature manifests", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("includes the AI chatbot reference pattern for admin-managed worker-backed features", () => {
|
||||
const chatbot = manifests.find((manifest) => manifest.id === "ai-chatbot-admin-managed");
|
||||
|
||||
expect(chatbot).toBeDefined();
|
||||
expect(chatbot?.integration.ownership).toBe("admin-managed");
|
||||
expect(chatbot?.integration.externalProviders).toContain("deployment-region-ai-provider");
|
||||
expect(chatbot?.integration.workers.required).toBe(true);
|
||||
expect(chatbot?.integration.workers.queues).toContain(queueNames.aiChatbot);
|
||||
expect(chatbot?.integration.workers.queues).toContain(queueNames.browserAutomation);
|
||||
expect(chatbot?.integration.workers.jobs).toEqual(expect.arrayContaining(["chat-completion", "browser-session-run", "browser-session-cleanup", "usage-flush"]));
|
||||
expect(chatbot?.integration.configuration.environment).toEqual(
|
||||
expect.arrayContaining([
|
||||
"MISTRAL_API_KEY",
|
||||
"MISTRAL_MODEL",
|
||||
"SCALEWAY_API_KEY",
|
||||
"SCALEWAY_MODEL",
|
||||
"SCALEWAY_BASE_URL",
|
||||
"ALEPH_ALPHA_API_KEY",
|
||||
"ALEPH_ALPHA_MODEL",
|
||||
"ALEPH_ALPHA_BASE_URL",
|
||||
"BULLMQ_REDIS_URL",
|
||||
"BROWSER_RUNTIME_URL",
|
||||
])
|
||||
);
|
||||
expect(chatbot?.integration.configuration.secrets.join(" ")).toContain("never be exposed");
|
||||
});
|
||||
|
||||
it("keeps admin-managed AI/browser feature contracts backed by config and queue packages", () => {
|
||||
it("keeps admin-managed browser feature contracts backed by config and queue packages", () => {
|
||||
[
|
||||
"BULLMQ_REDIS_URL",
|
||||
"BROWSER_RUNTIME_URL",
|
||||
@@ -164,7 +137,6 @@ describe("feature manifests", () => {
|
||||
expect(definition?.targets.some((target) => target === "api" || target === "worker"), name).toBe(true);
|
||||
});
|
||||
|
||||
expect(queueNames.aiChatbot).toBe("toolctrl.ai-chatbot");
|
||||
expect(queueNames.browserAutomation).toBe("toolctrl.browser-automation");
|
||||
expect(queueNames.browserAutomation).toBe("hivegrid.browser-automation");
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ describe("currencies", () => {
|
||||
name: "United States Dollar",
|
||||
value: "usd",
|
||||
symbol: "$",
|
||||
default: true,
|
||||
default: false,
|
||||
disabled: false,
|
||||
parities: [{ from: "usd", parity: 1 }],
|
||||
symbolRight: false,
|
||||
@@ -20,7 +20,8 @@ describe("currencies", () => {
|
||||
name: "Euro",
|
||||
value: "eur",
|
||||
symbol: "€",
|
||||
disabled: true,
|
||||
default: true,
|
||||
disabled: false,
|
||||
parities: [{ from: "usd", parity: 1 }],
|
||||
symbolRight: true,
|
||||
thousandSeparator: ".",
|
||||
|
||||
@@ -5,7 +5,7 @@ const currencies: CurrencyDto[] = [
|
||||
name: "United States Dollar",
|
||||
value: "usd",
|
||||
symbol: "$",
|
||||
default: true,
|
||||
default: false,
|
||||
disabled: false,
|
||||
parities: [{ from: "usd", parity: 1 }],
|
||||
symbolRight: false,
|
||||
@@ -16,7 +16,8 @@ const currencies: CurrencyDto[] = [
|
||||
name: "Euro",
|
||||
value: "eur",
|
||||
symbol: "€",
|
||||
disabled: true,
|
||||
default: true,
|
||||
disabled: false,
|
||||
parities: [{ from: "usd", parity: 1 }],
|
||||
symbolRight: true,
|
||||
thousandSeparator: ".",
|
||||
|
||||
@@ -16,7 +16,7 @@ const UNIT_API_CALL = {
|
||||
|
||||
function generatePrice(currency: string, price: number, billingPeriod: SubscriptionBillingPeriod): SubscriptionPriceDto {
|
||||
return {
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
subscriptionProductId: "",
|
||||
type: billingPeriod === SubscriptionBillingPeriod.ONCE ? SubscriptionPriceType.ONE_TIME : SubscriptionPriceType.RECURRING,
|
||||
billingPeriod,
|
||||
@@ -56,7 +56,7 @@ function generateUsageBasedPrice(
|
||||
});
|
||||
return {
|
||||
id: "",
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
subscriptionProductId: "",
|
||||
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
|
||||
currency,
|
||||
@@ -74,7 +74,7 @@ function generateUsageBasedPrice(
|
||||
function generateCommonPlan(order: number, model: PricingModel) {
|
||||
if (order === 1) {
|
||||
return {
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title: "pricing.products.plan1.title",
|
||||
description: "pricing.products.plan1.description",
|
||||
@@ -112,7 +112,7 @@ function generateCommonPlan(order: number, model: PricingModel) {
|
||||
};
|
||||
} else if (order === 2) {
|
||||
return {
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title: "pricing.products.plan2.title",
|
||||
description: "pricing.products.plan2.description",
|
||||
@@ -149,7 +149,7 @@ function generateCommonPlan(order: number, model: PricingModel) {
|
||||
};
|
||||
} else if (order === 3) {
|
||||
return {
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title: "pricing.products.plan3.title",
|
||||
description: "pricing.products.plan3.description",
|
||||
@@ -187,7 +187,7 @@ function generateCommonPlan(order: number, model: PricingModel) {
|
||||
}
|
||||
|
||||
return {
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title: "pricing.products.plan1.title",
|
||||
description: "pricing.products.plan1.description",
|
||||
@@ -241,12 +241,6 @@ const FLAT_RATE_PRICES: SubscriptionProductDto[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const PER_SEAT_PRICES: SubscriptionProductDto[] = [
|
||||
...FLAT_RATE_PRICES.map((item) => {
|
||||
return { ...item, model: PricingModel.PER_SEAT };
|
||||
}),
|
||||
];
|
||||
|
||||
const USAGE_BASED_PRICES: SubscriptionProductDto[] = [
|
||||
{
|
||||
...generateCommonPlan(1, PricingModel.USAGE_BASED),
|
||||
@@ -327,5 +321,5 @@ const ONE_TIME_PRICES: SubscriptionProductDto[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const plans = [...FLAT_RATE_PRICES, ...PER_SEAT_PRICES, ...USAGE_BASED_PRICES, ...FLAT_RATE_PLUS_USAGE_BASED_PRICES, ...ONE_TIME_PRICES];
|
||||
const plans = [...FLAT_RATE_PRICES, ...USAGE_BASED_PRICES, ...FLAT_RATE_PLUS_USAGE_BASED_PRICES, ...ONE_TIME_PRICES];
|
||||
export default plans;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import plans from "~/application/pricing/plans.server";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { HIVEGRID_SUBSCRIPTION_PRICING_MODELS, isHiveGridSubscriptionPricingModel } from "./pricingModelPolicy";
|
||||
|
||||
describe("HiveGrid subscription pricing model policy", () => {
|
||||
it("does not allow seat-type pricing models", () => {
|
||||
expect(HIVEGRID_SUBSCRIPTION_PRICING_MODELS).not.toContain(PricingModel.PER_SEAT);
|
||||
expect(isHiveGridSubscriptionPricingModel(PricingModel.PER_SEAT)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps generated admin pricing seeds free of seat-type plans", () => {
|
||||
expect(plans).not.toHaveLength(0);
|
||||
expect(plans.map((plan) => plan.model)).not.toContain(PricingModel.PER_SEAT);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
|
||||
export const HIVEGRID_SUBSCRIPTION_PRICING_MODELS = [
|
||||
PricingModel.FLAT_RATE,
|
||||
PricingModel.USAGE_BASED,
|
||||
PricingModel.FLAT_RATE_USAGE_BASED,
|
||||
PricingModel.ONCE,
|
||||
] as const;
|
||||
|
||||
export function isHiveGridSubscriptionPricingModel(model: PricingModel) {
|
||||
return HIVEGRID_SUBSCRIPTION_PRICING_MODELS.includes(model as (typeof HIVEGRID_SUBSCRIPTION_PRICING_MODELS)[number]);
|
||||
}
|
||||
|
||||
@@ -82,13 +82,11 @@ describe("AdminSidebar", () => {
|
||||
expect(Array.isArray(sidebar)).toBe(true);
|
||||
expect(serialized).toContain("/dashboard");
|
||||
expect(serialized).toContain("/accounts");
|
||||
expect(serialized).toContain("/analytics/overview");
|
||||
expect(serialized).toContain("/audit-trails");
|
||||
expect(serialized).toContain("/notifications/messages");
|
||||
expect(serialized).toContain("/feature-flags/flags");
|
||||
expect(serialized).toContain("/onboarding/onboardings");
|
||||
expect(serialized).toContain("/metrics/summary");
|
||||
expect(serialized).toContain("/settings/profile");
|
||||
expect(serialized).not.toContain("/metrics");
|
||||
expect(sidebar).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
@@ -100,7 +98,7 @@ describe("AdminSidebar", () => {
|
||||
);
|
||||
expect(sidebar.at(-1)?.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: "ui.nav.admin.switchToApp", path: "/", exact: true }),
|
||||
expect.objectContaining({ id: "ui.nav.admin.switchToApp", path: "/select-tenant", permission: "admin.accounts.view", exact: true }),
|
||||
])
|
||||
);
|
||||
const emittedPaths = serialized.match(/"path":"[^"]*"/g) ?? [];
|
||||
|
||||
@@ -6,7 +6,6 @@ import { AppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import IconSettings from "~/components/layouts/icons/IconSettings";
|
||||
import IconApp from "~/components/layouts/icons/IconApp";
|
||||
import IconKeys from "~/components/layouts/icons/IconKeys";
|
||||
import IconEntities from "~/components/layouts/icons/IconEntities";
|
||||
import IconAnalytics from "~/components/layouts/icons/IconAnalytics";
|
||||
import IconDocs from "~/components/layouts/icons/IconDocs";
|
||||
import IconEmails from "~/components/layouts/icons/IconEmails";
|
||||
@@ -14,18 +13,13 @@ import IconEvents from "~/components/layouts/icons/IconEvents";
|
||||
import IconFeatureFlags from "~/components/layouts/icons/IconFeatureFlags";
|
||||
import IconHelpDesk from "~/components/layouts/icons/IconHelpDesk";
|
||||
import IconMetrics from "~/components/layouts/icons/IconMetrics";
|
||||
import IconNavigation from "~/components/layouts/icons/IconNavigation";
|
||||
import IconNotifications from "~/components/layouts/icons/IconNotifications";
|
||||
import IconOnboarding from "~/components/layouts/icons/IconOnboarding";
|
||||
import IconPortals from "~/components/layouts/icons/IconPortals";
|
||||
import IconWorkflows from "~/components/layouts/icons/IconWorkflows";
|
||||
import { UI_NAV_IDS } from "~/application/ui/uiRegistry";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absoluteAppRootPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import type { PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import { disabledPluginRouteSlugs } from "~/utils/app/PublicRouteSegments";
|
||||
|
||||
const adminSidebarPath = (path?: string) => adminPath(path, { mode: "host-aware" });
|
||||
const rootAppFallbackPath = "/";
|
||||
const disabledAdminRouteSlugs = new Set<string>(disabledPluginRouteSlugs);
|
||||
|
||||
function isAdminRouteEnabled(slug: string) {
|
||||
@@ -42,7 +36,7 @@ type Props = {
|
||||
routing?: PublicDomainRoutingConfig;
|
||||
};
|
||||
|
||||
export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarItem[] => [
|
||||
export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
|
||||
{
|
||||
id: "ui.nav.admin.primary",
|
||||
title: "",
|
||||
@@ -92,6 +86,13 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
items: [],
|
||||
permission: "admin.accounts.view",
|
||||
},
|
||||
{
|
||||
id: "ui.nav.admin.accounts.billing",
|
||||
title: t("admin.billing.title"),
|
||||
path: adminSidebarPath("accounts/billing"),
|
||||
items: [],
|
||||
permission: "admin.account.subscription",
|
||||
},
|
||||
{
|
||||
id: "ui.nav.admin.accounts.rolesAndPermissions",
|
||||
title: t("app.sidebar.rolesAndPermissions"),
|
||||
@@ -117,32 +118,16 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
permission: "admin.accounts.view",
|
||||
},
|
||||
{
|
||||
id: UI_NAV_IDS.adminAnalytics,
|
||||
title: t("app.sidebar.analytics"),
|
||||
path: adminSidebarPath("analytics"),
|
||||
icon: <IconAnalytics />,
|
||||
id: UI_NAV_IDS.adminAudit,
|
||||
title: t("admin.auditAndEvents"),
|
||||
path: adminSidebarPath("audit"),
|
||||
icon: <IconEvents />,
|
||||
isCollapsible: true,
|
||||
items: [
|
||||
{ id: "ui.nav.admin.analytics.overview", title: t("app.sidebar.overview"), path: adminSidebarPath("analytics/overview"), permission: "admin.analytics.view" },
|
||||
{ id: "ui.nav.admin.analytics.pageViews", title: t("app.sidebar.pageViews"), path: adminSidebarPath("analytics/page-views"), permission: "admin.analytics.view" },
|
||||
{ id: "ui.nav.admin.analytics.visitors", title: t("app.sidebar.visitors"), path: adminSidebarPath("analytics/visitors"), permission: "admin.analytics.view" },
|
||||
{ id: "ui.nav.admin.analytics.events", title: t("models.event.plural"), path: adminSidebarPath("analytics/events"), permission: "admin.analytics.view" },
|
||||
{ id: "ui.nav.admin.analytics.settings", title: t("app.sidebar.settings"), path: adminSidebarPath("analytics/settings"), permission: "admin.settings.analytics.view" },
|
||||
{ id: "ui.nav.admin.audit.viewer", title: t("app.sidebar.audit"), path: adminSidebarPath("audit"), permission: "admin.auditTrails.view" },
|
||||
{ id: "ui.nav.admin.audit.trails", title: t("app.sidebar.auditTrails"), path: adminSidebarPath("audit-trails"), permission: "admin.auditTrails.view" },
|
||||
{ id: "ui.nav.admin.audit.events", title: t("models.event.plural"), path: adminSidebarPath("events"), permission: "admin.events.view" },
|
||||
],
|
||||
permission: "admin.analytics.view",
|
||||
},
|
||||
{
|
||||
id: UI_NAV_IDS.adminEvents,
|
||||
title: t("models.event.plural"),
|
||||
path: adminSidebarPath("events"),
|
||||
icon: <IconEvents />,
|
||||
permission: "admin.events.view",
|
||||
},
|
||||
{
|
||||
id: UI_NAV_IDS.adminAuditTrails,
|
||||
title: t("app.sidebar.auditTrails"),
|
||||
path: adminSidebarPath("audit-trails"),
|
||||
icon: <IconEvents />,
|
||||
permission: "admin.auditTrails.view",
|
||||
},
|
||||
{
|
||||
@@ -161,31 +146,10 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "ui.nav.admin.build",
|
||||
title: t("segments.build"),
|
||||
id: "ui.nav.admin.platform",
|
||||
title: t("segments.platform"),
|
||||
path: "",
|
||||
items: [
|
||||
{
|
||||
id: UI_NAV_IDS.adminEntities,
|
||||
title: t("models.entity.plural"),
|
||||
path: adminSidebarPath("entities"),
|
||||
icon: <IconEntities />,
|
||||
permission: "admin.entities.view",
|
||||
},
|
||||
...enabledAdminRouteItem("workflow-engine", {
|
||||
id: UI_NAV_IDS.adminWorkflows,
|
||||
title: t("models.workflow.plural"),
|
||||
path: adminSidebarPath("workflow-engine"),
|
||||
icon: <IconWorkflows />,
|
||||
isCollapsible: true,
|
||||
items: [
|
||||
{ id: "ui.nav.admin.workflows.workflows", title: t("models.workflow.plural"), path: adminSidebarPath("workflow-engine/workflows") },
|
||||
{ id: "ui.nav.admin.workflows.executions", title: t("app.sidebar.executions"), path: adminSidebarPath("workflow-engine/executions") },
|
||||
{ id: "ui.nav.admin.workflows.templates", title: t("models.entity.templates"), path: adminSidebarPath("workflow-engine/templates") },
|
||||
{ id: "ui.nav.admin.workflows.credentials", title: t("app.sidebar.credentials"), path: adminSidebarPath("workflow-engine/credentials") },
|
||||
{ id: "ui.nav.admin.workflows.variables", title: t("app.sidebar.variables"), path: adminSidebarPath("workflow-engine/variables") },
|
||||
],
|
||||
}),
|
||||
{
|
||||
id: UI_NAV_IDS.adminApi,
|
||||
title: t("settings.api.title"),
|
||||
@@ -197,8 +161,6 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
items: [
|
||||
{ id: "ui.nav.admin.api.keys", title: t("app.sidebar.apiKeys"), path: adminSidebarPath("api/keys"), permission: "admin.apiKeys.view" },
|
||||
{ id: "ui.nav.admin.api.logs", title: t("app.sidebar.logs"), path: adminSidebarPath("api/logs"), permission: "admin.apiKeys.view" },
|
||||
{ id: "ui.nav.admin.api.docs", title: t("app.sidebar.docs"), path: adminSidebarPath("api/docs"), permission: "admin.apiKeys.view" },
|
||||
{ id: "ui.nav.admin.api.credits", title: t("app.sidebar.credits"), path: adminSidebarPath("api/credits"), permission: "admin.apiKeys.view" },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -213,18 +175,6 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
],
|
||||
permission: "admin.featureFlags.view",
|
||||
},
|
||||
{
|
||||
id: UI_NAV_IDS.adminNavigation,
|
||||
title: t("admin.navigation.title"),
|
||||
path: adminSidebarPath("navigation"),
|
||||
icon: <IconNavigation className="size-4" />,
|
||||
},
|
||||
...enabledAdminRouteItem("portals", {
|
||||
id: UI_NAV_IDS.adminPortals,
|
||||
title: t("app.sidebar.portals"),
|
||||
path: adminSidebarPath("portals"),
|
||||
icon: <IconPortals />,
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -281,31 +231,6 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
{ id: "ui.nav.admin.helpDesk.feedback", title: t("app.sidebar.feedback"), path: adminSidebarPath("help-desk/feedback") },
|
||||
],
|
||||
}),
|
||||
{
|
||||
id: UI_NAV_IDS.adminOnboarding,
|
||||
title: t("app.sidebar.onboarding"),
|
||||
path: adminSidebarPath("onboarding"),
|
||||
icon: <IconOnboarding />,
|
||||
isCollapsible: true,
|
||||
items: [
|
||||
{ id: "ui.nav.admin.onboarding.onboardings", title: t("app.sidebar.onboardings"), path: adminSidebarPath("onboarding/onboardings"), permission: "admin.onboarding.view" },
|
||||
{ id: "ui.nav.admin.onboarding.sessions", title: t("app.sidebar.sessions"), path: adminSidebarPath("onboarding/sessions"), permission: "admin.onboarding.view" },
|
||||
],
|
||||
permission: "admin.onboarding.view",
|
||||
},
|
||||
{
|
||||
id: UI_NAV_IDS.adminMetrics,
|
||||
title: t("app.sidebar.metrics"),
|
||||
path: adminSidebarPath("metrics"),
|
||||
icon: <IconMetrics />,
|
||||
isCollapsible: true,
|
||||
items: [
|
||||
{ id: "ui.nav.admin.metrics.summary", title: t("app.sidebar.summary"), path: adminSidebarPath("metrics/summary"), permission: "admin.metrics.view" },
|
||||
{ id: "ui.nav.admin.metrics.logs", title: t("app.sidebar.logs"), path: adminSidebarPath("metrics/logs"), permission: "admin.metrics.view" },
|
||||
{ id: "ui.nav.admin.metrics.settings", title: t("app.sidebar.settings"), path: adminSidebarPath("metrics/settings"), permission: "admin.metrics.view" },
|
||||
],
|
||||
permission: "admin.metrics.view",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -330,7 +255,6 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
path: adminSidebarPath("settings/authentication"),
|
||||
permission: "admin.settings.authentication.view",
|
||||
},
|
||||
{ id: "ui.nav.admin.settings.analytics", title: t("settings.admin.analytics.title"), path: adminSidebarPath("settings/analytics"), permission: "admin.settings.analytics.view" },
|
||||
{
|
||||
id: "ui.nav.admin.settings.transactionalEmails",
|
||||
title: t("settings.admin.transactionalEmails.title"),
|
||||
@@ -345,8 +269,9 @@ export const AdminSidebar = ({ t, appConfiguration, routing }: Props): SideBarIt
|
||||
{
|
||||
id: UI_NAV_IDS.adminSwitchToApp,
|
||||
title: t("admin.switchToApp"),
|
||||
path: routing ? absoluteAppRootPath(routing) : rootAppFallbackPath,
|
||||
path: adminSidebarPath("select-tenant"),
|
||||
icon: <IconApp />,
|
||||
permission: "admin.accounts.view",
|
||||
exact: true,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -2,48 +2,55 @@ import { existsSync } from "node:fs";
|
||||
import { vi, describe, it, expect } from "vitest";
|
||||
import { AppSidebar } from "./AppSidebar";
|
||||
import { UI_NAV_IDS } from "~/application/ui/uiRegistry";
|
||||
import { EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
// R-P6B-β (AD-2): the generic entity-builder is gone, so AppSidebar no longer
|
||||
// renders dynamic per-entity / entity-group nav. Only typed product features and
|
||||
// static targets remain.
|
||||
|
||||
describe("AppSidebar", () => {
|
||||
const starterProductAccess = {
|
||||
dashboard: { allowed: true },
|
||||
"crm-basic": { allowed: true },
|
||||
projects: { allowed: true },
|
||||
automation: { allowed: false },
|
||||
"email-marketing": { allowed: false },
|
||||
api: { allowed: false },
|
||||
"workflow-engine": { allowed: false },
|
||||
"ai-credits": { allowed: true },
|
||||
};
|
||||
const proProductAccess = {
|
||||
dashboard: { allowed: true },
|
||||
"crm-basic": { allowed: true },
|
||||
projects: { allowed: true },
|
||||
automation: { allowed: false },
|
||||
"email-marketing": { allowed: true },
|
||||
"email-inbox": { allowed: true },
|
||||
api: { allowed: true },
|
||||
"workflow-engine": { allowed: false },
|
||||
"ai-credits": { allowed: true },
|
||||
};
|
||||
const businessProductAccess = {
|
||||
dashboard: { allowed: true },
|
||||
"crm-basic": { allowed: true },
|
||||
projects: { allowed: true },
|
||||
automation: { allowed: true },
|
||||
"email-marketing": { allowed: true },
|
||||
"email-inbox": { allowed: true },
|
||||
api: { allowed: true },
|
||||
"workflow-engine": { allowed: true },
|
||||
"ai-credits": { allowed: true },
|
||||
};
|
||||
|
||||
it("returns the expected sidebar items", () => {
|
||||
it("returns the expected static sidebar items", () => {
|
||||
const t = vi.fn().mockImplementation((v: string) => v) as any;
|
||||
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
|
||||
const entities = [
|
||||
{ name: "entity1", slug: "entity1", titlePlural: "Entity 1", showInSidebar: true, icon: "" },
|
||||
{ name: "entity2", slug: "entity2", titlePlural: "Entity 2", showInSidebar: false, icon: "" },
|
||||
{ name: "entity3", slug: "entity3", titlePlural: "Entity 3", showInSidebar: true, icon: "" },
|
||||
] as EntitySimple[];
|
||||
|
||||
const result = AppSidebar({ t, i18n, tenantId: "test-user", entities, entityGroups: [], appConfiguration: null });
|
||||
const result = AppSidebar({ t, i18n, tenantId: "test-user", appConfiguration: null });
|
||||
const serialized = JSON.stringify(result);
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
title: "",
|
||||
path: "",
|
||||
items: [
|
||||
expect(result[0].items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: "ui.nav.app.dashboard",
|
||||
title: "app.sidebar.dashboard",
|
||||
@@ -54,25 +61,13 @@ describe("AppSidebar", () => {
|
||||
title: "app.sidebar.notifications",
|
||||
path: "/test-user/notifications",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "ui.nav.app.entity.entity1",
|
||||
title: "Entity 1",
|
||||
path: "/test-user/entity1",
|
||||
permission: "entity.entity1.view",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "ui.nav.app.entity.entity3",
|
||||
title: "Entity 3",
|
||||
path: "/test-user/entity3",
|
||||
permission: "entity.entity3.view",
|
||||
}),
|
||||
],
|
||||
});
|
||||
])
|
||||
);
|
||||
expect(result[1]).toMatchObject({
|
||||
title: "",
|
||||
path: "",
|
||||
isSecondary: true,
|
||||
items: [
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: "ui.nav.app.settings",
|
||||
title: "app.sidebar.settings",
|
||||
@@ -85,8 +80,10 @@ describe("AppSidebar", () => {
|
||||
path: "/dashboard",
|
||||
adminOnly: true,
|
||||
}),
|
||||
],
|
||||
]),
|
||||
});
|
||||
expect(serialized).not.toContain("ui.nav.app.entity.");
|
||||
expect(serialized).not.toContain("ui.nav.app.entityGroup.");
|
||||
expect(serialized).not.toContain("/app/");
|
||||
expect(serialized).not.toContain("/admin/");
|
||||
expect(serialized).not.toContain("/blog");
|
||||
@@ -102,113 +99,50 @@ describe("AppSidebar", () => {
|
||||
const t = vi.fn().mockImplementation((v: string) => v) as any;
|
||||
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
|
||||
|
||||
const starter = JSON.stringify(
|
||||
AppSidebar({ t, i18n, tenantId: "starter", entities: [], entityGroups: [], appConfiguration: null, productAccess: starterProductAccess })
|
||||
);
|
||||
const pro = JSON.stringify(
|
||||
AppSidebar({ t, i18n, tenantId: "pro", entities: [], entityGroups: [], appConfiguration: null, productAccess: proProductAccess })
|
||||
);
|
||||
const business = JSON.stringify(
|
||||
AppSidebar({ t, i18n, tenantId: "business", entities: [], entityGroups: [], appConfiguration: null, productAccess: businessProductAccess })
|
||||
);
|
||||
const starter = JSON.stringify(AppSidebar({ t, i18n, tenantId: "starter", appConfiguration: null, productAccess: starterProductAccess }));
|
||||
const pro = JSON.stringify(AppSidebar({ t, i18n, tenantId: "pro", appConfiguration: null, productAccess: proProductAccess }));
|
||||
const business = JSON.stringify(AppSidebar({ t, i18n, tenantId: "business", appConfiguration: null, productAccess: businessProductAccess }));
|
||||
|
||||
expect(starter).toContain("/starter/crm");
|
||||
expect(starter).toContain("/starter/settings/credits");
|
||||
expect(starter).toContain("/starter/contacts");
|
||||
expect(starter).toContain("/starter/projects");
|
||||
expect(starter).not.toContain("/starter/settings/credits");
|
||||
expect(starter).not.toContain("/starter/email-marketing");
|
||||
expect(starter).not.toContain("/starter/emails");
|
||||
expect(starter).not.toContain("/starter/automations");
|
||||
expect(starter).not.toContain("/starter/settings/api");
|
||||
expect(starter).not.toContain("/starter/workflow-engine");
|
||||
|
||||
expect(pro).toContain("/pro/crm");
|
||||
expect(pro).toContain("/pro/contacts");
|
||||
expect(pro).toContain("/pro/projects");
|
||||
expect(pro).toContain("/pro/email-marketing");
|
||||
expect(pro).toContain("/pro/emails");
|
||||
expect(pro).not.toContain("/pro/automations");
|
||||
expect(pro).toContain("/pro/settings/api");
|
||||
expect(pro).not.toContain("/pro/workflow-engine");
|
||||
|
||||
expect(business).toContain("/business/crm");
|
||||
expect(business).toContain("/business/contacts");
|
||||
expect(business).toContain("/business/projects");
|
||||
expect(business).toContain("/business/email-marketing");
|
||||
expect(business).toContain("/business/automations");
|
||||
expect(business).toContain("/business/settings/api");
|
||||
expect(business).toContain("/business/workflow-engine");
|
||||
});
|
||||
|
||||
it("marks collapsible entity groups as expand-only parents", () => {
|
||||
const t = vi.fn().mockImplementation((v: string) => v) as any;
|
||||
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
|
||||
const entities = [
|
||||
{ name: "company", slug: "companies", titlePlural: "Companies", showInSidebar: true, icon: "" },
|
||||
] as EntitySimple[];
|
||||
|
||||
const result = AppSidebar({
|
||||
t,
|
||||
i18n,
|
||||
tenantId: "acme",
|
||||
entities: [],
|
||||
entityGroups: [
|
||||
{
|
||||
slug: "sales",
|
||||
title: "Sales",
|
||||
icon: "",
|
||||
collapsible: true,
|
||||
section: null,
|
||||
entities: [{ entity: entities[0] }],
|
||||
},
|
||||
] as any,
|
||||
appConfiguration: null,
|
||||
});
|
||||
const group = result[0].items?.find((item) => item.id === "ui.nav.app.entityGroup.sales");
|
||||
|
||||
expect(group).toMatchObject({
|
||||
isCollapsible: true,
|
||||
path: "/acme/g/sales",
|
||||
});
|
||||
expect(group?.items?.[0]).toMatchObject({ title: "shared.overview", path: "/acme/g/sales" });
|
||||
});
|
||||
|
||||
it("translates DB-backed labels only when locale keys exist", () => {
|
||||
const t = vi.fn().mockImplementation((v: string) => `translated:${v}`) as any;
|
||||
const i18n = { exists: vi.fn().mockImplementation((value: string) => value === "models.contact.plural" || value === "groups.sales") } as any;
|
||||
const entities = [
|
||||
{ name: "contact", slug: "contacts", titlePlural: "models.contact.plural", showInSidebar: true, icon: "" },
|
||||
{ name: "custom", slug: "custom", titlePlural: "Custom records", showInSidebar: true, icon: "" },
|
||||
] as EntitySimple[];
|
||||
|
||||
const result = AppSidebar({
|
||||
t,
|
||||
i18n,
|
||||
tenantId: "acme",
|
||||
entities,
|
||||
entityGroups: [
|
||||
{
|
||||
slug: "sales",
|
||||
title: "groups.sales",
|
||||
icon: "",
|
||||
collapsible: true,
|
||||
section: null,
|
||||
entities: [{ entity: entities[0] }],
|
||||
},
|
||||
] as any,
|
||||
appConfiguration: null,
|
||||
});
|
||||
const serialized = JSON.stringify(result);
|
||||
|
||||
expect(serialized).toContain("translated:models.contact.plural");
|
||||
expect(serialized).toContain("translated:groups.sales");
|
||||
expect(serialized).toContain("Custom records");
|
||||
expect(serialized).not.toContain('"models.contact.plural"');
|
||||
expect(serialized).not.toContain('"groups.sales"');
|
||||
});
|
||||
|
||||
it("keeps static tenant sidebar targets backed by registered route files", () => {
|
||||
const t = vi.fn().mockImplementation((v: string) => v) as any;
|
||||
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
|
||||
const result = AppSidebar({ t, i18n, tenantId: "acme", entities: [], entityGroups: [], appConfiguration: null, productAccess: businessProductAccess });
|
||||
const result = AppSidebar({ t, i18n, tenantId: "acme", appConfiguration: null, productAccess: businessProductAccess });
|
||||
const serialized = JSON.stringify(result);
|
||||
|
||||
expect(serialized).toContain("/acme/dashboard");
|
||||
expect(serialized).toContain("/acme/notifications");
|
||||
expect(serialized).toContain("/acme/crm");
|
||||
expect(serialized).toContain("/acme/contacts");
|
||||
expect(serialized).toContain("/acme/projects");
|
||||
expect(serialized).toContain("/acme/automations");
|
||||
expect(serialized).toContain("/acme/email-marketing");
|
||||
expect(serialized).toContain("/acme/workflow-engine");
|
||||
expect(serialized).toContain("/acme/settings/api");
|
||||
expect(serialized).toContain("/acme/settings/credits");
|
||||
expect(serialized).not.toContain("/acme/settings/credits");
|
||||
expect(serialized).toContain("/acme/settings");
|
||||
expect(serialized).toContain("/acme/settings/profile");
|
||||
expect(serialized).not.toContain("/app/");
|
||||
@@ -217,11 +151,14 @@ describe("AppSidebar", () => {
|
||||
[
|
||||
"apps/web/app/routes/app.$tenant/dashboard.tsx",
|
||||
"apps/web/app/routes/app.$tenant/notifications.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm.tsx",
|
||||
"apps/web/app/routes/app.$tenant/contacts._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/projects._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/automations._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/automations.$id.edit.tsx",
|
||||
"apps/web/app/routes/app.$tenant/automations.templates._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/email-marketing.tsx",
|
||||
"apps/web/app/routes/app.$tenant/__workflows/workflow-engine.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/api/index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/credits.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/profile.tsx",
|
||||
].forEach((routeFile) => {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { SideBarItem } from "./SidebarItem";
|
||||
import { EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import { TFunction, type i18n as I18n } from "i18next";
|
||||
import { EntityGroupWithDetails } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { AppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import IconSettings from "~/components/layouts/icons/IconSettings";
|
||||
import IconDashboard from "~/components/layouts/icons/IconDashboard";
|
||||
@@ -10,46 +8,88 @@ import IconNotifications from "~/components/layouts/icons/IconNotifications";
|
||||
import IconEmails from "~/components/layouts/icons/IconEmails";
|
||||
import IconKeys from "~/components/layouts/icons/IconKeys";
|
||||
import IconWorkflows from "~/components/layouts/icons/IconWorkflows";
|
||||
import CreditsIcon from "~/components/ui/icons/CreditsIcon";
|
||||
import AddressBookIcon from "~/components/ui/icons/crm/AddressBookIcon";
|
||||
import IconDocs from "~/components/layouts/icons/IconDocs";
|
||||
import ViewListIcon from "~/components/ui/icons/ViewListIcon";
|
||||
import { UI_ID_PATTERNS, UI_NAV_IDS, uiIdSegment } from "~/application/ui/uiRegistry";
|
||||
import CalendarIcon from "~/components/ui/icons/CalendarIcon";
|
||||
import { UI_NAV_IDS } from "~/application/ui/uiRegistry";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absoluteAdminPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import { getEntityPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
import { resolveConnectorNavState } from "~/utils/connector/connectorNavState";
|
||||
import { WALKING_SKELETON_MODULE_KEY } from "~/modules/walkingSkeleton/constants";
|
||||
import { SearchIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
type Props = {
|
||||
t: TFunction;
|
||||
i18n: I18n;
|
||||
tenantId: string;
|
||||
entities: EntitySimple[];
|
||||
entityGroups: EntityGroupWithDetails[];
|
||||
appConfiguration: AppConfiguration | null;
|
||||
routing?: PublicDomainRoutingConfig;
|
||||
productAccess?: Record<string, { allowed: boolean; reason?: string }>;
|
||||
};
|
||||
|
||||
export const AppSidebar = ({ t, i18n, tenantId, entities, entityGroups, routing, productAccess }: Props): SideBarItem[] => {
|
||||
export const AppSidebar = ({ t, tenantId, routing, productAccess }: Props): SideBarItem[] => {
|
||||
const tenantPath = (path?: string) => appPath({ tenantSlug: tenantId, path, mode: "host-aware" });
|
||||
const hasFeatureAccess = (featureKey: string) => productAccess?.[featureKey]?.allowed === true;
|
||||
const hasDashboardAccess = productAccess ? hasFeatureAccess("dashboard") : true;
|
||||
// R-P1c Konnektor-Demo: Walking-Skeleton-Eintrag zeigt die drei Gate-Zustaende (aktiv/gesperrt/ausgeblendet).
|
||||
const walkingSkeletonDecision = productAccess?.[WALKING_SKELETON_MODULE_KEY];
|
||||
const walkingSkeletonState = walkingSkeletonDecision ? resolveConnectorNavState(walkingSkeletonDecision) : "hidden";
|
||||
|
||||
const sectionItems: SideBarItem[] = [];
|
||||
const entitiesItems: SideBarItem[] = [];
|
||||
const productCoreItems: SideBarItem[] = [
|
||||
...(hasFeatureAccess("search")
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appSearch,
|
||||
title: t("search.nav.title"),
|
||||
path: tenantPath("search"),
|
||||
icon: <SearchIcon />,
|
||||
permission: "search.use" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("automation")
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appAutomation,
|
||||
title: t("automation.nav.title"),
|
||||
path: tenantPath("automations"),
|
||||
icon: <IconWorkflows />,
|
||||
permission: "automation.read" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("crm-basic")
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appCrm,
|
||||
title: t("crm:title"),
|
||||
path: tenantPath("crm"),
|
||||
// R-P6: typed CRM contacts replace the entity-builder CRM (/crm → /contacts).
|
||||
path: tenantPath("contacts"),
|
||||
icon: <AddressBookIcon />,
|
||||
permission: "crm.read_own" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("leads")
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appLeads,
|
||||
title: t("leads.nav.title"),
|
||||
path: tenantPath("leads"),
|
||||
icon: <ViewListIcon />,
|
||||
permission: "leads.read_own" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("projects")
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appProjects,
|
||||
title: t("projects.nav.title"),
|
||||
path: tenantPath("projects"),
|
||||
icon: <ViewListIcon />,
|
||||
permission: "projects.read_own" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -75,6 +115,78 @@ export const AppSidebar = ({ t, i18n, tenantId, entities, entityGroups, routing,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("hr")
|
||||
? [
|
||||
{
|
||||
id: "ui.nav.app.hr",
|
||||
title: t("hr.nav.title"),
|
||||
path: tenantPath("hr"),
|
||||
icon: <AddressBookIcon />,
|
||||
permission: "hr.read_own" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("integrations")
|
||||
? [
|
||||
{
|
||||
id: "ui.nav.app.integrations",
|
||||
title: t("integrations.nav.title"),
|
||||
path: tenantPath("integrations"),
|
||||
icon: <IconWorkflows />,
|
||||
permission: "integrations.read" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("integrations")
|
||||
? [
|
||||
{
|
||||
// AK-P16a · calendar reuses the integrations feature gate (it is an
|
||||
// Apps-Engine integration); the entry is gated by calendar.connect_own.
|
||||
id: UI_NAV_IDS.appCalendar,
|
||||
title: t("calendar.nav.title"),
|
||||
path: tenantPath("calendar"),
|
||||
icon: <CalendarIcon />,
|
||||
permission: "calendar.connect_own" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("email-inbox")
|
||||
? [
|
||||
{
|
||||
// VA-P23 · mailbox sync inbox — own `email-inbox` feature gate; the
|
||||
// entry is gated by email.read_own (own-mailbox visibility, M09 I).
|
||||
id: UI_NAV_IDS.appEmails,
|
||||
title: t("emailInbox.nav.title"),
|
||||
path: tenantPath("emails"),
|
||||
icon: <IconEmails className="h-5 w-5" />,
|
||||
permission: "email.read_own" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("booking")
|
||||
? [
|
||||
{
|
||||
// AK-P16b · Booking module — own `booking` feature gate; the entry is
|
||||
// gated by bookings.read_own (every provider can see their own bookings).
|
||||
id: UI_NAV_IDS.appBookings,
|
||||
title: t("bookings.nav.title"),
|
||||
path: tenantPath("bookings"),
|
||||
icon: <CalendarIcon />,
|
||||
permission: "bookings.read_own" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("forms")
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appForms,
|
||||
title: t("settings.forms.admin.title"),
|
||||
path: tenantPath("forms"),
|
||||
icon: <ViewListIcon />,
|
||||
permission: "forms.basic" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("email-marketing")
|
||||
? [
|
||||
{
|
||||
@@ -105,16 +217,6 @@ export const AppSidebar = ({ t, i18n, tenantId, entities, entityGroups, routing,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasFeatureAccess("ai-credits")
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appCredits,
|
||||
title: t("models.credit.plural"),
|
||||
path: tenantPath("settings/credits"),
|
||||
icon: <CreditsIcon />,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(walkingSkeletonState !== "hidden"
|
||||
? [
|
||||
{
|
||||
@@ -128,87 +230,23 @@ export const AppSidebar = ({ t, i18n, tenantId, entities, entityGroups, routing,
|
||||
: []),
|
||||
];
|
||||
|
||||
entityGroups.forEach((group) => {
|
||||
const item: SideBarItem = {
|
||||
id: `ui.nav.app.entityGroup.${uiIdSegment(group.slug)}`,
|
||||
uiIdPattern: UI_ID_PATTERNS.appEntityGroup,
|
||||
uiIdParams: { groupSlug: group.slug },
|
||||
title: translateLabel(t, i18n, group.title),
|
||||
// icon: group.icon,
|
||||
path: tenantPath(`g/${group.slug}`),
|
||||
icon: group.icon,
|
||||
// isActive: true,
|
||||
};
|
||||
if (group.collapsible) {
|
||||
item.isCollapsible = true;
|
||||
item.items = [
|
||||
{
|
||||
id: `ui.nav.app.entityGroup.${uiIdSegment(group.slug)}.overview`,
|
||||
title: t("shared.overview"),
|
||||
path: tenantPath(`g/${group.slug}`),
|
||||
},
|
||||
...group.entities.map(({ entity }) => {
|
||||
return {
|
||||
id: `ui.nav.app.entityGroup.${uiIdSegment(group.slug)}.entity.${uiIdSegment(entity.slug)}`,
|
||||
uiIdPattern: UI_ID_PATTERNS.appEntityGroupEntity,
|
||||
uiIdParams: { groupSlug: group.slug, entityName: entity.name ?? entity.slug },
|
||||
title: translateLabel(t, i18n, entity.titlePlural),
|
||||
// icon: entity.icon,
|
||||
path: tenantPath(`g/${group.slug}/${entity.slug}`),
|
||||
permission: getEntityPermission(entity, "view"),
|
||||
// entityIcon: entity.icon,
|
||||
};
|
||||
}),
|
||||
];
|
||||
}
|
||||
if (group.section) {
|
||||
const sectionTitle = translateLabel(t, i18n, group.section);
|
||||
const section = sectionItems.find((f) => f.title === sectionTitle);
|
||||
if (section) {
|
||||
section.items = [...(section.items ?? []), item];
|
||||
} else {
|
||||
sectionItems.push({
|
||||
id: `ui.nav.app.section.${uiIdSegment(group.section)}`,
|
||||
uiIdPattern: UI_ID_PATTERNS.appSection,
|
||||
uiIdParams: { sectionName: group.section },
|
||||
title: sectionTitle,
|
||||
path: ``,
|
||||
items: [item],
|
||||
});
|
||||
}
|
||||
} else {
|
||||
entitiesItems.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
entities
|
||||
.filter((f) => f.showInSidebar)
|
||||
.forEach((entity) => {
|
||||
entitiesItems.push({
|
||||
id: `ui.nav.app.entity.${uiIdSegment(entity.slug)}`,
|
||||
uiIdPattern: UI_ID_PATTERNS.appEntity,
|
||||
uiIdParams: { entityName: entity.name ?? entity.slug, entitySlug: entity.slug },
|
||||
title: translateLabel(t, i18n, entity.titlePlural),
|
||||
icon: entity.icon,
|
||||
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN],
|
||||
path: tenantPath(entity.slug),
|
||||
permission: getEntityPermission(entity, "view"),
|
||||
// side: isDebugMode && SideText({ text: modelProperties.length > 0 ? "DB Model" : "Custom" }),
|
||||
});
|
||||
});
|
||||
|
||||
const appItem: SideBarItem = {
|
||||
id: "ui.nav.app.primary",
|
||||
title: "",
|
||||
path: "",
|
||||
items: [
|
||||
{
|
||||
id: UI_NAV_IDS.appDashboard,
|
||||
title: t("app.sidebar.dashboard"),
|
||||
path: tenantPath("dashboard"),
|
||||
icon: <IconDashboard />,
|
||||
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN, TenantUserType.MEMBER],
|
||||
},
|
||||
...(hasDashboardAccess
|
||||
? [
|
||||
{
|
||||
id: UI_NAV_IDS.appDashboard,
|
||||
title: t("app.sidebar.dashboard"),
|
||||
path: tenantPath("dashboard"),
|
||||
icon: <IconDashboard />,
|
||||
permission: "dashboard.read" as const,
|
||||
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN, TenantUserType.MEMBER],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
id: UI_NAV_IDS.appNotifications,
|
||||
title: t("app.sidebar.notifications"),
|
||||
@@ -216,7 +254,6 @@ export const AppSidebar = ({ t, i18n, tenantId, entities, entityGroups, routing,
|
||||
icon: <IconNotifications />,
|
||||
},
|
||||
...productCoreItems,
|
||||
...entitiesItems,
|
||||
// {
|
||||
// title: t("models.email.plural"),
|
||||
// path: `${currentTenantUrl}/emails`,
|
||||
@@ -227,7 +264,6 @@ export const AppSidebar = ({ t, i18n, tenantId, entities, entityGroups, routing,
|
||||
|
||||
return [
|
||||
appItem,
|
||||
...sectionItems,
|
||||
{
|
||||
id: "ui.nav.app.secondary",
|
||||
title: "",
|
||||
|
||||
@@ -3,8 +3,7 @@ import { AdminSidebar } from "./AdminSidebar";
|
||||
import { AppSidebar } from "./AppSidebar";
|
||||
import { DocsSidebar } from "./DocsSidebar";
|
||||
import type { SideBarItem } from "./SidebarItem";
|
||||
import type { EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import { UI_ID_PATTERNS, UI_NAV_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
|
||||
import { UI_NAV_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
|
||||
|
||||
function flattenSidebarItems(items: SideBarItem[]): SideBarItem[] {
|
||||
return items.flatMap((item) => [item, ...flattenSidebarItems(item.items ?? [])]);
|
||||
@@ -48,44 +47,22 @@ describe("sidebar UI IDs", () => {
|
||||
expectStaticItemsHaveIds(sidebar);
|
||||
expect(ids).toContain(UI_NAV_IDS.adminDashboard);
|
||||
expect(ids).toContain(UI_NAV_IDS.adminSettings);
|
||||
expect(ids).toContain(UI_NAV_IDS.adminEntities);
|
||||
});
|
||||
|
||||
it("assigns unique IDs to app sidebar static and dynamic items", () => {
|
||||
const entities = [
|
||||
{ id: "1", order: 1, name: "contacts", slug: "contacts", title: "Contact", titlePlural: "Contacts", active: true, type: "custom", hasApi: true, showInSidebar: true, icon: "", onEdit: null },
|
||||
{ id: "2", order: 2, name: "hidden", slug: "hidden", title: "Hidden", titlePlural: "Hidden", active: true, type: "custom", hasApi: true, showInSidebar: false, icon: "", onEdit: null },
|
||||
] as EntitySimple[];
|
||||
const sidebar = AppSidebar({
|
||||
t,
|
||||
i18n,
|
||||
tenantId: "acme",
|
||||
entities,
|
||||
entityGroups: [
|
||||
{
|
||||
slug: "sales",
|
||||
title: "Sales",
|
||||
icon: "",
|
||||
collapsible: true,
|
||||
section: "Operations",
|
||||
entities: [{ entity: entities[0] }],
|
||||
},
|
||||
] as any,
|
||||
appConfiguration: null,
|
||||
});
|
||||
it("assigns unique IDs to app sidebar static items", () => {
|
||||
// R-P6B-β (AD-2): the generic entity-builder is gone, so AppSidebar no longer
|
||||
// renders dynamic per-entity / entity-group items.
|
||||
const sidebar = AppSidebar({ t, i18n, tenantId: "acme", appConfiguration: null });
|
||||
const ids = flattenSidebarItems(sidebar).map((item) => item.id);
|
||||
const dynamicEntity = flattenSidebarItems(sidebar).find((item) => item.id === "ui.nav.app.entity.contacts");
|
||||
|
||||
expectCompleteUniqueIds(sidebar);
|
||||
expectStaticItemsHaveIds(sidebar);
|
||||
expectDynamicItemsHavePatternMetadata(sidebar);
|
||||
expect(ids).toContain(UI_NAV_IDS.appDashboard);
|
||||
expect(ids).toContain(UI_NAV_IDS.appSettings);
|
||||
expect(ids).toContain("ui.nav.app.entity.contacts");
|
||||
expect(ids).toContain("ui.nav.app.entityGroup.sales");
|
||||
expect(ids).toContain("ui.nav.app.section.operations");
|
||||
expect(dynamicEntity?.uiIdPattern).toBe(UI_ID_PATTERNS.appEntity);
|
||||
expect(dynamicEntity?.uiIdParams).toMatchObject({ entityName: "contacts", entitySlug: "contacts" });
|
||||
expect(ids).not.toContain("ui.nav.app.entity.contacts");
|
||||
expect(ids.some((id) => id?.startsWith("ui.nav.app.entity."))).toBe(false);
|
||||
expect(ids.some((id) => id?.startsWith("ui.nav.app.entityGroup."))).toBe(false);
|
||||
});
|
||||
|
||||
it("assigns unique IDs to docs sidebar items", () => {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { featureKeys, type FeatureKey } from "@hivegrid/entitlements";
|
||||
|
||||
// Registry gate for a recurring footgun: AppSidebar gates entries via
|
||||
// hasFeatureAccess("<key>"), but productAccess is only resolved for the keys in
|
||||
// appData.ts tenantNavigationFeatureKeys. A key used in the sidebar but missing
|
||||
// from that list silently hides the entry for ALL tenants/plans (happened to
|
||||
// files+tasks → fixed in 1017cf58b, then again to dashboard/automation/leads/
|
||||
// projects/hr/integrations/email-inbox/booking/forms → fixed 2026-07-07 after
|
||||
// the R-P5 verification). This static contract makes the drift a test failure.
|
||||
|
||||
const sidebarSource = readFileSync(resolve(__dirname, "AppSidebar.tsx"), "utf8");
|
||||
const appDataSource = readFileSync(resolve(__dirname, "../../utils/data/.server/appData.ts"), "utf8");
|
||||
|
||||
function usedSidebarFeatureKeys(): string[] {
|
||||
const keys = new Set<string>();
|
||||
for (const match of sidebarSource.matchAll(/hasFeatureAccess\("([^"]+)"\)/g)) {
|
||||
keys.add(match[1]);
|
||||
}
|
||||
return [...keys].sort();
|
||||
}
|
||||
|
||||
function resolvedNavigationFeatureKeys(): string[] {
|
||||
const listMatch = appDataSource.match(/const tenantNavigationFeatureKeys = \[([\s\S]*?)\]/);
|
||||
if (!listMatch) {
|
||||
throw new Error("tenantNavigationFeatureKeys list not found in appData.ts");
|
||||
}
|
||||
const keys = new Set<string>();
|
||||
for (const match of listMatch[1].matchAll(/featureKeys\.(\w+)/g)) {
|
||||
const value = featureKeys[match[1] as keyof typeof featureKeys];
|
||||
if (!value) {
|
||||
throw new Error(`Unknown featureKeys entry in tenantNavigationFeatureKeys: ${match[1]}`);
|
||||
}
|
||||
keys.add(value);
|
||||
}
|
||||
return [...keys].sort();
|
||||
}
|
||||
|
||||
describe("sidebar feature-access registry contract", () => {
|
||||
test("every hasFeatureAccess key used by AppSidebar is resolved in appData", () => {
|
||||
const used = usedSidebarFeatureKeys();
|
||||
const resolved = resolvedNavigationFeatureKeys();
|
||||
expect(used.length).toBeGreaterThan(0);
|
||||
const missing = used.filter((key) => !resolved.includes(key));
|
||||
expect(
|
||||
missing,
|
||||
`AppSidebar gates on feature keys that appData.ts tenantNavigationFeatureKeys does not resolve — those sidebar entries are invisible for every tenant. Add them to the list: ${missing.join(", ")}`
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("all sidebar gate keys are valid entitlement feature keys", () => {
|
||||
const validValues = new Set<string>(Object.values(featureKeys));
|
||||
const invalid = usedSidebarFeatureKeys().filter((key) => !validValues.has(key as FeatureKey));
|
||||
expect(invalid, `AppSidebar uses gate keys that are no entitlement feature keys: ${invalid.join(", ")}`).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buttonAdapterNames, buttonAdapters } from "@toolctrl/ui/buttons";
|
||||
import { layoutAdapterNames, layoutAdapters } from "@toolctrl/ui/layout";
|
||||
import { navigationAdapterNames, navigationAdapters } from "@toolctrl/ui/navigation";
|
||||
import { buttonAdapterNames, buttonAdapters } from "@hivegrid/ui/buttons";
|
||||
import { layoutAdapterNames, layoutAdapters } from "@hivegrid/ui/layout";
|
||||
import { navigationAdapterNames, navigationAdapters } from "@hivegrid/ui/navigation";
|
||||
|
||||
describe("@toolctrl/ui button adapter contract", () => {
|
||||
describe("@hivegrid/ui button adapter contract", () => {
|
||||
it("exposes the first available button adapter targets without importing React components", () => {
|
||||
expect(buttonAdapterNames).toEqual(["Button", "buttonVariants"]);
|
||||
expect(buttonAdapters).toEqual([
|
||||
@@ -13,7 +13,7 @@ describe("@toolctrl/ui button adapter contract", () => {
|
||||
status: "available",
|
||||
source: "apps/web/app/components/ui/button.tsx",
|
||||
implementation: "shadcn/radix",
|
||||
packageExport: "@toolctrl/ui/buttons",
|
||||
packageExport: "@hivegrid/ui/buttons",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
category: "buttons",
|
||||
@@ -21,13 +21,13 @@ describe("@toolctrl/ui button adapter contract", () => {
|
||||
status: "available",
|
||||
source: "apps/web/app/components/ui/button.tsx",
|
||||
implementation: "shadcn/radix",
|
||||
packageExport: "@toolctrl/ui/buttons",
|
||||
packageExport: "@hivegrid/ui/buttons",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("@toolctrl/ui shell and navigation adapter contracts", () => {
|
||||
describe("@hivegrid/ui shell and navigation adapter contracts", () => {
|
||||
it("exposes available layout adapter targets without importing React components", () => {
|
||||
expect(layoutAdapterNames).toEqual(["ShadcnSidebarLayout", "UiRegistry"]);
|
||||
expect(layoutAdapters).toEqual([
|
||||
@@ -37,7 +37,7 @@ describe("@toolctrl/ui shell and navigation adapter contracts", () => {
|
||||
status: "available",
|
||||
source: "apps/web/app/components/layouts/sidebars/shadcn/ShadcnSidebarLayout.tsx",
|
||||
implementation: "shell-layout",
|
||||
packageExport: "@toolctrl/ui/layout",
|
||||
packageExport: "@hivegrid/ui/layout",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
category: "layout",
|
||||
@@ -45,7 +45,7 @@ describe("@toolctrl/ui shell and navigation adapter contracts", () => {
|
||||
status: "available",
|
||||
source: "apps/web/app/application/ui/uiRegistry.ts",
|
||||
implementation: "agent-registry",
|
||||
packageExport: "@toolctrl/ui/layout",
|
||||
packageExport: "@hivegrid/ui/layout",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -71,6 +71,6 @@ describe("@toolctrl/ui shell and navigation adapter contracts", () => {
|
||||
expect.objectContaining({ name: "NavActions", source: "apps/web/app/components/layouts/sidebars/shadcn/nav-actions.tsx" }),
|
||||
expect.objectContaining({ name: "SidebarPrimitives", source: "apps/web/app/components/ui/sidebar.tsx" }),
|
||||
]);
|
||||
expect(navigationAdapters.every((adapter) => adapter.status === "available" && adapter.packageExport === "@toolctrl/ui/navigation")).toBe(true);
|
||||
expect(navigationAdapters.every((adapter) => adapter.status === "available" && adapter.packageExport === "@hivegrid/ui/navigation")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { uiAdapterCategories } from "@toolctrl/ui";
|
||||
import { layoutAdapters } from "@toolctrl/ui/layout";
|
||||
import { navigationAdapters } from "@toolctrl/ui/navigation";
|
||||
import { uiAdapterCategories } from "@hivegrid/ui";
|
||||
import { layoutAdapters } from "@hivegrid/ui/layout";
|
||||
import { navigationAdapters } from "@hivegrid/ui/navigation";
|
||||
import { UI_ACTION_IDS, UI_NAV_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
|
||||
import { readRepoDir, repoPathExists } from "~/utils/testing/repoPaths";
|
||||
|
||||
@@ -137,7 +137,7 @@ describe("UI surface map", () => {
|
||||
const uiPlaybook = fs.readFileSync(path.join(process.cwd(), "docs/agent-playbooks/ui-changes.md"), "utf8");
|
||||
const adapterPlaybook = fs.readFileSync(path.join(process.cwd(), "docs/agent-playbooks/ui-adapter-migration.md"), "utf8");
|
||||
expect(uiPlaybook).toContain("Identify the target by `data-ui-id`");
|
||||
expect(adapterPlaybook).toContain("@toolctrl/ui/buttons");
|
||||
expect(adapterPlaybook).toContain("@hivegrid/ui/buttons");
|
||||
});
|
||||
|
||||
it("matches the declared surface schema shape", () => {
|
||||
|
||||
@@ -40,8 +40,16 @@ export const UI_ACTION_IDS = {
|
||||
export const UI_NAV_IDS = {
|
||||
appDashboard: "ui.nav.app.dashboard",
|
||||
appNotifications: "ui.nav.app.notifications",
|
||||
appSearch: "ui.nav.app.search",
|
||||
appAutomation: "ui.nav.app.automation",
|
||||
appCrm: "ui.nav.app.crm",
|
||||
appLeads: "ui.nav.app.leads",
|
||||
appProjects: "ui.nav.app.projects",
|
||||
appEmailMarketing: "ui.nav.app.emailMarketing",
|
||||
appEmails: "ui.nav.app.emails",
|
||||
appCalendar: "ui.nav.app.calendar",
|
||||
appBookings: "ui.nav.app.bookings",
|
||||
appForms: "ui.nav.app.forms",
|
||||
appApi: "ui.nav.app.api",
|
||||
appWorkflowEngine: "ui.nav.app.workflowEngine",
|
||||
appCredits: "ui.nav.app.credits",
|
||||
@@ -49,23 +57,15 @@ export const UI_NAV_IDS = {
|
||||
appSwitchToAdmin: "ui.nav.app.switchToAdmin",
|
||||
adminDashboard: "ui.nav.admin.dashboard",
|
||||
adminAccounts: "ui.nav.admin.accounts",
|
||||
adminAnalytics: "ui.nav.admin.analytics",
|
||||
adminEntities: "ui.nav.admin.entities",
|
||||
adminWorkflows: "ui.nav.admin.workflows",
|
||||
adminApi: "ui.nav.admin.api",
|
||||
adminEvents: "ui.nav.admin.events",
|
||||
adminAuditTrails: "ui.nav.admin.auditTrails",
|
||||
adminAudit: "ui.nav.admin.audit",
|
||||
adminNotifications: "ui.nav.admin.notifications",
|
||||
adminFeatureFlags: "ui.nav.admin.featureFlags",
|
||||
adminNavigation: "ui.nav.admin.navigation",
|
||||
adminPortals: "ui.nav.admin.portals",
|
||||
adminPrompts: "ui.nav.admin.prompts",
|
||||
adminEmailMarketing: "ui.nav.admin.emailMarketing",
|
||||
adminMarketing: "ui.nav.admin.marketing",
|
||||
adminKnowledgeBase: "ui.nav.admin.knowledgeBase",
|
||||
adminHelpDesk: "ui.nav.admin.helpDesk",
|
||||
adminOnboarding: "ui.nav.admin.onboarding",
|
||||
adminMetrics: "ui.nav.admin.metrics",
|
||||
adminSettings: "ui.nav.admin.settings",
|
||||
adminSwitchToApp: "ui.nav.admin.switchToApp",
|
||||
docsIntroduction: "ui.nav.docs.introduction",
|
||||
|
||||
|
Before Width: | Height: | Size: 97 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="820 20 500 440" role="img" aria-label="HiveGrid">
|
||||
<path fill="#F1B729" d="M1266.6 237.2l-48.1-83.3-144.2 83.3h96.1l-48 83.2h-96.1l-48.1-83.2 48.1-83.3h192.2l-38.4-66.4-9.7-16.8H978.2l-96.1 166.5 96.1 166.4h192.2l96.2-166.4z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 324 B |
|
Before Width: | Height: | Size: 106 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="820 20 500 440" role="img" aria-label="HiveGrid">
|
||||
<path fill="#F1B729" d="M1266.6 237.2l-48.1-83.3-144.2 83.3h96.1l-48 83.2h-96.1l-48.1-83.2 48.1-83.3h192.2l-38.4-66.4-9.7-16.8H978.2l-96.1 166.5 96.1 166.4h192.2l96.2-166.4z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 324 B |
@@ -1,7 +1,7 @@
|
||||
import logoLight from "./logo-light.png";
|
||||
import logoDark from "./logo-dark.png";
|
||||
import iconLight from "./icon-light.png";
|
||||
import iconDark from "./icon-dark.png";
|
||||
import logoLight from "./logo-light.svg";
|
||||
import logoDark from "./logo-dark.svg";
|
||||
import iconLight from "./icon-light.svg";
|
||||
import iconDark from "./icon-dark.svg";
|
||||
|
||||
export const defaultBrandImages = {
|
||||
logoLight,
|
||||
|
||||
|
Before Width: | Height: | Size: 40 KiB |
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1900 500" role="img" aria-label="HiveGrid">
|
||||
<g fill="#F9F9F9">
|
||||
<path d="M26.6 78.2h58.6v102.5H217V78.2h58.6v256.3H217V231.9H85.2v102.6H26.6V78.2z"/>
|
||||
<path d="M325.1 78.2h58.6v256.3h-58.6V78.2z"/>
|
||||
<path d="M412.9 107.5V78.2h54.9l76.9 199.6h3.7l76.9-199.6h54.9v29.3l-95.2 227h-76.9l-95.2-227z"/>
|
||||
<path d="M907.1 315.2H766.4v-51.3h111.1l-15.2-26.3 14.4-24.9H766.4v-51.3h139.9l21.2-36.5v-14.7H707.8v256.3h219.7v-15.9l-20.4-35.4z"/>
|
||||
<path d="M1418.2 271.1c9-1.7 17.2-4.8 24.5-9.1 6.3-3.9 12.1-9.6 17.2-17 5.1-7.5 7.7-17.6 7.7-30.6v-43.9c0-18.3-5.5-32.9-16.5-43.9-11-11-25.6-16.5-43.9-16.5h-184.9v13.5l66.1 114.6-66.1 114.2v14h58.6V264l59.3-.1 79.9 102.4h53.1V337l-55-65.9zm-9.2-71.4c0 15.9-8.8 13-24.6 13h-103.5v-51.5h104.3c15.9 0 23.8 7.9 23.8 23.8v14.7z"/>
|
||||
<path d="M1513.4 110h58.6v256.3h-58.6V110z"/>
|
||||
<path d="M1621.4 110h188.6c18.3 0 32.9 5.5 43.9 16.5s16.5 25.6 16.5 43.9v135.5c0 18.3-5.5 33-16.5 43.9s-25.6 16.5-43.9 16.5h-188.6V110zm166.6 205.1c15.9 0 23.8-7.9 23.8-23.8V185.1c0-15.9-7.9-23.8-23.8-23.8h-108v153.8h108z"/>
|
||||
</g>
|
||||
<path fill="#F1B729" d="M1266.6 237.2l-48.1-83.3-144.2 83.3h96.1l-48 83.2h-96.1l-48.1-83.2 48.1-83.3h192.2l-38.4-66.4-9.7-16.8H978.2l-96.1 166.5 96.1 166.4h192.2l96.2-166.4z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 43 KiB |
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1900 500" role="img" aria-label="HiveGrid">
|
||||
<g fill="#231F20">
|
||||
<path d="M26.6 78.2h58.6v102.5H217V78.2h58.6v256.3H217V231.9H85.2v102.6H26.6V78.2z"/>
|
||||
<path d="M325.1 78.2h58.6v256.3h-58.6V78.2z"/>
|
||||
<path d="M412.9 107.5V78.2h54.9l76.9 199.6h3.7l76.9-199.6h54.9v29.3l-95.2 227h-76.9l-95.2-227z"/>
|
||||
<path d="M907.1 315.2H766.4v-51.3h111.1l-15.2-26.3 14.4-24.9H766.4v-51.3h139.9l21.2-36.5v-14.7H707.8v256.3h219.7v-15.9l-20.4-35.4z"/>
|
||||
<path d="M1418.2 271.1c9-1.7 17.2-4.8 24.5-9.1 6.3-3.9 12.1-9.6 17.2-17 5.1-7.5 7.7-17.6 7.7-30.6v-43.9c0-18.3-5.5-32.9-16.5-43.9-11-11-25.6-16.5-43.9-16.5h-184.9v13.5l66.1 114.6-66.1 114.2v14h58.6V264l59.3-.1 79.9 102.4h53.1V337l-55-65.9zm-9.2-71.4c0 15.9-8.8 13-24.6 13h-103.5v-51.5h104.3c15.9 0 23.8 7.9 23.8 23.8v14.7z"/>
|
||||
<path d="M1513.4 110h58.6v256.3h-58.6V110z"/>
|
||||
<path d="M1621.4 110h188.6c18.3 0 32.9 5.5 43.9 16.5s16.5 25.6 16.5 43.9v135.5c0 18.3-5.5 33-16.5 43.9s-25.6 16.5-43.9 16.5h-188.6V110zm166.6 205.1c15.9 0 23.8-7.9 23.8-23.8V185.1c0-15.9-7.9-23.8-23.8-23.8h-108v153.8h108z"/>
|
||||
</g>
|
||||
<path fill="#F1B729" d="M1266.6 237.2l-48.1-83.3-144.2 83.3h96.1l-48 83.2h-96.1l-48.1-83.2 48.1-83.3h192.2l-38.4-66.4-9.7-16.8H978.2l-96.1 166.5 96.1 166.4h192.2l96.2-166.4z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -17,7 +17,7 @@ function pubsubEnabled(): boolean {
|
||||
* Idempotent boot hook. Starts every cache-invalidation subscriber this
|
||||
* web replica needs to keep its in-process L1 caches consistent with the
|
||||
* SharedStore L2 (and with mutations originating in other apps such as
|
||||
* the Stripe webhook in apps/api).
|
||||
* the billing webhook in apps/api).
|
||||
*
|
||||
* Safe to call multiple times — only the first invocation wires the
|
||||
* subscribers; subsequent calls are no-ops. Failures are logged but
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import { vi, describe, it, expect } from "vitest";
|
||||
import "@testing-library/jest-dom";
|
||||
import { render } from "@testing-library/react";
|
||||
import { BrowserRouter as Router } from "react-router";
|
||||
|
||||
import SetupSteps from "./SetupSteps";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => {
|
||||
return { t: (str: string) => str };
|
||||
},
|
||||
}));
|
||||
|
||||
describe("SetupSteps component", () => {
|
||||
const mockItems = [
|
||||
{ title: "Step 1", description: "Description 1", path: "/step1", completed: true },
|
||||
{ title: "Step 2", description: "Description 2", path: "/step2", completed: false },
|
||||
{ title: "Step 3", description: "Description 3", path: "/step3", completed: false },
|
||||
];
|
||||
|
||||
it("renders a list of setup steps with correct details", () => {
|
||||
const { getAllByRole, getByText } = render(
|
||||
<Router>
|
||||
<SetupSteps items={mockItems} />
|
||||
</Router>
|
||||
);
|
||||
|
||||
const stepItems = getAllByRole("listitem");
|
||||
|
||||
expect(stepItems).toHaveLength(mockItems.length);
|
||||
|
||||
stepItems.forEach((stepItem, index) => {
|
||||
const item = mockItems[index];
|
||||
const title = getByText(item.title);
|
||||
const description = getByText(item.description);
|
||||
expect(title).toBeInTheDocument();
|
||||
expect(description).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SetupItem } from "~/application/dtos/setup/SetupItem";
|
||||
import ButtonSecondary from "../ui/buttons/ButtonSecondary";
|
||||
import clsx from "clsx";
|
||||
import { CheckCircleIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
items: SetupItem[];
|
||||
}
|
||||
|
||||
function CompletedIcon() {
|
||||
return (
|
||||
<CheckCircleIcon className="border-border h-6 w-6 rounded-full border text-gray-200" />
|
||||
);
|
||||
}
|
||||
|
||||
function IncompletedIcon() {
|
||||
return (
|
||||
<CheckCircleIcon className="h-6 w-6 rounded-full border border-teal-500 text-teal-500" />
|
||||
);
|
||||
}
|
||||
|
||||
function SetupStep({ item, index, total }: { item: SetupItem; index: number; total: number }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<li key={index} className="border-border bg-background space-y-3 rounded-lg border p-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="shrink-0">{!item.completed ? <CompletedIcon /> : <IncompletedIcon />}</div>
|
||||
<div className="flex w-full justify-between">
|
||||
<div className="font-medium">{item.title}</div>
|
||||
<div className=" text-muted-foreground text-sm">
|
||||
{index + 1}/{total}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className=" text-sm">{item.description}</p>
|
||||
<div>
|
||||
<ButtonSecondary to={item.path} className="mt-3">
|
||||
{!item.completed ? t("app.sidebar.setup") : `${t("shared.goTo")} ${item.title.toLowerCase()}`} →
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SetupSteps({ items }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div>
|
||||
<h3 className="text-foreground font-medium leading-4">{t("onboarding.gettingStarted.title")}</h3>
|
||||
<ul
|
||||
className={clsx(
|
||||
"mt-3 grid grid-cols-1 gap-4",
|
||||
items.length === 1 && "lg:grid-cols-3",
|
||||
items.length === 2 && "lg:grid-cols-2",
|
||||
items.length === 3 && "lg:grid-cols-3",
|
||||
items.length === 4 && "lg:grid-cols-2",
|
||||
items.length === 5 && "lg:grid-cols-3",
|
||||
items.length === 6 && "lg:grid-cols-3",
|
||||
items.length === 7 && "lg:grid-cols-4",
|
||||
items.length === 8 && "lg:grid-cols-4",
|
||||
items.length === 9 && "lg:grid-cols-3",
|
||||
items.length === 10 && "lg:grid-cols-5",
|
||||
items.length === 11 && "lg:grid-cols-4",
|
||||
items.length === 12 && "lg:grid-cols-4"
|
||||
)}
|
||||
>
|
||||
{items.map((item, index) => (
|
||||
<SetupStep key={index} item={item} index={index} total={items.length} />
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import React from "react";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import AnalyticsPageViewsTable from "./AnalyticsPageViewsTable";
|
||||
import { BrowserRouter as Router } from "react-router";
|
||||
import { AnalyticsPageView } from "@toolctrl/db/prisma-browser";
|
||||
import { AnalyticsPageView } from "@hivegrid/db/prisma-browser";
|
||||
import { vi, describe, expect, test } from "vitest";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AnalyticsPageView } from "@toolctrl/db/prisma-browser";
|
||||
import { AnalyticsPageView } from "@hivegrid/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import DateCell from "../ui/dates/DateCell";
|
||||
import TableSimple from "../ui/tables/TableSimple";
|
||||
|
||||
@@ -118,8 +118,6 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
|
||||
t,
|
||||
i18n,
|
||||
tenantId: params.tenant ?? "",
|
||||
entities: appData?.entities ?? [],
|
||||
entityGroups: appData?.entityGroups ?? [],
|
||||
appConfiguration: rootData.appConfiguration,
|
||||
routing: rootData.routing,
|
||||
productAccess: appData?.productAccess,
|
||||
@@ -138,7 +136,7 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
|
||||
});
|
||||
return groups.filter((g) => g.items.length > 0);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [layout, menuItems, location.pathname, params.tenant, appData?.productAccess, appData?.entities, appData?.entityGroups]);
|
||||
}, [layout, menuItems, location.pathname, params.tenant, appData?.productAccess]);
|
||||
|
||||
const navMain = menu.filter((g) => g.type === "main");
|
||||
const navSecondary = menu.filter((g) => g.type === "secondary");
|
||||
@@ -241,15 +239,22 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 self-stretch pl-1" data-ui-id={UI_SURFACE_IDS.shellNavActions}>
|
||||
<button
|
||||
type="button"
|
||||
className="hidden md:flex md:min-w-[192px] md:max-w-[320px] md:grow"
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className="hidden cursor-pointer md:flex md:min-w-[192px] md:max-w-[320px] md:grow"
|
||||
onClick={() => commandPalette.toggle()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
commandPalette.toggle();
|
||||
}
|
||||
}}
|
||||
aria-label={t("shared.search")}
|
||||
data-ui-id={UI_ACTION_IDS.search}
|
||||
>
|
||||
<SearchInput className="pointer-events-none h-auto w-full" size="small" placeholder={t("shared.searchPlaceholder")} />
|
||||
</button>
|
||||
<SearchInput className="pointer-events-none h-auto w-full min-w-0 max-w-none" size="small" fillContainer placeholder={t("shared.searchPlaceholder")} />
|
||||
</div>
|
||||
<a href={params.tenant ? UrlUtils.currentTenantUrl(params, "notifications") : "#"} aria-label={t("app.sidebar.notifications", { defaultValue: "Notifications" })} data-ui-id={UI_ACTION_IDS.notifications}>
|
||||
<IconButton variant="ghost" size="small" icon={<FeatherBell />} />
|
||||
</a>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useMemo } from "react";
|
||||
import type { Log } from "@toolctrl/db/prisma-browser";
|
||||
import type { Log } from "@hivegrid/db/prisma-browser";
|
||||
import { LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
@@ -16,7 +16,6 @@ export type LogsTableItem = Log & {
|
||||
user?: LogWithDetails["user"] | { id: string; email: string; firstName?: string | null; lastName?: string | null } | null;
|
||||
apiKey?: LogWithDetails["apiKey"] | { id: string; alias: string } | null;
|
||||
tenant?: LogWithDetails["tenant"] | { id: string; name: string; slug?: string | null } | null;
|
||||
comment?: LogWithDetails["comment"] | { id: string; value: string } | null;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -46,13 +46,15 @@ describe("log action i18n", () => {
|
||||
["settings.groups.deleted", "models.log.actions.deleted"],
|
||||
["settings.memberRoles.created", "models.log.actions.created"],
|
||||
["settings.memberRoles.deleted", "models.log.actions.deleted"],
|
||||
["settings.members.deactivated", "models.log.actions.memberDeactivated"],
|
||||
["settings.members.reactivated", "models.log.actions.memberReactivated"],
|
||||
["settings.groups.membersAdded", "models.log.actions.groupMembersAdded"],
|
||||
["settings.groups.membersRemoved", "models.log.actions.groupMembersRemoved"],
|
||||
["settings.rolesAndPermissions.userRoles.created", "models.log.actions.created"],
|
||||
["settings.rolesAndPermissions.userRoles.deleted", "models.log.actions.deleted"],
|
||||
["settings.tenant.updateDetails", "models.log.actions.updateTenantDetails"],
|
||||
["Update tenant details", "models.log.actions.updateTenantDetails"],
|
||||
["Updated", "models.log.actions.updated"],
|
||||
["Updated AI overage configuration", "models.log.actions.updatedAiOverageConfiguration"],
|
||||
["admin.pricing.aiOverage.updated", "models.log.actions.updatedAiOverageConfiguration"],
|
||||
["Updated pricing plan", "models.log.actions.updatedPricingPlan"],
|
||||
["portal.pricing.plan.updated", "models.log.actions.updatedPricingPlan"],
|
||||
["Workspace Role Created", "models.log.actions.workspaceRoleCreated"],
|
||||
|
||||
@@ -38,13 +38,15 @@ export const LOG_ACTION_I18N_KEYS = {
|
||||
"settings.groups.deleted": "models.log.actions.deleted",
|
||||
"settings.memberRoles.created": "models.log.actions.created",
|
||||
"settings.memberRoles.deleted": "models.log.actions.deleted",
|
||||
"settings.members.deactivated": "models.log.actions.memberDeactivated",
|
||||
"settings.members.reactivated": "models.log.actions.memberReactivated",
|
||||
"settings.groups.membersAdded": "models.log.actions.groupMembersAdded",
|
||||
"settings.groups.membersRemoved": "models.log.actions.groupMembersRemoved",
|
||||
"settings.rolesAndPermissions.userRoles.created": "models.log.actions.created",
|
||||
"settings.rolesAndPermissions.userRoles.deleted": "models.log.actions.deleted",
|
||||
"settings.tenant.updateDetails": "models.log.actions.updateTenantDetails",
|
||||
"Update tenant details": "models.log.actions.updateTenantDetails",
|
||||
"Updated": "models.log.actions.updated",
|
||||
"Updated AI overage configuration": "models.log.actions.updatedAiOverageConfiguration",
|
||||
"admin.pricing.aiOverage.updated": "models.log.actions.updatedAiOverageConfiguration",
|
||||
"Updated pricing plan": "models.log.actions.updatedPricingPlan",
|
||||
"portal.pricing.plan.updated": "models.log.actions.updatedPricingPlan",
|
||||
"Workspace Role Created": "models.log.actions.workspaceRoleCreated",
|
||||
|
||||
@@ -1,49 +1,58 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { twClassNames } from "~/ui/utils";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { IconWithBackground } from "~/ui/components/IconWithBackground";
|
||||
import { Logo } from "~/ui/components/Logo";
|
||||
|
||||
type StatusTone = "positive" | "negative" | "neutral";
|
||||
type CardSize = "small" | "medium" | "large" | "extra-large";
|
||||
type SubtitleVariant = "regular-0" | "regular-150" | "medium-150";
|
||||
|
||||
const STATUS_BADGE: Record<StatusTone, string> = {
|
||||
positive: "bg-surface-feedback-subtle-positive",
|
||||
negative: "bg-surface-feedback-subtle-negative",
|
||||
neutral: "bg-surface-feedback-subtle-neutral",
|
||||
};
|
||||
const STATUS_ICON: Record<StatusTone, string> = {
|
||||
positive: "text-icon-feedback-positive",
|
||||
negative: "text-icon-feedback-negative",
|
||||
neutral: "text-icon-neutral-primary",
|
||||
const SUBTITLE_CLS: Record<SubtitleVariant, string> = {
|
||||
"regular-0": "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
|
||||
"regular-150": "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary",
|
||||
"medium-150": "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary",
|
||||
};
|
||||
|
||||
// Gemeinsames Auth-Layout nach Davids Subframe-Auth-Screens (Login/Signup/Reset/2FA/Magic-Link):
|
||||
// zentriertes Logo (64) + Card (Titel/Untertitel + Inhalt) + optionaler Footer. min-h-screen statt Davids
|
||||
// h-full (Auth-Routen ohne full-height-Parent). Titel-Ausrichtung + Untertitel-Gewicht variieren je Screen
|
||||
// in Davids Designs -> als Props (titleAlign/subtitleStrong). twClassNames, damit cardClassName Basis-Tokens
|
||||
// (gap/shadow) sauber ueberschreibt.
|
||||
// Gemeinsames Auth-Layout nach Davids WF-P2-Subframe-Auth-Screens (Login/Signup/Reset/2FA/Magic-Link):
|
||||
// optionales Logo (64) + Davids ECHTE Card-Komponente (~/ui) + optionaler Footer. min-h-screen statt Davids
|
||||
// h-full (Auth-Routen ohne full-height-Parent). Card-Groesse/Logo-Sichtbarkeit/Header-Abstand/Untertitel-Stil
|
||||
// variieren je Screen in Davids Designs -> als Props (cardSize/showLogo/headerGap/subtitleVariant/titleAlign).
|
||||
// Card statt Inline-Nachbau beseitigt Token-Drift (rounded-md/px-6/items-start kommen jetzt aus der Card).
|
||||
// `items-stretch`-Override haelt Form-Kinder auf voller Breite (Davids Card-Root ist items-start).
|
||||
|
||||
export function AuthShell({
|
||||
title,
|
||||
subtitle,
|
||||
children,
|
||||
footer,
|
||||
cardClassName = "max-w-[400px]",
|
||||
cardSize = "large",
|
||||
cardClassName = "max-w-[448px]",
|
||||
showLogo = true,
|
||||
logoIconOnly = false,
|
||||
titleAlign = "start",
|
||||
subtitleStrong = false,
|
||||
titleAlign = "center",
|
||||
headerGap = "gap-1.5",
|
||||
subtitleVariant = "regular-150",
|
||||
dataUiId,
|
||||
}: {
|
||||
title: ReactNode;
|
||||
subtitle?: ReactNode;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
/** Davids Card-Groesse. S01 Login/V01/V02 = large, S04 2FA = extra-large. */
|
||||
cardSize?: CardSize;
|
||||
/** Breite/Overrides der Card; Forms = max-w-[400px] (Default). */
|
||||
cardClassName?: string;
|
||||
/** Icon-only-Logo (wie Davids 2FA-/Status-Screens) statt vollem Wortmarken-Logo. */
|
||||
/** Logo ueber der Card zeigen. Davids S01 Login/V01/V02 = ohne Logo. */
|
||||
showLogo?: boolean;
|
||||
/** Icon-only-Logo (wie Davids Auth-Screens, Logo size=64 hideText) statt vollem Wortmarken-Logo. */
|
||||
logoIconOnly?: boolean;
|
||||
/** Titel-/Untertitel-Ausrichtung. David: Login=center, Signup/Forgot/Reset/2FA=start. */
|
||||
titleAlign?: "center" | "start";
|
||||
/** Untertitel-Gewicht. David: Forgot/2FA = medium-150, sonst regular-0. */
|
||||
subtitleStrong?: boolean;
|
||||
/** Abstand Titel<->Untertitel. David: S01 Login = gap-1.5, sonst gap-1. */
|
||||
headerGap?: string;
|
||||
/** Untertitel-Stil. David: S01 Login = regular-150, 2FA/Forgot = medium-150, sonst regular-0. */
|
||||
subtitleVariant?: SubtitleVariant;
|
||||
dataUiId?: string;
|
||||
}) {
|
||||
return (
|
||||
@@ -51,29 +60,16 @@ export function AuthShell({
|
||||
className="flex min-h-screen w-full flex-col items-center justify-center gap-8 bg-surface-neutral-primary px-4 py-12 mobile:gap-6 mobile:py-6"
|
||||
data-ui-id={dataUiId}
|
||||
>
|
||||
<Logo size="64" showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} />
|
||||
<div
|
||||
className={twClassNames(
|
||||
"flex w-full flex-col items-stretch gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-8 py-8 shadow-sm mobile:px-6",
|
||||
cardClassName
|
||||
)}
|
||||
>
|
||||
<div className={twClassNames("flex w-full flex-col gap-1", titleAlign === "center" ? "items-center" : "items-start")}>
|
||||
{showLogo ? <Logo size="64" showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} /> : null}
|
||||
<Card size={cardSize} variant="default" className={twClassNames("items-stretch", cardClassName)}>
|
||||
<div className={twClassNames("flex w-full flex-col", headerGap, titleAlign === "center" ? "items-center" : "items-start")}>
|
||||
<h1 className="text-heading- font-heading- text-text-neutral-primary">{title}</h1>
|
||||
{subtitle ? (
|
||||
<p
|
||||
className={
|
||||
subtitleStrong
|
||||
? "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary"
|
||||
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary"
|
||||
}
|
||||
>
|
||||
{subtitle}
|
||||
</p>
|
||||
<p className={twClassNames(SUBTITLE_CLS[subtitleVariant], titleAlign === "center" ? "text-center" : "")}>{subtitle}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</Card>
|
||||
{footer ? <div className="flex w-full flex-wrap items-center justify-center gap-2">{footer}</div> : null}
|
||||
</div>
|
||||
);
|
||||
@@ -105,29 +101,44 @@ export function AuthStatus({
|
||||
data-ui-id={dataUiId}
|
||||
>
|
||||
<Logo size="64" />
|
||||
<div className="flex w-full max-w-[400px] flex-col items-center gap-6 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-8 py-8 text-center shadow-sm mobile:px-6">
|
||||
<div className={`flex h-12 w-12 flex-none items-center justify-center rounded-round ${STATUS_BADGE[tone]}`}>
|
||||
<span className={`text-heading- font-heading- ${STATUS_ICON[tone]}`}>{icon}</span>
|
||||
<Card size="large" variant="default" className="max-w-[448px] items-center text-center">
|
||||
<div className="flex w-full flex-col items-center gap-4">
|
||||
<IconWithBackground
|
||||
variant={tone === "positive" ? "success" : tone === "negative" ? "destructive" : "neutral"}
|
||||
size="extra-large"
|
||||
round={true}
|
||||
icon={icon}
|
||||
/>
|
||||
<div className="flex w-full flex-col items-center gap-2">
|
||||
<h1 className="text-center text-heading- font-heading- text-text-neutral-primary">{title}</h1>
|
||||
<p className="text-center text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary">{message}</p>
|
||||
{hint ? (
|
||||
<p className="text-center text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{hint}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-center gap-2">
|
||||
<h1 className="text-center text-heading- font-heading- text-text-neutral-primary">{title}</h1>
|
||||
<p className="text-center text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary">{message}</p>
|
||||
{hint ? (
|
||||
<p className="text-center text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{hint}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{children ? <div className="flex w-full flex-col items-center gap-3">{children}</div> : null}
|
||||
</div>
|
||||
{children ? <div className="flex w-full flex-col items-center gap-3 py-1">{children}</div> : null}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Davids "oder"-Trenner zwischen Primär- und Sekundär-Aktion (z.B. Login vs. Magic-Link).
|
||||
export function AuthDivider({ label }: { label: ReactNode }) {
|
||||
export function AuthDivider({ label, labelSize = "small" }: { label: ReactNode; labelSize?: "small" | "extra-small" }) {
|
||||
return (
|
||||
<div className="flex w-full items-center justify-center gap-3">
|
||||
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{label}</span>
|
||||
<span
|
||||
className={twClassNames(
|
||||
"text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
|
||||
{
|
||||
"text-body-extra-small-regular-150 font-body-extra-small-regular-150":
|
||||
labelSize === "extra-small",
|
||||
}
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { createElement, useEffect, useRef } from "react";
|
||||
|
||||
interface Props {
|
||||
/** Render the mCaptcha widget. When false (or unconfigured) nothing is rendered. */
|
||||
/** Render the captcha widget. When false (or unconfigured) nothing is rendered. */
|
||||
enabled: boolean;
|
||||
/** Public base URL of the self-hosted mCaptcha instance (web config / MCAPTCHA_INSTANCE_URL). */
|
||||
/** Active self-hosted provider. Defaults to mCaptcha for compatibility. */
|
||||
provider?: "mcaptcha" | "cap";
|
||||
/** Public base URL of the self-hosted captcha instance. */
|
||||
instanceUrl?: string;
|
||||
/** Public sitekey for this surface (e.g. MCAPTCHA_SITEKEY_LOGIN). */
|
||||
/** Public sitekey for this surface. */
|
||||
sitekey?: string;
|
||||
}
|
||||
|
||||
@@ -15,18 +17,17 @@ interface Props {
|
||||
const MOUNT_ID = "mcaptcha__widget-container";
|
||||
|
||||
/**
|
||||
* mCaptcha (proof-of-work) widget — replaces the former no-op RecaptchaWrapper.
|
||||
* Self-hosted captcha widget — replaces the former no-op RecaptchaWrapper.
|
||||
*
|
||||
* Render this **inside** the <form> it should protect: the glue injects the
|
||||
* hidden `mcaptcha__token` field next to this mount, so it is submitted with
|
||||
* the form and verified server-side by `@toolctrl/captcha` (see AuthService /
|
||||
* api.leads.capture / infra/mcaptcha/README.md + AD-7).
|
||||
* Render this **inside** the <form> it should protect: the provider injects a
|
||||
* hidden token field (`cap-token` or `mcaptcha__token`), so it is submitted
|
||||
* with the form and verified server-side by `@hivegrid/captcha`.
|
||||
*
|
||||
* Client load failures are non-fatal — the server verifier fails open
|
||||
* (CAPTCHA_FAIL_OPEN, default true) when no token is present. The glue is
|
||||
* imported dynamically so it never runs during SSR.
|
||||
* Client load failures are non-fatal. The server verifier applies
|
||||
* CAPTCHA_FAIL_OPEN for provider outages, while a missing token remains a hard
|
||||
* failure when captcha is required.
|
||||
*/
|
||||
export default function Captcha({ enabled, instanceUrl, sitekey }: Props) {
|
||||
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey }: Props) {
|
||||
const active = enabled && Boolean(instanceUrl && sitekey);
|
||||
const initialized = useRef(false);
|
||||
|
||||
@@ -36,6 +37,10 @@ export default function Captcha({ enabled, instanceUrl, sitekey }: Props) {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
if (provider === "cap") {
|
||||
loadCapAssets(instanceUrl!);
|
||||
return;
|
||||
}
|
||||
const { default: Widget } = await import("@mcaptcha/vanilla-glue");
|
||||
if (cancelled) return;
|
||||
// Widget self-mounts into #MOUNT_ID and injects the hidden mcaptcha__token field.
|
||||
@@ -47,8 +52,47 @@ export default function Captcha({ enabled, instanceUrl, sitekey }: Props) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [active, instanceUrl, sitekey]);
|
||||
}, [active, instanceUrl, provider, sitekey]);
|
||||
|
||||
if (!active) return null;
|
||||
if (provider === "cap") {
|
||||
return (
|
||||
<>
|
||||
{/*
|
||||
Cap's custom element injects <input name="cap-token"> into the
|
||||
enclosing form when solved.
|
||||
*/}
|
||||
{createCapWidget(instanceUrl!, sitekey!)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <div id={MOUNT_ID} className="m-captcha" data-ui-id="ui.captcha.mount" />;
|
||||
}
|
||||
|
||||
function createCapWidget(instanceUrl: string, sitekey: string) {
|
||||
return createElement("cap-widget", {
|
||||
required: true,
|
||||
"data-cap-api-endpoint": `${instanceUrl.replace(/\/+$/, "")}/${sitekey}/`,
|
||||
"data-ui-id": "ui.captcha.mount",
|
||||
});
|
||||
}
|
||||
|
||||
function loadCapAssets(instanceUrl: string): void {
|
||||
const base = instanceUrl.replace(/\/+$/, "");
|
||||
const scriptSrc = `${base}/assets/widget.js`;
|
||||
window.CAP_CUSTOM_WASM_URL = `${base}/assets/cap_wasm_bg.wasm`;
|
||||
if (document.querySelector(`script[data-cap-widget-loader="true"][src="${scriptSrc}"]`)) return;
|
||||
const script = document.createElement("script");
|
||||
script.type = "module";
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
script.src = scriptSrc;
|
||||
script.dataset.capWidgetLoader = "true";
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
CAP_CUSTOM_WASM_URL?: string;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
|
||||
import SkipToContent from "./SkipToContent";
|
||||
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
|
||||
import { expectNoAxeViolations } from "@hivegrid/ui-app/test-setup/axe";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import ApiKeyForm from "./ApiKeyForm";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (value: string) => value }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useSubmit: () => vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ csrf: "csrf-test-token" }),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/forms/FormGroup", () => ({
|
||||
default: ({ children }: { children: React.ReactNode }) => <form>{children}</form>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputText", () => ({
|
||||
default: ({ title, name, value, setValue, disabled }: { title: string; name: string; value: string; setValue: (value: string) => void; disabled?: boolean }) => (
|
||||
<label>
|
||||
{title}
|
||||
<input name={name} value={value} onChange={(event) => setValue(event.currentTarget.value)} disabled={disabled} />
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputDate", () => ({
|
||||
default: ({ title, name, value, onChange, disabled }: { title: string; name: string; value?: Date; onChange: (value: Date) => void; disabled?: boolean }) => (
|
||||
<label>
|
||||
{title}
|
||||
<input
|
||||
type="date"
|
||||
name={name}
|
||||
value={value?.toISOString().split("T")[0] ?? ""}
|
||||
onChange={(event) => onChange(new Date(event.currentTarget.value))}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputCheckboxInline", () => ({
|
||||
default: ({ name, title, value, setValue, disabled }: { name: string; title: React.ReactNode; value?: boolean; setValue?: (value: boolean) => void; disabled?: boolean }) => (
|
||||
<label>
|
||||
<input type="checkbox" name={name} checked={value} onChange={(event) => setValue?.(event.currentTarget.checked)} disabled={disabled} />
|
||||
{title}
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/tooltips/HintTooltip", () => ({
|
||||
default: ({ text }: { text: string }) => <span>{text}</span>,
|
||||
}));
|
||||
|
||||
const entity = {
|
||||
id: "entity_contacts",
|
||||
order: 1,
|
||||
name: "contact",
|
||||
title: "Contacts",
|
||||
titlePlural: "Contacts",
|
||||
active: true,
|
||||
slug: "contacts",
|
||||
type: DefaultEntityTypes.AppOnly,
|
||||
hasApi: true,
|
||||
showInSidebar: true,
|
||||
icon: "users",
|
||||
onEdit: null,
|
||||
};
|
||||
|
||||
describe("ApiKeyForm scope editor", () => {
|
||||
it("uses accessible CRUD labels and keeps entities[] payloads in sync", () => {
|
||||
render(<ApiKeyForm entities={[entity]} />);
|
||||
|
||||
const createCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.create Contacts/i });
|
||||
const readCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.read Contacts/i });
|
||||
const updateCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.update Contacts/i });
|
||||
const deleteCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.delete Contacts/i });
|
||||
|
||||
expect(createCheckbox).toBeChecked();
|
||||
expect(readCheckbox).toBeChecked();
|
||||
expect(updateCheckbox).toBeChecked();
|
||||
expect(deleteCheckbox).toBeChecked();
|
||||
|
||||
fireEvent.click(deleteCheckbox);
|
||||
|
||||
const hiddenPayload = document.querySelector<HTMLInputElement>('input[type="hidden"][name="entities[]"]');
|
||||
expect(hiddenPayload).toBeInTheDocument();
|
||||
expect(JSON.parse(hiddenPayload?.value ?? "{}")).toEqual({
|
||||
entityId: "entity_contacts",
|
||||
create: true,
|
||||
read: true,
|
||||
update: true,
|
||||
delete: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("disables scope checkboxes when updates are not allowed", () => {
|
||||
render(<ApiKeyForm entities={[entity]} canUpdate={false} />);
|
||||
|
||||
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.create Contacts/i })).toBeDisabled();
|
||||
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.read Contacts/i })).toBeDisabled();
|
||||
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.update Contacts/i })).toBeDisabled();
|
||||
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.delete Contacts/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import type { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { useRef, useState, useEffect } from "react";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputCheckboxInline from "~/components/ui/input/InputCheckboxInline";
|
||||
@@ -11,18 +10,15 @@ import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
|
||||
import type { EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
|
||||
|
||||
interface Props {
|
||||
entities: EntitySimple[];
|
||||
item?: RedactedApiKeyWithDetails | null;
|
||||
tenants?: Tenant[];
|
||||
canUpdate?: boolean;
|
||||
canDelete?: boolean;
|
||||
canRotate?: boolean;
|
||||
}
|
||||
export default function ApiKeyForm({ entities, item, tenants, canUpdate = true, canDelete, canRotate = false }: Props) {
|
||||
export default function ApiKeyForm({ item, tenants, canUpdate = true, canDelete, canRotate = false }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const rootData = useRootData();
|
||||
@@ -33,25 +29,6 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
|
||||
const [alias, setAlias] = useState(item?.alias ?? "");
|
||||
const [expires, setExpires] = useState<Date | undefined>(item?.expires ?? undefined);
|
||||
const [active, setActive] = useState(item?.active ?? true);
|
||||
const [permissions, setPermissions] = useState<{ entityId: string; create: boolean; read: boolean; update: boolean; delete: boolean }[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const permissions: { entityId: string; create: boolean; read: boolean; update: boolean; delete: boolean }[] = [];
|
||||
entities
|
||||
.filter((f) => (f.type === DefaultEntityTypes.AppOnly || f.type === DefaultEntityTypes.All) && f.hasApi)
|
||||
.forEach((entity) => {
|
||||
const existing = item?.entities.find((f) => f.entityId === entity.id);
|
||||
permissions.push({
|
||||
entityId: entity.id,
|
||||
create: existing?.create ?? true,
|
||||
read: existing?.read ?? true,
|
||||
update: existing?.update ?? true,
|
||||
delete: existing?.delete ?? true,
|
||||
});
|
||||
});
|
||||
setPermissions(permissions);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
@@ -82,7 +59,7 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
|
||||
{tenants && (
|
||||
<>
|
||||
<InputSelect
|
||||
className="col-span-6"
|
||||
className="col-span-12"
|
||||
name="tenant-id"
|
||||
title={t("models.tenant.object")}
|
||||
value={tenantId}
|
||||
@@ -114,6 +91,7 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
|
||||
<InputDate
|
||||
disabled={!canUpdate}
|
||||
className="col-span-6"
|
||||
classNameInput="h-[34px] !text-[16px] !leading-[22px] font-body-default-regular-0 md:!text-[16px]"
|
||||
name="expires"
|
||||
title={t("models.apiKey.expires")}
|
||||
value={expires}
|
||||
@@ -129,121 +107,6 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="col-span-12 flex flex-col">
|
||||
<div className="overflow-x-auto">
|
||||
<div className="inline-block min-w-full py-2 align-middle">
|
||||
<div className="border-border overflow-hidden border shadow-xs sm:rounded-lg">
|
||||
<table className="divide-border min-w-full divide-y">
|
||||
<thead className="bg-secondary">
|
||||
<tr>
|
||||
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
|
||||
<div className="text-muted-foreground flex items-center space-x-1">
|
||||
<div>{t("models.entity.object")}</div>
|
||||
</div>
|
||||
</th>
|
||||
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
|
||||
{t("models.apiKey.create")}
|
||||
</th>
|
||||
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
|
||||
{t("models.apiKey.read")}
|
||||
</th>
|
||||
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
|
||||
{t("models.apiKey.update")}
|
||||
</th>
|
||||
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
|
||||
{t("models.apiKey.delete")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-border bg-background divide-y">
|
||||
{entities
|
||||
.filter((f) => (f.type === DefaultEntityTypes.AppOnly || f.type === DefaultEntityTypes.All) && f.hasApi)
|
||||
.map((item, idx) => {
|
||||
const entityLabel = t(item.title);
|
||||
const entityDescription = `/${item.slug}`;
|
||||
return (
|
||||
<tr key={idx}>
|
||||
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
|
||||
<input
|
||||
type="hidden"
|
||||
name="entities[]"
|
||||
value={JSON.stringify({
|
||||
entityId: item.id,
|
||||
create: permissions.find((f) => f.entityId === item.id)?.create ?? false,
|
||||
read: permissions.find((f) => f.entityId === item.id)?.read ?? false,
|
||||
update: permissions.find((f) => f.entityId === item.id)?.update ?? false,
|
||||
delete: permissions.find((f) => f.entityId === item.id)?.delete ?? false,
|
||||
})}
|
||||
/>
|
||||
<div className="font-medium text-foreground">{entityLabel}</div>
|
||||
<div className="text-xs">{entityDescription}</div>
|
||||
</td>
|
||||
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
|
||||
<InputCheckboxInline
|
||||
disabled={!canUpdate}
|
||||
name={`${item.id}-create`}
|
||||
title={`${t("models.apiKey.create")} ${entityLabel}`}
|
||||
help={`${t("models.apiKey.create")} ${entityDescription}`}
|
||||
value={permissions.find((f) => f.entityId === item.id)?.create ?? false}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(permissions, setPermissions, idx, {
|
||||
create: e,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
|
||||
<InputCheckboxInline
|
||||
disabled={!canUpdate}
|
||||
name={`${item.id}-read`}
|
||||
title={`${t("models.apiKey.read")} ${entityLabel}`}
|
||||
help={`${t("models.apiKey.read")} ${entityDescription}`}
|
||||
value={permissions.find((f) => f.entityId === item.id)?.read ?? false}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(permissions, setPermissions, idx, {
|
||||
read: e,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
|
||||
<InputCheckboxInline
|
||||
disabled={!canUpdate}
|
||||
name={`${item.id}-update`}
|
||||
title={`${t("models.apiKey.update")} ${entityLabel}`}
|
||||
help={`${t("models.apiKey.update")} ${entityDescription}`}
|
||||
value={permissions.find((f) => f.entityId === item.id)?.update ?? false}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(permissions, setPermissions, idx, {
|
||||
update: e,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
|
||||
<InputCheckboxInline
|
||||
disabled={!canUpdate}
|
||||
name={`${item.id}-delete`}
|
||||
title={`${t("models.apiKey.delete")} ${entityLabel}`}
|
||||
help={`${t("models.apiKey.delete")} ${entityDescription}`}
|
||||
value={permissions.find((f) => f.entityId === item.id)?.delete ?? false}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(permissions, setPermissions, idx, {
|
||||
delete: e,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<InputCheckboxInline
|
||||
disabled={!canUpdate}
|
||||
className="col-span-12"
|
||||
|
||||
@@ -3,7 +3,6 @@ import { render, screen } from "@testing-library/react";
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import ApiKeysTable from "./ApiKeysTable";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
@@ -28,21 +27,6 @@ vi.mock("~/components/ui/buttons/ButtonTertiary", () => ({
|
||||
}));
|
||||
|
||||
const now = new Date("2026-01-01T00:00:00.000Z");
|
||||
const entity = {
|
||||
id: "entity_contacts",
|
||||
order: 1,
|
||||
name: "contact",
|
||||
title: "Contacts",
|
||||
titlePlural: "Contacts",
|
||||
active: true,
|
||||
slug: "contacts",
|
||||
type: DefaultEntityTypes.AppOnly,
|
||||
hasApi: true,
|
||||
showInSidebar: true,
|
||||
icon: "users",
|
||||
onEdit: null,
|
||||
};
|
||||
|
||||
const apiKey = {
|
||||
id: "api_key_1",
|
||||
keyPrefix: "tc_live",
|
||||
@@ -66,24 +50,12 @@ const apiKey = {
|
||||
locale: "en",
|
||||
createdAt: now,
|
||||
},
|
||||
entities: [
|
||||
{
|
||||
id: "permission_1",
|
||||
apiKeyId: "api_key_1",
|
||||
entityId: "entity_contacts",
|
||||
create: true,
|
||||
read: true,
|
||||
update: false,
|
||||
delete: false,
|
||||
entity: { id: "entity_contacts", title: "Contacts", titlePlural: "Contacts", slug: "contacts" },
|
||||
},
|
||||
],
|
||||
_count: { apiKeyLogs: 2 },
|
||||
};
|
||||
|
||||
describe("ApiKeysTable redacted key display", () => {
|
||||
it("renders redacted metadata without raw key text or copy controls", () => {
|
||||
const { container } = render(<ApiKeysTable entities={[entity]} items={[apiKey]} />);
|
||||
const { container } = render(<ApiKeysTable items={[apiKey]} />);
|
||||
|
||||
expect(screen.getByText("tc_live…••••9xyz")).toBeInTheDocument();
|
||||
expect(screen.queryByText("tc_live_raw_secret_that_must_not_render")).not.toBeInTheDocument();
|
||||
@@ -92,7 +64,7 @@ describe("ApiKeysTable redacted key display", () => {
|
||||
});
|
||||
|
||||
it("keeps inactive state visible alongside redacted metadata", () => {
|
||||
render(<ApiKeysTable entities={[entity]} items={[{ ...apiKey, active: false }]} />);
|
||||
render(<ApiKeysTable items={[{ ...apiKey, active: false }]} />);
|
||||
|
||||
expect(screen.getByText("tc_live…••••9xyz")).toBeInTheDocument();
|
||||
expect(screen.getByText("shared.inactive")).toBeInTheDocument();
|
||||
@@ -103,7 +75,7 @@ describe("ApiKeysTable redacted key display", () => {
|
||||
const newerApiKey = { ...apiKey, id: "api_key_newer", alias: "Newer integration", createdAt: new Date("2026-01-01T00:00:00.000Z") };
|
||||
const sourceItems = [olderApiKey, newerApiKey];
|
||||
|
||||
render(<ApiKeysTable entities={[entity]} items={sourceItems} />);
|
||||
render(<ApiKeysTable items={sourceItems} />);
|
||||
|
||||
expect(screen.getByText("Newer integration")).toBeInTheDocument();
|
||||
expect(sourceItems.map((item) => item.id)).toEqual(["api_key_older", "api_key_newer"]);
|
||||
@@ -113,7 +85,6 @@ describe("ApiKeysTable redacted key display", () => {
|
||||
const source = readFileSync(path.resolve(process.cwd(), "apps/web/app/components/core/apiKeys/ApiKeysTable.tsx"), "utf8");
|
||||
|
||||
expect(source).toContain("const filteredSortedRows = useMemo<ApiKeyTableRow[]>(");
|
||||
expect(source).toContain("apiKeyEntityById: new Map(item.entities.map");
|
||||
expect(source).toContain("redactedKey: getRedactedKey(item)");
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,12 @@
|
||||
import clsx from "clsx";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import EmptyState from "~/components/ui/emptyState/EmptyState";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
|
||||
import type { EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
|
||||
interface Props {
|
||||
entities: EntitySimple[];
|
||||
items: RedactedApiKeyWithDetails[];
|
||||
withTenant?: boolean;
|
||||
canCreate?: boolean;
|
||||
@@ -21,7 +17,6 @@ type Header = {
|
||||
};
|
||||
|
||||
type ApiKeyTableRow = {
|
||||
apiKeyEntityById: Map<string, RedactedApiKeyWithDetails["entities"][number]>;
|
||||
item: RedactedApiKeyWithDetails;
|
||||
redactedKey: string;
|
||||
};
|
||||
@@ -30,17 +25,12 @@ function getRedactedKey(item: RedactedApiKeyWithDetails) {
|
||||
return [item.keyPrefix, item.keyLastFour ? `••••${item.keyLastFour}` : undefined].filter(Boolean).join("…") || "••••";
|
||||
}
|
||||
|
||||
export default function ApiKeysTable({ entities, items, withTenant, canCreate }: Props) {
|
||||
export default function ApiKeysTable({ items, withTenant, canCreate }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const apiEntities = useMemo(
|
||||
() => entities.filter((f) => (f.type === DefaultEntityTypes.AppOnly || f.type === DefaultEntityTypes.All) && f.hasApi),
|
||||
[entities]
|
||||
);
|
||||
|
||||
const headers = useMemo(() => {
|
||||
const nextHeaders: Header[] = [];
|
||||
if (withTenant) {
|
||||
@@ -49,14 +39,11 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
|
||||
nextHeaders.push({ name: "key", title: t("models.apiKey.key") });
|
||||
nextHeaders.push({ name: "alias", title: t("models.apiKey.alias") });
|
||||
nextHeaders.push({ name: "usage", title: t("models.apiKey.usage") });
|
||||
apiEntities.forEach((entity) => {
|
||||
nextHeaders.push({ name: "entityId", title: t(entity.titlePlural) });
|
||||
});
|
||||
nextHeaders.push({ name: "expires", title: t("models.apiKey.expires") });
|
||||
nextHeaders.push({ name: "createdAt", title: t("shared.createdAt") });
|
||||
nextHeaders.push({ name: "createdByUser", title: t("shared.createdBy") });
|
||||
return nextHeaders;
|
||||
}, [apiEntities, t, withTenant]);
|
||||
}, [t, withTenant]);
|
||||
|
||||
const filteredSortedRows = useMemo<ApiKeyTableRow[]>(() => {
|
||||
if (!items) {
|
||||
@@ -73,7 +60,6 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
|
||||
return -1;
|
||||
})
|
||||
.map((item) => ({
|
||||
apiKeyEntityById: new Map(item.entities.map((apiKeyEntity) => [apiKeyEntity.entityId, apiKeyEntity])),
|
||||
item,
|
||||
redactedKey: getRedactedKey(item),
|
||||
}));
|
||||
@@ -136,7 +122,7 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-border bg-background divide-y">
|
||||
{filteredSortedRows.map(({ apiKeyEntityById, item, redactedKey }, idx) => {
|
||||
{filteredSortedRows.map(({ item, redactedKey }, idx) => {
|
||||
return (
|
||||
<tr key={idx}>
|
||||
{withTenant && (
|
||||
@@ -155,19 +141,6 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
|
||||
{formatters.number(item._count.apiKeyLogs)}{" "}
|
||||
{item._count.apiKeyLogs === 1 ? t("models.apiCall.object") : t("models.apiCall.plural")}
|
||||
</td>
|
||||
{apiEntities.map((entity) => {
|
||||
const apiKeyEntity = apiKeyEntityById.get(entity.id);
|
||||
return (
|
||||
<td key={entity.id} className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
|
||||
<div className="flex items-center">
|
||||
<span className={clsx(apiKeyEntity?.create ? "text-foreground font-bold" : "text-red-400")}>C</span>
|
||||
<span className={clsx(apiKeyEntity?.read ? "text-foreground font-bold" : "text-red-400")}>R</span>
|
||||
<span className={clsx(apiKeyEntity?.update ? "text-foreground font-bold" : "text-red-400")}>U</span>
|
||||
<span className={clsx(apiKeyEntity?.delete ? "text-foreground font-bold" : "text-red-400")}>D</span>
|
||||
</div>
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
|
||||
<time
|
||||
dateTime={item.expires ? new Date(item.expires).toISOString() : undefined}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Entity } from "@toolctrl/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
|
||||
@@ -13,9 +12,8 @@ import { CheckCircleIcon, XCircleIcon, PlusIcon } from "~/components/ui/icons/ve
|
||||
interface Props {
|
||||
items: SubscriptionFeatureDto[];
|
||||
setItems: React.Dispatch<React.SetStateAction<SubscriptionFeatureDto[]>>;
|
||||
entities: Entity[];
|
||||
}
|
||||
export default function PricingFeaturesForm({ items, setItems, entities }: Props) {
|
||||
export default function PricingFeaturesForm({ items, setItems }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
function addFeature() {
|
||||
|
||||
@@ -30,6 +30,7 @@ import { Button } from "~/components/ui/button";
|
||||
import { TrashIcon } from "~/components/ui/icons/vendor";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { HIVEGRID_SUBSCRIPTION_PRICING_MODELS } from "~/application/pricing/pricingModelPolicy";
|
||||
|
||||
interface Props {
|
||||
plans?: SubscriptionProductDto[];
|
||||
@@ -48,31 +49,13 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
|
||||
const navigate = useNavigate();
|
||||
const submit = useSubmit();
|
||||
|
||||
let pricingModels = [
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE]),
|
||||
value: PricingModel.FLAT_RATE,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.PER_SEAT]),
|
||||
value: PricingModel.PER_SEAT,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.USAGE_BASED]),
|
||||
value: PricingModel.USAGE_BASED,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE_USAGE_BASED]),
|
||||
value: PricingModel.FLAT_RATE_USAGE_BASED,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.ONCE]),
|
||||
value: PricingModel.ONCE,
|
||||
},
|
||||
];
|
||||
let pricingModels = HIVEGRID_SUBSCRIPTION_PRICING_MODELS.map((value) => ({
|
||||
name: t("pricing." + PricingModel[value]),
|
||||
value,
|
||||
}));
|
||||
if (isPortalPlan) {
|
||||
pricingModels = pricingModels.filter(
|
||||
(f) => f.value !== PricingModel.USAGE_BASED && f.value !== PricingModel.FLAT_RATE_USAGE_BASED && f.value !== PricingModel.PER_SEAT
|
||||
(f) => f.value !== PricingModel.USAGE_BASED && f.value !== PricingModel.FLAT_RATE_USAGE_BASED
|
||||
);
|
||||
}
|
||||
const inputTitle = useRef<RefInputText>(null);
|
||||
@@ -393,7 +376,7 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{[PricingModel.FLAT_RATE, PricingModel.PER_SEAT, PricingModel.FLAT_RATE_USAGE_BASED, PricingModel.ONCE].includes(model) && (
|
||||
{[PricingModel.FLAT_RATE, PricingModel.FLAT_RATE_USAGE_BASED, PricingModel.ONCE].includes(model) && (
|
||||
<SettingSection title={t("pricing.planForm.sections.flatPrices.title")} description={t("pricing.planForm.sections.flatPrices.description")} className="">
|
||||
<FlatPrices model={model} prices={prices} setPrices={setPrices} disabled={item !== undefined} isPortalPlan={isPortalPlan} />
|
||||
</SettingSection>
|
||||
@@ -448,7 +431,7 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
|
||||
model={model}
|
||||
prices={prices}
|
||||
usageBasedPrices={usageBasedPrices}
|
||||
stripeCoupon={null}
|
||||
billingProviderCoupon={null}
|
||||
isPreview={true}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -97,7 +97,7 @@ export default function UsageBasedPrices({ initial, onUpdate, disabled }: Props)
|
||||
usageBasedPrices.push({
|
||||
id: "",
|
||||
subscriptionProductId: "",
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
|
||||
currency: price.currency,
|
||||
unit: unit.unit,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Group } from "@toolctrl/db/prisma-browser";
|
||||
import type { Group } from "@hivegrid/db/prisma-browser";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Permission, Role } from "@toolctrl/db/prisma-browser";
|
||||
import type { Permission, Role } from "@hivegrid/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Permission } from "@toolctrl/db/prisma-browser";
|
||||
import type { Permission } from "@hivegrid/db/prisma-browser";
|
||||
import clsx from "clsx";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Permission, Role } from "@toolctrl/db/prisma-browser";
|
||||
import type { Permission, Role } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
import { i18nNamespaces } from "~/locale/i18n";
|
||||
|
||||
@@ -72,6 +72,42 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
|
||||
users: "users",
|
||||
impersonate: "impersonate",
|
||||
changePassword: "changePassword",
|
||||
// P4 Files (AK-P4a) + Tasks (AK-P4b) bundle actions — the `files.*` / `tasks.*`
|
||||
// permissions use these read/write/admin verbs instead of the CRUD set above.
|
||||
read_own: "read_own",
|
||||
read_own_member: "read_own_member",
|
||||
read_own_pl: "read_own_pl",
|
||||
read_all: "read_all",
|
||||
write: "write",
|
||||
bulk_reassign: "bulk_reassign",
|
||||
change_stage: "change_stage",
|
||||
manage_members: "manage_members",
|
||||
read_volume_own: "read_volume_own",
|
||||
read_volume_all: "read_volume_all",
|
||||
read_aggregates: "read_aggregates",
|
||||
admin: "admin",
|
||||
// P5 Integrations (R-P5) — Apps-Engine connector bundle actions.
|
||||
read: "read",
|
||||
connect: "connect",
|
||||
disconnect: "disconnect",
|
||||
manual_sync: "manual_sync",
|
||||
view_logs: "view_logs",
|
||||
// P16 Calendar-Sync (AK-P16a) — per-user connect capability action.
|
||||
connect_own: "connect_own",
|
||||
// P17 HR-Hub workflows (AK-P17b) — leave approval + survey results capabilities.
|
||||
approve: "approve",
|
||||
results: "results",
|
||||
basic: "basic",
|
||||
builder: "builder",
|
||||
publisher: "publisher",
|
||||
send: "send",
|
||||
revoke: "revoke",
|
||||
customize: "customize",
|
||||
run: "run",
|
||||
self: "self",
|
||||
tenant_export: "tenant_export",
|
||||
tenant_deletion: "tenant_deletion",
|
||||
accept: "accept",
|
||||
};
|
||||
|
||||
const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
|
||||
@@ -86,32 +122,29 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
|
||||
"app.settings.subscription": "app.settings.subscription",
|
||||
"app.settings.subscription.invoices": "app.settings.subscription.invoices",
|
||||
"app.plugins": "app.plugins",
|
||||
"app.onboarding.demoData": "app.onboarding.demoData",
|
||||
"app.onboarding.checklist": "app.onboarding.checklist",
|
||||
"admin.account": "admin.account",
|
||||
"admin.account.settings": "admin.account.settings",
|
||||
"admin.accountTypes": "admin.accountTypes",
|
||||
"admin.accounts": "admin.accounts",
|
||||
"admin.analytics": "admin.analytics",
|
||||
"admin.apiKeys": "admin.apiKeys",
|
||||
"admin.auditTrails": "admin.auditTrails",
|
||||
"admin.blacklist": "admin.blacklist",
|
||||
"admin.dashboard": "admin.dashboard",
|
||||
"admin.emails": "admin.emails",
|
||||
"admin.entities": "admin.entities",
|
||||
"admin.events": "admin.events",
|
||||
"admin.featureFlags": "admin.featureFlags",
|
||||
"admin.formulas": "admin.formulas",
|
||||
"admin.kb": "admin.kb",
|
||||
"admin.marketing.funnels": "admin.marketing.funnels",
|
||||
"admin.marketing.integrations": "admin.marketing.integrations",
|
||||
"admin.marketing.leads": "admin.marketing.leads",
|
||||
"admin.metrics": "admin.metrics",
|
||||
"admin.notifications": "admin.notifications",
|
||||
"admin.onboarding": "admin.onboarding",
|
||||
"admin.pricing": "admin.pricing",
|
||||
"admin.prompts": "admin.prompts",
|
||||
"admin.relationships": "admin.relationships",
|
||||
"admin.roles": "admin.roles",
|
||||
"admin.settings.analytics": "admin.settings.analytics",
|
||||
"admin.settings.authentication": "admin.settings.authentication",
|
||||
"admin.settings.cookies": "admin.settings.cookies",
|
||||
"admin.settings.danger": "admin.settings.danger",
|
||||
@@ -120,6 +153,57 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
|
||||
"admin.settings.seo": "admin.settings.seo",
|
||||
"admin.tenantIpAddress": "admin.tenantIpAddress",
|
||||
"admin.users": "admin.users",
|
||||
// P4 platform primitives (AK-P4a Files, AK-P4b Tasks) — these scopes carry no
|
||||
// `app.`/`admin.` prefix, so they need their own scope-key mapping.
|
||||
files: "files",
|
||||
tasks: "tasks",
|
||||
// P6 CRM core (R-P6) — typed CRM contacts scope, no `app.`/`admin.` prefix.
|
||||
crm: "crm",
|
||||
// P7 Lead-Inbox (R-P7) — typed lead intake scope, no `app.`/`admin.` prefix.
|
||||
leads: "leads",
|
||||
// P8 Projekt/Pipelines (R-P8a). `deals.*` is the historical permission
|
||||
// backstop for sales-pipeline volume/aggregates; the entity remains Projekt.
|
||||
projects: "projects",
|
||||
deals: "deals",
|
||||
plantafel: "plantafel",
|
||||
acceptance: "acceptance",
|
||||
// P17 HR-Hub (AK-P17a). `hr.passwordsafe` maps to a FLAT key (`hrPasswordsafe`)
|
||||
// on purpose: the `hr` scope is itself a string leaf, so a nested
|
||||
// `scopes.hr.passwordsafe` path would collide with it.
|
||||
hr: "hr",
|
||||
"hr.passwordsafe": "hrPasswordsafe",
|
||||
// P17 HR-Hub workflows (AK-P17b) — flat keys for the same collision reason as
|
||||
// hrPasswordsafe (the `hr` scope is itself a string leaf).
|
||||
"hr.leave": "hrLeave",
|
||||
"hr.surveys": "hrSurveys",
|
||||
// P5 Integrations (R-P5) — Apps-Engine connector scope.
|
||||
integrations: "integrations",
|
||||
// P14 Email (AK-P14a) — sending-domain settings. Flat key (the email-marketing
|
||||
// module gate is feature-access; this scope is tenant-side domain management).
|
||||
"email.domain": "emailDomain",
|
||||
// P23 Postfach-Sync (VA-P23) — per-user mailbox mirror scope (read_own/read_all/write).
|
||||
email: "email",
|
||||
// P14 Email-Marketing (AK-P14b) — campaigns/segments/reporting scope.
|
||||
emailMarketing: "emailMarketing",
|
||||
// P16 Calendar-Sync (AK-P16a) — per-user calendar connection scope.
|
||||
calendar: "calendar",
|
||||
// P16 Booking (AK-P16b) — booking pages, availability, appointment lifecycle scope.
|
||||
bookings: "bookings",
|
||||
// P16 Forms (AK-P16c) — embedded forms and form-builder scope.
|
||||
forms: "forms",
|
||||
// P16 Signature (AK-P16d) — SES/PandaDoc signature workflow scope.
|
||||
signature: "signature",
|
||||
// P11 Global Search (R-P11a) — global permission-aware search surface.
|
||||
search: "search",
|
||||
// P11 Dashboard (R-P11b) — role dashboard surface and filter customization.
|
||||
dashboard: "dashboard",
|
||||
// P12 Automation (R-P12a) — typed automation rules, executions and guards.
|
||||
automation: "automation",
|
||||
// P21 Privacy/GDPR (AK-P21). Flat keys avoid colliding with the privacy leaf.
|
||||
privacy: "privacy",
|
||||
"privacy.user_export": "privacyUserExport",
|
||||
"privacy.avv": "privacyAvv",
|
||||
"privacy.subprocessors": "privacySubprocessors",
|
||||
};
|
||||
|
||||
function humanizeIdentifier(value: string) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState } from "react";
|
||||
import clsx from "~/utils/shared/ClassesUtils";
|
||||
import type { TenantUserInvitation } from "@toolctrl/db/prisma-browser";
|
||||
import type { TenantUserInvitation } from "@hivegrid/db/prisma-browser";
|
||||
import { useSubmit } from "react-router";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import UserBadge from "../../users/UserBadge";
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import type { TenantUserWithUser } from "~/utils/db/tenants.db.server";
|
||||
import type { TenantUser } from "@toolctrl/db/prisma-browser";
|
||||
import type { TenantUser } from "@hivegrid/db/prisma-browser";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import UserBadge from "../../users/UserBadge";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
|
||||
@@ -209,12 +209,12 @@ export default function ChangeSubscription({ items, current, billingPeriod, curr
|
||||
{/* Button */}
|
||||
<div className="shrink-0 space-y-2 pt-4">
|
||||
<button
|
||||
disabled={loading || isCurrent(plan) || !getPrice(plan)?.stripeId || !canSubscribe}
|
||||
disabled={loading || isCurrent(plan) || !getPrice(plan)?.billingProviderId || !canSubscribe}
|
||||
type="button"
|
||||
onClick={() => selectPrice(plan)}
|
||||
className={clsx(
|
||||
"inline-flex w-full items-center justify-center rounded-lg border px-4 py-2 text-sm transition-colors focus:outline-hidden focus:ring-2 focus:ring-offset-2",
|
||||
loading || isCurrent(plan) || !getPrice(plan)?.stripeId || !canSubscribe
|
||||
loading || isCurrent(plan) || !getPrice(plan)?.billingProviderId || !canSubscribe
|
||||
? "cursor-not-allowed opacity-80"
|
||||
: "hover:bg-secondary/90 border-slate-800"
|
||||
// isUpgrade(plan) && canSubscribe && "hover:text-teal-600",
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Stripe from "stripe";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import DownloadIcon from "~/components/ui/icons/DownloadIcon";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/CustomerBillingInvoiceDto";
|
||||
|
||||
interface Props {
|
||||
items: Stripe.Invoice[];
|
||||
items: CustomerBillingInvoiceDto[];
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
export default function MyInvoices({ items }: Props) {
|
||||
function invoiceStatusColor(status: CustomerBillingInvoiceDto["status"], paymentStatus: CustomerBillingInvoiceDto["paymentStatus"]): Colors {
|
||||
if (paymentStatus === "succeeded") return Colors.GREEN;
|
||||
if (status === "voided" || status === "failed" || paymentStatus === "failed") return Colors.RED;
|
||||
return Colors.YELLOW;
|
||||
}
|
||||
|
||||
export default function MyInvoices({ items, error }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm font-medium">{t("app.subscription.invoices.title")}</div>
|
||||
{items.length === 0 ? (
|
||||
{error ? (
|
||||
<div className="text-muted-foreground text-sm">{error}</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="text-muted-foreground text-sm italic">{t("shared.noRecords")}</div>
|
||||
) : (
|
||||
<TableSimple
|
||||
@@ -25,11 +33,11 @@ export default function MyInvoices({ items }: Props) {
|
||||
{
|
||||
name: "date",
|
||||
title: t("shared.createdAt"),
|
||||
value: (i) => formatters.date(new Date(i.created * 1000), { dateStyle: "medium" }),
|
||||
value: (i) => (i.issuingDate ? formatters.date(new Date(i.issuingDate), { dateStyle: "medium" }) : t("shared.unknown")),
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.date(new Date(item.created * 1000), { dateStyle: "medium" })}</div>
|
||||
<div className="text-xs">{formatters.relativeDate(new Date(item.created * 1000))}</div>
|
||||
<div>{item.issuingDate ? formatters.date(new Date(item.issuingDate), { dateStyle: "medium" }) : t("shared.unknown")}</div>
|
||||
{item.issuingDate && <div className="text-xs">{formatters.relativeDate(new Date(item.issuingDate))}</div>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -38,8 +46,10 @@ export default function MyInvoices({ items }: Props) {
|
||||
title: t("app.subscription.invoices.amount"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.currency(Number(i.amount_paid) / 100, i.currency.toUpperCase())}</div>
|
||||
<div className="text-muted-foreground text-xs uppercase">{i.currency}</div>
|
||||
<div>
|
||||
{i.amountCents !== null && i.currency ? formatters.currency(i.amountCents / 100, i.currency.toUpperCase()) : t("shared.unknown")}
|
||||
</div>
|
||||
{i.currency && <div className="text-muted-foreground text-xs uppercase">{i.currency}</div>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -47,9 +57,10 @@ export default function MyInvoices({ items }: Props) {
|
||||
name: "status",
|
||||
title: t("shared.status"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<SimpleBadge title={t("app.subscription.invoices.status." + i.status)} color={i.status === "paid" ? Colors.GREEN : Colors.YELLOW} />
|
||||
</div>
|
||||
<SimpleBadge
|
||||
title={t(`app.subscription.invoices.paymentStatus.${i.paymentStatus}`)}
|
||||
color={invoiceStatusColor(i.status, i.paymentStatus)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -58,13 +69,8 @@ export default function MyInvoices({ items }: Props) {
|
||||
title: t("app.subscription.invoices.items"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
{i.lines.data.map((lineItem, idx) => {
|
||||
return (
|
||||
<div key={idx}>
|
||||
{lineItem.description}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<span>{i.number ?? i.id}</span>
|
||||
{i.invoiceType && <span className="text-muted-foreground text-xs">{t(`app.subscription.invoices.type.${i.invoiceType}`)}</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -76,8 +82,8 @@ export default function MyInvoices({ items }: Props) {
|
||||
<DownloadIcon className="h-4 w-4" />
|
||||
</div>
|
||||
),
|
||||
onClickRoute: (_, item) => item.invoice_pdf ?? "",
|
||||
disabled: (item) => !item.invoice_pdf,
|
||||
onClickRoute: (_, item) => item.downloadHref ?? "",
|
||||
disabled: (item) => !item.downloadHref,
|
||||
onClickRouteTarget: "_blank",
|
||||
firstColumn: true,
|
||||
},
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Stripe from "stripe";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
|
||||
interface Props {
|
||||
items: Stripe.PaymentMethod[];
|
||||
items: {
|
||||
id: string;
|
||||
card?: {
|
||||
brand?: string | null;
|
||||
country?: string | null;
|
||||
exp_month?: number | null;
|
||||
exp_year?: number | null;
|
||||
last4?: string | null;
|
||||
} | null;
|
||||
}[];
|
||||
onAdd: () => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
@@ -57,7 +65,7 @@ export default function MyPaymentMethods({ items, onAdd, onDelete }: Props) {
|
||||
title: t("app.subscription.paymentMethods.expiration"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
{i.card?.exp_month.toString().padStart(2, "0")}/{i.card?.exp_year}
|
||||
{i.card?.exp_month?.toString().padStart(2, "0")}/{i.card?.exp_year}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Stripe from "stripe";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
items: Stripe.PaymentIntent[];
|
||||
items: {
|
||||
created: number;
|
||||
amount: number;
|
||||
currency: string;
|
||||
status: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export default function MyPayments({ items }: Props) {
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import { Link } from "react-router";
|
||||
import TenantProduct from "./TenantProduct";
|
||||
import { TenantSubscriptionProductWithDetails } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
|
||||
import { subscriptionCheckoutPath } from "~/utils/app/SubscriptionUrlUtils";
|
||||
|
||||
interface Props {
|
||||
currentTenant: { slug: string };
|
||||
items: TenantSubscriptionProductWithDetails[];
|
||||
onCancel?: (item: TenantSubscriptionProductWithDetails) => void;
|
||||
}
|
||||
@@ -37,7 +34,7 @@ function splitItems(items: TenantSubscriptionProductWithDetails[]) {
|
||||
return { active, history };
|
||||
}
|
||||
|
||||
export default function MyProducts({ currentTenant, items, onCancel }: Props) {
|
||||
export default function MyProducts({ items, onCancel }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { active, history } = splitItems(items);
|
||||
const [showHistory, setShowHistory] = useState(false);
|
||||
@@ -45,11 +42,7 @@ export default function MyProducts({ currentTenant, items, onCancel }: Props) {
|
||||
return (
|
||||
<div className="space-y-4" data-ui-id="ui.subscription.products">
|
||||
{active.length === 0 ? (
|
||||
<WarningBanner title={t("settings.subscription.noSubscription")} text={""}>
|
||||
<Link to={subscriptionCheckoutPath(currentTenant.slug)} className="underline" data-ui-id="ui.subscription.checkout.link">
|
||||
{t("settings.subscription.viewAllProducts")}.
|
||||
</Link>
|
||||
</WarningBanner>
|
||||
<WarningBanner title={t("settings.subscription.noSubscription")} text={t("settings.subscription.readOnlyExternalReference")} />
|
||||
) : (
|
||||
<div className="grid gap-2" data-ui-id="ui.subscription.product.active">
|
||||
{active.map((item, idx) => {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Stripe from "stripe";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
items: Stripe.Invoice[];
|
||||
items: {
|
||||
amount_due: number;
|
||||
currency: string;
|
||||
next_payment_attempt?: number | null;
|
||||
lines: { data: { description?: string | null }[] };
|
||||
}[];
|
||||
}
|
||||
|
||||
export default function MyUpcomingInvoice({ items }: Props) {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Fragment, useState } from "react";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import AnalyticsHelper from "~/utils/helpers/AnalyticsHelper";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Stripe from "stripe";
|
||||
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
|
||||
import PlanFeatureDescription from "./PlanFeatureDescription";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
@@ -42,7 +42,7 @@ interface Props {
|
||||
canSubmit?: boolean;
|
||||
isUpgrade?: boolean;
|
||||
isDowngrade?: boolean;
|
||||
stripeCoupon: Stripe.Coupon | null;
|
||||
billingProviderCoupon: BillingProviderCouponDto | null;
|
||||
isPreview?: boolean;
|
||||
onClickFeature?: (name: string) => void;
|
||||
/** When set, the user has an existing active subscription on a *different* plan. Click opens a proration preview before submitting. */
|
||||
@@ -65,7 +65,7 @@ export default function Plan({
|
||||
canSubmit,
|
||||
isUpgrade,
|
||||
isDowngrade,
|
||||
stripeCoupon,
|
||||
billingProviderCoupon,
|
||||
isPreview,
|
||||
onClickFeature,
|
||||
currentPlanInfo,
|
||||
@@ -154,7 +154,7 @@ export default function Plan({
|
||||
}
|
||||
|
||||
// If the user has an existing sub on a different plan, show a proration
|
||||
// preview modal before sending them to Stripe Checkout. First-subscribe
|
||||
// preview modal before submitting the plan change. First-subscribe
|
||||
// (no currentPlanInfo) and same-plan re-buy go straight through.
|
||||
const isPlanChange = (isUpgrade || isDowngrade) && !!currentPlanInfo && !alreadyOwned;
|
||||
if (isPlanChange) {
|
||||
@@ -186,24 +186,24 @@ export default function Plan({
|
||||
if (alreadyOwned && !product?.canBuyAgain) {
|
||||
return true;
|
||||
}
|
||||
return isSubscribing || !product?.stripeId;
|
||||
return isSubscribing || !product?.billingProviderId;
|
||||
}
|
||||
return isSubscribing || !product?.stripeId;
|
||||
return isSubscribing || !product?.billingProviderId;
|
||||
}
|
||||
|
||||
const getCoupon = () => {
|
||||
if (!stripeCoupon) {
|
||||
if (!billingProviderCoupon) {
|
||||
return null;
|
||||
}
|
||||
if (stripeCoupon.applies_to) {
|
||||
if (stripeCoupon.applies_to.products.includes(product?.stripeId ?? "")) {
|
||||
if (!stripeCoupon.currency || stripeCoupon.currency === currency) {
|
||||
return stripeCoupon;
|
||||
if (billingProviderCoupon.applies_to) {
|
||||
if (billingProviderCoupon.applies_to.products.includes(product?.billingProviderId ?? "")) {
|
||||
if (!billingProviderCoupon.currency || billingProviderCoupon.currency === currency) {
|
||||
return billingProviderCoupon;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!stripeCoupon.currency || stripeCoupon.currency === currency) {
|
||||
return stripeCoupon;
|
||||
if (!billingProviderCoupon.currency || billingProviderCoupon.currency === currency) {
|
||||
return billingProviderCoupon;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -384,7 +384,7 @@ export default function Plan({
|
||||
</div>
|
||||
<SubscribeOrBuyButton
|
||||
product={product}
|
||||
isPreview={product?.stripeId === undefined}
|
||||
isPreview={product?.billingProviderId === undefined}
|
||||
model={model}
|
||||
price={getFlatPrice()}
|
||||
badge={badge}
|
||||
@@ -402,7 +402,7 @@ export default function Plan({
|
||||
) : (
|
||||
<SubscribeOrBuyButton
|
||||
product={product}
|
||||
isPreview={product?.stripeId === undefined}
|
||||
isPreview={product?.billingProviderId === undefined}
|
||||
model={model}
|
||||
price={getFlatPrice()}
|
||||
badge={badge}
|
||||
|
||||
@@ -45,7 +45,7 @@ describe("PlanChangePreviewModal i18n", () => {
|
||||
"Wechsel auf ${toPlanTitle}?",
|
||||
"You're upgrading from ${fromPlanTitle} to ${toPlanTitle}.",
|
||||
"Heute (geschätzte anteilige Berechnung)",
|
||||
"Stripe will show the exact prorated amount",
|
||||
"The checkout will show the exact prorated amount",
|
||||
"Continue to checkout",
|
||||
"Weiter zur Bestätigung",
|
||||
]) {
|
||||
|
||||
@@ -56,7 +56,7 @@ export default function PlanChangePreviewModal({
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
// Rough client-side proration estimate. The exact figure is what Stripe
|
||||
// Rough client-side proration estimate. The exact figure is what Mollie
|
||||
// Checkout shows on its hosted page before final confirmation — we just
|
||||
// give the user a ballpark so they aren't surprised.
|
||||
const estimate = useMemo(() => {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { getBillingPeriodParams, getYearlyDiscount } from "~/utils/helpers/PricingHelper";
|
||||
import type { TenantSubscriptionWithDetails } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import type { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
|
||||
import type Stripe from "stripe";
|
||||
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
|
||||
import { useSearchParams } from "react-router";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
@@ -18,14 +18,14 @@ interface Props {
|
||||
tenantSubscription?: TenantSubscriptionWithDetails | null;
|
||||
canSubmit?: boolean;
|
||||
className?: string;
|
||||
stripeCoupon: Stripe.Coupon | null;
|
||||
billingProviderCoupon: BillingProviderCouponDto | null;
|
||||
currenciesAndPeriod: {
|
||||
currencies: { value: string; options: string[] };
|
||||
billingPeriods: { value: SubscriptionBillingPeriod; options: SubscriptionBillingPeriod[] };
|
||||
};
|
||||
onClickFeature?: (name: string) => void;
|
||||
}
|
||||
export default function Plans({ items, tenantSubscription, canSubmit, className, stripeCoupon, currenciesAndPeriod, onClickFeature }: Props) {
|
||||
export default function Plans({ items, tenantSubscription, canSubmit, className, billingProviderCoupon, currenciesAndPeriod, onClickFeature }: Props) {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const formatters = useLocaleFormatters();
|
||||
const [currency, setCurrency] = useState(currenciesAndPeriod.currencies.value);
|
||||
@@ -156,7 +156,7 @@ export default function Plans({ items, tenantSubscription, canSubmit, className,
|
||||
canSubmit={canSubmit}
|
||||
isUpgrade={checkUpgradeDowngrade(plan)?.upgrade}
|
||||
isDowngrade={checkUpgradeDowngrade(plan)?.downgrade}
|
||||
stripeCoupon={stripeCoupon}
|
||||
billingProviderCoupon={billingProviderCoupon}
|
||||
onClickFeature={onClickFeature}
|
||||
currentPlanInfo={currentPlanInfo}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TenantSubscriptionProductPrice } from "@toolctrl/db/prisma-browser";
|
||||
import { TenantSubscriptionProductPrice } from "@hivegrid/db/prisma-browser";
|
||||
import { Fragment, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
|
||||
@@ -188,17 +188,10 @@ export default function TenantProduct({ item, onCancel }: Props) {
|
||||
<div className="font-medium">{t("settings.subscription.debug.id")}</div>
|
||||
<div>{item.id}</div>
|
||||
</div>
|
||||
{item.stripeSubscriptionId && (
|
||||
{item.billingProviderSubscriptionId && (
|
||||
<div className="flex items-baseline space-x-2">
|
||||
<div className="font-medium">{t("settings.subscription.debug.stripeId")}</div>
|
||||
<a
|
||||
target="_blank"
|
||||
className="underline"
|
||||
rel="noreferrer"
|
||||
href={`https://dashboard.stripe.com${rootData.isStripeTest ? "/test" : ""}/subscriptions/${item.stripeSubscriptionId}`}
|
||||
>
|
||||
{item.stripeSubscriptionId}
|
||||
</a>
|
||||
<div className="font-medium">{t("settings.subscription.debug.billingProviderId")}</div>
|
||||
<div>{item.billingProviderSubscriptionId}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Fragment, useMemo, useState } from "react";
|
||||
import type { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import type { TenantSubscriptionWithDetails } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import Plans from "../Plans";
|
||||
import type Stripe from "stripe";
|
||||
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
|
||||
@@ -12,13 +12,13 @@ interface Props {
|
||||
items: SubscriptionProductDto[];
|
||||
tenantSubscription?: TenantSubscriptionWithDetails | null;
|
||||
canSubmit?: boolean;
|
||||
stripeCoupon: Stripe.Coupon | null;
|
||||
billingProviderCoupon: BillingProviderCouponDto | null;
|
||||
currenciesAndPeriod: {
|
||||
currencies: { value: string; options: string[] };
|
||||
billingPeriods: { value: SubscriptionBillingPeriod; options: SubscriptionBillingPeriod[] };
|
||||
};
|
||||
}
|
||||
export default function PlansGrouped({ items, tenantSubscription, canSubmit, stripeCoupon, currenciesAndPeriod }: Props) {
|
||||
export default function PlansGrouped({ items, tenantSubscription, canSubmit, billingProviderCoupon, currenciesAndPeriod }: Props) {
|
||||
const [showFeatureInfoModal, setShowFeatureInfoModal] = useState<boolean>(false);
|
||||
const [showFeatureInfo, setShowFeatureInfo] = useState<string | null>(null);
|
||||
const groups = useMemo(() => {
|
||||
@@ -64,7 +64,7 @@ export default function PlansGrouped({ items, tenantSubscription, canSubmit, str
|
||||
tenantSubscription={tenantSubscription}
|
||||
canSubmit={canSubmit}
|
||||
className="space-y-4"
|
||||
stripeCoupon={stripeCoupon}
|
||||
billingProviderCoupon={billingProviderCoupon}
|
||||
currenciesAndPeriod={currenciesAndPeriod}
|
||||
onClickFeature={(name) => {
|
||||
setShowFeatureInfo(name);
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { Form, useActionData, useSubmit } from "react-router";
|
||||
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
|
||||
import RowProperties from "~/components/entities/rows/RowProperties";
|
||||
import type { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
export default function TenantNew({ tenantSettingsEntity }: { tenantSettingsEntity: EntityWithDetails | null }) {
|
||||
const actionData = useActionData<{ tenantId?: string; error?: string; success?: string }>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const rootData = useRootData();
|
||||
|
||||
const inputName = useRef<RefInputText>(null);
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
const successModal = useRef<RefSuccessModal>(null);
|
||||
|
||||
const [name, setName] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
inputName.current?.input.current?.focus();
|
||||
inputName.current?.input.current?.select();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
errorModal.current?.show(actionData.error);
|
||||
} else if (actionData?.success) {
|
||||
successModal.current?.show(actionData.success);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [actionData]);
|
||||
|
||||
function createdTenant() {
|
||||
if (actionData?.tenantId) {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-tenant");
|
||||
form.set("tenantId", actionData.tenantId);
|
||||
form.set("redirectTo", location.pathname + location.search);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: "/",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-1 flex-col justify-between">
|
||||
<Form method="post" className="" data-ui-id="ui.account.create.form">
|
||||
<input type="hidden" name="action" value="create" hidden readOnly />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} hidden readOnly />
|
||||
<div className="space-y-3 pb-5 pt-2">
|
||||
<div>
|
||||
{/* <label className="block text-xs font-medium text-muted-foreground">
|
||||
{t("account.register.organization")} <span className="ml-1 text-red-500">*</span>
|
||||
</label> */}
|
||||
|
||||
<div className="mt-1 -space-y-px rounded-md shadow-2xs">
|
||||
<div>
|
||||
{/* <label htmlFor="tax-id" className="sr-only">
|
||||
{t("shared.name")}
|
||||
</label> */}
|
||||
<InputText
|
||||
title={t("shared.name")}
|
||||
ref={inputName}
|
||||
type="text"
|
||||
name="name"
|
||||
id="name"
|
||||
dataUiId="ui.account.create.name"
|
||||
placeholder={t("shared.name")}
|
||||
required
|
||||
value={name}
|
||||
setValue={setName}
|
||||
// className="focus:border-theme-500 focus:ring-ring relative block w-full appearance-none rounded-md border border-border px-3 py-2 text-foreground placeholder-gray-500 focus:z-10 focus:outline-hidden sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{tenantSettingsEntity && (
|
||||
<div className="col-span-6 sm:col-span-6">
|
||||
<RowProperties entity={tenantSettingsEntity} item={null} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="pb-6 text-right">
|
||||
<div className="right-0 text-sm leading-5">
|
||||
<span className="ml-2 inline-flex rounded-sm shadow-2xs">
|
||||
<LoadingButton type="submit" dataUiId="ui.account.create.submit">{t("shared.create")}</LoadingButton>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
<SuccessModal ref={successModal} onClosed={createdTenant} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,62 +8,25 @@ import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
|
||||
import { RowHeaderActionDto } from "~/application/dtos/data/RowHeaderActionDto";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import type Stripe from "stripe";
|
||||
import { Link } from "react-router";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { createLocaleFormatters, type LocaleFormatters } from "~/locale/format";
|
||||
import { createLocaleFormatters } from "~/locale/format";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
interface Props {
|
||||
items: TenantWithUsage[];
|
||||
pagination: PaginationDto;
|
||||
actions?: RowHeaderActionDto<TenantWithUsage>[];
|
||||
tenantInvoices?: Stripe.Invoice[];
|
||||
isStripeTest?: boolean;
|
||||
}
|
||||
|
||||
type TenantInvoiceSummary = {
|
||||
lastInvoice?: Stripe.Invoice;
|
||||
paidCount: number;
|
||||
totalsPaidByCurrency: Map<string, number>;
|
||||
};
|
||||
|
||||
export default function TenantsTable({ items, pagination, actions = [], tenantInvoices, isStripeTest }: Props) {
|
||||
export default function TenantsTable({ items, pagination, actions = [] }: Props) {
|
||||
const { i18n, t } = useTranslation();
|
||||
const formatters = useMemo(() => createLocaleFormatters(i18n.language), [i18n.language]);
|
||||
const rootData = useRootData();
|
||||
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<TenantWithUsage>[]>([]);
|
||||
const invoiceSummaryByCustomer = useMemo(() => {
|
||||
if (!tenantInvoices) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const summaries = new Map<string, TenantInvoiceSummary>();
|
||||
for (const invoice of tenantInvoices) {
|
||||
const customerId = invoice.customer?.toString();
|
||||
if (!customerId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const summary = summaries.get(customerId) ?? { paidCount: 0, totalsPaidByCurrency: new Map<string, number>() };
|
||||
const currency = invoice.currency.toUpperCase();
|
||||
const amountPaid = Number(invoice.amount_paid / 100);
|
||||
if (amountPaid > 0) {
|
||||
summary.totalsPaidByCurrency.set(currency, (summary.totalsPaidByCurrency.get(currency) ?? 0) + amountPaid);
|
||||
}
|
||||
if (invoice.status === "paid") {
|
||||
summary.paidCount += 1;
|
||||
}
|
||||
if (!summary.lastInvoice || invoice.created > summary.lastInvoice.created) {
|
||||
summary.lastInvoice = invoice;
|
||||
}
|
||||
summaries.set(customerId, summary);
|
||||
}
|
||||
return summaries;
|
||||
}, [tenantInvoices]);
|
||||
|
||||
useEffect(() => {
|
||||
const headers: RowHeaderDisplayDto<TenantWithUsage>[] = [];
|
||||
@@ -136,63 +99,6 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
|
||||
</span>
|
||||
),
|
||||
});
|
||||
if (tenantInvoices !== undefined) {
|
||||
function getInvoiceSummary(tenant: TenantWithUsage): TenantInvoiceSummary | undefined {
|
||||
const customerId = tenant.subscription?.stripeCustomerId;
|
||||
return customerId ? invoiceSummaryByCustomer?.get(customerId) : undefined;
|
||||
}
|
||||
headers.push({
|
||||
name: "lastInvoice",
|
||||
title: t("settings.tenant.billing.lastInvoice"),
|
||||
value: (i) =>
|
||||
(() => {
|
||||
const summary = getInvoiceSummary(i);
|
||||
return (
|
||||
<a
|
||||
className="flex flex-col space-y-1 hover:underline"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
href={`https://dashboard.stripe.com${isStripeTest ? "/test" : ""}/customers/${i.subscription?.stripeCustomerId ?? ""}`}
|
||||
>
|
||||
<div className="flex flex-col space-y-1">
|
||||
{!summary?.lastInvoice ? (
|
||||
<span className="text-muted-foreground italic">{t("shared.none")}</span>
|
||||
) : (
|
||||
<TenantInvoice item={summary.lastInvoice} formatters={formatters} />
|
||||
)}
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
})(),
|
||||
});
|
||||
headers.push({
|
||||
name: "totalInvoicesPaid",
|
||||
title: t("settings.tenant.billing.totalPaid"),
|
||||
value: (i) =>
|
||||
(() => {
|
||||
const summary = getInvoiceSummary(i);
|
||||
return (
|
||||
<a
|
||||
className="flex flex-col space-y-1 hover:underline"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
href={`https://dashboard.stripe.com${isStripeTest ? "/test" : ""}/customers/${i.subscription?.stripeCustomerId ?? ""}`}
|
||||
>
|
||||
{!summary || summary.totalsPaidByCurrency.size === 0 ? (
|
||||
<span className="text-muted-foreground italic">{t("shared.none")}</span>
|
||||
) : (
|
||||
<div className="flex flex-col">
|
||||
{[...summary.totalsPaidByCurrency.entries()].map(([currency, totalPaid]) => (
|
||||
<span key={currency}>{formatters.currency(totalPaid, currency)}</span>
|
||||
))}
|
||||
<span className="text-muted-foreground text-xs">({formatters.number(summary.paidCount)})</span>
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
);
|
||||
})(),
|
||||
});
|
||||
}
|
||||
headers.push({
|
||||
name: "types",
|
||||
title: t("shared.types"),
|
||||
@@ -210,11 +116,6 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
|
||||
value: (i) => i.users.map((f) => f.user.email).join(", "),
|
||||
href: (i) => adminPath(`accounts/users?tenantId=${i.id}`, { mode: "host-aware" }),
|
||||
});
|
||||
headers.push({
|
||||
name: "rows",
|
||||
title: t("models.row.plural"),
|
||||
value: (item) => <Link to={adminPath("entities/rows?tenantId=" + item.id, { mode: "host-aware" })}>{formatters.number(item._count.rows ?? 0)}</Link>,
|
||||
});
|
||||
headers.push({
|
||||
name: "events",
|
||||
title: t("models.event.plural"),
|
||||
@@ -233,7 +134,7 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
|
||||
),
|
||||
});
|
||||
setHeaders(headers);
|
||||
}, [formatters, invoiceSummaryByCustomer, isStripeTest, rootData.routing, t, tenantInvoices]);
|
||||
}, [formatters, rootData.routing, t]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
@@ -252,20 +153,3 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TenantInvoice({ item, formatters }: { item: Stripe.Invoice; formatters: LocaleFormatters }) {
|
||||
const { t } = useTranslation();
|
||||
const createdAt = new Date(item.created * 1000);
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div title={formatters.dateTime(createdAt, { timeStyle: "medium" })} className="flex items-center space-x-1">
|
||||
<div className="flex items-baseline space-x-1">
|
||||
<div>{formatters.currency(item.total / 100, item.currency.toUpperCase())}</div>
|
||||
<div className="text-muted-foreground text-xs uppercase">{item.currency}</div>
|
||||
</div>
|
||||
<SimpleBadge title={t("app.subscription.invoices.status." + item.status)} color={item.status === "paid" ? Colors.GREEN : Colors.YELLOW} />
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">{item.created ? formatters.relativeDate(createdAt) : ""}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,9 +6,7 @@ import UploadDocuments from "~/components/ui/uploaders/UploadDocument";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import type { TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import RowProperties from "~/components/entities/rows/RowProperties";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import type { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
@@ -22,14 +20,13 @@ type TenantTypeOption = {
|
||||
interface Props {
|
||||
tenant: TenantWithDetails;
|
||||
disabled: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
tenantTypes?: TenantTypeOption[];
|
||||
options?: {
|
||||
canChangeType: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export default function UpdateTenantDetailsForm({ tenant, disabled, tenantSettingsEntity, tenantTypes, options }: Props) {
|
||||
export default function UpdateTenantDetailsForm({ tenant, disabled, tenantTypes, options }: Props) {
|
||||
const { i18n, t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
|
||||
@@ -123,11 +120,6 @@ export default function UpdateTenantDetailsForm({ tenant, disabled, tenantSettin
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{tenantSettingsEntity && (
|
||||
<div className="col-span-6 sm:col-span-6">
|
||||
<RowProperties entity={tenantSettingsEntity} item={tenant.tenantSettingsRow?.row ?? null} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useFetcher } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { TenantWithProfile } from "~/utils/db/tenants.db.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { defaultAnrede, isAnrede, type Anrede } from "@hivegrid/i18n";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import InputChoicebox from "~/components/ui/input/InputChoicebox";
|
||||
|
||||
type Props = {
|
||||
tenant: TenantWithProfile;
|
||||
};
|
||||
|
||||
/**
|
||||
* Schlichter du/Sie-Umschalter (Anrede). Persistiert `Tenant.anrede` und setzt
|
||||
* den `_anrede`-Cookie (Server-Action `update-anrede`). Default "du" verhaelt
|
||||
* sich byte-identisch zum Status quo; "sie" schaltet die App auf die
|
||||
* "<locale>-formal"-Sprachvariante um (Fallback auf Basis-Locale).
|
||||
*/
|
||||
export default function UpdateTenantFormAnrede({ tenant }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { csrf } = useRootData();
|
||||
const fetcher = useFetcher<{ success?: string; error?: string }>();
|
||||
|
||||
const initial: Anrede = isAnrede(tenant?.anrede ?? undefined) ? (tenant.anrede as Anrede) : defaultAnrede;
|
||||
const [anrede, setAnrede] = useState<Anrede>(initial);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.success) {
|
||||
toast.success(fetcher.data.success);
|
||||
} else if (fetcher.data?.error) {
|
||||
toast.error(fetcher.data.error);
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
const onChange = (value: string) => {
|
||||
if (!isAnrede(value) || value === anrede) {
|
||||
return;
|
||||
}
|
||||
setAnrede(value);
|
||||
const form = new FormData();
|
||||
form.set("action", "update-anrede");
|
||||
form.set("anrede", value);
|
||||
if (csrf) {
|
||||
form.set("csrf", csrf);
|
||||
}
|
||||
fetcher.submit(form, { method: "post", preventScrollReset: true });
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingSection title={t("settings:tenant.anrede.title")} description={t("settings:tenant.anrede.description")}>
|
||||
<InputChoicebox
|
||||
name="anrede"
|
||||
value={anrede}
|
||||
onChange={onChange}
|
||||
disabled={fetcher.state !== "idle"}
|
||||
options={[
|
||||
{ value: "du", name: t("settings:tenant.anrede.du") },
|
||||
{ value: "sie", name: t("settings:tenant.anrede.sie") },
|
||||
]}
|
||||
/>
|
||||
</SettingSection>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApiKey } from "@toolctrl/db/prisma-browser";
|
||||
import { ApiKey } from "@hivegrid/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -5,7 +5,7 @@ import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { useEscapeKeypress } from "~/utils/shared/KeypressUtils";
|
||||
import clsx from "~/utils/shared/ClassesUtils";
|
||||
import EmptyState from "~/components/ui/emptyState/EmptyState";
|
||||
import { User } from "@toolctrl/db/prisma-browser";
|
||||
import { User } from "@hivegrid/db/prisma-browser";
|
||||
import { XIcon, PlusIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
export interface RefSelectUsers {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AdminUser, Role, UserRole } from "@toolctrl/db/prisma-browser";
|
||||
import { AdminUser, Role, UserRole } from "@hivegrid/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import AtSymbolIcon from "~/components/ui/icons/AtSymbolIcon";
|
||||
import UserAvatarBadge from "./UserAvatarBadge";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Log, Role, User } from "@toolctrl/db/prisma-browser";
|
||||
import { Log, Role, User } from "@hivegrid/db/prisma-browser";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useSubmit } from "react-router";
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation detail.
|
||||
// Pure component: it receives the server-built KontaktDetailVM data + the
|
||||
// Activity-Stream VM + option lists and renders the inline-edit forms (DoD 3).
|
||||
// It NEVER calls useLoaderData/useFetcher (the route injects the data) and holds
|
||||
// no server imports; every form posts back to the current route's action.
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ActivityStreamVM, KontaktDetailData } from "@hivegrid/view-models";
|
||||
|
||||
export type KontaktDetailViewProps = {
|
||||
data: KontaktDetailData;
|
||||
activity: ActivityStreamVM;
|
||||
allTags: { id: string; name: string; farbe: string }[];
|
||||
customFieldDefs: { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string }[];
|
||||
ownerOptions: { id: string; label: string }[];
|
||||
backHref: string;
|
||||
listLabelKey: string;
|
||||
errorKey?: string | null;
|
||||
};
|
||||
|
||||
const crmFieldLabelClass = "block text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary";
|
||||
const crmFieldControlClass =
|
||||
"mt-1 h-9 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
|
||||
const crmTextareaClass =
|
||||
"mt-1 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 py-2 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
|
||||
|
||||
export default function KontaktDetailView(props: KontaktDetailViewProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { data } = props;
|
||||
const isOrg = data.kontaktTyp === "organisation";
|
||||
const dateTime = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeStyle: "short" });
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.detail">
|
||||
<nav className="text-muted-foreground mb-4 text-sm" aria-label={t("crm.detail.breadcrumb")} data-ui-id="ui.crm.detail.breadcrumb">
|
||||
<a href={props.backHref} className="hover:text-foreground" data-ui-id="ui.crm.detail.back">
|
||||
{t(props.listLabelKey)}
|
||||
</a>
|
||||
<span className="px-2">{"/"}</span>
|
||||
<span className="text-foreground">{data.displayName}</span>
|
||||
</nav>
|
||||
|
||||
<header className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-foreground text-xl font-semibold">{data.displayName}</h1>
|
||||
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.typLabelKey)}</span>
|
||||
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.statusLabelKey)}</span>
|
||||
{data.isArchived ? <span className="text-destructive text-xs">{t("crm.detail.archivedBadge")}</span> : null}
|
||||
</header>
|
||||
|
||||
{props.errorKey ? (
|
||||
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.detail.error">
|
||||
{t(props.errorKey)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{/* --- Basics (inline edit) --- */}
|
||||
<section className="mt-6" data-ui-id="ui.crm.detail.basics">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.basics")}</h2>
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="mt-2 grid gap-2 sm:grid-cols-2">
|
||||
<input type="hidden" name="intent" value="updateBasics" />
|
||||
{isOrg ? (
|
||||
<>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.orgName")}</span>
|
||||
<input name="orgName" defaultValue={data.orgName ?? ""} className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.orgMerkmal")}</span>
|
||||
<select name="orgMerkmal" defaultValue={data.orgMerkmal ?? ""} className={crmFieldControlClass}>
|
||||
<option value="">{t("crm.fields.none")}</option>
|
||||
{(["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const).map((merkmal) => (
|
||||
<option key={merkmal} value={merkmal}>
|
||||
{t(`crm.orgMerkmal.${merkmal}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.vorname")}</span>
|
||||
<input name="vorname" defaultValue={data.vorname ?? ""} className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.nachname")}</span>
|
||||
<input name="nachname" defaultValue={data.nachname ?? ""} className={crmFieldControlClass} />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.status")}</span>
|
||||
<select name="kontaktStatus" defaultValue={data.kontaktStatus} className={crmFieldControlClass}>
|
||||
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
|
||||
<option key={status} value={status}>
|
||||
{t(`crm.kontaktStatus.${status}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="sm:col-span-2">
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.basics.save">
|
||||
{t("crm.actions.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<dl className="mt-2 grid grid-cols-[8rem_1fr] gap-y-1 text-sm">
|
||||
<dt className="text-muted-foreground">{t("crm.fields.status")}</dt>
|
||||
<dd>{t(data.statusLabelKey)}</dd>
|
||||
{data.orgMerkmalLabelKey ? (
|
||||
<>
|
||||
<dt className="text-muted-foreground">{t("crm.fields.orgMerkmal")}</dt>
|
||||
<dd>{t(data.orgMerkmalLabelKey)}</dd>
|
||||
</>
|
||||
) : null}
|
||||
</dl>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* --- Emails --- */}
|
||||
<section className="mt-6" data-ui-id="ui.crm.detail.emails">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.emails")}</h2>
|
||||
<ul className="mt-2 text-sm">
|
||||
{data.emails.map((email) => (
|
||||
<li key={email.id} className="flex items-center gap-2 py-0.5" data-row-id={email.id}>
|
||||
<span>{email.email}</span>
|
||||
{email.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
|
||||
{data.canWrite && !email.primaer ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="setPrimaryEmail" />
|
||||
<input type="hidden" name="emailId" value={email.id} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("crm.actions.makePrimary")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="removeEmail" />
|
||||
<input type="hidden" name="emailId" value={email.id} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("crm.actions.remove")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
|
||||
<input type="hidden" name="intent" value="addEmail" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.email")}</span>
|
||||
<input name="email" type="email" required className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-muted-foreground flex items-center gap-1 text-xs">
|
||||
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.add")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{/* --- Phones --- */}
|
||||
<section className="mt-6" data-ui-id="ui.crm.detail.telefone">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.telefone")}</h2>
|
||||
<ul className="mt-2 text-sm">
|
||||
{data.telefone.map((tel) => (
|
||||
<li key={tel.id} className="flex items-center gap-2 py-0.5" data-row-id={tel.id}>
|
||||
<span>{tel.telefon}</span>
|
||||
{tel.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
|
||||
{data.canWrite && !tel.primaer ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="setPrimaryTelefon" />
|
||||
<input type="hidden" name="telefonId" value={tel.id} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("crm.actions.makePrimary")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="removeTelefon" />
|
||||
<input type="hidden" name="telefonId" value={tel.id} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("crm.actions.remove")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
|
||||
<input type="hidden" name="intent" value="addTelefon" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.telefon")}</span>
|
||||
<input name="telefon" required className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-muted-foreground flex items-center gap-1 text-xs">
|
||||
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.add")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{/* --- Address (read-only) --- */}
|
||||
{data.adresse ? (
|
||||
<section className="mt-6" data-ui-id="ui.crm.detail.adresse">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.adresse")}</h2>
|
||||
<p className="mt-1 text-sm">
|
||||
{[data.adresse.strasse, data.adresse.hausnummer].filter(Boolean).join(" ")}
|
||||
{data.adresse.plz || data.adresse.ort ? `, ${[data.adresse.plz, data.adresse.ort].filter(Boolean).join(" ")}` : ""}
|
||||
{`, ${data.adresse.land}`}
|
||||
</p>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{/* --- Relations --- */}
|
||||
<section className="mt-6" data-ui-id="ui.crm.detail.relations">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.relations")}</h2>
|
||||
<ul className="mt-2 text-sm">
|
||||
{data.relationen.map((rel) => (
|
||||
<li key={rel.id} className="flex items-center gap-2 py-0.5" data-row-id={rel.id}>
|
||||
<span>{rel.otherKontaktId}</span>
|
||||
<span className="text-muted-foreground text-xs">{t(rel.rolleLabelKey)}</span>
|
||||
{rel.kontext ? <span className="text-muted-foreground text-xs">{rel.kontext}</span> : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="removeRelation" />
|
||||
<input type="hidden" name="relationId" value={rel.id} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("crm.actions.remove")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
|
||||
<input type="hidden" name="intent" value="addRelation" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.relationTarget")}</span>
|
||||
<input name="zuKontaktId" required className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.relationRole")}</span>
|
||||
<select name="rolle" className={crmFieldControlClass}>
|
||||
{(["hauptkontakt", "sekundaerkontakt", "mitarbeiter", "sonstige"] as const).map((rolle) => (
|
||||
<option key={rolle} value={rolle}>
|
||||
{t(`crm.kontaktArt.${rolle}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.relationContext")}</span>
|
||||
<input name="kontext" className={crmFieldControlClass} />
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.add")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{/* --- Tags --- */}
|
||||
<section className="mt-6" data-ui-id="ui.crm.detail.tags">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.tags")}</h2>
|
||||
<ul className="mt-2 flex flex-wrap gap-2 text-sm">
|
||||
{data.tags.map((tag) => (
|
||||
<li key={tag.id} className="border-border flex items-center gap-1 rounded border px-2 py-0.5" data-row-id={tag.id}>
|
||||
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
|
||||
<span>{tag.name}</span>
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="removeTag" />
|
||||
<input type="hidden" name="tagId" value={tag.id} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("crm.actions.remove")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{data.canWrite && props.allTags.length > 0 ? (
|
||||
<form method="post" className="mt-2 flex items-end gap-2">
|
||||
<input type="hidden" name="intent" value="addTag" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.tag")}</span>
|
||||
<select name="tagId" className={crmFieldControlClass}>
|
||||
{props.allTags.map((tag) => (
|
||||
<option key={tag.id} value={tag.id}>
|
||||
{tag.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.add")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{/* --- Custom fields --- */}
|
||||
<section className="mt-6" data-ui-id="ui.crm.detail.customFields">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.customFields")}</h2>
|
||||
<dl className="mt-2 grid grid-cols-[10rem_1fr] gap-y-1 text-sm">
|
||||
{data.customFields.map((cf) => (
|
||||
<div key={cf.definitionId} className="contents" data-row-id={cf.definitionId}>
|
||||
<dt className="text-muted-foreground">{cf.label}</dt>
|
||||
<dd>{cf.wert == null ? "" : String(cf.wert)}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{data.canWrite && props.customFieldDefs.length > 0 ? (
|
||||
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
|
||||
<input type="hidden" name="intent" value="setCustomField" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.customField")}</span>
|
||||
<select name="definitionId" className={crmFieldControlClass}>
|
||||
{props.customFieldDefs.map((def) => (
|
||||
<option key={def.id} value={def.id}>
|
||||
{def.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.value")}</span>
|
||||
<input name="wert" className={crmFieldControlClass} />
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.save")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{/* --- Quick actions --- */}
|
||||
{data.canWrite || data.canDelete ? (
|
||||
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.actions">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.actions")}</h2>
|
||||
<div className="mt-2 flex flex-wrap items-end gap-4">
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="flex items-end gap-2">
|
||||
<input type="hidden" name="intent" value="reassign" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.owner")}</span>
|
||||
<select name="zustaendigerUserId" defaultValue={data.zustaendigerUserId ?? ""} className={crmFieldControlClass}>
|
||||
{props.ownerOptions.map((option) => (
|
||||
<option key={option.id} value={option.id}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.reassign")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="flex-1">
|
||||
<input type="hidden" name="intent" value="addNote" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.note")}</span>
|
||||
<textarea name="note" required rows={2} className={crmTextareaClass} />
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 mt-1 text-sm font-medium" data-ui-id="ui.crm.detail.addNote">
|
||||
{t("crm.actions.addNote")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-3">
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value={data.isArchived ? "reactivate" : "archive"} />
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.archive">
|
||||
{t(data.isArchived ? "crm.actions.reactivate" : "crm.actions.archive")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canDelete ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="delete" />
|
||||
<button type="submit" className="text-destructive text-sm font-medium" data-ui-id="ui.crm.detail.delete">
|
||||
{t("crm.actions.delete")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{/* --- Activity stream --- */}
|
||||
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.activity">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.activity")}</h2>
|
||||
{props.activity.status === "ready" && props.activity.data ? (
|
||||
<ul className="mt-2 space-y-2 text-sm">
|
||||
{props.activity.data.entries.map((entry) => (
|
||||
<li key={entry.id} className="border-border border-l-2 pl-3" data-row-id={entry.id}>
|
||||
<p>{entry.summaryText}</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t(entry.activityLabelKey)}
|
||||
{entry.actorLabel ? ` · ${entry.actorLabel}` : ""} · <time dateTime={entry.createdAtIso}>{dateTime.format(new Date(entry.createdAtIso))}</time>
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-muted-foreground mt-2 text-sm" data-ui-id="ui.crm.detail.activity.empty">
|
||||
{t("crm.detail.activityEmpty")}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation browser.
|
||||
// Pure component: it renders the server-built KontaktListVM (filter / sort /
|
||||
// paginate / bulk / CSV, DoD 2). The filter bar is a GET form (state lives in the
|
||||
// URL); bulk actions are a POST form whose checkboxes carry the selected ids.
|
||||
// No useLoaderData/useFetcher, no server imports.
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { KontaktListVM } from "@hivegrid/view-models";
|
||||
import { kontaktListQueryToParams, type KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
|
||||
|
||||
export type KontaktListViewProps = {
|
||||
moduleActive: boolean;
|
||||
variant: "contacts" | "companies";
|
||||
vm: KontaktListVM;
|
||||
tagOptions: { id: string; name: string; farbe: string }[];
|
||||
ownerOptions: { id: string; label: string }[];
|
||||
query: KontaktListQuery;
|
||||
baseHref: string;
|
||||
newHref: string;
|
||||
exportHref: string;
|
||||
errorKey?: string | null;
|
||||
};
|
||||
|
||||
function pageHref(baseHref: string, query: KontaktListQuery, page: number): string {
|
||||
const params = kontaktListQueryToParams({ ...query, page });
|
||||
const qs = params.toString();
|
||||
return qs ? `${baseHref}?${qs}` : baseHref;
|
||||
}
|
||||
|
||||
export default function KontaktListView(props: KontaktListViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const titleKey = props.variant === "companies" ? "crm.companies.title" : "crm.contacts.title";
|
||||
const emptyHeadlineKey = props.variant === "companies" ? "crm.empty.companies.headline" : "crm.empty.contacts.headline";
|
||||
const emptyBodyKey = props.variant === "companies" ? "crm.empty.companies.body" : "crm.empty.contacts.body";
|
||||
|
||||
if (!props.moduleActive) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.list">
|
||||
<div className="mt-10 text-center" data-ui-id="ui.crm.list.locked">
|
||||
<p className="text-foreground font-medium">{t("crm.locked.headline")}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("crm.locked.body")}</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const data = props.vm.status === "ready" ? props.vm.data : null;
|
||||
const { filter, sort } = props.query;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-6xl px-4 py-10" data-ui-id="ui.crm.list">
|
||||
<header className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t(titleKey)}</h1>
|
||||
<div className="flex gap-3 text-sm">
|
||||
<a href={props.exportHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.export">
|
||||
{t("crm.actions.exportCsv")}
|
||||
</a>
|
||||
<a href={props.newHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.new">
|
||||
{t("crm.actions.newContact")}
|
||||
</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* --- Filter bar (GET, URL-driven, server-side) --- */}
|
||||
<form method="get" action={props.baseHref} className="mt-6 flex flex-wrap items-end gap-2" data-ui-id="ui.crm.list.filter">
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.search")}</span>
|
||||
<input name="q" defaultValue={filter.search ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
{props.variant === "contacts" ? (
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.type")}</span>
|
||||
<select name="typ" defaultValue={filter.kontaktTyp ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
<option value="">{t("crm.filter.any")}</option>
|
||||
<option value="privatperson">{t("crm.kontaktTyp.privatperson")}</option>
|
||||
<option value="organisation">{t("crm.kontaktTyp.organisation")}</option>
|
||||
</select>
|
||||
</label>
|
||||
) : null}
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.status")}</span>
|
||||
<select name="status" defaultValue={filter.kontaktStatus ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
<option value="">{t("crm.filter.any")}</option>
|
||||
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
|
||||
<option key={status} value={status}>
|
||||
{t(`crm.kontaktStatus.${status}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.owner")}</span>
|
||||
<select name="owner" defaultValue={filter.zustaendigerUserId ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
<option value="">{t("crm.filter.any")}</option>
|
||||
{props.ownerOptions.map((option) => (
|
||||
<option key={option.id} value={option.id}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.tags")}</span>
|
||||
<select name="tags" multiple defaultValue={filter.tagIds ?? []} className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
{props.tagOptions.map((tag) => (
|
||||
<option key={tag.id} value={tag.id}>
|
||||
{tag.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.tagMatch")}</span>
|
||||
<select name="tagMatch" defaultValue={filter.tagMatch} className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
<option value="or">{t("crm.filter.tagMatchOr")}</option>
|
||||
<option value="and">{t("crm.filter.tagMatchAnd")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.sort")}</span>
|
||||
<select name="sort" defaultValue={sort.field} className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
<option value="createdAt">{t("crm.filter.sortCreated")}</option>
|
||||
<option value="name">{t("crm.filter.sortName")}</option>
|
||||
<option value="kontaktStatus">{t("crm.filter.sortStatus")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.filter.direction")}</span>
|
||||
<select name="dir" defaultValue={sort.dir} className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
<option value="desc">{t("crm.filter.dirDesc")}</option>
|
||||
<option value="asc">{t("crm.filter.dirAsc")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-muted-foreground flex items-center gap-1 text-xs">
|
||||
<input type="checkbox" name="archived" value="1" defaultChecked={filter.includeArchived} /> {t("crm.filter.includeArchived")}
|
||||
</label>
|
||||
<label className="text-muted-foreground flex items-center gap-1 text-xs">
|
||||
<input type="checkbox" name="demo" value="show" defaultChecked={filter.includeDemoData} /> {t("onboarding.demoData.showInLists")}
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.applyFilter")}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{props.errorKey ? (
|
||||
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.list.error">
|
||||
{t(props.errorKey)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!data ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.crm.list.empty">
|
||||
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
|
||||
<a href={props.newHref} className="text-theme-600 mt-2 inline-block text-sm font-medium">
|
||||
{t("crm.actions.newContact")}
|
||||
</a>
|
||||
</div>
|
||||
) : (
|
||||
<form method="post" className="mt-6" data-ui-id="ui.crm.list.bulkForm">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm" data-ui-id="ui.crm.list.table">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b">
|
||||
<th className="py-2" />
|
||||
<th className="py-2">{t("crm.column.name")}</th>
|
||||
<th className="py-2">{t("crm.column.type")}</th>
|
||||
<th className="py-2">{t("crm.column.status")}</th>
|
||||
<th className="py-2">{t("crm.column.email")}</th>
|
||||
<th className="py-2">{t("crm.column.telefon")}</th>
|
||||
<th className="py-2">{t("crm.column.owner")}</th>
|
||||
<th className="py-2">{t("crm.column.tags")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.rows.map((row) => (
|
||||
<tr key={row.id} className="border-b" data-row-id={row.id}>
|
||||
<td className="py-2">
|
||||
<input type="checkbox" name="kontaktId" value={row.id} aria-label={t("crm.actions.select")} />
|
||||
</td>
|
||||
<td className="py-2">
|
||||
<a href={row.detailHref} className="text-theme-600">
|
||||
{row.displayName}
|
||||
</a>
|
||||
{row.isArchived ? <span className="text-muted-foreground ml-1 text-xs">{t("crm.detail.archivedBadge")}</span> : null}
|
||||
</td>
|
||||
<td className="py-2">{t(row.typLabelKey)}</td>
|
||||
<td className="py-2">{t(row.statusLabelKey)}</td>
|
||||
<td className="py-2">{row.primaerEmail ?? ""}</td>
|
||||
<td className="py-2">{row.primaerTelefon ?? ""}</td>
|
||||
<td className="py-2">{row.zustaendigerLabel ?? ""}</td>
|
||||
<td className="py-2">
|
||||
{row.tagChips.map((tag) => (
|
||||
<span key={tag.id} className="mr-1 inline-flex items-center gap-1">
|
||||
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
|
||||
{tag.name}
|
||||
</span>
|
||||
))}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* --- Bulk actions (operate on the checked rows) --- */}
|
||||
<div className="mt-4 flex flex-wrap items-end gap-3" data-ui-id="ui.crm.list.bulk">
|
||||
<button type="submit" name="intent" value="bulkArchive" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.bulkArchive")}
|
||||
</button>
|
||||
<span className="flex items-end gap-1">
|
||||
<select name="zustaendigerUserId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.owner")}>
|
||||
{props.ownerOptions.map((option) => (
|
||||
<option key={option.id} value={option.id}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="submit" name="intent" value="bulkReassign" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.bulkReassign")}
|
||||
</button>
|
||||
</span>
|
||||
<span className="flex items-end gap-1">
|
||||
<select name="tagId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.tag")}>
|
||||
{props.tagOptions.map((tag) => (
|
||||
<option key={tag.id} value={tag.id}>
|
||||
{tag.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="submit" name="intent" value="bulkTag" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.bulkTag")}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<nav className="mt-4 flex items-center gap-4 text-sm" data-ui-id="ui.crm.list.pagination">
|
||||
{data.pagination.hasPrev ? (
|
||||
<a href={pageHref(props.baseHref, props.query, data.pagination.page - 1)} className="text-theme-600">
|
||||
{t("crm.pagination.prev")}
|
||||
</a>
|
||||
) : null}
|
||||
<span className="text-muted-foreground">
|
||||
{t("crm.pagination.page", { page: data.pagination.page, pageCount: Math.max(data.pagination.pageCount, 1), total: data.pagination.total })}
|
||||
</span>
|
||||
{data.pagination.hasNext ? (
|
||||
<a href={pageHref(props.baseHref, props.query, data.pagination.page + 1)} className="text-theme-600">
|
||||
{t("crm.pagination.next")}
|
||||
</a>
|
||||
) : null}
|
||||
</nav>
|
||||
</form>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { useParams } from "react-router";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { EntitySummaryDto } from "~/utils/services/appDashboardService";
|
||||
import RowsList from "../entities/rows/RowsList";
|
||||
import EntityIcon from "../layouts/icons/EntityIcon";
|
||||
import ButtonSecondary from "../ui/buttons/ButtonSecondary";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
|
||||
export default function EntitySummaries({ items, routes }: { items: EntitySummaryDto[]; routes: EntitiesApi.Routes }) {
|
||||
return (
|
||||
<Fragment>
|
||||
{items
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map(({ rowsData }, idx) => {
|
||||
return <LatestRows key={idx} rowsData={rowsData} routes={routes} />;
|
||||
})}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function LatestRows({ rowsData, routes }: { rowsData: RowsApi.GetRowsData; routes: EntitiesApi.Routes }) {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
|
||||
const [listRoute, setListRoute] = useState<string>();
|
||||
useEffect(() => {
|
||||
const group = appOrAdminData.entityGroups.find((f) => f.entities.some((g) => g.entityId === rowsData.entity.id));
|
||||
if (group) {
|
||||
setListRoute(UrlUtils.currentTenantUrl(params, `g/${group.slug}/${rowsData.entity.slug}`));
|
||||
} else {
|
||||
const entity = appOrAdminData.entities.find((f) => f.id === rowsData.entity.id);
|
||||
if (entity) {
|
||||
setListRoute(UrlUtils.currentTenantUrl(params, entity.slug));
|
||||
}
|
||||
}
|
||||
}, [appOrAdminData.entityGroups, appOrAdminData.entities, rowsData.entity.id, rowsData.entity.slug, params]);
|
||||
return (
|
||||
<div className="space-y-3 overflow-hidden p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<EntityIcon className="h-5 w-5" icon={rowsData.entity.icon} />
|
||||
<h3 className="text-foreground grow font-medium leading-4">{t("models.dashboard.latestEntity", { entity: t(rowsData.entity.titlePlural) })}</h3>
|
||||
</div>
|
||||
{listRoute && <ButtonSecondary to={listRoute}>{t("shared.viewAll")}</ButtonSecondary>}
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-2 overflow-x-scroll">
|
||||
<RowsList entity={rowsData.entity} view={"card"} items={rowsData.items} routes={routes} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import { EntityWithCount } from "~/utils/db/entities/entities.db.server";
|
||||
import SimpleBadge from "../ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import TableSimple from "../ui/tables/TableSimple";
|
||||
import RelationshipHelper from "~/utils/helpers/RelationshipHelper";
|
||||
import OrderListButtons from "../ui/sort/OrderListButtons";
|
||||
import { useEffect, useState } from "react";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { translateEntityTitlePlural, translatePropertyTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
interface Props {
|
||||
items: EntityWithCount[];
|
||||
selected?: EntityWithCount[];
|
||||
onSelected?: (items: EntityWithCount[]) => void;
|
||||
}
|
||||
|
||||
export default function EntitiesTable({ items, selected, onSelected }: Props) {
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<EntityWithCount>[]>([]);
|
||||
useEffect(() => {
|
||||
const headers: RowHeaderDisplayDto<EntityWithCount>[] = [
|
||||
{
|
||||
name: "type",
|
||||
title: t("models.entity.type"),
|
||||
value: (item) => (
|
||||
<SimpleBadge
|
||||
title={item.type === "all" ? "app-and-admin" : item.type}
|
||||
color={item.type === "app" ? Colors.BLUE : item.type === "admin" ? Colors.GRAY : Colors.EMERALD}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("shared.order"),
|
||||
name: "order",
|
||||
value: (item) => item.order,
|
||||
formattedValue: (_, idx) => <OrderListButtons index={idx} items={items} />,
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.entity.title"),
|
||||
value: (item) => (
|
||||
<div className="flex items-center space-x-1">
|
||||
<Link to={adminPath("entities/" + item.slug + "/details", { mode: "host-aware" })} className="font-medium hover:underline">
|
||||
{translateEntityTitlePlural(t, i18n, item)}
|
||||
</Link>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "properties",
|
||||
title: t("models.property.plural"),
|
||||
className: "w-full text-xs",
|
||||
value: (item) => (
|
||||
<div className="max-w-xs truncate">
|
||||
{item.properties.filter((f) => !f.isDefault).length > 0 ? (
|
||||
<Link className="truncate pb-1 hover:underline" to={adminPath("entities/" + item.slug + "/properties", { mode: "host-aware" })}>
|
||||
{item.properties
|
||||
.filter((f) => !f.isDefault)
|
||||
.map((f) => translatePropertyTitle(t, i18n, item.name, f) + (f.isRequired ? "*" : ""))
|
||||
.join(", ")}
|
||||
</Link>
|
||||
) : (
|
||||
<Link className="text-muted-foreground truncate pb-1 hover:underline" to={adminPath("entities/" + item.slug + "/properties", { mode: "host-aware" })}>
|
||||
{t("shared.setCustomProperties")}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "relationships",
|
||||
title: t("models.relationship.plural"),
|
||||
value: (item) => (
|
||||
<Link className="truncate pb-1 hover:underline" to={adminPath("entities/" + item.slug + "/relationships", { mode: "host-aware" })}>
|
||||
{[...item.parentEntities, ...item.childEntities]
|
||||
.map((relationship) => t(RelationshipHelper.getTitleWithName({ fromEntityId: item.id, relationship })))
|
||||
.join(", ")}
|
||||
</Link>
|
||||
),
|
||||
className: "text-xs",
|
||||
},
|
||||
{
|
||||
name: "rows",
|
||||
title: t("models.row.plural"),
|
||||
value: (item) => (
|
||||
<Link to={adminPath("entities/" + item.slug + "/rows", { mode: "host-aware" })} className="hover:underline">
|
||||
{item._count.rows}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
setHeaders(headers);
|
||||
}, [appOrAdminData.tenantTypes, items, t]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<TableSimple
|
||||
selectedRows={selected}
|
||||
onSelected={onSelected}
|
||||
items={items}
|
||||
actions={[
|
||||
{
|
||||
title: t("models.entity.noCode.menu"),
|
||||
onClickRoute: (_, item) => adminPath(`entities/${item.slug}/no-code`, { mode: "host-aware" }),
|
||||
disabled: (i) => !i.isAutogenerated,
|
||||
},
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, item) => adminPath(`entities/${item.slug}/details`, { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
headers={headers}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "./EntityForm.tsx"), "utf8");
|
||||
|
||||
describe("EntityForm routing examples", () => {
|
||||
it("renders entity API examples through the canonical API host helper", () => {
|
||||
expect(source).toContain("apiPath(`entities/${slug || \"entity-name\"}/rows`, { mode: \"host-aware\" })");
|
||||
expect(source).toContain("rootData.apiBaseUrl ? new URL(apiRowsPath, rootData.apiBaseUrl).toString() : apiRowsPath");
|
||||
expect(source).not.toContain("Generates entity API at /v1/entities/");
|
||||
});
|
||||
});
|
||||
@@ -1,373 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import InputText, { RefInputText } from "../ui/input/InputText";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import InputGroup from "../ui/forms/InputGroup";
|
||||
import EntityIcon from "../layouts/icons/EntityIcon";
|
||||
import QuestionMarkFilledIcon from "../ui/icons/QuestionMarkFilledIcon";
|
||||
import InputNumber from "../ui/input/InputNumber";
|
||||
import InputCheckboxWithDescription from "../ui/input/InputCheckboxWithDescription";
|
||||
import { Entity } from "@toolctrl/db/prisma-browser";
|
||||
import FormGroup from "../ui/forms/FormGroup";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import StringUtils from "~/utils/shared/StringUtils";
|
||||
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
|
||||
import InputSelect from "../ui/input/InputSelect";
|
||||
import VisibilityHelper from "~/utils/helpers/VisibilityHelper";
|
||||
import Constants from "~/application/Constants";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { adminPath, apiPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
interface Props {
|
||||
item?: Entity | null;
|
||||
}
|
||||
export default function EntityForm({ item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
|
||||
const inputName = useRef<RefInputText>(null);
|
||||
|
||||
const [title, setTitle] = useState(item?.title ?? "");
|
||||
const [titlePlural, setTitlePlural] = useState(item?.titlePlural ?? "");
|
||||
const [name, setName] = useState(item?.name ?? "");
|
||||
const [type, setType] = useState(item?.type ?? DefaultEntityTypes.AppOnly);
|
||||
|
||||
const [slug, setSlug] = useState(item?.slug ?? "");
|
||||
const [icon, setIcon] = useState(
|
||||
item?.icon ??
|
||||
`<svg stroke="currentColor" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /> </svg>`
|
||||
);
|
||||
const [order, setOrder] = useState<number | undefined>(
|
||||
item?.order ?? (adminData.entities.length > 0 ? Math.max(...adminData.entities.map((o) => o.order)) : 0) + 1
|
||||
);
|
||||
const [prefix, setPrefix] = useState(item?.prefix ?? "");
|
||||
const [isAutogenerated, setIsAutogenerated] = useState(item?.isAutogenerated ?? true);
|
||||
const [hasApi, setHasApi] = useState(item?.hasApi ?? true);
|
||||
const [active, setActive] = useState(item?.active ?? true);
|
||||
|
||||
const [showInSidebar, setShowInSidebar] = useState(item?.showInSidebar ?? true);
|
||||
const [hasTags, setHasTags] = useState(item?.hasTags ?? true);
|
||||
const [hasComments, setHasComments] = useState(item?.hasComments ?? true);
|
||||
const [hasTasks, setHasTasks] = useState(item?.hasTasks ?? false);
|
||||
const [hasActivity, setHasActivity] = useState(item ? item.hasActivity : true);
|
||||
const [hasBulkDelete, setHasBulkDelete] = useState(item ? item.hasBulkDelete : false);
|
||||
const [hasViews, setHasViews] = useState(item ? item.hasViews : false);
|
||||
|
||||
const [defaultVisibility, setDefaultVisibility] = useState<string | number | undefined>(item?.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY);
|
||||
|
||||
const [onCreated, setOnCreated] = useState(item?.onCreated ?? "redirectToOverview");
|
||||
const [onEdit, setOnEdit] = useState(item?.onEdit ?? "editRoute");
|
||||
const apiRowsPath = apiPath(`entities/${slug || "entity-name"}/rows`, { mode: "host-aware" });
|
||||
const apiRowsUrl = rootData.apiBaseUrl ? new URL(apiRowsPath, rootData.apiBaseUrl).toString() : apiRowsPath;
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
inputName.current?.input.current?.focus();
|
||||
}, 100);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (!item) {
|
||||
// const slug = UrlUtils.slugify(t(titlePlural));
|
||||
// setSlug(slug);
|
||||
// if (titlePlural.length >= 3) {
|
||||
// setPrefix(t(titlePlural).substring(0, 3).toUpperCase());
|
||||
// }
|
||||
// }
|
||||
// // eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
// }, [titlePlural]);
|
||||
|
||||
return (
|
||||
<FormGroup id={item?.id} onCancel={() => navigate(adminPath("entities", { mode: "host-aware" }))} editing={true} canDelete={false}>
|
||||
<InputGroup title={t("models.entity.object")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputText
|
||||
ref={inputName}
|
||||
className="sm:col-span-6"
|
||||
name="name"
|
||||
title={t("models.entity.name")}
|
||||
value={name}
|
||||
setValue={setName}
|
||||
required
|
||||
help={t("models.entity.form.help.name")}
|
||||
autoComplete="off"
|
||||
onBlur={() => {
|
||||
if (!title.trim()) {
|
||||
const generateTitle = (str: string) => {
|
||||
return str
|
||||
.replace(/([a-z])([A-Z])/g, "$1 $2") // Insert space before capital letters
|
||||
.split(" ") // Split by spaces
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) // Capitalize the first letter of each word
|
||||
.join(" "); // Join the words back together
|
||||
};
|
||||
const newTitle = generateTitle(name);
|
||||
if (newTitle) {
|
||||
setTitle(newTitle);
|
||||
setPrefix(t(newTitle).substring(0, 3).toUpperCase());
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
className="sm:col-span-6"
|
||||
name="title"
|
||||
title={t("models.entity.title")}
|
||||
value={title}
|
||||
setValue={setTitle}
|
||||
required
|
||||
autoComplete="off"
|
||||
help={t("models.entity.form.help.title")}
|
||||
withTranslation
|
||||
/>
|
||||
<InputText
|
||||
className="sm:col-span-6"
|
||||
name="slug"
|
||||
title={t("models.entity.slug")}
|
||||
value={slug}
|
||||
setValue={(e) => {
|
||||
const withoutStartingSlash = e?.toString().replace(/^\//, "");
|
||||
setSlug(withoutStartingSlash);
|
||||
}}
|
||||
required
|
||||
autoComplete="off"
|
||||
help={t("models.entity.form.help.slug")}
|
||||
onBlur={() => {
|
||||
setSlug(UrlUtils.slugify(slug));
|
||||
if (!titlePlural.trim()) {
|
||||
const words = slug.split(/[- ]/).map((w) => StringUtils.capitalize(w.toLowerCase()));
|
||||
setTitlePlural(words.join(" "));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<InputText
|
||||
className="sm:col-span-6"
|
||||
name="title-plural"
|
||||
title={t("models.entity.titlePlural")}
|
||||
value={titlePlural}
|
||||
setValue={setTitlePlural}
|
||||
required
|
||||
autoComplete="off"
|
||||
help={t("models.entity.form.help.titlePlural")}
|
||||
withTranslation
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("models.entity.permissions")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputSelect
|
||||
className="sm:col-span-12"
|
||||
name="default-visibility"
|
||||
title={t("models.entity.defaultVisibility")}
|
||||
value={defaultVisibility}
|
||||
setValue={setDefaultVisibility}
|
||||
options={[
|
||||
{
|
||||
name: VisibilityHelper.getVisibilityTitle(t, DefaultVisibility.Private),
|
||||
value: DefaultVisibility.Private,
|
||||
},
|
||||
{
|
||||
name: VisibilityHelper.getVisibilityTitle(t, DefaultVisibility.Tenant),
|
||||
value: DefaultVisibility.Tenant,
|
||||
},
|
||||
{
|
||||
name: VisibilityHelper.getVisibilityTitle(t, DefaultVisibility.Public),
|
||||
value: DefaultVisibility.Public,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("models.entity.form.sections.display")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputSelect
|
||||
className="sm:col-span-3"
|
||||
name="type"
|
||||
title={t("models.entity.type")}
|
||||
value={type}
|
||||
// display="name"
|
||||
setValue={(e) => setType(e?.toString() ?? DefaultEntityTypes.AppOnly)}
|
||||
options={[
|
||||
{ name: t("models.entity.typeOptions.app"), value: DefaultEntityTypes.AppOnly },
|
||||
{ name: t("models.entity.typeOptions.admin"), value: DefaultEntityTypes.AdminOnly },
|
||||
{ name: t("models.entity.typeOptions.appAndAdmin"), value: DefaultEntityTypes.All },
|
||||
{ name: t("models.entity.typeOptions.system"), value: DefaultEntityTypes.System },
|
||||
]}
|
||||
required
|
||||
/>
|
||||
<InputNumber
|
||||
className="sm:col-span-3"
|
||||
name="order"
|
||||
title={t("models.entity.order")}
|
||||
value={order}
|
||||
setValue={setOrder}
|
||||
disabled={!item}
|
||||
min={1}
|
||||
max={99}
|
||||
required
|
||||
help={t("models.entity.form.help.order")}
|
||||
// readOnly={item === undefined}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
className="sm:col-span-3"
|
||||
name="prefix"
|
||||
title={t("models.entity.prefix")}
|
||||
value={prefix}
|
||||
setValue={(e) => setPrefix(e.toString().toUpperCase())}
|
||||
minLength={2}
|
||||
maxLength={5}
|
||||
required
|
||||
help={t("models.entity.form.help.prefix")}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
className="sm:col-span-3"
|
||||
name="icon"
|
||||
title={t("models.entity.icon")}
|
||||
// required
|
||||
value={icon}
|
||||
setValue={setIcon}
|
||||
hint={<div className="text-muted-foreground">{t("models.entity.form.iconHint")}</div>}
|
||||
button={
|
||||
<div className="absolute inset-y-0 right-0 flex py-0.5 pr-0.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-secondary inline-flex w-10 items-center justify-center rounded border px-1 text-center font-sans text-xs font-medium">
|
||||
{icon ? (
|
||||
<EntityIcon className="text-muted-foreground h-7 w-7" icon={icon} title={title} />
|
||||
) : (
|
||||
<QuestionMarkFilledIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("models.entity.form.sections.behavior")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputSelect
|
||||
className="sm:col-span-6"
|
||||
name="onCreated"
|
||||
title={t("models.entity.form.onCreated")}
|
||||
value={onCreated}
|
||||
setValue={(e) => setOnCreated(e?.toString() ?? "")}
|
||||
options={[
|
||||
{ value: "redirectToOverview", name: t("models.entity.form.onCreatedOptions.redirectToOverview") },
|
||||
{ value: "redirectToEdit", name: t("models.entity.form.onCreatedOptions.redirectToEdit") },
|
||||
{ value: "redirectToList", name: t("models.entity.form.onCreatedOptions.redirectToList") },
|
||||
{ value: "redirectToNew", name: t("models.entity.form.onCreatedOptions.redirectToNew") },
|
||||
{ value: "addAnother", name: t("models.entity.form.onCreatedOptions.addAnother") },
|
||||
{ value: "redirectToGroup", name: t("models.entity.form.onCreatedOptions.redirectToGroup") },
|
||||
]}
|
||||
/>
|
||||
<InputSelect
|
||||
className="sm:col-span-6"
|
||||
name="onEdit"
|
||||
title={t("models.entity.form.onEdit")}
|
||||
value={onEdit}
|
||||
setValue={(e) => setOnEdit(e?.toString() ?? "")}
|
||||
options={[
|
||||
{ value: "editRoute", name: t("models.entity.form.onEditOptions.editRoute") },
|
||||
{ value: "overviewRoute", name: t("models.entity.form.onEditOptions.overviewRoute") },
|
||||
{ value: "overviewAlwaysEditable", name: t("models.entity.form.onEditOptions.overviewAlwaysEditable") },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("shared.settings")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<div className="divide-border col-span-12 divide-y">
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-api"
|
||||
title={t("models.entity.hasApi")}
|
||||
value={hasApi}
|
||||
setValue={setHasApi}
|
||||
description={t("models.entity.form.descriptions.hasApi", { apiRowsUrl })}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="is-autogenerated"
|
||||
title={t("models.entity.isAutogenerated")}
|
||||
value={isAutogenerated}
|
||||
setValue={setIsAutogenerated}
|
||||
description={t("models.entity.form.descriptions.isAutogenerated")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="active"
|
||||
title={t("models.entity.active")}
|
||||
value={active}
|
||||
setValue={setActive}
|
||||
description={t("models.entity.form.descriptions.active")}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="show-in-sidebar"
|
||||
title={t("models.entity.showInSidebar")}
|
||||
value={showInSidebar}
|
||||
setValue={setShowInSidebar}
|
||||
description={t("models.entity.form.descriptions.showInSidebar")}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-tags"
|
||||
title={t("models.entity.hasTags")}
|
||||
value={hasTags}
|
||||
setValue={setHasTags}
|
||||
description={t("models.entity.form.descriptions.hasTags")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-comments"
|
||||
title={t("models.entity.hasComments")}
|
||||
value={hasComments}
|
||||
setValue={setHasComments}
|
||||
description={t("models.entity.form.descriptions.hasComments")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-tasks"
|
||||
title={t("models.entity.hasTasks")}
|
||||
value={hasTasks}
|
||||
setValue={setHasTasks}
|
||||
description={t("models.entity.form.descriptions.hasTasks")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-activity"
|
||||
title={t("models.entity.hasActivity")}
|
||||
value={hasActivity}
|
||||
setValue={setHasActivity}
|
||||
description={t("models.entity.form.descriptions.hasActivity")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-bulk-delete"
|
||||
title={t("models.entity.hasBulkDelete")}
|
||||
value={hasBulkDelete}
|
||||
setValue={setHasBulkDelete}
|
||||
description={t("models.entity.form.descriptions.hasBulkDelete")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-views"
|
||||
title={t("models.entity.hasViews")}
|
||||
value={hasViews}
|
||||
setValue={setHasViews}
|
||||
description={t("models.entity.form.descriptions.hasViews")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import { useNavigate } from "react-router";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityGroupWithDetails } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import InputText, { RefInputText } from "../ui/input/InputText";
|
||||
import FormGroup from "../ui/forms/FormGroup";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import InputCheckboxCards from "../ui/input/InputCheckboxCards";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityIcon from "../layouts/icons/EntityIcon";
|
||||
import QuestionMarkFilledIcon from "../ui/icons/QuestionMarkFilledIcon";
|
||||
import InputCheckboxWithDescription from "../ui/input/InputCheckboxWithDescription";
|
||||
import InputSelector from "../ui/input/InputSelector";
|
||||
import { EntityViewWithTenantAndUser } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export function EntityGroupForm({
|
||||
item,
|
||||
allEntities,
|
||||
systemViews,
|
||||
}: {
|
||||
item: EntityGroupWithDetails | undefined;
|
||||
allEntities: EntitySimple[];
|
||||
systemViews: EntityViewWithTenantAndUser[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [title, setTitle] = useState(item?.title ?? "");
|
||||
const [slug, setSlug] = useState(item?.slug ?? "");
|
||||
const [icon, setIcon] = useState(
|
||||
item?.icon ??
|
||||
`<svg stroke="currentColor" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /> </svg>`
|
||||
);
|
||||
const [collapsible, setCollapsible] = useState(item?.collapsible ?? false);
|
||||
const [section, setSection] = useState(item?.section ?? "");
|
||||
const [entities, setEntities] = useState<{ entityId: string; allViewId: string | null }[]>(item?.entities ?? []);
|
||||
|
||||
const input = useRef<RefInputText>(null);
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
input.current?.input.current?.focus();
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!item) {
|
||||
const slug = UrlUtils.slugify(title.toLowerCase());
|
||||
setSlug(slug);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [title]);
|
||||
|
||||
return (
|
||||
<FormGroup
|
||||
id={item?.id}
|
||||
onCancel={() => navigate(adminPath("entities/groups", { mode: "host-aware" }))}
|
||||
editing={true}
|
||||
canDelete={getUserHasPermission(appOrAdminData, "admin.entities.delete")}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between space-x-2">
|
||||
<InputText ref={input} autoFocus name="title" title={t("shared.title")} value={title} setValue={setTitle} required />
|
||||
<InputText name="slug" title={t("shared.slug")} value={slug} setValue={setSlug} required onBlur={() => setSlug(UrlUtils.slugify(slug))} />
|
||||
</div>
|
||||
<InputText
|
||||
className="col-span-12"
|
||||
name="icon"
|
||||
title={t("models.entity.icon")}
|
||||
value={icon}
|
||||
setValue={setIcon}
|
||||
hint={<div className="text-muted-foreground">{t("models.entityGroup.form.iconHint")}</div>}
|
||||
button={
|
||||
<div className="absolute inset-y-0 right-0 flex py-0.5 pr-0.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-secondary inline-flex w-10 items-center justify-center rounded border px-1 text-center font-sans text-xs font-medium">
|
||||
{icon ? (
|
||||
<EntityIcon className="text-muted-foreground h-7 w-7" icon={icon} title={title} />
|
||||
) : (
|
||||
<QuestionMarkFilledIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<InputText name="section" title={t("models.entityGroup.section")} value={section} setValue={setSection} />
|
||||
<InputCheckboxWithDescription
|
||||
name="collapsible"
|
||||
title={t("models.entityGroup.collapsible")}
|
||||
value={collapsible}
|
||||
setValue={setCollapsible}
|
||||
description={t("models.entityGroup.form.collapsibleDescription")}
|
||||
/>
|
||||
<InputCheckboxCards
|
||||
display="name"
|
||||
columns={allEntities.length === 1 ? 1 : 2}
|
||||
name="entities"
|
||||
title={t("models.entity.plural")}
|
||||
value={entities.map((f) => f.entityId)}
|
||||
selectAndClearAll
|
||||
onChange={(e) =>
|
||||
setEntities(
|
||||
e.map((v) => ({
|
||||
entityId: v.toString(),
|
||||
allViewId: entities.find((f) => f.entityId === v.toString())?.allViewId ?? null,
|
||||
}))
|
||||
)
|
||||
}
|
||||
options={allEntities.map((v) => ({ value: v.id, name: `${t(v.title)}` }))}
|
||||
/>
|
||||
|
||||
<div>
|
||||
{/* <label className="mb-1 flex justify-between space-x-2 text-xs font-medium">Layouts</label> */}
|
||||
<div className="space-y-1">
|
||||
{entities
|
||||
.filter((f) => systemViews.some((v) => v.entityId === f.entityId))
|
||||
.map((f, idx) => {
|
||||
const entity = allEntities.find((e) => e.id === f.entityId);
|
||||
if (!entity) {
|
||||
return <div key={f.entityId}>{t("models.entityGroup.form.invalidEntity")}</div>;
|
||||
}
|
||||
const entitySystemViews = systemViews.filter((v) => v.entityId === entity.id);
|
||||
return (
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
key={f.entityId}
|
||||
title={t("models.entityGroup.layoutFor", { entity: t(entity.title) })}
|
||||
value={f.allViewId ?? undefined}
|
||||
setValue={(e) => {
|
||||
const newEntities = [...entities];
|
||||
newEntities[idx].allViewId = e?.toString() ?? null;
|
||||
setEntities(newEntities);
|
||||
}}
|
||||
options={entitySystemViews.map((f) => {
|
||||
return {
|
||||
value: f.id,
|
||||
name: `${f.title} (${f.layout})`,
|
||||
};
|
||||
})}
|
||||
hint={
|
||||
<>
|
||||
{!!f.allViewId && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const newEntities = [...entities];
|
||||
const entity = entities.find((e) => e.entityId === f.entityId);
|
||||
if (entity) {
|
||||
entity.allViewId = null;
|
||||
}
|
||||
setEntities(newEntities);
|
||||
}}
|
||||
className="text-muted-foreground text-xs"
|
||||
>
|
||||
{t("shared.clear")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{entities.map((item) => {
|
||||
return <input key={item.entityId} type="hidden" name={"entities[]"} value={JSON.stringify(item)} />;
|
||||
})}
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const sourcePath = path.resolve(process.cwd(), "apps/web/app/components/entities/EntityForm.tsx");
|
||||
|
||||
describe("entity form i18n", () => {
|
||||
it("uses semantic translation keys for visible labels, options, help text, and descriptions", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.entity.defaultVisibility");
|
||||
expect(source).toContain("models.entity.typeOptions.appAndAdmin");
|
||||
expect(source).toContain("models.entity.form.help.slug");
|
||||
expect(source).toContain("models.entity.form.onCreatedOptions.redirectToOverview");
|
||||
expect(source).toContain("models.entity.form.descriptions.hasApi");
|
||||
expect(source).toContain("QuestionMarkFilledIcon");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('text-red-600">?</span>');
|
||||
expect(source).not.toContain('help="eg: contract"');
|
||||
expect(source).not.toContain('"Redirect to overview"');
|
||||
expect(source).not.toContain('"App and Admin"');
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/components/entities/relationships/EntityRelationshipsTable.tsx",
|
||||
"apps/web/app/components/entities/views/EntityViewsTable.tsx",
|
||||
];
|
||||
|
||||
describe("entity table i18n formatting", () => {
|
||||
it("uses locale-aware formatters for relationship and view counts", () => {
|
||||
const sources = sourceFiles.map((file) => readRepoFile(file)).join("\n");
|
||||
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.number");
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
});
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
import { EntityTemplate } from "@toolctrl/db/prisma-browser";
|
||||
import { useSubmit } from "react-router";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputCheckbox from "~/components/ui/input/InputCheckbox";
|
||||
import InputDate from "~/components/ui/input/InputDate";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
|
||||
const NovelEditor = lazy(() => import("~/modules/novel/ui/editor"));
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
item?: EntityTemplate;
|
||||
}
|
||||
|
||||
export default function EntityTemplateForm({ entity, item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const [title, setTitle] = useState<string>(item?.title ?? "");
|
||||
const [config, setConfig] = useState<{ [key: string]: any }>(item?.config ? JSON.parse(item?.config) : {});
|
||||
|
||||
function onSubmit(formData: FormData) {
|
||||
formData.set("config", JSON.stringify(config));
|
||||
submit(formData, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<FormGroup onSubmit={onSubmit} id={item?.id} editing={true}>
|
||||
<InputText name="title" title={t("models.entityTemplate.title")} value={title} setValue={setTitle} required />
|
||||
{entity.properties
|
||||
.filter((f) => !f.isDefault)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((property) => {
|
||||
return (
|
||||
<div key={property.name}>
|
||||
{property.type === PropertyType.TEXT ? (
|
||||
<>
|
||||
{PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor) === "wysiwyg" ? (
|
||||
<div className="h-52 overflow-y-auto">
|
||||
<div>
|
||||
<label htmlFor={property.name} className="text-muted-foreground mb-1 block text-xs font-medium">
|
||||
{t(property.title)}
|
||||
</label>
|
||||
<Suspense fallback={null}>
|
||||
<NovelEditor
|
||||
autoFocus={false}
|
||||
content={config[property.name]}
|
||||
onChange={(e) => {
|
||||
setConfig({ ...config, [property.name]: e.html });
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<InputText
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : property.type === PropertyType.BOOLEAN ? (
|
||||
<InputCheckbox
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name] === "false" ? false : config[property.name] === "true" ? true : config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
) : property.type === PropertyType.DATE ? (
|
||||
<InputDate
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
onChange={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
) : property.type === PropertyType.NUMBER ? (
|
||||
<InputNumber
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
) : property.type === PropertyType.SELECT ? (
|
||||
<InputSelector
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
options={property.options}
|
||||
/>
|
||||
) : (
|
||||
<div>{t("models.entityTemplate.errors.unsupportedPropertyType", { type: PropertyType[property.type] })}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
import { Property } from "@toolctrl/db/prisma-browser";
|
||||
import clsx from "clsx";
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useSubmit } from "react-router";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import ButtonTertiary from "../../ui/buttons/ButtonTertiary";
|
||||
import LockClosedIcon from "../../ui/icons/LockClosedIcon";
|
||||
import NewFieldIcon from "../../ui/icons/NewFieldIcon";
|
||||
import PencilIcon from "../../ui/icons/PencilIcon";
|
||||
import TrashIcon from "../../ui/icons/TrashIcon";
|
||||
import ConfirmModal, { RefConfirmModal } from "../../ui/modals/ConfirmModal";
|
||||
import PropertyBadge from "./PropertyBadge";
|
||||
import OrderListButtons from "../../ui/sort/OrderListButtons";
|
||||
import { defaultDisplayProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import EyeIcon from "~/components/ui/icons/EyeIcon";
|
||||
import EyeLashIcon from "~/components/ui/icons/EyeLashIcon";
|
||||
import DocumentDuplicateIconFilled from "~/components/ui/icons/DocumentDuplicateIconFilled";
|
||||
|
||||
interface Props {
|
||||
items: PropertyWithDetails[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function PropertiesList({ items, className }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [showDefaultFields, setShowDefaultFields] = useState(false);
|
||||
|
||||
function deleteField(item: Property) {
|
||||
confirmDelete.current?.setValue(item);
|
||||
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function confirmedDelete(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete");
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onToggleDisplay(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "toggle-display");
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onDuplicate(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "duplicate");
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={clsx(className, "")}>
|
||||
<div className="space-y-2">
|
||||
{showDefaultFields && (
|
||||
<div className="mb-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">{t("models.property.defaultProperties.title")}</h3>
|
||||
{showDefaultFields && (
|
||||
<div className="flex justify-end">
|
||||
<ButtonTertiary className="-my-1" onClick={() => setShowDefaultFields(!showDefaultFields)}>
|
||||
{t("models.property.defaultProperties.hide")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{defaultDisplayProperties.map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="border-border bg-secondary/90 rounded-md border px-4 py-2 shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
<LockClosedIcon className="h-4 w-4 text-gray-300" />
|
||||
{/* <PropertyBadge className="h-4 w-4 text-muted-foreground" /> */}
|
||||
{/* <div className="truncate text-sm text-muted-foreground">{t("entities.fields." + PropertyType[item.type])}</div> */}
|
||||
</div>
|
||||
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{/* <PropertyTitle item={item} /> */}
|
||||
<div className="flex flex-col">
|
||||
<div>{t(item.title)}</div>
|
||||
<div className="text-muted-foreground text-xs">{item.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">{t("models.property.plural")}</h3>
|
||||
{!showDefaultFields && (
|
||||
<div className="flex justify-end">
|
||||
<ButtonTertiary className="-my-1" onClick={() => setShowDefaultFields(!showDefaultFields)}>
|
||||
{t("models.property.defaultProperties.show")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items
|
||||
.filter((f) => !f.isDefault)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="border-border bg-background rounded-md border px-4 py-1 shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2 truncate">
|
||||
<div className="flex items-center space-x-3 truncate">
|
||||
<div className="hidden shrink-0 sm:flex">
|
||||
<OrderListButtons index={idx} items={items.filter((f) => !f.isDefault)} editable={true} />
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<PropertyBadge type={item.type} className="text-muted-foreground h-4 w-4" />
|
||||
</div>
|
||||
<div className="text-foreground flex items-center space-x-2 truncate text-sm">
|
||||
<PropertyTitle item={item} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 space-x-1">
|
||||
<div className="flex items-center space-x-1 truncate p-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggleDisplay(item)}
|
||||
aria-label={t(item.isDisplay ? "shared.hide" : "shared.show")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
>
|
||||
{item.isDisplay ? (
|
||||
<EyeIcon className="text-muted-foreground hover:text-muted-foreground h-4 w-4" />
|
||||
) : (
|
||||
<EyeLashIcon className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
)}
|
||||
</button>
|
||||
<Link
|
||||
to={item.id}
|
||||
aria-label={t("shared.edit")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
preventScrollReset
|
||||
// onClick={() => update(idx, item)}
|
||||
>
|
||||
<PencilIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDuplicate(item)}
|
||||
aria-label={t("shared.duplicate")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
>
|
||||
<DocumentDuplicateIconFilled className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("shared.delete")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
onClick={() => deleteField(item)}
|
||||
>
|
||||
<TrashIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<Link
|
||||
to={`new`}
|
||||
className="focus:ring-ring border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed px-12 py-6 text-center focus:ring-2 focus:ring-offset-2 focus:outline-hidden"
|
||||
preventScrollReset
|
||||
>
|
||||
<NewFieldIcon className="text-muted-foreground mx-auto h-8" />
|
||||
<span className="text-foreground mt-2 block text-sm font-medium">{t("models.property.actions.add")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
{/* <PropertyForm ref={propertyForm} entityId={entityId} onCreated={created} onUpdated={updated} onDeleted={deleted} /> */}
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={confirmedDelete} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const PropertyTitle = ({ item }: { item: PropertyWithDetails }) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-baseline space-x-1 truncate">
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{t(EntityHelper.getFieldTitle(item, item.isDefault))}
|
||||
{item.isRequired && <span className="text-red-500">*</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{item.name}
|
||||
{item.subtype === "phone" && " (phone)"}
|
||||
{item.subtype === "url" && " (URL)"}
|
||||
{[PropertyType.MULTI_SELECT, PropertyType.SELECT].includes(item.type) && "[]"}
|
||||
{[PropertyType.RANGE_NUMBER, PropertyType.RANGE_DATE].includes(item.type) && ` (${t("models.property.badges.range")})`}
|
||||
{[PropertyType.FORMULA].includes(item.type) && ` (${t("models.property.badges.formula")})`}
|
||||
</div>
|
||||
</div>
|
||||
{/* {item.type === PropertyType.FORMULA && <div className="truncate italic text-muted-foreground">({item.formula})</div>} */}
|
||||
{[PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(item.type) && (
|
||||
<div className="text-muted-foreground truncate text-xs">
|
||||
[
|
||||
{item.options.length === 0
|
||||
? t("models.property.noOptions")
|
||||
: t("models.property.optionsSummary", { options: item.options?.map((f) => f.value).join(", ") })}
|
||||
]
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.attributes.filter((f) => f.value).length > 0 && (
|
||||
<div className="text-muted-foreground truncate text-xs">
|
||||
[
|
||||
{item.attributes
|
||||
.filter((f) => f.value)
|
||||
.map((f) => `${f.name}: ${f.value}`)
|
||||
.join(", ")}
|
||||
]
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,116 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
|
||||
interface Props {
|
||||
name: PropertyAttributeName;
|
||||
title: string;
|
||||
value: string | undefined;
|
||||
setValue: React.Dispatch<React.SetStateAction<string | undefined>>;
|
||||
className?: string;
|
||||
}
|
||||
export default function PropertyAttribute({ name, title, value, setValue, className }: Props) {
|
||||
const { t } = useTranslation();
|
||||
function isNumber() {
|
||||
return [
|
||||
PropertyAttributeName.Min,
|
||||
PropertyAttributeName.Max,
|
||||
PropertyAttributeName.MaxSize,
|
||||
PropertyAttributeName.Rows,
|
||||
PropertyAttributeName.Columns,
|
||||
].includes(name);
|
||||
}
|
||||
function isBoolean() {
|
||||
return [PropertyAttributeName.Uppercase, PropertyAttributeName.Lowercase, PropertyAttributeName.Password].includes(name);
|
||||
}
|
||||
function isSelector() {
|
||||
return PropertyAttributeHelper.getPropertyAttributeOptions(name, t).length > 0;
|
||||
}
|
||||
function getPlaceholder() {
|
||||
if (name === PropertyAttributeName.Step) {
|
||||
return "0.01";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
function getDescription() {
|
||||
if (name === PropertyAttributeName.Uppercase) {
|
||||
return t("models.entity.propertyAttributes.descriptions.uppercase");
|
||||
} else if (name === PropertyAttributeName.Lowercase) {
|
||||
return t("models.entity.propertyAttributes.descriptions.lowercase");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{isNumber() ? (
|
||||
<InputNumber
|
||||
className={className}
|
||||
name={name}
|
||||
title={title}
|
||||
value={Number(value)}
|
||||
setValue={(e) => setValue(e?.toString())}
|
||||
max={name === PropertyAttributeName.Columns ? 12 : undefined}
|
||||
hint={
|
||||
<>
|
||||
{value && (
|
||||
<button type="button" onClick={() => setValue("")} className="text-muted-foreground text-xs hover:text-red-500">
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
) : isBoolean() ? (
|
||||
<InputCheckboxWithDescription
|
||||
className={className}
|
||||
description={getDescription()}
|
||||
name={name}
|
||||
title={title}
|
||||
value={value === "true" ? true : false}
|
||||
setValue={(e) => setValue(e ? (Boolean(e) === true ? "true" : "false") : "false")}
|
||||
/>
|
||||
) : isSelector() ? (
|
||||
<InputSelector
|
||||
className={className}
|
||||
withSearch={false}
|
||||
name={name}
|
||||
title={title}
|
||||
value={value}
|
||||
setValue={(e) => setValue(e?.toString())}
|
||||
options={PropertyAttributeHelper.getPropertyAttributeOptions(name, t)}
|
||||
hint={
|
||||
<>
|
||||
{value && (
|
||||
<button type="button" onClick={() => setValue("")} className="text-muted-foreground text-xs hover:text-red-500">
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
></InputSelector>
|
||||
) : (
|
||||
<InputText
|
||||
className={className}
|
||||
name={name}
|
||||
title={title}
|
||||
value={value}
|
||||
setValue={(e) => setValue(e.toString())}
|
||||
placeholder={getPlaceholder()}
|
||||
hint={
|
||||
<>
|
||||
{value && (
|
||||
<button type="button" onClick={() => setValue("")} className="text-muted-foreground text-xs hover:text-red-500">
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import clsx from "clsx";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import SimpleBadge from "../../ui/badges/SimpleBadge";
|
||||
import PaperClipIcon from "../../ui/icons/PaperClipIcon";
|
||||
import ExperimentIconFilled from "~/components/ui/icons/tests/ExperimentIconFilled";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
type: PropertyType;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function PropertyBadge({ title, type, className }: Props) {
|
||||
return (
|
||||
<>
|
||||
{title ? (
|
||||
<SimpleBadge title={title} color={Colors.ORANGE} />
|
||||
) : [PropertyType.NUMBER, PropertyType.RANGE_NUMBER].includes(type) ? (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className={clsx(className, "h-5 w-5 shrink-0")} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
) : [PropertyType.DATE, PropertyType.RANGE_DATE].includes(type) ? (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className={clsx(className, "h-5 w-5 shrink-0")} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
) : type === PropertyType.TEXT ? (
|
||||
<svg
|
||||
className={clsx(className, "h-5 w-5 shrink-0")}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 172 172"
|
||||
fill="currentColor"
|
||||
>
|
||||
<g
|
||||
fill="none"
|
||||
fillRule="nonzero"
|
||||
stroke="none"
|
||||
strokeWidth="1"
|
||||
strokeLinecap="butt"
|
||||
strokeLinejoin="miter"
|
||||
strokeMiterlimit="10"
|
||||
strokeDasharray=""
|
||||
strokeDashoffset="0"
|
||||
fontFamily="none"
|
||||
fontWeight="none"
|
||||
fontSize="none"
|
||||
// textAnchor="none"
|
||||
>
|
||||
<path d="M0,172v-172h172v172z" fill="none"></path>
|
||||
<g fill="currentColor">
|
||||
<path d="M146.59473,57.24935c-5.28183,0 -9.90758,1.23715 -13.89941,3.69531c-3.98467,2.451 -7.04629,5.9742 -9.19629,10.56803c-2.14283,4.59384 -3.2194,9.90187 -3.2194,15.92904v3.83528c0,9.44567 2.33353,16.88702 6.9847,22.29785c4.65117,5.41083 11.04261,8.11849 19.16244,8.11849c7.42467,0 13.40816,-1.93175 17.94466,-5.80892c4.5365,-3.87717 7.05009,-9.19203 7.54459,-15.94304v-0.014h-13.03157c-0.29383,3.81983 -1.4442,6.6341 -3.42936,8.45443c-1.98517,1.8275 -4.99348,2.74349 -9.02832,2.74349c-4.46483,0 -7.74101,-1.5573 -9.81218,-4.68913c-2.07117,-3.12467 -3.10742,-8.08556 -3.10742,-14.86523v-4.73112c0.05733,-6.48583 1.16705,-11.2725 3.33138,-14.36133c2.16433,-3.08883 5.40602,-4.63314 9.75618,-4.63314c4.00617,0 6.98784,0.92316 8.94434,2.74349c1.96367,1.82033 3.10686,4.7552 3.42936,8.80436h13.04557c-0.69517,-7.009 -3.27573,-12.4438 -7.74056,-16.32096c-4.46483,-3.87717 -10.36871,-5.82292 -17.67871,-5.82292zM23.58561,58.11719l-23.58561,62.70833h13.88542l4.35319,-12.91959h22.87174l4.40918,12.91959h13.87142l-23.71159,-62.70833zM65.31185,58.11719v62.70833h24.63542c7.19533,-0.05733 12.73058,-1.64195 16.61491,-4.74511c3.8915,-3.10317 5.83691,-7.66229 5.83691,-13.68946c0,-3.53317 -0.94298,-6.52167 -2.81348,-8.95833c-1.8705,-2.43667 -4.43807,-4.06842 -7.68457,-4.87109c2.84517,-1.08933 5.06459,-2.79355 6.66276,-5.13705c1.59816,-2.3435 2.39355,-5.04399 2.39355,-8.11849c0,-5.62583 -1.98539,-9.90478 -5.96289,-12.82161c-3.9775,-2.91683 -9.80692,-4.36719 -17.49675,-4.36719zM78.35742,68.58724h9.1403c3.59767,0 6.2247,0.61465 7.89453,1.86165c1.66983,1.247 2.50553,3.29969 2.50553,6.14486c0,5.08117 -3.29599,7.68189 -9.88216,7.79655h-9.6582zM29.63249,73.96224l7.96452,23.47364h-15.84505zM78.35742,93.5306h11.96777c6.00567,0.086 9.00032,2.99387 9.00032,8.73438c0,2.55133 -0.86235,4.55722 -2.58952,6.00489c-1.72717,1.44767 -4.12016,2.16959 -7.19466,2.16959h-11.18392z"></path>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
) : type === PropertyType.BOOLEAN ? (
|
||||
<CheckIcon className={clsx(className, "h-5 w-5 shrink-0")} />
|
||||
) : type === PropertyType.SELECT || type === PropertyType.MULTI_SELECT || type === PropertyType.MULTI_TEXT ? (
|
||||
<svg
|
||||
className={clsx(className, "h-5 w-5 shrink-0")}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 172 172"
|
||||
fill="currentColor"
|
||||
>
|
||||
<g
|
||||
fill="none"
|
||||
fillRule="nonzero"
|
||||
stroke="none"
|
||||
strokeWidth="1"
|
||||
strokeLinecap="butt"
|
||||
strokeLinejoin="miter"
|
||||
strokeMiterlimit="10"
|
||||
strokeDasharray=""
|
||||
strokeDashoffset="0"
|
||||
fontFamily="none"
|
||||
fontWeight="none"
|
||||
fontSize="none"
|
||||
// textAnchor="none"
|
||||
>
|
||||
<path d="M0,172v-172h172v172z" fill="none"></path>
|
||||
<g fill="currentColor">
|
||||
<path d="M21.5,43v14.33333h129v-14.33333zM21.5,71.66667v14.33333h129v-14.33333zM21.5,100.33333v14.33333h129v-14.33333zM64.5,129l21.5,21.5l21.5,-21.5z"></path>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
) : type === PropertyType.MEDIA ? (
|
||||
<PaperClipIcon className={clsx(className, "h-5 w-5 shrink-0")} />
|
||||
) : type === PropertyType.FORMULA ? (
|
||||
<ExperimentIconFilled className={clsx(className, "h-5 w-5 shrink-0")} />
|
||||
) : (
|
||||
<div></div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,377 +0,0 @@
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import PencilAltIcon from "~/components/ui/icons/PencilAltIcon";
|
||||
import ViewListIcon from "~/components/ui/icons/ViewListIcon";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { PropertyWithDetails, EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import StringUtils from "~/utils/shared/StringUtils";
|
||||
import PropertyTypeSelector from "./PropertyTypeSelector";
|
||||
import PropertyOptionsForm, { OptionValue, RefPropertyOptionsForm } from "./PropertyOptionsForm";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import PropertyAttribute from "./PropertyAttribute";
|
||||
import PropertySubtypeSelector from "./PropertySubtypeSelector";
|
||||
import PropertyFormulaSelector from "./PropertyFormulaSelector";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import { Link } from "react-router";
|
||||
|
||||
interface Props {
|
||||
item?: PropertyWithDetails;
|
||||
properties: PropertyWithDetails[];
|
||||
entities: EntitySimple[];
|
||||
formulas: FormulaDto[];
|
||||
formulaListPath?: string;
|
||||
formulaDetailsPath?: (formulaId: string) => string;
|
||||
}
|
||||
|
||||
export default function PropertyForm({ item, properties, formulas, formulaListPath, formulaDetailsPath }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const selectOptionsForm = useRef<RefPropertyOptionsForm>(null);
|
||||
|
||||
const [showAdvancedOptions, setShowAdvancedOptions] = useState(true);
|
||||
|
||||
const [order, setOrder] = useState<number | undefined>(item?.order ?? Math.max(...properties.map((o) => o.order)) + 1);
|
||||
const [name, setName] = useState<string>(item?.name ?? "");
|
||||
const [title, setTitle] = useState<string>(item?.title ?? "");
|
||||
const [type, setType] = useState<PropertyType>(item?.type ?? PropertyType.TEXT);
|
||||
const [subtype, setSubtype] = useState<string>(item?.subtype ?? "");
|
||||
const [formulaId, setFormulaId] = useState(item?.formulaId ?? undefined);
|
||||
const [options, setOptions] = useState<OptionValue[]>(
|
||||
item?.options?.map((o) => {
|
||||
return {
|
||||
id: o.id,
|
||||
order: o.order,
|
||||
value: o.value,
|
||||
name: o.name,
|
||||
color: o.color,
|
||||
};
|
||||
}) ?? []
|
||||
);
|
||||
const [isRequired, setIsRequired] = useState<boolean>(item?.isRequired ?? true);
|
||||
const [showInCreate, setShowInCreate] = useState<boolean>(item?.showInCreate ?? true);
|
||||
const [isHidden, setIsHidden] = useState<boolean>(item?.isHidden ?? false);
|
||||
const [isDisplay, setIsDisplay] = useState<boolean>(item?.isDisplay ?? properties.filter((f) => !f.isDefault).length === 0);
|
||||
const [isReadOnly, setIsReadOnly] = useState<boolean>(item?.isReadOnly ?? false);
|
||||
const [canUpdate, setCanUpdate] = useState<boolean>(item ? item.canUpdate : true);
|
||||
const [attributes, setAttributes] = useState<{ name: string; value: string | undefined }[]>(item?.attributes ?? []);
|
||||
|
||||
// const [formula, setFormula] = useState<string>();
|
||||
|
||||
const [titleEnabled, setTitleEnabled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!item) {
|
||||
if (title.includes(".")) {
|
||||
const keys = title.split(".");
|
||||
setName(StringUtils.toCamelCase(keys[keys.length - 1].toLowerCase()));
|
||||
} else {
|
||||
setName(StringUtils.toCamelCase(title.toLowerCase()));
|
||||
}
|
||||
}
|
||||
}, [item, title, type]);
|
||||
|
||||
useEffect(() => {
|
||||
const formula = formulas.find((f) => f.id === formulaId);
|
||||
if (!item && formula) {
|
||||
setTitle(formula.name);
|
||||
setName(StringUtils.toCamelCase(formula.name.toLowerCase()));
|
||||
}
|
||||
}, [item, formulaId, formulas]);
|
||||
|
||||
useEffect(() => {
|
||||
setTitleEnabled(true);
|
||||
if (!item) {
|
||||
if (type === PropertyType.TEXT) {
|
||||
setSubtype("singleLine");
|
||||
} else if (type === PropertyType.SELECT) {
|
||||
setSubtype("dropdown");
|
||||
} else if (type === PropertyType.MULTI_SELECT) {
|
||||
setSubtype("combobox");
|
||||
} else {
|
||||
// setSubtype("");
|
||||
}
|
||||
} else {
|
||||
if (type === PropertyType.TEXT) {
|
||||
if (!subtype || !["singleLine", "email", "phone", "url"].includes(subtype)) {
|
||||
setSubtype("singleLine");
|
||||
}
|
||||
} else if (type === PropertyType.SELECT) {
|
||||
if (!subtype || !["dropdown", "radioGroupCards"].includes(subtype)) {
|
||||
setSubtype("dropdown");
|
||||
}
|
||||
} else if (type === PropertyType.MULTI_SELECT) {
|
||||
if (!subtype || !["combobox", "checkboxCards"].includes(subtype)) {
|
||||
setSubtype("combobox");
|
||||
}
|
||||
} else {
|
||||
// setSubtype("");
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [item, type]);
|
||||
|
||||
useEffect(() => {
|
||||
if (type === PropertyType.FORMULA) {
|
||||
setShowAdvancedOptions(false);
|
||||
setIsRequired(false);
|
||||
setIsReadOnly(true);
|
||||
setShowInCreate(false);
|
||||
}
|
||||
}, [type]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormGroup
|
||||
id={item?.id}
|
||||
editing={true}
|
||||
canDelete={item !== undefined && !item?.isDefault && showAdvancedOptions}
|
||||
className="space-y-2 pb-4"
|
||||
classNameFooter="px-4"
|
||||
>
|
||||
<input type="hidden" name="order" value={order} hidden readOnly />
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="space-y-3 px-4">
|
||||
<div className="w-full">
|
||||
<label htmlFor="type" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.type")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertyTypeSelector selected={type} onSelected={(e) => setType(e)} />
|
||||
</div>
|
||||
</div>
|
||||
{type === PropertyType.TEXT && (
|
||||
<div>
|
||||
<label htmlFor="subtype" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.subtype")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertySubtypeSelector types={["singleLine", "email", "phone", "url"]} selected={subtype} onSelected={(e) => setSubtype(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{type === PropertyType.SELECT && (
|
||||
<div>
|
||||
<label htmlFor="subtype" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.subtype")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertySubtypeSelector types={["dropdown", "radioGroupCards"]} selected={subtype} onSelected={(e) => setSubtype(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{type === PropertyType.MULTI_SELECT && (
|
||||
<div>
|
||||
<label htmlFor="subtype" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.subtype")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertySubtypeSelector types={["combobox", "checkboxCards"]} selected={subtype} onSelected={(e) => setSubtype(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{type === PropertyType.FORMULA && (
|
||||
<div>
|
||||
<div className="flex justify-between space-x-2">
|
||||
<label htmlFor="formula" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.formula")}
|
||||
</label>
|
||||
{item?.formulaId && formulaDetailsPath ? (
|
||||
<Link to={formulaDetailsPath(item.formulaId)} className="text-xs text-blue-500 hover:underline">
|
||||
{t("models.property.goToFormula")}
|
||||
</Link>
|
||||
) : formulaListPath ? (
|
||||
<Link to={formulaListPath} className="text-xs text-blue-500 hover:underline">
|
||||
{t("models.property.viewFormulas")}
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
<PropertyFormulaSelector name="formula-id" items={formulas} selected={formulaId} onSelected={(e) => setFormulaId(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{titleEnabled && (
|
||||
<InputText
|
||||
name="title"
|
||||
title={t("models.property.title")}
|
||||
value={title}
|
||||
setValue={(e) => setTitle(e)}
|
||||
disabled={!titleEnabled}
|
||||
required
|
||||
withTranslation
|
||||
placeholder={t("models.property.form.placeholders.title")}
|
||||
autoFocus
|
||||
/>
|
||||
)}
|
||||
<InputText
|
||||
name="name"
|
||||
title={t("models.property.name")}
|
||||
value={name}
|
||||
setValue={(e) => setName(e)}
|
||||
required
|
||||
placeholder={t("models.property.form.placeholders.name")}
|
||||
pattern="[a-z]+((\d)|([A-Z0-9][a-z0-9]+))*([A-Z])?"
|
||||
hint={<span className="text-muted-foreground font-normal italic">{t("models.property.form.hints.camelCase")}</span>}
|
||||
/>
|
||||
|
||||
<div className="border-border w-full rounded-md border border-dotted px-2 py-0">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-display"
|
||||
title={t("models.property.isDisplay")}
|
||||
description={t("models.property.form.descriptions.isDisplay")}
|
||||
value={isDisplay}
|
||||
setValue={setIsDisplay}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* {type === PropertyType.FORMULA && (
|
||||
<div className="w-full">
|
||||
<label htmlFor="formula" className="block text-xs font-medium text-foreground/80">
|
||||
{t("entities.fields.FORMULA")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<InputText
|
||||
name="formula"
|
||||
title={t("models.property.formula")}
|
||||
value={formula}
|
||||
setValue={(e) => setFormula(e.toString())}
|
||||
disabled={!titleEnabled}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)} */}
|
||||
{[PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(type) && (
|
||||
<div className="w-full">
|
||||
<label htmlFor="property-options-display" className="text-foreground/80 block text-sm font-medium">
|
||||
{t("models.property.options")}
|
||||
</label>
|
||||
<div className="mt-1 flex rounded-md shadow-2xs">
|
||||
<div className="relative flex grow items-stretch focus-within:z-10">
|
||||
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
|
||||
<ViewListIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
</div>
|
||||
{options.map((option) => {
|
||||
return <input key={option.order} hidden readOnly type="text" id="options[]" name="options[]" value={JSON.stringify(option)} />;
|
||||
})}
|
||||
<input
|
||||
id="property-options-display"
|
||||
disabled
|
||||
className="focus:border-border focus:ring-ring border-border text-foreground bg-secondary/90 block w-full rounded-none rounded-l-md border pl-10 sm:text-sm"
|
||||
value={options.length === 0 ? t("models.property.form.noDropdownValues") : options.map((f) => f.value).join(", ")}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectOptionsForm.current?.set(options)}
|
||||
className="focus:border-border focus:ring-ring border-border bg-secondary hover:bg-secondary/90 text-foreground/80 relative -ml-px inline-flex items-center space-x-2 rounded-r-md border px-4 py-1.5 text-sm font-medium focus:outline-hidden focus:ring-1"
|
||||
>
|
||||
<PencilAltIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
<span>{t("models.property.form.setOptions")}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex">
|
||||
<ButtonTertiary onClick={() => setShowAdvancedOptions(!showAdvancedOptions)}>
|
||||
{!showAdvancedOptions ? t("models.property.form.showAdvancedOptions") : t("models.property.form.hideAdvancedOptions")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={clsx("border-border bg-secondary my-2 space-y-3 border border-dashed px-4 py-3", showAdvancedOptions ? "" : "hidden")}>
|
||||
<div className="w-full">
|
||||
<InputNumber name="order" title={t("models.property.order")} value={order} setValue={setOrder} />
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="show-in-create"
|
||||
title={t("models.property.showInCreate")}
|
||||
description={t("models.property.form.descriptions.showInCreate")}
|
||||
value={showInCreate}
|
||||
setValue={setShowInCreate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-required"
|
||||
title={t("models.property.isRequired")}
|
||||
description={t("models.property.form.descriptions.isRequired")}
|
||||
value={isRequired}
|
||||
setValue={setIsRequired}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-hidden"
|
||||
title={t("models.property.isHidden")}
|
||||
description={t("models.property.form.descriptions.isHidden")}
|
||||
value={isHidden}
|
||||
setValue={setIsHidden}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-read-only"
|
||||
title={t("models.property.isReadOnly")}
|
||||
description={t("models.property.form.descriptions.isReadOnly")}
|
||||
value={isReadOnly}
|
||||
setValue={setIsReadOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="can-update"
|
||||
title={t("models.property.canUpdate")}
|
||||
description={t("models.property.form.descriptions.canUpdate")}
|
||||
value={canUpdate}
|
||||
setValue={setCanUpdate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* <div className="font-bold">{t("models.propertyAttribute.plural")}</div> */}
|
||||
|
||||
{attributes.map((attribute) => {
|
||||
return <input key={attribute.name} hidden readOnly type="text" id="attributes[]" name="attributes[]" value={JSON.stringify(attribute)} />;
|
||||
})}
|
||||
|
||||
{PropertyAttributeHelper.getAttributesByType(type, attributes).map((item) => {
|
||||
return (
|
||||
<PropertyAttribute
|
||||
className="mb-2"
|
||||
key={item}
|
||||
name={item}
|
||||
title={PropertyAttributeHelper.getAttributeTitle(t, item)}
|
||||
value={attributes.find((f) => f.name === item)?.value ?? undefined}
|
||||
setValue={(e) => {
|
||||
const value = { name: item, value: e?.toString() };
|
||||
const found = attributes.find((f) => f.name === item);
|
||||
if (found) {
|
||||
setAttributes([...attributes.filter((f) => f.name !== item), value]);
|
||||
} else {
|
||||
setAttributes([...attributes, value]);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</FormGroup>
|
||||
<PropertyOptionsForm ref={selectOptionsForm} title={title} onSet={(e) => setOptions(e)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { Fragment } from "react";
|
||||
import { Listbox, Transition } from "@headlessui/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import clsx from "clsx";
|
||||
import SelectorIcon from "../../ui/icons/SelectorIcon";
|
||||
import CheckIcon from "../../ui/icons/CheckIcon";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
// import PropertySubtypeBadge from "./PropertySubtypeBadge";
|
||||
|
||||
interface Props {
|
||||
name: string;
|
||||
items: FormulaDto[];
|
||||
className?: string;
|
||||
selected: string | undefined;
|
||||
onSelected: (item: string) => void;
|
||||
}
|
||||
|
||||
export default function PropertyFormulaSelector({ name, items, className, selected, onSelected }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Listbox name={name} value={selected} onChange={onSelected}>
|
||||
{({ open }) => (
|
||||
<>
|
||||
<input type="hidden" name="subtype" value={selected} hidden readOnly />
|
||||
<div className={clsx("relative", className)}>
|
||||
<Listbox.Button className="focus:border-border focus:ring-ring border-border text-foreground bg-background relative w-full cursor-default rounded-md border py-2 pl-3 pr-10 text-left shadow-2xs focus:outline-hidden focus:ring-1 sm:text-sm">
|
||||
{selected ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
{/* <PropertySubtypeBadge subtype={selected} className="h-4 w-4 text-muted-foreground" /> */}
|
||||
<div className="truncate">{items.find((item) => item.id === selected)?.name}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground">{t("shared.select")}...</div>
|
||||
)}
|
||||
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
<SelectorIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
</Listbox.Button>
|
||||
|
||||
<Transition show={open} as={Fragment} leave="transition ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0">
|
||||
<Listbox.Options className="border-border bg-background absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border py-1 text-base shadow-lg focus:outline-hidden sm:text-sm">
|
||||
{items.length === 0 ? (
|
||||
<div className=" flex select-none justify-center p-2 text-red-500">{t("models.property.selectors.noFormulas")}</div>
|
||||
) : (
|
||||
<>
|
||||
{items.map((item, idx) => (
|
||||
<Listbox.Option
|
||||
key={idx}
|
||||
className={({ active }) =>
|
||||
clsx(active ? " bg-secondary " : "", "hover:bg-secondary relative cursor-default select-none py-2 pl-3 pr-9")
|
||||
}
|
||||
value={item.id}
|
||||
>
|
||||
{({ selected, active }) => (
|
||||
<>
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="truncate">{item.name}</div>
|
||||
</div>
|
||||
{selected ? (
|
||||
<span className={clsx(active ? "" : "", "absolute inset-y-0 right-0 flex items-center pr-4")}>
|
||||
<CheckIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Option>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Options>
|
||||
</Transition>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Listbox>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { DateFormatType } from "~/utils/shared/DateUtils";
|
||||
import { NumberFormatType } from "~/utils/shared/NumberUtils";
|
||||
import RowNumberCell from "../rows/cells/RowNumberCell";
|
||||
import RowDateCell from "../rows/cells/RowDateCell";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { FormulaValueType } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import { BooleanFormatType } from "~/utils/shared/BooleanUtils";
|
||||
import RowBooleanCell from "../rows/cells/RowBooleanCell";
|
||||
|
||||
interface Props {
|
||||
property: PropertyWithDetails;
|
||||
value: FormulaValueType;
|
||||
}
|
||||
export default function PropertyFormulaValueBadge({ property, value }: Props) {
|
||||
const getNumberFormat = () => {
|
||||
return property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value as NumberFormatType;
|
||||
};
|
||||
const getBooleanFormat = () => {
|
||||
return property.attributes.find((f) => f.name === PropertyAttributeName.FormatBoolean)?.value as BooleanFormatType;
|
||||
};
|
||||
const getDateFormat = () => {
|
||||
return property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value as DateFormatType;
|
||||
};
|
||||
return (
|
||||
<div className="flex space-x-1">
|
||||
{/* <div>
|
||||
<div>[resultAs:{property.formula?.resultAs}]</div>
|
||||
<div>[calculationTrigger:{property.formula?.calculationTrigger}]</div>
|
||||
<div>value: {JSON.stringify(value)}</div>
|
||||
</div> */}
|
||||
{property.formula?.resultAs === "number" ? (
|
||||
<RowNumberCell value={Number(value) ?? undefined} format={getNumberFormat()} />
|
||||
) : property.formula?.resultAs === "boolean" ? (
|
||||
<RowBooleanCell value={Boolean(value) ?? undefined} format={getBooleanFormat()} />
|
||||
) : property.formula?.resultAs === "date" ? (
|
||||
<RowDateCell value={value ? (value as Date) : undefined} format={getDateFormat()} />
|
||||
) : (
|
||||
<div>{value?.toString()}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import { ReactNode, useEffect, useState } from "react";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import InputCheckboxCards from "~/components/ui/input/InputCheckboxCards";
|
||||
|
||||
interface Props {
|
||||
name: string;
|
||||
title: string;
|
||||
options: { value: string; name: string | null; color: number }[];
|
||||
subtype?: "combobox" | "checkboxCards";
|
||||
required?: boolean;
|
||||
disabled?: boolean;
|
||||
value?: RowValueMultipleDto[];
|
||||
onSelected?: (item: RowValueMultipleDto[]) => void;
|
||||
hint?: ReactNode;
|
||||
help?: string;
|
||||
icon?: string;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
const PropertyMultiSelector = ({ name, title, options, subtype, disabled, value, onSelected, required }: Props) => {
|
||||
const [actualValue, setActualValue] = useState<(string | number)[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const selection = value?.map((f) => f.value) ?? [];
|
||||
if (selection.sort().join(",") !== actualValue.sort().join(",")) {
|
||||
setActualValue(selection);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value]);
|
||||
|
||||
useEffect(() => {
|
||||
// onSelected(actualValue);
|
||||
}, [actualValue, onSelected]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* actualValue: {JSON.stringify(actualValue)} */}
|
||||
{!subtype || subtype === "combobox" ? (
|
||||
<InputCombobox
|
||||
name={name}
|
||||
title={title}
|
||||
value={actualValue}
|
||||
onChange={setActualValue}
|
||||
options={options}
|
||||
disabled={disabled}
|
||||
withSearch={false}
|
||||
withLabel={true}
|
||||
required={required}
|
||||
/>
|
||||
) : subtype === "checkboxCards" ? (
|
||||
<InputCheckboxCards
|
||||
name={name}
|
||||
title={title}
|
||||
value={actualValue}
|
||||
onChange={setActualValue}
|
||||
options={options.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: f.name ?? f.value,
|
||||
};
|
||||
})}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
/>
|
||||
) : null}
|
||||
{actualValue?.map((item, idx) => {
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
type="hidden"
|
||||
name={name + `[]`}
|
||||
value={JSON.stringify({
|
||||
value: item,
|
||||
order: idx,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PropertyMultiSelector;
|
||||
@@ -1,44 +0,0 @@
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import { translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type OptionDto = { value: string; name: string | null };
|
||||
|
||||
interface Props {
|
||||
values: RowValueMultipleDto[] | null;
|
||||
options?: OptionDto[];
|
||||
entityName?: string;
|
||||
propertyName?: string;
|
||||
}
|
||||
export default function PropertyMultipleValueBadge({ values, options, entityName, propertyName }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
function getSelectedNames() {
|
||||
let names: string[] = [];
|
||||
if (values) {
|
||||
for (const value of values) {
|
||||
const option = options?.find((f) => f.value === value.value);
|
||||
if (option && entityName && propertyName) {
|
||||
names.push(translateSelectOptionLabel(t, i18n, entityName, propertyName, option));
|
||||
} else {
|
||||
names.push(option?.name ?? value.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
return (
|
||||
<div className="flex space-x-1">
|
||||
{getSelectedNames().join(", ") ?? <span className="text-gray-300"></span>}
|
||||
{/* {values?.map((value) => {
|
||||
return (
|
||||
<div
|
||||
key={value.id}
|
||||
className="relative mx-0.5 inline-flex max-w-sm shrink-0 select-none items-center space-x-0.5 overflow-x-auto rounded-full border border-border bg-secondary px-2 py-0.5"
|
||||
>
|
||||
<div className="text-xs font-medium text-muted-foreground">{value.value}</div>
|
||||
</div>
|
||||
);
|
||||
})} */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||