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
@@ -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