Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+4
-64
@@ -2,20 +2,14 @@ import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useParams, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant, getTenantBySlug, getTenantUsers, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import { getTenant, getTenantBySlug, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import UsersTable from "~/components/core/users/UsersTable";
|
||||
import { adminGetAllTenantUsers, getUser } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import {
|
||||
getOrPersistTenantSubscription,
|
||||
getTenantSubscription,
|
||||
updateTenantSubscriptionCustomerId,
|
||||
type TenantSubscriptionWithDetails,
|
||||
} from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getTenantSubscription, type TenantSubscriptionWithDetails } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { createStripeCustomer, isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { Fragment, useEffect, useRef } from "react";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
|
||||
@@ -25,12 +19,9 @@ import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { deleteAndCancelTenant, isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { findEntityByName, type EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { getAllTenantTypes, getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
@@ -46,8 +37,6 @@ type LoaderData = {
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
|
||||
};
|
||||
|
||||
@@ -59,11 +48,10 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, tenantSettingsEntity, tenantTypes] = await Promise.all([
|
||||
const [users, subscription, subscriptionProducts, tenantTypes] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(params.id ?? ""),
|
||||
getAllSubscriptionProducts(),
|
||||
findEntityByName({ tenantId: null, name: "tenantSettings" }),
|
||||
getTenantTypeOptions(),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
@@ -72,8 +60,6 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
tenantSettingsEntity,
|
||||
tenantTypes,
|
||||
};
|
||||
return data;
|
||||
@@ -153,23 +139,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
const tenantSettingsEntity = await findEntityByName({ tenantId: null, name: "tenantSettings" });
|
||||
if (tenantSettingsEntity) {
|
||||
try {
|
||||
await RowsApi.createCustom({
|
||||
entity: tenantSettingsEntity,
|
||||
tenantId: existing.id,
|
||||
t,
|
||||
form,
|
||||
row: existing?.tenantSettingsRow?.row as Parameters<typeof RowsApi.createCustom>[0]["row"],
|
||||
rowCreateInput: { tenantSettingsRow: { create: { tenantId: existing.id } } },
|
||||
request,
|
||||
});
|
||||
} catch {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.updateDetailsFailed") });
|
||||
}
|
||||
}
|
||||
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.updated",
|
||||
@@ -186,33 +155,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
return Response.json({
|
||||
success: t("settings.tenant.updated"),
|
||||
});
|
||||
} else if (action === "create-stripe-customer") {
|
||||
if (!tenant) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.invalidTenant") });
|
||||
}
|
||||
const tenantUsers = await getTenantUsers(params.id ?? "");
|
||||
if (tenantUsers.length === 0) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noUsers") });
|
||||
}
|
||||
const tenantOwner = tenantUsers.find((user) => user.type === TenantUserType.OWNER);
|
||||
if (!tenantOwner) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noOwner") });
|
||||
}
|
||||
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
|
||||
if (tenantSubscription.stripeCustomerId) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.customerAlreadySet") });
|
||||
}
|
||||
const stripeCustomer = await createStripeCustomer(tenantOwner.user.email, tenant.name);
|
||||
if (!stripeCustomer) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.createFailed") });
|
||||
}
|
||||
await updateTenantSubscriptionCustomerId(tenant.id, {
|
||||
stripeCustomerId: stripeCustomer.id,
|
||||
});
|
||||
const data: ActionData = {
|
||||
updateSubscriptionSuccess: t("admin.accounts.subscriptionCustomer.actions.created"),
|
||||
};
|
||||
return data;
|
||||
} else if (action === "delete-tenant") {
|
||||
await EventsService.create({
|
||||
request,
|
||||
@@ -274,7 +216,6 @@ export default function TenantRoute() {
|
||||
<UpdateTenantDetailsForm
|
||||
tenant={data.tenant}
|
||||
disabled={!getUserHasPermission(adminData, "admin.account.settings.update")}
|
||||
tenantSettingsEntity={data.tenantSettingsEntity}
|
||||
tenantTypes={data.tenantTypes}
|
||||
options={{
|
||||
canChangeType: true,
|
||||
@@ -328,7 +269,6 @@ export default function TenantRoute() {
|
||||
tenant={data.tenant}
|
||||
subscription={data.subscription}
|
||||
subscriptionProducts={data.subscriptionProducts}
|
||||
isStripeTest={data.isStripeTest}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -343,7 +283,7 @@ export default function TenantRoute() {
|
||||
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
translateIpAddressLogAction,
|
||||
translateIpAddressLogDescription,
|
||||
translateIpAddressLogError,
|
||||
} from "./ip-address-log-labels";
|
||||
|
||||
const t = ((key: string, options?: Record<string, unknown>) => (options?.value ? `${key}:${String(options.value)}` : key)) as TFunction;
|
||||
|
||||
describe("IP address log labels", () => {
|
||||
it("translates known action codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogAction(t, "login")).toBe("admin.accounts.ipAddresses.logs.actions.login");
|
||||
expect(translateIpAddressLogAction(t, "register")).toBe("admin.accounts.ipAddresses.logs.actions.register");
|
||||
expect(translateIpAddressLogAction(t, "reset")).toBe("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
expect(translateIpAddressLogAction(t, "forgot-password")).toBe("admin.accounts.ipAddresses.logs.actions.forgotPassword");
|
||||
expect(translateIpAddressLogAction(t, "reset-password")).toBe("admin.accounts.ipAddresses.logs.actions.resetPassword");
|
||||
expect(translateIpAddressLogAction(t, " custom-action ")).toBe("admin.accounts.ipAddresses.logs.actions.unknownWithValue:custom-action");
|
||||
expect(translateIpAddressLogAction(t, " ")).toBe("");
|
||||
});
|
||||
|
||||
it("translates known description codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogDescription(t, "registration-attempt")).toBe("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
expect(translateIpAddressLogDescription(t, "{empty email}")).toBe("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
expect(translateIpAddressLogDescription(t, "custom description")).toBe("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue:custom description");
|
||||
expect(translateIpAddressLogDescription(t, null)).toBe("");
|
||||
});
|
||||
|
||||
it("translates known error codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogError(t, "blacklisted")).toBe("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
expect(translateIpAddressLogError(t, "Unauthorized.")).toBe("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
expect(translateIpAddressLogError(t, "provider error")).toBe("admin.accounts.ipAddresses.errors.unknownWithValue:provider error");
|
||||
});
|
||||
});
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
export function translateIpAddressLogAction(t: TFunction, action?: string | null) {
|
||||
const normalized = action?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "login") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.login");
|
||||
}
|
||||
if (normalized === "register") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.register");
|
||||
}
|
||||
if (normalized === "reset") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
}
|
||||
if (normalized === "forgot-password") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.forgotPassword");
|
||||
}
|
||||
if (normalized === "reset-password") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.resetPassword");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.logs.actions.unknownWithValue", { value: normalized });
|
||||
}
|
||||
|
||||
export function translateIpAddressLogDescription(t: TFunction, description?: string | null) {
|
||||
const normalized = description?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "registration-attempt") {
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
}
|
||||
if (normalized === "{empty email}") {
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue", { value: normalized });
|
||||
}
|
||||
|
||||
export function translateIpAddressLogError(t: TFunction, error?: string | null) {
|
||||
const normalized = error?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "blacklisted" || normalized === "Blacklisted") {
|
||||
return t("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
}
|
||||
if (normalized === "unauthorized" || normalized === "Unauthorized" || normalized === "Unauthorized.") {
|
||||
return t("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.errors.unknownWithValue", { value: normalized });
|
||||
}
|
||||
+2
-2
@@ -6,7 +6,7 @@ import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { IpAddressLog } from "@toolctrl/db/prisma-browser";
|
||||
import { IpAddressLog } from "@hivegrid/db/prisma-browser";
|
||||
import { getAllIpAddressLogs } from "~/modules/ipAddress/db/ipAddressLogs.db.server";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
@@ -22,7 +22,7 @@ import DownArrow from "~/components/ui/icons/DownArrow";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { translateIpAddressLogAction, translateIpAddressLogDescription, translateIpAddressLogError } from "./ip-address-log-labels";
|
||||
import { translateIpAddressLogAction, translateIpAddressLogDescription, translateIpAddressLogError } from "~/modules/ipAddress/ipAddressLogLabels";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { IpAddress } from "@toolctrl/db/prisma-browser";
|
||||
import { IpAddress } from "@hivegrid/db/prisma-browser";
|
||||
import { getAllIpAddresses } from "~/modules/ipAddress/db/ipAddresses.db.server";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
|
||||
+4
-14
@@ -16,9 +16,6 @@ type AdminAccountSecurityTranslations = {
|
||||
adminUsers: string;
|
||||
accountUsers: string;
|
||||
};
|
||||
seed: {
|
||||
tab: string;
|
||||
};
|
||||
};
|
||||
ipAddresses: {
|
||||
actions: Record<string, string>;
|
||||
@@ -66,14 +63,13 @@ function readTranslations(locale: "en" | "de") {
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-addresses.tsx",
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-address-log-labels.ts",
|
||||
"apps/web/app/modules/ipAddress/ipAddressLogLabels.ts",
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-addresses.logs.tsx",
|
||||
"apps/web/app/routes/admin/accounts/blacklist.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/permissions/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/roles/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/roles/$id.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/seed.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users.tsx",
|
||||
@@ -103,26 +99,20 @@ describe("admin account security i18n", () => {
|
||||
expect(source).toContain('normalized === "unauthorized"');
|
||||
expect(source).toContain("formattedSelectedCount");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.actions.deleteSelectedLogs");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.seed.tab");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.roles");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.permissions");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.adminUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.accountUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.seed.missingTitle");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.permissions.errors.existingPermission");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.existingRole");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.updateFailed");
|
||||
expect(source).toContain("settings.tenant.errors.nameRequired");
|
||||
expect(source).toContain("settings.tenant.errors.slugRequired");
|
||||
expect(source).toContain("admin.accounts.errors.updateDetailsFailed");
|
||||
expect(source).toContain("models.blacklist.types.");
|
||||
expect(source).toContain("admin.accounts.subscriptionCustomer.errors.customerAlreadySet");
|
||||
expect(source).toContain("admin.accounts.subscriptionCustomer.actions.created");
|
||||
expect(source).toContain("admin.accounts.users.filters.hasLoggedIn");
|
||||
expect(source).toContain('app.shared.periods.LAST_N_MONTHS", { count: 6, formattedCount: "6" }');
|
||||
expect(source).toContain("admin.accounts.danger.deleteAccountTitle");
|
||||
expect(source).toContain("admin.permissions.entities.viewPage");
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.relativeDate");
|
||||
expect(source).toContain("models.permission.matrix.rolePermissionCount");
|
||||
@@ -147,9 +137,9 @@ describe("admin account security i18n", () => {
|
||||
expect(source).not.toContain("Role not found with ID:");
|
||||
expect(source).not.toContain("Account name must have at least 1 character");
|
||||
expect(source).not.toContain("Account slug must have at least 1 character");
|
||||
expect(source).not.toContain("Stripe Customer already set");
|
||||
expect(source).not.toContain("Could not create stripe customer");
|
||||
expect(source).not.toContain("Stripe customer created");
|
||||
expect(source).not.toContain("Mollie Customer already set");
|
||||
expect(source).not.toContain("Could not create billing customer");
|
||||
expect(source).not.toContain("Mollie customer created");
|
||||
expect(source).not.toContain('from "~/utils/shared/DateUtils"');
|
||||
expect(source).not.toContain("i.types.map((f) => f.title).join");
|
||||
expect(source).not.toContain("{i.error}");
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { listAdminBillingRows, requestManualBillingSync, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
|
||||
import { action, loader } from "./billing";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key) }),
|
||||
}));
|
||||
vi.mock("~/components/ui/buttons/ButtonPrimary", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/services/admin/billing-admin.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/billing-admin.server")>("~/services/admin/billing-admin.server");
|
||||
return {
|
||||
...actual,
|
||||
listAdminBillingRows: vi.fn(),
|
||||
requestManualBillingSync: vi.fn(),
|
||||
setTenantBillingPlanSeats: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
function requestWithForm(form: Record<string, string>) {
|
||||
return new Request("https://admin.example.test/accounts/billing", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams(form),
|
||||
});
|
||||
}
|
||||
|
||||
describe("admin accounts billing route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key),
|
||||
} as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "user_1", email: "ops@hivegrid.de" } as never);
|
||||
vi.mocked(listAdminBillingRows).mockResolvedValue([
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
tenantName: "Acme",
|
||||
tenantSlug: "acme",
|
||||
status: "active",
|
||||
readOnly: false,
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
lagoCustomerId: "lago_1",
|
||||
mollieCustomerId: "mollie_1",
|
||||
lastInvoiceExternalId: "inv_1",
|
||||
lastPaymentExternalId: "pay_1",
|
||||
currentPeriodStart: null,
|
||||
currentPeriodEnd: null,
|
||||
pastDueSince: null,
|
||||
frozenAt: null,
|
||||
cancelledAt: null,
|
||||
entitlementCount: 1,
|
||||
},
|
||||
] as never);
|
||||
});
|
||||
|
||||
it("checks subscription permission before loading billing rows", async () => {
|
||||
const body = await loader({
|
||||
request: new Request("https://admin.example.test/accounts/billing"),
|
||||
params: {},
|
||||
context: {},
|
||||
} as LoaderFunctionArgs);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.subscription");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(listAdminBillingRows).mock.invocationCallOrder[0]);
|
||||
expect(body.vm.status).toBe("ready");
|
||||
expect(body.vm.data.rows[0].tenantName).toBe("Acme");
|
||||
});
|
||||
|
||||
it("routes plan/seat override actions to the admin service", async () => {
|
||||
const response = (await action({
|
||||
request: requestWithForm({
|
||||
csrf: "csrf",
|
||||
action: "set-plan-seats",
|
||||
tenantId: "tenant_1",
|
||||
planCode: "pro",
|
||||
seatQuantity: "7",
|
||||
reason: "Sonderkunde",
|
||||
}),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.planSeatsUpdated" });
|
||||
expect(setTenantBillingPlanSeats).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
planCode: "pro",
|
||||
seatQuantity: "7",
|
||||
reason: "Sonderkunde",
|
||||
actorUserId: "user_1",
|
||||
actorEmail: "ops@hivegrid.de",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("routes manual provider sync actions to the admin service", async () => {
|
||||
const response = (await action({
|
||||
request: requestWithForm({ csrf: "csrf", action: "request-sync", tenantId: "tenant_1", provider: "lago" }),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.syncRequested:admin.billing.providers.lago" });
|
||||
expect(requestManualBillingSync).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", provider: "lago", actorUserId: "user_1" }));
|
||||
});
|
||||
});
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
import { buildAdminBillingVM, type AdminBillingRow } from "@hivegrid/view-models";
|
||||
import { ActionFunctionArgs, Form, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData, useNavigation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import {
|
||||
listAdminBillingRows,
|
||||
requestManualBillingSync,
|
||||
setTenantBillingPlanSeats,
|
||||
AdminBillingError,
|
||||
type BillingSyncProvider,
|
||||
} from "~/services/admin/billing-admin.server";
|
||||
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildAdminBillingVM>;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
const vm = buildAdminBillingVM({ rows: await listAdminBillingRows() });
|
||||
return {
|
||||
title: `${t("admin.billing.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData) {
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
|
||||
function billingErrorKey(error: unknown): string {
|
||||
if (error instanceof AdminBillingError || error instanceof AdminActionInputError) return error.i18nKey;
|
||||
return "admin.billing.errors.UNKNOWN";
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const tenantId = form.get("tenantId")?.toString() ?? "";
|
||||
const userInfo = await getUserInfo(request);
|
||||
const actor = await getUser(userInfo.userId);
|
||||
|
||||
try {
|
||||
if (action === "set-plan-seats") {
|
||||
await setTenantBillingPlanSeats({
|
||||
tenantId,
|
||||
planCode: form.get("planCode")?.toString() ?? "",
|
||||
seatQuantity: form.get("seatQuantity")?.toString() ?? "",
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.planSeatsUpdated") } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (action === "request-sync") {
|
||||
const provider = form.get("provider")?.toString() as BillingSyncProvider;
|
||||
if (provider !== "lago" && provider !== "mollie") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
await requestManualBillingSync({
|
||||
tenantId,
|
||||
provider,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.syncRequested", { provider: t(`admin.billing.providers.${provider}`) }) } satisfies ActionData);
|
||||
}
|
||||
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
} catch (error) {
|
||||
return badRequest({ error: t(billingErrorKey(error)) });
|
||||
}
|
||||
};
|
||||
|
||||
function FieldValue({ label, value }: { label: string; value: string | number | null }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="text-muted-foreground text-xs font-medium uppercase">{label}</div>
|
||||
<div className="text-foreground text-sm break-all">{value || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SyncButtons({ row, csrf }: { row: AdminBillingRow; csrf?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(["lago", "mollie"] as const).map((provider) => (
|
||||
<Form key={provider} method="post">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="request-sync" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<input type="hidden" name="provider" value={provider} />
|
||||
<ButtonSecondary type="submit" className="h-8 px-3 text-xs">
|
||||
{t("admin.billing.actions.requestProviderSync", { provider: t(`admin.billing.providers.${provider}`) })}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlanSeatForm({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Form method="post" className="grid gap-2 md:grid-cols-[minmax(120px,1fr)_96px_minmax(180px,1.5fr)_auto]">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="set-plan-seats" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.planCode")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="planCode"
|
||||
defaultValue={row.planCode ?? ""}
|
||||
placeholder={t("admin.billing.placeholders.planCode")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.seats")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="seatQuantity"
|
||||
type="number"
|
||||
min={1}
|
||||
defaultValue={row.seatQuantity ?? 1}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.reason")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="reason"
|
||||
placeholder={t("admin.billing.placeholders.reason")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end">
|
||||
<ButtonPrimary type="submit" disabled={loading} className="h-9 px-3 text-xs">
|
||||
{t("admin.billing.actions.saveOverride")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function BillingRowCard({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="border-border bg-background rounded-md border p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-foreground text-base font-semibold">{row.tenantName}</div>
|
||||
<div className="text-muted-foreground text-sm">{row.tenantSlug}</div>
|
||||
</div>
|
||||
<div className="bg-muted text-foreground rounded-full px-3 py-1 text-xs font-medium">{t(row.statusLabelKey)}</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-4">
|
||||
<FieldValue label={t("admin.billing.fields.planCode")} value={row.planCode} />
|
||||
<FieldValue label={t("admin.billing.fields.seats")} value={row.seatQuantity} />
|
||||
<FieldValue label={t("admin.billing.fields.lastInvoice")} value={row.lastInvoiceExternalId} />
|
||||
<FieldValue label={t("admin.billing.fields.lastPayment")} value={row.lastPaymentExternalId} />
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-3">
|
||||
<FieldValue label={t("admin.billing.fields.readOnlyReason")} value={t(row.readOnlyReasonKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.recoveryHint")} value={t(row.recoveryHintKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.providers")} value={t(row.providerSummaryKey)} />
|
||||
</div>
|
||||
|
||||
<div className="border-border mt-4 border-t pt-4">
|
||||
<PlanSeatForm row={row} csrf={csrf} loading={loading} />
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<SyncButtons row={row} csrf={csrf} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminBillingRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const rootData = useRootData();
|
||||
const loading = navigation.state === "submitting";
|
||||
const rows = data.vm.status === "ready" ? data.vm.data.rows : [];
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.billing.title")} fullWidth>
|
||||
<div className="space-y-4">
|
||||
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
||||
<div className="text-muted-foreground text-sm">{t("admin.billing.description")}</div>
|
||||
{actionData?.success && <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div>}
|
||||
{actionData?.error && <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div>}
|
||||
</div>
|
||||
|
||||
{data.vm.status === "empty" ? (
|
||||
<div className="border-border bg-background rounded-md border p-6">
|
||||
<div className="font-medium">{t("admin.billing.empty.headline")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.billing.empty.body")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => (
|
||||
<BillingRowCard key={row.tenantId} row={row} csrf={rootData.csrf} loading={loading} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ import { Form, useNavigation, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { addToBlacklist, deleteFromBlacklist, getBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { Blacklist } from "@toolctrl/db/prisma-browser";
|
||||
import { Blacklist } from "@hivegrid/db/prisma-browser";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
|
||||
+4
-26
@@ -3,13 +3,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./index";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { findEntityByName } from "~/utils/db/entities/entities.db.server";
|
||||
import { adminGetAllTenantsWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getStripeInvoices } from "~/utils/stripe.server";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
@@ -29,7 +27,6 @@ vi.mock("react-router", async () => {
|
||||
|
||||
vi.mock("~/components/core/tenants/DeactivateTenantModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/tenants/TenantsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/entities/rows/RowProperties", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
||||
vi.mock("~/components/ui/forms/FormGroup", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputCheckboxWithDescription", () => ({ default: () => null }));
|
||||
@@ -52,7 +49,6 @@ vi.mock("~/utils/api/.server/TenantsApi", () => ({ TenantsApi: { create: vi.fn()
|
||||
vi.mock("~/utils/app/UrlUtils", () => ({ default: { slugify: (value: string) => value.toLowerCase() } }));
|
||||
vi.mock("~/utils/csrf", () => ({ appendCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({ useAppOrAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/db/entities/entities.db.server", () => ({ findEntityByName: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
@@ -69,18 +65,13 @@ vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
}));
|
||||
vi.mock("~/utils/services/tenantService", () => ({ getExistingSlug: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/stripe.server", () => ({
|
||||
getStripeInvoices: vi.fn(),
|
||||
isStripeTestMode: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
const tenants = [
|
||||
{
|
||||
id: "tenant-1",
|
||||
name: "Acme",
|
||||
slug: "acme",
|
||||
createdAt: new Date("2026-05-01T00:00:00.000Z"),
|
||||
subscription: { stripeCustomerId: "cus_1" },
|
||||
subscription: { billingProviderCustomerId: "cus_1" },
|
||||
},
|
||||
{
|
||||
id: "tenant-2",
|
||||
@@ -99,7 +90,7 @@ function callLoader(url = "https://admin.example.test/accounts") {
|
||||
describe("admin accounts invoice hydration", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([] as never);
|
||||
@@ -110,27 +101,14 @@ describe("admin accounts invoice hydration", () => {
|
||||
items: tenants,
|
||||
pagination: { page: 1, pageSize: 10, totalItems: tenants.length, totalPages: 1 },
|
||||
} as never);
|
||||
vi.mocked(findEntityByName).mockResolvedValue(null as never);
|
||||
vi.mocked(getStripeInvoices).mockResolvedValue([{ id: "in_1", customer: "cus_1" }] as never);
|
||||
});
|
||||
|
||||
it("does not load Stripe invoices for the default tenant list", async () => {
|
||||
it("loads the default tenant list without processor invoice hydration", async () => {
|
||||
const response = await callLoader();
|
||||
const body = await response.json();
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.view");
|
||||
expect(getStripeInvoices).not.toHaveBeenCalled();
|
||||
expect(body.tenantInvoices).toBeUndefined();
|
||||
expect(body.includeInvoices).toBe(false);
|
||||
});
|
||||
|
||||
it("loads invoices only when includeInvoices is explicitly requested", async () => {
|
||||
const response = await callLoader("https://admin.example.test/accounts?includeInvoices=true");
|
||||
const body = await response.json();
|
||||
|
||||
expect(getStripeInvoices).toHaveBeenCalledTimes(1);
|
||||
expect(getStripeInvoices).toHaveBeenCalledWith("cus_1", { limit: 10 });
|
||||
expect(body.tenantInvoices).toEqual([{ id: "in_1", customer: "cus_1" }]);
|
||||
expect(body.includeInvoices).toBe(true);
|
||||
expect(body).not.toHaveProperty("includeInvoices");
|
||||
});
|
||||
});
|
||||
+5
-62
@@ -1,5 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { adminGetAllTenantsWithUsage, createTenantUser, TenantSimple, TenantWithUsage, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import TenantsTable from "~/components/core/tenants/TenantsTable";
|
||||
@@ -11,24 +11,20 @@ import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropert
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useActionData, useLocation, useNavigation, useSubmit } from "react-router";
|
||||
import { useActionData, useNavigation, useSubmit } from "react-router";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import type Stripe from "stripe";
|
||||
import { getStripeInvoices, isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { EntityWithDetails, findEntityByName } from "~/utils/db/entities/entities.db.server";
|
||||
import { TenantsApi } from "~/utils/api/.server/TenantsApi";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import RowProperties from "~/components/entities/rows/RowProperties";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getExistingSlug } from "~/utils/services/tenantService";
|
||||
import DeactivateTenantModal from "~/components/core/tenants/DeactivateTenantModal";
|
||||
@@ -36,12 +32,8 @@ import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { mapWithConcurrency } from "@toolctrl/foundation";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
const ADMIN_TENANT_INVOICE_HYDRATION_CONCURRENCY = 3;
|
||||
const ADMIN_TENANT_INVOICE_LIST_LIMIT = 10;
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
@@ -49,10 +41,6 @@ type LoaderData = {
|
||||
items: TenantWithUsage[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
tenantInvoices?: Stripe.Invoice[];
|
||||
includeInvoices: boolean;
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
@@ -97,31 +85,11 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await time(adminGetAllTenantsWithUsage(filters, currentPagination), "adminGetAllTenantsWithUsage");
|
||||
const includeInvoices = ["1", "true"].includes((urlSearchParams.get("includeInvoices") ?? "").toLowerCase());
|
||||
|
||||
let tenantInvoices: Stripe.Invoice[] | undefined;
|
||||
if (includeInvoices) {
|
||||
tenantInvoices = [];
|
||||
await time(
|
||||
mapWithConcurrency(items, ADMIN_TENANT_INVOICE_HYDRATION_CONCURRENCY, async (item) => {
|
||||
if (item.subscription?.stripeCustomerId) {
|
||||
const invoices = await getStripeInvoices(item.subscription.stripeCustomerId, { limit: ADMIN_TENANT_INVOICE_LIST_LIMIT });
|
||||
tenantInvoices?.push(...invoices);
|
||||
}
|
||||
}),
|
||||
"getStripeInvoices[adminTenantList]"
|
||||
);
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.plural")} | ${process.env.APP_NAME}`,
|
||||
items: items.sort((a, b) => (a.createdAt > b.createdAt ? -1 : 1)),
|
||||
filterableProperties,
|
||||
pagination,
|
||||
tenantInvoices,
|
||||
includeInvoices,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
tenantSettingsEntity: await findEntityByName({ tenantId: null, name: "tenantSettings" }),
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
@@ -163,7 +131,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
if (!slug || existingSlug) {
|
||||
return Response.json({ error: t("shared.slugTaken") }, { status: 400 });
|
||||
}
|
||||
const { tenant, user } = await TenantsApi.create({ request, form, name, slug });
|
||||
const { tenant, user } = await TenantsApi.create({ request, name, slug });
|
||||
const addMySelf = Boolean(form.get("addMySelf"));
|
||||
if (addMySelf) {
|
||||
const roles = await getAllRoles("app");
|
||||
@@ -192,11 +160,9 @@ export default function AdminTenantsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
|
||||
const [deactivatingTenant, setDeactivatingTenant] = useState<TenantWithUsage>();
|
||||
const [creatingNewAccount, setCreatingNewAccount] = useState(false);
|
||||
const invoiceToggleHref = buildIncludeInvoicesHref(location.search, !data.includeInvoices);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.createdTenantId) {
|
||||
@@ -231,11 +197,6 @@ export default function AdminTenantsRoute() {
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button type="button" variant="outline" size="sm" asChild>
|
||||
<Link to={invoiceToggleHref}>
|
||||
{t(data.includeInvoices ? "shared.hide" : "shared.show")} {t("app.subscription.invoices.title")}
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
@@ -251,8 +212,6 @@ export default function AdminTenantsRoute() {
|
||||
<TenantsTable
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
tenantInvoices={data.tenantInvoices}
|
||||
isStripeTest={data.isStripeTest}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
@@ -281,7 +240,7 @@ export default function AdminTenantsRoute() {
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">
|
||||
<CreateTenantForm tenantSettingsEntity={data.tenantSettingsEntity} />
|
||||
<CreateTenantForm />
|
||||
</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
@@ -291,18 +250,7 @@ export default function AdminTenantsRoute() {
|
||||
);
|
||||
}
|
||||
|
||||
function buildIncludeInvoicesHref(search: string, includeInvoices: boolean): string {
|
||||
const params = new URLSearchParams(search);
|
||||
if (includeInvoices) {
|
||||
params.set("includeInvoices", "true");
|
||||
} else {
|
||||
params.delete("includeInvoices");
|
||||
}
|
||||
const nextSearch = params.toString();
|
||||
return nextSearch ? `?${nextSearch}` : "?";
|
||||
}
|
||||
|
||||
function CreateTenantForm({ tenantSettingsEntity }: { tenantSettingsEntity: EntityWithDetails | null }) {
|
||||
function CreateTenantForm() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
@@ -330,11 +278,6 @@ function CreateTenantForm({ tenantSettingsEntity }: { tenantSettingsEntity: Enti
|
||||
<div className="space-y-3">
|
||||
<InputText ref={firstInput} autoFocus name="name" title={t("shared.name")} value={name} setValue={setName} required />
|
||||
<InputText name="slug" title={t("shared.slug")} value={slug} setValue={setSlug} required onBlur={() => setSlug(UrlUtils.slugify(slug))} />
|
||||
{tenantSettingsEntity && (
|
||||
<div className="col-span-6 sm:col-span-6">
|
||||
<RowProperties entity={tenantSettingsEntity} item={null} />
|
||||
</div>
|
||||
)}
|
||||
<InputCheckboxWithDescription
|
||||
name="addMySelf"
|
||||
title={t("admin.accounts.create.addMyselfAsOwner")}
|
||||
|
||||
-4
@@ -69,10 +69,6 @@ export default function AdminRolesRoute() {
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.accountUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.seed.tab"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/seed", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRole } from "~/utils/db/permissions/roles.db.server";
|
||||
import { adminGetAllTenantUsers, adminGetAllUsers, getUser, UserWithRoles } from "~/utils/db/users.db.server";
|
||||
import UserRolesTable from "~/components/core/roles/UserRolesTable";
|
||||
import { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { useEffect, useState } from "react";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
|
||||
-1
@@ -56,7 +56,6 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
description,
|
||||
type,
|
||||
isDefault: false,
|
||||
entityId: null,
|
||||
};
|
||||
const permission = await createPermission(data);
|
||||
await setPermissionRoles(permission.id, roles);
|
||||
|
||||
-207
@@ -1,207 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useActionData, useLoaderData, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useRef } from "react";
|
||||
import {
|
||||
CreatePermissionDto,
|
||||
CreateRoleDto,
|
||||
defaultAdminRoles,
|
||||
defaultAppRoles,
|
||||
defaultPermissions,
|
||||
seedRolesAndPermissions,
|
||||
} from "~/utils/services/rolesAndPermissionsService";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getAllRolesNames } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllPermissionsIdsAndNames } from "~/utils/db/permissions/permissions.db.server";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { toast } from "sonner";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
roles: {
|
||||
all: CreateRoleDto[];
|
||||
missing: CreateRoleDto[];
|
||||
};
|
||||
permissions: {
|
||||
all: CreatePermissionDto[];
|
||||
missing: CreatePermissionDto[];
|
||||
};
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const roles: { all: CreateRoleDto[]; missing: CreateRoleDto[] } = {
|
||||
all: [...defaultAppRoles, ...defaultAdminRoles],
|
||||
missing: [],
|
||||
};
|
||||
const createdRoles = await getAllRolesNames();
|
||||
roles.all.forEach((role) => {
|
||||
const existing = createdRoles.find((r) => r.name === role.name);
|
||||
if (!existing) {
|
||||
roles.missing.push(role);
|
||||
}
|
||||
});
|
||||
|
||||
const permissions: { all: CreatePermissionDto[]; missing: CreatePermissionDto[] } = {
|
||||
all: defaultPermissions,
|
||||
missing: [],
|
||||
};
|
||||
const createdPermissions = await getAllPermissionsIdsAndNames();
|
||||
permissions.all.forEach((permission) => {
|
||||
const existing = createdPermissions.find((r) => r.name === permission.name);
|
||||
if (!existing) {
|
||||
permissions.missing.push(permission);
|
||||
}
|
||||
});
|
||||
const data: LoaderData = {
|
||||
title: t("admin.accounts.rolesAndPermissions.seed.metaTitle", { appName: process.env.APP_NAME }),
|
||||
roles,
|
||||
permissions,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "seed") {
|
||||
try {
|
||||
await seedRolesAndPermissions();
|
||||
return Response.json({ success: t("admin.accounts.rolesAndPermissions.seed.actions.seeded") }, { status: 200 });
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return Response.json({ error: t("shared.unexpectedError") }, { status: 500 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
const submit = useSubmit();
|
||||
|
||||
const modalConfirmSeed = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onSeed() {
|
||||
modalConfirmSeed.current?.show(
|
||||
t("admin.accounts.rolesAndPermissions.seed.confirm.title"),
|
||||
t("shared.confirm"),
|
||||
t("shared.back"),
|
||||
t("admin.accounts.rolesAndPermissions.seed.confirm.description")
|
||||
);
|
||||
}
|
||||
|
||||
function onConfirmSeed() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "seed");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
<InputGroup title={t("admin.accounts.rolesAndPermissions.seed.missingTitle")}>
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-foreground text-lg font-medium">{t("models.role.plural")}</h3>
|
||||
<TableSimple
|
||||
items={data.roles.missing}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("shared.type"),
|
||||
value: (i) => i.type,
|
||||
},
|
||||
{
|
||||
name: "name",
|
||||
title: t("shared.name"),
|
||||
value: (i) => i.name,
|
||||
className: "w-full",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<h3 className="text-foreground text-lg font-medium">{t("models.permission.plural")}</h3>
|
||||
<TableSimple
|
||||
items={data.permissions.missing}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("shared.type"),
|
||||
value: (i) => i.type,
|
||||
},
|
||||
{
|
||||
name: "name",
|
||||
title: t("shared.name"),
|
||||
value: (i) => i.name,
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("shared.description"),
|
||||
value: (i) => i.description,
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "inRoles",
|
||||
title: t("models.permission.inRoles"),
|
||||
value: (i) => i.inRoles.join(", "),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonSecondary disabled={!getUserHasPermission(appOrAdminData, "admin.roles.update")} destructive onClick={onSeed}>
|
||||
{t("admin.accounts.rolesAndPermissions.seed.button", {
|
||||
rolesMissing: data.roles.missing.length,
|
||||
rolesTotal: data.roles.all.length,
|
||||
permissionsMissing: data.permissions.missing.length,
|
||||
permissionsTotal: data.permissions.all.length,
|
||||
})}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<ConfirmModal ref={modalConfirmSeed} onYes={onConfirmSeed} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+1
-1
@@ -48,7 +48,7 @@ describe("admin account subscription i18n", () => {
|
||||
expect(revenue).not.toContain('title={"Revenue"}');
|
||||
expect(revenue).not.toContain(" usd");
|
||||
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.stripeId");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.billingProviderId");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currentPeriod");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.canceledAt");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currency");
|
||||
|
||||
+13
-3
@@ -7,18 +7,28 @@ import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { StripeRevenueByProductPriceCurrency, getStripeRevenueByProductPriceCurrency } from "~/utils/stripe.server";
|
||||
|
||||
type RevenueByProductPriceCurrency = {
|
||||
product: string;
|
||||
billingPeriod: SubscriptionBillingPeriod;
|
||||
currency: string;
|
||||
revenueInCurrency: number;
|
||||
revenueUsd: number;
|
||||
revenuePercentageUsd: number;
|
||||
count: number;
|
||||
countPercentage: number;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: StripeRevenueByProductPriceCurrency[];
|
||||
items: RevenueByProductPriceCurrency[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: t("admin.accounts.revenue.metaTitle", { appName: process.env.APP_NAME }) }],
|
||||
items: await getStripeRevenueByProductPriceCurrency(),
|
||||
items: [],
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
+1
-4
@@ -16,11 +16,10 @@ import {
|
||||
getAllSubscriptionProducts,
|
||||
getAllTenantSubscriptionProducts,
|
||||
type TenantSubscriptionProductWithTenant,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
@@ -30,7 +29,6 @@ type LoaderData = {
|
||||
items: TenantSubscriptionProductWithTenant[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
isStripeTest: boolean;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
@@ -90,7 +88,6 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { adminGetTenantSubscriptionProductById, type TenantSubscriptionProductWithTenant } from "@toolctrl/db/subscriptions.server";
|
||||
import { adminGetTenantSubscriptionProductById, type TenantSubscriptionProductWithTenant } from "@hivegrid/db/subscriptions.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
@@ -40,7 +40,7 @@ export default function () {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputText title={t("models.tenant.object")} defaultValue={data.item.tenantSubscription.tenant.name} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.stripeId")} defaultValue={data.item.stripeSubscriptionId ?? ""} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.billingProviderId")} defaultValue={data.item.billingProviderSubscriptionId ?? ""} readOnly />
|
||||
<InputText title={t("models.subscriptionProduct.object")} defaultValue={t(data.item.subscriptionProduct.title)} readOnly />
|
||||
<InputText title={t("models.subscription.quantity")} defaultValue={data.item.quantity?.toString() ?? ""} readOnly />
|
||||
{data.item.prices.length > 0 && (
|
||||
|
||||
+4
-4
@@ -29,7 +29,7 @@ vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
vi.mock("~/utils/app/HostRouting.server", () => ({
|
||||
getHostRoutingContextFromRequest: vi.fn(() => "admin"),
|
||||
}));
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({ routing: undefined }),
|
||||
}));
|
||||
vi.mock("~/components/core/users/UsersTable", () => ({ default: () => null }));
|
||||
@@ -78,14 +78,14 @@ vi.mock("~/utils/session.server", () => ({
|
||||
setLoggedUser: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/impersonation-audit.server", () => ({
|
||||
vi.mock("@hivegrid/db/impersonation-audit.server", () => ({
|
||||
createImpersonationAudit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
|
||||
+4
-4
@@ -19,7 +19,7 @@ import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropert
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { adminGetAllTenantsIdsAndNames, getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import type { Log } from "@toolctrl/db/prisma-browser";
|
||||
import type { Log } from "@hivegrid/db/prisma-browser";
|
||||
import { getLastUserLogsByUserIds } from "~/utils/db/logs.db.server";
|
||||
import { useNavigate, useOutlet } from "react-router";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
@@ -33,10 +33,10 @@ import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAppPath, absoluteAppRootPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
|
||||
+3
-4
@@ -15,8 +15,8 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
import { formatDate, useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
@@ -76,8 +76,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
// Capacitor track patch (#65 → unblocks main): the dsgvo-bulk-ops
|
||||
// agent referenced a non-existent `admin.users.update` permission;
|
||||
// The dsgvo-bulk-ops agent referenced a non-existent `admin.users.update` permission;
|
||||
// the seed catalog only exposes `admin.users.view`. Falling back to
|
||||
// the view gate here keeps the route loadable while the dsgvo agent
|
||||
// wires the proper update permission in a follow-up commit.
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useState } from "react";
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
Reference in new issue
Block a user