Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/crm.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm.tsx",
|
||||
"apps/web/app/routes/admin/crm/index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm/index.tsx",
|
||||
"apps/web/app/routes/admin/crm/sync.tsx",
|
||||
"apps/web/app/modules/crm/services/CrmService.ts",
|
||||
];
|
||||
const crmRouteFiles = [
|
||||
"apps/web/app/routes/admin/crm.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm.tsx",
|
||||
"apps/web/app/routes/admin/crm/index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm/index.tsx",
|
||||
];
|
||||
|
||||
describe("CRM i18n", () => {
|
||||
it("uses semantic keys for overview and sync chrome", () => {
|
||||
const sources = sourceFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
|
||||
expect(sources).toContain("pages.adminCrm.metaTitle");
|
||||
expect(sources).toContain('getTranslations(request)');
|
||||
expect(sources).toContain("pages.adminCrm.contacts");
|
||||
expect(sources).toContain("pages.adminCrm.createOpportunity");
|
||||
expect(sources).toContain("pages.adminCrm.openOpportunitiesCount");
|
||||
expect(sources).toContain("pages.adminCrm.columns.expectedCloseDate");
|
||||
expect(sources).toContain("admin.crm.sync.actions.syncContact");
|
||||
expect(sources).toContain("admin.crm.sync.actions.createdContactsPart");
|
||||
expect(sources).toContain("admin.crm.sync.actions.updatedContactsPart");
|
||||
expect(sources).toContain("formattedCount: formatNumber");
|
||||
expect(sources).toContain("formatters.number(filtered.length)");
|
||||
expect(sources).toContain("admin.crm.sync.sources.unknown");
|
||||
expect(sources).toContain("admin.crm.sync.table.marketingSubscriber");
|
||||
expect(sources).toContain("crm.newsletter.errors.integrationMissing");
|
||||
expect(sources).toContain("CrmConfigurationError");
|
||||
expect(sources).toContain("CrmProviderError");
|
||||
expect(sources).toContain("admin.crm.sync.errors.providerFetchFailed");
|
||||
expect(sources).toContain("crm.newsletter.subscribed");
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
|
||||
const crmRoutes = crmRouteFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
expect(crmRoutes).not.toContain('from "i18next"');
|
||||
expect(crmRoutes).not.toContain("i18nT");
|
||||
});
|
||||
|
||||
it("does not keep raw visible CRM labels or legacy overview formatting in source", () => {
|
||||
const forbidden = [
|
||||
">from {NumberUtils.intFormat",
|
||||
"NumberUtils.intFormat(data.summary",
|
||||
"NumberUtils.numberFormat(data.summary",
|
||||
"<div>${",
|
||||
'return "Sync"',
|
||||
'return "Sync 1 contact"',
|
||||
'syncContact", { count: filtered.length })',
|
||||
'createdContacts", { count: progress.created })',
|
||||
'updatedContacts", { count: progress.updated })',
|
||||
'createdAndUpdatedContacts", { created: progress.created, updated: progress.updated })',
|
||||
'return "?"',
|
||||
'title="Sync"',
|
||||
'title: "Source"',
|
||||
'title: "Status"',
|
||||
'title: "User"',
|
||||
'title: "Contact"',
|
||||
'title="Synced"',
|
||||
'title="User"',
|
||||
'return { error: "No CRM or ConvertKit integration configured" }',
|
||||
"CRM is not configured:",
|
||||
'Entity "',
|
||||
"load the template",
|
||||
'must be "All" or',
|
||||
"return { error: response.message }",
|
||||
"ConvertKit error:",
|
||||
"return { error: e.message }",
|
||||
'return { success: "Subscribed" }',
|
||||
"<Link\n to={params.tenant ? UrlUtils.getModulePath(params, \"crm/opportunities/new\") : adminPath(`crm/opportunities/new`, { mode: \"host-aware\" })}\n className=\"text-foreground bg-secondary hover:bg-secondary/90 rounded-full p-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600\"\n >",
|
||||
];
|
||||
|
||||
for (const file of sourceFiles) {
|
||||
const source = fs.readFileSync(path.join(repoRoot, file), "utf8");
|
||||
for (const literal of forbidden) {
|
||||
expect(source).not.toContain(literal);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RowsList from "~/components/entities/rows/RowsList";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import CrmService, { CrmSummaryDto } from "~/modules/crm/services/CrmService";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { RowDisplayDefaultProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
summary: CrmSummaryDto;
|
||||
routes: EntitiesApi.Routes;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const data: LoaderData = {
|
||||
title: t("pages.adminCrm.metaTitle", { appName: process.env.APP_NAME }),
|
||||
summary: await CrmService.getSummary(tenantId),
|
||||
routes: EntitiesApi.getNoCodeRoutes({ request, params }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("shared.overview")}</h3>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-4">
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/companies") : adminPath("crm/companies", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.companies")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.companies, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/contacts") : adminPath("crm/contacts", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.contacts")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.contacts, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/opportunities") : adminPath("crm/opportunities", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground flex items-center space-x-2 truncate text-xs font-medium uppercase">
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<div>{t("pages.adminCrm.opportunities")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>{formatters.currency(data.summary.opportunities.value, "USD", { maximumFractionDigits: 0 })}</div>
|
||||
<div className="text-muted-foreground text-xs font-normal lowercase">
|
||||
{t("pages.adminCrm.openOpportunitiesCount", {
|
||||
count: data.summary.opportunities.count,
|
||||
formattedCount: formatters.number(data.summary.opportunities.count, { maximumFractionDigits: 0 }),
|
||||
})}
|
||||
</div>
|
||||
</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/submissions") : adminPath("crm/submissions", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.submissions")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.submissions, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
</dl>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-muted-foreground text-sm font-medium">{t("pages.adminCrm.opportunities")}</h3>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/opportunities/new") : adminPath(`crm/opportunities/new`, { mode: "host-aware" })}
|
||||
className="text-foreground bg-secondary hover:bg-secondary/90 rounded-full p-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600"
|
||||
aria-label={t("pages.adminCrm.createOpportunity")}
|
||||
>
|
||||
<PlusIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</Link>
|
||||
</div>
|
||||
<RowsList
|
||||
view="board"
|
||||
entity="opportunity"
|
||||
items={data.summary.data.openOpportunities}
|
||||
readOnly={true}
|
||||
columns={[
|
||||
{ name: "name", title: t("pages.adminCrm.columns.name"), visible: true },
|
||||
{ name: "value", title: t("pages.adminCrm.columns.value"), visible: true },
|
||||
{ name: "expectedCloseDate", title: t("pages.adminCrm.columns.expectedCloseDate"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_AT, title: t("shared.createdAt"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_BY, title: t("shared.createdBy"), visible: true },
|
||||
]}
|
||||
routes={data.routes}
|
||||
onClickRoute={(i) => UrlUtils.getModulePath(params, `crm/opportunities/${i.id}`)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-muted-foreground text-sm font-medium">{t("pages.adminCrm.submissions")}</h3>
|
||||
</div>
|
||||
<RowsList
|
||||
view="table"
|
||||
entity="submission"
|
||||
items={data.summary.data.submissions}
|
||||
readOnly={true}
|
||||
columns={[
|
||||
{ name: RowDisplayDefaultProperty.FOLIO, title: "", visible: true },
|
||||
{ name: "users", title: t("pages.adminCrm.columns.users"), visible: true },
|
||||
{ name: "message", title: t("pages.adminCrm.columns.message"), visible: true },
|
||||
{ name: "parent.contact", title: t("pages.adminCrm.columns.contact"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_AT, title: t("shared.createdAt"), visible: true },
|
||||
]}
|
||||
routes={data.routes}
|
||||
onClickRoute={(i) => UrlUtils.getModulePath(params, `crm/submissions/${i.id}`)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import { ReloadIcon } from "~/components/ui/icons/vendor";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import toast from "react-hot-toast";
|
||||
import { ContactStatus } from "~/application/dtos/crm/ContactStatus";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import CrmService, { CrmConfigurationError, CrmProviderError, UserInCrmDto } from "~/modules/crm/services/CrmService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { formatNumber, useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
users: UserInCrmDto[];
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
try {
|
||||
await CrmService.validate(tenantId);
|
||||
} catch (error) {
|
||||
if (error instanceof CrmConfigurationError) {
|
||||
throw new Response(t("crm.newsletter.errors.integrationMissing"), { status: 503 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
let usersInCrm: UserInCrmDto[];
|
||||
try {
|
||||
usersInCrm = await CrmService.getUsersInCrm({
|
||||
invalidateCache: searchParams.get("cache") === "clear",
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof CrmProviderError) {
|
||||
throw new Response(t("admin.crm.sync.errors.providerFetchFailed"), { status: 502 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const data: LoaderData = {
|
||||
users: usersInCrm,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "sync") {
|
||||
try {
|
||||
await CrmService.validate(tenantId);
|
||||
} catch (error) {
|
||||
if (error instanceof CrmConfigurationError) {
|
||||
return Response.json({ error: t("crm.newsletter.errors.integrationMissing") }, { status: 503 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const emails = form.getAll("emails[]").map((x) => x.toString());
|
||||
let usersInCrm: UserInCrmDto[];
|
||||
try {
|
||||
usersInCrm = await CrmService.getUsersInCrm({ invalidateCache: false });
|
||||
} catch (error) {
|
||||
if (error instanceof CrmProviderError) {
|
||||
return Response.json({ error: t("admin.crm.sync.errors.providerFetchFailed") }, { status: 502 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
let progress: { updated: number; created: number } = { updated: 0, created: 0 };
|
||||
let filteredUsers = usersInCrm.filter((x) => emails.includes(x.email));
|
||||
for (const userInCrm of filteredUsers) {
|
||||
if (userInCrm.status === "to-update" && userInCrm.contact?.id) {
|
||||
const changes = await CrmService.updateContact(userInCrm.contact?.id, {
|
||||
firstName: userInCrm.firstName ?? "",
|
||||
lastName: userInCrm.lastName ?? "",
|
||||
marketingSubscriber: true,
|
||||
});
|
||||
if (changes && changes.length > 0) {
|
||||
progress.updated++;
|
||||
}
|
||||
} else if (userInCrm.status === "to-create") {
|
||||
const created = await CrmService.createContact({
|
||||
request,
|
||||
tenantId: null,
|
||||
firstName: userInCrm.firstName ?? "",
|
||||
lastName: userInCrm.lastName ?? "",
|
||||
email: userInCrm.email,
|
||||
jobTitle: "",
|
||||
status: ContactStatus.Customer,
|
||||
marketingSubscriber: true,
|
||||
options: {
|
||||
createEvent: false,
|
||||
checkUsage: false,
|
||||
createLog: false,
|
||||
storeMedia: false,
|
||||
reportUsage: false,
|
||||
},
|
||||
});
|
||||
if (created) {
|
||||
progress.created++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (progress.created === 0 && progress.updated === 0) {
|
||||
return Response.json({ error: t("admin.crm.sync.actions.noUsers") }, { status: 400 });
|
||||
} else if (progress.created > 0 && progress.updated === 0) {
|
||||
return Response.json({ success: t("admin.crm.sync.actions.createdContacts", { count: progress.created, formattedCount: formatNumber(progress.created, locale) }) });
|
||||
} else if (progress.created === 0 && progress.updated > 0) {
|
||||
return Response.json({ success: t("admin.crm.sync.actions.updatedContacts", { count: progress.updated, formattedCount: formatNumber(progress.updated, locale) }) });
|
||||
}
|
||||
const created = t("admin.crm.sync.actions.createdContactsPart", { count: progress.created, formattedCount: formatNumber(progress.created, locale) });
|
||||
const updated = t("admin.crm.sync.actions.updatedContactsPart", { count: progress.updated, formattedCount: formatNumber(progress.updated, locale) });
|
||||
return Response.json({
|
||||
success: t("admin.crm.sync.actions.createdAndUpdatedContacts", { created, updated }),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher<{ success?: string; error?: string }>();
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.success) {
|
||||
toast.success(fetcher.data.success);
|
||||
} else if (fetcher.data?.error) {
|
||||
toast.error(fetcher.data.error);
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!data.users) {
|
||||
return [];
|
||||
}
|
||||
return data.users.filter(
|
||||
(f) =>
|
||||
f.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.source?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.status?.toString().toUpperCase().includes(searchInput.toUpperCase())
|
||||
);
|
||||
};
|
||||
|
||||
function getSyncTitle() {
|
||||
const filtered = filteredItems();
|
||||
if (filtered.length === 0) {
|
||||
return t("admin.crm.sync.actions.sync");
|
||||
}
|
||||
return t("admin.crm.sync.actions.syncContact", { count: filtered.length, formattedCount: formatters.number(filtered.length) });
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("admin.crm.sync.title")}
|
||||
withHome={false}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonSecondary to={adminPath("crm/sync?cache=clear", { mode: "host-aware" })}>
|
||||
<ReloadIcon className="h-5 w-5" />
|
||||
</ButtonSecondary>
|
||||
<LoadingButton
|
||||
disabled={filteredItems().length === 0}
|
||||
isLoading={fetcher.state === "submitting"}
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.append("action", "sync");
|
||||
filteredItems().forEach((user) => {
|
||||
form.append("emails[]", user.email);
|
||||
});
|
||||
fetcher.submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}}
|
||||
>
|
||||
{getSyncTitle()}
|
||||
</LoadingButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-2 pb-20">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<TableSimple
|
||||
items={filteredItems()}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.crm.sync.actions.viewContact"),
|
||||
onClickRoute: (_, item) => adminPath(`crm/contacts/${item.contact?.id}`, { mode: "host-aware" }),
|
||||
disabled: (item) => !item.isContact,
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "source",
|
||||
title: t("admin.crm.sync.table.source"),
|
||||
value: (item) => {
|
||||
if (item.source === "user") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.sources.user")} color={Colors.BLUE} />;
|
||||
}
|
||||
return <SimpleBadge title={t("admin.crm.sync.sources.unknown", { source: item.source })} color={Colors.GRAY} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
title: t("admin.crm.sync.table.status"),
|
||||
value: (item) => {
|
||||
if (item.status === "synced") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.synced")} color={Colors.GREEN} />;
|
||||
} else if (item.status === "to-create") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.toCreate")} color={Colors.RED} />;
|
||||
} else if (item.status === "to-update") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.toUpdate")} color={Colors.YELLOW} />;
|
||||
}
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.notSynced")} color={Colors.RED} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
title: t("admin.crm.sync.table.user"),
|
||||
className: "w-full",
|
||||
value: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{item.email}</div>
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{item.firstName} {item.lastName}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "contact",
|
||||
title: t("admin.crm.sync.table.contact"),
|
||||
className: "w-full",
|
||||
value: (item) => {
|
||||
if (!item.contact) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{item.contact.email}</div>
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{item.contact.firstName} {item.contact.lastName}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "isContact",
|
||||
title: t("admin.crm.sync.table.isContact"),
|
||||
value: (item) => (
|
||||
<div>{item.isContact ? <CheckIcon className="h-5 w-5 text-green-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "isMarketingSubscriber",
|
||||
title: t("admin.crm.sync.table.marketingSubscriber"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{item.contact?.marketingSubscriber ? <CheckIcon className="h-5 w-5 text-green-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
// {
|
||||
// name: "createdAt",
|
||||
// title: "Created at",
|
||||
// value: (item) => <DateCell date={item.createdAt} />,
|
||||
// },
|
||||
{
|
||||
name: "updatedAt",
|
||||
title: t("admin.crm.sync.table.updatedAt"),
|
||||
value: (item) => <DateCell date={item.updatedAt} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
Reference in new issue
Block a user